text
stringlengths
180
608k
[Question] [ [Logic gates](https://en.wikipedia.org/wiki/Logic_gate) are functions which perform basic logic operations. In this problem, we will account for the following 6 logic gates: `AND`, `OR`, `XOR`, `NAND`, `NOR`, and `XNOR`. Each of these takes two boolean inputs \$ a \$ and \$ b \$, and outputs a boolean. Below are the truth tables which show the output of each gate given two inputs. [![enter image description here](https://i.stack.imgur.com/U89H0.jpg)](https://i.stack.imgur.com/U89H0.jpg) ## Task Given two boolean inputs \$ a \$ and \$ b \$, return/output a list of the names of all gates which would return a Truthy value. The order doesn't matter, but the names must be in the exact format as given in the 2nd sentence of the above paragraph (not the ones in the diagram). You are also allowed to output them exclusively in lowercase, if desired. ## Clarifications * You may also output a delimiter-separated string * I will allow leading/trailing spaces ## Test Cases ### Input ``` 0 0 0 1 1 0 1 1 ``` ### Output ``` [NOR, NAND, XNOR] [OR, NAND, XOR] [OR, NAND, XOR] [OR, AND, XNOR] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), ~~53 50~~ 49 bytes *Thanks @JonathanAllan for saving 1 byte!* ``` lambda a,b:"NOR N"[a|b:5-a*b]+"AND X"+"NOR"[a^b:] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fpmAb8z8nMTcpJVEhUSfJSsnPP0jBTyk6sSbJylQ3USspVlvJ0c9FIUJJGyQFlIhLsor9X1CUmVeikaZhoKNgoKnJhcQ1ROIaosoagmX/AwA "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 46 bytes ``` ;:@'AND NAND OR NOR XOR XNOR'#~*,*:,+.,+:,~:,= ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ra0c1B39XBT8QIR/kIIfEEeAMJChrlynpaNlpaOtp6NtpVNnpWP7X5MrNTkjH6g/TcEAwTSEMA0RoiCm4X8A "J – Try It Online") *-5 bytes thanks to Bubbler* We execute a train `*,*:,+.,+:,~:,=` corresponding to the gates on the arguments, which will produce a single boolean mask of the results. We then apply that mask as a filter `#~` on the list of words, which is in the same order. *Note:* Since the returned strings of are of unequal length, J requires them to be boxed. [Answer] # [Ruby](https://www.ruby-lang.org), 49 bytes ``` ->a,b{"#{?N[a|b]}OR #{?N[a&b]}AND X#{?N[a^b]}OR"} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepWkm52t4vOrEmKbbWP0gBwlEDchz9XBQiINw4sJxS7f@S1OKSYgVbhWguBYVoAx0Fg1gdKMsQwjKEixmCxLhi9VITkzMUqhVqSmoUChTSorVKYhVq/wMA "Ruby – Try It Online") Interpolates `'N'` into the output string conditionally for each gate. Alternatively, a direct port of @Surculose Sputum's excellent [Python answer](https://codegolf.stackexchange.com/a/203983/92901) (be sure to upvote it!) is also 49 bytes: ``` ->a,b{"NOR "[a|b,4]+"NAND X"[a&b,6]+"NOR"[a^b,3]} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepWsnPP0hBKTqxJknHJFZbyc/Rz0UhAshXS9IxA/H9g4CcuCQd49ja/yWpxSXFCrYK0VwKCtEGOgoGsTpQliGEZQgXMwSJccXqpSYmZyhUK9SU1CgUKKRFa5XEKtT@BwA "Ruby – Try It Online") [Answer] # Python 2.7, ~~117~~ ~~111~~ ~~102~~ 98 bytes *-6 bytes thanks to @math junkie! -13 bytes thanks to @Surculose Sputum!* [Try it online!](https://tio.run/##XY3BCgIhFEX37ysebxEKQ4zRSvBLYog35pQQT1GD6evNWrY5XDhwbn63R5JT9@iQiDpPq4uSX01pqI5SQWG54Z4KQdyQnVttdfVYQn6yD4oSTSSJ9M8e/qTwsEz6YuwCuURpWPu4gW2ErxgFC8s9qLO2gBj24NH3ecIZBgyY7xowHw) Probably could be made shorter with `lambda` but I don't know how to use it: ``` a,b=input() s="or nand xor" if a==b:s=s.replace("o","no") if a&b:s=s.replace("na","a")[1:] print s ``` EDIT: Yep. This program uses string manipulation to solve the problem, which I thought was simpler, but now I'm not so sure. [Answer] # [J](http://jsoftware.com/), ~~39~~ 37 bytes ``` [:;(_5<\'NAND NOR XNOR')}.~&.>*,+.,~: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62sNeJNbWLU/Rz9XBT8/IMUIoCEumatXp2anp2WjraeTp3Vf00urtTkjHygvjQFAwTTEMI0RIiCmIb/AQ "J – Try It Online") -2 bytes thanks to @Jonah. A solution that pretty much works like [Surculose Sputum's Python 3 answer](https://codegolf.stackexchange.com/a/203983/78410). ### How it works ``` NB. The three segments in the new version _5<\'NAND NOR XNOR' 'NAND NOR XNOR' NB. a length-13 string _5<\ NB. enclose non-overlapping length-5 chunks (which works because the three N's to filter appear at indexes 0, 5, 10) NB. Previous version [:;('NAND ';'NOR X';'NOR')}.~&.>*,+.,~: NB. Input: two bits as left/right args *,+.,~: NB. evaluate AND, OR, XOR ('NAND ';'NOR X';'NOR') NB. corresponding three segments &.> NB. pair up both sides unboxed and }.~ NB. drop the first char from left if right is 1 [:; NB. Remove boxing and concatenate into a single vector ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes ``` .•UNœ5Z’dµ•#εI…PàONè.Vi'nõ.; ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f71HDolC/o5NNox41zEw5tBXIVT631fNRw7KAwwv8/Q6v0AvLVM87vFXP@v//aEMdBcNYAA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), 55 bytes ``` a=>b=>'1OR 3AND X5OR'.replace(/\d/g,n=>n>>a+b&1?'N':'') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1k7d0D9IwdjRz0UhwtQ/SF2vKLUgJzE5VUM/JkU/XSfP1i7Pzi5RO0nN0F7dT91KXV3zf3J@XnF@TqpeTn66RpqGgSYQaXJhCBpiCBpiU2kIVvkfAA "JavaScript (Node.js) – Try It Online") ### How? For each gate type, we use the sum of \$a\$ and \$b\$ to right-shift a bit mask. We test the least significant bit of the result to find out if we must return the complementary form of the gate. ``` a | 1 | 0 | 1 | 0 | b | 1 | 1 | 0 | 0 | ------+---+-------+---+--------- a+b | 2 | 1 | 0 | decimal ------+---+-------+---+--------- NOR | 0 | 0 | 1 | 1 NAND | 0 | 1 | 1 | 3 XNOR | 1 | 0 | 1 | 5 ``` --- # JavaScript (ES6), 55 bytes Using a template literal is just as long. ``` a=>b=>['N'[a|b]]+`OR ${['N'[a&b]]}AND X${['N'[a^b]]}OR` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i5a3U89OrEmKTZWO8E/SEGlGiKgBhSodfRzUYiAicSBRPyDEv4n5@cV5@ek6uXkp2ukaRhoApEmF4agIYagITaVhmCV/wE "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~65~~ ~~60~~ 58 bytes ``` f(a,b){printf("NOR %s X%s"+(a|b),"NAND"+a*b,"NOR"+(a^b));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSbO6oCgzryRNQ8nPP0hBtVghQrVYSVsjsSZJU0fJz9HPRUk7UStJByQLEo5L0tS0rv2fm5iZp6FZzZWmYaCjYKBpraCvpQDSD9KgEAFiaelzwQyOyVPStIYoNYQohavErtAQbiZhhQgTka2u/Q8A "C (gcc) – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 234 bytes ``` >-[-[-<]>>+<]>-[<<++>+>-]<<+<<<-[+>++[++<]>]>-->>[>>>>[-]<<<<[>>+>>+<<<<-]<]<<,<,[>+<-]>[>+>+>>+<<<<-]>>>>--[>.<[-]]>>.>.>+++.>.[<]<<[>>+<<-]>+>[<[-]>[-]]<[->+<]>[>.<[-]]>+.+++.<<<<[>>>+<<<-]>>>>>>>>.<<<<++++++.<-[>>>.<<<[-]]>>>+.+++. ``` [Try it online!](https://tio.run/##TU5BCsMwDKPvUZ0XCH9E5NAOBmOww2Dvz@Q0jNmQWJZk@3wfj9f9c3uOkSEneyb8hEggkdFdkAwZQSjSdGQqHSqedI0ylrDTrZ27jKNbhj@uPBHKRjuNmhOAP5VNU2gZUqWo@d3FvOnnQivL2jsnX4MrZhszmo9enWvZMo6xbV8 "brainfuck – Try It Online") Takes input as two bytes (0 or 1) on stdin, outputs space-separated to stdout without trailing whitespace. The TIO link has the `11` test case because I couldn't figure out how to type the null character into a web browser, but if you delete the second input character it will do the same thing as the `10` test-case, and if you delete both it will be the same as the `00` test-case. Here's my annotated version (the two input bytes are `b` and `a`, their sum is `c`): ``` -[-[-<]>>+<]>- *32* from https://esolangs dot org/wiki/Brainfuck_constants#32 [<<++>+>-] 64 32 *0* <<+<<< *0* 0 0 65 32 -[+>++[++<]>]>-- *78* 65 32 from https://esolangs dot org/wiki/Brainfuck_constants#78 >> [>>>>[-]<<<<[>>+>>+<<<<-]<] 0 *0* 0 0 78 65 78 65 32 << ,<, *b* a 0 0 0 0 78 65 78 65 32 [>+<-]> 0 *b plus a=c* 0 0 0 0 78 65 78 65 32 [>+>+>>+<<<<-]>>>> 0 0 c c 0 *c* 78 65 78 65 32 -- 0 0 c c 0 *c minus 2* 78 65 78 65 32 [>.<[-]]>>.>.>+++.>. 0 0 c c 0 0 78 65 78 *68* 32 (N)AND space print N if c != 2 [<]<<[>>+<<-]>> 0 0 c 0 0 *c* 78 65 78 68 32 <+>[<[-]>[-]]<[->+<]> 0 0 c 0 0 *!c* 78 65 78 68 32 [>.<[-]]>+.+++. 0 0 c 0 0 0 *82* 65 78 68 32 (N)OR print N if c == 0 < <<<[>>>+<<<-]>>> 0 0 0 0 0 *c* 82 65 78 68 32 >>>>>.<<<<++++++.< 0 0 0 0 0 *c* 88 65 78 68 32 space X -[>>>.<<<[-]] 0 0 0 0 0 *0* 88 65 78 68 32 (N) print N if c != 1 >>>+.+++. 0 0 0 0 0 0 88 65 *82* 68 32 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes ``` 00 N2N 11 ODN \d+ OND D AND X O|$ OR ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w38CAy8/Ij8vQkMvfxY8rJkWby9/PhcuFy9HPRSGCy79Ghcs/SOE/SJmhAZeBIVAhAA "Retina 0.8.2 – Try It Online") Input is as a single 2-digit string (one of `00`, `01`, `10`, or `11`). Performs a series of replacements to arrive at the required output. **Explanation** `AND X` is a string common to all 4 outputs, so we encode the string as `D`. `OR` appears in a bunch of places so we encode that as `O`. Then, we can replace each pair of digits with a string of `N`s, `O`s and `D`s. (The `00 -> N2N` and the `\d+ -> OND` are golfs arising from `10` and `01` yielding the same output and sharing some overlap with the output for `00`. Finally, we just replace the `O`s and `D`s with the expanded string mentioned above and we get the required list! [Answer] # [Pyth](https://github.com/isaacg1/pyth), 37 bytes ``` AQ%"%sOR X%sOR %sAND"*R\N!M[|GHxGH&GH ``` [Try it online!](https://tio.run/##K6gsyfj/3zFQVUm12D9IIQJMqhY7@rkoaQXF@Cn6Rte4e1S4e6i5e/z/H@2WmFOcqqMApmIB "Pyth – Try It Online") Takes a list of two values as input, outputs in the form `AND OR XNOR` ### Explanation ``` AQ # Q is the input. Set G:=Q[0], H:=Q[1] % # Format a string (printf-style) "%sOR X%sOR %sAND" # Format string *R\N!M[|GHxGH&GH # replacement values as a list: [ # [ ] |GH # G or H xGH # G xor H &GH # G and H !M # map each to its negation *R\N # map each x to "N"*x ``` (Ab)uses the fact that in Python and thus Pyth, `True == 1` and `False == 0` and thus `"N"*True == "N"` and `"N"*False == ""`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` S11,:Sµ“×®ṫ.¡Ḍẹhɗ»x€⁸¦0 ``` A monadic Link accepting a list of two integers (in `[0,1]`) which yields a list of characters - the gate names separated by spaces. **[Try it online!](https://tio.run/##ATkAxv9qZWxsef//UzExLDpTwrXigJzDl8Ku4bmrLsKh4biM4bq5aMmXwrt44oKs4oG4wqYw////WzAsMF0 "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/Y0FDHKvjQ1kcNcw5PP7Tu4c7VeocWPtzR83DXzoyT0w/trnjUtOZR445Dywz@H91zuB3IywKJNMy1ivz/P9pAxyBWB0gaAklDMNsQyAYA "Jelly – Try It Online"). ### How? Observe that there are three outputs, aligning with the sums and that the sum \$1\$ and sum \$2\$ outputs are the sum \$0\$ one missing certain characters. When one-indexed the sum \$1\$ needs characters `1` and `11` removed while the sum \$2\$ one needs characters `1` and `5` removed. Furthermore \$\lfloor \frac{11}{2} \rfloor = 5\$. ``` S11,:Sµ“×®ṫ.¡Ḍẹhɗ»x€⁸¦0 - Link: list of integers, B e.g [0,0] [1,1] [1,0] (or [0,1]) S - sum (B) 0 2 1 11 - literal eleven 11 11 11 , - pair [11,0] [11,2] [11,1] S - sum (B) 0 2 1 : - integer division [inf,nan] [5,1] [11,1] µ - start a new monadic link, call that X “×®ṫ.¡Ḍẹhɗ» - compressed string "NOR NAND XNOR" "NOR NAND XNOR" "NOR NAND XNOR" € ¦ - sparse application... ⁸ - ...to indices: chain's left argument x 0 - ...action: repeat zero times "NOR NAND XNOR" "OR AND XNOR" "OR NAND XOR" ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~53~~ 49 bytes ``` tr 01 N\\0<<<"$[$1|$2]OR $[$1&$2]AND X$[$1^$2]OR" ``` [Try it online!](https://tio.run/##RY4xC8IwEIX3@xWPEFxEbZxrQVDHFpwEq5CkrXVoIrGCg/89JqXWG@7efY93nJLP1mvZI3s4e3OyQ5qyfXFgvndIBPKyTNKA@JmLD19fiiOinAW5zXc4xeU6cOZDjEi3na3wmr8xHiRqrIPE3SCBIKCyoQGRqj@NNTqxat1aLAwYl@AKmwxs8par36@DOYVNTeP0Xw "Bash – Try It Online") This is a full program. Input is passed as arguments, and the output is written to stdout. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` ∊'NAND ' 'NOR X' 'NOR'↓⍨¨∧,∨,≠ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FHl7qfo5@LgrqCup9/kEIEhFZ/1Db5Ue@KQysedSzXedSxQudR54L/aY/aJjzq7XvU1XxovfGjtomP@qYGBzkDyRAPz@D/QNo5Ur04MadEXeFRd4tCal5iUk5qsKNPCFdsUn5FZl66Qn4el4GCocKjjhl6aQpAFgA "APL (Dyalog Unicode) – Try It Online") A port of [my own J answer](https://codegolf.stackexchange.com/a/203992/78410). ### How it works ``` ∊'NAND ' 'NOR X' 'NOR'↓⍨¨∧,∨,≠ ∧,∨,≠ ⍝ AND, OR, XOR 'NAND ' 'NOR X' 'NOR'↓⍨¨ ⍝ Drop an N from the string segments at ones ∊ ⍝ Flatten ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes ``` .•Vs’9ìï´¸•.•B»Î5γ'¸•DŠ‚s.•B»¯4qld•‚«IðмCè ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f71HDorDiRw0zLQ@vObz@0JZDO4ACIEGnQ7sP95me26wOFnE5uuBRw6xiqMSh9SaFOSlANlDs0GrPwxsu7HE@vOL/f0MFQwA "05AB1E – Try It Online") Makes a list: `["nor nand xnor", "or nand xor", "or nand xor", "or and xnor"]`; the input is read as a binary number and that corresponds to the position in the list. This could probably be reduced heavily as I see the other 05ab1e answer just uses `"nand nor xnor"` as its string. [Answer] # x86-16 machine code, IBM PC DOS, ~~57~~ 52 bytes **Binary:** ``` 00000000: a182 0025 0101 8bd8 ba2f 0152 0ac4 7401 ...%...../.R..t. 00000010: 42b4 09cd 21ba 2801 84df 7401 42cd 215a B...!.(...t.B.!Z 00000020: 32df 7401 42cd 21c3 4e41 4e44 2058 244e 2.t.B.!.NAND X$N 00000030: 4f52 2024 OR $ ``` **Listing:** ``` A1 0082 MOV AX, [0082H] ; load command line chars into AH/AL 25 0101 AND AX, 0101H ; ASCII convert 8B D8 MOV BX, AX ; save input to BX for later BA 012F MOV DX, OFFSET NOR ; DX = string 'NOR' 52 PUSH DX ; save 'NOR' for later 0A C4 OR AL, AH ; OR or NOR? 74 01 JZ OUT_NOR ; is OR? 42 INC DX ; increment string pointer to skip 'N' OUT_NOR: B4 09 MOV AH, 9 ; DOS write string function CD 21 INT 21H ; write to STDOUT BA 0128 MOV DX, OFFSET NAND ; DX = string 'NAND X' 84 DF TEST BL, BH ; AND or NAND? 74 01 JZ OUT_NAND ; is AND? 42 INC DX ; increment string pointer to skip 'N' OUT_NAND: CD 21 INT 21H ; write string to STDOUT 5A POP DX ; Restore DX = 'NOR' 32 DF XOR BL, BH ; XOR or XNOR? 74 01 JZ OUT_XOR ; is OR? 42 INC DX ; increment string pointer to skip 'N' OUT_XOR: CD 21 INT 21H ; write string to STDOUT C3 RET ; return to DOS NAND DB 'NAND X$' NOR DB 'NOR $' ``` A standalone PC DOS executable. Input via command line, output string to `STDOUT`. **I/O:** [![enter image description here](https://i.stack.imgur.com/p2hKQ.png)](https://i.stack.imgur.com/p2hKQ.png) [Answer] # [OIL](https://github.com/L3viathan/OIL), 81 bytes ``` 5 1 5 NAND OR XOR 10 NAND NOR XNOR 1 9 20 10 AND OR XNOR 6 14 17 4 10 3 4 5 3 4 3 ``` As usual with golfed OIL code, we use cells as both data and code. All the strings also serve as references to the cell #0 (which will later contain the second input), and we use cell #6 (the one containing a `1`) as both a reference to cell #1, as well as the value `1`. [Answer] # [Aceto](https://github.com/aceto/aceto), 67 bytes ``` pdA`ANpn "Ln>"D"L RON' Ov "p Vu p^`p"pX N''XRO irHL "<` riMdpN' ``` [Try it online!](https://tio.run/##S0xOLcn//78gxTHB0a8gj0vJJ89OyUXJhyvI309dQcG/jEtBqUBBQSGslKsgLqFAqSCCy09dPSLInyuzyMNHQckmgaso0zelwE/9/39DLgMA "Aceto – Try It Online") --- I'm using quick storage for one of the inputs, the stack for the other. It's mostly conditionally escaped movement to avoid printing `N`, but I also used the reverse-and-jump-to-the-end trick for a few saved bytes. [Answer] ## Common Lisp, 154 bytes Not a short answer, but relies on [`BOOLE`](http://clhs.lisp.se/Body/f_boole.htm), which is a function that is practically never used: ``` (lambda(a b)(loop for(n o)in`((and,boole-and)(nand,boole-nand)(or,boole-ior)(nor,boole-nor)(xor,boole-xor)(xnor,boole-eqv))if(/=(boole o a b)0)collect n)) ``` Readable version: ``` (loop for (name op) in `((and ,boole-and) (nand ,boole-nand) (or ,boole-ior) (nor ,boole-nor) (xor ,boole-xor) (xnor ,boole-eqv)) unless (= (boole op a b) 0) collect name) ``` All couples `(name op)` in the list are made of `name`, a symbol used for the output, and `op`, a constant integer value that represents a particular boolean operation. The `boole` functions knows how to perform the operation based on such value. Note that `xnor` is the equivalence operation, namely `boole-eqv`. The loop builds a list of names such that the associated operation yields a non-zero result. Indeed, if you do: ``` (boole boole-nand 1 1) ``` The result is `-2`, a.k.a. `-10` in binary; this is because those operations assume an *infinite* two's complement representation (<https://comp.lang.lisp.narkive.com/OXYD1hNK/two-s-complement-representation-and-common-lisp>) [Answer] # [Python 3](https://docs.python.org/3/), 60 bytes Not really close to the gold, but found it interesting that just picking from the list of options is within 11 bytes of the best python answer, and more than 30 bytes smaller than the other python answer. Shows how impressive golfing those 11 bytes are imo. Also shorter than some other langs that i think could also implement the same method. ``` lambda a,b:['nor nand xn','or nand x','or and xn'][a+b]+'or' ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8kqWj0vv0ghLzEvRaEiT11HHc6BsKHisdGJ2kmx2kAR9f8FRZl5JRppGgY6CgaamlxIXEMkriGqrCFY9j8A "Python 3 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 55 bytes ``` [ + { "NOR NAND XNOR""OR NAND XOR""OR AND XNOR" } nth ] ``` [Try it online!](https://tio.run/##PY7BCsIwEETv@Yoh4MmL7VFREATxEkERhNJDSBMN1rQm6UFKvz0utZRdmHnMMqyRKjY@3a4ncVzjpb3TNWyDt4xPBP3ptFM6QHovvwGm8RRE6x7YMNajx4pmGDUbNZs4G3lgrICxPsQcedW14IsKtNsdOFpvXTSpwJLuuThfIPbigDs5zmeaYE6o1dFrZVKyrv8dKKGleqYf "Factor – Try It Online") Add and index into list of strings. This one's pretty boring, so here's a longer but more interesting version: # [Factor](https://factorcode.org/), 73 bytes ``` [ [ or ] [ and ] [ xor ] 2tri [ "" "N"? ] tri@ "%sOR %sAND X%sOR"printf ] ``` [Try it online!](https://tio.run/##LYzLCsIwEEX3/YpLoD/QpeILBHFTQRGE0kWIiQZrWidTUEq/PaZRZuDMuQzXSMUthfNpX@5meGhyuoFt4fWr105pD0kkPx6mpadktu6GeZYNGGDijImcyH/n5GOWVTCWPBcorn0HkfeIu1hCoCPr2IQKFVpCHSHdNfGdvGCyUYSAKMUqBtHXscEfjsj9ptziMt3i14M6KNk003sK4r@W6h6@ "Factor – Try It Online") My first submission in Factor! Hopefully the first of many, since this language is really cool. Technically this doesn't run on new versions of the language because I didn't put spaces after some strings, but it works on the old version TIO has. (I would use ATO, but it's offline at the moment.) Explanation: `[ ... ]` Quotation (anonymous function) taking two booleans `[ or ] [ and ] [ xor ] 2tri` Apply each of the three quotations `or`, `and`, `xor` on the two booleans `[ "" "N"? ] tri@` Apply to each of the three results: If true, "", else "N" `"%sOR %sAND X%sOR"printf` Insert each "" or "N" into the right part of the string, and print. [Answer] # [Io](http://iolanguage.org/), 65 bytes Port of Surculose Sputum's Python answer. ``` method(a,b,"NOR "slice(a|b).."NAND X"slice(a&b).."NOR"slice(a^b)) ``` [Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0UjUSdJR8nPP0hBqTgnMzlVI7EmSVNPT8nP0c9FIQImpgYR8w@CCcQlaWr@T9Mw0DHQVCgoyswrycnjAnENkbmGqLKGSLL/AQ "Io – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 160 bytes ``` ×N¬ΣθOR ×N‹Σθ²AND X×N↔⊖ΣθOR ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMkMze1WEPJT0lHwS@/RCO4NFejUBMIrLkg8kr@QQpKcB6Sap/U4mKoch0FI2Qdjn4uChFY9TgmFefnlJakarikJhel5qbmlaSmIKxEthOo/f9/A4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array or string of two bits. Explanation: Just interpolates the `N`s as appropriate based on the count of `1` bits (zero for the first `N`, less than 2 for the second, and absolute difference from 1 for the third). [Answer] # Haskell, 78 Bytes ``` a?b=[h(a||b)"OR""NOR",h(a&&b)"AND""NAND",h(a/=b)"XOR""XNOR"];h x a b|x=a|9>0=b ``` ]
[Question] [ I was messing around with Pyth's url request feature, and noticed that google always gave a response with a slightly different length for me, usually `~10500` characters. So your task in this challenge is to print out the average length of the html response from `http://google.com`. # Specs * You will take an input `n` which is the number of requests to make. * For each request, you will make an HTTP get request. * You will count the response body (the html text), not the headers. * Output the arithmetic mean of the lengths of the responses. * You can only access the url `http://google.com`, not any other. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! **Sample output for input `10`:** `10560.1` (I used Python's `urllib` for that) **P.S: does anyone know why google does this?** [Answer] ## Bash + system utilities, ~~56~~ ~~53~~ ~~49~~ 48 bytes *Update:* saved 4 bytes thanks to [Digital Trauma](/users/11259/digital-trauma) and 1 byte more thanks to [Dennis](/users/12012/dennis) ``` curl -L `yes google.com|sed $1q`|wc|dc -e1k?$1/p ``` In my original answer I was using `yes` in combination with `xargs` to emulate a for loop. But `curl` can accept as input a list of URLs, so only the output from `yes` is actually needed. When `curl` accesses *google.com*, it receives a 302 redirection page that has the new URL in the body section, so the `-L` option is needed to follow it. **Run example:** answer is printed to STDOUT, I redirect STDERR just for clarity ``` me@LCARS:/PPCG$ ./google_length.sh "8" 2> /dev/null 10583.2 ``` **Explanation:** (of the initially submitted code) ``` yes google.com| # repeatedly output a line containing the string "google.com" sed $1q| # print the first $1 lines only (shorter than head -$1) xargs curl -sL| # xargs reads the input lines and executes "curl -sL" with the #current input line as an additional argument. wc -m| # count the number of characters dc -e1k?$1/p # dc script: set precision to 1, read input, push $1 and divide ``` **Edit:** I replaced `wc -m` with `wc`, because even if without arguments it prints 2 more statistics than the one I wanted, the same `dc` script following this output still works, because the count we want is, happily, placed on top of the stack during parsing. [Answer] # [MATL](https://github.com/lmendo/MATL), 28 bytes ``` :"'http://google.com'Xin]vYm ``` Gif or it didn't happen: [![enter image description here](https://i.stack.imgur.com/dbtQH.gif)](https://i.stack.imgur.com/dbtQH.gif) ### How it works ``` : % Implicitly input n. Push [1 2 ... n] " % For each 'http://google.com' % Push this string Xi % URL read. Gives a string n % Number of elements ] % End v % Concatenate stack contents into a vertical vector Ym % Mean. Implicitly display ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 48 bytes ``` 1.."$args"|%{irm google.com}|measure Le* -a|% A* ``` ## Explanation 1. Create a range from `1` to the input integer. 2. For each value in the range `Invoke-RestMethod` (`irm`) the google homepage. The result is not JSON so it will return the body verbatim instead of deserializing it. 3. Send that to `Measure-Object` (`measure`), getting an average of the `Length` property of the input strings (the bodies). 4. Expand the resulting `Average` property. [Answer] # Java 8, 197 184 182 181 bytes Golfed: ``` n->{int s=0,i=0;while(i++<n)try{s+=new java.util.Scanner(new java.net.URL("http://google.com").openStream()).useDelimiter("\\A").next().length();}catch(Exception e){}return s*1f/n;} ``` Ungolfed: ``` public class AverageLengthOfGoogle { public static void main(String[] args) { float bytes = f(n -> { int s = 0, i = 0; while (i++ < n) { try { s += new java.util.Scanner(new java.net.URL("http://google.com").openStream()) .useDelimiter("\\A").next().length(); } catch (Exception e) { } } return s * 1f / n; } , 10); System.out.println(bytes); } private static float f(java.util.function.IntFunction<Float> f, int n) { return f.apply(n); } } ``` This leaks resources, but that is a small price to pay in search of the fewest bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes Code: ``` F’й.ŒŒ’.wgO}¹/ ``` Explanation: ``` F } # Input times do.. ’й.ŒŒ’ # Push the string "google.com" .w # Read all and wrap into a string g # Get the length O # Sum it up with the total ¹/ # Divide by input ``` Uses the **CP-1252** encoding. When run in the offline interpreter I get the following: ``` > py -3 05AB1E.py -c test.abe 1 11039.0 > py -3 05AB1E.py -c test.abe 2 11070.0 > py -3 05AB1E.py -c test.abe 3 11046.666666666666 > py -3 05AB1E.py -c test.abe 4 11029.75 > py -3 05AB1E.py -c test.abe 5 11015.8 ``` [Answer] # PHP, ~~90~~ 78 bytes ``` while($i++<$argv[1]){$s+=strlen(file_get_contents('http://google.com'));}echo $s/$argv[1]; ``` ``` while($i++<$argv[1])$s+=strlen(join(file('http://google.com')));echo$s/($i-1); ``` * Used shorter functions/variables and removed unnecessary syntactic construct as mentioned by commenters [Answer] # Pyth, 25 bytes ``` .OmslM'"http://google.com ``` `'` is the open function in Pyth, and when given a string starting with `http`, it performs a GET resuest to that website. The return value is a list of `bytes` objects. Unfortunately, Pyth's `s` doesn't know how to concatenate these objects, so instead of `ls`, I use `slM` to get the total length. This is performed a number of times equal to the input by `m`, and the results are averaged by `.O`. [Answer] # Mathematica, 58 bytes ``` N@Mean[StringLength@URLFetch@"http://google.com"~Table~#]& ``` Anonymous function. Takes a number as input, and returns a number as output. [Answer] # Python, 102 bytes ``` import urllib2 f=lambda n:sum([len(urllib2.urlopen(x).read()) for x in ['http://google.com']*n],0.0)/n ``` Or, if we can return integers rather than floats, the answer can be 98 bytes: ``` import urllib2 f=lambda n:sum([len(urllib2.urlopen(x).read()) for x in ['http://google.com']*n])/n ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` rd_"google.com"a*:gs,\/ ``` Doesn't work on TIO for security reasons. ### Test run ``` $ echo -n 'rd_"google.com"a*:gs,\/' > google-avg.cjam $ wc -c google-avg.cjam 23 google-avg.cjam $ java -jar cjam-0.6.5.jar google-avg.cjam <<< 10; echo 10663.2 $ java -jar cjam-0.6.5.jar google-avg.cjam <<< 10; echo 10650.0 $ java -jar cjam-0.6.5.jar google-avg.cjam <<< 10; echo 10651.0 $ java -jar cjam-0.6.5.jar google-avg.cjam <<< 10; echo 10651.4 $ java -jar cjam-0.6.5.jar google-avg.cjam <<< 10; echo 10673.5 ``` ### How it works ``` rd e# Read a double from STDIN. Let's call it D. _ e# Push a copy of D. "google.com"a e# Wrap the string in an array, pushing ["google.com"]. * e# Repeat the array D times. :g e# Map `get` over the array, making D requests to the URL. s e# Combine all D responses into a single string. , e# Compute the length. \ e# Swap the length with the original D. / e# Perform division. ``` [Answer] # Clojure, 102 bytes ``` (fn[n](/(reduce + 0.0(repeatedly n #(count(slurp(clojure.java.io/reader"http://www.google.com")))))n)) ``` Ungolfed: ``` (fn [n] (/ (reduce + 0.0 (repeatedly n #(count (slurp (clojure.java.io/reader "http://www.google.com"))))) n)) ``` `#(count (slurp (clojure.java.io/reader "http://www.google.com")))` is a local function which counts the bytes from an http request to google, `repeatedly` calls the function n times and makes a list from the returned counts, reduce sums the results together, and finally that is divided by n to make an average. The reduce is started at 0.0 to force the result into a float- otherwise the division would result in a rational. Whole thing is wrapped in an anonymous function which takes the number of times to name the request. [Answer] # Python 3, 95 bytes Recursive solution ``` import requests as r f=lambda n,t:f(n-1,t+len(r.get('http://google.com').text)) if n>0 else t/i ``` where `n=i=int(input())` [requests library](http://docs.python-requests.org/en/master/user/install/#install) [Answer] # Perl, 66 bytes ``` perl -MLWP::Simple -pe'map$t+=length get"http://google.com",1..$_;$_=$t/$_' ``` 51 bytes + 14 bytes for `-MLWP::Simple<space>` + 1 byte for `-p`. Straightforward solution using [LWP::Simple](https://metacpan.org/pod/LWP::Simple). The `get` function is exported by default and returns the response content on success. # Perl 5.14+, ~~94~~ 93 bytes (core modules only) ``` perl -MHTTP::Tiny -pe'map$t+=length${+get{new HTTP::Tiny}"http://google.com"}{content},1..$_;$_=$t/$_' ``` 79 bytes + 13 bytes for `-MHTTP::Tiny<space>` + 1 byte for `-p`. Uses [HTTP::Tiny](https://metacpan.org/pod/HTTP::Tiny), which has been in core since Perl 5.14. ## How it works This: ``` get{new HTTP::Tiny}"http://google.com" ``` is the [indirect object syntax](http://perldoc.perl.org/perlobj.html#Indirect-Object-Syntax) equivalent of this: ``` HTTP::Tiny->new->get("http://google.com") ``` and saves three bytes. The `get` method returns a hashref with the content stored under the `content` key. To get the actual response content, we do: ``` ${+get{new HTTP::Tiny}"http://google.com"}{content} ``` which is equivalent to: ``` (get{new HTTP::Tiny}"http://google.com")->{content} ``` but saves one byte when we add `length`: ``` length(foo)->{bar} # wrong, equivalent to (length(foo))->{bar} length+(foo)->{bar} length${+foo}{bar} ``` [Answer] # CJam, 27 bytes ``` {"google.com"g,}ri*]_:+\,d/ ``` CJam assumes HTTP if not specified. **Explanation** ``` {"google.com"g,} A block which fetches from http://google.com and gets its length ri* Run this block a number of times equal to the input ] Collect all the results in an array _ Duplicate the array :+ Sum it \ Swap back to the original array , Get its length d/ Cast to double and divide (without casting, it would be integer division) ``` [Answer] # Rebol, 69 bytes ``` n: 0 loop i: do input[n: n + length? read http://www.google.com]n / i ``` [Answer] # Clojure, 70 bytes ``` #(/(reduce(fn[a _](+ a(count(slurp"http://google.com"))))0(range %))%) ``` A fold over a `n` long range. Sums the length of each request, then divides it by number of requests. Due to the way Clojure handles division, this returns a fraction, not a decimal. If this is unacceptable, I can fix it at the cost of a couple bytes. ``` (defn avg-request-len [n] (/ (reduce (fn [acc _] (+ acc (count (slurp "http://google.com")))) 0 (range n)) n)) ``` [Answer] # Ruby, 73 + 10 = 83 bytes Uses the `-rnet/http` flag. ``` ->n{s=0.0;n.times{s+=Net::HTTP.get(URI"http://www.google.com").size};s/n} ``` [Answer] # Common Lisp + [quicklisp](http://quicklisp.org)/[dexador](https://github.com/fukamachi/dexador), 23 + 72 = 95 bytes If quicklisp is installed on the system it will download and install dexador as neccesary. Prelude: ``` (ql:quickload :dexador) ``` Code ``` (lambda(n)(/(loop :repeat n :sum(length(dex:get"http://google.com")))n)) ``` Ungolfed: ``` (lambda (n) (/ (loop :repeat n :sum (length (dex:get "http://google.com"))) n)) ``` Explaination `(dex:get "http://google.com")` This performs the web request to google and returns five values: 1. The web request itself as a string or byte array (depending on content type) 2. The http status code 3. A hash map of the http response headers 4. A QURI object representing the final URI after resolving redirects 5. The socket used to communicate with the web server (if it wasn't closed by the server or one of the optional args to the function) `(length (dex:get ...))` If you don't explicity request otherwise, Common Lisp will discard all the return values other than the first, so the length function only sees the http response itself and returns the length of this string. `(loop :repeat n :sum (length ...))` This calculates the response length n times and adds them. `(/ (loop ...) n)` This divides the summed lengths by n to compute the average. `(lambda (n) ...)` This wraps the body of code in an anonymous function which takes n as an argument and returns the average response length for n web requests to <http://google.com>. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ƛ`‹`¨UL;ṁ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm2DigLlgwqhVTDvhuYEiLCIiLCIiXQ==) The joys of the [short dictionary](https://codegolf.stackexchange.com/a/238374/78850). ## Explained ``` ƛ`‹`¨UL;ṁ ƛ ; # over the range [1, input]: `‹` # push "https://www.google.com" and ¨U # do a GET request L # taking the length of the result ;ṁ # take the average of that list ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ’й.ŒŒ’и.w€gÅA ``` ``` ’...’и.w€gÅA # trimmed program ÅA # mean of elements of... g # lengths of... € # each element of... .w # content of responses from urls... # (implicit) "http://" concatenated with each element of... и # list of... # implicit input... ’...’ # "google.com"... и # s # implicit output ``` ]
[Question] [ # Summary Given a list of integers, return the index each integer would end up at when sorted. For example, if the list was `[0,8,-1,5,8]`, you should return `[1,3,0,2,4]`. Note that the two `8`s maintain their order relative to each other (the sort is stable). Put another way: For each element in the list, return the number of elements in the list that are: Smaller than the chosen element OR (equal to the element AND appears before the chosen element) Indexes must start with 0 (not 1)EDIT: given the large pushback, I'll allow 1-based indicies. # Test cases: ``` 0 -> 0 23 -> 0 2,3 -> 0,1 3,2 -> 1,0 2,2 -> 0,1 8,10,4,-1,-1,8 -> 3,5,2,0,1,4 0,1,2,3,4,5,6,7 -> 0,1,2,3,4,5,6,7 7,6,5,4,3,2,1,0 -> 7,6,5,4,3,2,1,0 4,4,0,1,1,2,0,1 -> 6,7,0,2,3,5,1,4 1,1,1,1,1,1,1,1 -> 0,1,2,3,4,5,6,7 1,1,1,1,1,1,1,0 -> 1,2,3,4,5,6,7,0 ``` [Answer] # APL, 2 [bytes](http://meta.codegolf.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) ``` ⍋⍋ ``` The “grade up” built-in, applied twice. Works if indexing starts at 0, which isn’t the default for all flavors of APL. [Try it here!](http://ngn.github.io/apl/web/index.html#code=f%u2190%u234B%u234B%0Af%204%204%200%201%201%202%200%201) ## Why does this work? `⍋x` returns a *list of indices that would stably sort `x`*. For example: ``` x ← 4 4 0 1 1 2 0 1 ⍋x 2 6 3 4 7 5 0 1 ``` because if you take element `2`, then `6`, then `3`… you get a stably sorted list: ``` x[⍋x] 0 0 1 1 1 2 4 4 ``` But the index list that answers this question is subtly different: first we want the index of the smallest element, then the second smallest, etc. — again, keeping the original order. If we look at `⍋x`, though, we see it can give us this list easily: the *position* of a `0` in `⍋x` tells us where the smallest element would end up after sorting, and the *position* of a `1` in `⍋x` tells us where the second smallest element would end up, etc. But we know `⍋x` contains exactly the numbers **[0, 1… n−1]**. If we grade it **again**, we’ll just get the index of `0` in `⍋x`, then the index of `1` in `⍋x`, etc., which is precisely what we’re interested in. So the answer is `⍋⍋x`. [Answer] # Jelly, 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ỤỤ ``` Grade up twice. 1-indexed. [Try it online!](http://jelly.tryitonline.net/#code=4buk4buk&input=&args=NCw0LDAsMSwxLDIsMCwx) [Answer] # JavaScript ES6, ~~87~~ ~~82~~ ~~79~~ ~~74~~ 70 bytes ``` (a,b={})=>a.map(l=>[...a].sort((a,b)=>a-b).indexOf(l)+(b[l]=b[l]+1|0)) ``` Don't like using an object but it seems to be the shortest way to keep track of dupes ## Explanation ``` (a,b={})=> `a` is input `b` stores the occurrences of each number a.map(l => Loop over the array, `l` is item [...a] Copy `a` .sort(...) Sort in ascending numerical order .indexOf(l) Index of input in that array + Add the following to account for dupes (b[l]= set and return the item `l` in hashmap `b` to... b[l]+1 Increase the counter by one if it exists yet |0 default is zero ) ``` [Answer] # [K](https://github.com/kevinlawler/kona/wiki), ~~5~~ 2 bytes ``` << ``` Grade up (`<`) twice. JohnE saved three bytes by pointing out tacit expressions exist in K! Super cool. [Try it out.](http://johnearnest.github.io/ok/index.html?run=(%3C%3C)%208%2C10%2C4%2C-1%2C-1%2C8) [Answer] ## Haskell, ~~50~~ 48 bytes ``` import Data.List m x=map snd$sort$zip x[0..] m.m ``` Usage example: `m.m $ [4,4,0,1,1,2,0,1]`-> `[6,7,0,2,3,5,1,4]`. It's `map snd.sort.zip x [0..]` applied twice on the input, i.e pair each element e with it's index i (`(e,i)`), sort it remove the first elements. Repeat one time. @Lynn came up with `m=map snd.sort.(`zip`[0..])` which has the same byte count. [Answer] # Python 2, ~~67~~ 60 bytes ``` def f(x):x=zip(x,range(len(x)));print map(sorted(x).index,x) ``` *Thanks to @xnor for golfing off 7 bytes!* Test it on [Ideone](http://ideone.com/LdrhrX). [Answer] ## PowerShell v2+, 63 bytes ``` param($n)$n|%{($n|sort).IndexOf($_)+($n[0..$i++]-eq$_).count-1} ``` Takes input `$n`, pipes that through a loop over every element `|%{...}`. Each iteration, we `sort` `$n` and get the `IndexOf` our current element `$_`. This counts how many items are smaller than the current element. We add to that a slice of `$n`, that expands every loop iteration, of the elements that are equal to the current element `$_` and take the `.Count` of that. We then subtract `-1` so we don't count our current element, and that number is left on the pipeline. Output at the end is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\ordering-a-list.ps1 @(4,4,0,1,1,2,0,1) 6 7 0 2 3 5 1 4 PS C:\Tools\Scripts\golfing> .\ordering-a-list.ps1 @(8,10,4,-1,-1) 3 4 2 0 1 ``` [Answer] # CJam, 15 bytes ``` {{eeWf%$1f=}2*} ``` [Try it online!](http://cjam.tryitonline.net/#code=e3tlZVdmJSQxZj19Mip9Cgpxflx-cA&input=WzQgNCAwIDEgMSAyIDAgMV0) ## Explanation ``` { } Delimits an anonymous block. { }2* Run this block on the argument twice: ee Enumerate ([A B C] → [[0 A] [1 B] [2 C]]) Wf% Reverse each ([[A 0] [B 1] [C 2]]) $ Sort the pairs lexicographically; i.e. first by value, then by index. 1f= Keep the indices. ``` [Answer] # J, 5 bytes ``` /:^:2 ``` Grade up (`/:`) twice (`^:2`). 0-indexed. To try it out, type `f =: /:^:2` and then `f 4 4 0 1 1 2 0 1` into [tryj.tk](http://tryj.tk/). [Answer] # MATL, ~~10~~ ~~9~~ 4 bytes *4 Bytes saved thanks to @Luis* ``` &S&S ``` This solution uses 1-based indexing [**Try it Online**](http://matl.tryitonline.net/#code=JlMmUw&input=WzAsOCwtMSw1LDhd) [Answer] ## 05AB1E, 12 bytes ``` 2FvyN‚}){€¦˜ ``` **Explained** ``` 2F # 2 times do vyN‚}) # create list of [n, index]-pairs {€¦ # sort and remove first element leaving the index ˜ # deep flatten # implicit output ``` [Try it online](http://05ab1e.tryitonline.net/#code=MkZ2eU7igJp9KXvigqzCpsuc&input=WzQsNCwwLDEsMSwyLDAsMV0) [Answer] # Python 2, 67 bytes ``` a=input() p=[] for x in a:print sorted(a).index(x)+p.count(x);p+=x, ``` xnor saved two bytes. [Answer] ## Haskell, 40 bytes ``` f l|z<-zip l[0..]=[sum[1|y<-z,y<x]|x<-z] ``` Annotate each element with its index, then map each element to the count of smaller elements, tiebreaking on index. No sorting. [Answer] # Julia, 17 bytes ``` ~=sortperm;!x=~~x ``` 1-indexed. Grade up ([`sortperm`](http://docs.julialang.org/en/release-0.4/stdlib/sort/#Base.sortperm)) twice. [Try it here.](http://julia.tryitonline.net/#code=fj1zb3J0cGVybTsheD1-fngKcHJpbnQoIVs0LDQsMCwxLDEsMiwwLDFdKQ&input=) EDIT: Dennis saved *four* bytes by giving stuff operator-y names! Julia is weird. [Answer] ## JavaScript (ES6), 52 bytes ``` a=>(g=a=>[...a.keys()].sort((n,m)=>a[n]-a[m]))(g(a)) ``` Defines `g` as the grade function, which returns an array of indices to which all the elements in the sorted array would have come from in the original array. Unfortunately what we want is the indices which all the elements will go to. Fortunately this turns out to be the mapping from the grade back to the original list of indices, which itself can be considered to be the result of sorting the grade, thus allowing us to take the grade of the grade to achieve the desired result. [Answer] # Pyth, ~~10~~ 9 bytes **1 byte thanks to Jakube.** ``` xLo@QNUQU ``` [Test suite.](http://pyth.herokuapp.com/?code=xLo%40QNUQU&test_suite=1&test_suite_input=%5B0%5D%0A%5B23%5D%0A%5B2%2C3%5D%0A%5B3%2C2%5D%0A%5B2%2C2%5D%0A%5B8%2C10%2C4%2C-1%2C-1%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%5D%0A%5B7%2C6%2C5%2C4%2C3%2C2%2C1%2C0%5D%0A%5B4%2C4%2C0%2C1%2C1%2C2%2C0%2C1%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D&debug=0) There **must** be a shorter way... [Answer] # Racket, 117 bytes ``` (λ(x)(build-list(length x)(λ(h)((λ(y)(+(count(λ(z)(< z y))x)(count(λ(z)(eq? z y))(take x h))))(list-ref x h))))) ``` I am eternally disappointed by the lack of a builtin for this. [Answer] # Ruby, ~~54~~ 53 bytes [Try it online](https://repl.it/CdjE/1) -1 byte from upgrading to @Downgoat's approach of using a hash to store values instead of counting the duplicates each time. ``` ->a{b={};a.map{|e|a.sort.index(e)+b[e]=(b[e]||-1)+1}} ``` [Answer] # Clojure, 83 bytes ``` (fn[a](nth(iterate #(->> %(map-indexed(comp vec rseq vector))sort(map second))a)2)) ``` I create an anonymous function that grades the input array up and iterate it twice on the input. The first call will return the grade. The second call operates on the grade and returns the rank. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes ``` lL-M,?og:MjO,L~l.#d:Orz:ma? ``` [Try it online!](http://brachylog.tryitonline.net/#code=bEwtTSw_b2c6TWpPLEx-bC4jZDpPcno6bWE_&input=Wzg6MTA6NDpfMTpfMTo4XQ&args=Wg) or [verify all test cases](http://brachylog.tryitonline.net/#code=Ons6MiZ3QE53fWEKbEwtTSw_b2c6TWpPLEx-bC4jZDpPcno6bWE_&input=W1swXTpbMjNdOlsyOjNdOlszOjJdOlsyOjJdOls4OjEwOjQ6XzE6XzE6OF06WzA6MToyOjM6NDo1OjY6N106Wzc6Njo1OjQ6MzoyOjE6MF06WzQ6NDowOjE6MToyOjA6MV06WzE6MToxOjE6MToxOjE6MV06WzE6MToxOjE6MToxOjE6MF1d). ### Explanation This is a straightforward implementation of the following relationship: each integer of the output corresponding to an element of the input is the index of that element in the sorted input. ``` Example input: [3:2] lL L is the length of the input (e.g L=2) -M, M = L-1 (e.g. M=1) ?o Sort the input... g:MjO, ... and create a list O with L copies of the input (e.g. O=[[2:3]:[2:3]]) L~l. Output is a list of length L (e.g. [I:J]) #d All elements of the output must be distinct (e.g. I≠J) :Orz Zip O with the output (e.g. [[[2:3]:I]:[[2:3]:J]]) :ma? Apply predicate Member with that zip as input and the input as output (e.g. 3 is the Ith element of [2:3] and 2 is the Jth element of [2:3]) ``` [Answer] # Mathematica, 15 bytes ``` (o=Ordering)@*o ``` [Answer] # Mathematica, 135 bytes ``` Function[{list}, SortBy[MapIndexed[Join[{#1}, #2]&, Sort@MapIndexed[Join[{#1}, #2] &, list]], #[[1, 2]] &][[All, 2]] - 1] ``` [Answer] ## Common Lisp, 117 bytes ``` (flet((i(Z)(mapcar'cdr(stable-sort(loop for e in Z for x from 0 collect(cons e x))'< :key'car))))(lambda(L)(i(i L)))) ``` Apply a [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform) twice. ``` ;; FIRST TIME (0 8 -1 5 8) ;; add indexes ((0 . 0) (8 . 1) (-1 . 2) (5 . 3) (8 . 4)) ;; sort by first element ((-1 . 2) (0 . 0) (5 . 3) (8 . 1) (8 . 4)) ;; extract second elements (2 0 3 1 4) ;; SECOND TIME (2 0 3 1 4) ;; indexes ((2 . 0) (0 . 1) (3 . 2) (1 . 3) (4 . 4)) ;; sort by first element ((0 . 1) (1 . 3) (2 . 0) (3 . 2) (4 . 4)) ;; extract second elements (1 3 0 2 4) ``` ### Test ``` (let ((fn (flet((i(Z)(mapcar'cdr(stable-sort(loop for e in Z for x from 0 collect(cons e x))'< :key'car))))(lambda(L)(i(i L)))))) (every (lambda (test expected) (equal (funcall fn test) expected)) '((0) (23) (2 3) (3 2) (2 2) (8 10 4 -1 -1 8) (0 1 2 3 4 5 6 7) (7 6 5 4 3 2 1 0) (4 4 0 1 1 2 0 1) (1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 0)) '((0) (0) (0 1) (1 0) (0 1) (3 5 2 0 1 4) (0 1 2 3 4 5 6 7) (7 6 5 4 3 2 1 0) (6 7 0 2 3 5 1 4) (0 1 2 3 4 5 6 7) (1 2 3 4 5 6 7 0)))) => T ``` [Answer] ## JavaScript (using external library) (105 bytes) ``` (n)=>{var a=_.From(n).Select((v,i)=>v+""+i);return a.Select(x=>a.OrderBy(y=>(y|0)).IndexOf(x)).ToArray()} ``` Link to lib: <https://github.com/mvegh1/Enumerable> Explanation of code: Create anonymous method that accepts a list of integers. \_.From creates an instance of the library that wraps an array with special methods. Select maps each item to a new item, by taking the "v"alue, parsing it to a string, then concatenating the "i"ndex of that item (this solves duplicate value case). Thats stored in variable 'a'. Then we return the result of the following: Map each item in 'a' to the index of that item in the sorted version of a (as integers), and cast back to a native JS array [![enter image description here](https://i.stack.imgur.com/8ahoa.png)](https://i.stack.imgur.com/8ahoa.png) Note that negative duplicate numbers seem to print in the reverse order. I'm not sure if that invalidates this solution? Technically 8,10,4,-1,-1,8 should be 3,5,2,0,1,4 according to OP but my code is printing 3,5,2,1,0,4 which I believe is still technically valid? [Answer] ## GNU Core Utils, 39 33 bytes ``` nl|sort -nk2|nl|sort -nk2|cut -f1 ``` Produces 1-based output. Add `-v0` after the second `nl` to get 0-based output. (+4 bytes) Commands we are using: * `nl` adds line numbers to each line of the input. * `sort -n -k 2` sorts by column 2 numerically. * `cut -f 1` takes the first Tab-delimited column, discarding the rest. Additionally, the `-s` option can be passed to `sort` to request a stable sort, but we don't need it here. If two items are identical, `sort` will determine their order by falling back to the other columns, which in this case is the monotonically increasing output from `nl`. So the sort will be stable without needing to specify it, by virtue of the input. [Answer] # Java ~~149~~ 140 bytes ``` public int[] indexArray(int[] index){ int[] out=new int[index.length]; for(int i=-1;++i<index.length;){ for(int j=-1;++i<index.length;){ if(index[i]==Arrays.sort(index.clone())[j]){ out[i]=j; } } } return out; } ``` Golfed ``` int[]a(int[]b){int l=b.length;int[]o=new int[l];for(int i=-1;++i<l;)for(int j=-1;++i<l;)if(b[i]==Arrays.sort(b.clone())[j])o[i]=j;return o;} ``` Thanks to @Kevin Cruissjen for shaving of 9 bytes. [Answer] # PHP, 88 bytes ``` unset($argv[0]);$a=$argv;sort($a);foreach($argv as$e)echo$h[$e]+++array_search($e,$a),_; ``` operates on command line arguments; prints 0-indexed, underscore-separated list. Run with `-nr`. **breakdown** ``` unset($argv[0]); // remove file name from arguments $a=$argv; // create copy sort($a); // sort copy (includes reindexing, starting with 0) foreach($argv as$e) // loop $e through original echo // print: $h[$e]++ // number of previous occurences +array_search($e,$a)// plus position in copy ,_ // followed by underscore ; ``` [Answer] # **MATLAB, 29 bytes** ``` function j=f(s);[~,j]=sort(s) ``` Most of MATLAB's sorting built-ins will return an optional second array containing the sorted indices. The `j=` could be removed if printing the indices is acceptable, rather than returning them. [Answer] # [CJam](https://sourceforge.net/p/cjam), 19 bytes ``` _$:A;{A#_AWt:A;1+}% ``` [Try it online!](https://tio.run/##S85KzP2fo66jX51Zq/o/XsXK0braUTneMbwEyDLUBor9N9Mx1rHQMdIx1DEGAAA "CJam – Try It Online") Explanation: ``` _ duplicate array $ sort array :A store in variable A ; discard top item in stack {A#_AWt:A;1+} block that finds index of item and removes it from sorted array to prevent duplicates % map block onto every item in array ``` ]
[Question] [ There's quite a few challenges on this site that ask you to print out a sequence, and this is no exception. (The following explanation of the sequence for this challenge assumes the symbols in the sequence are `0` and `1`.) The recursive definition of the [Thue-Morse sequence](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence) is that ``` T_0 = 0 T_2n = T_n T_2n+1 = 1 - T_n ``` A more direct definition is that the sequence from `0` to `2**m-1` and `2**m to 2**(m+1)-1` are binary complements. So `0` is followed by `1`, `01` is followed by `10`, `0110` is followed by `1001`, and, skipping ahead a bit, `0110100110010110` is followed by `1001011001101001`. The challenge is to write a program or a function that prints out the [Thue-Morse sequence](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence) for the first `n` elements, where `n` is any non-negative integer. The output can use any two symbols, as shown in the examples below. **Examples** ``` >>> tm_01(20) 01101001100101101001 >>> tm_ab(42) abbabaabbaababbabaababbaabbabaabbaababbaab >>> tm_paren(37) ())()(())(()())()(()())(())()(())(()( >>> tm_space_star(12) ** * ** * >>> tm_01(0) # to show that this is a valid input ``` **Rules** * The input will be any non-negative integer. You can assume all inputs are valid. * The output must be the first `n` elements of the Thue-Morse sequence, using any symbols that are convenient. If you like, you can also add a separator. In my examples, I have not. **Note:** This rule allows lists (like those of Python), as `,` is a valid separator and I don't mind leading or trailing characters, such as `[` and `]` in the output. * This is code golf, so the smallest number of bytes wins. As always, if the problem is unclear, please let me know. Good luck and good golfing! ## Catalogue ``` var QUESTION_ID=65549;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=47581;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"http://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.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)}} ``` ``` 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} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Pyth, 6 bytes ``` xMjR2Q ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=xMjR2Q&input=20&debug=0) Based on the solution from @ThomasKwa and a variation of @FryAmTheEggman. It uses the following formular: the `i`-th digit in the Thue-Morse sequence is: `xor(digits of i in base 2)`. ### Explanation: ``` xMjR2Q implicit: Q = input number jR2Q convert each number in [0, 1, ..., Q-1] to its binary digits xM xor each binary list ``` [Answer] ## CJam, ~~17~~ 9 bytes ``` ri{2b:^}/ ``` or ``` ri,2fb::^ ``` [Test it here.](http://cjam.aditsu.net/#code=q~%7B2b%3A%5E%7D%2F&input=42) ### Explanation This uses the alternative definition given on Wikipedia, based on the parity of the number of `1`s in the binary representation of the `n`. ``` ri e# Read input and convert to integer n. { e# For each i from 0 to n-1... 2b e# Convert i to base 2. :^ e# Fold XOR over the bits to compute the parity of the number of 1s. }/ ``` The alternative solution uses `,` to turn `n` explicitly into a range `[0 ... n-1]` before using infix operators to compute the binary representations and the XOR without needing a block. ### Bonus Solutions Here are some solutions based on other definitions. If there are two solutions, the shorter one will blow up memory *very* quickly (because the precomputation generates `2^n` bits before truncating to `n`). As an L-system with `0 --> 01` and `1 --> 10`: ``` ri_2mL2,\{2,aA+f=s:~}*< ri_2,\{2,aA+f=s:~}*< ``` By negating and appending the previous part: ``` ri_2mL2,\{_:!+}*< ri_2,\{_:!+}*< ``` Using the recurrence relation given in the challenge, using `divmod` and XOR to distinguish between the two recursive definitions: ``` ri{Ta{2md\j^}j}/ ``` (Although, of course, this recurrence relation is just a different way to express the Thue-Morse sequence as the parity of the 1-bits in the binary representation of `n`.) [Answer] # LabVIEW, 15 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) now as super fancy gif with a probe [![enter image description here](https://i.stack.imgur.com/nRHM4.gif)](https://i.stack.imgur.com/nRHM4.gif) [Answer] ## Dyalog APL, ~~8~~ 7 bytes ``` ≠⌿⍴∘2⊤⍳ ``` This is a monadic train that expects an index origin of 0 (`⎕IO←0`). The equivalent non-train function is `{≠⌿(⍵⍴2)⊤⍳⍵}`. Explanation: ``` ⍳ List of numbers from 0 to (input-1) ⍴∘2 (input) copies of 2 ⊤ Convert all the elements in ⍳ to base 2 to (input) digits ≠⌿ Reduce over the first axis by not-equal ``` Output is a space-separated list of `0` and `1`. Try it [here](http://tryapl.org/?a=%u2395IO%u21900%u22C4%28%u2260%u233F%u2374%u22182%u22A4%u2373%29%A80%201%202%203%205%208%2013&run). [Answer] # Mathematica, ~~35~~ 21 bytes Mathematica has a built-in for the Thue-Morse sequence! ``` Array[ThueMorse,#,0]& ``` --- Original answer: ``` #&@@@DigitCount[Range@#-1,2]~Mod~2& ``` [Answer] ## J, ~~12~~ 11 bytes @MartinBüttner saved a byte. ``` ~:/@#:"0@i. ``` This is a monadic (meaning unary) function, used as follows: ``` f =: ~:/@#:"0@i. f 10 0 1 1 0 1 0 0 1 1 0 ``` ## Explanation I'm using the alternative definition that Tn is the parity of the number of 1-bits in the binary representation of n. ``` ~:/@#:"0@i. Input is n. ~:/ Output is XOR folded over @#: the binary representations of "0 each element of @i. integers from 0 to n-1. ``` [Answer] ## Pyth, ~~11~~ 10 bytes ``` m%ssM.Bd2Q ``` Outputs as a Python-style list. [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~29~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Uo ®¤¬r@X^Y ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VW8grqSsckBYXlk=&input=NDI=) Outputs directly as an array, which saves about 4 bytes. ### Ungolfed and explanation ``` Uo ® ¤ ¬ r@ X^Y Uo mZ{Zs2 q rXY{X^Y}} // Implicit: U = input number Uo // Create an array of integers in the range `[0, U)`. mZ{Zs2 // Map each item Z in this range to Z.toString(2), q rXY{ // split into chars, and reduced by X^Y}} // XORing. // This returns (number of 1s in the binary string) % 2. // Implicit: output last expression ``` **Edit:** You can now use the following **8-byte** code (not valid; feature published after this challenge): ``` Uo ®¤¬r^ ``` [Answer] ## Haskell, ~~39~~ ~~36~~ 35 bytes ``` take<*>(iterate([id,(1-)]<*>)[0]!!) ``` [Try it online!](https://tio.run/##VcixDkAwEADQ3VecxNCKJtUY8SNluFRLo2i03@9Yje9tmHYbArlhooy77euR@WxvzJZpvzSsFXz@kms5lyWnA/0JAyxXARBvf2aowEGrflTyx04V9BgXcE0kTIwv "Haskell – Try It Online") How it works: start with `[0]` and apply the `x ++ invert x`-function `n` times. Take the first `n` elements from the resulting list. Thanks to Haskell's laziness only the first `n` elements are actually calculated. Note: the first `<*>` is in function context, the second in list context. With GHC v8.4 (which wasn't available at the the time of the challenge) there's a 34 byte solution: ``` take<*>(iterate(id<>map(1-))[0]!!) ``` Edit: -3 resp. -4 bytes thanks to @Laikoni. -1 byte thanks to @Ørjan Johansen. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 33 bytes ``` n->[sumdigits(x,2)%2|x<-[0..n-1]] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLrq4NDclMz2zpFijQsdIU9WopsJGN9pATy9P1zA29n9BUWZeiUaahrGRpuZ/AA "Pari/GP – Try It Online") [Answer] # K5, ~~27~~ 13 bytes ``` {x#((log x)%log 2){x,~x}/0} ``` Calculating the sequence is pretty easy, the problem is avoiding computing too much. We can recognize that the easy expansion of the sequence gives us a sequence of strings which are successive powers of two in length. Taking the log base 2 of the input and rounding up will give us enough to work with and then we can cut it down to the appropriate size: ``` {x#((log x)%log 2){x,~x}/0}'(20 42 37 12 0) (0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 0 1 1 0 1 0 0 1 1 0 0 1 ()) ``` ## Edit: A parity-based solution: ``` ~=/'(64#2)\'! ``` In action: ``` ~=/'(64#2)\'!20 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 ``` Note that since K5 doesn't have an arbitrary convert-to-binary primitive I have to specify, for example, a 64-bit decoding. K5 doesn't use arbitrary precision math, so there will be a limit to the size of inputs we can deal with in any case. [Answer] # Octave, ~~33~~ 31 bytes Saved 2 bytes thanks to Thomas Kwa. ``` @(n)mod(sum(dec2bin(0:n-1)'),2) ``` [Answer] ## Haskell, 54 bytes Less compact than nimi's solution, but I did not want to deny you this piece of functional code obfuscation. Works for any pair of objects; e.g. you can replace `(f 0.f 1)` by `(f 'A'.f 'B')`. Based on the definition that the first 2n digits are followed by the same sequence of digits inverted. What we do is build up two lists side-by-side; one for the sequence, one for the inverse. Continuously we append increasingly long parts of one list to the other. The implementation consists of three definitions: ``` t=(f 0.f 1)t f c=flip take.(c:).g 1 g n l=l n++g(n+n)l ``` Function `t` accepts any number and returns the Thue-Morse sequence of that length. The other two functions are helpers. * Function `f` represents either list; `f 0` is for the sequence, `f 1` for the inverse. * Function `g` takes care of appending increasingly long repetitions of one list to the other. Fiddle: <http://goo.gl/wjk9S0> [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes *This language was designed after the challenge*. ## Approach 1: 13 bytes This builds the sequence by concatenating negated copies of increasing-size blocks. ``` itBFw"t~h]w:) ``` ### Example ``` >> matl itBFw"t~h]w:) > 20 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 ``` ### Explanation ``` i % input number, say "N" tB % duplicate and convert to binary. Produces a vector F % initialize sequence to "false" w % swap to bring vector to top " % for loop. There will be at least log2(N) iterations t~h % duplicate, negate, concatenate ] % end for w % swap :) % index with vector 1, 2, ..., N ``` ## Approach 2: 9 bytes This uses the same approach as [Alephalpha's answer](https://codegolf.stackexchange.com/a/65612/36398). ``` i:1-B!s2\ ``` ### Example ``` >> matl i:1-B!s2\ > 20 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 ``` ### Explanation ``` i % input "N" :1- % create vector 0, 1, ..., N-1 B % convert to binary ! % tranpose s % sum 2\ % modulo 2 ``` [Answer] ## Burlesque, 21 bytes ``` {0}{J)n!_+}400E!jri.+ ``` Examples: ``` blsq ) "20"{0}{J)n!_+}400E!jri.+ {0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1} blsq ) "42"{0}{J)n!_+}400E!jri.+ {0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1} ``` Explanation: ``` {0} -- setup {J)n!_+} -- duplicate, map invert, concatenate 400E! -- do 400 times (this will eventually run out of memory). jri.+ -- take n elements ``` Without the `jri.+` part you will run out of memory (because it will compute the morse sequence of length *incredibly huge number*). But since Burlesque is lazy just asking for the first n-element will work anyway. [Answer] # Perl 5, ~~62~~ 49 bytes Yeah, not the best language for this one, but I still like the way it came out. Requires 5.14+ for `/r` and `say`. ``` sub{$_=0;$_.=y/01/10/r while$_[0]>length;say substr$_,0,$_[0]} ``` Using the parity definition, requires 5.12+ for `say`: ``` sub{say map{sprintf("%b",$_)=~y/1//%2}0..$_[0]-1} ``` [Answer] # Prolog (SWI), 115 bytes **Code:** ``` N*X:-N>1,R is N//2,R*Y,X is(N mod 2)xor Y;X=N. p(N):-M is N-1,findall(E,between(0,M,E),L),maplist(*,L,K),write(K). ``` **Explained:** ``` N*X:- % Calculate Thue-Morse number at index N N>1, % Input is bigger than 1 R is N//2,R*Y,X is(N mod 2)xor Y % Thue-Morse digit at index N is binary digits of N xor'ed ;X=N. % OR set X to N (end of recursion) p(N):- M is N-1, % Get index of Nth number findall(E,between(0,M,E),L), % Make a list of number 0->N-1 maplist(*,L,K), % Map * on list L producing K write(K). % Print K ``` **Example:** ``` p(20). [0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1] ``` Try it online [here](http://swish.swi-prolog.org/p/HhUAESEr.pl) [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~70~~ 69 bytes Using the definition as an L-system with initial word `0` and productions `0 --> 01` and `1 --> 10`. ``` ^ 0; (T`d`ab`^(.)+;(?!(?<-1>.)+$) a 01 )`b 10 !`^(?=.*;(.)+)(?<-1>.)+ ``` Input is taken [in unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). You can run the code from a single file with the `-s` flag. Or just [try it online.](http://retina.tryitonline.net/#code=XgphCihUYGFiYEFCYF4oXEQpKzEoPyEoPzwtMT4uKSskKQpBCmFiCilgQgpiYQohYF4oPz1cRCooLikrKSg_PC0xPi4pKw&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx) ### Explanation ``` ^ 0; ``` Prepends `0;` to the input, where `0` is the initial word and `;` is just a separator. ``` (T`d`ab`^(.)+;(?!(?<-1>.)+$) ``` The `(` indicates that this is the beginning of a loop (which repeats until the loop stops changing the string). This stage itself turns `0` and `1` into `a` and `b` respectively (because `d` expands to `0-9`). It does this as long as current word (whose length is measured with `(.)+` is shorter than the input (i.e. as long as we can't read the end of the string by matching as many `1`s as we have in the word). ``` a 01 ``` Replace `a` (stand-in for `0`) with `01`. ``` )`b 10 ``` Replace `b` (stand-in for `1`) with `10`. This is also the end of the loop. The loop terminates once the condition in the transliteration stage fails, because then all `0`s and `1`s will remain unchanged and the other two stages won't find anything to match. ``` !`^(?=.*;(.)+)(?<-1>.)+ ``` The last step is to truncate the word to the length of the input. This time we measure the length of the input with `(.)+` in a lookahead. Then we match that many characters from the beginning of the string. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 11 chars / 23 bytes (non-competitive) ``` Ⓐïⓜ_ⓑⓢĊ⇀$^_ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=5&code=%E2%92%B6%C3%AF%E2%93%9C_%E2%93%91%E2%93%A2%C4%8A%E2%87%80%24%5E_)` The circles are strong with this one. [Answer] # Ruby, 33 ``` ->n{n.times{|i|p ("%b"%i).sum%2}} ``` Call like this: ``` f=->n{n.times{|i|p ("%b"%i).sum%2}} f[16] ``` Uses the fact that the parity of binary numbers forms the thue-morse sequence. Separator character is newline. Converts number `i` to a binary string, then calculates the sum of all ASCII codes, modulo 2. If newline is not an acceptable separator, the following has no separator for an additional 2 bytes: ``` ->n{n.times{|i|$><<("%b"%i).sum%2}} ``` [Answer] # C, 88 83 bytes Calculates the parity for each individual position. ``` i,j;main(int c,char**a){for(;i<atoi(a[1]);putchar(c))for(c=48,j=i++;j;j&=j-1)c^=1;} ``` Fiddle: <http://goo.gl/znxmOk> [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ḶB§Ḃ ``` Note that this challenge is older than Jelly. [Try it online!](https://tio.run/##y0rNyan8///hjm1Oh5Y/3NH0//9/EyMA "Jelly – Try It Online") ### How it works ``` ḶB§Ḃ Main link. Argument: n (integer) Ḷ Unlength; yield [0, ..., n-1]. B Compute the binary representation of each integer in the range. § Take the sum of each binary representation. Ḃ Take the LSB of each sum. ``` [Answer] # [Common Lisp](http://www.clisp.org/), 50 bytes ``` (lambda(n)(dotimes(i n)(princ(mod(logcount i)2)))) ``` [Try it online!](https://tio.run/##DcdLEoAgCADQfadgCTvrRuanYQbBUs9Pvt1LwqM7jjJfqI4S250jKmG2ya0MZNjpH2vCZhnFnmRLJzBdtDkdWJemKAIVzhDIfw "Common Lisp – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), ~~35~~ 29 bytes ``` C0<esc>qqy$V!tr 01 10 P|q@-@q@-lD ``` [Try it online!](https://tio.run/##K/v/39nAJrU42a6wsFIlTLGkSMHAUMHQgCugptBB1wGIc1z@/zcy@K9bBgA "V (vim) – Try It Online") -6 bytes from Leo. Prints the first \$n\$ elements. The sequence is basically a string replacement and append, so it does that \$n\$ times using `tr` and then truncates the sequence to \$n\$ digits. [Answer] # Matlab, 42 I am using the fact that it is the same as beginning with `0` and then repeating the step of appending the complement of the current series, `n` times. ``` t=0;for k=1:input('');t=[t;~t];end;disp(t) ``` [Answer] ## Bash, 71 66 bytes Based on the definition that the first 2n digits are followed by the same sequence of digits inverted. ``` x=0;y=1;while((${#x}<$1));do z=$x;x=$x$y;y=$y$z;done;echo ${x::$1} ``` `$1` as a parameter is the desired number of digits. Fiddle: <http://goo.gl/RkDZIC> [Answer] ## Batch, 115 + 2 = 117 bytes Based on the Bash answer. ``` @echo off set x=0 set y=1 set z=0 :a set x=!x!!y! set y=!y!!z! set z=!x:~0,%1! if !z!==!x! goto a echo !z! ``` Needs an extra `/V` in the invocation to allow the use of `!`s. [Answer] ## ES6, 53 bytes ``` f=(i,x="0",y=1)=>x.length<i?f(i,x+y,y+x):x.slice(0,i) ``` Recursion seemed simpler than a loop. [Answer] # [Par](http://ypnypn.github.io/Par/), 8 bytes ``` ✶u[Σ_✶¨^ ``` Explanation: ``` ✶ parse implicit input number u range [0..n-1] [ map: Σ convert to binary _✶ get digit list ¨^ fold with xor ``` Outputs something like: ``` (0 1 1 0 1 0 0 1) ``` [Answer] # [Math++](http://esolangs.org/wiki/Math%2B%2B), 86 bytes Uses `0.0\n` for 0 and `1.0\n` for 1 ``` ?>n 3*!!(n-m)>$ m>a 0>k 6+6*!a>$ 9-2*!(a%2)>$ a/2>a 5>$ (a-1)/2>a !k>k 5>$ k m+1>m 2>$ ``` ]
[Question] [ ## Description The Gameboy stores tiles as 2 bit-per-pixel 8x8 images, thus 16 bytes. Every two bytes is a complete row with all of the Low-bits of each pixel in the first byte, and all of the High-bits of each pixel in the second. ## Input Input will be exactly 16 bytes, received through [Standard IO](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) in one of the following forms: * Array of bytes or strings * 16 byte string Per the Standard IO, these may be in a language convenient form (Deliminated string, on the stack, etc.) ## Output An image, Rendered or Saved, of the Gameboy Tile. Scale and Aspect Ratio of each pixel is not fixed. Each 2 bit colour of the Pallet may be anything so long as the Manhattan Distance of the RGB256 representation is atleast 48. Eg. `#FFFFFF, #AAAAAA, #555555, #000000`. Traditionally, although not a requirement, `00` is the lightest colour, and `11` is the darkest. ## Examples `[FF, 00, 7E, FF, 85, 81, 89, 83, 93, 85, A5, 8B, C9, 97, 7E, FF]` [![A Pokemon Window](https://i.stack.imgur.com/xpqR1.png)](https://i.stack.imgur.com/xpqR1.png) `[7C, 7C, 00, C6, C6, 00, 00, FE, C6, C6, 00, C6, C6, 00, 00, 00]` [![The letter A](https://i.stack.imgur.com/tHeTg.png)](https://i.stack.imgur.com/tHeTg.png) ## Final Notes * [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * An online demo, and more in-depth explanation of the implementation can be found [HERE](https://www.huderlem.com/demos/gameboy2bpp.html) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! (The Gameboy only had 65536 bytes of Address Space, after all!) * Have Fun! [Answer] # Gameboy machine code, 257 bytes ``` 00000000 f0 44 fe 90 38 fa 3e e4 e0 47 21 90 81 1a 22 13 |.D..8.>..G!...".| 00000010 1a 22 13 1a 22 13 1a 22 13 1a 22 13 1a 22 13 1a |."..".."..".."..| 00000020 22 13 1a 22 13 1a 22 13 1a 22 13 1a 22 13 1a 22 |".."..".."..".."| 00000030 13 1a 22 13 1a 22 13 1a 22 13 1a 22 18 fe 00 00 |..".."..".."....| 00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| * 000000d0 00 00 00 00 00 00 00 00 ff 00 7e ff 85 81 89 83 |..........~.....| 000000e0 93 85 a5 8b c9 97 7e ff 00 00 00 00 00 00 00 00 |......~.........| 000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000100 c7 |.| 00000101 ``` Generated by this RGBASM assembly: ``` DEF rLY EQU $ff44 DEF rBGP EQU $ff47 SECTION "0",ROM0[0] WaitVBlank: ldh a, [rLY] cp 144 jr c, WaitVBlank ld a, %11100100 ; set background palette ldh [rBGP], a ld hl, $8190 ; override the tile data for the (R) icon REPT 15 ld a, [de] ld [hli], a inc de ENDR ld a, [de] ld [hli], a jr @ SECTION "Input Data",ROM0[$d8] DB $ff, $00, $7e, $ff, $85, $81, $89, $83, $93, $85, $a5, $8b, $c9, $97, $7e, $ff SECTION "Entrypoint",ROM0[$100] rst 0 ; jump to reset vector 0 ``` You can compile this code with rgbds: `rgbasm tile.asm -o - | rgblink - -o tile.gb`. A gameboy ROM is usually at least 16K, so some emulators don't support this, but sameboy executes it with no problem. The entrypoint of the ROM, after the boot ROM executed is 0x100, so I don't think it can be any smaller. As per the IO rules, [Assembly programs may read input from some specified memory location](https://codegolf.meta.stackexchange.com/a/8510), in this case `0xd8`, which is conveniently the value of the `de` register when the boot ROM exits. [Answer] # [J](http://jsoftware.com/), 41 bytes ``` load'viewmat' [:viewmat 2#._2|:@|.\#:@dfh ``` [Try it online - fails because TIO can't run viewmat](https://tio.run/##NYrLCoJAAEX3fsUVF7OZBh@UzUBgRi7btkiRIWfSHgoqPUD69UmpFgfOPdyz4bbwsoUtOCHm2siC3Cv1uMmeWHrFDuK34Dss9wcRDSx1RFTo0uxihr1CLy8KsoZsW/lCo1GqJ7q@repTZ6lj2UAj95GlIKAEM/YGSRIK16UItxSTL@cj3ggfCSh48G3rqccUm7Hz8P8n5gM "J – Try It Online") [Working link that outputs a matrix of integers 0 thru 3](https://tio.run/##NY1BC4IwAIXv@xXPPIxgDTXKNghMyVN06NJFkVFbVqCgHgqkv74m0eGDx8fjvYcVngzLtScFpWTGqcFWgoIhgHQsOLLTIbeRz6tolMnIC18mV1PbOSHHlOOsMainhmqguk690RrU@oV@6O7NrSf6UrcwqCKUxbRL3eQHNM/dQ8AQ7xmmvFk5QodwLBnE8ud2k08ZMudF/O9T@wU "J – Try It Online") Takes input as an array of hex strings. * Convert each hex string to a binary number * Take then in rows of two, reverse and transpose and convert back decimal * View the resulting matrix as an image Image produced when running the function locally: [![enter image description here](https://i.stack.imgur.com/zVB7l.png)](https://i.stack.imgur.com/zVB7l.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` 8&B1L&Y)E+1YG ``` Inputs an array of bytes, and displays an image. The image consists of grey colours where `00` corresponds to black and `11` to white. Try it at [MATL Online](https://matl.io/?code=8%26B1L%26Y%29E%2B1YG&inputs=%5B255+++0+++126+++255+++133+++129+++137+++131+++147+++133+++165+++139+++201+++151+++126+++255%5D&version=22.7.4)! ### How it works ``` 8&B % Implicit input: 1×16 array. Convert to binary with 8 bits. % Gives a 16×8 array 1L % Push [1 2 j]. As an index, this is interpreted as 1:2:end &Y) % Two-ouput row indexing. This gives an 8×8 subarray with the % indicated rows, and an 8×8 subarray with the remaining rows E % Multiply by 2, element-wise + % Add. This gives an 8×8 array with possible values 0, 1, 2, 3 1YG % Display as an image with scaled colors, using the default % grey colormap ``` [Answer] # Shell + [rgbds](https://rgbds.gbdev.io/) devkit, 16 bytes ``` rgbgfx -r1 -o- - ``` Takes raw bytes from stdin and outputs a png on stdout. rgbgfx is the graphics conversion program from the RGBDS Gameboy Development Kit, intended to convert PNGs to Gameboy tile data, and vice-versa. [Answer] # [R](https://www.r-project.org), 65 bytes ``` \(a)image(t((b=outer(rev(a),2^(7:0),`%/%`)%%2)[!1:0,]+2*b[!0:1])) ``` [Don't attempt This Online](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3HWM0EjUzcxPTUzVKNDSSbPNLS1KLNIpSy4DCOkZxGuZWBpo6Car6qgmaqqpGmtGKhlYGOrHaRlpJ0YoGVoaxmpoQgxZAKSgNAA); instead, [Try it at rdrr.io with graphical output](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a)image(t((b%3Douter(rev(a)%2C2%5E(7%3A0)%2C%60%25%2F%25%60)%25%252)%5B!1%3A0%2C%5D%2B2*b%5B!0%3A1%5D))%0A%0A%0Ab%3Dc(124%2C%20124%2C%20%20%200%2C%20198%2C%20198%2C%20%20%200%2C%20%20%200%2C%20254%2C%20198%2C%20198%2C%20%20%200%2C%20198%2C%20198%2C%20%20%200%2C%20%20%200%2C%20%20%200)%0Af(b)%0Ab%3Dc(255%2C%20%20%200%2C%20126%2C%20255%2C%20133%2C%20129%2C%20137%2C%20131%2C%20147%2C%20133%2C%20165%2C%20139%2C%20201%2C%20151%2C%20126%2C%20255)%0Af(b)%0A) (uses `function` instead of `\` due to older version of R installed at rdrr.io). Note that this could be 7 bytes shorter by omitting the `image()` call and outputting a [matrix of bytes](https://codegolf.meta.stackexchange.com/a/9100/95126), but R has good graphical output so it seems more in the spirit of the challenge to actually draw the image. [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), ~~100~~ 96 bytes ``` SCREEN 7 FOR r=0TO 7 INPUT a INPUT b FOR c=0TO 7 PSET(7-c,r),a\2^c MOD 2+(1AND b\2^c)*3 NEXT c,r ``` You can try it on [Archive.org](https://archive.org/details/msdos_qbasic_megapack). Input the bytes one at a time as decimal integers (0 to 255). The image is displayed in the upper left corner of the screen, overwriting the `?` prompt from the first `INPUT` statement. Each "pixel" is 2x2. The colors are: * Black: rgb(0,0,0) * Blue: rgb(0,0,170) * Cyan: rgb(0,170,170) * Red: rgb(170,0,0) [![Example run of the golfed code](https://i.stack.imgur.com/NECdb.png)](https://i.stack.imgur.com/NECdb.png) ### Ungolfed With a less golfy formula for computing the color code, and drawing each pixel as a filled box rather than a single point, it turns out we can reproduce the grayscale images in the OP exactly. ``` SCREEN 7 ' Each point in screen mode 7 is 2x2 pixels, so we draw 15x15 boxes to match ' the 30x30 pixel boxes in OP's image size = 15 FOR row = 0 TO 7 INPUT lowbits INPUT highbits FOR col = 0 TO 7 place = 2 ^ (7 - col) lowbit = (lowbits \ place) AND 1 highbit = (highbits \ place) AND 1 ' 00 = color 15, white ' 01 = color 7, light gray ' 10 = color 8, dark gray ' 00 = color 0, black colorcode = 15 - lowbit * 8 - highbit * 7 ' Compute top and left coordinates of the box based on row and column ' (with the left shifted over to avoid drawing over the inputs) top = row * size left = 60 + col * size ' Draw the box using the LINE command with the BF (box filled) option LINE (left, top)-(left + size - 1, top + size - 1), colorcode, BF NEXT col NEXT row ``` [![Example run of the ungolfed code](https://i.stack.imgur.com/EWYih.png)](https://i.stack.imgur.com/EWYih.png) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17 25~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` m¤ùT8 ò ®y͸Ãi"P2 8 8 3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&header=cSIsICIgbW5H&code=baT5VDgg8iCuec24w2kiUDIgOCA4IDM&input=IjdDLCA3QywgMDAsIEM2LCBDNiwgMDAsIDAwLCBGRSwgQzYsIEM2LCAwMCwgQzYsIEM2LCAwMCwgMDAsIDAwIgotUg) Saved two bytes thanks to Shaggy Previously, this answer outputted a string using differently shaded unicode characters to represent the different colors, but as OP has clarified that this is not allowed, it now outputs a [Plain PGM](https://netpbm.sourceforge.net/doc/pgm.html#plainpgm) file. Takes input as byte array and outputs a string representing a PGM file. ``` m¤ùT8 ò ®y͸Ãi"P2 8 8 3 : implicit input of byte array m¤ : convert each byte to binary ùT8 : left-pad each binary string with 0s ò ® : map each pair of lines to: yÍ : transpose the pair, map each two-char string to a number ¸ : join by spaces à : end map i"P2 8 8 3 : prepend the start of a PGM file : -R join by newlines ``` [![enter image description here](https://i.stack.imgur.com/S8kV4.png)](https://i.stack.imgur.com/S8kV4.png) ## [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs a [matrix of bytes](https://codegolf.meta.stackexchange.com/a/9100/58563). ``` m¤ùT8 ò ®yÍ ``` [Answer] # JavaScript (ES6), 79 bytes Expects a list of bytes and outputs [a matrix of RGB tuples](https://codegolf.meta.stackexchange.com/a/9104/58563), using the greenish palette `00C000`, `008000`, `004000`, `000000`. ``` a=>(v=[...'01234567']).map(y=>v.map(x=>[0,~a[y*2]<<x>>1&64|~a[y-~y]<<x&128,0])) ``` [Try it online!](https://tio.run/##dY9fC4IwFMXf@xQ95Qxdc@Y/cEKJfomxh2EahTnJEIXwq1vbHgyqlx/3nnO4h3vlPe@K@6V92I04lXNFZk4S0BMKITSQg9295wcGM@GNt2AkSa@GgSQUWWDidNxiFsfDxsHhU672NLItlgr2fHOHLcRMcy5E04m6hLU4gwpQNOS5tUYDQpJBJqmV0FN0FCNFVzJyF/egM0fJVGWi4PPOu3D1VRikKpIutam/UCuaefbb/ZdH6sMX "JavaScript (Node.js) – Try It Online") ## 73 bytes Outputs [a matrix of bytes](https://codegolf.meta.stackexchange.com/a/9100/58563). ``` a=>(v=[...'01234567']).map(y=>v.map(x=>~a[y*2]<<x>>1&64|~a[y-~y]<<x&128)) ``` [Try it online!](https://tio.run/##dc3dCoIwHAXw@56iK90ix/ycghuU6EuIF8M0ClPJkAnhq682Lwyqmx/j/A87Vz7yobxf@ofVdqdK1lRyysBIc4SQiW3H9fyAmAVEN96DibJRPwRlM8@nnVPEsWDMNgLvqQJrnlRi2E4IoSy7duiaCjXdGdQgxyLL9lssMFaSVLkkoa@1tZHWVUbuej0snaMy0Z2IfP5TQLj5GiSJriTrbBKsLslilv6@/utj/B6ULw "JavaScript (Node.js) – Try It Online") ## Rendering ``` f= a=>(v=[...'01234567']).map(y=>v.map(x=>[0,~a[y*2]<<x>>1&64|~a[y-~y]<<x&128,0])) F = (id, a) => { m = f(a); m.forEach(r => r.forEach(rgb => { div = document.createElement('div'); div.style.backgroundColor = '#' + rgb.map(v => v.toString(16).padStart(2, '0')).join(''); document.getElementById(id).appendChild(div); })) } F('b0', [0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF]) F('b1', [0xFF, 0x00, 0x7E, 0xFF, 0x85, 0x81, 0x89, 0x83, 0x93, 0x85, 0xA5, 0x8B, 0xC9, 0x97, 0x7E, 0xFF]) F('b2', [0x7C, 0x7C, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0x00]) F('b3', [0xFF, 0xFF, 0xFF, 0x81, 0xC3, 0x81, 0xDF, 0x85, 0xDF, 0x85, 0xFF, 0xBD, 0xFF, 0x81, 0xFF, 0xFF]) ``` ``` .box { float:left; margin-right:16px; width:128px; height:128px; } .box div { float:left; width:16px; height:16px; } ``` ``` <div id="b0" class="box"></div><div id="b1" class="box"></div><div id="b2" class="box"></div><div id="b3" class="box"></div> ``` [Answer] # C, ~~108~~ ~~105~~ ~~95~~ ~~93~~ ~~89~~ 85 bytes ``` b;main(j){for(puts("P5 8 8 3");j=j-1?:read(0,&b,2)*4;b+=b)putchar(3^b>>14&2^b>>7&1);} ``` [Try it online!](https://tio.run/##hY7dasJAEIXvfYpDLsKuunZjbJO4/qAhuW2fQNjdqGmgjcQIAeuzx1ks2LsyZ9gzh@HbKfS57K1usVhk7zl@YC1ER13jaFqI3qgv/fnNKn491A07Xdoz8z5eEVOFHlfVshLBet7sdcHk2DfjKR/OlBktDaddW@qGhTuzWgUzf@reyA@4uvX012Cwt2UNL88hJaIMZGICB4gTxCGS0I0bSrZIEyTRY8ejG7uugGggTuQnL@7OR6bgkL/cKAWJ0OmbExlSnj3Hv7mU/3P7Ow "Dash – Try It Online") Reads raw bytes from `stdin` and outputs an image in the [PGM format](https://netpbm.sourceforge.net/doc/pgm.html#format) to `stdout`. -17! thanks to @c-- [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 44 bytes ``` `0:"P2 8 8 3" 2/+,/+'0N 2#-8#'+(8#0),2\.0:` ``` Takes input as a space separated list of integers. Outputs a plain pgm to stdout. Colors are inverted from the example. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 20.5 bytes (41 nibbles) ``` "P2 8 8 3 ".`/~.$``@hex:1$>>/$!@@~++ ``` Input is an array of hex strings; output is a [plain PGM](https://netpbm.sourceforge.net/doc/pgm.html) image file (inspired by [pan's answer](https://codegolf.stackexchange.com/a/257943/95126)). ``` "P2 8 8 3 " # prepend the string "P2 8 8 3 " onto: . # map over $ # the input: :1$ # prepend a '1' hex # then get the hex value ``@ # convert to bits `/ # get chunks of 2 . # and map over these: /$ # fold across each chunk of 2 !@@ # zipping-together the 2 elements ~+ # by adding together + # the first elements added to themselves # and the second elements >> # and remove the first element ``` [![enter image description here](https://i.stack.imgur.com/U2xx9.png)](https://i.stack.imgur.com/U2xx9.png) [![enter image description here](https://i.stack.imgur.com/89xaf.png)](https://i.stack.imgur.com/89xaf.png) --- Note that if output as a [matrix of bytes](https://codegolf.meta.stackexchange.com/a/9100/95126) would be valid, we could drop the initial `"P2 8 8 3 "` header for the plain PGM format, for just 13 bytes. [Answer] # JavaScript, 105 bytes ``` v=>{for(i=0;i<8;++i)for(j=0;j<8;++j)window['c'+i+(7-j)].className='wldb'[2*(b=n=>v[2*i+n]>>j&1)(0)+b(1)]} ``` Try it: ``` f=v=>{for(i=0;i<8;++i)for(j=0;j<8;++j)window['c'+i+(7-j)].className='wldb'[2*(b=n=>v[2*i+n]>>j&1)(0)+b(1)]} button.addEventListener('click', _=>f(input.value.split` `.map(x=>+('0x'+x)))); ``` ``` .f { border: 1px solid black; width: fit-content; } .r { display: flex; } [id^="c"] { width: 40px; height: 40px; background-color: lightblue; } input { width: 320px; } .w { background-color: #fff; } .l { background-color: #555; } .d { background-color: #aaa; } .b { background-color: #000; } ``` ``` <input id="input" value="7C 7C 00 C6 C6 00 00 FE C6 C6 00 C6 C6 00 00 00"> <button id='button'>Draw</button> <br><br> <div class="f"> <div class="r"> <div id="c00"></div><div id="c01"></div><div id="c02"></div><div id="c03"></div><div id="c04"></div><div id="c05"></div><div id="c06"></div><div id="c07"></div> </div> <div class="r"> <div id="c10"></div><div id="c11"></div><div id="c12"></div><div id="c13"></div><div id="c14"></div><div id="c15"></div><div id="c16"></div><div id="c17"></div> </div> <div class="r"> <div id="c20"></div><div id="c21"></div><div id="c22"></div><div id="c23"></div><div id="c24"></div><div id="c25"></div><div id="c26"></div><div id="c27"></div> </div> <div class="r"> <div id="c30"></div><div id="c31"></div><div id="c32"></div><div id="c33"></div><div id="c34"></div><div id="c35"></div><div id="c36"></div><div id="c37"></div> </div> <div class="r"> <div id="c40"></div><div id="c41"></div><div id="c42"></div><div id="c43"></div><div id="c44"></div><div id="c45"></div><div id="c46"></div><div id="c47"></div> </div> <div class="r"> <div id="c50"></div><div id="c51"></div><div id="c52"></div><div id="c53"></div><div id="c54"></div><div id="c55"></div><div id="c56"></div><div id="c57"></div> </div> <div class="r"> <div id="c60"></div><div id="c61"></div><div id="c62"></div><div id="c63"></div><div id="c64"></div><div id="c65"></div><div id="c66"></div><div id="c67"></div> </div> <div class="r"> <div id="c70"></div><div id="c71"></div><div id="c72"></div><div id="c73"></div><div id="c74"></div><div id="c75"></div><div id="c76"></div><div id="c77"></div> </div> </div> ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` EE⁸⮌E²↨↧S¹⁶⮌⭆⁸§░▒▓█↨²﹪÷ιX²λ² ``` [Try it online!](https://tio.run/##TY3BCoIwGIBfZXiasMCUUOmkleBBkDyKh6GjBkNlTfMRulbgA/oia5tE/bDv8O/j@@sr5nWHmZQ5p62AGe5h0TMqYNr2g4A2Aq56ZzISfiOwEMq6aClAIBJp25AJWsv8XObXMr@X@WEhEGNlughkXTOwToXEkY60IfBboaqYd3fCtcVsc2OdvZRl6UxJgoAzOY6mf9JcN8HOcGsYGnqaoff7jVYn1jwYJ/T/O1UlNyP7AA "Charcoal – Try It Online") Link is to verbose version of code. Now uses @Arnauld's output characters. Explanation: ``` ⁸ Literal integer `8` E Map over implicit range ² Literal integer `2` E Map over implicit range S Next input hex digit pair ↧ Lowercased ↨ ¹⁶ Converted from base `16` ⮌ Reversed E Map over each pair of hex values ⁸ Literal integer `8` ⭆ Map over implicit range and join ░▒▓█ Literal string § Indexed by ι Current pair ÷ Vectorised divided by ² Literal integer `2` X Raised to power λ Current value ﹪ ² Vectorised modulo `2` ↨² Converted from base `2` ⮌ Reversed Implicitly print ``` Note that the deverbosifier on TIO erroneously uselessly quotes the special characters inside `”y` and `”`; this is not actually necessary for correct operation of the program. 32 bytes by taking the input bytes with `0x` prefix using the newer version of Charcoal on ATO: ``` EE⁸⮌E²N⮌⭆⁸§░▒▓█↨²﹪÷ιX²λ² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcnBRRl5pVo-CYWgLGFjkJQallqUXEqmGuko-CZV1Ba4leam5RapKEJBAgFwSVArelQXY4lnnkpqRUaSo-mTXw0bdKjaZMfTetQ0lFwSgSqBBrjm59SmpOv4ZlX4pJZlpmSqpGpoxCQXw40FCiZAzLWSBMCrJcUJyUXQ923PFpJtyxHKfamv0GFm5uCQYWBAZAwd1WAci1MQYQhiLAEEcZAwtIYJuEIlnUCEs4gWUtzhF6I8QA "Charcoal – Attempt This Online") Link is to verbose version of code. [Answer] # [C (GCC)](https://gcc.gnu.org), ~~110~~ ~~109~~ 93 bytes *-16 bytes thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)* ``` m;main(h){for(;m=m/2?:read(!puts(""),&h,2)*64;)printf("[%dm ",(h&m?39:99)+(h>>8&m?1:8));} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6Fjdjc61zEzPzNDI0q9PyizSsc21z9Y3srYpSE1M0FAtKS4o1lJQ0ddQydIw0tcxMrDULijLzStI0lKSjVVNyFaSjc5V0NDLUcu2NLa0sLTW1NTLs7CyAXEMrC01N61qIJVC7FtzU0S930tY3CXfKjPQPyUgM96mMStHWN66wcPRNcnd0dNGuKI50BGEgsIVoAgA) Takes the input as a binary array from `stdin`, outputs spaces with different ANSI-colored background. If the input is longer than 16 bytes, it continues displaying 8-pixel rows (which is incidentally useful for testing). [Answer] # [Befunge-with-graphics](https://github.com/Jachdich/befunge-with-graphics), 149 bytes Takes raw bytes from stdin and creates a window which displays the result. ``` 99*:sfcu88803v v_v#!:-1\~<+p< $ > ^ >802p>:2%\2/\01p\:2%\2/\01g2*+3\-89+5v $ ^$p20_v#:-1g20-1g30\xg30g20f::**< ^$p30_v#:$ < v-1z<u< > #^_@ ``` Test case: [![Output image](https://i.stack.imgur.com/psx42.png)](https://i.stack.imgur.com/psx42.png) [Answer] # SAS # 136 - ascii art in Log This solution uses the idea from Charcoal language with help of special characters: `" ░▒▓"` of "gradient dots", it is 11 bytes, the firs symbol is a space. The Code: ``` data;input(a b)(:hex2.)@@;do x=1to 8;c=ksubstr(" ░▒▓",1+2*char(put(a,binary8.),x)+char(put(b,binary8.),x),1);put c+(-1)@;end;put;cards;; ``` Input goes between last two semicolons as a string e.g., `FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF` It allows to use multiple strings at once, so if there are any other test cases I gladly add then to display. In human readable form it looks like: ``` data; input (a b) (:hex2.) @@; do x = 1 to 8; c = ksubstr(" ░▒▓" ,1 + 2*char(put(a, binary8.), x) + char(put(b, binary8.), x) ,1); put c +(-1) @; end; put; cards; FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF 7C 7C 00 C6 C6 00 00 FE C6 C6 00 C6 C6 00 00 00 ; ``` In the log you will see: ``` ▒▒▒▒▒▒▒▒ ░▓▓▓▓▓▓░ ▓ ▒ ▓ ▓ ▒ ░▓ ▓ ▒ ░▒▓ ▓ ▒ ░▒░▓ ▓▒ ░▒░░▓ ░▓▓▓▓▓▓░ ▓▓▓▓▓ ░░ ░░ ▒▒ ▒▒ ░░░░░░░ ▓▓ ▓▓ ░░ ░░ ▒▒ ▒▒ ``` # 180 = 113+67 - heatmap Since SAS at its origin stand for Statistical Analysis System let's use "three dimensional" histogram i.e. [HeatMap](https://en.wikipedia.org/wiki/Heat_map) The code * part 1) ``` data;input(a b)(:hex2.)@@;y+(-1);do x=1to 8;c=2*char(put(a,binary8.),x)+char(put(b,binary8.),x);output;end;cards; ``` * part 2) ``` ;proc sgplot;heatmap x=x y=y/colorresponse=c nxbins=8 nybins=8;run; ``` Input goes between past 1) and 2) as a string e.g., `FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF` Human readable form looks like: ``` data; input (a b) (:hex2.) @@; y + (-1); do x = 1 to 8; c = 2*char(put(a, binary8.), x) + char(put(b, binary8.), x); output; end; cards; FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF ; proc sgplot; heatmap x=x y=y / colorresponse=c nxbins=8 nybins=8 ; run; ``` The `sgplot` procedure uses its default setup and the output looks like: [![enter image description here](https://i.stack.imgur.com/pm7GD.png)](https://i.stack.imgur.com/pm7GD.png) Wit some "polishing" ``` proc sgplot noautolegend; heatmap x=x y=y / colorresponse=c nxbins=8 nybins=8 colormodel=(lightgrey black); xaxis display=none; yaxis display=none; run; ``` the output looks like: [![enter image description here](https://i.stack.imgur.com/LzQEC.png)](https://i.stack.imgur.com/LzQEC.png) and [![enter image description here](https://i.stack.imgur.com/jUVwO.png)](https://i.stack.imgur.com/jUVwO.png) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~26~~ 21 bytes ``` bṅvṅ2ẇv∩vvB883f‛P2pp⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCLijIhIIiwiYuG5hXbhuYUy4bqHduKIqXZ2Qjg4M2bigJtQMnBw4oGLIiwiIiwiN0MgN0MgMDAgQzYgQzYgMDAgMDAgRkUgQzYgQzYgMDAgQzYgQzYgMDAgMDAgMDAiXQ==) Uses roughly the same method as my Japt answer. I have tried a lot of different things but I can't find a 20-byter. With Vyncode this is 17 bytes but I'm not the biggest fan of that. Takes input as a list of bytes, outputs a Plain PGM file. Explanation: ``` bṅvṅ2ẇv∩vvB883f‛P2pp⁋­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁡⁤‏⁠‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌­ b # ‎⁡Convert to list of binary digits ṅ # ‎⁢join each to a string vṅ # ‎⁣pad each binary string to length 8 with zeroes 2ẇ # ‎⁤chunks of length 2 v∩ # ‎⁢⁡transpose each pair to a list of two-bit binary strings vvB # ‎⁢⁢convert each from binary 883f # ‎⁢⁣digits of 883 ‛P2 # ‎⁢⁤string literal “P2” p # ‎⁣⁡prepend this to digit list p # ‎⁣⁢prepend this header to the matrix ⁋ # ‎⁣⁣join each item on spaces and then join the items on newlines 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Go](https://go.dev), ~~304~~ 302 bytes ``` import(."image";c"image/color";d"image/draw";p"image/png";."os") func f(s[]byte){N,S,R,D,P:=NewUniform,d.Src,Rect,d.Draw,Point{0,0} T:=NewGray(R(0,0,8,8)) for i:=0;i<8;i++{for l,h,j:=s[2*i],s[2*i+1],0;j<8;j++{D(T,R(j,i,j+1,i+1),N(c.Gray{255-85*(h&128>>6+l&128>>7)}),P,S) h*=2 l*=2}} p.Encode(Stdout,T)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZDPboJAEMbTK09BODS7MtIFQ0UpJm3V3owBezIe6AK6FFiCmGoIT9KLadJbX6h9mi5g0l5-8-_Ll5l5_9jy81fu01d_G8qpz7LPQxn1rZ8rjaU5L0qkKSwVM8WmXXJDecILxQ4uZVD4b4qdX6o82yq2pvC9gqXokFE5Qvv15uVUhrhagAcuTGE5dhbh23PGIl6kEGheQcENaSnSqTCDJWdZWREgtbRqpU-Ff0IuEh2wwMLCmRcyGzvEZneWzVS1ahoJ7CAeO_u10WMbaIOqb4DYsRDFQjRFK3BRDAxiVQcxxLBAVGvcK8M0-5bZQ7tr3bAmk1s16ZIhrjEswcPSrucYUiJQ11KuzTLKgxB5ZcAPJaxw3b3t-9Qe3fwRYbmSItQdX5HjfA4yORLScDhr2HUss6XectRy0HA0-Jved5qHho-tZjT871Nj6bLA-dzFXw) Prints the bytes of a PNG to STDOUT. * -2 bytes by @The Thonnu ### Slightly-Ungolfed Explanation ``` import(."image";c"image/color";d"image/draw";p"image/png";."os") func f(s[]byte){ N,S,R,D,P:=NewUniform,d.Src,Rect,d.Draw,Point{0,0} // various variables T:=NewGray(R(0,0,8,8)) // new 8-bit grayscale, 8x8px for i:=0;i<8;i++{ // for each row... l,h:=s[2*i],s[2*i+1] // get the bytes for that row for j:=0;j<8;j++{ // for each pixel... C:=c.Gray{255-85*(h&128>>6+l&128>>7)} // calculate the color. // yields an inverted color, so `255-x` is needed. D(T,R(j,i,j+1,i+1),N(C),P,S) // draw the pixel to the tile h<<=1;l<<=1}} // shift the bytes left to get the next pixel. p.Encode(Stdout,T)} // print the PNG to STDOUT ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno) `N`, \$ 30 \log\_{256}(96) \approx \$ 24.69 bytes ``` b8zK2ApeZt.JBA_sjE"P2 8 8 3"ZN ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSn1LsciUdBaWoTI-lpSVpuhb7kiyqvI0cC1KjSvS8nBzji7NclQKMFCyA0Fgpyg-iaAGUuumgZO6sowDCBgY6Cs5mEAxig7CbK6oYuryBgRLEIAA) Port of ~~Jacob~~ *noodle man*'s Japt answer. *-3 characters thanks to noodle man* #### Explanation ``` b # Convert each number in the (implicit) input list to binary 8zK # Fill each with zeros to length 8 2Ap # Split the list into pairs e # Map over this list of pairs: Zt # Transpose the pair .J # And join each inner list into a string B # Convert each string from binary A_sj # And join this list of strings by spaces E # (End map) "..."ZN # Prepend the string "P2 8 8 3" # Implicit output, joined on newlines ``` [Answer] # Python, ~~526 524 483 471 470 454~~ 447 bytes I'm a `turtle` veteran. For fast results, use `speed(0)`. Uses the given pallet. ``` def g(l,x=range(8)): r=[int(i,16)for i in l];j=[[r[i+1],r[i]]for i in range(0,16,2)] for i in x:j[i]=["".join([bin(j[i][0])[2:].zfill(8).replace(" ","0")[k],bin(j[i][1])[2:].zfill(8).replace(" ","0")[k]])for k in x] for i in x: for l in x:j[i][l]=int(j[i][l],2);j[i][l]="#"+"FA50"[j[i][l]]*6 for i in j: for k in i:seth(0);color(k);begin_fill();exec('fd(9);rt(90);'*4);end_fill();fd(9) pu();goto(0,ycor()-9);pd();ht() from turtle import* ``` Test case 1: [![enter image description here](https://i.stack.imgur.com/HrsZa.png)](https://i.stack.imgur.com/HrsZa.png) Test case 2: [![enter image description here](https://i.stack.imgur.com/QcMMA.png)](https://i.stack.imgur.com/QcMMA.png) [Answer] ## Clojure, 316 bytes ``` (fn[i](doto(Frame.)(.add(proxy[Panel][](paint[g](dotimes[r 8](dotimes[c 8](.setColor g(((mapv(fn[[l h]](mapv #(Color.({0 0xFFFFFF 1 0xAAAAAA 2 5592405 3 0}(Long/parseLong(str % %2)2)))h l))(partition 2(map #(clojure.pprint/cl-format nil "~8,'0b"%)i)))r)c))(.fillRect g(* c 9)(* r 9)9 9)))))).pack(.setVisible true))) ``` Inputs: 1. `[0xFF, 0x00, 0x7E, 0xFF, 0x85, 0x81, 0x89, 0x83, 0x93, 0x85, 0xA5, 0x8B, 0xC9, 0x97, 0x7E, 0xFF]` 2. `[0x7C, 0x7C, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0x00]` Outputs: [![enter image description here](https://i.stack.imgur.com/SEUlr.png)](https://i.stack.imgur.com/SEUlr.png) [Answer] # Postscript 245 168 Images in Postscript can have 2 bits per pixel, or, more specifically, 2 bits per color component and 1 component (e.g. Grayscale) per sample. However, interpreter expects bytes in data source to constitute a continuous bit stream, not low bits here, high bits there. We'll have to zip bits from each two bytes: ``` currentpagedevice /PageSize get aload pop scale <FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF> % 16 byte string on stack here {not} forall % 16 bytes 8 8 2 [8 0 0 8 0 0] { % consume by pairs (a, b) 0 % accumulator (x) 0 1 7 { % a b x s dup dup % a b x s s s 1 exch bitshift % a b x s s m dup 5 index and % a b x s s m bm 4 1 roll % a b x bm s s m 6 index and % a b x bm s s am exch bitshift % a b x bm s ax 3 1 roll % a b x ax bm s 1 add bitshift % a b x ax bx or or % a b x } for 3 1 roll pop pop % x dup 256 idiv exch 255 and % 2 bytes 2 string dup 0 5 -1 roll put dup 1 4 -1 roll put } image ``` I'll use "16 byte string already on stack" for simplicity as allowed in the OP, though it could have been read from file (e.g. STDIN) or command line. I think it's OK for program size byte count to begin after 1st comment, and then stripped of insignificant whitespace it would be: ``` {not}forall 8 8 2[8 0 0 8 0 0]{0 0 1 7{dup dup 1 exch bitshift dup 5 index and 4 1 roll 6 index and exch bitshift 3 1 roll 1 add bitshift or or}for 3 1 roll pop pop dup 256 idiv exch 255 and 2 string dup 0 5 -1 roll put dup 1 4 -1 roll put}image ``` The very 1st line was not included in count as it just serves to produce more "pleasing" output. Command (`gs` in Linux) ``` gswin64c -q -g200x200 source.ps ``` (again, image size on command line is only for better looking square tile, instead of scaled non-proportionately to A4 (or Letter) default page). [![enter image description here](https://i.stack.imgur.com/0DwnI.png)](https://i.stack.imgur.com/0DwnI.png) For golfing purposes, long repeatedly used operators could be re-defined as short-named procedures, or entire source compactly written as binary tokens, though result would be not very readable. I have better idea: to produce the same output, let's draw not one 2 ppx image, but **three** 1 ppx image masks to paint with 0.33, 0.66 and 1.0 ink, respectively. Then, e.g., if a bit is set in low-bits byte and I paint this pixel with light-gray, it won't interfere with painting later in dark-gray and/or black (if bit is set in high-bits byte). ``` currentpagedevice /PageSize get aload pop scale <FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF> % 16 byte string on stack here {} forall 16 -1 9 { dup index exch 1 sub index and } for 23 -1 16 { -1 roll } for 24 -8 roll 2 -1 0 { 3 div setgray 8 8 true [8 0 0 8 0 0] { 1 string dup 0 4 -1 roll put } imagemask } for ``` I.e.: ``` {}forall 16 -1 9{dup index exch 1 sub index and}for 23 -1 16{-1 roll}for 24 -8 roll 2 -1 0{3 div setgray 8 8 true[8 0 0 8 0 0]{1 string dup 0 4 3 roll put}imagemask}for ``` There is bytes moving around stack instead of bits juggling, which is significantly less cumbersome, and shorter. [Answer] # [Ruby](https://www.ruby-lang.org/), 101 bytes Returns the lines of a PGM file. I'm sure that `each_slice` could be golfed out but I don't feel like it. Could be a byte shorter by removing the splat before `a.map` but I don't like returning a ragged array. ``` ->a{["P2 8 8 3",*a.map{("%08b"%_1).chars}.each_slice(2).map{_1.transpose.map{|x|x.join.to_i 2}*" "}]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3U3XtEqujlQKMFCyA0FhJRytRLzexoFpDSdXAIklJNd5QUy85I7GouFYvNTE5I744JzM5VcNIE6wo3lCvpCgxr7ggvzgVLFBTUVOhl5WfmadXkh-fqWBUq6WkoFQbWwu1LKOgtKRYwS062qDCzU1HwaDCwABEmruCSIiIhSmYNASTlmDSGERaGiNkHSFqnECkM1iNpTmyObGxEPsWLIDQAA) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 22 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ḃ8ṛ2ẇıṬ€JḂ;883`P2ƤƤðȷj ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPU9IJmNvZGU9JUUxJUI4JTgzOCVFMSVCOSU5QjIlRTElQkElODclQzQlQjElRTElQjklQUMlRTIlODIlQUNKJUUxJUI4JTgyJTNCODgzJTYwUDIlQzYlQTQlQzYlQTQlQzMlQjAlQzglQjdqJmZvb3Rlcj0maW5wdXQ9N0MlMjA3QyUyMDAwJTIwQzYlMjBDNiUyMDAwJTIwMDAlMjBGRSUyMEM2JTIwQzYlMjAwMCUyMEM2JTIwQzYlMjAwMCUyMDAwJTIwMDAmZmxhZ3M9Tg==) Port of noodle man's Japt answer. #### Explanation ``` ḃ8ṛ2ẇıṬ€JḂ;883`P2ƤƤðȷj # Implicit input ḃ8ṛ # Convert each to binary and pad with zeros to length 8 2ẇı ; # To each chunk of 2: Ṭ€J # Transpose and join each Ḃ # Then convert back from binary 883 # Push 883 `P2Ƥ # Prepend "P2" Ƥ # And prepend this header ðȷj # Join each inner list on spaces # Implicit output, joined on newlines ``` ]
[Question] [ ## Challenge Calculate the strange sum of two natural numbers (also known as lunar addition): Given \$A=...a\_2 a\_1 a\_0\$ and \$B=... b\_2 b\_1 b\_0\$ two natural numbers written in the decimal base, the **strange sum** is defined, based on the **maximum** operation, as: \$A+B=... \max(a\_2,b\_2) \max(a\_1,b\_1) \max(a\_0,b\_0)\$ ``` ... a2 a1 a0 + ... b2 b1 b0 ---------------------------------------- ... max(a2,b2) max(a1,b1) max(a0,b0) ``` ## Input Two natural numbers All the following is allowed: * Zero-padded strings (same length) * Left-space-padded strings * Right-space-padded strings * Array of two padded strings * 2D space-padded char array ## Output A natural numbers ## Example ``` 1999 + 2018 -> 2999 17210 + 701 -> 17711 32 + 17 -> 37 308 + 250 -> 358 308 + 25 -> 328 ``` ## Rules * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) (choose the most appropriate format for your language/solution). * No need to handle **negative** values or **invalid input** * 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] # [Python 2](https://docs.python.org/2/), 20 bytes ``` lambda*a:map(max,*a) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSvRKjexQCM3sUJHK1Hzf0FRZl6JQppGZl5BaYmGpg6U1vwfbaijYK6jYKSjAGQYxHJFGwApsBCQNIwFAA "Python 2 – Try It Online") I/O as 0-pre-padded lists of digits. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` » ``` [Try it online!](https://tio.run/##y0rNyan8///Q7v///0cb6iiY6ygY6SgAGQax/6MNgBRYCEgaxgIA "Jelly – Try It Online") I/O as 0-pre-padded lists of digits. [Answer] # [R](https://www.r-project.org/), ~~68~~ 65 bytes ``` function(x)apply(outer(x,10^(max(nchar(x)):1-1),`%/%`)%%10,2,max) ``` [Try it online!](https://tio.run/##DclBCoAgEAXQq7QR5sNETquMzhKKJAWlIQZ2emv5eLmFbulbeKIvR4pU4e77fCk9ZctUWfRKl6sU/e5@A7P0ArZqUBZKieaR/0cL5EmMMdyNWiagfQ "R – Try It Online") Input as integers, output as list of digits. If zero-padding lists of digits was allowed, then simply `pmax` would suffice. [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` X> ``` > > Choose the most appropriate format for your language/solution > > > The input format is: 2D char array of two rows, each corresponding to a line, with the shorter number left-padded with spaces. For example ``` 17210 701 ``` which in MATL is defined as ``` ['17210'; ' 701'] ``` [Try it online!](https://tio.run/##y00syfn/P8Lu//9odUNzI0MDdWsFdQUFcwND9VgA "MATL – Try It Online") ### Explanation ``` % Implicit input: 2D char array with two rows X> % Take maximum of (code points of) each column % Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ ~~60~~ 56 bytes ``` lambda a,b:map(max,zip(a.rjust(len(b)),b.rjust(len(a)))) ``` [Try it online!](https://tio.run/##bczPCsIwDAbwu08R8JAWOmkyRjtBn8RLiw4n@1PmBPXla@dlm/jdku@XhNd47TuO1eEUG9f6swOn/L51QbTuqd51EG433B73UTSXTngplV/MTqbEMNTdCJVAKssSQQGyJosStgBZdoQUTs1mdoZJowJAo2npyBii2eWMaZkcpJPVv4kunLb4dciFXru8sH/cBH8c2/gB "Python 2 – Try It Online") Takes input as two strings, and returns a list of digits --- Alternative: Takes input as two integers; same output # [Python 2](https://docs.python.org/2/), ~~60~~ 59 bytes ``` lambda*i:map(max,zip(*['%*d'%(len(`max(i)`),v)for v in i])) ``` [Try it online!](https://tio.run/##ZczRCoIwFMbx@57iQIjbmLAzkc2gXqQCFyYNdA4RqV5@LS9M6dx9f34c/xofvZOhOV5Ca7pbbZg9dMaTzjz523rCzmnC6jQh7d2RKlZiaUX5RJt@gAmsA3ulNPjBuhEagmVZAgcpUFPYA2TZCeLJmHeLURIFB1ACVwaVQlxMLmPic17/@e6fEXo2shAbkxf6z0S0NVKHDw "Python 2 – Try It Online") [Answer] # Java 10, ~~78~~ 57 bytes ``` a->b->{for(int i=a.length;i-->0;)if(a[i]<b[i])a[i]=b[i];} ``` Input as two space-padded character arrays. Modifies the first input-array instead of returning a new one to save 21 bytes (thanks to *@OlivierGrégoire*). [Try it online.](https://tio.run/##bZBBj4IwEIXv/ooJp5JAU9gYJCiJMdnbnjwaD0MFrWIhMLgxxt/OFmiy68ZL8/rea@fLnPGG/vlw6WWJbQtfqPRjBtASkpJwNinvSJW86LQkVWn@acVSnrDZ7b13nU2l2@6aN7aTplDACnr008xPH0XVMKUJ1Ap5mesjnRLl@6lIXFUw3Kn9MjOHO6jVoJJnn8wMU91lpWGyaLdKHeBqcNmWGqWPuz2gO6ADUN4Sc4I4jh0PnFAEC8dN/iZRGIghAohE8Jp9hEMQRP9csRi/mou3PoTzyX/Ofnc3Ao61CRDQA6sgs6TTfmBttoOcqo25rpsG78xOKTjWdXlna5ejlHlNLHut2d723lJ@5VVHvDYTqNRM5992nHlt4Z79Dw) **Explanation:** ``` a->b->{ // Method with two char-array parameters and String return-type for(int i=a.length;i-->0;) // Loop `i` in the range (length, 0]: if(a[i]<b[i]) // If the `i`'th character in input `a` is smaller than in input `b`: a[i]=b[i];} // Change the `i`'th character in `a` to the `i`'th character of `b` ``` [Answer] # [J](http://jsoftware.com/), 14 12 bytes -2 bytes thanks to Jonah ``` (>./@,:)&.|. ``` [Try it online!](https://tio.run/##ZYy9CoNAEIT7e4ohhT@gmz1F1APFdwlZQpoUtsmzX0ZPK5lmdr6PfUdbJ4EiQGMxy32pQpnJV2LpboLcJslR4Rdgq3PPx@uDBuOeOsAf1TgqryEZHj3jmd3pST25sdFKTsuDtCWzzTnXDkPalWX720FP1lxY/AM "J – Try It Online") Input and output as list(s) of digits [Answer] # Japt, ~~9~~ ~~8~~ 7 bytes Takes input as an array of digit arrays. ``` mÔÕÔËrw ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=bdTV1Mtydw==&input=WwpbMSw3LDIsMSwwXQpbNywwLDFdCl0KLVE=) ``` m :Map Ô : Reverse Õ :Transpose Ô :Reverse Ë :Map r : Reduce by w : Maximum ``` --- If taking zero-padded arrays as input is permitted (it would currently fall under a "convenient format" but I suspect that's not the challenger's intent) then this can be 3 bytes. ``` íwV ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=7XdW&input=WzEsNywyLDEsMF0KWzAsMCw3LDAsMV0KLVE=) ``` í :Interleave the first input V :With the second w :Reduce each pair by maximum ``` [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` a#b=zipWith max(p b++a)$p a++b p=(' '<$) ``` Input/output as strings, [try it online!](https://tio.run/##LY5BC4IwAIXv@xWPElSWsSmhguvStU4dOkTERkMlnUMXRfTfLavD4/E9vsOr5HDVTTOOcq7Es7aH2lVo5SOwUJTK0LOQlCpiReDDL7xwbGVtID6O3Z1RdliiqY0eIIoCpXabzjht3IB7pXtNMCmNwQtHuVAnFBHuXX8Zpk3A3tze9VsDDxKUYoZvKNSPovUPg8@7cOR5niNmPCM8jTlDyjhJYvCUJCxDvGL/fgM "Haskell – Try It Online") ### Explanation The function `p` replaces each character by a space, using `p b++a` and `p a++b` are thus the same length. This way we can use `zipWith` without losing any elements, using `max` with it works because a (space) has lower codepoint than any of the characters `['0'..'9']`. [Answer] # [Perl 6](http://perl6.org/), 37 bytes ``` {[R~] roundrobin($_».reverse)».max} ``` [Try it online!](https://tio.run/##RcpBCsIwFEXRrTyKiKKUn4imAdtFOC1FWk1AMI2kKJYQN@bMjcXYibNz4d6Uu@6iGTHXKKOvD68Gzt77s7PdpV/Mjp937tRDuUEtE037DHFoR2Q@r6kJWCGBJZTwGtN@sqYLGbR12DMpJTixolqnEJwRBLFfbDiYmEAF@Jb@rOIX "Perl 6 – Try It Online") Takes input as a list of lists of digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9 6~~ 5 bytes -3 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) -1 thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` íζ€àR ``` Takes input as a list of lists of digits ``` í # Reverse both inputs ζ # Zip €à # Keep the bigger digits R # Reverse ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Npz2x41rTm8IOj//@hoQx1LEIzViTbSMdAx1LGIjQUA "05AB1E – Try It Online") or [Try all test cases](https://tio.run/##yy9OTMpM/W/q9v/w2nPbHjWtObwg6L/O/@hoQx1LEIzViTbSMdAx1LGIjeUCiZrrGAF5BkBxc5A4WNRYxwjIB8pBeQZA1SB9pkB1aCKxsQA "05AB1E – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes ``` {[~] [Zmax] $_} ``` [Try it online!](https://tio.run/##RcrRCoIwAIXhVzkMyw1jbIuag9yDJCJWDoqWYV0koq@@Zjfdff/hPNv@vg9@wNqhCGM5VyiPvvlUSOopvJoB/NZdHzRFhpTNBAXI7GhSW8udf1OyGjMe//zc@dN0ISzuCxlc1@MgjTFQQuZ2E0MrKaCFXGKrIPUPIofaiT9t@AI "Perl 6 – Try It Online") Takes input as a list of space padded arrays of characters, though for this challenge the lax input format makes it rather boring. Alternatively, here's the program that takes a list of two integers instead: # [Perl 6](https://github.com/nxadm/rakudo-pkg), 41 bytes ``` {+[~] [Zmax] $_>>.fmt("%{.max}d")>>.comb} ``` [Try it online!](https://tio.run/##RYxLCsIwGAav8hHUtlTCn4imAZuDWIrUR0AxRqoLS2muHqMbdzOzmMe5v22iG7CwqONYNqFFs3Pdu8Vsbwy37pWz@chTmU6sSOXo3WGKz24Av/rLPc9QIisCQw0WeNpY32MrtNaQJCqzTKKkICgSX1lJCPUDqiDX9EcTPw "Perl 6 – Try It Online") If you don't mind a huge amount of whitespace, you can also remove the `+` from the front. ### Explanation: ``` { } # Anonymous code block $_>> # Map each integer to .fmt("%{.max}d") # The number padded by the max of the list spaces >>.comb # And split each to list of characters [Zmax] # Get the max of each digit at each index # This works because space is coerced to 0 # Otherwise we would have to add a 0 to the formatting string [~] # Join the list of digits and spaces + # And coerce the string to a number to get rid of leading whitespace ``` [Answer] # JavaScript (ES6), ~~51~~ 49 bytes *NB: This answer was posted before the loose I/O formats were explicitly allowed. With zero-padded arrays of digits, this can be done in [33 bytes](https://tio.run/##dc7BDoMgDAbg@56CIySdAsYgS2APQjyg08VFwcxlr8/owcNm1h566df@D//2W/@c1tc5xNuQRpO8sZ2xvlj8SmmAiRkbbOem9houOFjqY9jiPBRzvNOROgEau2XUSeAgoGkZI1hlSYjUWp8OQoHMixwNz0ahQ5WFUEqIX1GBxN0M99t74Q9CKnUUHINgphofsW9R1c1fwXO4@ihkkz4), (but is much less interesting, IMHO).* Takes input as two integers. Returns an integer. ``` f=(a,b,t=10)=>a|b&&(a%t<b%t?b:a)%t+t*f(a/t,b/t)|0 ``` [Try it online!](https://tio.run/##bc1BDoIwEAXQvaeYDaTVajslpMWInqVFMBpCjUxccfdaYEec5f8vf17u68bm83zTcQj3NsauZk54QTUqXl/d5POcuYwuPqObPzue0YH2HXOShJfEJxWbMIyhb099eLCOYVVVArRCyzlICaBTsNsYo1EJMApXg8YgbkyhRcpTP9@8A1CYrVE2vSrVohZTlPa/WYdWo238AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: a, // a = first integer b, // b = second integer t = 10 // t = 10 (which is used 6 times below) ) => // a | b // bitwise OR between a and b to test whether at least one of // them still has an integer part && // if not, stop recursion; otherwise: ( // a % t < b % t ? b : a // if a % 10 is less than b % 10: use b; otherwise: use a ) % t + // isolate the last decimal digit of the selected number t * // add 10 times the result of f(a / t, b / t) // a recursive call with a / 10 and b / 10 | 0 // bitwise OR with 0 to isolate the integer part ``` ### Alternate version Same I/O format. ``` f=(a,b)=>a|b&&[f(a/10,b/10)]+(a%10<b%10?b:a)%10|0 ``` [Try it online!](https://tio.run/##bc3BDoIwDAbgu0/Ri2SLU9YRsmFEH8R46BCIhjAjxhPvPgvciD20Sfvl75O@NFTvx@uz78O9jrEpBSkvyzONPkmujaAUtfLc5G0naIv65Lld/JEkz1HHKvRD6OpDF1rRCCyKQoHR6KSENAUwvNisjDWcCVbjYtBaxJXJjOI936eacgAyuzba8atcz2o2We7@myVoMcbFHw "JavaScript (Node.js) – Try It Online") [Answer] # Python 3, 53 bytes ``` s=lambda p,q:p+q and 10*s(p//10,q//10)+max(p%10,q%10) ``` [Answer] # [Tcl](http://tcl.tk/), 156 bytes ``` proc S a\ b {join [lmap x [split [format %0[set l [expr max([string le $a],[string le $b])]]d $a] ""] y [split [format %0$l\d $b] ""] {expr max($x,$y)}] ""} ``` [Try it online!](https://tio.run/##ZY7NCoMwEITveYqhpFDBQ6IU9Tk8xhziT4slatAUIuKzW2NLKXRP384uM2MrvW1mHCrkUAVKLI@h7SF0pwwcxGR0ayFuw9gpizMTU2OhIRpnRnTKXcRkx7a/QzegSoa/aykDKWsv43SSmP/dqC5q/3fcl68ndSGdg9XL63Y0eVcjPMsyRIynhCcRZ0gYJ3EEPzwhMUt3iK7sQzuSFYt52gki33v4qHV7AQ "Tcl – Try It Online") Not very golfy, but I had to give a try on it. Will golf it later! [Answer] ## Batch, 120 bytes ``` @set/aw=1,x=%1,y=%2,z=0 @for /l %%i in (0,1,9)do @set/a"z+=w*((v=y%%10)+(v-=x%%10)*(v>>4)),y/=10,x/=10,w*=10 @echo %z% ``` Takes input as command-line parameters. 188-byte version works on arbitrary length integers: ``` @set/px= @set/py= @set z= :l @if %x:~-1% gtr %y:~-1% (set z=%x:~-1%%z%)else set z=%y:~-1%%z% @set x=%x:~,-1% @set y=%y:~,-1% @if "%x%" neq "" if "%y%" neq "" goto l @echo %x%%y%%z% ``` Takes input on STDIN. [Answer] # [Twig](https://twig.symfony.com/), 125 bytes When I saw this challenge, I though: "let me use a template language! sure is a good fit" I was wrong ... so wrong .... ... But was fun! ``` {%macro a(a,b,s='')%}{%for k,x in a|reverse|split('')%}{%set s=max(x,(b|reverse|split('')[k]))~s%}{%endfor%}{{s}}{%endmacro%} ``` This requires that "strict\_variables" is set to `false` (default value). To use this macro, you can do like this: ``` {% import 'file.twig' as my_macro %} {{ my_macro.a(195,67) }} ``` Should display 167. You can try this in <https://twigfiddle.com/rg0biy> ("strict\_variables" set to off, it is on by default on the website) [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ↔¤żY↔ ``` Conveniently takes input/output as list of digits, [try it online](https://tio.run/##yygtzv7//1HblENLju6JBNL///@PNtQx1zHSMdQxiP0fba5joGMYCwA "Husk – Try It Online") or [verify all!](https://tio.run/##yygtzv6fq3Foeb52graSgq6dgpKGl5KCtoJSuaZGccqh5YeWPGpqzE8petQ24VHbpHJNzUPb/j9qm3JoydE9kUD6////hpaWlgpGBoYWXIbmRoYGCuYGhlzGRgqG5lzGBhYKRqYGUBoA "Husk – Try It Online") ## Explanation ``` ↔¤żY↔ -- example inputs [1,4] [3,2] ¤ ↔ -- reverse the arguments of: [4,1] [2,3] żY -- | zipWith (keeping elements of longer) max: [4,3] ↔ -- reverse: [3,4] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` |>E:o ``` [Run and debug it](https://staxlang.xyz/#c=%7C%3EE%3Ao&i=[%221999%22+%222018%22]%0A[%2217210%22+%22701%22]%0A[%2232%22+%2217%22]%0A[%22308%22+%22250%22]%0A[%22308%22+%2225%22]&a=1&m=2) This program takes input as an array of strings. ``` |> Right align inputs (filling with \0) E "Explode" array onto stack separately :o "Overlay" Keep the maximum element respective element from two arrays. ``` [Run this one](https://staxlang.xyz/#c=%7C%3EE%3Ao&i=[%221999%22+%222018%22]%0A[%2217210%22+%22701%22]%0A[%2232%22+%2217%22]%0A[%22308%22+%22250%22]%0A[%22308%22+%2225%22]&a=1&m=2) This is the first time I've seen a use for the overlay instruction "in the wild". [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 153 bytes ``` X =INPUT Y =INPUT Y =DUPL(0,SIZE(X) - SIZE(Y)) Y S X LEN(1) . A REM . X :F(O) Y LEN(1) . B REM . Y O =O GT(A,B) A :S(S) O =O B :(S) O OUTPUT =O END ``` [Try it online!](https://tio.run/##TY3NCsIwEITPm6fY4y7UUv9AAj0kNEqhJsWkkHj0LPbg@xNTKeJpZr5hmPdrfszPQ84Qse3tOAUB6d910zhQU/n@bigybvDrEjMm4ctoMJa2jDUqvJlr0QjyTI6X8a/Ta5cEOGwdXgKpSjMqkJ48r1SDXIIDN4VyX5Awtst535zE7vgB "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # Pyth, 5 bytes ``` meSdC ``` Takes input as array of two space-padded strings. ``` meSd map greatest C on the transpose of input ``` Try it [here](http://pyth.herokuapp.com/?code=meSdC&input=%5B%271999%27%2C%272018%27%5D&test_suite=1&test_suite_input=%5B%271999%27%2C%272018%27%5D%0A%5B%2717210%27%2C%27++701%27%5D%0A%5B%2732%27%2C%2717%27%5D%0A%5B%27308%27%2C%27250%27%5D%0A%5B%27308%27%2C%27+25%27%5D&debug=0). [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes Input is taken as a an array of two 0-padded number arrays. ``` y_rw ``` [Try it online!](https://tio.run/##y0osKPn/vzK@qPz//2iuaEMdcx0jHUMdg1gdrmgDHQMg10DHMJYrlotLNwAA "Japt – Try It Online") [Answer] # Ceylon, 55 / 99 With 0- or space-padded strings of same length (returning an iterable of characters): ``` function t(String a,String b)=>zipPairs(a,b).map(max); ``` With 0- or space-padded strings (returning a String): ``` String t(String a,String b)=>String(zipPairs(a,b).map(max)); ``` With strings of possibly different length (returning a String): ``` String u(String a,String b)=>String(zipPairs(a.padLeading(b.size),b.padLeading(a.size)).map(max)); ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/learn/dotnet/what-is-dotnet), 57 bytes ``` a=>b=>a.Select((x,i)=>a[i]>b[i]?x:b[i]) ``` *-1 bytes by adding currying* [Try It Online](https://tio.run/##jY5PSwMxEMXv@RQhpwTWkO2lrtuNh6KiKIg9eBAP2XTUQJpgkpWK9LOviV3EPwjOYYbHG37v6XigfYBxiMY94tVrTLBp0VfFl95a0Ml4F/92@Bk4CEb/@Lg07rlF2qoY8TV@QzhPTCoZjV@8WeMrZRxlk1HmdHB6EVPIjOqbOD9xwwaC6i0s9JMKUkr8kH3c4VF1su@k4isodSjdVoZlfWfuZZ/X8faoHDa26DNnmTt7C/w2mAS5JdB9Dr/wuREhVWFTUjdNQxglM1EfEsZY@38AngjzWS0KQoi5qPeMX5AbUOsPxhSwQ7vxHQ) [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->a,b{a.zip(b).map &:max} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k6Ua8qs0AjSVMvN7FAQc0qN7Gi9j9Q3Dba0NzI0EBHwdzAMBYkV12TUqOhpGpgmqKkmqKpl5yRWFQMEtdQsyrJj8/UrOUqUADq00mLBpKxeln5mXl6IIn/AA "Ruby – Try It Online") Pre-padded list blah blah. (Although it feels a little like cheating.) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes ``` +`^(.*)(.)¶(.*)(.) $1¶$3¶$2$4 %O`. ¶.? ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg8187IU5DT0tTQ0/z0DYog0vF8NA2FWMgNlIx4VL1T9DjOrRNz57r/39DS0tLHSMDQwsuQ3MjQwMdBQVzA0MuYyMdQ3MuYwMLHSNTAzCtYGQKAA "Retina 0.8.2 – Try It Online") Link includes test suite. Previous 45-byte [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1 version accepts unpadded strings: ``` P^`.+ +`^(.*)(.)¶(.*)(.) $1¶$3¶$2$4 %O`. ¶.? ``` [Try it online!](https://tio.run/##LcYxCoAwDEDRPeeoUDWEJFVqJ4@g4C51cHBxEM/WA/Ri1aHD5/3nfK/7kNLYLWJZ90g99HG31LWW2pzqgJGcjPtTM0CzRIKcaIZSJISAyjKBeBVGzwJOUTw4nlBHrn4 "Retina – Try It Online") Link includes test suite. Explanation: ``` P^`.+ ``` Pad both values to the same length. (Retina 1 only. There are ways of emulating this in Retina 0.8.2 but they are not very golfy.) ``` +`^(.*)(.)¶(.*)(.) $1¶$3¶$2$4 ``` Transpose the values. ``` %O`. ``` Sort each pair into order. ``` ¶.? ``` Delete all the low digits and surplus newlines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` ⭆θ⌈⟦ι§ηκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKPgmVmTmluZqRGfqKDiWeOalpFZoZOgoZGvGampqWv//b2huZGjApaBgbmD4X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input ⭆ Map over characters and join ⌈ Maximum of ⟦ List of ι Current character of first input and η Second input § Indexed by κ Current index Implicitly print ``` 10-byte version "adds" any number of padded strings: ``` ⭆§θ⁰⌈Eθ§λκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaDiWeOalpFZoFOooGGjqKPgmVmTmluZqgKSAQjDZHB2FbE0QsP7/PzqaS8nQ3MjQQEmHS0lBwdzAEMIwNrCAMBSMTJW4YmP/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Previous 14-byte version accepts unpadded strings: ``` ⭆◧θLη⌈⟦ι§◧ηLθκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQkpvikppVoFOoo@KTmpZdkaGRoauoo@CZWZOaW5mpEZ@ooOJZ45qWkVsCVZsCVFoKUZsdqampa//9vaG5kaMBlbmD4X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input ◧ Padded to L Length of η Second input ⭆ Map over characters and join ⌈ Maximum of ⟦ List of ι Current character of first input and η Second input ◧ Padded to L Length of θ First input § Indexed by κ Current index Implicitly print ``` 17-byte version "adds" any number of strings: ``` ≔⌈EθLιη⭆η⌈Eθ§◧ληκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7EiM7c0F0gXaBTqKPik5qWXZGhkampq6ihkaFpzBRRl5pVoBJcAqXSQmgwdBTQtjiWeeSmpFRoBiSk@qWklGjkgjToK2ZogYP3/f3Q0l5KhuZGhgZIOl5K5gSGIMjawAFFGpkpcsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Wren](https://github.com/munificent/wren), 74 bytes ``` Fn.new{|i|(0...i.count/2).map{|j|i[j]>i[j+i.count/2]?i[j]:i[j+i.count/2]}} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xgq/DfLU8vL7W8uiazRsNAT08vUy85vzSvRN9IUy83saC6JqsmMzor1g5IaMOlYu1BYlaoYrW1/4Mri0tSc/UKijLzShxzcjRAVuglJwJZ0YY6CuY6CkY6CkCGgQ6XAm5gAFIAUgwkDWM1Nf8DAA "Wren – Try It Online") Input is a single list of the two operands, e.g. ``` [1, 7, 2, 1, 0, 0, 0, 7, 0, 1] ``` ## Explanation Now I need to figure out a formula for maximum. ``` Fn.new{|i| } // New anonymous function with the operand i (0...i.count/2) // Define an exclusive range from 0 to half the input .map{|j| } // Turn every item of the list into ... i[j]>i[j+i.count/2]?i[j]:i[j+i.count/2] // ... The maximum between i[j] and i[j+i.count/2] // (which is simply the other list's index at the same position) ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=max -F`, 22 bytes ``` say map{max $_,getc}@F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7GgOjexQkElXic9tSS51sHt/38DQwMjLiMDQ@N/@QUlmfl5xf91fU31gKJA2iezuMTKKrQkM8cWqO2/rhsA "Perl 5 – Try It Online") Input must be 0 or space padded so that the entries are the same length. [Answer] # APL(NARS), 51 chars, 102 bytes ``` {k←⌈/≢¨(a b)←⍎¨∘⍕¨⍺⍵⋄f←{((k-≢⍵)⍴0),⍵}⋄10⊥(f a)⌈f b} ``` test: ``` h←{k←⌈/≢¨(a b)←⍎¨∘⍕¨⍺⍵⋄f←{((k-≢⍵)⍴0),⍵}⋄10⊥(f a)⌈f b} 1999 h 2018 2999 17210 h 701 17711 32 h 17 37 308 h 250 358 308 h 25 328 ``` ]
[Question] [ If a compiled language is used, the program must delete the compiled executable (but need not delete the source file). If an interpreted language is used, the program must delete the source file. My opening bid: ## Python (29 characters) ``` import os;os.remove(__file__) ``` Edit: to prevent solutions like [rm -rf /](https://codegolf.stackexchange.com/a/11797/14091), the program must not delete anything except the executable or source file. ``` html,body{margin:0;padding:0;height:100%;overflow:hidden} ``` ``` <iframe src="https://xmikee1.github.io/ppcg-leaderboard/?id=19355" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe> ``` [Answer] ## Bash script (7 characters, 7 bytes) ``` rm "$0" ``` [Answer] # Unix? (9): ``` #!/bin/rm ``` A classic. Uses `rm` as interpreter, for instant self-deletion. Not the very shortest though. [Answer] ## Batch - 6 bytes ``` Del %0 ``` Pretty simple. Note: Works even if the name contains spaces. [Answer] # Ruby, 14 characters ``` File.delete $0 ``` `$0` is a special global variable that contains the name of the currently running script. [Answer] # BASIC-80 / BASICA / GW-BASIC / IBM BASIC / Commodore 64 BASIC / Vintage BASIC / Commodore LCD BASIC / Atari BASIC \* # 5 bytes ``` 1 NEW ``` Well, that's about as simple as it gets. `NEW` creates a new program, so putting this anywhere in your program will delete it. Proof of concept on IBM BASIC (putting `NEW` on line 40 for clarity): [![](https://i.stack.imgur.com/uyjCu.png)](https://i.stack.imgur.com/uyjCu.png) \* Yeah, I listed every old BASIC version I've tested this in (or pretty much ever used) [Answer] # PHP, 17 characters ``` unlink(__FILE__); ``` [Answer] **PowerShell (32)** ``` del $MyInvocation.MyCommand.Name ``` [Answer] **Perl 5 (8 characters)** ``` unlink$0 ``` `$0` is the script name, and `unlink` removes it. Normally, you'd at least add a space in between for readability. [Answer] **C# (112)** ``` Process.Start("cmd.exe","/C choice /C Y /N /D Y /T 3 & Del " + Application.ExecutablePath); Application.Exit(); ``` Shamelessly stolen from <http://www.codeproject.com/Articles/31454/How-To-Make-Your-Application-Delete-Itself-Immedia> [Answer] ### R, 26 characters ``` unlink(sys.frame(1)$ofile) ``` [Answer] # k (8) ``` ~-1!.z.f ``` Or the q equivalent for 14: ``` hdel hsym .z.f ``` [Answer] # Python, 18 ``` open(__file__,'w') ``` Opens itsself in write-only mode, erasing itself. [Answer] # Node.js - 22 chars ``` fs.unlink(__filename); ``` [Answer] # Julia, 13 bytes ``` rm(@__FILE__) ``` Simple. But longer. :P [Answer] # Vitsy + bash, 8 bytes ``` iG' mr', iG Get the name of the use declaration at the top item (-1) (returns the current one) ' mr' Concatenate "rm " to the front of it. , Execute via shell. ``` [Answer] # Mathematica, 29 bytes ``` DeleteFile@NotebookFileName[] ``` [Answer] # Lua, 17 bytes ``` os.remove(arg[0]) ``` This actually only works if you run the program by typing out the full filepath, i.e. `lua ~/Scripts/removeself.lua` would work, but `lua removeself.lua` would not, assuming a filename of `removeself.lua` and a current working directory of `~/Scripts`. As far as I know, there's no way to find the actual filepath of a script, just the arguments passed to it. I do know about `debug.getinfo(1).source`, but in my testing that game exactly the same results as `arg[0]`. If anyone knows of a way to find the filepath, please let me know. [Answer] # JS, 37 bytes ``` document.documentElement.innerHTML="" ``` Does this count? It kills javascript on the page [Answer] # tcl, 18 ``` file delete $argv0 ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMY2M1TWNWWWQycGM) — **ATTENTION:** It is only a one time demo! Only the first time it will be runnable. Please reserve it to the question's original poster. To try: press the `Execute` button. The green area will not report any error. After that, any subsequent clicks on the `Execute` button will result on a `not found` error! [Answer] # [shortC](//github.com/aaronryank/shortC), 10 bytes ``` Aremove(*@ ``` How it works: ``` A main function remove( delete file specified in next string *@ program name ``` Equivalent C program: ``` int main(int argc, char **argv){remove(*argv);} ``` [Answer] ## C, 32 bytes ``` main(c,v)char**v;{remove(v[0]);} ``` [Answer] # JavaScript (ES6), 13 bytes ``` f=_=>delete f ``` --- ## Try It Logs the source of `f`, calls `f` (which deletes `f`), tries to log `f` again but throws an error because `f` is now undefined. ``` f=_=>delete f console.log(f) f() console.log(f) ``` [Answer] # 8086/8088 machine code, 1 byte ``` aa stosb ``` Assumptions: * The registers CS, IP, ES, DI, and AL are all initially 0. * This code is placed at address 0. The `stosb` instruction stores the byte in the AL register at the memory location pointed to by ES and DI, then increments or decrements DI. In this case, it stores the byte 0 at the memory address 0, which happens to be where the instruction itself is. Granted, this program doesn't delete a file or anything. But if you manage to get your hands on an 8086 processor, poke this program into memory, and run it, it will in fact overwrite itself. [Answer] # VBA, ~~69~~ 62 Bytes Subroutine that takes no input and deletes itself. Requires that the code below be the first line in the active code pane, and that VBA has trusted access to the VBE Project model. ``` Sub A:Parent.VBE.CodePanes(1).CodeModule.DeleteLines 1:End Sub ``` -2 bytes for replacing `ActiveCodePane` with with `CodePane(1)` -5 bytes for replacing `Application` with `Parent` [Answer] ## PowerShell v3 - 17 ``` ri $PSCommandPath ``` [Answer] # Julia - 25 bytes Write this into a file, and then include the file with `include("<filename here>")` and run `f()`: ``` f()=rm(functionloc(f)[1]) ``` This is, obviously, a function - I'm not sure how one would go about detecting the file name of a file being run directly (as an include statement without a function definition in it). [Answer] ## C++, 137 bytes. Works most of the time on windows ``` #include <stdlib.h> #include <string> int main(int, char*v[]){char c[99];sprintf(c,"start cmd /C del \"%s\"/Q", *v);return system(c);} ``` ## C, 90 bytes ``` void main(int n,char**v){char c[99];sprintf(c,"start cmd /C del \"%s\"/Q", *v);system(c);} ``` [Answer] ## MATLAB, 36 bytes ``` delete([mfilename('fullpath'),'.m']) ``` Save the above code as an m-file following Matlab's filename guidelines. [Answer] # Nodejs, 32 bytes ``` require("fs").unlink(__filename) ``` [Answer] # T-SQL, 28 bytes ``` CREATE PROC d AS DROP PROC d ``` It just drops/removes the procedure and the code when executing itself. Usage: ``` EXECUTE d ``` ]
[Question] [ Two-dimensional programming languages often have mirror commands like `/` and `\` to redirect the instruction pointer on the grid: ``` >>>>\ v v <<<</ ``` In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction. ## Rules The incoming direction will be given as one of the characters `NESW` and the mirror will be given as either `/` or `\`. You may receive these in any order. You must use uppercase letters. You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters `NWSE\/`. Output should be a character from `NESW` or single-character string. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them: ``` N / --> W N \ --> E E / --> S E \ --> N S / --> E S \ --> W W / --> N W \ --> S ``` [Answer] # Python, ~~40~~ 38 bytes -2 bytes thanks to @MitchSchwartz `(ord(d)+ord(m))%8` -> `ord(d)+ord(m)&7` ``` lambda d,m:' NESSWNW'[ord(d)+ord(m)&7] ``` plain lookup of answer in a list (AKA string) indexed by the smallest mod of the sum of ordinals that works. Test cases are on [**ideone**](http://ideone.com/mPGH1A) [Answer] # Python 2, 40 bytes ``` lambda c,m,k="NWES":k[k.find(c)^(m>k)+1] ``` Sp3000 saved one byte (`.index` → `.find`). ## Explanation We want to map the directions like so: ``` \ N ⇄⇄⇄⇄⇄⇄⇄ E ⇅ ⇅ ⇅ ⇅ / ⇅ ⇅ / ⇅ ⇅ ⇅ ⇅ W ⇄⇄⇄⇄⇄⇄⇄ S \ ``` We can assign the directions 2-bit codes, and view both flips as XOR-ing the first and second bits: ``` xor 2 0 0 ⇄⇄⇄⇄⇄ 1 0 ⇅ ⇅ ⇅ ⇅ xor 1 ⇅ ⇅ xor 1 ⇅ ⇅ ⇅ ⇅ 0 1 ⇄⇄⇄⇄⇄ 1 1 xor 2 ``` The mapping between bit strings and directions happens using the string `k`. Now we just need to map mirror characters `'/'` and `'\\'` to the values `1` and `2`. Since `'/' < '\\'`, we could naïvely use `(m>'/')+1` as a formula. But wait! Lexicographically, ``` '/' < 'NWES' < '\\' ``` and we have `'NWES'` nicely assigned to `k`! So we can use `(m>k)+1` instead. [Answer] # CJam, 14 bytes (@MartinEnder ported my [Python answer](https://codegolf.stackexchange.com/a/92023/53748)) ``` l1b" NESSWNW"= ``` How? ``` l1b" NESSWNW"= - l - read input 1b - cast characters as base 1 digits " NESSWNW" - the string " NESSWNW" = - modulo index into the string ``` Tests are on [**aditsu**](http://cjam.aditsu.net/#code=%7B%0A%0Al1b%22%20NESSWNW%22%3D%0A%0AoNo%7D8%2A&input=N%5C%0AN%2F%0AE%5C%0AE%2F%0AS%5C%0AS%2F%0AW%5C%0AW%2F) [Answer] ## Javascript (ES6), ~~50~~ ~~41~~ ~~40~~ 37 bytes ``` d=>m=>(S="NWES")[S.search(d)^-~(m>S)] ``` *Saved 3 more bytes by using comparison, thanks to Lynn's answer* ### Usage ``` let f = d=>m=>(S="NWES")[S.search(d)^-~(m>S)] console.log(f("N")("/")); // --> W console.log(f("N")("\\")); // --> E console.log(f("E")("/")); // --> S console.log(f("E")("\\")); // --> N console.log(f("S")("/")); // --> E console.log(f("S")("\\")); // --> W console.log(f("W")("/")); // --> N console.log(f("W")("\\")); // --> S ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~19~~ 17 bytes ``` 'NWSE'jy&mjy+Eq-) ``` [Try it online!](http://matl.tryitonline.net/#code=J05XU0UnankmbWp5K0VxLSk&input=Vwov) Or [verify the eight cases](http://matl.tryitonline.net/#code=ODoiCidOV1NFJ2p5Jm1qeStFcS0p&input=TgovCk4KXApFCi8KRQpcClMKLwpTClwKVwovClcKXA). ### Explanation ``` 'NWSE' % Push this string j % Take first input, say 'W'. Stack contains: 'NWSE', 'W' y % Duplicate from below. Stack: 'NWSE', 'W', 'NWSE' &m % Index of membership. Stack: 'NWSE', 2 j % Take second input, say '/'. Stack: 'NWSE', 2, '/' y % Duplicate from below. Stack: 'NWSE', 2, '/', 2 + % Add (char '/' is converted to code point). Stack: 'NWSE', 2, 49 Eq % Multiply by 2, subtract 1. Stack: 'NWSE', 2, 97 - % Subtract. Stack: 'NWSE', -95 ) % Apply -95 as (modular, 1-based) index into 'NWSE'. Stack: 'N' % Implicitly display ``` [Answer] # Pyth, ~~17~~ ~~16~~ 15 bytes *Thanks to @Jakube and @Maltysen for -1 byte each* ``` @J"NWES"xxJQh>E ``` A program that takes input of two newline-separated quoted strings, first the direction and then the mirror, and prints the result. This is a port of @Lynn's Python [answer](https://codegolf.stackexchange.com/a/92014/55526). [Try it online](https://pyth.herokuapp.com/?code=%40J%22NWES%22xxJQh%3EE&input=%22E%22%0A%22%5C%5C%22&test_suite=1&test_suite_input=%22N%22%0A%22%2F%22%0A%22N%22%0A%22%5C%5C%22%0A%22E%22%0A%22%2F%22%0A%22E%22%0A%22%5C%5C%22%0A%22S%22%0A%22%2F%22%0A%22S%22%0A%22%5C%5C%22%0A%22W%22%0A%22%2F%22%0A%22W%22%0A%22%5C%5C%22&debug=0&input_size=2) **How it works** ``` @J"NWES"xxJQh>E Program. Inputs: Q, E J"NWES" J="NWES". Yield J xJQ J.index(Q) >E E>Q, lexographically (implicit input fill) h +1 x Bitwise XOR of the above two @ Index into J with the above Implicitly print ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 14 bytes ``` ‘€Ã‘DIkI'/kÌ^è ‘€Ã‘ # from string "NEWS" è # get element at index DIk # index of 1st input in string "NEWS" ^ # XOR I'/k # index of 2nd input in string "/" Ì # +2 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCY4oKsw4PigJhESWtJJy9rw4xew6g&input=Tgov) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14 13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (a port of my [Python answer](https://codegolf.stackexchange.com/a/92023/53748)) -1 byte thanks to @MartinEnder (add a space to end of the string and remove need for modulo 8) -1 byte thanks to @LuisMendo (take a single string argument rather than two) ``` OSị“NESSWNW ``` How? ``` OSị“NESSWNW - takes a single argument "dm" (direction and mirror), in either order. strings and lists are equivalent in Jelly O - ordinal: [ord(d),ord(m)] S - sum: ord(d)+ord(m) “NESSWNW - string: "NESSWNW " ị - fetch modulo index (the string is 8 long and 1-based) ``` Test it on [**TryItOnline**](http://jelly.tryitonline.net/#code=T1Phu4vigJxORVNTV05XIA&input=&args=Ik4vIg) [Answer] # Java 7, ~~71~~ ~~70~~ 68 bytes ``` char c(int d,int m){return"NEWS".charAt("NEWS".indexOf(d)^-~(m%2));} ``` Too bad the `charAt` and `indexOf` takes up so much bytes.. **Ungolfed & all test cases:** [Try it here.](https://ideone.com/dhykEw) ``` class M{ static char c(int d, int m) { return "NEWS".charAt("NEWS".indexOf(d) ^ -~(m%2)); } public static void main(String[] a){ System.out.print(c('N', '/') + " "); System.out.print(c('N', '\\') + " "); System.out.print(c('E', '/') + " "); System.out.print(c('E', '\\') + " "); System.out.print(c('S', '/') + " "); System.out.print(c('S', '\\') + " "); System.out.print(c('W', '/') + " "); System.out.print(c('W', '\\') + " "); } } ``` **Output:** ``` W E S N E W N S ``` [Answer] # Python, ~~63~~ ~~61~~ 59 bytes ``` lambda d,m,x='NESW'*2:x[x.find(d)+2*(m=='/\\'[d in'NS'])-1] ``` Pretty simple. Can definitely be golfed more. Decides whether to add 1 or -1 to the input's index in `'NESW'`. This is a lambda expression; to use it, prefix it with `f=`. [Ideone it!](http://ideone.com/jIBN2i) [Answer] # Java 8, ~~62~~ ~~58~~ 56 bytes ``` (d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2); ``` # Ungolfed test program ``` import java.util.function.BiFunction; public class Mirror { public static void main(String[] args) { BiFunction<String, String, Character> function = (d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2); System.out.println(function.apply("N", "/")); //W System.out.println(function.apply("N", "\\")); //E System.out.println(function.apply("W", "/")); //N System.out.println(function.apply("W", "\\")); //S System.out.println(function.apply("E", "/")); //S System.out.println(function.apply("E", "\\")); //N System.out.println(function.apply("S", "/")); //E System.out.println(function.apply("S", "\\")); //W } } ``` [Answer] ## PowerShell v2+, 34 bytes ``` param($a,$b)"xNESSWNW"[(+$a+$b)%8] ``` Takes input as two explicit `char`s, outputs a `char`. This works as follows: If we sort the output, we want `S` `/` to somehow equal the same as `N` `\`, `W` `/` to equal `E` `\`, etc. Or, at least, produce numbers that are "close enough" yet still distinct. If we look at the ASCII values, we get a table like the below: ``` In1 In2 Res. Sum S 83 / 47 --> E 69 -> 130 N 78 \ 92 --> E 69 -> 170 W 87 / 47 --> N 78 -> 134 E 69 \ 92 --> N 78 -> 161 W 87 \ 92 --> S 83 -> 179 E 69 / 47 --> S 83 -> 116 N 78 / 47 --> W 87 -> 125 S 83 \ 92 --> W 87 -> 175 ``` Running a quick brute-forcer on the summations column (derived from summing the ASCII code points of the inputs) shows that if we take the sums modulo `8`, we get the following `2 2 | 6 1 | 3 4 | 5 7`. That's evidenced in the string `"xNESSWNW"`, as `E` is at index `2`, `N` is at `6` and `1`, and so on. So, we just need to sum the inputs (implicitly casting from `char` to `int32` along the way), take that `%8`, and use that to index into our string. ### Test Cases ``` PS C:\Tools\Scripts\golfing> ('N','/'),('N','\'),('E','/'),('E','\'),('S','/'),('S','\'),('W','/'),('W','\')|%{"$($_[0]) $($_[1]) --> "+(.\mirror-mirror-in-the-code.ps1 ([char]$_[0]) ([char]$_[1]))} N / --> W N \ --> E E / --> S E \ --> N S / --> E S \ --> W W / --> N W \ --> S ``` [Answer] ## Batch, 111 bytes ``` :goto %1 :W/ :E\ @echo N @exit/b :S/ :N\ @echo E @exit/b :E/ :W\ @echo S @exit/b :N/ :S\ @echo W ``` Accepts e.g. `W/` as a two-character string command line parameter. The `\` and `/` make looping awkward; it would have taken 124 bytes. [Answer] # Octave, 30 bytes Used the same order of arguments as Jonathan Allan. Takes the input as two-character string `'W\'`. ``` @(x)['NESSWNW'](mod(sum(x),8)) ``` Try it [online](https://ideone.com/zzyxeb). [Answer] # C, 44, 35, 34 bytes ``` f(a,b){return"NWES"[a&a/2&3^b&3];} ``` It requires two characters as two variables. It takes both lower and upper case. It uses a lot of bit manipulation. The fragment `a&a/2` results in a value that has unique values for the lower two bits, `&3` cuts off all higher bits. This used as an index into the string "NWES" for the `\` mirror. Luckily, the lower two bits of the ASCII characters `\` and `/` are 00 and 11 respectively, which is perfect to XOR with the aforementioned index to get the correct direction for the `/` mirror. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 17 bytes ``` r"SWEN"_e!r'/#=er ``` Input is space-separated. [Try it online!](http://cjam.tryitonline.net/#code=ewoKciJTV0VOIl9lIXInLyM9ZXIKCm59OCo&input=TiBcCk4gLwpFIFwKRSAvClMgXApTIC8KVyBcClcgLw) (As a linefeed-separated test suite.) This is the solution I found before posting the challenge. Not as short as Jonathan's cyclic indexing, but I thought this approach is quite interesting (and novel). ### Explanation The goal is use transliteration (i.e. using a character-to-character mapping) to replace the input character with the output character. To do this, we need to select the correct map based on whether the mirror is `/` or `\`. We'll map from the `SWEN` list to another one which we'll select conditionally. If the input list is `SWEN`, the two output maps need to be the following: ``` in SWEN / ENSW \ WSNE ``` Note that these are in sorted and reverse-sorted order (which is why we chose the seemingly random `SWEN` order as the input set). We could generate these by sorting the input list and the reversing the result if the input has `\`, but there's a better way: ``` r e# Read incoming direction. "SWEN" e# Push input list for transliteration. _e! e# Duplicate and get all permutations. The way, `e!` is implemented, it e# always gives the permutations in sort order, regardless of the order e# of the input set. Specifically that means that "ENSW" will be first e# and "WSNE" will be last in this list. r e# Read the mirror. '/# e# Find the index of / in this string. If the mirror is '/', then this e# gives 0. Otherwise, this gives -1, indicating that '/' was not found. = e# Select the corresponding permutation. Indexing is zero-based and e# cyclic so that 0 (input '/') gives the first permutation "ENSW" and e# -1 (input '\') gives the last permutation "WSNE". er e# Perform the transliteration on the incoming direction. e# Printing is implicit. ``` [Answer] # SED 48 (42 + 1 for -r) 43 Saved 5 thanks to Martin Ender♦ ``` s,N/|S\\,W,;s,E/|W\\,S,;s,N.|S/,E,;s,..,N, ``` Takes input as a two character string. [Answer] # Mathematica, 98 bytes ``` If[#2=="/",{"S",,,,,,,,,"W",,,,,"E",,,,"N"},{"N",,,,,,,,,"E",,,,,"W",,,,"S"}][[LetterNumber@#-4]]& ``` Anonymous function. Takes two strings as input and returns a string as output. [Answer] ## C, 81 bytes ``` f(char*a){return a!="N/"&a!="S\\"?a!="N\\"&a!="S/"?a!="W\\"&a!="E/"?78:83:69:87;} ``` ### Usage ``` main() { printf("N/ \t %c\n",f("N/")); printf("N\\\t %c\n",f("N\\")); printf("E/ \t %c\n",f("E/")); printf("E\\\t %c\n",f("E\\")); printf("S/ \t %c\n",f("S/")); printf("S\\\t %c\n",f("S\\")); printf("W/ \t %c\n",f("W/")); printf("W\\\t %c\n",f("W\\")); } ``` **Output:** ``` N/ : W N\ : E E/ : S E\ : N S/ : E S\ : W W/ : N W\ : S ``` [Answer] # Pyth, 13 bytes ``` @."EW¹0`Y"sCM ``` [Test suite](https://pyth.herokuapp.com/?code=%40.%22EW%C2%B90%60Y%22sCM&test_suite=1&test_suite_input=%22N%2F%22%0A%22N%5C%5C%22%0A%22E%2F%22%0A%22E%5C%5C%22%0A%22S%2F%22%0A%22S%5C%5C%22%0A%22W%2F%22%0A%22W%5C%5C%22&debug=0) Sum the code points, modular index, compressed string. [Answer] # TI-Basic, 40 bytes Hardcodes the inputs. Boring, but the shortest way. ``` sub("NEWS",1+int(inString("E/W\N\S/N/S\E\W/",Ans)/4),1 ``` ]
[Question] [ See the [cop thread](https://codegolf.stackexchange.com/questions/61804/create-a-programming-language-that-only-appears-to-be-unusable) for more information. Each answer to this question should crack an answer there. That is to say, it should be code to find the third-largest integer in the input when run in the interpreter given in that answer. If you post a crack that turns out to be invalid, you should delete it and are ineligible to post another attempt against the same answer. ### Scoring The winner of this question is the robber who makes the highest number of successful cracks. [Answer] ## [Shuffle, by Liam Noronha](https://codegolf.stackexchange.com/a/61983/8478) ``` cinpush main: gte Hans 1s Leopold jnz Leopold done mov 1s Hans gte Gertrude Hans Leopold jnz Leopold done mov Gertrude ShabbySam mov Hans Gertrude mov ShabbySam Hans gte Alberto Gertrude Leopold jnz Leopold done mov Alberto ShabbySam mov Gertrude Alberto mov ShabbySam Gertrude done: mov 10 ShabbySam gte 1s ShabbySam Leopold jz Leopold undo_u mov 30 ShabbySam gte 1s ShabbySam Leopold jz Leopold undo_d undo_r: POP!! 1 "shuffle" f "shuffle" f "shuffle" b "shuffle" b "shuffle" l "shuffle" f "shuffle" f "shuffle" b "shuffle" b jmp end undo_u: POP!! 1 "shuffle" f "shuffle" f "shuffle" f "shuffle" b "shuffle" b "shuffle" b "shuffle" l "shuffle" l "shuffle" l "shuffle" f "shuffle" b jmp end undo_d: POP!! 1 "shuffle" f "shuffle" b "shuffle" l "shuffle" f "shuffle" f "shuffle" f "shuffle" b "shuffle" b "shuffle" b end: jnz 1s main print Hans done! ``` This was really great fun, thank you Liam! :) Thanks to Sp3000 for a slight but necessary nudge in the right direction. ### How? Two words: [Pocket Cube](https://en.wikipedia.org/wiki/Pocket_Cube). It turns out that the stacks correspond to the faces of a 2x2x2 Rubik's cube as follows: ``` ____ ____ | | | | 19 | 17 | |____U____| | | | | 20 | 18 | _________|____|____|____ ____ ____ ____ | | | | | | | | | | 13 | 14 | 1 | 2 | 9 | 10 | 6 | 5 | |____L____|____F____|____R____|____B____| | | | | | | | | | | 15 | 16 | 3 | 4 | 11 | 12 | 8 | 7 | |____|____|____|____|____|____|____|____| | | | | 22 | 24 | |____D____| | | | | 21 | 23 | |____|____| ``` Where `ULFRBD` indicate which face corresponds to up, left, front, right, back, down when the cube is folded properly. The permutations correspond to rotating any one side by 90 degrees (where the names thankfully match up). It turns out that `f`, `r` and `d` are clockwise rotations (when viewing the face) and `r`, `l` and `u` are counter-clockwise rotations (when viewing the face). Now the `cinpush` command operates such that it applies one of the rotations `u`, `d` or `r` (depending on the given value) and then pushes the input value onto the stack in position `1`. (And then it repeats doing this for every element in the input.) That means we can reverse this process (to ensure we end up with the correct order of stacks without having to solve an arbitrary Rubik's cube) by repeatedly looking at the stack in position `1`, undoing the corresponding permutation and popping the value of that stack (so that next time we see the stack, we get the value underneath). How do we undo the rotations? Thankfully, we have both `f` and `b` at our disposal. If we apply both of them, we rotate the entire cube by 90 degrees. This means we can move the affected side (`U`, `R` or `D`) to `L`, undo the rotation using one or three `l`s (depending on the relative direction of `l` and the rotation performed during the input), and then rotate the cube back to its previous orientation using `f` and `b` again. In particular, each of the rotations performed during input can be undone as follows: ``` u --> fffbbblllfb r --> ffbblffbb d --> fblfffbbb ``` I'll see if I can come up with some animations to show that this works. Now this gives us a way to iterate through the entire input once. But with 5 registers, that's all we need: * `Alberto` is the maximum value encountered so far. * `Gertrude` is the 2nd largest value encountered so far. * `Hans` is the 3rd largest value encountered so far. When we encounter a new value, we bubble it up those three as far as necessary, where we can use `ShabbySam` as a temporary register for the swaps. That still leaves `Leopold` which we can use to hold a conditional when making the necessary comparisons. At the end of the process, we simply print the contents of `Hans`, which will already hold the 3rd largest value. [Answer] ## [TKDYNS by Sam Cappleman-Lynes](https://codegolf.stackexchange.com/a/62083/8478) This is probably not optimal, but I think it does the trick... ``` cvcvc>v>^>>^^>>v>vvvvvvvv<<<^<<^<<^^>^<^cvc>v<cvcvcvc^>>vv<<c >>^>>v>>>^^^^^^^^<^<<vv<<v<^<^^>cv<>^ >>^>>v>>>^^^^^^^^<^<<vv<<v<^<^^>vc^v<>^ >>^>>v>>>^^^^^^^^<^<<vv<<v<^c<^>^ >>^>>v>>>^^^^^^^^<^<<vv<<v<c^<^>^ >>^^<<^^>^c^^<^>^ >>^^<<^^>c<^>^^<^>^ >>^^<^c^<^>^^<^>^ >>^^<c<^^^>^^<^>^ >^cv>^>^<<<^^^>^^<^>^ >c>^>^<<<^^^>^^<^>^ >>^>>v>>>^^^^^^^^<^<<vv<<v<^<^^>>cv^ >>^>>v>>>^^^^^^^^<^<<<v<c^ >>^>>v>>>^^^^^^^^<^<<vv<<c^^ >>^>>v>>>^^^^^^^^<^<<vv<<vcv>>>^<^<<^^ >>^^<<^^>>^c>>>^<^<<^^ >>^^<<^^>>c<^>>>>^<^<<^^ >>^>>v>>^<^^<<<c^<^>>>>^<^<<^^ >>^^c>vv>^^^<<^<^>>>>^<^<<^^ >>^c^>vv>^^^<<^<^>>>>^<^<<^^ >>c^^>vv>^^^<<^<^>>>>^<^<<^^ >>^>>v>>>^^^^^^^^<^<<<c<> >>^>>v>>>^^^^^^^^<^<<<vc^<> >>^>>v>>>^^^^^^^^<^<<vv<c^^ >>^>>v>>>^^^^^^^^<^<<vv<vc^^^ >>^^<<^^>>>^c^^^^ >>^^<<^^>>>c^^^^^ >>^>>v>>^<^^<<c^^^^^^ >>^>^c<^^<^>^^^>^ >>^>c^<^^<^>^^^>^ >>>c^^<^^<^>^^^>^ >>^>>v>>>^^^^^^^^<^<<c<<>> >>^>>v>>>^^^^^^^^<^<<vc<^> >>^>>v>>>^^^^^^^^<^<<vvc>^<<^> >>^>>v>>>^^^^^^^^<^<<vv<v>c>^^<<^> >>^>>v>>>^^^^^^^^<^<<vv<v>>v<c^>^^<<^> >>^^<<^^>>>>cv<^<^^>^>>^<<^> >>^>>v>>^<^^<c<^<^^>^>>^<<^> >>^>>v>>^<^^<vc>^^<v<^<^^>^>>^<<^> >>^>>c>^^^<v<^<^^>^>>^<<^> >>^>>vc<<^^>^^<^^>^>>^<<^> >>^>>v>>>^^^^^^^^<^<cv^ >>^>>v>>>^^^^^^^^<<c^ >>^>>v>>>^^^^^^^^<^<<vv>c<^>^ >>^>>v>>>^^^^^^^^<^<<vv<v>>c<^^>^ >>^>>v>>>^^^^^^^^<^<<vv<v>>vc^<^^>^ >>^>>v>>^<^^^c^^<^^>^ >>^>>v>>^<^^c>v>>^>^<^^^<^<<^ >>^>>v>>^<^c^>v>>^>^<^^^<^<<^ >>^>>v>>^<c^^>v>>^>^<^^^<^<<^ >>^>>v>c^^^>v>>^>^<^^^<^<<^ >>^>>v>>>^^^^^^^^<^c<v^> >>^>>v>>>^^^^^^^^<c<^> >>^>>v>>>^^^^^^^^<^<<vv<v>>>^c<vv<<v<^^<^<^^>>>>>> >>^>>v>>>^^^^^^^^<^<<vv<v>>>c>^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>>^^^^^^^^<^<<vv<v>>v>c^>^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>>^^^^<c^^>^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>^<^^>c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>^<^^>vc^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>^cv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >>^>>v>>>^^^^^^^^<^>c>< >>^>>v>>>^^^^^^^^c>^< >>^>>v>>>^^^^^^^c^>^< >>^>>v>>>^^^^^^c>^<^>^< >>^>>v>>>^^^^^c^>^<^>^< >>^>>v>>>^^^^c^^>^<^>^< >>^>>v>>>^^^c>^^<^>^<^>^< >>^>>v>>>^^c^>^^<^>^<^>^< >>^>>v>>>^cv>^^<^>^^<^>^<^>^< >>^>>v>>>c>^^<^>^^<^>^<^>^< >>^>>v>>>^^^^^^^^>^c<> >>^>>v>>>^^^^^^^^>c^<> >>^>>v>>>^^^^^^^>cv<vvv>v<<^^^^^^>>^ >>^>>v>>>^^^^^^^>vc<vvv>v<<^^^^^^>>^ >>^>>v>>>^^^>^^c^<vvv>v<<^^^^^^>>^ >>^>>v>>>^^^>^c^^<vvv>v<<^^^^^^>>^ >>^>>v>>>^^^>cv<<^^^^^^>>^ >>^>>v>>>^^^>vc<<^^^^^^>>^ >>^>>v>>>^>cv<<<^<<<^>>>>^^^^^^>>^ >>^>>v>>>^>vc<<<^<<<^>>>>^^^^^^>>^ >>^>>v>>>^^^^^^^^>^>cv^ >>^>>v>>>^^^^^^^>>^c^ >>^>>v>>>^^^^^^^>>c^^ >>^>>v>>>^^^>^^>^c^^^ >>^>>v>>>^^^>^^>cvv<^^^^^^> >>^>>v>>>^^^>^^>vcv<^^^^^^> >>^>>v>>>^^^>>c<^^^^^^> >>^>>v>>>^>v>^^cvv<<^<^^>^>^^^^^> >>^>>v>>>^>v>^cv<<^<^^>^>^^^^^> >>^>>v>>>^>v>c<<^<^^>^>^^^^^> cvc<v>cvcvc<v>cvc^<vv>c>>v<v<^cvc >^>^<<<^^^>^>^>^^<cv^ >^>^<<<^^^>^>^^c^ >^>^<<<^^^>^>^c^^ >^>^<<<^^^>^>cv>>>^<^<<^^ >^>^<^^^c>>>^<^<<^^ >^>^<^^c<^>>>>^<^<<^^ >^>^<^c^<^>>>>^<^<<^^ >^>^<c>vv>^^^<<^<^>>>>^<^<<^^ >^c^>vv>^^^<<^<^>>>>^<^<<^^ >c^^>vv>^^^<<^<^>>>>^<^<<^^ >^>^<<<^^^>^>^>^^c<<>> >^>^<<<^^^>^>^>^c^<<>> >^>^<<<^^^>^>^>c^^<<>> >^>^<<<^^^>^>>c^^^ >^>^<^^^>c^^^^ >^>^<^^>c^^^^^ >^>^<^>c^^^^^^ >^>^c<^^<^>^^^>^ >^>c^<^^<^>^^^>^ >^>>v<c^^<^^<^>^^^>^ >^>^<<<^^^>^>^>^^>c<v<>^> >^>^<<<^^^>^>^>^^>vc<^> >^>^<<<^^^>^>^>^^>>>>v<vv<<^c>^<<^> >^>^<<<^^^>^>^>^^>>>>v<vv<<c>^^<<^> >^>^<^^^>>c^>^^<<^> >^>^<^>>^cv<^<^^>^>>^<<^> >^>^<^>>c<^<^^>^>>^<<^> >^>^<^>>vc>^^<v<^<^^>^>>^<<^> >^>>c>^^^<v<^<^^>^>>^<<^> >^>>vc<<^^>^^<^^>^>>^<<^> >^>^<<<^^^>^>^>^^>>cv^ >^>^<<<^^^>^>^>^^>>>>v<<c^ >^>^<<<^^^>^>^>^^>>>>v<v<c<^>^ >^>^<<<^^^>^>^>^^>>>>v<vv<c<^^>^ >^>^<<<^^^>^>^>^^>>>>v<v>>v<v<<c^<^^>^ >^>^<<<^^^>^>^>^^>>>>v<v>>v<v<<vc^^<^^>^ >^>^<^>>v>^c>v>>^>^<^^^<^<<^ >^>^<^>>v>c^>v>>^>^<^^^<^<<^ >^>^<^>>v>vc^^>v>>^>^<^^^<^<<^ >^>^<^>>v>vvc^^^>v>>^>^<^^^<^<<^ >^>^<<<^^^>^>^>^^>>>c<v^> >^>^<<<^^^>^>^>^^>>>>v<c<^> >^>^<<<^^^>^>^>^^>>>>v<vc<vv<<v<^^<^<^^>>>>>> >^>^<<<^^^>^>^>^^>>>>v<vvc>^<<vv<<v<^^<^<^^>>>>>> >^>^<<<^^^>^>^>^^>>>>v<v>>v<v<c^>^<<vv<<v<^^<^<^^>>>>>> >^>^<^>>v>>>>^<<^c^^>^<<vv<<v<^^<^<^^>>>>>> >^>^<^>>v>>>>^<<c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >^>^<^>>v>>c^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >^>^<^>>v>>vcv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >^>^<^>>v>vv>c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >^>^<<<^^^>^>^>^^>>>>c<v^> >^>^<<<^^^>^>^>^^>>>>vc>^< >^>^<<<^^^>^>^>^^>>>>v<v>c^>^< >^>^<<<^^^>^>^>^^>>>>v<v>>v<c>^<^>^< >^>^<<<^^^>^>^>^^>>>>v<v>>v<vc^>^<^>^< >^>^<<<^^^>^>^>^^>>>>v<v>>vvv<c^^>^<^>^< >^>^<^>>v>>>>^<c>^^<^>^<^>^< >^>^<^>>v>>>c^>^^<^>^<^>^< >^>^<^>>v>>>vcv>^^<^>^^<^>^<^>^< >^>^<^>>v>vv>>c>^^<^>^^<^>^<^>^< >^>^<<<^^^>^>^>^^>>>>>cv^ >^>^<<<^^^>^>^>^^>>>>v>c^ >^>^<<<^^^>^>^>^^>>>>v<v>>cv<vvv>v<<^^^^^^>>^ >^>^<<<^^^>^>^>^^>>>>v<v>>vc<vvv>v<<^^^^^^>>^ >^>^<<<^^^>^>^>^^>>>>v<v>>vvc^<vvv>v<<^^^^^^>>^ >^>^<<<^^^>^>^>^^>>>>v<v>>vvvc^^<vvv>v<<^^^^^^>>^ >^>^<^>>v>>>>^cv<<^^^^^^>>^ >^>^<^>>v>>>>c<<^^^^^^>>^ >^>^<^>>v>>>v>cv<<<^<<<^>>>>^^^^^^>>^ >^>^<^>>v>>>v>>v<c<<<^<<<^>>>>^^^^^^>>^ >^>^<<<^^^>^>^>^^>>>>>>c<v^> >^>^<<<^^^>^>^>^^>>>>>>vc^<v^> >^>^<<<^^^>^>^>^^>>>>v<v>>v>^c^^ >^>^<<<^^^>^>^>^^>>>>v<v>>v>c^^^ >^>^<<<^^^>^>^>^^>>>>v<v>>vvv>^cvv<^^^^^^> >^>^<<<^^^>^>^>^^>>>>v<v>>vvv>cv<^^^^^^> >^>^<<<^^^>^>^>^^>>>>v<v>>vvv>vc<^^^^^^> >^>^<<<^^^>^>^>^^>>>>v<v>>vvv>vvcvv<<^<^^>^>^^^^^> >^>^<^>>v>>>v>>cv<<^<^^>^>^^^^^> >^>^<^>>v>>>v>>vc<<^<^^>^>^^^^^> cvcvc>>v>v<<<^cvc<v>cvc>>vvv<^^<cvcvc ^^>vv>>^^^^>^>^>^<^<<^<<c<> ^^>vv>>^^^^>^>^>^<^<<^<<vc^<> ^^>vv>^^^<<^<^>>>>^<^<c^^ ^^>vv>^^^<<^<^>>>>^<^<vc^^^ ^^>vv>^^^<<^<^>>c^^^^ ^^>vv>^^^<^c^^^^^ ^^>vv>^^^<c^^^^^^ ^^>c<^^<^>^^^>^ ^^>vc^<^^<^>^^^>^ ^^>vvc^^<^^<^>^^^>^ ^^>vv>>^^^^>^>^>^<^<<^<c<<>> ^^>vv>^^^<<^<^>>>>^<^^c<^> ^^>vv>^^^<<^<^>>>>^<^c>^<<^> ^^>vv>^^^<<^<^>>>>^<c>^^<<^> ^^>vv>^^^<<^<^>>>c^>^^<<^> ^^>vv>^^^<<^<^>>>vcv<^<^^>^>>^<<^> ^^>vv>^^^c<^<^^>^>>^<<^> ^^>vv>^^c>^^<v<^<^^>^>>^<<^> ^^>vv>^c>^^^<v<^<^^>^>>^<<^> ^^>vv>c<<^^>^^<^^>^>>^<<^> ^^>vv>>^^^^>^>^>^<^<<^cv<>^ ^^>vv>>^^^^>^>^>^<^<<c^v<>^ ^^>vv>^^^<<^<^>>>>^>^<c<^>^ ^^>vv>^^^<<^<^>>>>^c<^^>^ ^^>vv>^^^<<^<^>>>>c^<^^>^ ^^>vv>>^^^^c^^<^^>^ ^^>vv>>^^^c>v>>^>^<^^^<^<<^ ^^>vv>>^^c^>v>>^>^<^^^<^<<^ ^^>vv>>^c^^>v>>^>^<^^^<^<<^ ^^>vv>>c^^^>v>>^>^<^^^<^<<^ ^^>vv>>^^^^>^>^>^<^<<^>c<<<<>>>> ^^>vv>>^^^^>^>^>^<^<c<^><<<<>>>> ^^>vv>^^^<<^<^>>>>^>^c<vv<<v<^^<^<^^>>>>>> ^^>vv>^^^<<^<^>>>>^>c>^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>^^^^>^c^>^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>^^^^>c^^>^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>^^^^>>>v<<c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>>>^<^c^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>>>^<cv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>>c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^>vv>>^^^^>^>^>^<^<<^>>c>< ^^>vv>>^^^^>^>^>^<^c>^< ^^>vv>>^^^^>^>^>^<c^>^< ^^>vv>>^^^^>^>^c>^<^>^< ^^>vv>>^^^^>^>c^>^<^>^< ^^>vv>>^^^^>>c^^>^<^>^< ^^>vv>>^^^^>>>v<c>^^<^>^<^>^< ^^>vv>>>>^<^>c^>^^<^>^<^>^< ^^>vv>>>>^cv>^^<^>^^<^>^<^>^< ^^>vv>>>>c>^^<^>^^<^>^<^>^< ^^>vv>>^^^^>^>^>^^^c<> ^^>vv>>^^^^>^>^>^^c^<> ^^>vv>>^^^^>^>^>^cv<vvv>v<<^^^^^^>>^ ^^>vv>>^^^^>^>^>c<vvv>v<<^^^^^^>>^ ^^>vv>>^^^^>>>>^<c^<vvv>v<<^^^^^^>>^ ^^>vv>>^^^^>>>c^^<vvv>v<<^^^^^^>>^ ^^>vv>>^^^^>>>vcv<<^^^^^^>>^ ^^>vv>>>>^<^>>c<<^^^^^^>>^ ^^>vv>>>>>>^<cv<<<^<<<^>>>>^^^^^^>>^ ^^>vv>>>>>c<<<^<<<^>>>>^^^^^^>>^ ^^>vv>>^^^^>^>^>^^>^c<> ^^>vv>>^^^^>^>^>^^>c^<> ^^>vv>>^^^^>^>^>^^>vc^^<> ^^>vv>>^^^^>^>^>>c^^^ ^^>vv>>^^^^>>>>^cvv<^^^^^^> ^^>vv>>^^^^>>>>cv<^^^^^^> ^^>vv>>^^^^>>>>vc<^^^^^^> ^^>vv>>>>>>^^cvv<<^<^^>^>^^^^^> ^^>vv>>>>>>^cv<<^<^^>^>^^^^^> ^^>vv>>>>>>c<<^<^^>^>^^^^^> cvcvcvcvcvcvc^^^^^<vvv<v>vv>cvcvc ^^<^^<^>^^^>>^c<> ^^<^^<^>^^^>>c<^> ^^<^^<^>^^^>v>c>^<<^> ^^<^^<^>^^^>vv>c>^^<<^> ^^<^^<^>^^^>vv>vc^>^^<<^> ^^<^^<^>^^^>vvvvv>^cv<^<^^>^>>^<<^> ^^<^^<^>^^^>vvvvv>c<^<^^>^>>^<<^> ^^<^^<^>^^^>vvvvv>vc>^^<v<^<^^>^>>^<<^> ^^<^^<^>^^^>vvvvv>v>v<c>^^^<v<^<^^>^>>^<<^> ^^<^^<^>^^^>vvvvv>v>vv<c<<^^>^^<^^>^>>^<<^> ^^<^^<^>^^^>>^>cv^ ^^<^^<^>^^^>>>c^ ^^<^^<^>^^^>v>>c<^>^ ^^<^^<^>^^^>vv>>c<^^>^ ^^<^^<^>^^^>vv>v>c^<^^>^ ^^<^^<^>^^^>vvvvv>^>c^^<^^>^ ^^<^^<^>^^^>vvvvv>>c>v>>^>^<^^^<^<<^ ^^<^^<^>^^^>vvvvv>v>c^>v>>^>^<^^^<^<<^ ^^<^^<^>^^^>vvvvv>v>vc^^>v>>^>^<^^^<^<<^ ^^<^^<^>^^^>vvvvv>v>vvc^^^>v>>^>^<^^^<^<<^ ^^<^^<^>^^^>>>>>>^<<c>><< ^^<^^<^>^^^>>>>c<^> ^^<^^<^>^^^>vv>>>^c<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vv>>>c>^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vv>>>vc^>^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vvvvv>v>v>>>^^<^<c^^>^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vvvvv>v>v>>>^^<<c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vvvvv>v>>c^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vvvvv>v>v>cv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>vvvvv>v>vv>c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^<^^<^>^^^>>>>>>^<c<<>> ^^<^^<^>^^^>>>>>c>^<<<>> ^^<^^<^>^^^>vv>>>^>c^>^< ^^<^^<^>^^^>vv>>>>c>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>>^^<^^c^>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>>^^<^c^^>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>>^^<c>^^<^>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>^c^>^^<^>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>cv>^^<^>^^<^>^<^>^< ^^<^^<^>^^^>vvvvv>v>v>>vc>^^<^>^^<^>^<^>^< ^^<^^<^>^^^>>>>>>^cv><^ ^^<^^<^>^^^>>>>>>c^v><^ ^^<^^<^>^^^>>>>>>^>vv<cv<vvv>v<<^^^^^^>>^ ^^<^^<^>^^^>vv>>>>>c<vvv>v<<^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>^^^^c^<vvv>v<<^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>^^^c^^<vvv>v<<^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>^^cv<<^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>^c<<^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>cv<<<^<<<^>>>>^^^^^^>>^ ^^<^^<^>^^^>vvvvv>v>v>>>vc<<<^<<<^>>>>^^^^^^>>^ ^^<^^<^>^^^>>>>>>^>cvvv^^^ ^^<^^<^>^^^>>>>>>^>vc^vvv^^^ ^^<^^<^>^^^>>>>>>^>vvc^^vvv^^^ ^^<^^<^>^^^>vvvvv>v>v>>>^^^^>^c^^^ ^^<^^<^>^^^>vvvvv>v>v>>>^^^^>cvv<^^^^^^> ^^<^^<^>^^^>vvvvv>v>v>>>^>^^cv<^^^^^^> ^^<^^<^>^^^>vvvvv>v>v>>>^>^c<^^^^^^> ^^<^^<^>^^^>vvvvv>v>v>>>^>cvv<<^<^^>^>^^^^^> ^^<^^<^>^^^>vvvvv>v>v>>>v>^cv<<^<^^>^>^^^^^> ^^<^^<^>^^^>vvvvv>v>v>>>v>c<<^<^^>^>^^^^^> c<v>c>v<c>v<cvc^>^<<v<vv>v>^cvc^>vv<c>v<c>^^^<v<v<vv>>c <<^^>^^<^^>^>>^^c<> <<^^>^^<^^>^>>^c^<> <<^^>^^<^^>^>>c<^>^ <<^^>^^<^^>^>>vc<^^>^ <<^^>^^<^^>^>>vvc^<^^>^ <<^^>^>^>c^^<^^>^ <<^^>^>^>vc>v>>^>^<^^^<^<<^ <<^^>^>^>vvc^>v>>^>^<^^^<^<<^ <<^^>^>^>vvvc^^>v>>^>^<^^^<^<<^ <<^^>^>^>vvvvc^^^>v>>^>^<^^^<^<<^ <<^^>^^<^^>^>>^^>c<<>> <<^^>^^<^^>^>>^>c<^><<>> <<^^>^^<^^>^>>>c<vv<<v<^^<^<^^>>>>>> <<^^>^^<^^>^>>vv>^c>^<<vv<<v<^^<^<^^>>>>>> <<^^>^^<^^>^>>vv>c^>^<<vv<<v<^^<^<^^>>>>>> <<^^>^^<^^>^>>vv>vc^^>^<<vv<<v<^^<^<^^>>>>>> <<^^>^>^>vv>^c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> <<^^>^>^>vv>c^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> <<^^>^>^>vv>vcv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> <<^^>^>^>vv>v>v<c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> <<^^>^^<^^>^>>^^>>c>v^< <<^^>^^<^^>^>>>>^c>^< <<^^>^^<^^>^>>>>c^>^< <<^^>^>^>vv>^>^>^^<c>^<^>^< <<^^>^>^>vv>^>^>^^<vc^>^<^>^< <<^^>^>^>vv>^>^c^^>^<^>^< <<^^>^>^>vv>^>c>^^<^>^<^>^< <<^^>^>^>vv>>c^>^^<^>^<^>^< <<^^>^>^>vv>v>cv>^^<^>^^<^>^<^>^< <<^^>^>^>vv>v>vc>^^<^>^^<^>^<^>^< <<^^>^^<^^>^>>^^>>>cv^ <<^^>^>^>vv>^>^>^^^^c^ <<^^>^>^>vv>^>^>^^^cv<vvv>v<<^^^^^^>>^ <<^^>^>^>vv>^>^>^^c<vvv>v<<^^^^^^>>^ <<^^>^>^>vv>^>^>^c^<vvv>v<<^^^^^^>>^ <<^^>^>^>vv>^>^>c^^<vvv>v<<^^^^^^>>^ <<^^>^>^>vv>^>^>vcv<<^^^^^^>>^ <<^^>^>^>vv>^>^>vvc<<^^^^^^>>^ <<^^>^>^>vv>^>^>vvvcv<<<^<<<^>>>>^^^^^^>>^ <<^^>^>^>vv>v>v>c<<<^<<<^>>>>^^^^^^>>^ <<^^>^>^>vv>^>^>^^^>^^c<> <<^^>^>^>vv>^>^>^^^>^c^<> <<^^>^>^>vv>^>^>^^^>c^^<> <<^^>^>^>vv>^>^>^^>c^^^ <<^^>^>^>vv>^>^>>^cvv<^^^^^^> <<^^>^>^>vv>^>^>>cv<^^^^^^> <<^^>^>^>vv>^>^>>vc<^^^^^^> <<^^>^>^>vv>^>^>>vvcvv<<^<^^>^>^^^^^> <<^^>^>^>vv>^>^>vvv>cv<<^<^^>^>^^^^^> <<^^>^>^>vv>v>v>>c<<^<^^>^>^^^^^> cvc<v>c<v>cvcvc^^<^^>>>v>vvv>v<v<<^<cvcvcvc ^^^>v>>^>^<^^^<^<^c<> ^^^>v>>^>^<^^^<^<c<^> ^^^>v>>^>^<^^^<<c<vv<<v<^^<^<^^>>>>>> ^^^>v>>^>^<^^^<v<c>^<<vv<<v<^^<^<^^>>>>>> ^^^>v>>^>^<^^^<vv<c^>^<<vv<<v<^^<^<^^>>>>>> ^^^>v>>^>^<^^^<^<<<vv>vv>c^^>^<<vv<<v<^^<^<^^>>>>>> ^^^>c<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^^>vc^<v<v>>v>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^>cv>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> >c>^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>> ^^^>v>>^>^<^^^<^<^>c>< ^^^>v>>^>^<^^^<^c>^< ^^^>v>>^>^<^^^<c^>^< ^^^>v>>^>^<^^^<vc>^<^>^< ^^^>v>>^>^<^^^<vvc^>^<^>^< ^^^>v>>^>^<^^^<^<<<vv>vv>>c^^>^<^>^< ^^^>v>>^<c>^^<^>^<^>^< ^^^>v>c^>^^<^>^<^>^< ^>>cv>^^<^>^^<^>^<^>^< ^^^>v>>>vv<<c>^^<^>^^<^>^<^>^< ^^^>v>>^>^<^^^<^>>^<c<> ^^^>v>>^>^<^^^<^>c^ ^^^>v>>^>^<^^^cv<vvv>v<<^^^^^^>>^ ^^^>v>>^>^<^^c<vvv>v<<^^^^^^>>^ ^^^>v>>^>^<^c^<vvv>v<<^^^^^^>>^ ^^^>v>>^>^<c^^<vvv>v<<^^^^^^>>^ ^^^>v>>^cv<<^^^^^^>>^ ^^^>v>>c<<^^^^^^>>^ ^^^>v>>vcv<<<^<<<^>>>>^^^^^^>>^ ^^^>v>>>vv<c<<<^<<<^>>>>^^^^^^>>^ ^^^>v>>^>^<^^^<^>>^c<<>> ^^^>v>>^>^<^^^<^>>c^<<>> ^^^>v>>^>^<^^^>c^^ ^^^>v>>^>^<^^>c^^^ ^^^>v>>^>^<^>cvv<^^^^^^> ^^^>v>>^>^cv<^^^^^^> ^^^>v>>^>c<^^^^^^> ^^^>v>>>cvv<<^<^^>^>^^^^^> ^^^>v>>>vcv<<^<^^>^>^^^^^> ^^^>v>>>vvc<<^<^^>^>^^^^^> c<v>c<^<<<<<vv>v>vv>^>>^^>c>v<cvcvc^^>>vvvv>vv<^<v<^<<^>^>cvc^<v<v>>cvc >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>>>c>< >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>c>^< >^>v>^^<^^^^<^c^>^< >^>v>^^<^^^^<c>^<^>^< >^>v>^^<^^^<c^>^<^>^< >^>v>^^<^^<c^^>^<^>^< ^<<^>^>>c>^^<^>^<^>^< ^<<^>^>>vc^>^^<^>^<^>^< >^cv>^^<^>^^<^>^<^>^< >c>^^<^>^^<^>^<^>^< >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>>^c<> >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>>c^<> >^>v>^^<^^^^^cv<vvv>v<<^^^^^^>>^ >^>v>^^<^^^^c<vvv>v<<^^^^^^>>^ >^>v>^^<^^^c^<vvv>v<<^^^^^^>>^ >^>v>^^<^^c^^<vvv>v<<^^^^^^>>^ >^>v>^^<^cv<<^^^^^^>>^ >^>v>^^<c<<^^^^^^>>^ >^>cv<<<^<<<^>>>>^^^^^^>>^ >^>vc<<<^<<<^>>>>^^^^^^>>^ >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>>^>cv^ >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>>>c^ >^>v>^^<^^^^<^<<vv<<v<^^<^<^^>>>>>v>>>>vc^^ >^>v>^^<^^^^>c^^^ >^>v>^^<^^>^cvv<^^^^^^> >^>v>^^<^^>cv<^^^^^^> >^>v>^^<^^>vc<^^^^^^> >^>v>^^cvv<<^<^^>^>^^^^^> >^>v>^cv<<^<^^>^>^^^^^> >^>v>c<<^<^^>^>^^^^^> c>v<cvc>v<cvcvc^>vv<cvc>vv<^cvc >^^<^>^^<^>^<^>^cv><^ >^^<^>^^<^>^<^>c^v><^ >^^<^>^^<^>^cv<vvv>v<<^^^^^^>>^ >^^<^>^^<^>c<vvv>v<<^^^^^^>>^ >^^<^>^^c^<vvv>v<<^^^^^^>>^ >^^<^>^c^^<vvv>v<<^^^^^^>>^ >^^<^>cv<<^^^^^^>>^ >^^c<<^^^^^^>>^ >^cv<<<^<<<^>>>>^^^^^^>>^ >c<<<^<<<^>>>>^^^^^^>>^ >^^<^>^^<^>^>^^c<> >^^<^>^^<^>^>^c^<> >^^<^>^^<^>^>c^^<> >^^<^>^^<^>>c^^^ >^^<^>^^>cvv<^^^^^^> >^>^^^cv<^^^^^^> >^>^^c<^^^^^^> >^>^cvv<<^<^^>^>^^^^^> >^>cv<<^<^^>^>^^^^^> >^>vc<<^<^^>^>^^^^^> cvc<<vvvvvv>>^<^^^>^cvcvcvc^^<vvv>cvc<<<<<<v>>>v>>>^cvc <<<^<<<^>>>>^^^^^^>>>^c<> <<<^<<<^>>>>^^^^^^>>>c^<> <<<^<<<^>>>>^^^^^^>>>vc^^<> <<<^<<<^>>>>>>^<^^^>v>^c^^^ <<<^<<<^>>>>>>^<^^^>v>cvv<^^^^^^> <<<^<<<^>>>>>>^>^cv<^^^^^^> <<<^<<<^>>>>>>^>c<^^^^^^> <<<^<<<^>>>>>>^>vcvv<<^<^^>^>^^^^^> ^>cv<<^<^^>^>^^^^^> >c<<^<^^>^>^^^^^> cvcvcvc^^^<vvvvvv>^^cvcvc<^<v<vv>v>>^^cvcvc ``` This may come as a surprise, but I didn't write this by hand... the code was generated by the following Mathematica program: ``` layouts = Graph /@ {Labeled[DirectedEdge[#, #2], #3] & @@@ {{0, 1, ">"}, ... }; path[layout_, a_, b_] := StringJoin[ PropertyValue[{layouts[[layout + 1]], #}, EdgeLabels] & /@ DirectedEdge @@@ Partition[FindShortestPath[layouts[[layout + 1]], a, b], 2, 1]] safetyCheck[layout_, target_] = ""; safetyCheck[0, 1] = safetyCheck[0, 11] = "v<>^"; safetyCheck[0, 2] = "v^"; safetyCheck[0, 3] = safetyCheck[0, 13] = "<>"; safetyCheck[0, 4] = "<<>>"; safetyCheck[0, 5] = "v^"; safetyCheck[0, 6] = "<v^>"; safetyCheck[0, 7] = "><"; safetyCheck[0, 8] = safetyCheck[0, 18] = "<>"; safetyCheck[0, 9] = "v^"; safetyCheck[1, 2] = "v^"; safetyCheck[1, 3] = safetyCheck[1, 13] = safetyCheck[1, 23] = "<<>>"; safetyCheck[1, 4] = "<v<>^>"; safetyCheck[1, 5] = "v^"; safetyCheck[1, 6] = "<v^>"; safetyCheck[1, 7] = "<v^>"; safetyCheck[1, 8] = "v^"; safetyCheck[1, 9] = safetyCheck[1, 19] = "<v^>"; safetyCheck[2, 3] = safetyCheck[2, 13] = "<>"; safetyCheck[2, 4] = "<<>>"; safetyCheck[2, 5] = safetyCheck[2, 15] = "v<>^"; safetyCheck[2, 6] = safetyCheck[2, 16] = "<<<<>>>>"; safetyCheck[2, 7] = "><"; safetyCheck[2, 8] = safetyCheck[2, 18] = "<>"; safetyCheck[2, 9] = safetyCheck[2, 19] = safetyCheck[2, 29] = "<>"; safetyCheck[3, 4] = "<>"; safetyCheck[3, 5] = "v^"; safetyCheck[3, 6] = ">><<"; safetyCheck[3, 7] = safetyCheck[3, 17] = "<<>>"; safetyCheck[3, 8] = safetyCheck[3, 18] = "v><^"; safetyCheck[3, 9] = safetyCheck[3, 19] = safetyCheck[3, 29] = "vvv^^^"; safetyCheck[4, 5] = safetyCheck[4, 15] = "<>"; safetyCheck[4, 6] = safetyCheck[4, 16] = "<<>>"; safetyCheck[4, 7] = ">v^<"; safetyCheck[4, 8] = "v^"; safetyCheck[4, 9] = safetyCheck[4, 19] = safetyCheck[4, 29] = "<>"; safetyCheck[5, 6] = "<>"; safetyCheck[5, 7] = "><"; safetyCheck[5, 8] = "<>"; safetyCheck[5, 9] = safetyCheck[5, 19] = "<<>>"; safetyCheck[6, 7] = "><"; safetyCheck[6, 8] = safetyCheck[6, 18] = "<>"; safetyCheck[6, 9] = "v^"; safetyCheck[7, 8] = safetyCheck[7, 18] = "v><^"; safetyCheck[7, 9] = safetyCheck[7, 19] = safetyCheck[7, 29] = "<>"; safetyCheck[8, 9] = safetyCheck[8, 19] = safetyCheck[8, 29] = "<>"; minions = {}; For[i = 0, i < 10, ++i, collector = "c"; For[j = i, j < 90, j += 10, collector = collector <> path[i, j, j + 10] <> "c" ]; AppendTo[minions, collector]; For[newI = i + 1, newI < 10, ++newI, For[k = 0, k < 10, ++k, AppendTo[minions, path[i, j, 10 k + newI] <> "c" <> path[newI, 10 k + newI, newI] <> safetyCheck[i, 10 k + newI]] ] ] ]; StringRiffle[minions, "\n"] ``` I actually wrote all those `safetyCheck` lines by hand. But the first line of that Mathematica code is actually about 28,000 characters long and was itself generated by the following CJam code: ``` '{o q~]{-1:W; 2b200Te[W%2/{W):W;~\{ "{"W+","W)++",\">\"}"+ "{"W)+","W++",\"<\"}"+ @ }*{ "{"W+","WA+++",\"v\"}"+ "{"WA++","W++",\"^\"}"+ }*}%", "*"Labeled[DirectedEdge[#,#2],#3]&@@@{ }"S/\* ]o',oNoNo}/'} ``` (Which takes as input the 10 layouts hardcoded into the interpreter. [You can run the code online.](http://goo.gl/vLnBuh)) Code-generation-ception! ### Explanation For a start, have a look at [*this* CJam script](http://goo.gl/RqxCM2) to see what the mazes look like. My solution is based on one important observation: as long as we pick up items along a single column, we won't change between layouts, regardless of whether the cells are filled or not. In particular, as long as we move along the left-most column we'll remain in layout `0`. As long as we move along the next column, we'll remain in layout `1`. The tricky bit is how to ensure that we've *changed* between layouts, because we don't know which cells in column `1` have items on them (if any!). So here's the algorithm (starting on cell `0` in layout `0`): 1. Collect all items along the current column, ending up on the bottom row. This minion will never die. 2. Now for each cell to the right of the current column (trying them in column-major order), try moving there in the current layout, pick up an item there, then move to the top row in that new column using the new layout. If the attempted cell contained an item, the layout will have changed and we will successfully reach the new column and layout. Because the new (safe) position is at the top row, but all the attempts of finding the next column include 10 net upward moves, all other attempts will fail, so we can ignore them. If the attempted cell did not contain an item, in most cases, the minion will die during the attempt to reach the top row using the wrong layout, hence discarding this attempt. However, this is not always the case. For instance, the attempted cell might already be on the top row, so no moves were made on the new layout. Likewise, in some cases, the path from the attempted cell to the top row is short enough to be valid on both layouts. I've collected all the cases where this is an issue by hand, and determined a set of moves which is *only* valid on the new layout (but which moves the minion back to the target cell, so it's effectively a no-op on the new layout). After each attempt where this can be an issue, I perform this set of moves to kill off any minions which didn't collect an item on the attempted cell. 3. We've now successfully moved to the top of the next column which contains at least one item. Go back to step 1. You may notice that the structure of solution is as follows: ``` Line with 10 "c"s 90 lines with 1 "c" Line with 10 "c"s 80 lines with 1 "c" Line with 10 "c"s 70 lines with 1 "c" Line with 10 "c"s 60 lines with 1 "c" ... Line with 10 "c"s 10 lines with 1 "c" Line with 10 "c"s ``` As for the Mathematica code, the `safetyCheck` strings are those hand-picked moves which ensure that we've reached the new layout. The first parameter to the lookup is the layout we're starting from and the second one is the cell we've attempted. Any combinations which aren't mentioned explicitly just give an empty safety check (because none is necessary). In addition to that, I'm simply setting up the 10 mazes as `Graph` objects, where there are two directed edges between any adjacent (and connected) cells, where each edge is annotated with move required to traverse the edge. With that in place, I can simply find the paths using `FindShortestPath` and then extract the corresponding edge labels with `PropertyValue[..., EdgeLabels]`. The rest of the code just makes use of that to implement the above algorithm fairly directly. The actual graph data is stored in `layouts` and was generated with the CJam script, which decodes the numbers as described in the cop post and turns them into a Mathematica list, which can easily be transformed into a graph. [Answer] ## [HPR, by Zgarb](https://codegolf.stackexchange.com/a/62102/32700) The code: ``` #(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))#(#(!(-)(#(-)()))())(*!(-)(#(-)()))#(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))#(#(!(-)(#(-)()))())(*!(-)(#(-)()))#(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))!(#(*#(!(-)(#(-)()))())(!(-)(#(-)()))-)(#(#(*#(!(-)(#(-)()))())(!(-)(#(-)()))-)())#(!(-)(#(-)()))() ``` First of all ... the code was generated, not hand written (or typed). Facts about the language: * It is **not** Turing Complete. * You can't compare integers found in the environment. * You can compare integers in lists with integers in the environment. * You can't add elements to lists or change elements in lists. The program uses the following psuedocode: ``` global item global list = input() biggest() remove() biggest() remove() biggest() print() def remove(): while item != list[0]: rotate_list list.remove(0) def print(): rotate_list until item == list[0] do until no change: list.pop() subtract removeList() def biggest(): item = 0 while hasListWithElements(): if item < list1[0]: item = list1[0] list.remove(0) restore list ``` The environment almost always contains only 1 list and 1 integer. In order to solve this, I created a small macro engine for this language. It also allows comments. Here is the macro engine: ``` import sys code = {} filename = sys.argv[1] f = open(filename, 'r') prog = f.read() f.close() def c(prog): for n in prog.splitlines(): if n.startswith('def'): parts = n[4:].split(' ', 2) code[parts[0]] = int(parts[1]) ,parts[2] prog = prog.replace(n, '', 1) elif n.strip().startswith('//'): prog = prog.replace(n, '', 1) return compile(prog) def compile(prog): ret = '' while prog: n = prog[0] if n == '<': name = prog[1:prog.find('>')] args_count, formatter = code[name] if args_count == 0: prog = prog[prog.find('>') + 1:] ret += compile(formatter)[0] continue; prog = prog[prog.find('>') + 2:] args = [] for n in range(args_count): arg, prog = compile(prog) if n == args_count - 1: arg = arg[:-1] args.append(arg) ret += compile(formatter.format(*args))[0] elif n == ')': return ret + ')', prog[1:] elif n == ',': return ret, prog[1:] elif n == '(': c, prog = compile(prog[1:]) ret += '(' + c else: ret += n prog = prog[1:] return ret.replace('\n','').replace(' ',''), prog print(c(prog)[0]) #Use pipes to put into file. ``` After I built the macro engine, I slowly built up useful functions for this language. Here is the code that the engine processed to create the program: ``` //While loop def w 2 !({1})({0}) //Detects changes def c 1 #({0})() //Do while it changes: def wc 1 <w>(<c>({0}), {0}) //Remove all items: def rint 0 <wc>(-) //Contains list: def clist 0 <rint> //Remove all lists: def rlist 0 #(<rint>)() //Contains item: def cint 0 <rlist> //False (empty environment): def false 0 <rint><rlist> //Not: def not 1 !(<false>)({0}) //Bool (if expression does not evaluate to an empty environment, // restore the environment to its previous state. def bool 1 <not>(<not>({0})) //And def and 2 <bool>({0}){1} //Or def or 2 <not>(<and>(<not>({0}), <not>({1}))) //Combine parts (takes the integer parts of first argument and //combines them with the list parts of second argument): def p 2 #({0}<rlist>)({1}<rint>) //If, executes an expression if condition evalutates to true. Only works in standard environment. def if 2 <p>(!({1}<rlist>)(<and>({0}, <rint>)),!({1}<rint>)(<and>({0}, <rlist>))) //equal (compares item to list[0]) for equality: def eq 0 <not>(#(*)()<rlist>) //list.remove(0), does not change item: def listr 0 <p>(, *) //remove, removes item from list, goes into infinite loop if list does not contain item. def remove 0 <w>(<not>(<eq>), $)<listr> //Greater than or equal, item >= list[0]: def ge 0 <w>(<and>(<not>(<eq>), <rlist>), -)<rlist> //Less than, item < list[0]: def lt 0 <not>(<ge>) //Zero, sets item to zero: def zero 0 <p>(*<rlist>!(-)(-), ) //Biggest, puts biggest item in the list into item: def biggest 0 <zero><p>(<w>(<c>(*), <if>(<lt>, <p>(<rint>*, ))<listr>), ) //print item, item must be somewhere on list. def print 0 <w>(<not>(<eq>), $)<wc>(<p>(*, )-)<rlist> //The actual program!!!! <biggest> <remove> <biggest> <remove> <biggest> <print> ``` [Answer] # [Brian & Chuck by Martin Büttner](https://codegolf.stackexchange.com/a/63121/6683) The following Python 2.7 program outputs my Brian & Chuck program, by translating a brainfuck program into Brian & Chuck (with the exception that `.` always prints `1`, since that's the only character we need to output). Control flow works by magic having Brian write out on Chuck's tape commands to send Brian to the correct position in code. Note that whitespace and `[]`s added to the B&C program are decorative only. ``` def brainfuck_to_brianchuck(code): # find biggest jump needed biggest_jump = 0 idx = 0 while idx < len(code): if code[idx] == '[': end = matching_bracket(code,idx) jump = sum(c == '[' for c in code[idx:end]) if jump > biggest_jump: biggest_jump = jump idx = end idx += 1 block_size = biggest_jump*4 + 4 fragments = [] depth = 0 for idx,c in enumerate(code): if c in '<>': fragments.append(block_size*c) elif c == '[': end = matching_bracket(code,idx) jump = sum(c == '[' for c in code[idx:end]) fragments.append('\n' + ' '*depth) fragments.append('[ ' + open_while(jump)) depth += 1 fragments.append('\n' + ' '*depth) elif c == ']': start = matching_bracket(code,idx) jump = sum(c == '[' for c in code[start:idx]) depth -= 1 fragments.append('\n' + ' '*depth) fragments.append('] ' + close_while(jump)) fragments.append('\n' + ' '*depth) elif c == '.': fragments.append('>' + write('0>.?',True) + '<<<?1<<<' + write('0>.?',False) + '<<<<') elif c in ',+-': fragments.append(c) return ''.join(fragments) + '\n```' def open_while(jump): fragments = [] right = '0' + '}>}>'*jump + '?' fragments.append('>' + write(right,True)) r = len(right)-1 fragments.append('<'*r + '?' + '_0') left = '{<{<'*jump + '>>?' l = len(left)-1 fragments.append('<'*l) fragments.append(write(left,False)) fragments.append('<'*l + '<') return ''.join(fragments) def close_while(jump): fragments = [] right = '0' + '}>}>'*jump + '?' fragments.append('>' + write(right,True)) r = len(right)-1 fragments.append('_0' + '<'*r) fragments.append(write(right,False)) fragments.append('<'*r) left = '{<{<'*jump + '>>?' l = len(left)-1 fragments.append(write(left,True)) fragments.append('<'*l + '<' + '?>') fragments.append(write(left,False)) fragments.append('<'*l + '<') return ''.join(fragments) # returns the code to write s, or erase it if increment is False def write(s,increment): c = '+' if increment else '-' return '>'.join(c*ord(a) for a in s) def matching_bracket(code, idx): bracket = code[idx] other_bracket = ']' if bracket == '[' else '[' direction = 1 if bracket == '[' else -1 idx += direction while code[idx] != other_bracket: if code[idx] == bracket: idx = matching_bracket(code, idx) idx += direction return idx print brainfuck_to_brianchuck(''' - >,------------------------------------------------[ ,------------------------------------------------[ ->+>>>[>+<<<<->>>-]<[>+<<<->>-]<[>+<<->-]>>>[<+>-]<<<<[>+<-] >>>>>,------------------------------------------------ ] <+[-<<<<<<+]- >,------------------------------------------------ ] >>>>[.>>>>>>]. ''') ``` [Answer] # [Firetype, by kirbyfan64sos](https://codegolf.stackexchange.com/a/62013/8478) Working, commented code: ``` _ Beginning of the loop where one iteration reads one unary number. - Decrement to cancel the next +, which is part of the loop. + Increment... this is executed once for each 1 we read. , Read a character. ^ "eval" # Negate. * Double three times to get -8 if we read a 1 and 0 otherwise. * * % If we read a 1, jump back to the +. Otherwise, continue. # Negate the resulting number to reverse the sort order later. ` Duplicate... ~ Logical NOT twice, to turn non-zero results into 1 (zeroes remain zeroes). ~ * Double, double, square, double, negate, to get -32 if the last number * we read was non-zero. The double-0 at the end of the input leads to a | zero being read as a unary number, which we use as the termination * condition. When this is the case, the current cell will be 0 instead # of -32. The next lines are padding to get the jump right... % So... if the unary number was not 0, jump back to the _. \ Sort the list... the sort is descending, but we negated all the values... < That means the largest value next to the pointer now, just with a minus < sign. We move to the left three times to find the place where the third < largest value is. # Negate to get its positive value again. ` Duplicate to ensure we've got a cell to the left of the result. < Move left to the other copy. ~ Logical NOT twice, to turn it into a 1. ~ > Move right to the result. ! This moves the pointer to the left (onto the 1) and executes "." (print) . "result" times, printing the result in unary. Yay! ``` This relies on the interpreter as currently provided in the cop's answer, which slightly contradicts the documentation regarding `%` and `!`. The main challenge here was parsing the input, since the `\` makes finding the third-largest value fairly simply. [Answer] # [Acc!, by DLosc](https://codegolf.stackexchange.com/a/62404) This langauge has **terrible** comparison support. ``` Count b while 0 { } Count c while 0 { } Count a while N-48 { Count q while N-48 { } Count a while _ { _ - 1 } a - (q + 1) Count z while (z-(10^6+1)) * (_ - z) { } Count x while (_ - z) { b Count c while _ { _ - 1 } a Count b while _ { _ - 1 } q Count a while _ { _ - 1 } z } z-((10^6)+1) Count x while _ { b - (q + 1) Count f while (f-(10^6+1)) * (_ - f) { } Count x while (_ - f) { b Count c while _ { _ - 1 } q Count b while _ { _ - 1 } f } f-((10^6)+1) Count x while _ { c - (q + 1) Count k while (k-(10^6+1)) * (_ - k) { } Count x while (_ - k) { q Count c while _ { _ - 1 } k } 0 } 0 } 0 Count j while (a - _) { _ + 1 } } c Write 49 Count h while _ { Write 49 _ - 1 } ``` The `count [varname] while 0` statements at the beginning are to declare the variable holding the largest number, the second largest number, the third largest number, and so on. The comparisons are accomplished by subtracting the two numbers then checking if the result is negative by checking if it is a number less that `10^6`. [Answer] ## [Zinc, by kirbyfan64sos](https://codegolf.stackexchange.com/a/62159/32014) This was not that hard, once I understood how the language works. The difficult part was to get though parser errors, but adding some superfluous parentheses seemed to fix that. Here's the solution: ``` let +=cut in {d:{c:({b:{a:S^((#S)-_)-1}^_})+0$#c}^_=2} ``` ## Explanation In the first and second rows, I define `+` to be the `cut` operation. The rest is set comprehensions. Let's take the input `101011101100` as an example, and start from the innermost one: ``` {a:S^((#S)-_)-1} ``` This takes those elements `a` from the input set `S = {1,0,1,0,1,1,1,0,1,1,0,0}` whose index is not `len(S)-1`, so all but the last one. I noticed that this also reverses the set, so the result is `A = {0,1,1,0,1,1,1,0,1,0,1}`. Next, the comprehension ``` {b:A^_} ``` takes all elements of `A` except the first and reverses it again, resulting in `B = {1,0,1,0,1,1,1,0,1,1}`. Then, we split `B` at the `0`s (this results in `{1,1,{1,1,1},{1,1}}` or its reversal, I didn't check which one), and sort the result by length. Singleton sets are flattened, but they are all `1`s so their length is still 1. Here's the code: ``` {c:(B)+0$#c} ``` The result of this is `C = {{1,1,1},{1,1},1,1}`. Finally, we filter out everything except the element at index 2 by ``` {d:C^_=2} ``` This results in the set `D = {1}` on our case. In general, it can have the form `{{1,1,..,1}}`, but this doesn't matter since only the `1`s are printed. [Answer] # [Compass Soup, by BMac](https://codegolf.stackexchange.com/questions/61804/create-a-programming-language-that-only-appears-to-be-unusable#62557) This was fun. Edit: this program must be prepended with a new line in order to work on BMac's interpreter. I can't seem to get the new line to appear in the code block. ``` !p#eXj0sXj0sp#exj#ss n Apw w n w s w s w s w s w s w e s eXj0seXj0sn ep0Yp+yXj0nYp#exj+sneXp exj#seXj+snep+eXj#sxj+nseXp exj#ss n w ej#ns e n n w e n n w n w n w s w e s y s Yw eXj+np yjCs C n ejBs B pC n e A pB n ej0n 0 pA n s w e s exj#s X eXj#nsejCsp1s n w n w w w @> # ``` The program is divided into 4 execution sections. The first, at line 1, appends a `#` to the end of the input by finding `00` and replacing the 2nd `0` with `#`. It also changes all `1`s to `A`s, since I wanted to have as few `1`s in the source code as possible. The second section, at line 5, fetches the second number in the input, and puts it below the first number as a string of `+`s. For example, if the input is `11011101100`, then it will result in the following: ``` #AA00000AA0# #+++ ``` The third section, at line 12, combines the string of `+`s with the first number: each `0` above a `+` becomes `A`, `A` becomes `B`, `B` becomes `C`, and `C` remains unchanged. Afterwards, we go back to the 2nd section to fetch the next number. Once all numbers have been combined this way, we reach the final section at line 18. The number of `C`s is our desired output, so we change these to `1`s, skipping the first `C` because there is a single `1` in the source code which is printed along with the output. ]
[Question] [ #### Story My local pizza delivery introduced new discount. You get 50% discount from every second item on your order. But being greedy capitalists, they forgot to mention that they will rearrange items the way they need to give you as little as possible. #### Example Imagine you ordered ``` - Pizza $20 - Pizza $20 - Coke $2 - Coke $2 ``` You expect to get $10 discount from the second pizza and $1 from the coke, but they rearrange it as ``` - Pizza $20 - Coke $2 - Pizza $20 - Coke $2 ``` and give you $2. #### Trick Later I noticed that I can place as many orders as I want simultaneously, so I just split my order into two: ``` 1. - Pizza $20 - Pizza $20 2. - Coke $2 - Coke $2 ``` and I got the discount I deserve. #### Problem Can you please help me to write a program that calculate the maximum discount I can get by splitting my order. It should accept a list of prices and return an amount. For simplicity, all prices are even numbers, so the result is always an integer. Order is never empty. Input have no specific order. This is code golf, do all usual rules applies. #### Testcases ``` [10] -> 0 [10,20] -> 5 [10,20,30] -> 10 [2,2,2,2] -> 2 [4,10,6,8,2,40] -> 9 ``` [Answer] # [Python 3](https://docs.python.org/3/), 33 bytes ``` lambda a:sum(sorted(a)[-2::-2])/2 ``` [Try it online!](https://tio.run/##NYfLCsMgEEXX6VcMWSmMNJ3shORHrAtDIh1oNKhZ9OvNA8qBc@7dfuUTQ1/98K5ft06zA6fzvoocU1lm4aRRpLUiK59UfUzAwAGMoQ4JL1k0r@7Wef/F/pqEN9bqR7MlDkUwtqBGaNELlrIe "Python 3 – Try It Online") This is my first answer :D [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~11~~ 10 bytes −1 thanks to Jonah. Anonymous tacit prefix function. ``` ⌊∨+.÷∞2⍴⍨≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FP16OOFdp6h7c/6phn9Kh3y6PeFY86F/1Pe9Q24VFv36Ou5ke9a4DCh9YbP2qb@KhvanCQM5AM8fAM/p@moGNowJWmYGigYASnFYxBTCMIBAA "APL (Dyalog Extended) – Try It Online") `≢` the tally of item prices …`⍴⍨` use that to reshape…  `0∞` the list `[0,infinity]` …`+.÷` sum the division of the following by that:  `∨` the item prices sorted into descending order `⌊` floor (because the infinity is actually just the largest representable float and thus the values are slightly too large) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` {RιθO; ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/OujcznM7/K3//482MtABIR2jWAA "05AB1E – Try It Online") Sort, `R`everse, split into even and odd indices, get second part, sum and take half. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṢU0Hƭ€S ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bmiVTBIxq3igqxT/8OHxZLhuZj//1syMCwxMF0 "Jelly – Try It Online") Based on [Adám's method](https://codegolf.stackexchange.com/a/233642/66833), so go upvote that as well ## How it works ``` ṢU0Hƭ€S - Main link. Takes a list L on the left ṢU - Sort L in descending order ƭ€ - Tie the previous 2 atoms, and alternate between the two for each element: 0 - At odd-indexed elements: Replace the element with 0 H - At even-indexed elements: Halve the element S - Sum ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes ``` sṘy½ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=s%E1%B9%98y%C2%BD&inputs=%5B20%2C20%2C2%2C2%5D&header=&footer=) [5 bytes](https://lyxal.pythonanywhere.com?flags=s&code=s%E1%B9%98y%C2%BD&inputs=%5B20%2C20%2C2%2C2%5D&header=&footer=) without the flag. Port of ovs's answer but with two key differences: * `y`, uninterleave, pushes both halves separately on the stack, so we don't need to get the second half * We have the `s` flag, so we don't need to sum the list in the code. ``` s # Sort Ṙ # Reverse y # Interleave ½ # Take half (vectorised) ``` [Answer] # [R](https://www.r-project.org/), 35 bytes Thanks to att for spotting a bug. ``` function(p).5*p%*%!rank(-p,,"f")%%2 ``` [Try it online!](https://tio.run/##K/qfklmcnF@aV2L7P600L7kkMz9Po0BTz1SrQFVLVbEoMS9bQ7dAR0cpTUlTVdUIrlojWcPIQAeEdIw0NbngwoYGSJxkIBeoRhNTSMcYTdRIxwjdKLANhhCl/wE "R – Try It Online") Takes the dot-product (`%*%`) of `p/2` and a vector of 0s and 1s, with the 1s at the positions corresponding to even ranks in the sorted version of `-p`. We need to use `.5*p` instead of `p/2` because of operator precedence. The `"f"` is needed to handle ties correctly in the vector of ranks. Dominic van Essen [also has an R answer](https://codegolf.stackexchange.com/a/233656/86301), with a different strategy, currently at 36 bytes. [Answer] ## [Perl 5](https://www.perl.org/), ~~49~~ ~~44~~ 43 bytes ``` sub f{@_=sort$a-$b,@_;pop;pop()/2+(@_&&&f)} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/uDRJIa3aId62OL@opFolUVclqdYh3rogvwCENTT1jbQ1HOLV1NTSNGv/FydWKqRpGBpoWnPBmDoKRuhcHQVjhJARUASCEEIGEAEDiOB/AA "Perl 5 – Try It Online") -6 thanx to @kjetil-s; [previous](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/uDRJIa3aId62OL@opFol0cbWTiWp1iHeuiC/AIQ1NPWNtDUc4tXU0oCkpmbt/@LESoU0DUMDTWsuGFNHwQidq6NgjBAyAopAEELIACJgABH8DwA "Perl 5 – Try It Online"). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` -Tr@Sort[-#/2][[2;;;;2]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XzekyCE4v6gkWldZ3yg2OtrIGgiMYmPV/gcUZeaVRCvr2qU5KMeq1QUnJ@bVVXNVGxrU6oBIHSMEQ8cYzDbSAUMw0wDEAhK1XLX/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org/), 36 bytes ``` function(p)sum(-sort(-c(p,0))*0:1)/2 ``` [Try it online!](https://tio.run/##ZYxLCoAwDAX3niSRFNO4EzxNROjCtvRz/loRRBTeZobhpba5rKH6sra9ei0ueIiY6wEmh1TAKERixJEXi5M8OSgI0zUSxOHRll@gHXuDf0XzxwrJfdVO "R – Try It Online") Assumes the price of each item in the order is non-negative. [Answer] ## [Perl 5](https://www.perl.org/), ~~66~~ 64 bytes ``` use List::Util pairmap,sum;sub f{sum+pairmap{$b/2}sort{$b-$a}@_} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYA1m@mQWl1hZhZZk5igUJGYW5SYW6BSX5loXlyYppFUDWdpQ0WqVJH2j2uL8ohIgS1clsdYhvvZ/cWKlQpqGoYGmNReMqaNghM7VUTBGCBkBRSAIIWQAETCACP4HAA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` W⁻θυF№ι⌊ι⊞υ⌊ιI⊘ΣEυ×ι﹪κ² ``` [Try it online!](https://tio.run/##VYyxDsIwDER3vsKjI4Wla8cuLJUqwVZ1iNqgWCQ1JHX5/GDoxOmWu3e6Obg8s4u1vgNFD9jTKgVfFsQYuHMG7FjWDcmCIkqSkIyiQUpA@Svb05BJp50rG15c3P2CV0W9e36XN0q@/H54kcj4sNCYQ22t49hoPjxN9bzHDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W⁻θυF№ι⌊ι⊞υ⌊ι ``` Sort the input in descending order. ``` I⊘ΣEυ×ι﹪κ² ``` Multiply each value by its index modulo 2, then take half the sum. [Answer] # JavaScript (ES6), 49 bytes ``` f=a=>1/a.sort((a,b)=>a-b)?0:a.pop(a.pop())/2+f(a) ``` [Try it online!](https://tio.run/##bYzNCsIwEITvPkWOu5jmT7wIqQ8iOWxrI0rphqb09SMk3uoMzOUbvg/tlMf1nbZu4edUSvTke6tJZV43AJID@p66Ae/mRipxgraI2p0jEJaRl8zzpGZ@QYSHNUHUIAqthTkduHT10vj1L5cXExq3B4GTteEncOUL "JavaScript (Node.js) – Try It Online") ### How? Because `sort()` operates in lexicographical order by default, we unfortunately need the explicit callback function `(a, b) => a - b`, although all test cases would pass without it. We can stop as soon as the array is empty or only one element remains. Hence the test `1 / a` which evaluates to: * `Infinity` (truthy) if the array is empty * A positive float (truthy) if the array is a singleton * `NaN` (falsy) when at least 2 elements remain Because the `.pop()` method ignores its argument(s), the expression `a.pop(a.pop())` simply discards the last element and returns the penultimate one. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes ``` /+`%~>>\`<_~ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWa_S1E1Tr7OxiEmzi6yBCUJkFN9UNDbgMDRSMoKSCsQGXkQIYcpkoAIXMFCyAHBMDiHoA) ``` /+`%~>>\`<_~ _ Input as a list of numbers `< Sort \ Reverse >> Remove first item `%~ Take every odd-indexed item + Sum / ~ Halve ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ṁ½Ċ2Θ↔O ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY2H9h7pMjo341HbFP////9HRxvpAKEBEMXqRBtCCBgHJG4MYoLV6BjFxgIA "Husk – Try It Online") ``` O # sort in ascending order ↔ # reverse Θ # prepend a zero Ċ2 # get every 2nd element, starting at the first ṁ½ # halve each of these, and then sum the results ``` [Answer] # [PHP](https://php.net/), 68 bytes FWIW, as small I can go down in PHP. ``` function d($a){rsort($a);for($c=0;$b=$a[++$i]/2;$i++)$c+=$b;echo$c;} ``` [Try it online!](https://tio.run/##dY5NCsIwEIX3PUUps0hIxFqLCGPwCB6gltIm/dskoakr8erGpFuVgcfwfTx4drL@crUhh4eW62x0qgi09Lk4s6zxw8EsBKTIEToBbcUYzPW@QJgZoyCZgA57ORmQ@PKKVIe8pphEkmZ3nWGyMV78w/z4wxR8u29R8lA68XOwZex5/zY2znZ@p1I3hdGNsb1u1nZ04qY/ "PHP – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` êzhrg¥§Σ½ ``` [Try it online.](https://tio.run/##y00syUjPz0n7///wqqqMovRDSw8tP7f40N7//w0NuAwNdIygpI6xAZeRDhhymegAhcx0LIAcEwMA) **Explanation:** ``` ê # Read the inputs as integer-list z # Sort this list in decreasing order h # Push the length of the list (without popping the list itself) r # Pop and push a list in the range [0, length) g # Filter this list by: ¥ # Modulo-2 (only keep the odd values) § # Use those to index into the decreasing ordered input-list Σ # Sum this list ½ # Halve the sum # (after which the entire stack - this value - is output implicitly as result) ``` [Answer] # TI-Basic, 27 bytes ``` Prompt A SortD(ʟA sum(ʟAseq(fPart(I/2),I,0,dim(ʟA)-1 ``` Output is stored in `Ans` and is displayed at the end. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ~ỤỤ~ḂHḋ ``` [Try it online!](https://tio.run/##y0rNyan8/7/u4e4lQFT3cEeTx8Md3f8Pt2tG/v8fbWgQq6MQbWSgA2EYGugA2cYQQR0FKALxTIAqdMx0LHSMdEwMYgE "Jelly – Try It Online") Or, more to the point, `ỤỤ^LḂḋH`. Turns out, there's a ton of 7-byters--and when that's the case, it really seems like there ought to be one in 6. I wouldn't normally post this until I've found something that does beat [the existing solution in 7](https://codegolf.stackexchange.com/a/233644/85334), but it's continued to elude me, and this is at least different enough for someone else to maybe springboard off of. ``` ỤỤ Get a permutation of [1 .. len(input)] in the same order as ~ the bitwise negation of the input. ~Ḃ Is the bitwise negation of each element odd? H Halve the results, ḋ and take the dot product with the input. ``` Bonus in-between: `ṢUḊm2SH` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~100~~ ~~78~~ 73 bytes (maybe 74 bytes because of the L"!") ``` r;f(a,l)int*a;{qsort(a,l,4,L"\x72b068bǃ");for(r=0;l--;++a)r+=*++a/2;r=r;} ``` [Try it online!](https://tio.run/##bVLLTsMwELzzFatIlfJwRJu0vEzggLjxB20PwXVKVLcF24eoVU58HH9F2NhxcQVR4mhnvDvjXbN0zVjXSVqFJRFRvdNxSY8fai91D5ApeQkWzXX2Or66ef36DCJa7WUoizEVaUqTpIxkUsT4v8yoLCRtu21Z78IIjheAD9YDzZWezJdQwHEybomJMxcTyByW@xiB3OFTi2cI27clcY8ri5vyQ9Wh0JDXEuPBBMJuVvWB7ytr6dIG8VDAozKfys6o3KfyM2rqUydx3rxzpvnK6uO5ZgTMEYcNMXvjbMOl5bHXz9miuX3CbxYQ8OM8aEm9W/EGm29ScRIQUjAY3DsrTtC5cTGFJDFb3WyG@cSwRWXbUMMvyYkGMVDiLxVr5FgpxJ6FeE8ieqLeJZatwmAeeKAx21@HGtPG6BodC@Mp@q3pJY/UaIUNqB/7LtwFuOp5vSy2uPwjtYT0AXy5XkmhUhVqAiLyfXOET1Oxx/pbcLSCkVrsUFYRcCNSRcGdenvRdt@sEuVademBN5wpXbLNDw "C (gcc) – Try It Online") Saved a whopping 22 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~43~~ 30 bytes saved 13 bytes thanks to the comment. adapted from [@Basto's answer](https://codegolf.stackexchange.com/a/233649/110802) --- 30 bytes: ``` a->-[0..#a-1]%2/2*vecsort(-a)~ ``` [Try it online!](https://tio.run/##XYzBCsIwEETv/YqlRUhktybpQaSkPxJyCGIkILakwYvor8ek0IsszL4ZhllcDHRfstfv7GgiI/q@cyTtQZ3U8XW7rnNMjBz/5g9A8whrAg3GKIEKq1g0Z5QS5YCywKX4Pyc2KeX941BR4XbWjo2fIwtaInR1H2GJ4ZlYZRMsQgs0QYvg94hzPuYf) 34 bytes: ``` a->[0..#a-1]%2/2*vecsort(-a)~*(-1) ``` [Try it online!](https://tio.run/##XYzBCoMwEETvfsWiFBLZtW48SJH4IyGHUJoSKFWi9FLaX0@N4KUszL4ZhpldDHSfk9fv5Gg0bdNUjtie1FnVr9t1meIqyMlvLYhl@gAUj7CsoMEY1aLCLBZNj8zIHfIGl83/uXaXrXx87DIq3M/aofBTFEEzQpX3EeYYnqvIbIJFKIFGKBH8EUkph/QD) --- 43 bytes: ``` a->sum(i=0,(#a-2)\2,vecsort(a)[#a-1-2*i])/2 ``` [Try it online!](https://tio.run/##XY7BCoMwEETvfsWil6RMqFkPRUR/JM0hlFoCbZVoeyn99jQRvJSF2TfDMuzsgle3OY79Jzo1LK@H8H0NUTnF8sx4Xy/LFFbhpEmRVnzwVh45fomKu19W6skYrsHIYmFO0Bq6gU7QJv/n6k3S8b7RZGRsY21XjFNIL2hQlftBc/DPVWQ23oJKUgOVoHGPpJRd/AE) --- It calculates the sum of alternating elements in the input array `a` after sorting it in decreasing order. [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` f=->l{*l,a,b=l.sort;b ?a/2+f[l]:0} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6nWitHJ1EnyTZHrzi/qMQ6ScE@Ud9IOy06J9bKoPZ/gUJadLShgY6RDoiIjeWCCxjoGBvExv4HAA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) +1 byte to handle unsorted inputs. ``` ñÍË*½*Eu ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8c3LKr0qRXU&input=WzIwLDEwLDMwXQ) [Answer] # [jq](https://stedolan.github.io/jq/), 37 bytes ``` sort|.[range(length-1;-1;-2)]=0|add/2 ``` [Try it online!](https://tio.run/##yyr8/784v6ikRi@6KDEvPVUjJzUvvSRD19AahIw0Y20NahJTUvSN/v@PNjSI5QISOkZwWscYxDTSAUMgy0QHKGymYwHkmhjEAgA "jq – Try It Online") [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 17 bytes ``` mF(//2)<cr<uaL<sr ``` ## Explanation This is a very simple chain of operations: * `sr` sorts the input. * `uaL` divides it into two lists, those at even indices and those at odd indices. * `cr` gets the even indices. * `mF` sums them together using a custom function ... * `(//2)` divides by 2. ## Reflections Ok so there's a lot to reflect on. The fact that `uaL` exists is basically just dumb luck. I made `uaL` because I needed it to make something else and I just gave it a name because I thought it could come in handy at some point. If it didn't exist this would be a lot longer. Initially I was going to use `im` which takes a list and a list of indices and produces a list of all the indices. This would have been pretty cumbersome. We probably need a couple of index / slicing builtins because next time we probably won't be as lucky that something like `uaL` just happens to exist. Next up is dividing by 2. Arithmetic is something I haven't put a lot of time into so I know it's lacking. However, there should be builtins to divide things by small amounts. `dv2` should exist and would have saved a byte. I also noticed that `fdv` a function that is supposed to be the flip of `dv` is exactly the same as `dv`. This is just a bug. So there's a lot to work on here. [Answer] # [Arturo](https://arturo-lang.io), 35 bytes ``` $=>[/∑map reverse sort&[x,y][y]2] ``` [Try it](http://arturo-lang.io/playground?tldKA4) Same method as most of the other answers. Sort, reverse, take every other element, sum, and halve. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes ``` z;ZlAKS2/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrq6yjchy9g430IXyo8ILV0UYGOiCkYxQLEQIA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLsOs9qlygfJQVdXTsFpSifpaUlaboWK6uso3IcvYON9CH8RVHeEMaCm8XRhgaxCshAGajTgAsorGOELAMSNoUK6xjDZUDChkDlRjpgGIus3Igr2kQHqMFMxwIoZwLSAxK2hNgNAA) Port of [ovs's 05AB1E answer](https://codegolf.stackexchange.com/a/233646/114446) #### Explanation ``` z;ZlAKS2/ # Implicit input z; # Reverse-sort Zl # Uninterleave AK # Last item S # Sum 2/ # Halve # Implicit output ``` [Answer] # Java, 86 bytes ``` L->{int s=0,i=L.size();for(L.sort((a,b)->a<b?1:-1);i-->0;)s+=i%2*L.get(i);return s/2;} ``` [Try it online.](https://tio.run/##ZZBRa8IwFIXf/RUXYZDMNNNOxrC2Y@xp0Pni49hDWqPE1USSWzcn/vYubdXpJBC4J19yTs5SbESwnH1WeSGcgzeh9K4DoDRKOxe5hEk9NgLkZOlpXqIqeKocjl89tZA2gZRGntp3/OZQoMphAhriKg2SXX3TxX2m4pQ79SMJjebGEj8Yi4QIltEgEePsaTAKBjRSQZD0I@p6sboJb1O@kEgUjazE0mpwd2G0r6LaaF1mhTc6@G2MmsHKpydTtEov3j8EbZOjdEgG/SbhaWLhtcDuL7SQNetcGjIPPrBHrw8v2eb@kT7vocnVML4Hzvkx1UZY3@m6xLpIiEHLL/hr99lasb2omPw7dNyhlWJFBOWZ@ZYzQnluikLmeIa2DH9pD4x1HE39LKH0EH@6dShX3JTI1743LPS1E5q2U@/V646g29M8J6fw9PDnffUL) **Explanation:** ``` L->{ // Method with Integer-List parameter and Integer return-type int s=0, // Sum-integer, starting at 0 i=L.size(); // Index-integer, starting at the size of the input-List for(L.sort( // Sort the input-List (a,b)->a<b?1:-1); // in reversed order i-->0;) // Loop `i` in the range (size,0]: s+= // Increase the sum by: i%2 // Check if the current `i` is odd (1 if odd; 0 if even) *L.get(i); // And multiply that to the current `i`'th value return s/2;} // After the loop, return halve the sum ``` ]
[Question] [ *Taken from [this question](https://stackoverflow.com/q/38739122/2586922) at Stack Overflow. Thanks also to @miles and @Dada for suggesting test inputs that address some corner cases.* ### The challenge Given an array of integer values, remove all zeros that are not flanked by some nonzero value. Equivalently, an entry should be kept either if it's a nonzero or if it's a zero that is immediately close to a nonzero value. The entries that are kept should maintain in the output the order they had in the input. ### Example Given ``` [2 0 4 -3 0 0 0 3 0 0 2 0 0] ``` the values that should be removed are marked with an `x`: ``` [2 0 4 -3 0 x 0 3 0 0 2 0 x] ``` and so the output should be ``` [2 0 4 -3 0 0 3 0 0 2 0] ``` ### Rules The input array may be empty (and then the output should be empty too). Input and output formats are flexible as usual: array, list, string, or anything that is reasonable. Code golf, fewest best. ### Test cases ``` [2 0 4 -3 0 0 0 3 0 0 2 0 0] -> [2 0 4 -3 0 0 3 0 0 2 0] [] -> [] [1] -> [1] [4 3 8 5 -6] -> [4 3 8 5 -6] [4 3 8 0 5 -6] -> [4 3 8 0 5 -6] [0] -> [] [0 0] -> [] [0 0 0 0] -> [] [0 0 0 8 0 1 0 0] -> [0 8 0 1 0] [-5 0 5] -> [-5 0 5] [50 0] -> [50 0] ``` [Answer] ## JavaScript (ES6), 35 bytes ``` a=>a.filter((e,i)=>e|a[i-1]|a[i+1]) ``` Works on floats too for two extra bytes. [Answer] ## Python, 50 bytes ``` f=lambda l,*p:l and l[:any(l[:2]+p)]+f(l[1:],l[0]) ``` A recursive function that takes a tuple. Includes the first element if there's a nonzero value among either the first two elements or the previous value stored from last time. Then, removes the first element and recurses. The previous element is stored in the singleton-list `p`, which automatically packs to list and starts as empty (thanks to Dennis for 3 bytes with this). --- 55 bytes: ``` lambda l:[t[1]for t in zip([0]+l,l,l[1:]+[0])if any(t)] ``` Generates all length-3 chunks of the list, first putting zeroes on the start and end, and takes the middles elements of those that are not all zero. An iterative approach turned out longer (58 bytes) ``` a=0;b,*l=input() for x in l+[0]:a|b|x and print(b);a,b=b,x ``` This doesn't exactly work because `b,*l` needs Python 3, but Python 3 `input` gives a string. The initialization is also ugly. Maybe a similar recursive approach would work. Unfortunately, the indexing method of ``` lambda l:[x for i,x in enumerate(l)if any(l[i-1:i+2])] ``` doesn't work because `l[-1:2]` interprets `-1` as the end of the list, not a point before its start. [Answer] ## Haskell, ~~55~~ 48 bytes ``` h x=[b|a:b:c:_<-scanr(:)[0]$0:x,any(/=0)[a,b,c]] ``` Usage example: `h [0,0,0,8,0,1,0,0]` -> `[0,8,0,1,0]`. `scanr` rebuilds the input list `x` with an additional `0` at the start and end. In each step we pattern match 3 elements and keep the middle one if there's at least one non-zero element. Thanks @xnor for 7 bytes by switching from `zip3` to `scanr`. [Answer] # Matlab, ~~29~~ 27 bytes The input must consist of a `1*n` matrix (where `n=0` is possible). (It will throw an error for `0*0` matrices.) ``` @(a)a(conv(a.*a,1:3,'s')>0) ``` > > Convolution is the key to success. > > > [Answer] # J, ~~17~~ 14 bytes ``` #~0<3+/\0,~0,| ``` Saved 3 bytes with help from @[Zgarb.](https://codegolf.stackexchange.com/users/32014/zgarb) ## Usage ``` f =: #~0<3+/\0,~0,| f 2 0 4 _3 0 0 0 3 0 0 2 0 0 2 0 4 _3 0 0 3 0 0 2 0 f '' f 0 0 0 8 0 1 0 0 0 8 0 1 0 ``` ## Explanation ``` #~0<3+/\0,~0,| Input: array A | Get the absolute value of each in A 0, Prepend a 0 0,~ Append a 0 3 \ For each subarray of size 3, left to right +/ Reduce it using addition to find the sum 0< Test if each sum is greater than one (Converts positive values to one with zero remaining zero) #~ Select the values from A using the previous as a mask and return ``` [Try it here.](http://tryj.tk) [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` tg3:Z+g) ``` Output is a string with numbers separated by spaces. An empty array at the output is displayed as nothing (not even a newline). [Try it online!](http://matl.tryitonline.net/#code=dGczOlorZyk&input=WzIgMCA0IC0zIDAgMCAwIDMgMCAwIDIgMCAwXQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0ZzM6WitnKQpEVA&input=WzIgMCA0IC0zIDAgMCAwIDMgMCAwIDIgMCAwXQpbXQpbMV0KWzQgMyA4IDUgLTZdCls0IDMgOCAwIDUgLTZdClswXQpbMCAwXQpbMCAwIDAgMF0KWzAgMCAwIDggMCAxIDAgMF0KWy01IDAgNV0KWzUwIDBd). ### Explanation The code converts the input to logical type, i.e. nonzero entries become `true` (or `1`) and zero entries become `false` (or `0`). This is then convolved with the kernel `[1 2 3]`. A nonzero value causes a nonzero result at that position and at its neighbouring positions. Converting to logical gives `true` for values that should be kept, so indexing the input with that produces the desired output. ``` t % Input array implicitly. Duplicate g % Convert to logical: nonzero becomes true, zero becomes false 3: % Push array [1 2 3] Z+ % Convolution, keeping size of first input g % Convert to logical ) % Index into original array. Implicitly display ``` [Answer] # Jolf, 14 bytes Now that I think of it, Jolf is the Java of golfing languages. *sighs* [Try it here.](http://conorobrien-foxx.github.io/Jolf/#code=z4h4ZHx8SC5ud1MubmhT&input=WzIsMCw0LC0zLDAsMCwwLDMsMCwwLDIsMCwwXQ) ``` ψxd||H.nwS.nhS ``` ## Explanation ``` ψxd||H.nwS.nhS ψxd filter input over this function || or with three args H the element .nwS the previous element .nhS or the next element ``` [Answer] # Python 3, 55 bytes ``` lambda s:[t[1]for t in zip([0]+s,s,s[1:]+[0])if any(t)] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 0,0jo3\Tị ``` [Try it online!](http://jelly.tryitonline.net/#code=MCwwam8zXFThu4s&input=&args=WzIsIDAsIDQsIC0zLCAwLCAwLCAwLCAzLCAwLCAwLCAyLCAwLCAwXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=MCwwam8zXFThu4sKw4figqxH&input=&args=WzIsIDAsIDQsIC0zLCAwLCAwLCAwLCAzLCAwLCAwLCAyLCAwLCAwXSwgW10sIFsxXSwgWzQsIDMsIDgsIDUsIC02XSwgWzQsIDMsIDgsIDAsIDUsIC02XSwgWzBdLCBbMCwgMF0sIFswLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDgsIDAsIDEsIDAsIDBdLCBbLTUsIDAsIDVdLCBbNTAsIDBd). ### How it works ``` 0,0jo3\Tị Main link. Argument: A (array) 0,0 Yield [0, 0]. j Join, separating with A. This prepends and appends a 0 to A. o3\ Reduce each group of three adjacent integers by logical OR. T Truth; get the indices of all truthy results. ị At-index; retrieve the elements of A at those indices. ``` [Answer] ## Perl, 34 + 1 (`-p` flag) = 35 bytes ``` s/([^1-9]0 |^)\K0 ?(?=0|$)//&&redo ``` Needs -p flag to run. Takes a list of number as imput. For instance : ``` perl -pe 's/([^1-9]0 |^)\K0 ?(?=0|$)//&&redo' <<< "0 0 0 8 0 1 0 0 0 0 0 -5 0 5" ``` [Answer] ## Haskell, 48 bytes ``` p%(h:t)=[h|any(/=0)$p:h:take 1t]++h%t p%e=e (0%) ``` Looks at the previous element `p`, the first element `h`, and the element after (if any), and if any are nonzero, prepends the first element `h`. The condition `any(/=0)$p:h:take 1t` is lengthy, in particular the `take 1t`. I'll look for a way to shorten it, perhaps by pattern matching. [Answer] # [Retina](https://github.com/m-ender/retina), ~~42~~ ~~35~~ 33 bytes **7 bytes thanks to Martin Ender.** ``` (?<=^|\b0 )0(?=$| 0) + ^ | $ ``` The last line is necessary. [Verify all testcases at once.](http://retina.tryitonline.net/#code=bShHJWAKKD88PV58XGIwICkwKD89JHwgMCkKCl4gfCAkCgogKwog&input=MiAwIDQgXzMgMCAwIDAgMyAwIDAgMiAwIDAKCjEKNCAzIDggNSBfNgo0IDMgOCAwIDUgXzYKMAowIDAKMCAwIDAgMAowIDAgMCA4IDAgMSAwIDAKXzUgMCA1CjUwIDA) (Slightly modified to run all testcases at once.) Looks like the perfect language to do this in... still got defeated by most of the answers. [Answer] # Mathematica, 43 bytes ``` ArrayFilter[If[#.#>0,#[[2]],Nothing]&,#,1]& ``` [Answer] # C, 96 bytes Call `f()` with a pointer to the list of integers, and a pointer to the size of the list. The list and size are modified in-place. ``` i,t,e,m;f(int*p,int*n){int*s=p;for(i=m=e=0;i++<*n;s+=t=m+*s||i<*n&&p[1],e+=t,m=*p++)*s=*p;*n=e;} ``` [Try it on ideone](http://ideone.com/vFCel4). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~44~~ 38 bytes ``` ,0gL:?:Lc:1fzbh. ~c[A:.:B],[0:0:0]'.l3 ``` [Try it online!](http://brachylog.tryitonline.net/#code=LDBnTDo_OkxjOjFmemJoLgp-Y1tBOi46Ql0sWzA6MDowXScubDM&input=WzI6MDo0Ol8zOjA6MDowOjM6MDowOjI6MDowXQ&args=Wg) This language is good as proving things, which is what we will use. ### Predicate 0 (main predicate) ``` ,0gL:?:Lc:1fzbh. 0gL [0] = L (assignment works both ways) L:?:Lc [L:input:L] = temp :1f find all solutions of predicate 1 with temp as input zbh. then transpose and take the middle row and assign to output ``` ### Predicate 1 (auxiliary predicate) ``` ~c[A:.:B],[0:0:0]'.l3 ~c[A:.:B] input is in the form of [A:output:B] , and [0:0:0]'. output is not [0:0:0] .l3 and length of output is 3 ``` [Answer] # Matlab with Image Processing Toolbox, 27 bytes ``` @(a)a(~imerode(~a,~~(1:3))) ``` This is an anonymous function. Example use: ``` >> @(a)a(~imerode(~a,~~(1:3))) ans = @(a)a(~imerode(~a,~~(1:3))) >> ans([0 0 0 8 0 1 0 0]) ans = 0 8 0 1 0 ``` [Answer] # Bash + GNU utils, 25 ``` grep -vC1 ^0|grep -v \\-$ ``` Accepts input as a newline-separated list. [Ideone](https://ideone.com/zPEoVA) - with test driver code added to run all testcases together by converting to/from space-separated and newline-separated. [Answer] # [Cheddar](http://cheddar.vihan.org/), 78 bytes ``` a->([[]]+a.map((e,i)->e|(i?a[i-1]:0)|(i-a.len+1?a[i+1]:0)?[e]:[])).reduce((+)) ``` [Test suite.](http://cheddar.tryitonline.net/#code=dmFyIGYgPSBhLT4oW1tdXSthLm1hcCgoZSxpKS0-ZXwoaT9hW2ktMV06MCl8KGktYS5sZW4rMT9hW2krMV06MCk_W2VdOltdKSkucmVkdWNlKCgrKSkKcHJpbnQoZihbMiwwLDQsLTMsMCwwLDAsMywwLDAsMiwwLDBdKSkKcHJpbnQoZihbXSkpCnByaW50KGYoWzFdKSkKcHJpbnQoZihbNCwzLDgsNSwtNl0pKQpwcmludChmKFs0LDMsOCwwLDUsLTZdKSkKcHJpbnQoZihbMF0pKQpwcmludChmKFswLDBdKSkKcHJpbnQoZihbMCwwLDAsMF0pKQpwcmludChmKFswLDAsMCw4LDAsMSwwLDBdKSkKcHJpbnQoZihbLTUsMCw1XSkpCnByaW50KGYoWzUwLDBdKSk&input=&debug=on) Cheddar has no filter, so filtering is done by wrapping the elements we want and transforming the elements we don't want into empty arrays, and then concatenate everything. For example, `[0,0,0,8,0,1,0,0]` becomes `[[],[],[0],[8],[0],[1],[0],[]]`, and then the concatenated array would be `[0,8,0,1,0]`. [Answer] # APL, 14 bytes ``` {⍵/⍨×3∨/0,⍵,0} ``` Test: ``` {⍵/⍨×3∨/0,⍵,0}2 0 4 ¯3 0 0 0 3 0 0 2 0 0 2 0 4 ¯3 0 0 3 0 0 2 0 ``` Explanation: * `0,⍵,0`: add a zero to the beginning and the end of ⍵ * `×3∨/`: find the sign of the GCD of every group of three adjacent numbers (this will be 0 if they are all zero and 1 otherwise). * `⍵/⍨`: select all the items from ⍵ for which the result was 1. [Answer] # Ruby 2.x, 63 bytes ``` f=->(x){x.select.with_index{|y,i|x[i-1].to_i|y|x[i+1].to_i!=0}} ``` Credit where it is due, this is essentially a port of Neil's superior ES6 answer. It's also my first pcg submission. yay. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 142 bytes [Try it online!](http://brain-flak.tryitonline.net/#code=KDwoKT4pKCgpKXt7fShbXTwoW10pe3t9KHt9PD4pPD4oe308Pik8Pih7fTw-KTw-KDw-KHt9PD4pPD4oe308Pik8Pih7fSk8Pil7e30oKDwoKT4pKX17fXt9KFtdWygpXSl9e317fTw-e30oW10pe3t9KHt9PD4pPD4oW10pfXt9PD4-W1tdXSl9e317fQ&input=MiAwIDQgLTMgMCAwIDAgMyAwIDAgMiAwIDA) ``` (<()>)(()){{}([]<([]){{}({}<>)<>({}<>)<>({}<>)<>(<>({}<>)<>({}<>)<>({})<>){{}((<()>))}{}{}([][()])}{}{}<>{}([]){{}({}<>)<>([])}{}<>>[[]])}{}{} ``` ## Explanation ``` (<()>) #Pad the top with an extra zero (()){{}([]<...>[[]])}{} #Until the stack height remains the same ([]){{}...([][()])}{} #Until the stack height is one ({}<>)<> #Move the top three to the other stack ({}<>)<> ({}<>)<> (...) #Push the sum of the top three <>({}<>) #Move the second and third back <>({}<>) <>({})<> #Leave the top of the stack {{}...}{} #If the sum is not zero ((<()>)) #Add a buffer to the top of the stack {} #Pop the buffer/middle value {} #Remove extra zero <> #Switch to the off stack {} #Remove extra zero ([]){{}({}<>)<>([])}{}<> #Move the entire off stack back ``` ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/18360/78850) *Adapted from exercise 4 of [100 little Keg exercises](https://github.com/JonoCode9374/100-Little-Keg-Exercises)* The ability to repeat chunks of code within a program is an important part of any programming language. Also just as important is the ability to make decisions based on different values. ## The Challenge I want you to write a program that: * Starts at the number 0, and: * For each number from 0 to 100 (inclusive): * If the number is even, print the letter `E` (uppercase or lowercase) * Otherwise: print the number Keeping in the spirit of this challenge, your source code must fit the pattern of having characters with an odd ordinal value followed by characters with an even ordinal value. *Note that ordinal value is defined here as if I called python's `ord()` function on the character using your language's prefered code page.* In other words, the code points of your program should be as such: ``` Odd Even Odd Even Odd Even ... ``` or ``` Even Odd Even Odd Even Odd ... ``` More concisely, the code points of your program must alternate between being odd and even. ## Example Output ``` E 1 E 3 E 5 E 7 E 9 E 11 E 13 E 15 E 17 E 19 E 21 E 23 E 25 E 27 E 29 E 31 E 33 E 35 E 37 E 39 E 41 E 43 E 45 E 47 E 49 E 51 E 53 E 55 E 57 E 59 E 61 E 63 E 65 E 67 E 69 E 71 E 73 E 75 E 77 E 79 E 81 E 83 E 85 E 87 E 89 E 91 E 93 E 95 E 97 E 99 E ``` Output can be in any other convenient format with any other separator. Leading and trailing whitespace is acceptable. ## Script Validation (UTF-8 only) [Here is a Keg script to see if your program fits the parity pattern requirement](https://tio.run/##y05N//9fOTi5KLOgRCEtv0ihJLW4JDMvXaEgsSizpBJIlZSkFuUpJOcXFaUml@SlFhdzKYcWpxYrhIa46Vpw2WsYqVrpKegoaXLpGKpVKxra1ahYKanYGtiqaamp16pFJzhDdCoEQExKqEnwzEtGE4vV@f@/orKqsgIA "Keg – Try It Online") Note that this can only be used for languages that use utf-8 as their codepage. [Here is an alternate Haskell script written by @WheatWizard which can handle newlines and shows which characters are invalid.](https://tio.run/##bZBBS8QwEIXv/RWPsrApdCvqbbEgVm968iKI7I7psC2mSU1SFv3zNaldi7CXwMy8983LNOQ@WKlxbLveWI978lRUDdlkblRGe2tU8WQ01UlHrUaJ2iSADBPW3uFmgwP7ai7DRLEPL/DeencrGqb6rvXbXRacHfUQYt@Zeo@rDAWMrbM/1OQ6GFLRGdTySyrG60zIcYkN5uItaB1/Dqwl77D6jQQIGbLncXM@gYIyiwG/2/56STzhT3smn2U/WL1wgH7wz96GjmvMERG7DOKBsMb6rDQw5/6xYQ0RalyUS5rVSZ/iJf1HeNRI03EkIbeMeC2ZMAiloG2WOMjw/xIsKH1Isx8 "Haskell – Try It Online") [Here is a Python Script that tells you where you need to insert extra characters. (As well as the binary codes and the ord code of the characters)](https://tio.run/##bVJNb9swDD1Hv4JzUMACkqDJbgaMYhgKrJdhh96CYBBkularSYZEJ8tlfz0jEzvpPnwxKVKPj0@vP1IXw8fTaQ7PncuQbXI9AaH3GY5xgEOHCc9RQGyAopqDCxkTge1MMpYw5ZVSDbaw/96XXlcwh6cM1CH0hrgcYG@8ax7UrE@4hxr89n6nZm1M4BiL03W1q9Rs5lqIqSmdvtvAhxp@SSJXOJfyLCENjLbmeERyajq8v1LYjBw@QbnXmFx7hLLXIxPqDMEhprcMMj8OCeyQEgYC7zIJXB48MfT2D4oy/1Jamb7HwCx5CX0dL6tf6lqphKZhhKIoTGkrBM2JVQgG6tJUWmWwsOYzLE3xWGjuY7pfTGqWNjZnsXls6AcCEX@lWn/hQ@P/SksGMTPyE6mtW1wUXExCCkc36kJe1/VaVmmvN8hvq@Vauhim3v4HYKfU@3bebw5f8eBdwCwk5KHb6H08uPDCipIQd6Fx1hBy7z8OmvwjF28eEtjnM1T6Yai6VRZiChBlbhHcwUbddGjlfSR7lcxVZ4O4QOWrVmNU1OPH3H8SPO4xLGPDaN0Q3mAqFrzd2P/t4piqWPDedSEV1tFjKFuv2Z2i49j6FGxkD1maDM/N6DPeOj7/XT@dfgM) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the fewest amount of bytes wins. Let it be known that flags don't count towards being in the pattern. They also don't count towards byte count in this challenge. ## 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=197210; var OVERRIDE_USER=78850; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` x="E";z= 1 while z <101: x=x+ ["E" , f' {z} ' ] [z%2] ;z=z+ 1 exit ( x) ``` [Try it online!](https://tio.run/##RY1BCsMgFETX5hS/gaCSBmq6S@uypxAXITGNIBpEqLX07Na0iy7fDPNme4bV2XOe3Kw4xjhHXt/qS@LAqseqjQKU0JWd2IAijy2I0qIjWjC80hswSBCp6SWURWrLRkUdEEGR5iITbOiYrDavbSCjMcT5mexPQkva9Af@55btyeI8aNAW/GjvihhlvzXtGKW0uNX04/wB "Python 3 – Try It Online") Just by coincidence, `exit` and `while` are both available. The rest is just the program separated by spaces and tabs to make it alternate. I'm hoping it's forgivable to output as an exit code, since `print` is unavailable. [Answer] # JavaScript (ES6), 42 bytes Contains a literal `Tab`. ``` f= y =>y>98? ' E ':' E ' + -~y +f (1 -~y ) ``` [Try it online!](https://tio.run/##VY3LCsIwFETX9itmI72hbaCufJCKiF8hguGaaiQ00pZCNv56TLtzMxxmYM5bT3rg3n7GqvMPE82kHXEiKNxjqxCgmtDstkfkuCDfL4kC1TegaFdULyTiXQ7OsqG6RFULccgy9t3gnZHOP6klIf6Kq5Ry1tykmUwfiLiEFckFlvzS/Tltp5EE1thAKdgZ0m38AQ "JavaScript (Node.js) – Try It Online") [Answer] ## Ruby, 41 bytes ``` n= 1 eval'puts"E";p n;n=n+2; '*50;puts"E" ``` [Try it online!](https://tio.run/##KypNqvyfnJ@SamtjU/w/z1bBkCu1LDFHvaC0pFjJVcm6gDPPOs82T9vIWkFdy9TAGir@v5gLpEmvuKQos0CRiwskrAAWSS8uTVLQjynW11FQV1BHkkjOSCwq1stNLKiuSa5RSNbLL0pRNarVUoeo4QJbC1b5HwA) (with parity check) This builds a string that contains the code to output `"E"` and `n`, then add 2 to `n`. Then it multiplies the string by 50 (repeating it 50 times) and `eval`s it. Finally, it prints the last `"E"` at the end. [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` 69H!Vo:E q"c@y ``` [Try it online!](https://tio.run/##y00syfn/38zSQzEs38pVoVAp2aHy/38A) MATL uses ASCII encoding. The code points of the source code are ``` 54 57 72 33 86 111 58 69 32 113 34 99 64 121 ``` ### How it works ``` 69 % Push 69. This is the code point of 'E' H % Push 2 ! % Transpose: does nothing to 2 V % Convert to string: gives '2' o % Convert to double: gives code point of '2', which is 50 : % Range. Gives [1 2 ... 50] E % Multiply each element by 2. Gives [2 4 ... 100] % (Space:) Does nothing q % Subtract 1 from each element. Gives [1 3 ... 99] " % For each k in [1 3 ... 99] c % Convert to char. In the first iteration the top of the stack contains 69, % which is converted into 'E'. In subsequent iterations the top of the stack % contains 'E', which is left as is @ % Push current k y % Duplicate from below: pushes another copy of 'E' % End (implicit) % Display stack, botom to top (implicit) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~112~~ ~~105~~ 99 bytes The code produces a string as in the example. ``` [ c|s<-"E 1 E 3 E 5 E 7 E 9 E" :[ ' ':k:m:' ': "E" |k<-"123456789" ,m<-"1 3 5 7 9" ,m>' ' ],c<- s ] ``` I was not able to find a way to print an integer or convert it to string. This is why the solutions looks like this. [Try it online!](https://tio.run/##y0gszk7NyflfXFKkYKsQ8z9aIbmm2EZXyVXBUMFVwRiITYHYHIgtFVyVOK2iFdQV1K2yrXKtQDSnElCsJhuo3tDI2MTUzNzCUolTJxfEB@o1BeoD8@2AahVidZJtdBWKFWL/5yZm5gEtKygtCS4p8slTANr9/19yWk5ievF/3QjngAAA "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` т Ýxт>çÞ‡ ``` -2 bytes thanks to *@Grimmy*. Outputs as a list with lowercase `e`. [Try it online.](https://tio.run/##yy9OTMpM/f//YpPC4bkVF5vsDi8/PO9Rw8L/Xv8B) **Explanation:** Shortest base version I could find was **~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: [`тÝx'EÞ‡`](https://tio.run/##yy9OTMpM/f//YtPhuRXqrofnPWpY6PX/PwA) (Outputs as a list with uppercase `E`.) -1 byte thank to *@Grimmy*. ``` т # Push 100 Ý # Pop and push a list in the range [0, 100] x # Push a list with each value doubled (without popping the original list) 'E '# Push "E" Þ # Pop and push an infinite list of "E": ["E","E","E",...] ‡ # Transliterate each doubled number to "E" in the original list # (after which this list is output implicitly as result) ``` The codepoints of this 7-byter are [`[15,221,120,39,69,222,135]` / `[1,1,0,1,1,0,]`](https://tio.run/##ASEA3v9vc2FiaWX//8W@xIZJU2s9w4ks///RgsOdeCdFw57igKE), which is already pretty good. So I now have this: ``` т # Push 100 # No-op space Ý # Pop and push a list in the range [0, 100] x # Push a list with each value doubled (without popping the original list) т # Push 100 > # Increase it by 1 to 101 ç # Convert this integer to a character with this ASCII codepoint: "E" Þ # Pop and push an infinite list of "e": ["e","e","e",...] ‡ # Transliterate each doubled number to "e" in the original list # (after which this list is output implicitly as result) ``` This 9-byter has the codepoints: [`[15,32,221,120,15,62,231,222,135]` / `[1,0,1,0,1,0,1,0,1]`](https://tio.run/##ASUA2v9vc2FiaWX//8W@xIZJU2s9w4ks///RgiDDnXjRgj7Dp8Oe4oCh). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` V101p? %N/T5NK\E ``` [Try it online!](https://tio.run/##K6gsyfj/P8zQwLDAXkHVTz/E1M87xvX/fwA "Pyth – Try It Online") [Verify it online!](https://tio.run/##K6gsyfj/P1fVOcWo/P//MEMDwwJ7BVU//RBTP@8YVwA "Pyth – Try It Online") Separated by `""` ## How it works: ``` V101p? %N/T5NK\E V101 - For 'N' in 0..100 ? %N/T5 - If N modulo (10÷5) (or N%2) is truthy... N - ...return N K\E - Otherwise, return 'E' (K here is just a separator) p - Print the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ³Ż¹⁾E Ḥ‘{$¦ K ``` [Code-points](https://github.com/DennisMitchell/jelly/wiki/Code-page): `[131, 210, 129, 142, 69, 32, 175, 252, 123, 36, 5, 32, 75]` A full program, which given no arguments prints the result. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//wrPFu8K54oG@RSDhuKTigJh7JMKmIEv//w "Jelly – Try It Online")** (As a bonus given a non-negative integer argument it will print the sequence for that number, [e.g.](https://tio.run/##ASMA3P9qZWxsef//wrPFu8K54oG@RSDhuKTigJh7JMKmIEv///8xNg "Jelly – Try It Online")) ### How? ``` ³Ż¹⁾E Ḥ‘{$¦ K - Main Link: no arguments ³ - literal 100 (if there are arguments provided, this is the 1st) Ż - zero-range = [0,1,2,3,...,100] ¹ - identity (no-op) ¦ - sparse application... $ - ...to indices: last two links as a monad: Ḥ - double = [0,2,4,6,...,200] { - use left argument as input to: ‘ - increment = [1,3,5,7,...,201] (note Jelly uses 1-based indexing) ⁾E. - ...what: literal character pair = ['E', ' '] . - no-op K - join with spaces - implicit, smashing print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-trigraphs` flag, ~~161~~ 141 bytes Thanks to WheatWizard for the validation script, which revealed that I mistakenly identified line endings as `CR` instead of `LF`! The fix didn't change the byte count, however. To get this to even work, in addition to the many spaces and tabs, I used a macro that uses digraphs and token-pasting to generate the disallowed function names (`main` and `printf`). As Unix line endings are `LF` (decimal 10), I had to add a space at the end of the first line to continue the odd/even pattern. Saving some more space, I could coalesce `in` because the two letters fit the odd/even pattern. [Parity verification](https://tio.run/##bVBNT8MwDD1nv@KpbFoissHGbR8CMbjBiQsSQlvaZmtEm5Q00zQQv324pWNC4mBbtt97fnKmqjed54eDKUrnA@5UUMNFpnynHSycDd7lw0dnVdoplLGYI3UdIKGNtqHCbICNDou2pU2uA2UgNqG64ZlW6a0Jk6UgZqFKcL4qXLrCWGAI51PxK9WwNk7lNZPQyT7JNV5aBYkRBmibV8JW@n2rbaKX6P5YAnhC3mV9WTZChBS1wQ9TXp0cN/LHOw3P67D19qQDlNvwFDxNqsztUMueFvWD0Ef/XyhptvNdpi049biYn9x0j/gIz9EfhQeLKDoczlK9NlZjz5VM5EYaCCj0Jr1J0mQGY@u6aTrTYfGUsIVUkkkGwQU@184zPgWL2Wx0OcI0ZvRNFp/TBwVhWUlITxEo1oKzuDe@jnopi9iERfegKlksMMXXNw "Haskell – Try It Online") ``` #define y(a,c,g,i ) a %:%:c %:%: in%:%:g %:%:i b; y(m,a, , )() {for (; b <101 ;b = b+ 1 ) y( p , r , t , f)( b%2?"%d " : "E " , b) ; } ``` [Try it online!](https://tio.run/##HYxBCsIwFETX4yk@kUCCv2BdNoorD5KkTQxoLWk3Rby6MXbxZhh4jG@i96Xs@yGkcaBVWfYcOZEmS7KTnd8SlMZ/x22lHZyp7pMtg0FaaXqHV4YyBIdze2zJONClrgO19WtVmKqZK0slaAUnT1chewh0EDeqzXCaDH1K@frwsHEuzZJTzHa6zz8 "C (gcc) – Try It Online") [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 32 bytes ``` >'D1+k$1:/$'D1+k$/2+:1.C(1+?.;8? EOEOEOEOEOEOEOEOEOEOEOEOEOEOEOEO ``` [Try it online!](https://tio.run/##KyrNy0z@/99O3cVQO1vF0EpfBcLSN9K2MtRz1jDUtteztrD//x8A "Runic Enchantments – Try It Online") `EO` sequence above just indicates whether each byte is even or odd. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ØA 5ị¶ 101Ḷ× Ḃ$oÑK ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//w5hBIDXhu4vCtiAxMDHhuLbDlyDhuIIkb8ORS/// "Jelly – Try It Online") In the Jelly code page, these character have the byte values of ``` 12 41 20 35 D8 7F 20 31 30 31 B2 11 20 BF 24 6F 10 4B ``` which follows the pattern `Even Odd Even Odd ...` ## How it works Removing the extra spaces we get: ``` ØA5ị 101Ḷ×Ḃ$oÑK ``` which is: ``` ØA5ị - Helper link: Yield "E" ØA - Yield the upper case alphabet 5ị - Take the fifth element ("E") 101Ḷ×Ḃ$oÑK - Main link: Yield "E 1 E 3 ... E 99 E" 101 - Yield 101 Ḷ - Lowered range: [0, 1, 2, ..., 99, 100] Ḃ$ - Take the parity of each: [0, 1, 0, ..., 1, 0] × - Multiply each together: [0, 1, 0, 3, ..., 99, 0] Ñ - Call the helper link: "E" o - Replace the 0s with "E"s: ["E", 1, "E", ..., 99, "E"] K - Join with spaces: "E 1 E 3 ... E 99 E" ``` [Answer] # [R](https://www.r-project.org/), 35 bytes Thanks to ErikF for correcting a bug. ``` x=0 :{ 98+2} ;x[ c( T ,!T) ] ="E";x ``` [Try it online!](https://tio.run/##K/r/v8LWgNOqWsHSQtuoVsG6IlohWYMzhFNHMURTIVbBVslVybri/38A "R – Try It Online") Defines `x` as the vector of integers from 0 to 100, then replaces all the even values with `"E"` and outputs `x`. Previous, quite different version: # [R](https://www.r-project.org/), 42 bytes ``` for (i in 1:50) write(c(i*+2- 1, "E"),1 ) ``` [Try it online!](https://tio.run/##K/r/Py2/iFMjUyEzj1PB0MrUQFOhvCizJFUjWSNTS9tIV8FQh1PJVUlTx1BB8/9/AA "R – Try It Online") Includes a few tabs instead of spaces. Uses newlines as separators. `cat` and `print` are unusable, but luckily `write` is OK. I had to resort to `i*+2 -1` instead of `i*2-1` to keep the alternation. [Answer] # [Python 3](https://docs.python.org/3/), 65 bytes ``` exit ([ ["E" , j] [j%2]for j in eval ('ran' +"g"+"e")(101 ) ] ) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P7Uis4RTI1ohWslViVOHMytWITpL1Sg2Lb@IM4tTITOPUyG1LDGHU0O9KDFPXUFbKV1JWylVSVPD0MBQQVMhVkHz/38A "Python 3 – Try It Online") This submission was built on using tabs *and* spaces, as well as a Very Clever™ abuse of `eval`. **Edit**: Fixed program to adhere to [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") (I had an extra space by mistake). [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 18 bytes I didn't expect such a small amount of whitespace ... ``` 101,{.3(%\"E"if} % ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/39DAUKdaz1hDNUbJVSkzrVZB9f9/AA "GolfScript – Try It Online") ## Explanation ``` 101, # Generate range [0 1 2 ... 99 100] { } % # Map every item using this scheme . # Copy the item 3(% # Modulo by 3-1 (2) \ # If modulo-ing by 2 is truthy: return the item "E"if # Otherwise, return "E" ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 20 bytes ``` "E"q♀{î♥☻/÷i¿{"E"}îq ``` [Try it online!](https://tio.run/##y00syUjPz0n7/1/JVanw0cyG6sPrHs1c@mjGbv3D2zMP7a8GCtceXlf4/z8A "MathGolf – Try It Online") Very similar to the [FizzBuzz example](https://github.com/maxbergmark/mathgolf/blob/master/examples/fizzbuzz.mg). Uses the [MathGolf codepage](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py), can verify parity with [this script](https://tio.run/##PZJZTxNhGIXv@yvGcQEEQcEVxR33fV@qiLRAXdqCuCBiaq1jG3vRZd7pDCJ0oS1dREGW2NY0@d7Ey@l/OH@kVkO8O8lJnpzkPO7xsWGXs6teH3DZ7H3u/iG71CPJHINegl6GkYaRgZGCEYcniZiO2CfEDBheGB4YeRgF6BVoJcR8UAieilgVWWhFKPNQwlCiUCJQQvDPQlGhLUGrSBus8sZNm7c0NbdsbW3b1t6xfUdn185du/fs3de9X5asllZJPtBz8NDhI0ePHe89cfLU6TNnz52/cPHS5StXr12/cfPW7Tt3rdZ79/se9D8csNkHh4Ydjx4/eep0uUdGn409f/Hy1fjriTeTbxH08sd1Hlc4x0me4zinOct5LvA8f@MFLrKPP3CAM6zwMq/yEpf5J1dZ42mRFCmRhjf7O8IJ/so/uMSLHBZ5URJVBEOiKH6JikiIgihDC0OLQItC9UKdAyVASZAGIlAKFAbFQF9A06DPUENQVajLUItQp6F6oFZAM@tbQbOgKZAKyoEyoDgoBCqCsqB5UIOeBhkgHRQBRUEFUB6qDjUIzQ/NB60RQtA85iLPmtGax0zV3ouVms/MmLqZM5fhn6kp5gr8OQQSYhGBNAJzCMYRTPAaAn7xHX5DrME/hXdV0TgtzjOyxTLoGpUcksMpyVa51yqPNByY4IW/kujlDl5ziOrEv2KSF0bkbovkHnU4x5r/m9U@6HDamh0tmzvb7E5bT1NTS73@Bw). ``` "E"q # Push and output "E" ♀ # Push 100 { # Loop from 1 to 100 î # Push loop counter ♥☻/ # Push 32, 16, and divide (basically pushes 2) ÷ # Is the loop counter divisible by 2? i # Convert to integer (does nothing) ¿{"E"} # If so, push "E" î # If not, push the loop counter q # Output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` 101Ḷ¹⁾E Ḃ ?€Ḣ€K ``` [Try it online!](https://tio.run/##y0rNyan8/9/QwPDhjm2Hdj5q3Oeq8HBHk4L9o6Y1D3csApLe//8DAA "Jelly – Try It Online") [Try it online with parity!](https://tio.run/##y0rNyan8/9/QwPDhjm2Hdj5q3Oeq8HBHk4L9o6Y1D3csApLe/w/P8Mp8tHHdo4aZQJmHO/cBBXXCHjXMCUgsyiyptFIAMoNSi0tzSkDMuUf3ROI3DwA "Jelly – Try It Online") A full program that takes no argument and prints the desired output. The footer demonstrates both the parity and result. [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes Adaptation of the [Python answer](https://codegolf.stackexchange.com/a/197229/52194). Unlike Python, however, Ruby `puts` is valid code to use for output, eliminating the need for `exit` hacks. I didn't want to do a direct port, but `map`, `each`, `upto`, and `times` are all forbidden by the spec... ``` x=0;( puts ["E" , x] [x%2] ;x=x+ 1 ) while x <101 ``` [Try it online!](https://tio.run/##KypNqvz/v8LWwFqDs6C0pFghWslViVOHsyJWIbpC1ShWwbrCtkJbwVBBU6E8IzMnVYGzgtPG0MDw/38A "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò#d_v) ?"E"):»Z ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8iNkX3YpID8iRSIpOrta) ``` ò#d range [0-100] _ passed through v) ? divisible by 2? "E"):»Z replace with 'E' else replace with number ``` [Layout](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=cSBtYw&input=IvIjZF92KSA/YkViKTq7WiI) : [242,35,100,95,118,41,32,63,98,69,98,41,58,187,90] [Answer] # [Haskell](https://www.haskell.org/), 296 bytes ``` w = k 1 a(c:e ) = c i =(id) e a =(a:) m 1 =(a"1") m 3 =(a"3") m 5 =(a"5") m 7 =(a"7") m 9 =(a"9") m c|c<1 = '0'|c<3 = '2'|c<5 = '4'|c<7 = '6'|c<9 = '8' m c =(m$c - 10) q 1 =0; q c|m c<a"1"= 1 + q(c - 1 ) q c = q$c - 1 k c|c>98= e(a"E")$e(a"9")$e(a"9")$i"E"; k c = e(a"E")$e(m$q c )$e(m c )$k$c +2 ``` [Try it online!](https://tio.run/##Tc7BCoMwDAbge58iiKBFBlbntGp32xPsCUpXmKhjbg4vvrtLIoyd8rVN0v9u370fhm1bwEAPStjY1R4knpzowMTdTQoPFmVrKUZQpEAF5Jydswt2wS7ZJVuzNdutrsV5iNIIlZMyUkE6kkrSiaRJVURTuGEMHRxApVJMlCBtsLoV31rKYvAugSnmHqAenIFpnxE9/XvWlQGPSS6BDP2e6Fc7vG2oD/57xpD2sLj2uC/JttF2D/P8zNf5Bcv2BQ "Haskell – Try It Online") This was pretty hard since `show` and `print` are both unusable, so I had to convert integers to strings on my own. [Answer] ## [W](http://github.com/a-ee/w) `z`, 19 bytes ``` 10#0#.a2m a&#"E"#|M ``` Pretty much the same as below. `100.a2ma&"E"|M` The only difference is the 0-range (which does no good for the program). ## W, 19 bytes ``` 101 a2m"E"#&a 1 -|M ``` ## Explanation Pretty simple: `#` and are both readability characters here and have no result on the stack. ``` 101a2m"E"&a1-|M ``` ``` 101 M % Foreach the range 1 -> 101 a2m % Modulo the current item by 2 "E"& % If true, return "E" (Because odd-1 -> even) a1-| % Otherwise, return a-1 ``` [Answer] # PowerShell, 72 bytes ``` for`t(`t`$i =0;`$i -le 101 - 1 ;`$i =`$i + 1 ) {`$ab=(' e ',`t`$i ) ;`$ab[`$i %2] } ``` For testing: ``` $a = "for`t(`t`$i =0;`$i -le 101 - 1 ;`$i =`$i + 1 ) {`$ab=(' e ',`t`$i ) ;`$ab[`$i %2] }" # Even/odd ok? 0..($a.Length-1) | % { [char]$a[$_] + " " + ([byte][char]$a[$_] % 2)} $a.Length Invoke-Expression $a ``` Missed the even-odd part in the code, thanks for pointing it out! [Try It Online](https://tio.run/##K8gvTy0qzkjNyfn/XyVRwVZBKS2/KKFEI6EkQSVTwdbAGkTp5qQqGBoYKugqGCqABWxBhDaQp6lQnaCSmGSroa6QqqCuA9GlCVKUmBQNYqsaxSrUKnF55pXlZ6fqulYUFKUWF2fm5ymoJP7/DwA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `HM`, 5 bytes ``` r⁽\EẆ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJITSIsIiIsInLigb1cXEXhuoYiLCIiLCIiXQ==) This works in both the Vyxal codepage and UTF-8. -2 thanks to pacman256. The `H` flag can be removed if you place a `₁` at the start, although it only works with UTF-8 then. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 18 bytes ``` F¹⁰¹«¿⊗﹪⊕ι²E↥I⌈ι⁰→ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw9DAUFOhmoszM01BwyW/NCknNUXDNz@lNCdfwzMvuSg1NzWvBCiUqamjYKSpqakQUJSZV6Kh5Kqkaa2QmlOcCtLLCRF0TiwGEqmZOZl56UANmprWcCkDELuWC5nnm1@WqmEVlJmeUQLk1v7//1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Here are the 18 hex codes in Charcoal's code page: ``` C6 B1 B0 B1 A8 BF 9E A5 9C E9 B2 45 18 C9 1A A9 B0 13 ``` Explanation: ``` F¹⁰¹« ``` Loop from 0 to 100. ``` ¿⊗﹪⊕ι² ``` Test whether the index is even. The index is incremented to comply with the source code restriction, which reverses the sense of the test. The result of the test is doubled to comply with the source code restriction, but this doesn't change the outcome of the decision. ``` E ``` If the number was even then output an `E`. ``` ↥I⌈ι ``` Otherwise take the ceiling of the number to comply with the source code restriction, cast the result to string, and uppercase the result to comply with the source code restriction. ``` ⁰ ``` Print 0 `-`s to comply with the source code restriction. ``` → ``` Leave a space between successive outputs. Note: If a trailing space is acceptable, then the last two characters can be replaced with a space for 17 bytes, although there are alternative solutions, such as this: ``` F¹⁰¹«¿⊗﹪⊕ι²E ⁺⌈ι ``` [Try it online!](https://tio.run/##LcqxCsJADADQ2X5FuCkBBevasTp0KPQX6jXVQHqBa89F/PZYxPXx4nPM0UZ1ny0D1uea4F0dZAa8WrkrT9jbVNSwSzHzwmnbSegIFyKCIUvaMNwgUAOsK/9l0LJiy6KSHr8d9kFN9XH300u/ "Charcoal – Try It Online") Link is to verbose version of code. Here are the 17 hex codes in Charcoal's code page: ``` C6 B1 B0 B1 A8 BF 9E A5 9C E9 B2 45 20 AB 1A E9 20 ``` Explanation: Much like the above, except that in the even case we directly include the space in the literal while in the odd case the ceiling of the number is concatenated with a space. [Answer] # [Zsh](https://www.zsh.org/), ~~50 30~~ 34 bytes *Bug fix: I was checking each pair of letters to make sure it had a character of each parity, instead of ensuring it alternated.* ``` "e"cho E" "{"1"'.'.9"9"'.'.'0'2} E ``` ~~[Try it online!](https://tio.run/##RU5LCsIwFFybUwyvkSbUjRURaysKtiAIXkCEfiJd@cS46ufsMV2Iuxnm29nW1eUHe9h3jTRFmF@L0JVVppZYYY0NttCCDNUtI7/NZH8vq/GPftz5nBCdbaciIR78hgFDkezVwSaJJqlSL2kaSe/QsFDqxTbK4gVUYBAhYI05Yq0xDDDTHBXH8yU/wf@T3ptAGskkGn4a9wU "Zsh – Try It Online") [Try it online!](https://tio.run/##FY7LCsIwFETX5iuG20gSKgW7a62iYAqC4DdIm5KVVxpXfXx7TDezmXOYmYKP3fuHC8LYoWmg7KtVkRx1nmFpRzMdSRWqqKoUpVphY0KEmILfHCEGHuHA0CRnfQ11bUjqJlWGVjIn9Cy0/nLIz@UBOnPIkbHBHqUxWBa4bYna2@Np70hXZGJrSCeZRM8fF/8 "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##NY7BCoJAGITP/U/x82vuroGoN82iIIWg6AHEg6zGnlpwOyn77NsqdJph5huY2Sgn@y@e0UwSqwpZ/WqYo5Gk0ljTjhbKiCUsKajYlKUst1g7zwHMRq1DgLeeUKp@Qk7hwi@mLAWFvPKdIEviiIMGczj5jAcbt8dcCIJBf0aAtkW/egoTxGka27/Psthi12EU4bjeaa73R31zPw "Zsh – Try It Online") Self-tests. Contains a literal tab. ~~I couldn't figure out a way to finagle the most straightforward `echo E\ {1..99..2} E` into anything, mostly due to the double period.~~ EDIT: I did it. Turns out in normal expressions, quotes inside brace ranges don't really matter. [Answer] # [Pip](https://github.com/dloscutoff/pip), 16 bytes ``` 1 +2 * ,50 JW"E" ``` [Try it online!](https://tio.run/##K8gs@P/fUEHbiFOLU8fUgNMrXMlV6f9/AA "Pip – Try It Online") Outputs without separators. Spaces and tabs are no-ops, so this boils down to: ``` ,50 Range(50) 0, 1, ..., 49 2* Multiply each by 2 0, 2, ..., 98 1+ Add 1 1, 3, ..., 99 JW"E" Join with "E", wrapping the outside with "E"s as well E1E3E...E99E ``` [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 55 bytes ``` } {do {$_.=$- %2?$-.' ':q(E ) } while(+$- =$- + 1 )<101 ``` [Try it online!](https://tio.run/##K0gtyjH9/79WoTolX6FaJV7PVkVXQdXIXkVXT11B3apQw1VBU6FWoTwjMydVQxsoB5LXVjBU0LQxNDD8//9ffkFJZn5e8X/dAgA "Perl 5 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 bytes ``` 101rm2% _"E"? ``` [Run and debug it](https://staxlang.xyz/#c=101rm2%25+_%22E%22%3F&i=&a=1) The program has these ASCII codes. ``` 49 48 49 114 109 50 37 32 95 34 69 34 63 ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), ~~36~~ 34 bytes ``` "E"' _&s&o '2_R_r_p[:+,u>' _l_&o<] ``` [Try it online!](https://tio.run/##y6n8/1/JVUldIV6tWC1fQd0oPii@KL4g2kpbp9QOKJoTr5ZvE/v/PwA "Ly – Try It Online") At a high level, this one works like this... * print the initial `E` * generate the sequence `1..49` * loops over that list printing the `N*2-1` plus `E` Here's the decimal codepoints for the source: ``` 34 69 34 39 32 95 38 115 38 111 32 39 50 95 82 95 114 95 112 91 58 43 44 117 62 39 32 95 108 95 38 111 60 93 ``` The code uses a couple of Ly specific tricks to achieve the even/odd sequence. First spaces can be added most places and are ignored, which allows for an "even" no-op. And `_` (underscores) work as "odd" no-op's the same way. Finally, quoting characters can be done using double quotes (even) or as a series of single characters after single quotes (odd). And the gory details: ``` "E"' - push "E " on stack _&s - stash a copy of the stack &o - print "E " '2 - push 50 on the stack _R - gen seq 0..49 _r - reverse stack _p - pop 0 (first entry) off stack [ ] - loop while stack not empty :+, - calc: <TOP>*2-1 u - print as number > - switch to new stack ' - push space _l - push "E " from stashed stack _&o - print stack < - switch back to original stack ``` ]
[Question] [ ## Golf a Venn Diagram generator ![enter image description here](https://i.stack.imgur.com/k9uMD.jpg) In order to properly celebrate [John Venn's 180th birthday](http://www.google.com/doodles/john-venns-180th-birthday), today your task will be creating a program that outputs a [Venn Diagram](http://en.wikipedia.org/wiki/Venn_diagram)! **Input:** A positive integer `N` that will define the range of numbers appearing in the diagram (From zero to `N`) and three sets of positive integers. **Output:** A 3 set Venn diagram showing all integers from 0 to `N` and the relationships of the sets by displaying them in the proper regions of the diagram, [similar to this one](http://s3.amazonaws.com/minglebox-photo/core-0000-c88370190d4b414d010d4b415d220010.data-0000-fdbffe7622c53ecd0122c5c50d0b0334.gif). **Notes** 1. Use `stdin` (or whatever your language's equivalent is) to get the values. 2. You can define the input format for the sets and for `N` (Separated by comma, slash or whatever works best for you). 3. Numbers that do not appear in any of the sets but are within the specified range must appear on the diagram, just not inside any region. 4. The sets don't need to be named. 5. The output can be a drawing or ascii-art. 6. The diagram can have any shape as long as the boundaries are unambiguously distinguishable (if you chose ASCII art, using + (or similar) for crossing boundaries is essential, for example). 7. The regions may but don't have to be shaded. 8. Any built-in functions or third party libraries that generate Venn Diagrams are disallowed. 9. [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes, wins. [Answer] ## Ruby, ~~654~~ ~~590~~ ~~566~~ ~~542~~ 505 bytes This was fun. I used ASCII. I wasn't able to test every possible combination yet, so if you find a glitchy test case, please let me know. ``` require'set' u=(0..gets.to_i).to_set a,b,c=eval(gets).map &:to_set i=' ' m,M,n,N,o,O,p,P,q,Q,r,R,s,S=[a-b-c,b-a-c,c-a-b,a&b-c,b&c-a,a&c-b,a&b&c].map{|u|[t=u.to_a*i,t.size]}.flatten H,V,X=?─,?│,?┼ puts'┌'+H*(A=[1+M+[P,S].max,1+R].max)+?┐+(u-a-b-c).to_a*i,V+i*M+?┌+(b=H*(T=-M+U=A-1)+X+H*(B=[N,Q].max))+?┐,V+m+V+p+i*(T-P)+V+n+i*(B-N)+V,'│┌'+H*(K=M-1)+X+b+X+H*(C=[O-B-1,0].max)+?┐,(v=V*2+i*K)+V+s+i*(T-S)+V+q+i*(B-Q)+V+i*C+V,v+?└+b+?┘+i*C+V,V*2+r+i*(U-R)+V+o+i*(-O+D=B+C+1)+V,'└┼'+H*U+?┘+i*D+V,' └'+H*(A+D)+?┘ ``` It expects the input on STDIN in the following format ``` 10 [[1,2,3,4,5,9],[1,2,3,6,8],[7,2,9]] ``` And will then reward you with this beauty ``` ┌───────┐0 10 │ ┌───┼───┐ │4 5│1 3│6 8│ │┌──┼───┼───┼┐ ││ │2 │ ││ ││ └───┼───┘│ ││9 │7 │ └┼──────┘ │ └───────────┘ ``` I don't think I can be bothered to add an ungolfed version. Please have a look at the original version in the edit history for a *somewhat* more readable version. This could certainly be golfed further by making the set boundaries less tight or even keeping them fixed like some of the graphical ones do, but I prefer that it looks nice and is done "properly" despite being golfed. [Answer] # BBC BASIC, 243 ASCII characters (tokenised file size 211 bytes) Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> **Golfed** ``` INPUT"N",n DIMs(n+1) FORi=0TO2PRINT"S";i REPEATINPUTx:s(x)=s(x)+2^i:UNTILx>n NEXTMODE4r=360CIRCLE460,r,r CIRCLE640,664,r CIRCLE820,r,r FORi=0TO7FORx=0TOn:IFs(x)=i PRINT;x NEXTREADa VDU28,a+1792;a+5; NEXT DATA19,4873,2572,4893,2586,5907,3091,34 ``` BBC Basic is very arbitrary about which newlines/whitespace you can eliminate. Apart from stripping out unnecessary newlines there's another trick here that's not in the ungolfed version: I assign the viewport (see explanation below in ungolfed comments) at the END of the plotting loop, not at the beginning. This means that the elements outside the set are plotted the top left, and the cursor is trapped in a viewport at top right at the end of the program. The reason for this is to eliminate the `VDU26`. **Ungolfed** Each set of numbers is terminated by the user entering the number N+1 (a slightly unusual choice, this is to avoid errors caused by trying to write outside the range of an array.) Then it changes from a text mode to a graphics mode and plots the Venn diagram. The input data is stored in an array, one cell for each value to be displayed. The data is stored as a 3-bit value: 1 for Set0 + 2 for Set1 + 4 for Set2 giving a number in the range 0 to 7. BBC basic has no shift operator, so the power operator is used instead: `2^i` instead of `1<<i` in C for example. After plotting the circles, an outer loops goes through each of the eight regions, moving to the required coordinates (as per a data table.) An inner loop prints all the numbers in that region (those with the corresponding 3-bit value in the array.) ``` INPUT"N",n :REM create an array called s() with range 0..n+1 DIMs(n+1) FORi=0TO2 PRINT"S";i :REM prompt the user for data for set 0, set 1 and set 2. REPEATINPUTx:s(x)=s(x)+2^i:UNTILx>n :REM input numbers and store as a bit table. Repeat until user enters n+1. NEXT MODE4 :REM change to graphics mode. r=360 CIRCLE460,r,r :REM plot a circle at x,y,r. CIRCLE640,664,r :REM for the bottom two circles y=r. CIRCLE820,r,r FORi=0TO7 :REM for each region of the venn diagram READa :REM read a 2 byte value for the coordinates of the top left corner of a text viewport from the DATA statement: x+256y VDU28,a+1792;a+5; :REM create a 5x7 viewport (limits each region to 7 numbers.) 1792=7*256 FORx=0TOn:IFs(x)=i PRINT;x :REM print all numbers in the array belonging to that region NEXT NEXT VDU26 :REM Restore the viewport to the whole screen, to ensure the command prompt does not mess up the display at the end of the program. DATA34,19,4873,2572,4893,2586,5907,3091 ``` **Montage of typical input and output (ungolfed version)** In the golfed version, the position of the numbers outside the sets is exchanged with the command prompt `>`. ![enter image description here](https://i.stack.imgur.com/yUnqD.png) [Answer] # Javascript 1235 <http://jsfiddle.net/44a4L/7/> Tested in google chrome v36. Input is taken in the variables upper, set1, set2 and set3. **Update:** Now automatically scales depending on the size of input. ``` function t(e,t){z.getElementById(e).innerHTML+=" "+t}z=document;s=200+upper*20;z.body.innerHTML+="<style>#m{width:"+s+"px;height:"+s+"px;}div{position:absolute;text-align:center;border-radius:50%;}#s1{left:calc(15% + 15px);top:30px;bottom:30%;right:calc(15% + 15px);background-color:rgba(255,0,0,0.4);padding:10%;}#s2{left:30px;bottom:30px;top:30%;right:30%;background-color:rgba(0,255,0,0.4);padding-right:40%;padding-top:30%;}#s3{right:30px;bottom:30px;top:30%;left:30%;background-color:rgba(0,0,255,0.4);padding-left:40%;padding-top:30%;}#s123{left:40%;top:40%;right:40%;bottom:40%;}#s12{left:20%;top:35%;right:65%;bottom:50%;}#s13{right:20%;top:35%;left:65%;bottom:50%;}#s23{left:40%;right:40%;bottom:15%;top:70%;}</style><div id=m><div id=s1 class=s></div><div id=s2 class=s></div><div id=s3 class=s></div><div id=s123 class=v></div><div id=s12 class=v></div><div id=s13 class=v></div><div id=s23 class=v></div></div>";for(i=0;i<=upper;i++){i1=i2=i3=false;if(set1.indexOf(i)!=-1)i1=true;if(set2.indexOf(i)!=-1)i2=true;if(set3.indexOf(i)!=-1)i3=true;if(i1&&i2&&i3)t("s123",i);else if(i1&&i2)t("s12",i);else if(i1&&i3)t("s13",i);else if(i2&&i3)t("s23",i);else if(i1)t("s1",i);else if(i2)t("s2",i);else if(i3)t("s3",i);else t("m",i)} ``` Sample output: ![Venn](https://i.stack.imgur.com/qdLNq.png) [Answer] # Mathematica ~~343~~ 264 ## UnGolfed ``` m=Input[]; data=Input[]; (* The circles to represent set boundaries *) {R1,R2,R3}=Circle[#,5]&/@{{-2,8.5},{2,8.5},{0,5}}; (*converts {1,0,1} to base 10, ie, the number 5. bool[x_]:=FromDigits[Boole[x],2] (* determines the region in which each number from 0 to `m` resides *) encode[num_]:=bool[Table[MemberQ[data[[k]],num],{k,3}]] (*Centroid of each region; the first is a location for numbers in none of the three sets *) points={{7,4},{0,2},{4,10},{3,6},{-4,10},{-3,6},{0,11},{0,7}} (* Plots the venn diagram with numbers in regions *) Graphics[{ Text@@@({#[[1]],points[[#[[2]]+1]]}&/@({#[[All,1]],#[[1,2]]}&/@GatherBy[{#,encode[#]}&/@Range[0,m],Last])), Opacity[.1],R1,R2,R3 }] ``` --- Assuming `10` was input for `m` and `{{1,2,3,4,5,9},{1,2,3,6,8},{7,2,9}}` was input for `d`, ![new venn diagram](https://i.stack.imgur.com/anyxz.png) --- ## Golfed 264 I was surprised that all of the computation could be carried out within the `Graphics` function itself. With the exception of the inputs, it is a one-liner. ``` m=Input[];d=Input[] Graphics@{Text@@@({#[[1]],{{7,4},{0,2},{4,10},{3,6},{-4,10},{-3,6},{0,11},{0,7}}[[#[[2]]+1]]}&/@({#[[All,1]],#[[1,2]]}&/@GatherBy[{#,FromDigits[Boole[Table[d[[k]]~MemberQ~#,{k,3}]],2]}&/@Range[0,m],Last])),Circle[#,5]&/@{{-2,8.5},{2,8.5},{0,5}}} ``` [Answer] # HTML + JavaScript (E6) 752 ~~761~~ Input format: *max set1 set2 set3* (each set is a comma separated list of numbers) Example: 10 1,2,3,4,5,9 1,2,3,6,8 7,2,9 ![Screenshot](https://i.stack.imgur.com/Q9A9C.png) Example 2: 30 2,4,6,8,10,12,14,16,18,30 3,6,9,12,15,18,21,30 5,10,15,20,25,30 ![Chrome Screenshot](https://i.stack.imgur.com/UFpG9.png) All the sections auto size thanks to html rendering. ``` <html><body><script> i=prompt().split(' '); r=",,,,,,,, class=',></i>".split(c=',') for (j=-1;j++<i[0];r[h]+=j+' ')for(h=k=0;++k<4;)if((c+i[k]+c).search(c+j+c)+1)h+=k+(k>2); document.write( "<style>div{1row}p{position:relative;text-align:center;padding:7;1cell}i{position:absolute;top:0;3:0;4:0;left:0}.a{2top-left5b{2top-45c{23-left5d{23-45x{6880,9.y{680,89.z{60,889</style>" .replace(/\d/g,x=>'09display:table-9border-9bottom9right9-radius:60px}.9background:rgba(930px9255,9.3)}'.split(9)[x]) +"<div><p8x a'/><p8x'>1</p><p><i8y a'9<i8x b'93</p><p8y'>2</p><p8y b'/></div><div><p8x c'/><p8z a'><i8x'95</p><p8z'><i8x d'9<i8y c'97</p><p8z b'><i8y'96</p><p8y d'/></div><div><p/><p8z c'/><p8z'>4</p><p8z d'/></div>0" .replace(/\d/g,x=>r[x])) </script></body></html> ``` **Javascript E5 version** Works in Chrome and MSIE 10 (maybe 9) ``` <html><body><script> i=prompt().split(' '); r=",,,,,,,, class=',></i>".split(c=',') for (j=-1;j++<i[0];r[h]+=j+' ')for(h=k=0;++k<4;)if((c+i[k]+c).search(c+j+c)+1)h+=k+(k>2); document.write( "<style>div{1row}p{position:relative;text-align:center;padding:7;1cell}i{position:absolute;top:0;3:0;4:0;left:0}.a{2top-left5b{2top-45c{23-left5d{23-45x{6880,9.y{680,89.z{60,889</style>" .replace(/\d/g,function(x){return '09display:table-9border-9bottom9right9-radius:60px}.9background:rgba(930px9255,9.3)}'.split(9)[x]}) +"<div><p8x a'/><p8x'>1</p><p><i8y a'9<i8x b'93</p><p8y'>2</p><p8y b'/></div><div><p8x c'/><p8z a'><i8x'95</p><p8z'><i8x d'9<i8y c'97</p><p8z b'><i8y'96</p><p8y d'/></div><div><p/><p8z c'/><p8z'>4</p><p8z d'/></div>0" .replace(/\d/g,function(x){return r[x]})) </script></body></html> ``` **Not (so) golfed** ``` <html> <style> div { display:table-row; } p { position: relative; text-align: center; padding: 30px; display: table-cell; } i { position: absolute; top:0;bottom:0;right:0;left:0; } .a { border-top-left-radius: 60px; } .b { border-top-right-radius: 60px; } .c { border-bottom-left-radius: 60px; } .d { border-bottom-right-radius: 60px; } .x { background: rgba(255,255,0,.3) } .y { background: rgba(255,0,255,.3) } .z { background: rgba(0,255,255,.3) } </style> <body> <div> <p class='x a'/><p class='x'><b id='b1'></b></p><p><i class='y a'></i><i class='x b'></i><b id='b3'></b></p><p class='y'><b id='b2'></b></p><p class='y b'/> </div> <div> <p class='x c'/><p class='z a'><i class='x'></i><b id='b5'></b></p><p class='z'><i class='x d'></i><i class='y c'></i><b id='b7'></b></p><p class='z b'><i class='y'></i><b id='b6'></b></p><p class='y d'/> </div> <div> <p/><p class='z c'/><p class='z'><b id='b4'></b></p><p class='z d'/> </div> <b id='b0'></b> <script> i=prompt().split(' ') r=',,,,,,,'.split(c=',') for (j=-1; j++<i[0];) { for(h = k = 0; ++k < 4;) { if( (c+i[k]+c).search(c+j+c) >= 0) h += k + (k>2); // bit mask 1 or 2 or 4 } r[h] += j + ' '; } for (j = 0; j < 8; j++) document.getElementById('b'+j).innerHTML=r[j] </script> </html> ``` [Answer] # Python - 603 ``` import re n,a,b,c=eval(input()) h=set(range(n+1))-a-b-c g=a&b&c d,e,f=a&b-g,b&c-g,a&c-g l,m=set(a),set(b) a-=b|c b-=l|c c-=l|m for t in'abcdefgh':exec("%s=' '.join(map(str,%s))"%(2*(t,))) l=len x,y,z=max(l(a),l(f)+2,3),l(max(d,g)),max(l(b),l(e)+2,l(c)-l(f+g)-2,3) j=[0]*4 for t in'abcdefg':exec("%s=%s.ljust([x,z,x+y+z-2,y,z-2,x-2,y][ord('%s')-97])+'|'"%(3*(t,))) s='\d| ' w=re.sub for r in (1,3):q=r//2;j[r]=['','| '][q]+'|'+[a+d+b,f+g+e][q]+['',' |'][q];j[r-1]=w('\|','+',w(s,'-',j[r])) j[0]+=h o=j[2] j[2]='| +'+j[2][3:-3]+'+ |' p=' |'+c q=' '+w('\|','+',w(s,'-',p))[2:] for l in j+[o,p,q]:print(l) ``` Input is N followed by the three sets, seperated by commas (e.g. `8, {1,2,4}, {2,3,4,5}, {4,6,8}`). It outputs a set in ACSII art like the following: ``` +---+-+---+0 7 |1 | |3 5| | +-+-+-+ | | |2|4| | | +-+-+-+-+-+ |6 8 | +-----+ ``` [Answer] # Python 3 - 353 ``` # 353 bytes, input format like: 6 1,2,3 2,3,4 1,3,4 import sys from turtle import* _,n,*q=sys.argv n=set(range(int(n))) a,b,c=map(set,map(eval,q)) for x,y in(0,0),(-115,-185),(115,-185):goto(x,y),pd(),circle(200),up() for x,y,s in(200,331,n-a-b-c),(-101,278,a-b-c),(-254,-49,b-a-c),(95,-49,c-a-b),(-172,164,a&b-c),(58,164,a&c-b),(-49,-39,b&c-a),(-49,52,a&b&c):goto(x,y),write(s or'',font=None) ht() done() ``` Did anybody else play with Logo as a kid? Sample: `python3 turtletest.py 15 1,2,3,4,5,9,10,12 1,3,4,6,7,9 1,2,7,8,9` ![enter image description here](https://i.stack.imgur.com/av00d.png) [Answer] # perl 388b 346b 488b This has output similar to another entry: ``` @a=split($",<>); $n=pop @a; @a=map[split(',')],@a; for$i(0..2){$b{$_}+=1<<$i foreach@{$a[$i]}} push@{$c[$b{$_}]},$_ for(0..$n); $l|=length($d[$_]=join($",@{$c[$_]}))for(0..$n); print$h=(("+-"."-"x$l)x3)."+ "; sub j{sprintf"% ".(sprintf"%ds",$l+($_[0]<4)+($_[0]==7)),$d[$_[0]]} sub r{join('|',map{j($_)}@_)} $h=~s/\+-/|+/; $h=~s/-\+$/+|/; print "|".r(1,3,2)."| ".$h; $h=~s/[|+]{2}/++/g; print "||".r(5,7,6)."|| ".$h; $h=~s/\+\+/ +/; $h=~s/\+\+/+ /; $h=~s/-\+-/---/g; $l=$l*3+3;print " |".j(4)."| ",$h,$d[0] ``` Test run and output: ``` # echo "1,2,3,7,13 2,3,8,11,13,6,9 3,4,5,11,12,13,14 15" | perl venn.pl ;echo +----------------+----------------+----------------+ | 1 7| 2| 6 8 9| |+---------------+----------------+---------------+| || | 3 13| 11|| ++---------------+----------------+---------------++ | 4 5 12 14| +------------------------------------------------+ ``` [Answer] ## T-SQL 2095 Assumes @N is an int containing N. Assumes @A, @B, and @C are tables containing the three sets of numbers. Didn't try to golf it too much. ``` DECLARE @D INT=@N,@E INT=0,@F CHAR='/',@G CHAR='\',@H CHAR='-',@I CHAR='|',@J CHAR='+'DECLARE @ TABLE(Z INT,Y INT,X INT,W INT,V INT,U INT,T INT,S INT)INSERT INTO @(Z)SELECT A.P FROM @A A JOIN @B B ON A.P=B.P JOIN @C C ON A.P=C.P INSERT INTO @(Y)SELECT A.P FROM @A A JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL INSERT INTO @(X)SELECT C.P FROM @C C JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL INSERT INTO @(W)SELECT B.P FROM @B B JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL INSERT INTO @(V)SELECT A.P FROM @A A LEFT JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL AND B.P IS NULL INSERT INTO @(U)SELECT C.P FROM @C C LEFT JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL AND A.P IS NULL INSERT INTO @(T)SELECT B.P FROM @B B LEFT JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL AND C.P IS NULL WHILE @N>=0BEGIN INSERT INTO @(S)SELECT @N WHERE @N NOT IN(SELECT*FROM @A UNION SELECT*FROM @B UNION SELECT*FROM @C)SET @N-=1 END DECLARE @Z TABLE(A CHAR(5),B CHAR(5),C CHAR(5),D CHAR(5),E CHAR(5),F CHAR(5),G CHAR(5),H CHAR(5))INSERT INTO @Z SELECT @F,@H,@F,@H,@G,@H,@G,''WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT V FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT X FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT U FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT S FROM @)),'')SET @E+=1 END INSERT INTO @Z SELECT @F,@H,@J,@H,@G,'',@I,''SET @E=0WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Y FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Z FROM @)),''),@I,'',@I,''SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@J,@H,@F,'',@I,''SET @E=0WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT T FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT W FROM @)),''),@I,'',@I,''SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@G,@H,@F,@H,@F,''SELECT*FROM @Z ``` Less golfed version: ``` --finding the sets DECLARE @D INT=@N,@E INT=0,@F CHAR='/',@G CHAR='\',@H CHAR='-',@I CHAR='|',@J CHAR='+' DECLARE @ TABLE(Z INT,Y INT,X INT,W INT,V INT,U INT,T INT,S INT) INSERT INTO @(Z) SELECT A.P FROM @A A JOIN @B B ON A.P=B.P JOIN @C C ON A.P=C.P INSERT INTO @(Y) SELECT A.P FROM @A A JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL INSERT INTO @(X) SELECT C.P FROM @C C JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL INSERT INTO @(W) SELECT B.P FROM @B B JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL INSERT INTO @(V) SELECT A.P FROM @A A LEFT JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL AND B.P IS NULL INSERT INTO @(U) SELECT C.P FROM @C C LEFT JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL AND A.P IS NULL INSERT INTO @(T) SELECT B.P FROM @B B LEFT JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL AND C.P IS NULL WHILE @N>=0 BEGIN INSERT INTO @(S) SELECT @N WHERE @N NOT IN(SELECT*FROM @A UNION SELECT*FROM @B UNION SELECT*FROM @C) SET @N-=1 END --displaying the venn diagram DECLARE @Z TABLE(A CHAR(5),B CHAR(5),C CHAR(5),D CHAR(5),E CHAR(5),F CHAR(5),G CHAR(5),H CHAR(5)) INSERT INTO @Z SELECT @F,@H,@F,@H,@G,@H,@G,'' WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT V FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT X FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT U FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT S FROM @)),'') SET @E+=1 END INSERT INTO @Z SELECT @F,@H,@J,@H,@G,'',@I,'' SET @E=0 WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Y FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Z FROM @)),''),@I,'',@I,'' SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@J,@H,@F,'',@I,'' SET @E=0 WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT T FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT W FROM @)),''),@I,'',@I,'' SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@G,@H,@F,@H,@F,'' SELECT*FROM @Z ``` ]
[Question] [ Given a string of ASCII characters, output the character that is in the middle. If there is no middle character (when the string has an even length), output the ASCII character whose ordinal is the floored average of the two center characters. If the string is empty, an empty string should be output. Test cases: ``` 12345 => 3 Hello => l Hiya => q (empty input) => (empty output) ``` Shortest program in characters wins. (Not bytes.) # 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 characters ``` 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 characters ``` 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 characters ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 characters ``` ``` <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 = 64599; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 47556; 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] # Pyth, 15 bytes ``` Cs.O@R/lz2_BCMz ``` [Demonstration](https://pyth.herokuapp.com/?code=Cs.O%40R%2Flz2_BCMz&input=Hiya&debug=0) Starting with "Hiya" as input: ``` z "Hiya" Input CM [72, 105, 121, 97] Character values _B [[72, 105, 121, 97], [97, 121, 105, 72]] Pair with reversal /lz2 2 Halfway index @R [121, 105] That element in each .O 113.0 Average s 113 Floor C "q" Cast to character q Print implicitly ``` Note that this crashes with an error on empty input, and prints nothing to STDOUT, which is a valid way to output an empty string by code-golf defaults. [Answer] # Brainf\*\*\*, 61 bytes # [Chinese](https://esolangs.org/wiki/Chinese), 16 characters This requires the input is in the ASCII range 1-127 and is null-terminated. It deletes pairs of characters from the start and end of the string until there are one or two characters remaining. If there are two, it adds them together, then divides by 2, rounding down. The remaining character is printed. ``` ,[>,]<<<[[<]>[-]>[>]<[-]<<<]>[[->+<]>[-[-<+<]>>]<[>]<[>]<<]>. ``` Try it on [this interpreter](http://brainfuck.tk/). Dissection: ``` ,[>,] Get the null terminated input <<< Move to the second last character [ While there are at least 3 characters [<]> Move to the first character [-] Delete it >[>]< Move to the last character [-] Delete it <<< Move the the third last character ] > Move to the second last character [ If there are two characters remaining [->+<] Add the two characters together >[-[-<+<]>>] Divide the character by 2 rounding down <[>]<[>]<< Move to before the character to exit the if loop ] >. Print the remaining character ``` \* Given each instruction could be compressed to 3 bits and encoded in UTF-32, the whole program could technically be expressed in 6 characters. **EDIT:** And thanks to [Jan Dvorak](https://codegolf.stackexchange.com/users/7209/jan-dvorak) for introducing me to [Chinese](https://esolangs.org/wiki/Chinese), which compresses this into 16 characters, on par with [Dennis'](https://codegolf.stackexchange.com/users/12012/dennis) [CJam answer](https://codegolf.stackexchange.com/a/64601/4934). ``` 蜐蕈帑聿纂胯箩悚衅鹊颂鹛拮拮氰人 ``` [Answer] # CJam, 16 bytes ``` q:i_W%.+_,2/=2/c ``` [Try it online!](http://cjam.tryitonline.net/#code=cTppX1clLitfLDIvPTIvYw&input=aGl5YQ) ### How it works ``` q e# Read all input. :i e# Cast each character to integer. _W% e# Push a reversed copy. .+ e# Perform vectorized addition. _,2/ e# Get the length, divided by 2. = e# Select the corresponding sum. 2/c e# Divide by 2 and cast to character. ``` [Answer] ## Python 3, ~~61~~ ~~59~~ ~~57~~ 55 bytes I try not to golf with languages I work in, but this isn't too evil. *Thanks to @xsot for 2 bytes!* ``` lambda x:chr((ord(x[len(x)//2])+ord(x[~len(x)//2]))//2) ``` The full program is 59 bytes: ``` x=input() l=len(x)//2 print(chr((ord(x[l])+ord(x[~l]))//2)) ``` Try it [here](https://repl.it/B2mj/4). [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 23 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ~~25 30 31 33~~ ``` ²(x[t=xn/2]c+xv[t]c)/2) ``` Uses @isaacg's idea of reversing the string. [Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22%C2%B2(x%5Bt%3Dxn%2F2%5Dc%2Bxv%5Bt%5Dc)%2F2)%22&inputs=%5B%22hiya%22%5D) [Test all of the cases](http://vihanserver.tk/p/TeaScript/#?code=%22_m(%23(x%3Dl,%20%20%C2%B2(x%5Bt%3Dxn%2F2%5Dc%2Bxv%5Bt%5Dc)%2F2)%20%20))%22&inputs=%5B%2212345%22,%22Hello%22,%22Hiya%22,%22%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) ## Ungolfed && Explanation TeaScript is still JavaScript so it functions a lot like JavaScript too. ``` C((x[t=xn/2]c+xv[t]c)/2) C(( // Char code to char x[t=xn/2]c // Floored center + // Add to xv[t]c // Ceil'd center ) / 2) // Divide by 2 ``` [Answer] # 8086 machine code + DOS, 31 bytes Hexdump: ``` BA 1E 01 B4 0A CD 21 8B F2 46 8A 1C D0 EB 8A 50 01 72 06 74 08 02 10 D0 EA B4 02 CD 21 C3 FF ``` Assembly source code (can be assembled with tasm): ``` .MODEL TINY .CODE org 100h MAIN PROC mov dx, offset buf mov ah, 10 ; DOS function "read string" int 21h mov si, dx inc si ; si now points to the length of the string mov bl, [si] ; shr bl, 1 ; divide the length by 2 mov dl, [si+bx+1] ; load the middle char jc calc_done ; if length was odd - done jz output_done ; if length was zero - exit add dl, [si+bx] ; add the other middle char shr dl, 1 ; divide by 2 calc_done: mov ah, 2 ; DOS function "output char" int 21h output_done: ret buf db 255 ; maximum bytes to input MAIN ENDP END MAIN ``` There is some delicate usage of the FLAGS register here. After it shifts the length of the string right by 1 bit (which is equivalent to division by 2), two flags store additional information: * Carry flag: contains the bit that was shifted out. If the bit is 1, the length was odd. * Zero flag: shows whether the result is zero. If the carry flag is 0 and the zero flag is 1, the length was zero, and nothing should be printed. Normally, the flags should be checked immediately, but here I use the fact that the `mov` instruction doesn't change flags. So they can be examined after loading the middle char. [Answer] # Matlab, ~~39~~ 37 bytes `floor((end+[1,2])/2)` returns the middle two indices of the string if the length is even, and returns the middle indice twice if the length is odd. `mean` just returns the mean of those values and `char` automatically floors it. ``` @(s)char(mean(s(floor(end/2+[.5,1])))) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` c½S¤+öc→←½↔ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr//9jwr1TwqQrw7Zj4oaS4oaQwr3ihpT///8iSGl5YSI "Husk – Try It Online") # Explanation Delicious, delicious combinators all the way down. `ö` is "compose these four functions", `¤` is "apply the first argument to the results of applying the second argument to two additional arguments separately", `S` is "apply this function (which should take two arguments) to `S`'s third argument and to the result of applying `S`'s second argument to its third". Therefore, ``` Function Type Semantics öc→←½ [TChar]->TInt ASCII code of middle (floored) char in string ¤+öc→←½ [TC]->[TC]->TI Sum of ASCII codes of middle of two strings S¤+öc→←½↔ [TC]->TI Sum of ASCII codes of the middle of a string and its reverse c½S¤+öc→←½↔ [TC]->TC ASCII character represented by half the above, QEF ``` Edited to add: Strictly speaking, this fails slightly to conform to the problem specification, which requests a string in the case of an empty input and a character in other cases. Due to Husk's strict typing, it's just not possible to define a function/program that can return either of two types. I chose to return a single character in all cases, and for Husk, the most reasonable choice for a single character to represent the empty string is `'(space)'` because that's the "default" value (and in fact, that's why this program returns it; the default value is used when taking the last (`→`) item of an empty list). I could have also reasonably chosen to return strings of zero or one characters, which would fail the specification in the other direction, but I didn't because it adds four bytes: `Ṡ&ö;c½S¤+öc→←½↔`, with the `;` converting the character to a one-character string, another `ö` to explicitly compose the needful, and a `Ṡ&` to shortcut in the case of falsy input. [Answer] # Prolog, 111 bytes **Code** ``` p(X):-atom_codes(X,L),length(L,N),I is N//2,J is(N-1)//2,nth0(I,L,A),nth0(J,L,B),Q is(A+B)//2,writef('%n',[Q]). ``` **Explained** ``` p(X):-atom_codes(X,L), % Convert to list of charcodes length(L,N), % Get length of list I is N//2, % Get mid index of list J is(N-1)//2, % Get 2nd mid index of list if even length nth0(I,L,A), % Get element at mid index nth0(J,L,B), % Get element at 2nd mid index Q is(A+B)//2, % Get average of elements at mid indices writef('%n',[Q]). % Print as character ``` **Examples** ``` >p('Hello'). l >p('Hiya'). q ``` [Answer] # [R](https://www.r-project.org/), 73 bytes ``` function(x,y=utf8ToInt(x),n=sum(1|y))if(n)intToUtf8(mean(y[n/2+c(1,.5)])) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCp9K2tCTNIiTfM69Eo0JTJ8@2uDRXw7CmUlMzM00jTzMzryQkPxSoQiM3NTFPozI6T99IO1nDUEfPVDNWU/N/moaSoZGxiamSJheQ6ZGak5MPZWZWJkJYmZVIktiIzEqcUhCdSpr/AQ "R – Try It Online") Many thanks to @ngm for coming up with this non-recursive idea - allowed to golf 20 bytes. Old solution: ### [R](https://www.r-project.org/), ~~101~~ 95 bytes ``` "!"=function(x,n=sum(1|x))"if"(n<3,mean(x),!x[-c(1,n)]) try(intToUtf8(!utf8ToInt(scan(,""))),T) ``` [Try it online!](https://tio.run/##DcoxCsMwDEbhPbewJv2gDCFLhuYA3d2pdCgmBg@WIZHBhdzd9fKW7529k6M9Vg2WinIT3a@aebkbQCkS62OVfHwHQVx7z4EXUXww2fnjpObLy@LGro768lTjK4xbiACIRyfqfw "R – Try It Online") Recursive solution. Corrected one issue at the price of 2 bytes: * added `try(expr, silent = TRUE)` to properly manage the case where the input is empty. thanks Giusppe for 4 bytes ! [Answer] # C++14, 56 bytes ``` [](auto s){int l=s.size();return(s[(l-1)/2]+s[l/2])/2;}; ``` Anonymous lambda taking string as an argument and returning int as char code. For `""`, it returns `0`. Not sure how exactly the input and output should look like (is not specified in the question). Ungolfed, with usage ``` #include <string> int main() { auto lmbd = [](auto str) { int len = str.size(); return (str[(len - 1) / 2] + str[len / 2]) / 2; }; std::cout << (char) lmbd("Hiya"s) << std::endl; // outputs q } ``` [Answer] # JavaScript (ES6), 83 bytes ~~89 91~~ *Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ* *Saved 6 bytes thanks to @ETHproductions* ``` s=>String.fromCharCode((s[~~(t=s.length/2-.5)][q='charCodeAt']()+s[0|t+.9][q]())/2) ``` JavaScript's not too good at all this string char code. [Answer] # [O](https://github.com/phase/o), ~~44~~ 34 bytes [Crossed out 44 is still regular 44 :(](https://codegolf.stackexchange.com/a/63373) ``` ise.eJ;2/m[(\($L;dJ{#\#+2/c}L;?o]; ``` Bytes wasted on: * Checking if the input's length is even/odd * Getting the middle character(s) [Answer] ## [Minkolang 0.13](https://github.com/elendiastarman/Minkolang), ~~23~~ 20 bytes ``` $oI2$%d$z,-Xz3&+2:O. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24oI2%24%25d3%7EG%2C-X3%26%2B2%3AO%2E%0A%24oI2%24%25d%24z%2C-Xz3%26%2B2%3AO.&input=hiya) ### Explanation ``` $o Read in the whole stack as characters I2$% Push I,2, then pop them and push I//2,I%2 d$z Duplicate top of stack (I%2) and store in register (z) ,-X <not> the top of stack, subtract, and dump that many off the top of stack z3& Retrieve value from register and jump 3 spaces if this is not zero +2: Add and then divide by 2 O. Output as character and stop. ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~40~~ ~~29~~ ~~23~~ ~~21~~ 20 bytes *Saved 4 bytes thanks to @ןnɟuɐɯɹɐןoɯ* Now only half the original length! I love code golf. :-D ``` UcV=K*Ul)+Uw cV)/2 d ``` Works properly on the empty string. [Try it online!](https://codegolf.stackexchange.com/a/62685/42545) ### How it works ``` // Implicit: U = input string, K = 0.5 Uc // Take the char-code at position V=K*Ul // V = 0.5 * length of U + // (auto-floored), plus Uw cV // the char-code at position V (auto-floored) in the reversed string, /2 d // divide by 2, and turn back into a character (auto-floored). // Implicit: output last expression ``` As you can see, it uses a lot of auto-flooring. (Thanks, JavaScript!) Suggestions welcome! [Answer] # Go, ~~166~~ ~~156~~ 153 bytes Go may not be the best language for golfing... but I love it, so so much, and I'm learning it, so there. This implementation accepts blank (`\n`) input and **will probably break with non-ASCII/ASCII-extended input.** However, OP has not specified input/output encoding thus ASCII is all I've explicitly supported. *Edit*: turns out `if`/`else` *is* shorter than `switch`. Now I know, I suppose. Golfed: ``` package main;import ."fmt";func main(){a:="";_,_=Scanln(&a);if b:=len(a);b>0{x:=b/2;if b%2==0{Printf("%c",(a[x]+a[x+1])/2)}else{Println(string(a[x]))}}} ``` Ungolfed: ``` package main # everything in go is a package. import . "fmt" # the dot allows for absolute package method references # (think "from string import *" in python) func main() { a := "" _, _ = Scanln(&a) # a pointer to a if b := len(a); b > 0 { # if statements allow local assignment statements x := b / 2 if b%2 == 0 { # modulo 2 is the easiest way to test evenness #in which case, average the charcodes and print the result Printf("%c", (a[x]+a[x+1])/2) } else { # else just find the middle character (no rounding needed; integer division in Go always results in an integer) Println(string(a[x])) } } } ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 23 chars ``` a=ïꝈ/2,ϚĎ((ïüa+ᴙïüa)/2) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=asdf&code=a%3D%C3%AF%EA%9D%88%2F2%2C%CF%9A%C4%8E%28%28%C3%AF%C3%BCa%2B%E1%B4%99%C3%AF%C3%BCa%29%2F2%29)` Thanks to @ETHProductions for the idea! [Answer] # C#, 77 bytes ``` s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);}; ``` It doesn't actually return a string, and you'll get a space character if the input string is empty because the function must always return a value. 2 more bytes would be needed to return a string. Full program with test cases: ``` using System; namespace FindTheCenter { class Program { static void Main(string[] args) { Func<string,char>f= s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);}; //77 bytes Console.WriteLine(f("")); Console.WriteLine(f("Hello")); Console.WriteLine(f("Hiya")); } } } ``` --- Alternatively, a full program which reads user input and prints the center of the entered string: # C#, 144 bytes ``` using C=System.Console;class P{static void Main(){var s=C.ReadLine();int n=s.Length;C.Write(n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2));}} ``` Again, it uses the same trick of printing a space character, which the user will not notice, and not an empty string, otherwise the solution is 2 bytes longer. [Answer] ## Vim, ~~38~~ ~~24~~ 23 keystrokes Because vim has a built in function to find the middle *line* but not the middle *char*, we split every character on a separate line first using `substitute`, find the middle line, then delete everything after and before it. ``` :s/\./\0\r/g<cr>ddMjdGkdgg ``` If you want to run this, beware of `.vimrc` files which may change the behavior of `.` (magic regex) and `g` (gdefault). Note that it actually saves me 3 keystrokes on my machine :) ## Previous answer ``` :exe 'norm '.(virtcol('$')/2).'|d^ld$' ``` Takes a one line buffer as input, updates the current buffer with the middle character. I thought there would have been a shortcut for this in vim! Note: a potentially shorter solution seems to cause an infinite loop... If someone has an idea: `qq^x$x@qq@qp` (12 keystrokes) - it works with `<c-c>` after the last `@q`... [Answer] # Excel, ~~122~~ 79 bytes Actually @Sophia Lechner's answer now: ``` =IFERROR(CHAR(CODE(MID(A8,LEN(A8)/2+.5,1))/2+CODE(MID(A8,LEN(A8)/2+1,1))/2),"") ``` --- -5 bytes from initial solution thanks to @Taylor Scott. ``` =IFERROR(IF(ISODD(LEN(A1)),MID(A1,LEN(A1)/2+1,1),CHAR((CODE(MID(A1,LEN(A1)/2,1))+CODE(MID(A1,LEN(A1)/2+1,1)))/2)),"") ``` 12 bytes needed for Empty String. [Answer] # Haskell, 87 bytes A nice recursive solution is possible here: ``` import Data.Char f[]=[] f[c]=[c] f[c,d]=[chr(ord c+div(ord d-ord c)2)] f(c:s)=f$init s ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` JÆṁị¹Æm ``` [Try it online!](https://tio.run/##y0rNyan8/9/rcNvDnY0Pd3cf2nm4Lff/0ckPdy5@1DBHwdZO4VHD3Ic7FvnrHG5Xebi7JwshyvVw95bD7Y@a1kT@/29oZGxiChI35vIAmpgPYuZweWRWJoJYhQA "Jelly – Try It Online") Takes input as a list of codepoints. Outputs a single codepoint. ## How it works ``` JÆṁị¹Æm - Main link. Takes a string S on the left J - Indices of S Æṁ - Median ¹ - Yield S ị - Index into S Æm - Get their arithmetic mean ``` The `Æṁ` median atom returns the mean of the two central elements if the list has an even list. When the list is the indices of `S` (i.e. `[1, 2, ..., len(S)]`), this will always be half the sum of an odd and an even integer, so the result will be \$x + \frac 1 2, x \in \mathbb N\$. When indexing with non-integers such as \$x + \frac 1 2\$, Jelly instead uses the pair \$[x, x+1]\$ to index, which, in this case, results the two central characters if the list length is even. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `K`, 8 bytes ``` ‡ḢṪ↔Ṫtṁ⌊ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=K&code=%E2%80%A1%E1%B8%A2%E1%B9%AA%E2%86%94%E1%B9%AAt%E1%B9%81%E2%8C%8A&inputs=%2212345%22&header=&footer=) Explanation: ``` # 'K' flag - Strings are inputted as a list of ordinal values ‡ḢṪ↔ # Remove the first and last elements elements of the list until empty, returning intermittent values Ṫt # Remove all but the second to last element of the list ṁ # Take the average of the middle character(s) ⌊ # Floor # 'K' flag - Output numbers as characters ``` [Answer] # Mathematica, ~~118~~ 99 chars ``` Floor If[#=="","",FromCharacterCode[%@Mean@#[[Ceiling[l=Length@#/2];;%[l+1]]]&@ToCharacterCode@#]]& ``` Mma character code manipulation is *pricey*... [Answer] # VBA, 130 Bytes ``` Function a(q) h=Len(q):a=Mid(q,(h)/2,2) If h Mod 2=0 Then:a=Chr((Asc(Left(a,1))+Asc(Right(a,1)))\2):Else:a=Right(a,1) End Function ``` > > Finds the Middle 2 Characters. > > If number of Characters is Odd then get the Right of the Middle 2 which will be the true middle as we rounded down. > > If not sum the ASCII `asc()` values of the 2 Characters divided by 2 and return the ASCII Character `chr()` based on that value. > > > I think I can golf away one of the `asc()` calls, but couldn't get it to work shorter. [Answer] # K, 40 bytes ``` {(*|r;`c$_(+/r:2#l_x)%2)@l=_l:-1+(#x)%2} ``` [Answer] ## ><>, 24 + 3 (for -s) = 27 bytes ``` l1+l4(*9$.~{~ ; o; +2,o; ``` Old solution (Doesn't work for empty input): ``` l3(?v~{~ ?vo;>l2= ;>+2,o ``` Both take input on the stack through `-s`. Both are 24 bytes. [Try it online here.](http://fishlanguage.com/playground) [Answer] # [pb](https://esolangs.org/wiki/pb), 83 bytes ``` ^<b[1]>>>w[B!0]{<w[B!0]{t[B]<b[T]>>}<b[0]<b[0]<[X]>>}w[B=0]{<}t[B]<[X]t[B+T]vb[T/2] ``` While there are at least 3 characters in the input string, the first and last are removed. This leaves either 1 character (should be printed unmodified) or 2 (should be averaged and printed). To handle this, the first and last characters of the string are added together and divided by two. If there was only one character, `(a+a)/2==a`. If there was two, `(a+b)/2` is the character that needs to be printed. pb "borrows" Python's expression evaluation (`def expression(e): return eval(e, globals())`) so this is automatically floored. Handling empty input costs me 5 bytes. Specifically, `<b[1]>` on the first line. Earlier, when I said "string", that was a total lie. pb doesn't have strings, it has characters that happen to be close to each other. Looking for the "last character of a string" just means moving the brush to the left until it hits a character. When no input is provided, the "while there are at least 3 characters" loop is skipped entirely and it starts looking for the last character. Without that `<b[1]>`, it would keep looking forever. That code puts a character with a value of 1 at (-1, -1) specifically to be found when the input is empty. After finding the "last character" of the string the brush assumes the first one is at (0, -1) and goes there directly, finding a value of 0. `(1+0)/2` is 0 in pb, so it prints a null character. > > But monorail, that's still printing! The challenge specification says `(empty input) => (empty output)`! Isn't printing a null character cheating? Also, this is unrelated, but you are smart and handsome. > > > Thanks, hypothetical question-asker. Earlier, when I said "print", that was a total lie. In pb, you don't really print values, you just place them on the canvas. Rather than "a way to output", it's more accurate to imagine the canvas as an infinitely large 2D array. It allows negative indices in either dimension, and a lot of programming in pb is really about making sure the brush gets to the location on the canvas that you want it. When the program finishes executing, anything on the canvas with non-negative X and Y coordinates is printed to the appropriate location on the console. When the program begins, the entire canvas is filled with values of 0. In order to not have to print an infinite number of lines, each with an infinite number of null bytes, each line of output is only printed up to the last nonzero character, and lines are only printed up to the last one with a nonzero character in it. So putting a `0` at (0, 0) is still an empty output. **Ungolfed:** ``` ^<b[1]> # Prevent an infinite loop on empty input >>w[B!0]{ # While there are at least 3 chars of input: <w[B!0]{ # Starting at the second character: t[B]<b[T]>> # Copy all characters one position to the left # (Effectively erasing the first character) } <b[0]<b[0] # Delete both copies of the last character <[X]>> # Get in place to restart loop } w[B=0]{<} # Go to last character of remaining string t[B]<[X]t[B+T] # Find it plus the first character vb[T/2] # Divide by 2 and print ``` [Answer] ## CoffeeScript, ~~104~~ 103 bytes ``` f=(x)->((y=x.length)%2&&x[y//2]||y&&String.fromCharCode (x[y/=2][z='charCodeAt']()+x[y-1][z] 0)//2)||'' ``` [Answer] # Ruby, ~~43~~ ~~42~~ 41 bytes ``` ->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]} ``` **42 bytes** ``` ->a{s=a.size;puts s==0?'':s%2<1??q:a[s/2]} ``` **43 bytes** ``` ->a{s=a.size;puts s==0?'':s%2<1?'q':a[s/2]} ``` **Usage:** ``` ->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]}['12345'] => 3 ``` ]
[Question] [ You know—they look like this: [![](https://i.stack.imgur.com/t4uJx.jpg)](https://i.stack.imgur.com/t4uJx.jpg) [source](http://covers8.com/sound-equalizer-rhythm-music-beats/) The goal is to draw a music beats illustration like the following: ``` = = = = = = = = == = == = == = ==== == ==== == === = = ======= ======== == ==== = ========= = ================================= ``` The rules are: * The width of the illustration is 33 symbols, but if you need—any trailing spaces exceeding this width are allowed. * Each column is made of equals signs (`=`). * Each column has a **random height** (the height of the next column shouldn’t depend in any way on the height of the previous column), varying from 1 to 6. It’s also fine if it’s at least *possible* to get some input with no strict math probability (i.e. some inputs could appear more rarely than others). * A column *can’t* float above the bottom and have gaps in it. * Since every column has the minimal height of 1, the last row can’t have any gaps either—it always consists of 33 equals signs. * Since it’s possible to have no columns with the height of 6 (it’s all random after all): in this case you don’t need to have a top line made of spaces. Applies to any edge cases of this nature: if suddenly your code provided no columns with the height greater than 1, you don’t need to have additional lines made of spaces above the bottom line. * **You don’t take any input**. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⊖⍉↑'='⍴¨⍨?33⍴6 ``` ### Explanation `33⍴6` 33 repetitions of 6 `?` random integer in range [1,*n*] for each of the 33 6s `'='⍴¨⍨` equality symbol repeated each of those number of times `↑` convert list of lists to table of rows `⍉` transpose rows into columns, columns into rows `⊖` flip upside down ### Example runs Input is indented six spaces: ``` ⊖⍉↑'='⍴¨⍨?33⍴6 = == = == = = = == ==== == = = = === == === ==== = === = = = ===== ==== === ==== = ==== = === ============== ==== ====== == ================================= ⊖⍉↑'='⍴¨⍨?33⍴6 = = = = = = = = == == == = = === == == = === ======= = ==== == == ====== ========== = ==== ============= ========== = = ================================= ⊖⍉↑'='⍴¨⍨?33⍴6 = = = = = = = = == = = = = = == = ==== === = = = = = = == = ==== ==== ===== = == == ============ ==== ================================= ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes And I [outgolfed Jelly](https://codegolf.stackexchange.com/a/85068/48934). ``` j_.tm*hO6\=33 ``` [Try it online!](http://pyth.herokuapp.com/?code=j_.tm%2ahO6%5C%3D33&debug=0) ``` j_.tm*hO6\=33 m 33 for 33 times: O6 yield a random number in [0,1,2,3,4,5]. h add one. * \= repeat "=" that number of times. .t transpose, filling with whitespace _ reverse j join by newlines. ``` [Answer] # JavaScript (ES6), 116 bytes ``` (a=Array(33).fill``.map(_=>[,,,,,,].fill` `.fill('=',Math.random()*6)))[0].map((x,i)=>a.map(x=>x[i]).join``).join` ` ``` ![Snippet preview](https://i.stack.imgur.com/o3CW1.png) Check it out in the animated snippet below: ``` F = () => (a=Array(33).fill``.map(_=>[,,,,,,].fill` `.fill('=',Math.random()*6)))[0].map((x,i)=>a.map(x=>x[i]).join``).join` ` var interval; G = () => output.innerHTML = F().split('\n').map((r, i) => `<span id="row-${6-i}">${r}</span>`).join('\n'); A = () => { clearInterval(interval); if (auto.checked) { speed.disabled = false; interval = setInterval(G, speed.value); } else { speed.disabled = true; } } S = () => { if (stylized.checked) { output.classList.add('stylized'); } else { output.classList.remove('stylized'); } } generate.onclick = G; auto.onchange = speed.onchange = A; stylized.onchange = S; G(); A(); S(); ``` ``` #output { background: #000; color: #9fff8a; overflow: hidden; padding: 1em; line-height: 1; } #output.stylized { line-height: 0.25; font-size: 2em; margin: 0.5em 0 0 0; padding: 0.5em; } .stylized #row-1 { color: #9fff8a; } .stylized #row-2 { color: #c5ff8a; } .stylized #row-3 { color: #e0ff8a; } .stylized #row-4 { color: #ffe88a; } .stylized #row-5 { color: #ffc28a; } .stylized #row-6 { color: #ff8a8a; } ``` ``` <button id="generate">Generate</button> <label>Auto: <input id="auto" type="checkbox" checked/></label> <label>Speed: <select id="speed"> <option value="25">25</option> <option value="50">50</option> <option value="100" selected>100</option> <option value="200">200</option> <option value="400">400</option> <option value="600">600</option> <option value="800">800</option> <option value="1000">1000</option> </select></label> <label>Stylized: <input id="stylized" type="checkbox" checked/></label> <pre id="output"></pre> ``` [Answer] # Jelly, 14 bytes ``` 6x33X€”=ẋz⁶Ṛj⁷ ``` [Try it here.](http://jelly.tryitonline.net/#code=NngzM1jigqzigJ094bqLeuKBtuG5mmrigbc&input=) [Answer] # C, 87 bytes ``` f(x,y){for(y=6;y--;){srand(time(0));for(x=33;x--;)putchar("= "[rand()%6<y]);puts("");}} ``` Call as `f();`. This answer relies on the fact that six consecutive calls to `time(0)` return the same result (in seconds). This is virtually always true, but probably worth mentioning. [Answer] ## Cheddar, ~~68~~ 65 bytes (non-competing) ``` ->(1:33).map(->IO.sprintf("%6s","="*Math.rand(1,7))).turn().vfuse ``` O\_O Cheddar is actually doing good! Uses `sprintf` and `turn` to do a bulk of the work. `vfuse` is vertical-fuse meaning it joins the array but vertically. This is very golfy but also rather fast. Version is prerelease v[1.0.0-beta.10](https://github.com/cheddar-lang/Cheddar/releases/tag/v1.0.0-beta.10), which post-dates the challenge. ## Explanation ``` -> // Anonymous function (1:33) // Range 1-33 inclusive .map(-> // Loop through the above range IO.sprintf("%6s", // `sprintf` from C/C++ "="*Math.rand(1,7) // Repeat `=` a random time from [1,7) ) ).turn().vfuse // Turn it 90deg, and fuse it vertically ``` Some example runs: [![enter image description here](https://i.stack.imgur.com/13iNL.png)](https://i.stack.imgur.com/13iNL.png) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 22 bytes No auto joining, no automatic filling while transposing, osabie is doomed on this one. Code: ``` 33F6ð×6L.R'=×ðñ})ø€J¶ý ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=MzNGNsOww5c2TC5SJz3Dl8Oww7F9KcO44oKsSsK2w70&input=). [Answer] # Python 2, 95 bytes ``` from random import* x=map(randrange,[6]*33) for y in range(6):print''.join('= '[z>y]for z in x) ``` [Answer] # Python 3, 115 bytes Python never even had a chance... ``` from random import* for k in zip(*[[' ']*(6-len(j))+j for j in[randint(1,6)*['=']for i in[0]*33]]):print(*k,sep='') ``` **How it works** ``` from random import* Import everything in the random module randint(1,6)*['='] Create a list containing a random number in [1,6] of '='... ...for i in[0]*33 ...33 times... [...] ...and store in a list X for j in... For all lists j in X... [' ']*(6-len(j))+j ...create a list containing j padded with the correct number of spaces to give a height of 6... [...] ...and store in a list Y Y now contains a list for each output line, but transposed. for k in zip(*...):... For all lists k in the transpose of Y... print(*k,sep='') Print all elements in k with no separating space ``` [Try it on Ideone](https://ideone.com/qOjFec) [Answer] # MATL, ~~20~~ ~~19~~ ~~18~~ 17 bytes *1 byte saved thanks to @Luis* ``` 33l2$r6*6:>!~61*c ``` [**Try it Online**](http://matl.tryitonline.net/#code=MzNsMiRyNio2Oj4hfjYxKmM&input=) [Answer] # SpecaBAS - 76 bytes ``` 1 FOR x=1 TO 33: r=1+INT(RND*6): FOR y=7-r TO 6: ?AT y,x;"=": NEXT y: NEXT x ``` Prints an equal sign at the relevant screen coordinate. [![enter image description here](https://i.stack.imgur.com/5hvKl.png)](https://i.stack.imgur.com/5hvKl.png) with a spot of colour and a `GOTO` loop it becomes [![enter image description here](https://i.stack.imgur.com/l59rD.gif)](https://i.stack.imgur.com/l59rD.gif) [Answer] # K4, 18 bytes Essentially a port of the APL solution (unsurprisingly). ``` +-6$(33?1+!6)#'"=" ``` [Answer] # C#, ~~200~~ 117 bytes ``` ()=>{var s="";int x,y=6;for(;y-->0;){var r=new Random();for(x=33;x-->0;)s+="= "[r.Next(6)<y?1:0];s+='\n';}return s;}; ``` I move to @Lynn [algorithm](https://codegolf.stackexchange.com/questions/85061/illustrate-music-beats/85078#85078) and save 83 bytes! C# lambda without input and where output is a string. [Try it online](https://dotnetfiddle.net/0F7K3b). Code: ``` ()=>{ var s="";int x,y=6; for(;y-->0;){ var r=new Random(); for(x=33;x-->0;) s+="= "[r.Next(6)<y?1:0]; s+='\n'; }return s; }; ``` [Answer] ## Haskell, 164 Bytes Being a purely functional language, Haskell was doomed from the start. I did it anyway and it turns out, that the necessary overhead is actually not that large. ``` import System.Random import Data.List f r n|r>n=' '|0<1='=' s=do g<-newStdGen mapM_ putStrLn$transpose$map(\n->map(f$mod n 6)[0..5])(take 33(randoms g)::[Int]) ``` **Usage:** ``` s ``` **Explanation:** ``` import System.Random ``` to be able to use `newStdGen` and `randoms` ``` import Data.List ``` to be able to use `transpose` ``` f r n|r>n=' '|0<1='=' ``` defines a function that prints a space if its first argument is larger than the second and a `=` otherwise. It is called with `map (f m) [0..5]` on a given number `m` and the list `[0,1,2,3,4,5]`. (See below) ``` s=do g<-newStdGen ``` Creates a new standard random number generator ``` (take 33(randoms g)::[Int]) ``` takes 33 random integers. ``` map(\n->map(f$mod n 6)[0..5]) ``` Calculates `m = n % 6` and maps `(f m)` to the list `[0,1,2,3,4,5]`, which results in one of `"======", " =====", ..., " ="`. These lines are mapped to the list of the 33 random integers resulting in a table. (A table in Haskell is a list of lists) ``` transpose$ ``` switches columns and rows of the table ``` mapM_ putStrLn$ ``` prints every line in the table [Answer] ## CJam, 19 bytes ``` {5mrS*6'=e]}33*]zN* ``` [Try it online!](http://cjam.aditsu.net/#code=%7B5mrS*6'%3De%5D%7D33*%5DzN*) ### Explanation ``` { e# 33 times... 5mr e# Push a random number in [0 1 2 3 4 5]. S* e# Create a string with that many spaces. 6'=e] e# Pad to length 6 with =. }33* ] e# Wrap all 33 strings in a list. z e# Transpose that list. N* e# Join the lines with linefeeds. ``` [Answer] # Mathematica, 78 bytes ``` StringRiffle[(PadLeft[Array["="&,#+1],6," "]&/@5~RandomInteger~33)," ",""]& ``` Anonymous function. Takes no input and returns a string as output. The Unicode character is U+F3C7, representing `\[Transpose]`. [Answer] # R, 102 bytes ``` m=rep(" ",33);for(i in 1:6){n=ifelse(m=="=",m,sample(c(" ","="),33,T,c(6-i,i)));m=n;cat(n,"\n",sep="")} ``` ### Explanation `m=rep(" ",33)` init an empty vector for the upcoming loop `n=ifelse(m=="=",m,sample(c(" ","="),33,T,c(6-i,i)))` If there's an `=` in the row above, then make sure the spot below also has an `=`; otherwise randomly pick. Random picks are weighted to make sure that a) the bottom row is all `=` and b) you get a neat shape to the whole thing. `cat(n,"\n",sep="")` output that row to the console with a newline at the end and no spaces between elements! [Answer] # PHP, ~~95~~ ~~92~~ 89 bytes ``` <?php for(;++$i<34;)for($j=6,$e=' ';$j--;)$a[$j].=$e=rand(0,$j)?$e:'=';echo join(" ",$a); ``` Pretty happy with this one actually. For a while I had a version that in theory could generate any input but in practise would generate only solid blocks of = but this is both shorter and equally distributed! Generates 7 undefined something notices whenever you run it but that's fine. edit: well I just learned that join is an alias of implode, so that's nice. [Answer] # J, 18 bytes ``` |.|:'='#~"0>:?33#6 ``` Very simple stuff. With a bugfix from miles! [Answer] ## Perl, 64 bytes ``` @f=$_="="x33;s/=/rand>.4?$&:$"/ge,@f=($_.$/,@f)while@f<6;print@f ``` ### Usage ``` perl -e '@f=$_="="x33;s/=/rand>.3?$&:$"/ge,@f=($_.$/,@f)while@f<6;print@f' = = = == = = = = === == = = = = = === == = = = = = = = === === = = = = = == ===== === ==== === = = ================================= ``` --- ## Perl, 68 bytes Alternative version that relies on ANSI escape codes to move the cursor around, first dropping down 6 lines, then writing the original line (all the `=`s), moving up a line and printing the replaced string (`s/=/rand>.4?$&:$"/ge`) repeatedly until it makes no more substitutions. This can end up writing more than six lines, but it is eventually replaced with an empty line. **Note: `\x1b`s are actually the ASCII `Esc` character.** ``` print"\x1bc\x1b[6B",$_="="x33;print"\x1b[1A\x1b[33D$_"while s/=/rand>.4?$&:$"/ge ``` [Answer] # Ruby, ~~102~~ ~~99~~ ~~84~~ 83 bytes ``` s=' '*203;33.times{|j|a=(' '*rand(6)).ljust 6,'=';6.times{|i|s[i*34+j]=a[i]}};$><<s ``` New and significantly shorter approach, where I start with string full of newlines. Older version... ``` s='';204.times do|i|s+=->i{i%34==0?"\n":i>170?'=':s[i-34]=='='?'=':rand(2)==1?'=':' '}[i]end;puts s ``` ...gave output with leading new line. My first submission in Ruby, using similar approach to @Barbarossa's one, but in single loop. What I liked in Ruby while working on this program: * `.times` loop * `rand()` which is pretty short * stacking ternary operators without parentheses I didn't like (mainly in terms of golfing): * ~~mandatory `$` for global variables~~ not so mandatory in `.times` loop * ~~`do` and `end` keywords~~ which can be replaced with single-line block * `0` is not falsy [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` F³³⁺×=⁺¹‽⁶¶⟲ ``` Beats Pyth by 1 byte! Link is to verbose version of code. [Try it online!](https://tio.run/##S85ILErOT8z5/98tv0jD2FhTIaAoM69EIyCntFgjJDM3tVhDyVZJx1A7KDEvJT9Xw0xTU0cpJk9JU5MrKL8ksST1////ujll/3V1U1LLUouS8osz0yoB "Charcoal – Try It Online") [Answer] # JavaScript, 179 bytes Still working on golfing this a bit. I like this since it's straightforward. ``` n=>{a=Array(33).fill(0).map(n=>Math.floor(Math.random()*6)+1);r=Array(6).fill("");r.map((e,m)=>{a.map(n=>{if (n<=m+1){r[m]+="="}else r[m]+=" "})});return r.join('\n');} ``` Usage: ``` >q=n=>{a=Array(33).fill(0).map(n=>{return Math.floor(Math.random() * 6)+1}); r=Array(6).fill("");r.map((e,m)=>{a.map(n=>{if (n<=m+1){r[m]+="="}else r[m]+=" "})});return r.join('\n');} >q(); = = = = = = = = = = = = == = = = = = = = = === ==== ==== = = === = = = = === ========== ======= = === =========================== ================================= ``` [Answer] # Forth, 190 bytes I had to create my own [PRNG](http://ideone.com/6aEScs), an xor-shift taken from [here](http://excamera.com/sphinx/article-xorshift.html). The word `f` is the word you would call multiple times to see the output. ``` variable S utime S ! : L lshift xor ; : R S @ dup 13 L dup 17 rshift xor dup 5 L dup S ! 6 mod ; : f 33 0 DO R LOOP 1 -5 DO 33 0 DO I PICK J + 0< 1+ IF ." =" ELSE SPACE THEN LOOP CR LOOP ; f ``` [**Try it online**](http://ideone.com/CWQRAk) - Note that the system time is one of two values based on which server (or something) is running the code. Other than that, they don't change in the online IDE for some reason. So you'll only see two possible outputs. You can manually set the seed by changing `utime` to an integer. ### Ungolfed ``` variable seed \ seed with time utime seed ! : RNG \ xor-shift PRNG seed @ dup 13 lshift xor dup 17 rshift xor dup 5 lshift xor dup seed ! 6 mod \ between 0 and 6, exclusive ; : f 33 0 DO RNG LOOP \ push 33 randoms 1 -5 DO \ for (J = -6; J < 0; J++) 33 0 DO \ for (I = 0; I < 33; I++) I PICK J + 0< 1+ IF \ if (stack[I] < J) 61 EMIT \ print "=" ELSE 32 EMIT \ print " " THEN LOOP CR \ print "\n" LOOP ; f ``` [**Ungolfed online**](http://ideone.com/0tkCSN) [Answer] # JavaScript, 165 Bytes ``` // function that fills a column with a specified number of = signs m=l=>Array(6).fill``.map((e,i)=>i<l?"=":" "); // fill an array of 33 length with columns of random number of = signs a=Array(33).fill``.map(e=>m(Math.ceil(Math.random()*6))); // transponse the rows and columns and print to console a[0].map((c,i)=>a.map(r=>r[5-i])).map(r=>console.log(r.join``)) ``` The newlines are unnecessary but they make it easier to see what's going on. Not the most optimal solution, but it makes sense to me at least. ]
[Question] [ ### Task > > Find all the non-negative integers up to and including a given non-zero positive integer *n*, that are prime and the count of `1's` and `0's` in their binary representation (having no leading zeroes) are prime too. > > > Here are the first five such primes, ``` 17, 19, 37, 41, 79 10001, 10011, 100101, 101001, 1001111 ``` ### Clarifications and rules * [Default I/O methods are accepted](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?noredirect=1&lq=1). * The answer can be a program or a function. * If there are no such primes then output garbage or nothing. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?noredirect=1&lq=1) are forbidden. * `2 3 5 7` did not make it to the list because in their binary representation number of occurrences of `0's` and `1's` are not prime. Consider `7`whose binary representation is `111`, here `0` occurs zero times and zero is not prime. * Built-ins are allowed. * The shortest code in bytes wins! ### Test cases ``` 10 [] 100 [17, 19, 37, 41, 79] 150 [17, 19, 37, 41, 79, 103, 107, 109, 131, 137] ``` ``` /* Configuration */ var QUESTION_ID = 107050; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 47650; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~106~~ ~~102~~ 100 bytes ``` k=m=1;p={0} exec"p^={m%k*k,0};c=bin(k).count\nif{k,c('1'),c('0')-1}<p:print k\nm*=k*k;k+=1;"*input() ``` [Try it online!](https://tio.run/nexus/python2#@59tm2traF1gW21Qy5VakZqsVBBnW52rmq2VrWNQa51sm5SZp5GtqZecX5pXEpOXmVadrZOsoW6orgmiDNQ1dQ1rbQqsCooy80oUsmPycrVsgVqts7WBhippZeYVlJZoaP7/b2hqAAA "Python 2 – TIO Nexus") ### Background To identify primes, we use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem): ![corollary of Wilson's theorem](https://i.stack.imgur.com/ordYr.png) ### How it works We start by initializing **k** and **m** as **1** and **p** as the set **{0}**. Note that **m = 1 = 0!² = (k - 1)!²**. Immediately afterwards, the following code is executed **n** times, where **n** is the integer read from standard input. ``` p^={m%k*k,0};c=bin(k).count if{k,c('1'),c('0')-1}<p:print k m*=k*k;k+=1 ``` By the corollary, **m % k** will be **1** if **k** is prime and **0** otherwise. Thus, `{m%k*k,0}` will return the set **{k, 0}** if **k** is prime and the set **{0}** otherwise. If (and only if) **k** is prime, since **p** cannot contain **k** at this point, the in-place symmetric difference `p^={m%k*k,0}` will add **k** to the set **p**. Also, **p** will contain **0** after the update if and only if it does not contain **0** before, so **0 ∊ p** if and only if **k** is even. On the same line, we define a function **c** via `c=bin(k).count`, which will count the occurrences of its argument in **k**'s binary representation. The second line produces the actual output. `{k,c('1'),c('0')-1}` returns the set that consists of **k** itself, the number of set bits in **k**, and the number of unset bits in **k**. Since the output of `bin(k)` begins with **0b**, we have to decrement `c('0')` to account for the leading **0**. If all of them are prime, they will all belong to **p**, which by now contains all prime numbers up to **k** (and potentially **0**). If **k** is a Mersenne number (i.e., if it has only set bits), `c('0')-1` will yield **0**. Since Mersenne numbers are odd, **p** will *not* contain **0**, so the condition will fail. After (potentially) printing **k**, we multiply **m** by **k²**. Since **m = (k-1)!²** before the update, **m = k!²** after it. After incrementing **k**, the relation **m = (k-1)!²** holds again and we're ready for the next iteration. [Answer] # Mathematica, ~~80~~ ~~68~~ 54 bytes ``` Select[p=PrimeQ;Range@#,p@#&&And@@p/@#~DigitCount~2&]& ``` **Explanation** ``` Select[p=PrimeQ;Range@#,p@#&&And@@p/@#~DigitCount~2&]& p=PrimeQ (* Store prime check func. in p *) Select[ ] (* Select *) Range@# (* from a list {1..n} *) p@# (* numbers that are prime *) && (* And *) #~DigitCount~2 (* whose digit counts in binary *) And@@p/@ (* are prime as well *) ``` [Answer] # JavaScript (ES6), ~~123~~ ~~118~~ ~~115~~ ~~111~~ ~~104~~ 96 bytes *Saved 4 bytes thanks to @Arnauld* ``` G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1) F=n=>F(n-1,G(n,a=[0,0,n])||alert(n)) ``` A combination of three typical recursive functions. Alerts the sequence in reverse order and terminates on a "too much recursion" error. ### Test snippet (modified to output to the page) ``` alert = s => O.textContent += s + "\n" G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1) F=n=>F(n-1,G(n,a=[0,0,n])||alert(n)) F(1000) ``` ``` <pre id=O></pre> ``` The main function can return an array for 104 bytes: ``` G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1) F=n=>n?F(n-1).concat(G(n,a=[0,0,n])?[]:n):[] ``` It can also be non-recursive at the cost of another byte: ``` G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1) n=>[for(_ of Array(n))if(!G(--n,a=[0,0,n]))n] ``` --- Here's the one I started with: *(Saved 6 bytes thanks to @Arnauld)* ``` P=(n,x=n)=>n>1&--x<2||n%x&&P(n,x) G=n=>n?G(n>>1,o+=n%2,t++):P(o)&P(t-o) F=n=>n?F(n-1).concat(P(n)&G(n,o=t=0)?n:[]):[] ``` I tried golfing this further and managed to do it in 104 bytes—then realized I had already found that solution (it's at the bottom of the answer). Don't you hate it when that happens? :P A non-recursive attempt at the main function (again, same byte count): ``` n=>[for(i of Array(n))if(P(--n)&G(n,o=t=0))n] ``` --- This one takes the easy route of counting how many 0's and 1's are in the binary representation: ``` F=n=>n?F(n-1).concat([n,(G=x=>n.toString(2).split(x).length-1)(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[] ``` Same thing with an array comprehension: ``` n=>[for(_ of Array(n))if(![--n,(G=x=>n.toString(2).split(x).length-1)(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1))n] ``` This one takes a slightly harder route to do the same thing: ``` F=n=>n?F(n-1).concat([n,(G=(x,w=n)=>w&&G(x,w>>1)+(w%2==x))(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[] ``` And this one takes yet another related route that's as short as the original: ``` F=n=>n?F(n-1).concat([n,o=(G=x=>x&&x%2+G(n>>++t))(n,t=0),t-o].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[] ``` Again, you can golf 8 bytes by making it alert the sequence in reverse order: ``` F=n=>F(n-1,[n,o=(G=x=>x&&x%2+G(n>>++t))(n,t=0),t-o].some(n=>(P=x=>n%--x?P(x):x)(n)-1)||alert(n)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BĠL€µ;LÆPẠ ÆRÇÐf ``` **[Try it online!](https://tio.run/nexus/jelly#ASEA3v//QsSgTOKCrMK1O0zDhlDhuqAKw4ZSw4fDkGb///8xMDA "Jelly – TIO Nexus")** ### How? ``` BĠL€µ;LÆPẠ - Link 1, hasPrimeBits: n e.g. 7 or 13 B - convert to binary e.g. [1,1,1] or [1,1,0,1] Ġ - group indices e.g. [1,2,3] or [3,[1,2,4]] L€ - length of €ach e.g. 3 or [1,3] µ - monadic chain separation ;L - concatenate length e.g. [3,1] or [1,3,2] - this caters for the edge case of Mersenne primes (like 7), which have - no zero bits, the length will be 1, which is not prime. ÆP - isPrime? e.g. [1,0] or [0,1,1] Ạ - All? e.g. 0 or 0 ÆRÇÐf - Main link: N ÆR - prime range (primes up to and including N) Ðf - filter keep those satisfying Ç - last link (1) as a monad ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ƒNpNbSD_‚OpP&– ``` [Try it online!](https://tio.run/nexus/05ab1e#@39skl@BX1KwS/yjhln@BQFqjxom//9vaGoAAA "05AB1E – TIO Nexus") **Explanation** ``` ƒ # for N in [0 ... input] Np # push N is prime Nb # push N converted to binary S # split into individual digits D_ # push an inverted copy ‚ # pair the 2 binary lists O # sum them p # elementwise check for primality P # product of list & # and with the primality of N – # if true, print N ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` RBċþd`ÆPPTfÆR ``` [Try it online!](https://tio.run/nexus/jelly#@x/kdKT78L6UhMNtAQEhaYfbgv7//29oagAA "Jelly – TIO Nexus") ### How it works ``` RBċþd`ÆPPTfÆR Main link. Argument: n R Range; yield [1, ..., n]. B Binary; convert each integer to base 2. d` Divmod self; yield [n : n, n % n], i.e., [1, 0]. ċþ Count table; count the occurrences of 1 and 0 in each binary representation, yielding a pair of lists of length n. ÆP Test each count for primality. P Product; multiply the corresponding Booleans. T Truth; get all indices of 1, yielding the list of integers in [1, ..., n] that have a prime amount of 0's and 1's. ÆR Prime range; yield all primes in [1, ..., n]. f Filter; intersect the lists. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 15 bytes ``` LDpÏvybSD_)OpP— ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@@/jUnC4v6wyKdglXtO/IOBRw5T//w0NDAA "05AB1E – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` :"@tB!t~hshZp?@ ``` [Try it online!](https://tio.run/nexus/matl#@2@l5FDipFhSl1GcEVVg7/D/v6GpAQA "MATL – TIO Nexus") ``` : % Input n (implicit). Push range [1 2 ... n] " % For each k in [1 2 ... n] @ % Push k tB! % Duplicate. Binary expansion as an m×1 vector t~ % Duplicate. Negate hs % Concatenate horizontally into an m×2 matrix. Sum of each column. % This gives a 1×2 vector. However, for k==1 this gives the sum of % the original 1×2 matrix (m==1). But fortunately it doesn't matter % because 1 is not a prime anyway h % Concatenate horizontally into a 1×3 row vector Zp % Isprime function applied on each of those three numbers ? % If all gave true @ % Push k % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] ## Perl, 101 bytes 99 bytes of code + `-nl` flags. ``` $r=q/^1?$|^(11+)\1+$/;for$@(2..$_){$_=sprintf"%b",$@;print$@if(1x$@)!~$r&y/01/1/dr!~$r&s/0//gr!~$r} ``` To run it: ``` perl -lne '$r=q/^1?$|^(11+)\1+$/;for$@(2..$_){$_=sprintf"%b",$@;print$@if(1x$@)!~$r&y/01/1/dr!~$r&s/0//gr!~$r}' <<< 150 ``` **Some short explanations** `$r` holds the classical prime checking regex (`q/^1?$|^(11+)\1+$/`). For all numbers between 2 and the input, `(1x$@)!~$r` checks if the number is prime, `y/01/1/dr!~$r` checks if the number of `0` in the binary representation is prime, `s/0//gr!~$r` checks if the number `1` in the binary representation is prime. (if the 3 conditions are met, `print$@` prints it). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅPʒbTS¢pP ``` Pretty straight-forward. [Try it online](https://tio.run/##yy9OTMpM/f//cGvAqUlJIcGHFhUE/P9vaGoAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w60BpyYlhQQfWlQQ8L9W53@0oYGOoQEQm4Jpg1gA). **Explanation:** ``` ÅP # Push a list of all prime numbers below or equal to the (implicit) input ʒ # Filter this list of primes by: b # Convert it to a binary string TS # Push 10, and pop and convert it to a list of digits as strings: ["1","0"] ¢ # Count those characters in the binary string p # Check for both those counts whether they're a prime number P # Check that this is truthy for both of them # (after which the filtered list is output implicitly as result) ``` There seems to be a bug in the count builtin `¢` when using an integer list on a string, so some alternatives to `TS` like `Љ`, `0L`, or `1Ý` doesn't seem to work and result in a pair of the binary string instead, unless we add a `§` (cast to string): [Try it online](https://tio.run/##yy9OTMpM/f//cGvAua1JIcGHFtXqHNpmzwXhH57wqGEDqpCBDyrf8PBcbHqWY@hajqkPLPT/v6GpAQA). [Answer] # Python, ~~129~~ ~~125~~ 123 bytes If only zero were prime... ``` p=lambda n:all(n%m for m in range(2,n))*n>1 lambda n:[i for i in range(n+1)if p(i)*all(p(bin(i)[2:].count(x))for x in'01')] ``` [**Try it online**](https://repl.it/FKoP/3) Function `p` is the prime-checking function, which has `>0` at the end so that it works for zero as well, which would otherwise return `-1`. The anonymous lambda is the lambda that checks all the conditions required. --- Here's a slightly different method using a set comprehension. The result will be a set. (**124 bytes**): ``` p=lambda n:all(n%m for m in range(2,n))*n>1 lambda n:{i*p(i)*all(p(bin(i)[2:].count(x))for x in'01')for i in range(n+1)}-{0} ``` [Answer] # [Perl 6](https://perl6.org), 65 bytes ``` {grep {all($^a,|map {+$a.base(2).comb(~$_)},0,1).is-prime},0..$_} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V@dXpRaoFCdmJOjoRKXqFOTmwjkaask6iUlFqdqGGnqJefnJmnUqcRr1uoY6Bhq6mUW6xYUZeamArl6eirxtf8LSksUwIYZmhr8BwA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 grep # find all of the values where { # lambda with placeholder parameter 「$a」 all( # all junction ( treat multiple values as a single value ) $^a, # declare parameter to block |\ # slip the following list into the outer list # get the count of 0's and 1's in the binary representation map { # bare block lambda with implicit parameter 「$_」 + # turn to numeric ( count the values in the list ) $a # the outer parameter .base(2) # in base 2 .comb(~$_) # find the characters that are the same as },0,1 # 0 or 1 # ask if $a, count of 0's, count of 1's are all prime ).is-prime }, 0 .. $_ # Range from 0 to the input inclusive } ``` [Answer] # Octave, 73 bytes ``` @(n)(p=primes(n))(all(isprime([s=sum(dec2bin(p)'-48);fix(log2(p))+1-s]))) ``` [Try It Online!](https://tio.run/#svX40) ``` @(n) (p=primes(n)) generate prime numbers (all( from them select those that isprime( are prime both [s=sum(dec2bin(p)'-48); sum of 1s fix(log2(p))+1-s]))) and sum of 0s ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~26~~ 27 bytes ``` ri){mp},{2b_1-,mp\0-,mp&},p ``` Straightforward algorithm, will golf further. EDIT: Forgot n was inclusive. [Try it online!](https://tio.run/nexus/cjam#@1@UqVkdn1sQY5QUb6irA2QYgEg1tVqdgv//DQ0MAA "CJam – TIO Nexus") For fun, this is very similar and also 27 bytes: ``` ri){_mp\2b_1-,mp\0-,mp&&},p ``` **Explanation** ``` ri e# Take an int as input ){mp}, e# Take the range up and including to the input, e# including only prime numbers { e# For each prime... 2b_ e# Convert it to binary and copy it 1-,mp e# Take the top binary number, remove 1's, check if the length e# is prime \ e# Swap top elements 0-,mp e# Do the same but remove 0's & e# And }, e# Filter out primes for which the above block was false p e# Print nicely ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` BċÆPðÐf ÆRç0ç1 ``` [Try it online!](https://tio.run/nexus/jelly#ARwA4///QsSLw4ZQw7DDkGYKw4ZSw6cww6cx////MTUw "Jelly – TIO Nexus") Unfortunately, I could only tie with @Dennis, but the algorithm seems to be somewhat different so I'm posting this anyway. ## Explanation Helper function (deletes list elements that don't have a prime number of occurrences of a given bit): ``` BċÆPðÐf Ðf Filter {the first argument}, looking for truthy returns from ð the preceding code, which takes two arguments: B Convert {the element being checked} to binary ċ Count the number of occurrences of {the second argument} ÆP Return true if prime, false if not prime ``` Main program: ``` ÆRç0ç1 ÆR Generate all primes from 2 to the input ç0 Call the subroutine to require a prime 0 count ç1 Call the subroutine to require a prime 1 count ``` [Answer] # Haxe, ~~169~~ 171 bytes ``` function f(n,?p)return[for(j in(p=[for(i in 0...++n)i<2?0:i]))if(j>0){var x=j*2,y=0,z=0,k=j;while(k<n)p[k+=j]=0;while((x>>=1)>0)x&1>0?y++:z++;p[y]<1||p[z]<1?continue:j;}]; ``` Nothing crazy. Essentially a modified sieve of Eratosthenes that evaluates the primality of the 0 / 1 count in the same iteration as crossing out higher non-primes. With some whitespace: ``` function f(n, ?p) return [ for (j in (p = [ for(i in 0...++n) i < 2 ? 0 : i ])) if (j > 0){ var x = j * 2, y = 0, z = 0, k = j; while (k < n) p[k += j] = 0; while((x >>= 1) > 0) x & 1 > 0 ? y++ : z++; p[y] < 1 || p[z] < 1 ? continue : j; } ]; ``` But today I learned I could put `continue` in a ternary operator and Haxe doesn't even mind. Edit: +2 because `n` is an inclusive upper bound! [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~129~~ ~~126~~ ~~123~~ ~~114~~ ~~111~~ 109 bytes ``` seq '-fp()([ `factor|wc -w` = 2 ]);g()(dc -e2o${n}n|tr -cd $1|wc -c|p);n=%.f;p<<<$n&&g 0&&g 1&&echo $n' $1|sh ``` [Try it online!](https://tio.run/nexus/bash#HYqxDoMgGAZf5RsoykAjJp3AJ2lMbH5Bpx@qJg7SZ0ftcsPdldV/UemQalW/MYQPbXHJO0HvAzq06JWdrjZexrdRHPzjvC3QNEKY/0g5Kcvd4xlscs4JlnJCc8NI6WmOEFzd8zqXUsyrOQE "Bash – TIO Nexus") Noticed the comment that the output doesn't have to be in increasing order -- shaved off 3 bytes by counting down instead of counting up. Replaced grep with wc to save 3 additional bytes. Eliminated a variable (9 more bytes off). Changed the way factor is used -- 3 more bytes. Made it golfier with seq (2 bytes). [Answer] # [Perl 6](http://perl6.org/), 50 bytes ``` {grep {($_&+.base(2).comb(~0&~1)).is-prime},0..$_} ``` Variation of [b2gills' answer](https://codegolf.stackexchange.com/a/107079/14880), using the `&` [junction](https://docs.perl6.org/type/Junction) operator to great effect. [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V@dXpRaoFCtoRKvpq2XlFicqmGkqZecn5ukUWegVmeoqamXWaxbUJSZm1qrY6CnpxJf@784sVIhTcHQ1OA/AA "Perl 6 – TIO Nexus") ### How it works ``` { } # Lambda 0..$_ # Range from 0 to the lambda argument. grep { }, # Filter values satisfying: ($_ ).is-prime # a) The Number itself is prime. ( +.base(2).comb(~0 )).is-prime # b) The count of 0's is prime. ( +.base(2).comb( ~1)).is-prime # c) The count of 1's is prime. & & # Junction magic! :) ``` [Answer] ## Python, ~~172~~ ~~170~~ ~~168~~ ~~159~~ ~~154~~ ~~133~~ 130 bytes ``` p=lambda n:[i for i in range(1,n)if n%i==0]==[1] lambda n:[i for i in range(n+1)if p(i)*all(p(bin(i)[2:].count(x))for x in'10')] ``` --- Usage: Call the anonymous lambda function Method `p` checks whether a number is prime --- Saved 2+2+9=13 bytes thanks to Gurupad Mamadapur Saved 5 bytes thanks to mbomb007 [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ò≥úû╙2ï⌡T5è╧²■ ``` [Run and debug it](https://staxlang.xyz/#p=95f2a396d3328bf554358acffdfe&i=10%0A100%0A150&a=1&m=2) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` 'bĊvtJ₅3=$væA∧ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%27b%C4%8AvtJ%E2%82%853%3D%24v%C3%A6A%E2%88%A7&inputs=100&header=&footer=) ``` ' # (implicitly convert to range), then filter by... b # Binary representation Ċ # Count the amount of each value in a (1 & 0 only) vt # Get the counts J # Join the current number to each of those ₅ # Duplicate and get length 3= # Is it equal to 3? $ # Swap væA # Are all prime? ∧ # Are both true? ``` [Answer] ## Pyke, 21 bytes ``` S#j_PI\0[jb2R/_P)I\1[ ``` [Try it here!](http://pyke.catbus.co.uk/?code=S%23j_PI%5C0%5Bjb2R%2F_P%29I%5C1%5B&input=150&warnings=0) ``` S#j - for j in filter(range(1, input+1)) _PI - if is_prime(j): [jb2R/_P) - function_[(a) = V jb2 - base_2(j) R/ - ^.count(a) \0 I - if function_[("0"): \1[ - function_[("1") ``` [Answer] ## Groovy, 120 bytes ``` p={x->(2..<x).every{x%it!=0}&x>1|x==2} {x->(1..x).findAll({y->p(y)&'10'.every{p(Integer.toBinaryString(y).count(it))}})} ``` This is an unnamed closure. [Try it here!](http://ideone.com/LWnXW3) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` f.APM_M+T/LSjT2U2S ``` [Try it online here](http://pyth.herokuapp.com/?code=f.APM_M%2BT%2FLSjT2U2S&input=100&debug=0). [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` def f(n,k=2,m=1,p={0}):f(n-1,k+1,m*k*k,p^{m%k*k,{*map(bin(m%k%n*k)[2:].count,'01')}<p==print(k)}) ``` This is the same algorithm as in [my Python 2 answer](https://codegolf.stackexchange.com/a/107073/12012), but the implementation is quite different. The function prints to STDOUT and terminates with an error. [Try it online!](https://tio.run/nexus/python3#FchNCsJADEDhq7gpTcZUJgU3xZxEKvg3UMLEUOpqmLOPdfe@117vdEhgpDJSFiaXEitO@xqY9MiUgwYlv5Xc/aOEfHd4LAa7OwuK13GaT8/P1zbqI/dYLy7i62IbKFZsCfgcsf0A "Python 3 – TIO Nexus") [Answer] # JavaScript (ES6), 110 bytes ``` B=n=>n?B(n>>1,v[n%2]++):v.every(n=>(P=i=>n%--i?P(i):1==i)(n)) F=(n,a=[])=>n?F(n-1,B(n,v=[0,0,n])?[n,...a]:a):a ``` ``` B=n=>n?B(n>>1,v,v[n%2]++):v.every(n=>(P=i=>n%--i?P(i):1==i)(n)) F=(n,a=[])=>n?F(n-1,B(n,v=[0,0,n])?[n,...a]:a):a const update = () => { console.clear(); console.log(F(input.value)) } input.oninput = update; update(); ``` ``` <input id="input" type="number" min="1" value="100" /> ``` [Answer] # **MATLAB, 50 bytes** ``` @(n)all(isprime([n,sum(de2bi(n)),sum(~de2bi(n))])) ``` [Answer] # Haxe, ~~158~~ 147 bytes ``` function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){var q=n,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(n)&&p(o)&&p(t-o)?trace(n):0;f(n-1);}; ``` Outputs to STDOUT and terminates on a "too much recursion" error; call with e.g. `f(1000);`. You can use a `while` loop with no error for 156 bytes: ``` function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){while(n>0){var q=n,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(n)&&p(o)&&p(t-o)?trace(n):0;n--;}}; ``` Using a range turned out three bytes longer: ``` function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){for(i in 0...n+1){var q=i,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(i)&&p(o)&&p(t-o)?trace(i):0;}}; ``` [Test it online!](http://try.haxe.org/#70094) [Answer] # Rust, 147 bytes ``` fn f(x:u32){let p=|n|n>1&&(2..n).all(|x|n%x!=0);for n in 9..x+1{if p(n)&&p(n.count_ones())&&p(n.count_zeros()-n.leading_zeros()){print!("{} ",n)}}} ``` [playground link](https://is.gd/zkedvo) The `count_ones`, `count_zeros`, and `leading_zeros` methods came in handy. ### Formatted version ``` fn f(x: u32) { // primality test closure using trial division let p = |n| n > 1 && (2..n).all(|x| n % x != 0); for n in 9..x + 1 { if p(n) && p(n.count_ones()) && p(n.count_zeros() - n.leading_zeros()) { print!("{} ", n) } } } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ↑<⁰foΛṗo§e#0Σḋİp ``` [Try it online!](https://tio.run/##AScA2P9odXNr///ihpE84oGwZm/Om@G5l2/Cp2UjMM6j4biLxLBw////MTA "Husk – Try It Online") ]
[Question] [ A [stochastic matrix](https://en.wikipedia.org/wiki/Stochastic_matrix) is a matrix of probabilities used in the context of Markov chains. A *right* stochastic matrix is a matrix where each row sums to `1`. A *left* stochastic matrix is a matrix where each column sums to `1`. A *doubly* stochastic matrix is a matrix where each row and each column sums to `1`. In this challenge, we will represent the probabilities **in percent using integers**. A row or column must in that case sum to `100` and not `1`. **Your goal** is to write a program or function which, given a square matrix of integers as input, outputs one of four values indicating that the matrix is either right stochastic, left stochastic, doubly stochastic or none of those. ### Input You may use any proper representation of a matrix that is natural for your language for the input. For example, a list of lists, a string of comma separated values with rows separated by linebreaks, etc. The input matrix will always be square and will only contain non-negative integers. The input matrix will always be at least `1×1`. You may pass the input using `STDIN`, as a function argument, or anything similar. ### Output You must choose **four distinct outputs** that correspond to *right stochastic*, *left stochastic*, *doubly stochastic* or *none of those*. Those outputs must be constant regardless of what input is passed. Your program may not return different outputs for the same case, e.g. saying that any negative number corresponds to *none of those* is not valid. In short, there must be a 1-to-1 correspondence between your output an the four possible cases. Some examples of those four outputs would be `{1, 2, 3, 4}` or `{[1,0], [0,1], [1,1], [0,0]}` or even `{right, left, doubly, none}`. Please indicate in your answer the four outputs your program uses. If a matrix is doubly stochastic, then you must return the output corresponding to doubly stochastic, and not right or left stochastic. You may print the output to `STDOUT`, return it from a function, or anything similar. ### Test cases ``` [100] => Doubly stochastic [42] => None of those [100 0 ] => Doubly stochastic [0 100] [4 8 15] [16 23 42] => Left stochastic [80 69 43] [99 1 ] => Right stochastic [2 98] [1 2 3 4 ] [5 6 7 8 ] => None of those [9 10 11 12] [13 14 15 16] ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Haskell, ~~57~~ 55 bytes ``` import Data.List s a=all((==100).sum)<$>[transpose a,a] ``` Input of type `(Eq a, Num a) => [[a]]`. Outputs boolean list `[left-stochastic, right-stochastic]` Thanks to @proudhaskeller for saving 2 bytes [Answer] ## R, 55 bytes ``` function(m)c(all(colSums(m)==100),all(rowSums(m)==100)) ``` Unnamed function where `m` is assumed to be an R-matrix. Output: * `[1] TRUE FALSE`: Left stochastic * `[1] FALSE TRUE`: Right stochastic * `[1] TRUE TRUE`: Doubly * `[1] FALSE FALSE`: None [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ ~~11~~ 10 bytes Right stochastic: `[0,1]` Left stochastic: `[1,0]` Doubly stochastic: `[1,1]` None of those: `[0,0]` ``` Dø2FOTnQPˆ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RMO4MkZPVG5RUMuG&input=W1s0LDgsMTVdLFsxNiwyMyw0Ml0sWzgwLDY5LDQzXV0) **Explanation** ``` D # duplicate input ø # transpose the copy 2F # 2 times do (once for each matrix) O # sum of the rows TnQ # is equal to 100 P # product ˆ # add to global list # implicitly print global list at the end of the program ``` [Answer] # Octave, ~~35~~ ~~34~~ ~~32~~ 31 bytes ``` @(n)any([sum(n);sum(n')]-100,2) ``` Call it like this: ``` f(100) f(42) f([4,8,15; 16,23,42; 80,69,43]) f([99,1;2,98]) f([1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]) ``` [**Test it here.**](https://ideone.com/ByF5r1) Saved 2 bytes thanks to flawr initially, but went for another approach that was 1 byte shorter. This outputs the following for the different cases: ``` 0 Doubly 0 1 None 1 0 Left 1 1 Right 0 ``` The last `,2` would be unnecessary if single digits weren't included. Also, if this summed to `1` instead of `100` (as it could have), it would save another `4` bytes. [Answer] ## Mathematica 29 Bytes ``` {}⋃Tr/@#=={100}&/@{#,#}& ``` substituting the =U+F3C7=[\Transpose] character. This code snippet will paste correctly into Mathematica. Same truthiness convention with {lefttruth, righttruth} as output [Answer] # k, ~~21~~ 19 bytes ``` {min'100=+/'(x;+x)} ``` Output * `00b` none * `10b` left * `01b` right * `11b` both Example: ``` k)f:{min'100=+/'(x;+x)} //store function as f k)f(100 0;98 2) 01b ``` **edit:** reduce byte count by 3 - function does not need to be enclosed in a lambda **edit:** reduce bytecount by 2 - H/T @Simon Major [Answer] # [MATL](http://github.com/lmendo/MATL), 12 bytes ``` sG!sv!100=XA ``` Output is two zero/one values. First indicates if the matrix is left-stochastic, second if it is right-stochastic. [Try it online!](http://matl.tryitonline.net/#code=c0chc3YhMTAwPVhB&input=WzQgOCAxNTsgMTYgMjMgNDI7IDgwICA2OSAgNDNd) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLCnNLIXN2ITEwMD1YQQpEVA&input=WzEwMF0KWzQyXQpbMTAwIDA7IDAgMTAwXQpbNCA4IDE1OyAxNiAyMyA0MjsgODAgIDY5ICA0M10KWzk5IDE7IDIgOThdClsxIDIgMyA0OyA1IDYgNyA4OyA5IDEwIDExIDEyOyAxMyAxNCAxNSAxNl0) ``` s % Implicitly input N×N matrix. Sum of each column. Gives a 1×N vector G! % Push input transposed s % Sum of each column. Gives a 1×N vector v % Concatenate vertically. Gives a 2×N matrix ! % Transpose. N×2 100= % Does each entry equal 100? XA % True for columns that contain only "true". Gives 1×2 vector. Implicitly display ``` [Answer] ## Mathematica, ~~46~~ 43 bytes ``` AllTrue[#==100&]/@Apply[Plus,{#,#},{1}]& ``` As with other answers, the outputs are `{False, False}` for non-stochastic `{True, False}` for left-stochastic `{False, True}` for right-stochastic `{True, True}` for doubly stochastic Saved 3 bytes by switching to the operator form of `AllTrue` [Answer] # PHP, 104 bytes ``` function($a){for($s=array_sum;$a[+$i];)$o|=$s($a[+$i])!=100|($s(array_column($a,+$i++))!=100)*2;echo$o;} ``` An anonymous function that echos 0 => both, 1=> left, 2=> right, 3=> neither. Use like: ``` php -r "$c=function($a){for($s=array_sum;$a[+$i];)$o|=$s($a[+$i])!=100|($s(array_column($a,+$i++))!=100)*2;echo$o;};$c(json_decode($argv[1]));" "[[4,8,15],[16,23,42],[80,69,43]]" ``` A command line program version at 114 bytes: ``` for($a=json_decode($argv[1]);$a[+$i];)$o|=($s=array_sum)($a[+$i])!=100|($s(array_column($a,+$i++))!=100)*2;echo$o; ``` Used like: ``` php -r "for($a=json_decode($argv[1]);$a[+$i];)$o|=($s=array_sum)($a[+$i])!=100|($s(array_column($a,+$i++))!=100)*2;echo$o;" "[[4,8,15],[16,23,42],[80,69,43]]" ``` [Answer] # Python 2, ~~70~~ 64 Bytes Nothing crazy here, just making use of splatting in `zip` to transpose the matrix :) The outputs are as follows: ``` 0 - not stochastic 1 - right stochastic 2 - left stochastic 3 - doubly stochastic ``` And here's the code :) ``` k=lambda m:all(sum(x)==100for x in m) lambda n:k(n)+2*k(zip(*n)) ``` [Answer] # C#, ~~205~~ ~~203~~ 183 bytes Golfed: ``` int F(int[,]m){int x,i,j,r,c,e,w;x=m.GetLength(0);e=w=1;for(i=0;i<x;i++){r=c=0;for(j=0;j<x;j++){r+=m[i,j];c+=m[j,i];}if(r!=100)e=0;if(c!=100)w=0;}return e==1&&w==1?3:e==1?1:w==1?2:4;} ``` Ungolfed with comments: ``` int F(int[,] m) { //x - matrix size //i, j - loop control variables //r, c - row/column sum //e, w - east/west, pseudo-bool values indicate right/left stochastic int x, i, j, r, c, e, w; x = m.GetLength(0); e = w = 1; for (i = 0; i < x; i++) { r = c = 0; for (j = 0; j < x; j++) { r += m[i, j]; c += m[j, i]; } if (r != 100) e = 0; if (c != 100) w = 0; } return e == 1 && w == 1 ? 3 : e == 1 ? 1 : w == 1 ? 2 : 4; } ``` Output key: 1 - right stochastic 2 - left stochastic 3 - double stochastic 4 - none Try it: <http://rextester.com/PKYS11433> EDIT1: `r=0;c=0;` => `r=c=0;` EDIT2: Nested ternary operators. Credits goes to @Yodle. [Answer] ## JavaScript (ES6), 83 bytes ``` a=>[a.some(a=>a.reduce((l,r)=>l-r,100)),a.some((_,i)=>a.reduce((l,a)=>l-a[i],100))] ``` Just to be contrary, not only does this output the right stoachistic result on the left, but the booleans are also inverted, so an output of `[false, true]` still means right stoachistic. [Answer] ## C#6, 130 bytes ``` using System.Linq;bool[]F(int[][]a)=>new[]{a.Where((_,i)=>a.Select(x=>x[i]).Sum()==100).Count()==a.Length,a.All(x=>x.Sum()==100)}; ``` `{False, False}` for non-stochastic `{True, False}` for left-stochastic `{False, True}` for right-stochastic `{True, True}` for doubly stochastic [repl.it demo](https://repl.it/E2PR/0) Ungolfed ``` bool[]F(int[][]a)=> // Return new array of two bools. Array type is inferred from arguments new[] { // Left: // Count the no. of columns which sums up to 100 a.Where((_,i)=>a.Select(x=>x[i]).Sum()==100).Count() // Then check if no. of such columns equal to total column count ==a.Length, // Right: Do all rows sum up to 100? // Can't use this trick for left because no overload of All() accept Func<TSource,int,bool> like Where() does a.All(x=>x.Sum()==100) }; ``` [Answer] # Groovy, 57 ``` {a={it.every{it.sum()==100}};[a(it),a(it.transpose())]}​ ``` ## Output `[0,0]` if neither. `[1,0]` if right. `[0,1]` if left. `[1,1]` if both. [Answer] ## [Pip](http://github.com/dloscutoff/pip), 17 bytes In an unexpected twist, this submission is a function. ``` {[h]=UQ$+_M[Zaa]} ``` Returns a list of two `0`/`1` values: `[0 0]` = not stochastic, `[0 1]` = left stochastic, `[1 0]` = right stochastic, `[1 1]` = doubly stochastic. [Try it online!](http://pip.tryitonline.net/#code=KAoge1toXT1VUSQrX01bWmFhXX0KIFtbOTkgMV1bMiA5OF1dCik&input=) ### Explanation ``` { } A function: a Function argument (nested list) [Za ] Create a list containing a's transpose and a M Map this function to each of the above: $+_ Sum down the columns UQ Get unique elements [h]= If stochastic, the result should be [100] ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) [`{∧/100=+/↑⍵(⍉⍵)}`](http://tryapl.org/?a=%7B%u2227/100%3D+/%u2191%u2375%28%u2349%u2375%29%7D%20%A8%20%28%u236A100%29%20%28%u236A42%29%20%28%u2191%28100%200%29%280%20100%29%29%20%28%u2191%284%208%2015%29%2816%2023%2042%29%2880%2069%2043%29%29%20%28%u2191%2899%201%29%282%2098%29%29%20%284%204%u23741+%u237316%29&run) `{ }` direct function definition (aka "dfn"), `⍵` is the argument `⍵(⍉⍵)` the matrix alongside its transposition `↑` mix them into a single 2×n×n array `+/` sum along last axis, get a 2×n matrix `100=` which elements are 100 (booleans are 0 1) `∧/` "and"-reduction along last axis, get 2 booleans for left,right stochastic [Answer] # C++14, ~~139~~ ~~136~~ ~~133~~ 130 bytes -3 bytes for `s=M.size()`, -3 bytes for returning by reference parameter, -3 bytes as a unnamed lambda ``` [](auto M,int&r){int a,b,i,j,s=M.size();r=3;for(i=-1;++i<s;){for(j=-1,a=b=0;++j<s;a+=M[i][j],b+=M[j][i]);r&=(a==100)+2*(b==100);}} ``` Assumes input to be like `vector<vector<int>>`. Returns 3,2,1,0 for doubly, left, right, none stochastic. Ungolfed: ``` auto f= [](auto M, int& r){ int a,b,i,j,s=M.size(); r=3; for(i=-1;++i<s;){ for(j=-1,a=b=0;++j<s; a+=M[i][j], b+=M[j][i]); r&=(a==100)+2*(b==100); } } ; ``` [Answer] # [Uiua](https://uiua.org), ~~14~~ 12 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /×=100/+∵⊟⍉. ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAgL8OXPTEwMC8r4oi14oqf4o2JLgoKZiBbWzEwMF1dCmYgW1s0Ml1dCmYgW1swIDEwMF1bMTAwIDBdXQpmIFtbNCA4IDE1XVsxNiAyMyA0Ml1bODAgNjkgNDNdXQpmIFtbOTkgMV1bMiA5OF1dCmYg4oavNF80KzHih6ExNgo=) -2 thanks to Bubbler Returns `[0 0]` for neither, `[0 1]` for left stochastic, `[1 0]` for right stochastic, and `[1 1]` for both. ``` /×=100/+∵⊟⍉. . # duplicate ⍉ # transpose ∵⊟ # elementwise couple /+ # sum =100 # where is it equal to 100? /× # product ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ,Z§ạȷ2§¬ ``` [Try it online!](https://tio.run/##VYwhDgIxEAC/gkCO6La90j4FmkoMuQ9gMXgUFnXmPAF5FxK@cXykLDkSgtrN7Ozstm27r5XN0E33y/Nqh27o63h8nKbbefk69OtacxZjSmGRs7fzVIApZMPvREQaZRKwDjXJ0RAS3s1GSohCS4rfChY1lTUEVkTd1NGoIJ9/cYjXKhL@Eg5NvgE "Jelly – Try It Online") Outputs `[1, 1]` for doubly, `[0, 1]` for left, `[1, 0]` for right, and `[0, 0]` for neither. ``` , Pair the input with Z its transpose, § sum the columns from each, ạ take the absolute differences between each sum and ȷ2 1*10^2, § sum each list of differences. ¬ Is each sum 0? ``` `,Z§=ȷ2P€` is perhaps more intuitive. ]
[Question] [ This is a code golf challenge. Just like the title says, write a program to covert a string of ascii characters into binary. For example: `"Hello World!"` should turn into `1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001`. Note: I am particularly interested in a pyth implementation. [Answer] # Python 3, 41 bytes ``` print(*[bin(ord(x))[2:]for x in input()]) ``` Like [KSFT's answer](https://codegolf.stackexchange.com/a/44831/21487), but I thought I'd point out that, in addition to `raw_input -> input`, Python 3 also has an advantage here due to the splat for `print`. [Answer] # CJam, 8 bytes ``` l:i2fbS* ``` Easy-peasy: ``` l:i "Read the input line and convert each character to its ASCII value"; 2fb "Put 2 on stack and use that to convert each ASCII value to base 2"; S* "Join the binary numbers by space"; ``` [Try it here](http://cjam.aditsu.net/) [Answer] # Pyth, 10 bytes ``` jdmjkjCd2z ``` Python mapping and explanation: ``` j # join( "Join by space" d # d, "this space" m # Pmap(lambda d: "Map characters of input string" j # join( "Join by empty string" k # k, "this empty string" j # join( "This is not a join, but a base conversion" C # Pchr( "Convert the character to ASCII" d # d "this character" # ), 2 # 2 "Convert to base 2" # ) # ), z # z))) "mapping over the input string" ``` Input is the string that needs to be converted without the quotes. [Try it here](http://pyth.herokuapp.com/) [Answer] # [MITS Altair 8800](https://en.wikipedia.org/wiki/Altair_8800), 0 bytes Input string is at memory address `#0000H` ([allowed](https://codegolf.meta.stackexchange.com/a/8510/84624)). Output in binary via front panel I/O lights `D7-D0`. Example, do `RESET`, then `EXAMINE` to see the first byte, followed by repeating `EXAMINE NEXT` to see the rest. `"H" = 01 001 000:` [![enter image description here](https://i.stack.imgur.com/yT3W2.png)](https://i.stack.imgur.com/yT3W2.png) `"e" = 01 100 101:` [![enter image description here](https://i.stack.imgur.com/FNuAN.png)](https://i.stack.imgur.com/FNuAN.png) `"l" = 01 101 100:` [![enter image description here](https://i.stack.imgur.com/iSryY.jpg)](https://i.stack.imgur.com/iSryY.jpg) [Try it online!](https://s2js.com/altair/sim.html) Non-competing, of course. :) [Answer] # Python 3 - 43 bytes --- ``` print(*map("{:b}".format,input().encode())) ``` No quite the shortest, but an interesting approach IMO. It has the added advantage that if the number of significant bits varies, E.G. `Hi!`, padding with zeros is trivial (2 more bytes, as opposed to 9 for `.zfill(8)`): ``` print(*map("{:08b}".format,input().encode())) ``` [Answer] # Python - 52 ``` print" ".join([bin(ord(i))[2:]for i in raw_input()]) ``` ~~I'll work on translating this into Pyth.~~ Someone else did a Pyth answer already. If you don't care about it being a full program or about I/O format and use Python 3, you can do it in 23 bytes like this: ``` [bin(ord(i))for i in x] ``` `x` is the input. I know this doesn't count because the interpreter wasn't released before the challenge was posted, but here it is in KSFTgolf: ``` oan ``` [Answer] # Ruby, ~~34~~ ~~28~~ 24 bytes ``` $<.bytes{|c|$><<"%b "%c} ``` Takes input via STDIN. 6 bytes saved thanks for AShelly and another 4 thanks to britishtea. [Answer] # PowerShell, ~~63~~ ~~59~~ 46 bytes -13 bytes thanks to @mazzy ``` "$($args|% t*y|%{[Convert]::ToString(+$_,2)})" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lFQyWxKL24RlWhRKuyRrU62jk/ryy1qCTWyiokP7ikKDMvXUNbJV7HSLNWU@k/UIMHUF@@jkJ4flFOiqISAA "PowerShell – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 45 bytes ``` : f 0 do dup i + c@ 2 base ! . decimal loop ; ``` [Try it online!](https://tio.run/##FcVBDkAwEEDRq/zaChFLNpZuYI1paTIyjXL@ird5we7nbI7wV8pAoEMMeRORmn2iZ1uzx9Eifo/XqqhZYiy5YvaqxmK3iqsI5QM "Forth (gforth) – Try It Online") ### Code Explanation ``` : f \ start a new word definition 0 do \ start a loop from 0 to string length - 1 dup i + \ duplicate the address and add the loop index to get addr of current character c@ \ get the character at that address 2 base ! \ set the base to binary . \ print the ascii value (in binary) decimal \ set the base back to decimal loop \ end the loop ; \ end the word definition ``` [Answer] # Matlab This is an anonymous function ``` f=@(x) dec2bin(char(x)) ``` usage is `f('Hello World')`. Alternatively, if `x` is defined as the string `Hello World!` in the workspace, then just `dec2bin(char(x))` will work. [Answer] # J - 9 ``` 1":#:3&u: ``` No idea how to make this in a row without doubling the length of the code, I need J gurus to tell me :) ``` 1":#:3&u:'Hello world!' 1001000 1100101 1101100 1101100 1101111 0100000 1110111 1101111 1110010 1101100 1100100 0100001 ``` [Answer] # Java - 148 Bytes ``` public class sToB{public static void main(String[] a){for(int i=0;i<a[0].length();i++){System.out.print(Integer.toString(a[0].charAt(i) ,2)+" ");}}} ``` Edited to include full file [Answer] # JavaScript ES6, 63 65 bytes ``` alert([for(c of prompt())c.charCodeAt().toString(2)].join(' ')) ``` This is rather long, thanks to JavaScript's long function names. The Stack Snippet below is the rough ES5 equivalent, so it can be run in any browser. Thanks to edc65 for the golfing improvements. ``` alert(prompt().split('').map(function(e){return e.charCodeAt().toString(2)}).join(' ')) ``` [Answer] # Scala - 59 - 55 Bytes ``` readLine().map(x=>print(x.toByte.toInt.toBinaryString)) ``` Normally, one should use foreach and not map. [Answer] # [Python 3.6](https://docs.python.org/3.6/), 39 bytes ``` print(*[f'{ord(c):b}'for c in input()]) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzv6AoM69EQys6Tb06vyhFI1nTKqlWPS2/SCFZITMPiApKSzQ0YzX///dIzcnJVwjPL8pJUQQA "Python 3 – Try It Online") [Answer] # Ruby, 24 bytes I was hoping to beat [Martin Ender](https://codegolf.stackexchange.com/a/44836/11261), but I only managed to tie him. Takes input on STDIN; +1 bytes for `-p` flag. ``` gsub(/./){"%b "%$&.ord} ``` [Try it online!](https://tio.run/##KypNqvz/P724NElDX09fs1pJNUlBSVVFTS@/KKX2/3@P1JycfIXw/KKcFMV/@QUlmfl5xf91CwA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` print(*[f'{ord(i):b}'for i in input()]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys6Tb06vyhFI1PTKqlWPS2/SCFTITMPiApKSzQ0YzX///dIzcnJVwjPL8pJUQQA "Python 3 – Try It Online") Slight improvement over the [current leading Python answer](https://codegolf.stackexchange.com/a/44846/87681) [Answer] # x86-16 machine code, IBM PC DOS, ~~33~~ ~~31~~ 28 bytes **Binary:** ``` 00000000: d1ee ad8a c849 b308 ac92 b000 d0e2 1430 .....I.........0 00000010: cd29 4b75 f5b0 20cd 29e2 ebc3 .)Ku.. .)... ``` **Listing:** ``` D1 EE SHR SI, 1 ; point SI to DOS PSP (80H) AD LODSW ; load input string length into AL, SI to 82H 8A C8 MOV CL, AL ; set up loop counter 49 DEC CX ; remove leading space/slash from char count LOOP_CHAR: B3 08 MOV BL, 8 ; loop 8 bits AC LODSB ; load next char 92 XCHG AX, DX ; use DX for bit shift LOOP_BIT: B0 00 MOV AL, 0 ; clear AL D0 E2 SHL DL, 1 ; high-order bit into CF 14 30 ADC AL, '0' ; AL = '0' + CF CD 29 INT 29H ; write AL to screen 4B DEC BX ; decrement bit counter 75 F5 JNZ LOOP_BIT ; loop next bit B0 20 MOV AL, ' ' ; display a space CD 29 INT 29H ; write AL to screen E2 EB LOOP LOOP_CHAR ; loop next char C3 RET ; return to DOS ``` A standalone PC DOS executable COM file. Input is via command line, output to screen. [![enter image description here](https://i.stack.imgur.com/sgSUD.png)](https://i.stack.imgur.com/sgSUD.png) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `S`, 3 bytes ``` bƛṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=S&code=b%C6%9B%E1%B9%85&inputs=Hello%2C%20World!&header=&footer=) Explanation: ``` b # Convert each letter to a list of bits ƛ # In each list of bits: ṅ # Join elements # 'S' flag - join top of stack with spaces and output ``` [Answer] # [Rust](https://www.rust-lang.org/), 47 45 bytes ``` |s:&str|for i in s.bytes(){print!("{:b} ",i)} ``` [Try it online!](https://tio.run/##PY2xCoMwGIRn8xR/MpQI0gdQOnWwU7dSSumg9Q8E0vySRKFonj1NHVzuu@MOzk0@JGXh02kry4UZDKBOafX1wQe3KnKgQVvwx/4b0OfJ6LQNXIql7iOISpcxNWzfzfjmT3FBYwju5MzARSXONCC0ZFT2V5zRZbZkbfennjHjQVPW2yheCyv2iwj1dtGwQskNW2UslzlEFtMP "Rust – Try It Online") A closure iterating over the string, converting each character to its ascii number, then printing out it's binary equivalent with `:b` Turns out you don't need `{}` always to define a closure [Answer] # Haskell, 65 ``` m s=tail$do c<-s;' ':do j<-[6,5..0];show$mod(fromEnum c`div`2^j)2 ``` heavy use of the list monad. it couldn't be converted to list comprehentions because the last statements weren't a `return`. [Answer] # C++ - 119 bytes Freeing memory? What's that? ``` #include<cstdio> #include<cstdlib> int main(int c,char**v){for(*v=new char[9];c=*(v[1]++);printf("%s ",itoa(c,*v,2)));} ``` (MSVC compiles the code with warning) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` OBK ``` [Try it online!](https://tio.run/##y0rNyan8/9/fyfv////qHkBevo5CeH5RToqiOgA "Jelly – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 52 bytes ``` proc B s {binary s $s B* b;regsub -all .{8} $b {& }} ``` [Try it online!](https://tio.run/##K0nO@f@/oCg/WcFJoVihOikzL7GoEshSKVZw0lJIsi5KTS8uTVLQTczJUdCrtqhVUElSqFZTqK39X1BaUqwQ7aSg5JGak5OvUJ5flJOiqBT7/z@UDwA "Tcl – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 12 bytes ``` 10⊥2⊥⍣¯1⎕UCS ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FH26O2CYYGj7qWGgHxo97Fh9YbPuqbGuocDJZUUPdIzcnJ11EIzy/KSVFUBwA "APL (Dyalog Unicode) – Try It Online") Thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) for help with this solution. [Answer] # Commodore VIC-20/C64/128 and TheC64Mini, 101 tokenized BASIC bytes Here is the obfuscated listing using Commodore BASIC keyword abbreviations: ``` 0dEfnb(x)=sG(xaNb):inputa$:fOi=1tolen(a$):b=64:c$=mI(a$,i,1):fOj=0to6 1?rI(str$(fnb(aS(c$))),1);:b=b/2:nEj:?" ";:nE ``` Here for explanation purposes is the non-obfuscated symbolic listing: ``` 0 def fn b(x)=sgn(x and b) 1 input a$ 2 for i=1 to len(a$) 3 let b=64 4 let c$=mid$(a$,i,1) 5 for j=0 to 6 6 print right$(str$(fn b(asc(c$))),1); 7 let b=b/2 8 next j 9 print " "; 10 next i ``` The function `fn b` declared on line zero accepts a numeric parameter of `x` which is `AND`ed with the value of `b`; [SGN](https://www.c64-wiki.com/wiki/SGN) is then used to convert `x and b` to `1` or `0`. Line one accept a string input to the variable `a$`, and the loop starts (denoted with `i`) to the length of that input. `b` represents each bit from the 6th to 0th bit. `c$` takes each character of the string at position `i`. line 5 starts the loop to test each bit position; `right$` is used in line 6 to remove a auto-formatting issue when Commodore BASIC displays a number, converting the output of `fn b` to a string; `asc(c$)` converts the current character to its ascii code as a decimal value. Line 7 represents the next bit value. The loop `j` is ended before printing a space, then the last loop `i` is ended. [![C64 converting PETSCII to Binary](https://i.stack.imgur.com/4hBi7.png)](https://i.stack.imgur.com/4hBi7.png) [Answer] # JavaScript ES6, 71 bytes ``` alert(prompt().split('').map(c=>c.charCodeAt(0).toString(2))).join(' ') ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 34 bytes ``` i\~48*o ?\:0(?;:2%:}-2,:0= ?\{nl1= ``` [Try it online!](https://tio.run/##S8sszvj/PzOmzsRCK5/LPsbKQMPe2spI1apW10jHysAWKFSdl2No@/@/R2pOTr5CeH5RTooiAA "><> – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Çbðý ``` [Try it online.](https://tio.run/##yy9OTMpM/f//cHvS4Q2H9/7/75Gak5OvEJ5flJOiCAA) **Explanation:** ``` Ç # Convert the (implicit) input-string to a list of unicode values b # Convert each integer to a binary string ðý # Join by spaces (and output the result implicitly) ``` Could be just the first two bytes if a list output is allowed, or 3 bytes with `»` if a newline delimiter instead of space delimiter is allowed. [Answer] # [Perl 5](https://www.perl.org/), 21 bytes ``` printf'%b ',ord for@F ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1dNUlBXSe/KEUhLb/Iwe3//0SFJIVkhRSFVIW0f/kFJZn5ecX/dd0A "Perl 5 – Try It Online") ]
[Question] [ Inspired by [a polyglot](https://meta.stackexchange.com/a/27846/344102) ~~on the [Stack Overflow 404 page](https://stackoverflow.com/error-404)~~: ![](https://cdn.sstatic.net/Sites/stackoverflow/img/polyglot-404.png) # Goal Your goal is simple, to create a polyglot that outputs the number **404**, and then terminate, in as many languages as possible. # Restrictions Here's the twist, there's a restriction to make it harder: You have to write **N** programs and pick **N** languages in a particular order. the **i**th program needs to print `404` in the first **i** languages, but not in any language after the **i**th. This is to prevent very simple solutions from destroying competition # Scoring: * The first criterion for determining a winner is the number of languages the main program runs in. * The second criterion is byte count, where the programs with more languages have more importance for this criterion. * The third and final criterion is time of submission # Clarifications: The source codes of the programs do not need to have any relation. They're run as separate programs. Any of the programs can output trailing and/or leading whitespace. **THE PROGRAMS DO NOT HAVE TO BE SUBSEQUENCES OF EACH OTHER!** Thanks to @MartinEnder for a better explanation! [Answer] # 54 Languages, 1331 bytes [><>](https://esolangs.org/wiki/Fish), [Gol><>](https://github.com/Sp3000/Golfish), [Foo](https://esolangs.org/wiki/Foo), [Befunge-93](https://github.com/catseye/Befunge-93), [Befunge-98](https://github.com/catseye/FBBI), [brainfuck](https://github.com/TryItOnline/brainfuck), [Brain-Flak](https://github.com/Flakheads/BrainHack), [Python 2](https://docs.python.org/2/), [Python 3](https://docs.python.org/3/), [Hexagony](https://github.com/m-ender/hexagony), [Perl](https://www.perl.org/), [Ruby](https://www.ruby-lang.org/), [Julia](http://julialang.org/), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [Brainbash](https://github.com/ConorOBrien-Foxx/Brainbash), [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), [Deadfish~](https://github.com/TryItOnline/deadfish-), [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), [Braille](https://gist.github.com/threeifbywhiskey/0e98d42150eb644a3406), [Rail](https://esolangs.org/wiki/Rail), [Fission](https://github.com/C0deH4cker/Fission), [ETA](http://www.miketaylor.org.uk/tech/eta/doc/), [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html), [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), [Numberwang](https://esolangs.org/wiki/Numberwang_(brainfuck_derivative)), [Actually](https://github.com/Mego/Seriously), [Emoji](https://esolangs.org/wiki/Emoji), [Symbolic Brainfuck](https://github.com/KelsonBall/Esolangs.Sbf), [TinCan](https://github.com/TryItOnline/tincan), [Alphuck](https://github.com/TryItOnline/brainfuck), [Shove](https://github.com/TryItOnline/shove), [Cood](https://github.com/jesobreira/cood/tree/php-interpreter), [Wise](https://github.com/Wheatwizard/Wise), [Width](https://github.com/stestoltz/Width), [Whispers](https://github.com/cairdcoinheringaahing/Whispers), [Thue](https://esolangs.org/wiki/Thue), [Surface](https://github.com/TryItOnline/surface), [Stones](https://github.com/cheezgi/stones), [evil](https://web.archive.org/web/20070103000858/www1.pacific.edu/%7Etwrensch/evil/index.html), [Set](https://github.com/somebody1234/Set), [Prelude](https://esolangs.org/wiki/Prelude), [Gaot++](https://github.com/tuxcrafting/gaot-plus-plus), [Cubix](https://github.com/ETHproductions/cubix), [Cubically](https://github.com/aaronryank/cubically), [PATH](https://sourceforge.net/projects/pathlang/), [Commercial](https://github.com/tuxcrafting/commercial), [Brian & Chuck](https://github.com/m-ender/brian-chuck), [Monkeys](https://github.com/TryItOnline/monkeys), [Nhohnhehr](https://github.com/catseye/Nhohnhehr), [Beam](https://github.com/ETHproductions/beam-js), [AsciiDots](https://github.com/aaronduino/asciidots), [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), [Alice](https://github.com/m-ender/alice), [Whirl](https://bigzaphod.github.io/Whirl/) This is getting very long, so at @MDXF's suggestion, I'm moving the subprograms and comments to a [gist](https://gist.github.com/GrayJoKing/60ab9a603791381171c091bcc3eec189). The program here is only the final program. Thanks to MDXF again for providing the TIO test driver. # 54. [Whirl](https://bigzaphod.github.io/Whirl/) ``` ##\$"404"#N#S# , ,,#$#?@\404!?@GJlICJlGCC*G^+0%=%=+0%x&fqpqqqiipsoddddoiipsohphhhhyhhhh? ?nnn4$4#!000110000011110000100000100000110000011001100000111100001110011000111000110000 #?\++++:----:++++:H@((((4O0O4O@((((()()()){}){x}x){}x()){}){}()){}){})<[-]>[-]-[<+>-----]<+x%"404"?.⌂----.++++.>11 #i(N/"404"ooo@ENTHOEONHSSEONTHOEONSETssipceaiiiiiscejiiiijeeeejapmzaeeaeueewzaeeeaeewzaeeaeueewqs??|?)999|997+|++++!999777+++++!999997+++++! print(404) __DATA__=1 # \"404"*CC'[-][ .-$_"404"&] """pp I want 404 of this How much is it # -52, Z, -1 # # -48, Y, -1 # # -52, X, -1 # [-][ x::=~404 ::= x ]<<< > 404 >> Output 1 red up two blue up red up one blue up red up two blue up baaaaa bleeeeeeeeet bleeeeeeeeet baaaaa bleeeeeeeeet a now 404 dollar off! a has been selling out worldwide! 2 LEFT 2 LEFT 2 UP 2 LEFT 2 TEACH 1 LEFT 1 RIGHT 1 BOND 1 BOND 1 TEACH 2 YELL 1 FIGHT 2 YELL 1 TEACH 2 YELL set ! 52 set ! 48 set ! 52 +------+ |$0011\| |/000\0| |0/0@11| |00 10| |0\10/0| |\1100/| +------+ $'main' \-444o000o444omm^ [-][$++++++++++++++++++++++++++++++++++++++++++++++++++++.----.++++.# <<<<<<```>>>>.>.>. ] ss""" #7777777777777777777777777777724091557093543643💬404💬➡77▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡⠎⡆⡎⡆⢐⠣⠃s&&&&~-<<:<<:<<<:<:>>>>>>>>:^||||G<> ``` [Try it online!](https://tio.run/##nVfdUuPIFb6efoqDbTCskWUbMwxgm7HBA7M7BVMLSXaDGY9@2laDpBZqCezFTCWbqr1KpVJJ1V5mh@Q2V3udq73OU7AvkDcgp1v@gbFhU2lZfb5z@lPr9FGf7rZpCOfuzjIiqFncpvmoFxGShm19O5cjXcsCrQcWjJpA42DleRxBqabb9EL3Y9cl3VxO0VA8IAbBFBW7bno8Yj73mMV9QnsBDyPYP9hptt/Wj/aqKT0Woe4yU/exq7bH7dilIiUfrIdWn8fE9UHrCNB5EOmGMumeETl5xJL1hrl9YgUTTxRwpRVbD/ueyV1mQSM0mN@JrTPicZ8nvQmzI@887dHJ47WFknzwC4378EryVazgrJMPXKhUKqlMUXrXoJ3Y71JtfSVxEPJJD4xPUN7sENLhIfSA@dAiqaAfOdxfSd7eYcJRVT7oj1@fmqJ1uauYIrRGeOqBpD/O5T2jxUx81U3mS/w4Q1t/oUgd02SzWKMYTtBjLMdAlor5nvEpKxneJOLpt8pQAptT4WcjcNkZhdhnkvEgIA@6CWOzn4TIoT2jy/2@zvyIhkFIsc6H5idvpaErv9N0H9NDOI1dZjxXoVDwic9jGaHNfMMdg9kfRwXFxNyboIesNLPPwOGXEHHA@WjFEYWjOIxcaiviMpiYWkxAREVE7WlHbGrYcnJoYzTbk0uHYReBYVH9UolHvHVdOpIzGLJBVbMmIhOCcX8kZzBoZMh7RksUsm6XhiM5gyE8mbVYPWw7NS4M0HAdUCQ/9kwaXhp@F/Yn8PGvaFhRbLhuH7NMTE2SxGWPn7Kknorr7BVFWXE1SZaDB2tMep9HIOKQjr64zSFymLgXB@Zbhj8UT6ai4QbO7EQUDr@gST01psAZRsri3H6QN7JlVromk4cJqqqn16xLZkdOUv8CEQeNiSnGYPacjZw4Wb0kmDXSOOzICT2UsxgR96nQIyPsUpy91KUGjiSxzpxIriEwOyIn8ZNe4ExX1eNjEVTdjww44WCM3dimI/kkt2vwKAiUaAduLFQln9C0DpuZlFZssl5S35trR5MFY8yy1GQfI@jEs/woDZ3GMKjtR8XjcZ7FPY@GFpOL4RhODXGybJshM3zNcpINZYynVm5Fxmw6o30xkk@44Tvc8R3qhMrnsfbIukwNT/EkuBe03/DwTMxYJ4TFmM0jobfbHmZgu/3E@Aw39nDOJmJqVPd5DOfuU3vXKFdCN6kftBKbEwBI9rft@iFoTcjGAnfQqPNik3UWM/Uvd399XDipfgBPp//@nb50FYT4ug6k5rW15yK1DCPK5jV1Bb3fvIrNk9YspDK9lHwdbosew2PfIZ73pJ7pwQCiEDQbstDyW2EryqLFwb0IswmKqwXUEh/dAB30qpMTFLyejF3foWaslv6LUr60UgXDtyHTrlZqCoXU5psg9ON3rV6poLV6a80TXYz8bbV684XSVzggHuJTC3qXbkJzf@cqk68VBgNh9CGVus5ixHx6d5dOtzKpcqGcSu@nD9OwDMvL6Ux662ULbXNbL3c/d19vf@7ubm9/tvsuV5ivzlex7i10zoPz83PGAsFtLFwhJ3Cw9GW1Bc8AtnzfL2fK6blCoVAsFgpKJGCoDW1j8SlrbCsOa2kl6a1WDsuGhmVDob2Xi1jKB4WD8oGCi0vyWrq6XrrqXfdQ9oba9UguVY61kxre2nElV5NdaSeVXG9eBWMrf/vHb6UpL7vP14pFkIWk2eK@rhic85fN/aO9g@bB/t7hIdYJPmwe4YYfWNRgsgiLnkp5SrGcGoH3jUGpQWNKLyVCmIDEdC62tgZbS@vr64P19bXcQL58DrW1tbXcCMsGhdEfjDFRn30RXVp6RuDZ6Cbt9k79qN5uV4t4jm8plz/b3s7ieI8hr2XayrJwQlKpVBCQ14BngwjQBryjdmGyh5uyF1uOPG6xCDsBbbW0DL9dBi0JxsySVsTyi2X4@n8hyh6/@iWi9Jn0NjaqH9A/gpL0yAn@CSE16TCp1eAgjgI8GBYJZgbEAUSXHEwXd0nEQxNO9k9N91jENGRBlY5K9IkyTSAG@BgkGTSbu64RYuw6c2h1DAEmpT4I6roMz1zyD@ElD10bTwN0jpTgTfPV0UT86u0EHzXr23ukmKhF@PL17p6UjYP9nYlISCX4uvnmDaqvFGmsPmjFzRjmYLU0BOUXE0tOTXotRwYZmVqtARnomF6tAoKCXnhZLEpQACgqS6uIRgQtmYX6YPJ4Jit3gSyBllYulzl2waX0vHdEfbtM7v8o@Un2pUlFlffv39ew5OVFTogQOHdJeu2pUioX1ourq2uF9ZXV8srz8sp/fvjLP/GDSXH7t5u1tdvvf0x@P@E1FD/d3H7/r/FPaj9OaDe3H/90e/Pd7Y2q//7n24//uP34B7GA5YNWqWyoH94btWHZeDfAslup3c1b1fPLxXq9Dpkgl4N6vYFA06DeqMOONDQasIN6Q@oL1dLq6iZudC5d3Fm6QmNjZLyGBvah8j5nOeEOqthWxdV@Ec911tLSJsno1czyptoxNnGfqDdOdL2L6Offf/fzt3/V60PlB6k0lHL8bkzK5/N6xrrKLFxvSv145ySbMY8zwUm2u0kvDPe/ "Bash – Try It Online") Whirl is described as a Turning Tarpit [sic], which uses only two instructions, 1 and 0. 1 rotates the current wheel of instructions (either the math wheel or the operations wheel), 0 swaps the rotation of the wheel, and two 0s executes the instruction and switches wheels. The relevant instructions are on the first line: `000110000011110000100000100000110000011001100000111100001110011000111000110000` ``` 000110000 Switch to math wheel and execute math.not (math.val = 1) 011110000 Execute math.store, (memval = math.val = 1) 10000 Execute math.add, (math.val = math.val+memval = 1+1 = 2) 010000 Execute math.store (memval = math.val = 2) 0110000 Execute math.multiply, (math.val = math.val*memval = 2*2 = 4) 01100 Execute math.store (memval=math.val) and switch to the ops ring 110000 Execute ops.one (ops.val = 1) 011110000 Executes ops.intio, printing memval (4) 11100 Add one to memory pointer (memval=0) 1100 Execute maths.nop to switch back to ops ring 011100 Execute ops.intio, printing memval (0) 01100 Execute maths.store, (memval=maths.val=4) 00 Execute maths.intio, printing memval (4) ``` The leading 01s cancel each other out, and the trailing 01s cause a floating point exception. Edit: fixed a *bunch* of broken stuff (Commands to be careful about in the future: `UDLR%"[.]o473psjw`) If any programs work for future languages or don't work for current or previous languages, please comment. [Answer] # 53 languages, 2789 bytes Bash, Foo, Implicit, Charcoal, Emoji, ><>, rk, Brain-Flak, C, Set, Cood, Arcyou, TRANSCRIPT, S.I.L.O.S, Commercial, C++, Braille, Deadfish~, Memescript 1.0, ETA, Python 1, Python 3, PARI/GP, Lily, Fission, Decimal, Cubically, Bitwise, TinCan, Whispers, Thue, Emotinomicon, what??!, Ook!, evil, Lennyfuck, Blablafuck, Stones, TacO, COW, Symbolic Brainfuck, Underload, Rail, Reticular, Gaot++, PATH, axo, Monkeys, Nhohnhehr, xEec, VTFF, K-on Fuck, Churro, and Forked. Try everything online in the [test driver!](https://tio.run/##rRjbbtvI9Z1v7RccybItWeZFitxkLUuuFDnrpIm1iJ1ttpYTUORIZExxGF4sqbIW3QYIij5si16CbVE0cYstUHRbFHlt0Yc8Ft2PqPIB3T9Izwx1MSXGyQY7Is99zpwZnjkcqql6xqtXmupDWaM6kfyeLwhLcFW@ms0KbU0DsQcaTFQgUtAkGviQL8s6OZHtwLKEdjbLzRBFDB1nwRRd73Sob9q0Y2rUFkjPoa4Pe/Xazv0PKge7paQceK5smU3ZRlf3O1QPLOIlWceKq/VpIFg2iC0PZOr4sspFckf1DQlpZnXTtPqC5swi4YTFpKjd73ea1DI1qLqqabcC7VjoUJuG3rxmi90S6ZFZ9/JKnnX8nkhtuMbs@VrBcUtyLNja2kqmchhdi7rQA9OGhpBs4pJO@yeZhHtvUcruGI1ndhycpK9qx@dpaAUxxpqBE6WqNSUkpx9jRjr0gRnCBQOn7xvUvhROumV6BgfxftxjvKJyN2j2w75Ntohiy1KPQ/I@IyW3GbWXZJ4yi0N7hN@L8RlOaKBRqsum7RPXcQlCiWleP5VxNiBadElcKzTyXdX2NNeMkOxZRuwfqCcqiJqlep6DyTWO17SoB/scxkSRnwTd6RBXM9kjmpILAeGihNtjttRsCS2LTPAFE9WJqrNHJk6pBf@bcIt0SDg7MD2wKSIb8wo964C5fHC9fi5bfJXdMc8/HDc3xvExxfRSXVNsO3LbAfFh3F4wPc@k9gTHWOhEMzu4hMp7tbhNEDRNDafSn1Hxu6Vp@l3TIxMcY4G1SFPtMbpgzbuG6WEWeVMifr/4RsBGszkR1bOCBpPNOS2BEUZ64M0/xu8bqr@9nbjwGW5CnR5fbBKb0OTEtICDuUFvEtvus@r4hmGrltq01DcahrvHpzbxZF9127jvXWIRFR9MKI2ObwXqeK@qGsXibtoSE8WkAe2yO6rh9ZxLsI6P47xj61gAqKqzMLvEdBfDY5uOg9cVO6xAphZYqjujFkrdeJdw@7ZKfcfh6L5jBR4HLGlEsWXGb@9xBWEPSPZcjRMx08YZHpO@N8EXeLINatgGMVzubsrFp26PEE3u7RBtPhs@PLh27cLny6vr@I041/eqEbguvai3oFMBALgP8WplH8QdWA1wrwZ@60rRbKVTldvvf3ioHJU@ho5M/vMjOTNwXHwrtCC5LF7@jpdch4lJcUgsj5xXb6B6pl2FZKqXZMMFltkx8Ziyj@cTxqd6cAq@C6IOq9CwG27DX0WJgfUVtw3kNhTkwhgtBwPslKqkFdhtIr53Ca7PXlFyjTSDdpu4cJKX8pdKoNo6pO6XtsqccolOi@DJh/cavbwiNnqXd45kbxJvo9FbVvJ3cUIUMzS1IrdJEXb2aoOUVFZOTz21D8nkcBVXzCavXi0FmNUtsJJQUApJp5jG1sgo4a@Y/urpZ38tIHg@@tkXjFbO0RP5i79g1xf/ONzcWMvlxJycO1peyaRRltm/J6/tYTvY29up7@3u7yM82K0jNE2P6tgoIwxeeCJgewqkGLANiz3eAmxHqTmniSj1tkD6OmDcYxtbYjuBF2JE0ZbgskRIRjUJLkqMFYnRp7/lS//V0198gQRDo9@fgU@BHSV9g/B0oS0mOX/hRpooQY1oVC6M3FC0C7ZiF4SlXA4HqV1ScjBtjcKysuwsrwhJbEQzKEuj01Nwjzdxk7pss/p4pi0xMfAM3UQWtQRd306ynFvD87vpF4WlolC/cwArG3lYyYVk4cqU5FJYk4UlfMdagU62PF83qWSUBVbb05kBO8qCWjk8Kg0uXV7PKcq6MiyGmyKtVtZZPhaH8toWa50fqoQQvFVs3QBbl1HQxfckX5qWa7Kzs8tO0E0EPqc82@SQ0Vi9AV8tERmWWr8PXUbqpq7j5wLo520jwvNDPAxwrYjbnJMLvc3N0scYuYBY6MGSgCddSMBGHldr9OzT0dnj0RmHf/j56NkfR88ejZ48D68X@BujF2ejJ/@cXox7PjM7S49@8zl8@bt/P0GcScOXZy/@nk6PfvJnTnEFpzKjnz4a/eqT0WeP//evp9Jael7931//KZS9fPS3ieTzqO93YDKhq3eIJ13mzNY7DTvrvOD2HQQTZ9@Ka99@CwlrLz95/PLHv4yDT18DX2f5@EKb13n@piQXx/n0a0b7TcVz8Vq9m2ReCwM6LJVKw0EpbMjiNcfOGQhlVjiFchnqge8EPuSE61hfsKayesoKO35HSMIuHl87gWawwm7628KNgFEGcYkklG8E66GTu3AjEJphLRZ4YcQjBzShOK4qWG1v0Xp4TQsNE9XrtzooyorjlhVOU4qSyykNOBVOZQVbTmZkA2XKWMrJUKogCVw6eW2cYlHlBbdpkUnzmRpDc74bsTw/bGqV1fpV/FLBiOoY2C0MHhpioVCgOBplWBxspVL3RCgPswPe7WSYlRiWstikJWEJIqNOIrk3GXErqi4Lebi5c@1ghu58MKMPdipXd4VcyObg9vX3dxmu1vdqMxQa5eGjnZs3kb3GjaZsRItHOwgc8LsUo8BvP6THIjytzYvOWxUFiofjLs8LnVr4XeFhfrQSKDZUD5qE2OARyzLtNrD/07rUtfSuqZMEWxBxI78OP1gH8dyrfb7xlRMLV9bho7cxZB7vvslw8QXGzp8Om0UGCXYjwF9mMIy5wFjCXbCESAkR5/AkEqY3P4MuJdfkV8ta6WE3XalUIOVks1CpVJEQRahUK1BjgmoVashXGb9Sym9sFPEL3SLpWmaAwupEOIQq@uDOs5rh1pBFXQkP2mn8HtUymaKQkkup9SI/rBfxiF6pHslyG6mwCMiVMcOqg1zlzOG9qZEkSXJKG6RWhkXGH9aOVlPNw5RztNoukhPV@j8) Join us in the [chatroom](https://chat.stackexchange.com/rooms/72240/unique-404-page-not-found) for this challenge! --- This post got way too large so here's a [gist](https://gist.github.com/aaronryank/49d3546428c56de8cde1a59c24d0d5c6) containing my progress. Current final program: # [Forked](https://github.com/aaronryank/Forked) ``` #undef l" 404"p;((((\)0)0)0)0;(😭4😲⏬😭0😲⏬😭4😲⏬«404»[:5*11-1/1]%&)(404)S^/*NNNNTNNEONHSSEONTHOEONiisoddddoiisohOok! Ook! Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook! Ook? Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. ????!?!!?!??!!!???????????????!?!!!?!????!??????????????!!??!??!??!????!⎚404»💬404💬➡ to for the and of to to to to to is the and a to to to to a and and and and a ;n4n0n4 #11404D301 \4%0%p%& """"echo 404|| rk:start int x = 404 print: x rk:end R"404"* exit; #; OUT &52 &1 OUT &48 &1 OUT &52 &1 */ #include<stdio.h> main(){char aA[]={37,100,0};printf(aA,404);}/*<<<<<mzaeeeaeeaaaawuuuuwaaaa what the frick frack backtrack snick snack tic tac snick snack patty wack diddily dack tic tac diddily dack frick frack quarterback frick frack x::=~404 ::= x # set ! 52 #;⠎⡆⡎⡆⢐⠣⠃▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡(♥ ͜ʖ♥)( ͡°((∩ ͡° ͜ʖ ͡°)⊃━☆゚.*( ͡° ͜ʖ ͡°)ᕦ( ͡°ヮ ͡°)ᕥ(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)) ͡°)(∩ ͡° ͜ʖ ͡°)⊃━☆゚.*( ͡° ͜ʖ ͡°)(> ͜ʖ<)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(> ͜ʖ<)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)(> ͜ʖ<)うんうんうんうんたんたんたんたんうんうんうんたんうんたんうんうんうんうんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんたんたんうんうんたんうんたんうんたんうんうんうんたんたんうんたんたんうんたんたんうんたんたんたんうんうんうんたんうんうんたんうんうんたんうんうんたんうんたんうんうん {o}===}{======={o}{o}}{======={o}{o}===}{======={o} > 404 >> Output 1 I want 404 of this. How much is it? Ju is here. >Ju, 404 >X Ju b = 404 printInt b ; set ! 48 MoOMoOMoO set ! 52 MoOOOMmoO +--------+ |$00110\ | |/00001/ | |\11000\ | |/11000/ | |\0100 \ | | | baaaaa bleeeeeeeeet | 404p@ | | | +--------+ $'main': OOMmOoOOM ; \-444o000o444o-{<$$^- >}+{-----v}+.----.++++.# # bleeeeeeeeet baaaaa ^ < bleeeeeeeeet > 2 LEFT 2 LEFT 2 UP 2 LEFT 2 TEACH 1 LEFT 1 RIGHT 1 BOND 1 BOND 1 TEACH 2 YELL 1 FIGHT 2 YELL 1 TEACH 2 YELL red up two blue up red up one blue up red up two blue up ; o now 404 dollars off! o has been selling out worldwide! # -52, Z, -1 # # -48, Y, -1 # # -52, X, -1 # ⡆⡎⡆⢐⠣⠃((((p 404)((()(((()()()){}){}){}){}){}){}){}) h#4 o# h#0 o# h#4 o# """ print(404)#"*/ ``` [Try it online!](https://tio.run/##rVZtb9tUFP5@v8EvOG7azknzYneumJImoWMdadU2aM2kjWWVnPgGW03t4NikIwnSqFQhPgzESzUQog1oSIiBUL@C@NCPSPsRc38A@wfl3Ou8OX1ZF@34@pznPOf43pOrm2NXLHuTaicnIdfUaAWqE6BIykQtJaIUw5J/pcQX@49/V1Adel88ZVgawj3@6Dd89Oive8m5iCzH5IR8f2o6LCIXXt9IRNZQCmtri/m13Po66kIuj9ow6paGYjGg561NAQIq21fxM1QWTj9xCZUNopFJhSC6rIq/iuo@kUURsgIOtGiCInBO8GEwInBK6AYE79H3fOtf7H/1FAEz3o8dcCyoWDY4OgXV1MCqMGZ4GPV@ENRAROVk4IaUqZiSqZCQLOMiN65KMvSlqExJU7WpaTKBQsu6xY5RqwX2ZrLuqLYDhunANqQZDTUbvSS6GKU49a0JduYihG4bToqEUiR/uwDTc7MwLftQudaHnIVIgoQMs1x1NTpfdzTDiusZsqUaphhulnXVBnXh3v108@pbUVmSolI7xZesiOpClJ3HVDsRmWey9bFKKcVbRWm4KA2GoKGrDt@aim2UN1GrqEuoHI7qpsE1w45RBkctB7ia6jgPoMGgZmiaUX0A2nBugBxe4kMX94rapRGebCeT6U@wcoKWbEOI1KkDAszN4m55B4@8zq7X4fqnL72Dn72DHW/v0B9HeHXNUcfb@7s/mHc4SOuI3ndP4NkP/@6hDYvwrHP0pyh6n/3KEQ9wFPY@3/G@eeg93v3vn/14RBwNP//2F5873vmjxzwJzj2GE/anGqMeMcOd@bGWHTx8atoxiN5kb5wlb16CYXL8cPf406/P0vvn6PMydy/MOW/m18VcXOf@K1b7uuq5eK/GY0aj0LTa6XS63Uz7gi6OEXckgWRY4ySZDORdp@Y6IJMl7C/YU1k/ZY1dN@pxkrMasOWWddbYDSdLll2GdGrTOMksu1F/kjuw7JKS34sJb4xLOFEJUt2ugt121cr7o99oGJXPr24hNRPrygxpTUqSLEtFaJFWQkKREwwWkZO6LIc@KyEEzvZeGy1sqrzhlqq0Jw4LY2m1twOZw8tOXmG9/koSWEV5LGwVi4diTFEUC1ezmI015ycnN2KQac80@WMftWfizMZnUOIhEoLAqr1KNnorzgfDGTILK4s3CwNz@70BLiwuvJMjsu/KcGvp3Ryz1/NrNwbGT5qFu4srK@je5El9NxC1qQZuDZyGhVW4lOEuZZl0lBrOShELTDwG7FxoVrWq2nU8HxUBaV2tQ4lSE@q0WjXMD8DCg9Sw7KrWMDQqsA2Jzc1G4f0oxIZe7aPCdy6mXIvC3cskshnvvCzx9AuMfX/W2K8II2A3KrzCzfYZA/QQ/gtCaCTfcA@/RPzjzb9BQxORxMnJ/w "Forked – Try It Online") My new (-ly implemented) esolang! [Answer] # 34 Languages, 387 characters **[Jelly](https://github.com/DennisMitchell/jelly), [M](https://github.com/DennisMitchell/m), [Pyon](https://github.com/alexander-liao/pyon), Proton, Python 3, Python 2, Python 1, Perl 6, Perl 5, Ruby, bc, Pari/GP, brainfuck, Emoji, Emotin🌗micon, Charcoal, Braingolf, Whitespace, Deadfish~, Deadfish, Self-modifying Brainfuck, Symbolic Brainfuck, Numberwang, Cardinal, Actually, Fission, Prelude, Brain-Flak (BrainHack), Alphuck, Deadfish x, TacO, Braille, [rk](https://github.com/aaronryank/rk-lang), evil** This answer is getting very long so [here](https://gist.github.com/dylannrees/0036e918153b2c5d5b827f1fcb1a84dc) is the full answer. From now on only the last program will be kept here. If anyone finds that one of the programs is broken for one language or one program works for a language it shouldn't, let me know. ``` print(404) +1#<[-]>--[<+>-----]"404".⌂<+.----.++++.💬404💬➡😒😀😒😨😨😨⎚404»___pppissiiiisiiiio▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡sipceaiiiiiscejiiiijeeeejaxxcxxxcxxxKddddKcxxxx7777777724091557093543643%R"404";77999++++++++!++++++++6+1+!++++++5++++!> @p404 sp7 rk:start print: "404"77szaeeaeueewzaeeeaeewzaeeaeueew +1#((a(()a((()(((()()())a{})a{})a{})a{})a{})a{})a{}) +1#ṛ“Nạç»⠎⡆⡎⡆⢐⠣⠃ ``` [Try it online!](https://tio.run/##dVDNSsNAED43T7FWhA2hobVJl9RQvBc8eC2lLHUPqaJLEzUoQlHwJEV6KFLFNnrQg6fetJ7ik3SfoG8QZzeJPfnNfDPf/DCwy868oyThfe84wFbZ0hFCBYQ0o7LptkrtRqnUcg2IgHYR5kVT3F27hikbpgEwV9PRBwxkEs/RavowAg6y/J5TDCewFC86nQ7n3PN9D6DCiRjPU4/BshRHYvz957Kar9ci3@NdRj11ost6MvcYoEfDsBumbB4AmlKFJMO2VXYqtk3KTtW2qjWrurWvnrRDiOM4RoaNXNSMSl7YatBAuxz2kc8J6h/W/YD2A6R@ro7UIUL8C8oYZaeMnUsFMhVpS1t/LsYUYx2IdawCmE4vr/5lQUOFnJomTyw/H8XgaW/5Ff28xQsxG4roVkQqvtyL2auY3STJLw) [Answer] # 11 languages, 10 bytes ### Pyon ``` print(404 ``` ### Pyon, Python 2 ``` print 808//2 ``` ### Pyon, Python 2, Python 1 ``` print None or 404 ``` ### Pyon, Python 2, Python 1, Python 3 ``` die=0 print(die or 404); ``` ### Pyon, Python 2, Python 1, Python 3, Lua ``` print(None or 404) ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5 ``` print(404 or 0) ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby ``` ;print("40"+"4") ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4 ``` print("40"+"4") ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6 ``` print(404**1) ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6, Julia ``` print(404); ``` ### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6, Julia, Lily ``` print(404) ``` [Answer] # 4 Languages: CJam, Python, Underload, ><> The following works in CJam but not Python, Underload, or ><>: ``` 404 ``` * To CJam: This pushes the literal `404` to the stack. The program ends, and the `404` is output. * To Python: This program consists of a single expression `404`. The expression is evaluated, and the program terminates. * To Underload: `4` and `0` are invalid commands, so the TIO interpreter simply ignores them, and the program terminates. * To ><>: `404` pushes `4`, `0` and `4` to the stack. The IP wraps around to the beginning, and the program repeats infinitely. --- The following works in CJam or Underload (though it errors) but not Python or ><>: ``` N(404)S;(\ ``` * To CJam: `N` pushes a string (array of characters) containing a newline to the stack. `(` pops the single character (a newline) out of the string. `404` pushes `404` to the stack, and then `)` increments it to give `405`. `S;` pushes a spaces and then immediately deletes it. `(` decrements again to get `404`, and then `\` swaps the newline and the `404`. `404\n` is output (the empty array is displayed as nothing). * To Underload: `N` is ignored. `(404)` pushes the string `404` to the stack. `S` outputs it. `;` is ignored. `(` causes the interpreter to try to look for a closing `)`, but as none is found, the program segfaults. * To Python: This is invalid syntax (the expression `N(404)` is followed by an identifier `S`, which is malformed), so the program errors. * To ><>: `N` is an invalid instruction, so the program errors. --- The following works in CJam (though it errors), Underload, or Python, but not ><>: ``` [] Le=404 +Le#(404)S (print(404)) ``` * To CJam: `[]` pushes the empty array to the stack, and `L` pushes the empty array to the stack. `e=` counts the number of occurrences of `[]` in `[]`, giving `0`. `404` pushes `404` to the stack. `+` adds the two numbers together, giving `404`. `L` pushes the empty array to the stack again, and `e#` creates a comment that lasts until the end of the line. `(` tries to pop an element out of an array, but since the top stack element is the empty array `[]`, the program errors. `404` is still output. * To Python: `[]` is a statement consisting of a no-op instruction. `Le=404` defines a variable `Le` to be equal to `404`. `+Le` takes the unary plus of the variable `Le` (a rather useless operation) and the result is discarded. `#(404)S` is a line comment. `(print(404))` prints 404. * To Underload: The only relevant part is `(404)S`, which pushes `404` to the stack and outputs it. `(print(404))` pushes `print(404)` to the stack, but nothing is done with it and the program terminates. * To ><>: `[` tries to pop a number off the top stack on the metastack, and then pop that many elements off that stack and make them into a new stack which is then pushed to the metastack. There is no number on the stack, so the program errors. --- The following works in CJam (though it errors), Python, Underload, and ><>: ``` "404nnn;\ " Le=404 +Le#(404)S (print(404)) ``` * To CJam: Most of what I said last time applies here. Instead of being `[]`, we now have a string literal, but the content is still unimportant. * To Python: Most of what I said last time applies here. Instead of being `[]`, the unused first expression is now a string literal, but the content is still unimportant. * To Underload: Everything I said last time applies here. All of the commands are still ignored. * To ><>: The `"` begins string mode, and the IP wraps around the first row pushing every character code it sees to the stack (this is unimportant). The IP wraps around and hits `"` again, which exits string mode. `404` pushes the digits `404` to the stack, and then `nnn` outputs each of them (technically, this happens in reverse order, but since 404 is a palindrome this doesn't matter). `;` ends the program. [Answer] # 8 Languages, 498 Bytes ## BFFuck ``` outc(52) outc(48) outc(52) ``` ## BFFuck, Python ``` print(404) ``` `print` prints a number in Python, while using `print()` with a string without quotes it prints out the string in BFFuck. ## BFFuck, Python, Brainfuck ``` print(404)#+++++++[>+++++++<-]>+++.----.++++. ``` BFFuck and Python both support `#` as comments. ## BFFuck, Python, Brainfuck, Befunge-93 ``` #["404",,,@] print(404)#+++++++[>+++++++<-]>+++.----.++++. ``` ## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus ``` #["404",,,@] print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+.-+++++.- ``` `-` in PlusOrMinus is the same as `.-` in BF, while `.` is an ignored character in PlusOrMinus ## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish ``` #["404",,,@]iisoddddoiiso print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+.-+++++.- ``` ## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish, Alphuck ``` #["404",,,@]pppiisoddddoiisosaeaeaepaepiceeeasccsajiiiijeeeej print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+.-+++++.-s ``` The hardest, because it mixes up with Python and Deadfish. ## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish, Alphuck, oOo CODE ``` #["404",,,@]pppiisoddddoiisosaeaeaepaepiceeeasccsajiiiijeeeej print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #+.-+++++.-saazzzZzZzzzZzZzzzZzZzZzzzzZzZzZzZzzzzZZzZZzZZzZzzzzZZzzZzzZzZZzzzZZz #ZzzZzzZzzZzzZZzZzZZzZZzZZzZZZz ``` [Answer] # 6 Languages Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript, Alphuck More to come! ## Brain-Hack ``` #(((()((()(((()()()){}){}){}){}){}){}){}) ``` Prints 404 in Brain-Hack ## Brain-Hack, Brain-Flak ``` (((()((()(((()()()){}){}){}){}){}){}){}) ``` ## Brain-Hack, Brain-Flak, Brain-Fuck ``` (((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++. ``` Uses comments in Brain-Flak to print it ## Brain-Hack, Brain-Flak, Brain-Fuck, Foo ``` "404" (((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++. ``` ## Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript ``` console.log("404") //(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++. ``` ## Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript, Alphuck ``` console.log("404") //(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++.iaipiiiiiaecsaejiiiijeeeej ``` [Answer] # 5 languages (87 bytes) ### [Pyon](https://github.com/alexander-liao/pyon) ``` print(404 ``` [Try it online!](https://tio.run/##K6jMz/v/v6AoM69Ew8TA5P9/AA "Pyon – Try It Online") ### [Python 2](https://docs.python.org/2/) ``` print(404) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69Ew8TARPP/fwA "Python 2 – Try It Online") ### [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack) ``` print(404)#(((()((()(((()()()){}){}){}){}){}){}){}) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v@/oCgzr0TDxMBEU1kDCDShGEgAoWZ1LRb0/z8A "Brain-Flak (BrainHack) – Try It Online") ### [brainfuck](https://github.com/TryItOnline/brainfuck) Taken from [Jo King's answer](https://codegolf.stackexchange.com/a/153724/59487) because I wasn't able to come up with a brainfuck code that had the brackets balanced (Brain-flak restriction). ``` print(404)#(((()((()(((()()()){}){}){}){}){}){}){})-[<+>-----]<+.----.++++.> ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v@/oCgzr0TDxMBEU1kDCDShGEgAoWZ1LRakG22jbacLArE22nogWk8bCPTs/v8HAA "brainfuck – Try It Online") ### [05AB1E](https://github.com/Adriandmen/05AB1E) Note that this also works with Ohm. ``` #404q print(404)#(((()((()(((()()()){}){}){}){}){}){}){})-[<+>-----]<+.----.++++.> ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f2cTApJCroCgzr0QDyNRU1gACTSgGEkCoWV2LBelG22jb6YJArI22HojW0wYCPbv//wE "05AB1E – Try It Online") Thanks to Jo King for -6 bytes. [Answer] # 2 Languages, 24 bytes, Python and Batch # Program 1: Python 3 ``` print('404') ``` # Program 2: Python 3 and Batch ``` print('404')#|echo 404 ``` After the the hash comments the rest of the code in python, and the | is a statement in bash to do this if the other command fails. [Answer] # 2 Languages, 53 bytes: C and Python Let's start things off with something simple. ## Program 1: C ``` int main(){printf("404");} ``` ## Program 2: C and Python ``` #define print(X)int main(){printf("404");} print(404) ``` TIO links: * [C program 1](https://tio.run/##S9ZNT07@/z8zr0QhNzEzT0OzuqAIyEnTUDIxMFHStK79/x8A) * [Python program 2](https://tio.run/##K6gsycjPM/r/XzklNS0zL1WhoCgzr0QjQhNIKuQmZuZpaFaDhdI0lEwMTJQ0rWu5IEqAPM3//wE) This is just an example, and will probably be beaten **many** times over. [Answer] # 4 languages, 91 bytes # C++ ``` #ifdef __cplusplus #include "stdio.h" int main(){printf("%d",404);} #endif ``` # C++, C ``` #include "stdio.h" int main(){printf("%d",404);} ``` Removes the C++ macro # C++, C, Befunge ``` #define A "404",,,@ #include "stdio.h" int main(){printf("%d",404);} ``` Adds a macro that will be ignored in C++, but read as code in Befunge. # C++, C, Befunge, Python ``` #define A "404",,,@ #include "stdio.h"//\ print(404);''' int main(){printf("%d",404);}//''' ``` Ads a piece of code that causes the next line to be a comment in C, but not in Python (`//<backslash>`) ]
[Question] [ As the majority of nations using the Euro have the `,` as the decimal separator, you must use it also. The task is to output all the values of the Euro coins and notes in ascending order. You must also put the trailing `,00` on the integer values. `0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00` I accept both output to stdout or a function returning an array/list. If output is to stdout, the acceptable separators between values are: space, tab, or newline. There will be no accepted answer, unless I see some one I find very creative. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so I want to know shortest answer by language. # Update: Leading `0` zeros are not acceptable. Sorry, I should make it clear before. # Update 2: It is also acceptable a function returning a string. [Answer] # Pure Bash, 48 ``` s={1,2,5} eval echo 0,0$s 0,${s}0 ${s}{,0,00},00 ``` [Try it online](https://tio.run/##S0oszvj/v9i22lDHSMe0liu1LDFHITU5I1/BQMdApRhIqlQX1xoogMhqHaCYQS0Q//8PAA). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~23~~ 22 bytes *-1 byte thanks to @Shaggy* ``` 5Æ#}ì ®eX-2 x2 d".," c ``` Returns an array of strings. [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=NcYjfewgrmVYLTIgeDIgZCIuLCIKYw==&input=LVI=) with the `-R` flag to output array items on separate lines. [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` print[('%.2f'%(10**(x/3-2)*(5>>~x%3))).replace(*'.,')for x in range(15)] ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr3gRd6Usla5@JDpIaAmxiniwS1@3mfK2O5MZo9REbQfBlYmCg16lhL7Y2aCEzbmvc4uIqoby@DOAFGoSGHNlnSVi1dMVQG94jPED "Python 2 – Try It Online") The expression `5>>~x%3` maps the non-negative integers to `1`, `2`, `5`, `1`, `2`, `5`… It works because `5`, `2`, `1` are the successive right-bitshifts of `5` (`0b101` → `0b10` → `0b1`); we cycle through them backwards. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` EE×125⁵⁺⁺×0⁻²÷κ³ι×0÷κ³⁺⁺✂ι⁰±²¦¹,✂ι±² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sQCMQzJzU4s1lAyNTJV0FEw1dRQCckqLNcAEVMoAKOGbmQcUMNJR8Mwrccksy0xJ1cjWUTDW1ARqyNRRQFKJoQDFyOCczORUDaAOAx0Fv9T0xJJUDSOgAkMgVtJRApJwBXBZELD@//@/btl/3eIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` 125 String `125` × ⁵ Repeated 5 times E Map over each character ÷κ³ ÷κ³ Integer divide loop index by 3 ⁻² Subtract from 2 ×0 ×0 Repeat the string `0` x times ⁺⁺ ι Concatenate with the character E Map over each resulting string ✂ι⁰±²¦¹ Slice off the last two digits ✂ι±² Extract the last two digits ⁺⁺ , Concatenate with a comma Implicitly print one per line ``` [Answer] # [SOGLOnline](https://github.com/dzaima/SOGLOnline) offline, ~~27~~ ~~26~~ ~~25~~ ~~24~~ ~~23~~ ~~22~~ 21 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 252¹5∙īυ;{⁴Ζ.,ŗP*F⁾?½ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MjUyJUI5NSV1MjIxOSV1MDEyQiV1MDNDNSUzQiU3QiV1MjA3NCV1MDM5Ni4lMkMldTAxNTdQKkYldTIwN0UlM0YlQkQ_) The online link doesn't show trailing zeroes, but the offline version does as Javas BigDecimals are nice. Explanation: ``` 252¹5∙īυ;{⁴Ζ.,ŗP*F⁾?½ 252¹ push the array [2, 5, 2] 5∙ multiply vertically by 5 īυ; push 0.01 below that - the main number { iterate over that array - [2,5,2,2,5,2,2,5,2,2,5,2,2,5,2] ⁴ duplicate the main number Ζ.,ŗ replace "." with "," P output in a new line * multiply the main number with the current item of the array F⁾? if the current array item-2 isn't 0, then ½ divide by 2 ``` TO run in the offline interpreter, download [SOGLOnlines repository](https://github.com/dzaima/SOGLOnline), go to compiler/interpreter, open any of the `.pde` files with [Processing](http://processing.org/), then do file -> export for your OS (otherwise you can't give arguments to a Processing program :/), and then execute the compiled program with an argument to the path of the file with the code. Then, stdout will contain [this](https://pastebin.com/Jy1u2vkQ). [`2L¼2¹5∙īυ;{⁴Ζ.,ŗP*`](https://dzaima.github.io/SOGLOnline/?code=MkwlQkMyJUI5NSV1MjIxOSV1MDEyQiV1MDNDNSUzQiU3QiV1MjA3NCV1MDM5Ni4lMkMldTAxNTdQKg__) for 18 bytes almost works but the zero amount grows, resulting in `0,01 0,02 0,050 0,100 0,200 0,5000 1,0000 2,0000 5,00000 10,00000 20,00000 50,000000 100,000000 200,000000 500,0000000` (newlines replaced with spaces) [Answer] # Java 8, ~~109~~ ~~108~~ ~~81~~ 80 bytes Thanks to @OlivierGrégoire for the Locale idea ``` x->{for(double i=.001;i<11;)System.out.printf("%.2f %.2f %.2f ",i*=10,i*2,5*i);} ``` [Try it online!](https://tio.run/##TY@xasMwFEV3f8UjUJBDIuxAJ8VZ0pYOpYVm6FA6KLIUnitLRnoKLcHf7go30C53OFwu53byLNd@0K5rPyfsBx8Iusx4IrT8yStptSiUlTHCG1wKgEiSUP0rmeQUoXd8711MvQ7bl2OnFe0gQDN9rXcX4wNrfTpaDdjwqqoFbutalIfvSLrnPhEfAjoybHHDNwb@YrHCZVNXOTer2yWWYpxEdhjyVna4qpw9ttBLdOxAeeb0/iHLWRXg9wCPmu60kckSu5KH1/vn/WMp5lbgUik9EHPJ2pmNxTj9AA "Java (OpenJDK 8) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 38 bytes ``` printf %.2f\\n {1,2,5}e{-2..2}|sort -h ``` Requires an appropriate locale, [which is allowed by default and costs no bytes](https://codegolf.meta.stackexchange.com/a/7886/12012). [Try it online!](https://tio.run/##S0oszvjv4@jnbpuaF@/i/b@gKDOvJE1BVc8oLSYmT6HaUMdIx7Q2tVrXSE/PqLamOL@oREE34/9/AA "Bash – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~30~~ 28 bytes Complete program. Outputs to space-separated to STDOUT. ``` '\.'⎕R','⊢2⍕×\.01,14⍴2 2.5 2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdtbQov/i/eoye@qO@qUHqOuqPuhYZPeqdenh6jJ6BoY6hyaPeLUYKRnqmCkYg5f/B6gE "APL (Dyalog Unicode) – Try It Online") `2 2.5 2` the list;  `[2,2.5,2]` `14⍴` cyclically **r**eshape to length 14;  `[2,2.5,2,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5]` `.01` prepend 0.01;  `[0.01,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5,2,2,2.5]` `×\` cumulative multiplication;  `[0.01,0.02,0.05,0.1,0.2,0.5,1,2,5,10,20,50,100,200,500]` `2⍕` format with two decimals;  `" 0.01 0.02 0.05 0.10 0.20 0.50 1.00 2.00 5.00 10.00 20.00 50.00 100.00 200.00 500.00"` `⊢` yield that (to separate `','` from `2`) `'\.'⎕R','` PCRE **R**eplace periods with commas;  `" 0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00"` [Answer] # R ~~70~~, 50 bytes inspired by @Giuseppe: ``` format(c(1,2,5)*10^rep(-2:2,e=3),ns=2,de=",",sc=F) ``` [Try it here!](https://tio.run/##K/r/Py2/KDexRCNZw1DHSMdUU8vQIK4otUBD18jKSCfV1lhTJ6/Y1kgnJdVWSUdJpzjZ1k3z/38A) Ungolfed ``` format(c(1,2,5)*10^rep(-2:2, each = 3), nsmall = 2, decimal.mark = ",", scientific = FALSE) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 37 bytes ``` smmX%"%.2f"*dk\.\,[1 2 5)[.01.1 1T^T2 ``` [Try it online!](https://tio.run/##K6gsyfj/vzg3N0JVSVXPKE1JKyU7Ri9GJ9pQwUjBVDNaz8BQz1DBMCQuxOj/fwA "Pyth – Try It Online") # [Pyth](https://github.com/isaacg1/pyth), 37 bytes Will shorten in a few minutes. ``` V[.01.1 1T^T2)V[1 2 5)X%"%.2f"*NH\.\, ``` [Try it online!](https://tio.run/##K6gsyfj/Pyxaz8BQz1DBMCQuxEgzLNpQwUjBVDNCVUlVzyhNScvPI0YvRuf/fwA "Pyth – Try It Online") [Answer] # JavaScript (ES6), 83 bytes Returns an array. ``` _=>[...'125'.repeat(k=5)].map(c=>(c*(c-1?k:k*=10)/5e3).toFixed(2).split`.`.join`,`) ``` ### Demo ``` let f = _=>[...'125'.repeat(k=5)].map(c=>(c*(c-1?k:k*=10)/5e3).toFixed(2).split`.`.join`,`) console.log(f()) ``` --- # Recursive version (ES7), 84 bytes Returns a string with a trailing space. ``` f=(i=0)=>i<15?('125'[i%3]/100*10**(i/3|0)).toFixed(2).split`.`.join`,`+' '+f(i+1):'' ``` ### Demo ``` f=(i=0)=>i<15?('125'[i%3]/100*10**(i/3|0)).toFixed(2).split`.`.join`,`+' '+f(i+1):'' console.log(f()) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ ~~77~~ ~~75~~ 73 bytes *-2 bytes thanks to @Mr.Xcoder* *-1 byte thanks to @EriktheOutgolfer* *-2 bytes thanks to @totallyhuman* *-2 bytes thanks to @Lynn* ``` print[('%.2f'%(v*m)).replace(*'.,')for m in.01,.1,1,10,100for v in 1,2,5] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kWkNdVc8oTV1Vo0wrV1NTryi1ICcxOVVDS11PR10zLb9IIVchM0/PwFBHz1AHCA2AyAAkXAYUVjDUMdIxjf3/HwA "Python 2 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 42 bytes ``` 5$*0 0 $'1$`¶$'2$`¶$'5$`¶ ..¶ ,$& m`^00? ``` [Try it online!](https://tio.run/##K0otycxL/P@fy1RFy4DLgEtF3VAl4dA2FXUjCGUKorj09ICEjooaV25CnIGBPdf//wA "Retina – Try It Online") Explanation: There are fifteen values, with 1, 2 and 5 in each of five places. The first stage inserts five 0s. The second stage repeats them into a square, then changes the trailing diagonal into 1s, then duplicates those lines three times with 2 and 5. The third stage inserts the commas and the last stage removes unnecessary leading zeros. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ”{➙∧N\`�4✳×″↶tι⦄|Q~(↥↗⁻“Q§U‴w⎇δUη◨÷¤G” ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJQMfAUAFIGIEIUyBhaAAkjECEqYGCoY6BgYIRiDAFEYYGYD6YNDWAiECFoGIgSknz////umX/dYtzAA "Charcoal – Try It Online") Link is to verbose version. Yay, compression! [Answer] # [Bash](https://www.gnu.org/software/bash/), 88 bytes ``` s=125 for i in {0..14};{ printf %1.2f\ `bc<<<"scale=2;${s:i%3:1}*10^$[i/3-2]"`|tr . ,;} ``` [Try it online!](https://tio.run/##S0oszvj/v9jW0MiUKy2/SCFTITNPodpAT8/QpNa6WqGgKDOvJE1B1VDPKC1GQSEhKdnGxkapODkxJ9XWyFqlutgqU9XYyrBWy9AgTiU6U99Y1yhWKaGmpEhBT0HHuvb/fwA "Bash – Try It Online") [Answer] # JavaScript (ES6), 81 bytes Returns an array. ``` _=>[...Array(13),b=.005,i=0].map(p=>(b*=++i%3?2:2.5).toFixed(2).replace(".",",")) ``` ### Demo ``` let f = _=>[...Array(13),b=.005,i=0].map(p=>(b*=++i%3?2:2.5).toFixed(2).replace(".",",")) console.log(f()) ``` --- [Answer] # Common Lisp, 95 bytes ``` (dotimes(i 5)(dolist(j'(1 2 5))(princ(substitute #\, #\.(format()"~$ "(*(expt 10(- i 2))j)))))) ``` [Try it online!](https://tio.run/##HYhLCoAwEMWuMqjgG1FRwdu48VNhxE@xU3Dl1WsxkEUy7@JsCFgulcM4CPUcI17FlqOlLg6GveWc4fzkVNSroXQoozXW6z5GBSdvRgkKmMcqtQ0qEuqYN/4J4QM) [Answer] # [Husk](https://github.com/barbuz/Husk), 28 bytes ``` ṁm↔ṪöJ',CtN`J§¤eR'0≥≤2ḣ5"125 ``` [Try it online!](https://tio.run/##ATMAzP9odXNr///huYFt4oaU4bmqw7ZKJyxDdE5gSsKnwqRlUicw4oml4omkMuG4ozUiMTI1//8 "Husk – Try It Online") Just string manipulation, since Husk is terrible at formatting floating point numbers. ## Explanation ``` ṁm↔ṪöJ',CtN`J§¤eR'0≥≤2ḣ5"125 "125 The string "125". ḣ5 The range [1,2,3,4,5]. Ṫö Compute their outer product wrt this function: Arguments are number n (say 3) and character c (say '5'). § ≥≤2 Compute max(0,n-2+1) and max(0,2-n+1), R'0 repeat '0' those numbers of times, ¤e and put them into a list: ["00",""] `J Join with c: "005" CtN Split to lengths 2 and at most 3: ["00","5"] J', Join with ',': "00,5" This gives a 2D array of the outputs reversed. ṁ Map and concatenate m↔ map reversal. Implicitly print separated by newlines. ``` [Answer] ## C++, ~~138~~ 120 bytes -18 bytes thanks to MSalters ``` #include<iostream> void p(){for(auto&a:{"0,0%d ","0,%d0 ","%d,00 ","%d0,00 ","%d00,00 "})for(int b:{1,2,5})printf(a,b);} ``` **Hardcoded version, by Lynn, 116 bytes** ``` #include<ios> void p(){puts("0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00");} ``` [Answer] # [R](https://www.r-project.org/), ~~70~~ 61 bytes ``` options(scipen=9,OutDec=",") print(c(1,2,5)*10^rep(-2:2,e=3)) ``` [Try it online!](https://tio.run/##K/r/P7@gJDM/r1ijODmzIDXP1lLHv7TEJTXZVklHSZOroCgzr0QjWcNQx0jHVFPL0CCuKLVAQ9fIykgn1dZYU/P/fwA "R – Try It Online") *-9 bytes thanks to Rui Barradas* Outgolfed by [AndriusZ](https://codegolf.stackexchange.com/a/141464/67312) [Answer] # [C (gcc)](https://gcc.gnu.org/), 82 bytes ``` p(n){printf("%d,%02d ",n/100,n%100);}f(n){for(n=1;n<5e4;n*=10)p(n),p(n*2),p(n*5);} ``` [Try it online!](https://tio.run/##S9ZNT07@/79AI0@zuqAoM68kTUNJNUVH1cAoRUFJJ0/f0MBAJ08VSGpa16aBFKXlF2nk2Rpa59mYpppY52nZGhpognTrAAktIwhlClT8PzcxM08DqF4DxAEA "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 125S5иεN3÷°*т/'.',:N2›i0« ``` Returns a list of strings. [Try it online.](https://tio.run/##ASsA1P9vc2FiaWX//zEyNVM10LjOtU4zw7fCsCrRgi8nLicsOk4y4oC6aTDCq///) **Explanation:** ``` 125 # Push 125 S # Split to a list of digits: [1,2,5] 5и # Repeat it 5 times: [1,2,5,1,2,5,1,2,5,1,2,5,1,2,5] ε # Map each to: N3÷ # Integer-divide the map-index by 3 ° # Take it to the power 10 * # Multiply the current map number with it т/ # Divide it by 100 '.',: # Replace all "." with "," N2›i # And if the map-index is larger than 2: 0« # Append a "0" ``` `125S5и` could be `•}•15∍` (push compressed `125`; enlarge it to size 15: `125125125125125`) and `'.',:` could be `„.,`:` (push string ".,", pop and push the characters as separated items to the stack) for the same byte-count: [Try it online.](https://tio.run/##yy9OTMpM/f//UcOiWiA2NH3U0Xtuq5/x4e2HNmhdbNJ/1DBPTyfBys/oUcOuTINDq///BwA) Also, `N3÷°*т/` can be shortened to `N3÷Ͱ*` (where `Í` subtracts 2), but unfortunately we need the `/` so all the numbers becomes decimals, whereas with `N3÷Ͱ*` most numbers will remain integers. [Answer] # T-SQL, 104 bytes ``` SELECT FORMAT(p*n,'0\,00') FROM(VALUES(1),(2),(5))a(n),(VALUES(1),(10),(100),(1E3),(1E4))b(p) ORDER BY p,n ``` Line breaks are for readability only. Annoyingly longer than the trivial `PRINT` version (90 bytes): ``` PRINT'0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00' ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 41 bytes ``` 00000000: 1dc5 8105 0040 1402 d055 1ae0 50d1 feab [[email protected]](/cdn-cgi/l/email-protection)... 00000010: dd2f 788f 8fc2 e192 433c 5c42 e891 7049 ./x.....C<\B..pI 00000020: 11ab 67a6 b8bc 90f5 01 ..g...... ``` [Try it online!](https://tio.run/##Zc49DsIwDAXgnVO8Exg7TdoEMSCY2FjYWJq/LiCxVOL2wS3deJJlefn84hzjs0zzqzXecoDk5OCFHZgtQywbZHYOMhaG4yyoZYwALTnp3IluunY/QdTI2VQM3lf4mgyKBAPbdQkuWT19EAxsgxr7z8pcjo8z0fu6GWbpIfqkH8Ye0ceEwFUbCf5DNK0GtfYF "Bubblegum – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 58 bytes ``` ¶0¶00¶000¶0000¶ .*¶ 1$&2$&5$& ^ ¶ +`¶(.?.?¶) ¶0$1 ..¶ ,$& ``` [Try it online!](https://tio.run/##K0otycxL/P@f69A2AyACYwgBJLn0tICEoYqakYqaqYoaVxxQFZd2wqFtGnr2evaHtmmCdKkYcunpAcV1VNT@/wcA "Retina – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~66~~ 62 bytes ``` -2.upto 2{|m|[1,2,5].map{|v|$><<('%.2f '.%v*10**m).tr(?.,?,)}} ``` 4 bytes shorter thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)! [Try it online!](https://tio.run/##KypNqvz/X9dIr7SgJF/BqLomtybaUMdIxzRWLzexoLqmrEbFzsZGQ11VzyhNQV1PtUzL0EBLK1dTr6RIw15Px15Hs7b2/38A "Ruby – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 107 bytes ``` Console.Write("0,01{0}2{0}5 0,10 0,20 0,50 1{1}2{1}5{1}1{2}2{2}5{2}10{2}20{2}50{2}"," 0,0",",00 ","0,00 "); ``` [Run it](https://tio.run/##HYoxCwMhDIX/SnC6A1sSwenGzp06dBYrRbgqXGyhSH67jR3e971HEvkU65HGeHMuT7h9uaXXFvfADLFzCy1H@NT8gGvIZVn7pRauezrfj9zSYtAidRSn8YCWUOEmPAJ10gOJ11B32p12J4RzTPgJY43@o8oiggr/XjeRMX4 "C# (.NET Core) – Try It Online") [Answer] # JavaScript - 96 bytes ``` x=>{for(o="",b=-2;b<3;b++)for(n of[1,2,5])o+=(n*10**b).toFixed(2).replace(".",",")+" ";return o} ``` And here's a slightly longer (98 characters) functional approach: ``` x=>[].concat.apply([],[.01,.1,1,10,100].map(n=>[n,n*2,n*5])).map(n=>n.toFixed(2).replace(".",",")) ``` [Answer] # [J](http://jsoftware.com/), 36 bytes ``` echo'.,'charsub 0j2":,1 2 5*/~10^i:2 ``` [Try it online!](https://tio.run/##y/r/PzU5I19dT0c9OSOxqLg0ScEgy0jJSsdQwUjBVEu/ztAgLtPK6P9/AA) [Answer] # [Tcl](http://tcl.tk/), 80 bytes ``` lmap d {-2 -1 0 1 2} {lmap c {1 2 5} {puts [regsub \\. [format %.2f $c\e$d] ,]}} ``` [Try it online!](https://tio.run/##K0nO@V@cWqKQmlem4ePo566pUFASHxDyPyc3sUAhRaFa10hB11DBQMFQwahWoRosmqxQDeQpmAL5BaUlxQrRRanpxaVJCjExegrRaflFuYklCqp6RmkKKskxqSopsQo6sbW1//8DAA "Tcl – Try It Online") # [Tcl](http://tcl.tk/), 90 bytes ``` lmap d {.01 .1 1 10 100} {lmap c {1 2 5} {puts [regsub \\. [format %.2f [expr $c*$d]] ,]}} ``` [Try it online!](https://tio.run/##HYlLCoAgGAav8i1qEyEadBp1YT7aFIkPCMSz/0nMbIYp9iK6bhPh0BgXYAIDPuQd7T8WTWDDPjrWkiGTP3M9oBSDDE@6TcHMtgDp35gw2WVyWmPVvRN9 "Tcl – Try It Online") Still very long, golfing it more later! ]
[Question] [ A prime power is a positive integer *n* that can be written in the form *n* = *pk* where *p* is a prime and *k* is a positive integer. For example, some prime powers are `[2, 3, 5, 4, 9, 25, 8, 27, 125]`. Next, consider prime powers of 2. These are `[2, 4, 8, 16, ...]` and can be written in the form 2*k*. They would all be included when considering prime powers beneath 20. However, 16 is the *maximal* prime power with a base prime of 2 in that range. A prime power *pk* is *maximal* in a range if it is the highest power of *p* in that range. We are only interested in the *maximal* prime power in each range so all lower prime powers must be excluded. Your goal is to write a function or program that takes a positive integer *n* and outputs the *maximal* prime powers in the range `[2, 3, 4, ..., n]`. Thanks to @[Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for clarifying the definition of *maximal* prime power and more. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so make your code as short as possible. * The *maximal* prime powers may be output in any order but there must be no duplicates. ## Test cases ``` n result 1 [] 2 [2] 3 [2, 3] 4 [3, 4] 5 [3, 4, 5] 6 [3, 4, 5] 7 [3, 4, 5, 7] 20 [5, 7, 9, 11, 13, 16, 17, 19] 50 [11, 13, 17, 19, 23, 25, 27, 29, 31, 32, 37, 41, 43, 47, 49] 100 [11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 64, 67, 71, 73, 79, 81, 83, 89, 97] 10000 <1229 results> [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, ..., 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973] ``` The full list of maximal prime powers for 10000 can be found [here](https://tio.run/nexus/bash#LdlLsu06bgTQqdQAqrElkviMpcIthyPc8/xbz8Li6SB4QV0cUEomEtj//M9//@///es/z@/597@e3xqTY/ozz/zznX@u2V1Ws7HHnPGd8cU8F7PKWeXs1uw2M76e3f423ufzve8ak2PGt@afE/nds3uY2Z3Ib8xGji/HN5Hfmo2JvCbdNUHXpLue@eekuybdtZkvwDqze2Y1ma7JdE2ma0KtmtUkuedF7Dn@fsa888/FrDHj27OaoHuS3DG7k@meyHuC7prVHH/Poc@82DNBz8Q7c/wzJz9z3jNJngl1JsqZ854575nzngl15qhnQsXkF3PomPPGYzUbk2RsZjYmaMyhYw4dk2TMoWOCxhw6Jr/8Md8jOVFyPkrOUXOOmhMq53vk5JcTJSe/nFA5qeW8tZoANV@hXmaNmY05ZU2omtRqEqoJVZNVzXlrEqr5qjVZ1QTtOWBPvJ6seqL0fNCeKD1n6wnVk1DPa@95YT2heqL0nK2h7gfLP2D@PdbvBfu1/GD9g@sfYP/iWrvBX/di8AP1T/x7a/5uzMPz8rw8oj2HR7Qneepaz4v2uoLvvXTiuCaPK/KFtOsOvvJ8D5s87pxb8Vlreb4yXCIvebov332eZ5b3sO4Nv1c8ruVxahflWbJd7fI76Zbb9n@3DF2QZ1@C2PzOvp19y3Y7@65r@b2BXZdWePqyC3rxV47czra@3CPmEfPI1oX5LI/Ix9ndl8eF@ezsujePO/OENxDvZTH2MtqltLhrT8o5ZBg3sjxdnSfFSdm6PU9uHu8hZZuyTd8rZej@fBZfytMVelyfp5y6RCinLl@nZFXOW76OG/RZz4jWorlFHwkj4HW52Fq09nU6Lz3z1GVpnj/GHu79DXI@eD7scPDvvdYu4v4dz8S1PIj6h6ndnc/y/5WBh51dN@VVZF5V5n3UgWfbFfkJnvRkqxyyen93PX53533fW2H45faKc8vKG/wyfJNfnm/dasQj/hJTafkKlAol2pKbyvIuMZdatZSopUa5L6/S8qotXyK3xily83W@UnftPO82fWlai@8GvW7Nq668W7ZbfAXlVUxet@Oz86Q78roj77llVG7uxUcYPDJxF17l43ULvlrL7@/Grb7@etwi7HSKx6t6fPauPXNjOl36Iul06YuoLG/6yilbt@OzPL5vOqPb8boRH6V5xrdwOz672KYCWDmX91bOXk6txLzuy@tevMrKR41jW5wWp72Bhuf2DhWWz/I4e0OLCvO6Ees3@Sw3Yqkp6/cSI0THb/OTHerIZ/npDTdiuQtL1fggxr5EzHtIGaomKJq4a8@UZ4pn3s9yCxb8L1Vjwf9SNRbMf9Yzxy4JRE6t11lUh3V11NVQqsNaTrTE@VNUm4emulJKvViQv66kukpqyW2LucVUHRbVtMimRTctwmlB@GftOuO@EWSoFnx2njnvtVfS0XTL2jsnpRbML9VhqQvr1LVXA45VEZZasNyCFc5LRi21YBFSK/5EI78zugWLfFpqwaKillqwoH2pCIucWirCIqgWCbXyalDnTajIvoJ0/HC@KKmlFiw4X2rBgvBFSS0CauH/RUKtukrW6QioBeGLjlotGjm1VITVzkhRLUJq9UTYv6uDJ5PPXmFsTRVTUFsV2HC@qabP8qQnCWF6adNLG/NvzL/1FRvzfwBZrPWxFuc5PHO6TR1t3cOG88/S5yJQR1v3sLH9hvkN7ful0GF@4/xNKW1KaWP7TQVtTcPG81vbsHH7XuQ9hG/Y3rdZuI3CbRJw@MbeG3tv@mffJuE2CLC9KZ9N82yaZx9v@HjDcP5Z/YWYUL3P7TichebZ8Lyx@qZ2dvhe@HzD8Gfnf0HyZ61lFbd1@WtbrrUrWooDw5uq2dh7Q/LWEGx6ZlMym5LZeHtD8me1Qb5aOVc5F1WzMfOmYTb0brjdmHlj5k23bLjdsLqpl60P2HC7aZiNqzf0bly9qZrdtwuTT98@7DZiOjHsfSD5YO9DyRzsfeD5szz6MHrmUDIHko@m@WiYDyVzMPl5NHSQfLD3ofkP9XKeYud7nff2hK/1uq2h3nDxBE/y@L@0yoHYQ88fKuXg6oOrD61ysPShTw418lkenSQdcvDzwc@HDjl63qPfPdTI2bdD3Z7ZdvP2rHZlBc/neBu31YXnA8Pntrx4@9Aq5/a6t9m93e5xRix94Plg4wO9R1d7KJMDvUdje@L2zL4RlX4ok0OTHJrkYOZDjXx2nk/nokCO/vbQIQcPH3g@tMeB3s/qwr0lnHx0tkdXe6iOQ58fzHxojwPhh1b/rF3xsfShQw60H5x8KJBDgRwK5LQnYTgwcEBsUN1BacRPq//T61PgQWkEBg4MHJRG4OGA2Hju5OC1XtfyiKZjDdojDHQCVsP4JuiNwMOBh4PeCDwcGPiz/IcVh94ODBw61qC3gwIJCiQo7TDACXgOeA6cHLRHmOIE7RG0R@hVAzOHeU5QIIGfAzOHLjWgN3ByUBpBUQdODnojYDWoizh3guL5cwcp/iLcBtwGdRHmNAG9cYc0d0Bz5zJ4OO4o5m8WI86dxmDdgNjAvQGxgYGDogiKInBvQG/kHefEnefY9dfzRhjkBxUR9ENAbBjGBC0RxjEBq2EWE7REwGpg5jCPCcz8JTiWrgi6IuiKoBxCRxktjplMYOOgmcNYJvrOnGSou8zfnT0NGpOuSIoi8XDCdlIUqaNMeE7zlnzuyGq@V9ISSUsk9CblkJRDUstpxpK6xYTe1C3me6de/i/WTfohYTipiKQWEusmnZxYN81PkjbOdWdmm18O5ieJb1Ovlzg2KeGEw6QNUpeXGDWhMU1FkkJIGjgxatIGSRUklH7NE882ott3zS8mxCZ2TShNmuGzdg0AaYaE2KQcEusmzZA0Q2LXhNg0CUndX94Ror4vITZxbNIMeYeJmDZ1eXmniJRDUgsJq0kbJKwmlCZ8JpWbWDTrb@R4155xFrOOhMykFrKdAqMmzZA0Q0Jp0gyps0vaoOiBwq5lvlEQWBi1aICCwKIBigYovFqUbeHVomzLDLDMAIsSKLOLogSKEihKoHRwn31nTioHaKz3b4Z6rVHqMkvd1nGtJ9O67qTV8/KB1cKohVFr3UGsE1GzBZ9lXlG0QWHOogGKmi2TvaIHigYoyrb0bqVrK3W/aNfCn6XWF2SW7qzMJQpzFjQWtiyqtXBmmUiUul8mcp/lMThW/YteLWgsXVhBY@HPUvELGssUoswfCn@WyUPhz4LJMp0ryCyMWri08s6hf9fe6fT472ybgi0zh7qTbdW/VPy6I22ILTOHjz7Ho8qXzqtgsoyyCxoLGot2LZxZ9GpjyFb9Gz4bWzYN0JRq48nWhTWsNg3QKn5jy8aWjSdbrW8ThsaWrdtqKG0Vv80ZGnO2ut/qfkNpw2dTrW3C1up@q/itvjel2pizYbKhsc0WWn1vlb3N01p9b/zZ5gkNma3batW8txz0XE21Nqy2Kt9Q2ti19/2tQG6w2vqvhthW95t2bXX/s35RkCEMt9lCQ2@f@3uDd@XnmDZVbtODVuUbbhti2wyh8Wfjz46/3yn8X38XYtv0oOGzdVutyrdZQVOnTZ123h85wtq71XO1it@w2qbHjUsbi7Za31Da1Gmr@K3ityrfWLTvzy64tO@vLxDb96cX/VffH1@waN8fXb5E/@uff/4f). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 4 bytes ``` æḟÆR ``` [Try it online!](https://tio.run/nexus/jelly#@3942cMd8w@3Bf0/3P6oaY37//@GOgpGOgrGOgomOgqmOgpmOgrmQBEDIAeIDQ0ghIEBAA "Jelly – TIO Nexus") ### How it works ``` æḟÆR Main link. Argument: n ÆR Prime range; yield all primes in [1, ..., n]. æḟ Power floor; round n down to the nearest power of each prime in the range. ``` [Answer] ## Mathematica, 44 43 40 bytes *Saved 4 bytes thanks to miles and Martin Ender* `n#^⌊#~Log~n⌋&/@Select[Range@n,PrimeQ]` ``` (x=Prime@Range@PrimePi@#)^⌊x~Log~#⌋& ``` `⌊` and `⌋` are the `3` byte characters `U+230A` and `U+230B` representing [`\[LeftFloor]`](https://reference.wolfram.com/language/ref/character/LeftFloor.html) and [`\[RightFloor]`](https://reference.wolfram.com/language/ref/character/RightFloor.html), respectively. ## Explanation: [![enter image description here](https://i.stack.imgur.com/8igDT.png)](https://i.stack.imgur.com/8igDT.png) Pure function. `#` is short for `Slot[1]` which represents the first argument to the `Function`. `PrimePi@#` counts the number of primes less or equal to `#`, `Range@PrimePi@#` is the list of the first `PrimePi[#]` positive integers, and so `Prime@Range@PrimePi@#` is the list of primes less than or equal to `#` (this is one byte shorter than `Select[Range@#,PrimeQ]`). The symbol `x` is `Set` equal to this list, then raised to the `Power` `⌊x~Log~#⌋`, which is the list of `Floor[Log[n,#]]` for each `n` in `x`. In Mathematica, raising a list to the `Power` of another list of the same length results in the list of the powers of their corresponding elements. [Answer] # MATL, 13 bytes ``` ZqG:!^tG>~*X> ``` [**Try it Online!**](https://tio.run/nexus/matl#@x9V6G6lGFfiblenFWH3/78xAA) **Explanation** ``` % Implicitly grab the input as a number (N) Zq % Get an array of all primes below N G:! % Create an array from [1...N] ^ % Raise each prime to each power in this array which creates a 2D matrix % where the powers of each prime are down the columns tG>~ % Create a logical matrix that is TRUE where the values are less than N * % Perform element-wise multiplication to force values > N to zero X> % Compute the maximum value of each column % Implicitly display the resulting array ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ÆR*ÆE€»/ ``` [Try it online!](https://tio.run/nexus/jelly#@3@4LUjrcJvro6Y1h3br/z/cDmS4//9vqGOkY6xjomOqY6ZjrmNkoGNqoGNoYAAA "Jelly – TIO Nexus") ### How it works ``` ÆR*ÆE€»/ Main link. Argument: n ÆR Prime range; yield all primes in [1, ..., n]. ÆE€ Prime exponents each; yield the exponents of 2, 3, 5, ... of the prime factorization of each k in [1, ..., n]. For example, 28 = 2² × 3⁰ × 5⁰ × 7¹ yields [2, 0, 0, 1]. * Exponentiation; raise the elements of the prime range to the powers of each of the exponents arrays. »/ Reduce the columns by maximum. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RÆEz0iṀ$€ ``` **[Try it online!](https://tio.run/nexus/jelly#@x90uM21yiDz4c4GlUdNa/7//29oYAAA)** (method is too slow for the 10000 case). ### How? Builds the list of **pk** in order of **p**. ``` RÆEz0iṀ$€ - Main link: n e.g. 7 R - range(n) [1 ,2 ,3 ,4 ,5 ,6 ,7] ÆE - prime factor vector (vectorises) [[],[1],[0,1],[2],[0,0,1],[1,1],[0,0,0,1]] z0 - transpose with filler 0 [[0,1,0,2,0,1,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]] $€ - la$t two links as a monad, for €ach ^ ^ ^ ^ i - first index of 4 3 5 7 Ṁ - maximum [4,3,5,7] ``` [Answer] ## Pyth, 13 bytes ``` m^ds.lQdfP_TS ``` [Try it here!](http://pyth.herokuapp.com/?code=m%5Eds.lQdfP_TS&input=23&debug=0) ``` f S - filter(v, range(1, input)) P_T - is_prime(T) m - map(v, ^) .lQd - log(input, d) s - int(^) ^d - d ** ^ ``` I haven't played with Pyth in a while so any golfing tips are appreciated. [Answer] I couldn't get a shorter Mathematica solution than [ngenisis's solution](https://codegolf.stackexchange.com/a/109309/56178), but I thought I'd offer a couple of (hopefully interesting) alternative approaches. ## Mathematica, 65 bytes ``` #/#2&@@@({#,#}&/@Range@#~Select~PrimeQ//.{a_,b_}/;a<=#:>{b a,b})& ``` First we use `{#,#}&/@Range@#~Select~PrimeQ` to build a list of all primes in the appropriate range, but with ordered pairs of each prime, like `{ {2,2}, {3,3}, ...}`. Then we operate on that list repeatedly with the replacement rule `{a_,b_}/;a<=#:>{b a,b}`, which multiplies the first element of the ordered pair by the second until the first element exceeds the input. Then we apply `#/#2&@@@` to output, for each ordered pair, the first element divided by the second. (They end up sorted by the underlying prime: an example output is `{16, 9, 5, 7, 11, 13, 17, 19}`.) ## Mathematica, 44 bytes ``` Values@Rest@<|MangoldtLambda@#->#&~Array~#|>& ``` The von Mangoldt function `Λ(n)` is an interesting number theory function: it equals 0 unless `n` is a prime power pk, in which case it equals `log p` (not `log n`). (These are natural logs, but it won't matter.) Thus `MangoldtLambda@#->#&~Array~#` creates an array of rules `{ 0->1, Log[2]->2, Log[3]->3, Log[2]->4, Log[5]->5, 0->6, ... }` whose length is the input integer. We then turn this list of rules into an "association" using `<|...|>`. This has the effect of retaining only the last rule with any given left-hand value. In other words, it will throw away `Log[2]->2` and `Log[2]->4` and `Log[2]->8` and keep only `Log[2]->16` (assuming that the input is between 16 and 31 for this example). Therefore the only remaining right-hand sides are the maximal prime powers—except for the one remaining rule `0->n`, where `n` is the largest non-prime-power up to the input integer. But `Rest` throws that undesired rule away, and `Values` extracts the right-hand sides from the rules in the association. (They end up sorted as above.) A slightly longer (46 bytes) version, which counts the number of appearances of each `log p` and then exponentiates to convert to the maximal prime powers: ``` E^(1##)&@@@Rest@Tally[MangoldtLambda~Array~#]& ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~21~~ 20 bytes *Saved 1 byte thanks to Martin Ender* ``` ri_){mp},f{\1$mLi#}p ``` [Try it online!](https://tio.run/nexus/cjam#@1@UGa9ZnVtQq5NWHWOokuuTqVxb8P@/oQEQAAA "CJam – TIO Nexus") **Explanation** ``` ri e# Read an integer from input (let's call it n) _ e# Duplicate it ){mp}, e# Push the array of all prime numbers up to and including n f{ e# Map the following block to each prime p: \ e# Swap the top two elements of the stack 1$ e# Copy the second element down in the stack. Stack is now [p n p] mL e# Take the base-p logatithm of n i e# Cast to int (floor) # e# Raise p to that power } e# (end of map block) p e# Print ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` ⟧{ḋ=}ˢ⊇Xhᵐ≠∧X×ᵐ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9o/vLqhzu6bWtPL3rU1R6R8XDrhEedCx51LI84PB3I/v/fyOB/FAA "Brachylog – TIO Nexus") This outputs the powers from biggest to smallest. This is very inefficient. ### Explanation ``` ⟧ The Range [Input, Input - 1, ..., 1, 0] { }ˢ Select: ḋ= The elements of that range whose prime decompositions are lists of the same element (e.g. [3,3,3]); output is those prime decompositions ⊇X X is an ordered subset of that list of prime decompositions Xhᵐ≠ All first elements of the prime decompositions are different (that is, X contains prime decompositions with different primes each times) ∧ X×ᵐ Output is the result of mapping multiplication to each element of X ``` This will find the biggest prime decompositions for each prime first because of the way `⊇` works: from left to right and from biggest to smallest subsets. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 21 19 bytes *3+2 bytes saved thanks to Fatalize!* This is my first time using Brachylog, and I know some things could have been done in shorter ways, but I'm happy that it even works :D ``` {≥.~^ℕ₁ᵐhṗ:.≜×>?∧}ᶠ ``` [Try it online!](https://tio.run/nexus/brachylog2#ASwA0///e@KJpS5@XuKEleKCgeG1kGjhuZc6LuKJnMOXPj/iiKd94bag//8xMDD/Wg "Brachylog – TIO Nexus") (Return values are ordered by their base primes) ### Explanation: ``` {................}ᶠ #Find all possible results of what's inside. ≥. #Input is >= than the output. .~^ℕ₁ᵐ #Output can be calculated as A^B, where A and B are #Natural numbers >=1. hṗ #The first of those numbers (A) is prime :.≜×>? #That same element (A), multiplied by the output #is greater than the input - This means #that B is the maximal exponent for A. ∧ #No more restrictions on the output. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 12 bytes ``` ƒNpiN¹N.nïm, ``` [Try it online!](https://tio.run/nexus/05ab1e#@39skl9Bpt@hnX56eYfX5@r8/29kAAA "05AB1E – TIO Nexus") **Explanation** ``` ƒ # for N in [0 ... input] Npi # if N is prime N # push N ¹N.n # push log_N(input) ï # convert to int m # raise N to this power , # print ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 74 bytes ``` seq $1|factor|sed "s@.*: \(\w*\)\$@\1;l($1);l(\1);print \"/^p\"@"|bc -l|dc ``` [Try it online!](https://tio.run/nexus/bash#@1@cWqigYliTlphckl9UU5yaoqBU7KCnZaUQoxFTrhWjGaPiEGNonaOhYqgJJGOAZEFRZl6JQoySflxBjJKDUk1SsoJuTk1K8v///w0NDAA "Bash – TIO Nexus") The input number is passed as an argument. The output is printed to stdout. (As is customary, stderr is ignored.) Sample output: ``` ./maximalprimepowers 100 2>/dev/null 64 81 25 49 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ./maximalprimepowers 10000 2>/dev/null | wc -l 1229 ``` Here's how it works: Call the argument N. `seq` generates all the numbers from 1 to N, and `factor` factors them all. The regex in the call to sed identifies those lines where the number is a prime P, and replaces those lines with lines that are of the form ` ``` P;l(N);l(P);print "/^p" ``` (where P and N are replaced by their actual numerical values, and everything else is copied literally, even the quotes and semicolons, and the string `print`). These lines are fed as input to `bc -l`; bc prints the values of the three indicated numbers, each followed by a newline, and then prints the characters `/^p` . (In bc, l(x) denotes the natural logarithm of x.) JK K The strings that bc prints are then fed as input to dc; dc prints the value of each P^(log(N)/log(P)) using integer arithmetic (truncating); that's the greatest power of P that is <= N. One thing that's glossed over above is what happens to lines that are produced by factors that don't correspond to primes. Those lines don't match the regex in the call to sed, so no replacement is done on those. As a result, those lines start with a number followed by a colon, which generates an error when fed as input to `bc`. But bc just prints to stderr then, which we ignore; it doesn't print anything to stdout. By default, [stderr is ignored on PPCG](http://meta.codegolf.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781). [Answer] # [Haskell](https://www.haskell.org/), ~~73 67~~ 66 bytes ``` p n=[last[x^i|i<-[1..n],x^i<=n]|x<-[2..n],all((>0).mod x)[2..x-1]] ``` [Try it online!](https://tio.run/nexus/haskell#HcgxCoAgFADQq/xRIUWDNvUE3UAMBBsE/Yk5OHR3s8b3RgHUNvm72X7EJypmJefoliml0T19zvqPT4kQIyjPV4BOv@1MOjeyjwga6unDjmCMhlIjNuBQxiZe "Haskell – TIO Nexus") Usage: ``` Prelude> p 50 [32,27,25,49,11,13,17,19,23,29,31,37,41,43,47] ``` **Edit:** 6 bytes off thanks to Zgarb! **Explanation:** ``` p n=[... x|x<-[2..n] ] -- list of all x in the range 2 to n p n=[... x|x<-[2..n], mod x<$>[2..x-1]] -- where the remainders of x mod the numbers 2 to x-1 p n=[... x|x<-[2..n],all(>0)$mod x<$>[2..x-1]] -- are all greater 0. This yields all primes in the range. p n=[ [x^i|i<-[1..n] ]|...] -- for each of those x generate the list of all x^i with i in the range 1 to n p n=[last[x^i|i<-[1..n],x^i<=n]|...] -- where x^i is smaller or equal to n p n=[last[x^i|i<-[1..n],x^i<=n]|...] -- and take the last (that is the largest) element ``` [Answer] # Regex (ECMAScript 2018 / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / .NET), 97 bytes ``` (?=(?=(xx+?)\1*$)(((?=(x+)(\4+$))\5)*\1$))(?<!(?=(?=(xx+?)(\6*$))(?=\7\1$)(?=(x+)\8+$)\8\9$)(x+)) ``` [Try it online!](https://tio.run/##bVHBbhoxEL3zFQuK5BkWrDUqTcrG7KkHLjm0xzhSrF2zcWW8W9uEFYRrPqCf2B@hXhIkDpV8mHlv5s288S/5Kn3pdBumtqnUyfMsd/yHqr93LfwMTtuaOrl7PkHB@9d1aYGCjW8Q4JynCOJLeoMo5jgWLAZQ3A@vq0F8HZ9hLm77gs82cRe7xJ34FpGY4umZeqNLBWwyZTghNcHcqd9b7RQQp2RltFUEaRnjoFY2KLeWsfygbbsNi9Y1pfKe@lBpe0TaWCDnjonhy0PNDfWt0QHINOrqNYDlNTXK1uEFl7O3N@0f5ANo3krne3WoH7MnxAuhrgm7ZAVb9DSGF9fsRiv7Ko2uEidtrRbJKDX5unGQ63uucp2meLhar9kGunM6KABfEGHJghBMdUqSv@9/krid5yzv@KgbUafaaBY0nuX28W9gwx1VnSqhQxxybrfG5HvO8DD4/4h9QZKPCZvH2dPFcX@B4SY6vACOGunDylaqS9Pj8YgnNr0dzLLBPBuwLJvO5tk/ "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 [Try it online!](https://tio.run/##TZBBboMwEEX3PoVrRbIHDLKT0qRQixPkBDGLSEBqiRpkWJAcoAfoEXsRapNUreTF/Jn//ow8XKf33u4W8zH0bsLjdeSuuTRzgZ1yhJCFlSq8eY5L0DLaAGOrjoHp53gDoDOItPQFK9@e/ruZfonWttL7YHhg@uApfdCvvuMlLH7LSeaJrAp8UwK1vcMdNjbcko5TbWyOcKe6dBw6MzGSEEA4mGwwubO9NMzYiXUnUQG/Vz4MYgkexKbFtxwPLgw86FfI4iEtp9@fX5Q3tlaUhmGIPa6x4Q/S1tjaTI1jjmMyk8hCficp5Ud/z9myLZxklfwJUf3GLTLZo61AmUBSiERm4gc "Python 3 – Try It Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) [Try it online!](https://tio.run/##TZDfaoMwGMXv@xROPjDRRVTm2tWFFna9JzBeiEtrIE0kplRavN0D7BH3Ii7K/kEu8jucczh8nb5w07dcygkMLQ0/8qHabhW/oH0woR2d3zBEO8zSEDBCC0cYsYcIMGY5DlnqPmj3fPffjdhjuMiUrWfDd4xtXIpt2JNTHOIp2N/7L/rUCcnffFzAlSbFQRteNy0C6QnlgVDd2eIb1BQk6TsprE/8QhwQ1HGjz8oSab1sNkQU6jKpRleAQNFSKFstSgGKSP7D6cxR5BInCiZ@rW3T8h4FQxCCwkvzFd8uRlhOWt3b0a1Kiz/2iNLuQFIo7vmgvM/3Dw/Q7@pmWX1y9U18NPrc9WVWxZKro21H7I/jlJL1KktWebJKk4RkefIF "PowerShell – Try It Online") - .NET Like [Pseudofactorial](https://codegolf.stackexchange.com/a/259550/17216), this uses [Neil's prime powers test](https://codegolf.stackexchange.com/a/210191/17216) instead of mine, because when capturing the smallest prime factor is also needed, it results in a shorter total length. ``` # tail = N ≤ M = input number # Assert tail is a prime power ≥ 2 (?= # Atomic lookahead (?=(xx+?)\1*$) # \1 = smallest prime factor of tail, # asserting that tail ≥ 2 ( # \2 = tail = N ( (?=(x+)(\4+$))\5 # tail = {largest proper divisor of tail} # = tail / {smallest prime factor of tail} )* # Iterate the above as many times necessary # (minimum zero) to make the following match: \1$ # Assert that tail == \1; if N is a prime power, # the end result of the above loop will always # be this. Otherwise it will be a larger prime, # and this will fail to match. ) ) # Assert there is no prime power (of the same base prime \1) # that is greater than N but less than or equal to M. (?<! # Negative Lookbehind - evaluated right-to-left, so read it # from bottom to top, but once entering the lookahead, go # back to left-to-right (top to bottom); assert that the # following cannot match: (?= # Lookahead (?=(xx+?)(\6*$)) # \6 = smallest prime factor of tail; \7 = tail-\6 (?= # Lookahead \7 # tail = tail - (tail - \6) = \6 \1$ # Assert tail == \1 ) (?=(x+)\8+$) # \8 = {largest proper divisor of tail} # = tail / {smallest prime factor of tail} \8\9$ # Assert tail == \8 + \9, meaning \8 == N ) (x+) # tail += \9 = any positive value, in which all possibilities # are tried, until a match is found, or all have been tried # and no matches were found) as long as the resulting tail ≤ M ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ræl/ÆF*/€ ``` One byte longer than [my other answer](https://codegolf.stackexchange.com/a/109305/12012), but finishes for input **10,000** is a couple of seconds. [Try it online!](https://tio.run/nexus/jelly#@x90eFmO/uE2Ny39R01r/v//b2gABAA "Jelly – TIO Nexus") ### How it works ``` Ræl/ÆF*/€ Main link. Argument: n R Range; yield [1, ..., n]. æl/ Reduce by least common multiple. ÆF Factor the LCM into [prime, exponent] pairs. */€ Reduce each pair by exponentiation. ``` [Answer] ## JavaScript (ES6), ~~118~~ ~~120~~ ~~119~~ ~~114~~ ~~112~~ 105 bytes ``` (n,r)=>(r=k=>[...Array(k-1)].map((_,i)=>i+2),r(n).filter(q=>r(q).every(d=>q%d|!(d%(q/d)*(q/d)%d)&q*d>n))) ``` Suggestions welcome. This is kind of long, but it seemed worth posting because it does all the divisibility testing explicitly rather than using built-ins related to primes. Notes: * A natural number q is a prime power <=> all of q's divisors are powers of the same prime <=> for any d which divides q, one of d and q/d is a divisor of the other. * If q is a power of p, q is maximal <=> q \* p > n <=> q \* d > n for every nontrivial divisor d of q. [Answer] # Sage, 43 bytes ``` lambda i:[x^int(ln(i,x))for x in primes(i)] ``` Maps each prime in the range `primes(i)` to its maximal prime power. `ln` is just an alias of `log` so it accepts alternate bases although its name suggests it can only use base `e`. [Answer] # Haskell, ~~110~~ 90 bytes ``` s[]=[];s(x:t)=x:s[y|y<-t,y`rem`x>0];f n=[last.fst.span(<=n).scanl1(*)$repeat x|x<-s[2..n]] ``` --updated per Laikoni's feedback [Answer] ## [Haskell](https://www.haskell.org/), 70 bytes ``` f n=[k|k<-[2..n],p:q<-[[d|d<-[2..k],mod k d<1]],k==p*p^length q,p*k>n] ``` Defines a function `f`. [Try it online!](https://tio.run/nexus/haskell#Jcg7CoAwEAXAq7zCSqKoYCPGi4QVhPgJq@sqKb17FOyGSQvEOn64L1xTlkJGu@uz84//i8kcpwfD9zWRYWs113GfZY0bLqM5D0LpmILAQu8gERkWtFV6AQ "Haskell – TIO Nexus") ## Explanation The idea is to filter the range `[2..n]` for those numbers `k` that satisfy `k == p^length(divisors k)` and `p*k > n`, where `p` is the smallest prime divisor of `k`. ``` f n= -- Define f n as [k| -- the list of numbers k, where k<-[2..n], -- k is drawn from [2..n], p:q<-[ -- the list p:q is drawn from [d| -- those lists of numbers d where d<-[2..k], -- d is drawn from [2..k] and mod k d<1] -- d divides k ], -- (so p:q are the divisors of k except 1, and p is the smallest one), k==p*p^length q, -- k equals p to the power of the divisor list's length -- (so it's in particular a prime power), and p*k>n] -- p*k, the next power of p, is not in the range [2..n]. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 6 bytes ``` ~æ~•⌊e ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJ+w6Z+4oCi4oyKZSIsIiIsIjMyIl0=) ``` ~ # Filter (implicit) range from 1 to n by æ # Is prime? ~ # Without popping • # Take the log of the input with base each of the primes ⌊ # Floor e # Raise the primes to those powers ``` [Answer] # PHP, ~~101~~ ~~93~~ ~~91~~ 88 bytes just a little bit of real maths ... ``` for($n=$argv[$i=1];$n>$j=$i++;$j?:$r[$p=$i**~~log($n,$i)]=$p)for(;$i%$j--;);print_r($r); ``` **breakdown** ``` for($n=$argv[$i=1]; // loop $i from 2 to $n $n>$j=$i++; // 0.: init $j to $i-1 $j?: // 2. if $i is prime $r[$p=$i**~~log($n,$i)]=$p) // 3. add maximum power to results for(;$i%$j--;); // 1. prime check (if $i is prime, $j will be 0) print_r($r); // print results ``` [Answer] # JavaScript ES7, 93 bytes Recursively iterate `i` from 0 up to and including `n`. If `i` is prime raise it to the highest floored exponent that makes it `<= n` (`i ^ floor(log(n) / log(i))`) ``` F=(n,i=n)=>i?[...((P=j=>i%--j?P(j):1==j)(i)?[i**((l=Math.log)(n)/l(i)|0)]:[]),...F(n,--i)]:[] ``` ]
[Question] [ To check whether a decimal number is divisible by 7: > > Erase the last digit. Multiply it by 2 and subtract from what is left. If the result is divisible by 7, the original number is divisible by 7. > > > (also described e.g. [here](https://www.easycalculation.com/divisibility-rule-by-7.php)) This rule is good for manual divisibility check. For example: > > Is 2016 divisible by 7? > > > Subtract `6*2` from 201; we get 189. Is this divisible by 7? To check it, let's apply the rule again. > > > Subtract `9*2` from 18; we get 0. Therefore, 2016 is divisible by 7. > > > In this challenge, you should apply this rule until the divisibility status is *obvious*, that is, the number is not greater than 70 (however, see below for details). Make a function or a full program. **Input**: a positive integer; your code should support inputs up to 32767 (supporting arbitrary-precision integers is a bonus; see below). **Output**: an integer (possibly negative), not greater than 70, that is a result of applying the divisibility-by-7 rule zero or more times. Test cases: ``` Input Output Alternative output 1 1 10 10 1 100 10 1 13 13 -5 42 42 0 2016 0 9 9 99 -9 9999 -3 12345 3 32767 28 -14 ---------- Values below are only relevant for the bonus 700168844221 70 7 36893488147419103232 32 -1 231584178474632390847141970017375815706539969331281128078915168015826259279872 8 ``` Where two possible outputs are specified, either result is correct: the second one corresponds to applying the rule one more time. It's forbidden to apply the rule on a single-digit number: if you erase the digit, nothing (not 0) is left. --- **Bonus**: If your algorithm * Supports arbitrary-precision integers * [Performs only one pass on the input](https://en.wikipedia.org/wiki/Streaming_algorithm) * Has space complexity `o(n)` (i.e. less than `O(n)`); and * Has time complexity `O(n)`, where `n` is the number of decimal digits: Subtract 50% from your code's byte count. **Real bonus**: In addition, if your algorithm reads the input in normal direction, starting from the most significant digit, subtract 50% once again - your score is 25% of your byte count (it seems possible, but I'm not absolutely sure). [Answer] # Golfscript, ~~27~~ 22 bytes ``` {.9>{.10/\10%2*-f}*}:f ``` You can use it this way: ``` 1000f ``` ## Explanation ``` {.9>{.10/\10%2*-f}*}:f { }:f # Define block 'f' (similar to a function) . # Duplicate the first value of the stack 9>{ }* # If the value on top of the stack is greater than 9 then the block is executed .10/\10%2*- # Same as nb/10 - (nb%10 * 2) with some stack manipulations '.' to duplicate the top of the stack and '\' to swap the the first and second element of the stack f # Execute block 'f' ``` 5 bytes saved thanks to Dennis ! [Answer] ## Haskell, 35 bytes ``` until(<71)(\n->div n 10-2*mod n 10) ``` Usage example: `until(<71)(\n->div n 10-2*mod n 10) 36893488147419103232` -> `32`. Nothing much to explain, it's a direct implementation of the algorithm. [Answer] # Jelly, 11 bytes ``` d⁵Uḅ-2µ>9$¿ ``` [Try it online!](http://jelly.tryitonline.net/#code=ZOKBtVXhuIUtMsK1Pjkkwr8&input=&args=MjMxNTg0MTc4NDc0NjMyMzkwODQ3MTQxOTcwMDE3Mzc1ODE1NzA2NTM5OTY5MzMxMjgxMTI4MDc4OTE1MTY4MDE1ODI2MjU5Mjc5ODcy) ### How it works ``` d⁵Uḅ-2µ>9$¿ Main link. Input: n d⁵ Divmod; return [n : 10, n % 10]. U Upend; yield [n % 10, n : 10]. ḅ-2 Convert from base -2 to integer, i.e., yield -2 × (n % 10) + (n : 10). µ Push the previous chain as a link and begin a new, monadic chain. ¿ Apply the previous chain while... >9$ its return value is greater than 9. ``` [Answer] # Python 2, 38 bytes ``` f=lambda x:f(x/10-x%10*2)if x>70else x ``` [Try it here](https://repl.it/Bmip/3)! Simple recursive approach. Prints x if its < 70 otherwise applies the divisibility rule and calls itself with the result. [Answer] # Pyth, 13 bytes ``` .W>H9-/ZTyeZQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=.W%3EH9-%2FZTyeZQ&input=36893488147419103232&test_suite_input=1%0A10%0A100%0A13%0A42%0A2016%0A9%0A99%0A9999%0A12345%0A700168844221%0A36893488147419103232&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=.W%3EH9-%2FZTyeZQ&input=36893488147419103232&test_suite=1&test_suite_input=1%0A10%0A100%0A13%0A42%0A2016%0A9%0A99%0A9999%0A12345%0A700168844221%0A36893488147419103232&debug=0) This will print all the alternative answers. ### Explanation: ``` .W>H9-/ZTyeZQ Q read a number from input .W while >H9 the number is greater than 9 do the following with the number: /ZT divide it by 10 - and subtract yeZ 2*(number%10) ``` [Answer] # Julia, ~~27~~ 26 bytes ``` f(x)=x>9?f(x÷10-x%10*2):x ``` This is a recursive function that accepts an integer and returns a `BigInt`. If the input is a large number like in the last example, Julia parses it as a `BigInt`, so no manual conversion is necessary. The approach is just a straightforward implementation of the algorithm. It will produce the alternate outputs. Taking the modulus when dividing by 10 yields the last digit and the quotient from integer division by 10 yields everything but the last digit. Saved a byte thanks to Dennis! [Answer] # Pyth, 17 bytes ``` L?<b70by-/bT*%bT2 ``` [Try it here!](http://pyth.herokuapp.com/?code=L%3F%3Cb70by-%2FbT*%25bT2yQ&input=700168844221&test_suite=1&test_suite_input=1%0A10%0A100%0A13%0A42%0A2016%0A9%0A99%0A9999%0A12345%0A700168844221%0A36893488147419103232&debug=0) Same recursive approach as in my [python answer](https://codegolf.stackexchange.com/a/73093/49110). Defines a lambda `y` which is called like this: `y12345`. The byte counter in the online interpreter shows 19 bytes because I added the lambda call to it, so you can just try it by hitting the run-button. ## Explanation ``` L?<b70by-/bT*%bT2 L # Defines the lambda y with the parameter b ?<b70 # if b < 70: b # return b, else: -/bT*%bT2 # calculate b/10 - b%10*2 and return it ``` [Answer] ## CJam - 19 bytes Do-while version: ``` r~A*{`)]:~~Y*-_9>}g ``` [Try it online](http://cjam.aditsu.net/#code=r~A*%7B%60)%5D%3A~~Y*-_9%3E%7Dg&input=231584178474632390847141970017375815706539969331281128078915168015826259279872) or While version #1: ``` r~{_9>}{`)]:~~Y*-}w ``` [Try it online](http://cjam.aditsu.net/#code=r~%7B_9%3E%7D%7B%60)%5D%3A~~Y*-%7Dw&input=231584178474632390847141970017375815706539969331281128078915168015826259279872) or While version #2: ``` r~{_9>}{_A/\A%Y*-}w ``` [Try it online](http://cjam.aditsu.net/#code=r~%7B_9%3E%7D%7B_A%2F%5CA%25Y*-%7Dw&input=231584178474632390847141970017375815706539969331281128078915168015826259279872). ``` r~ | Read and convert input A* | Multiply by 10 to get around "if" rule ` | Stringify ) | Split last character off ] | Convert stack to array :~ | Foreach in array convert to value ~ | Dump array Y* | Multiply by 2 - | Subtract _ | Duplicate 9> | Greater than 9? { }g | do-while ``` [Answer] # Oracle SQL 11.2, 116 bytes ``` WITH v(i)AS(SELECT:1 FROM DUAL UNION ALL SELECT TRUNC(i/10)-(i-TRUNC(i,-1))*2 FROM v WHERE i>70)SELECT MIN(i)FROM v; ``` Un-golfed ``` WITH v(i) AS ( SELECT :1 FROM DUAL UNION ALL SELECT TRUNC(i/10)-(i-TRUNC(i,-1))*2 FROM v WHERE i>70 ) SELECT MIN(i) FROM v; ``` [Answer] # Haskell, ~~157~~ ~~192~~ ~~184~~ ~~167~~ ~~159~~ ~~147~~ 138+5 bytes - 50% = 71.5 bytes **O(1) space, O(n) time, single-pass!** ``` h d=d%mod d 10 d%r=(quot(r-d)10,r) p![d]=d-p*10 p![d,e]=d#(e-p) p!(d:e:f)|(b,a)<-quotRem(2*d)10,(q,r)<-h$e-a-p=(b+q)!(r:f) m#0=m m#n=n-2*m (0!) ``` Use as `0![6,1,0,2]` to apply the rule to 2016, i.e. pass it a number in stream form with least significant figure first. In this way, it will pass over the number digit by digit, applying the rule with O(1) space complexity. The ungolfed code is here: ``` import Data.Char {- sub a b = sub2 0 a b where sub2 borrow (a:as) (b:bs) = res : sub2 borrow2 as bs where (borrow2, res) = subDig borrow a b sub2 borrow (a:as) [] = sub2 borrow (a:as) (0:[]) sub2 _ [] _ = [] -} --subDig :: Int -> Int -> Int -> (Int, Int) subDig borrow a b = subDig2 (a - b - borrow) where subDig2 d = subDig3 d (d `mod` 10) subDig3 d r = ((r-d) `quot` 10, r) seven ds = seven2 0 ds seven2 borrow (d:e:f:gs) = seven2 (b + borrow2) (res:f:gs) where (a, b) = double d (borrow2, res) = subDig borrow e a seven2 borrow (d:e:[]) = finalApp d (e-borrow) seven2 borrow (d:[]) = d - borrow*10 double d = ((2*d) `mod` 10, (2*d) `quot` 10) finalApp m 0 = m finalApp m n = n - 2*m num2stream :: Int -> [Int] num2stream = reverse . map digitToInt . show sev = seven . num2stream ``` The gist of how this works is that it implements a [digit-by-digit subtraction algorithm](https://en.wikipedia.org/wiki/Subtraction#In_America), but takes advantage of the fact that each number to be subtracted is at most 2-digits, and so we can subtract an arbitrary amount of these 1-or-2 digit numbers from the main one (as well as eating the least significant digits). The subtraction algorithm is O(1) and only stores the current 'borrow' value. I altered this to add in the extra digit (either 0 or 1), and we note that this borrow value is bounded (within the range [-2,2] so we need only 3 bits to store this). The other values stored in memory are temporary variables representing the current 2-digit number to add, a single look-ahead in the stream, and to apply one step of the subtraction algorithm (i.e. it takes two digits and a borrow value, and returns one digit and a new borrow value). Finally at the end it processes the last two digits in the stream at once to return a single-digit number rather than a list of digits. N.B. The `sev` function in the ungolfed version will work on an `Integer`, converting it into the reversed stream form. [Answer] # GNU dc, ~~20~~ 15 bytes ``` [10~2*-d70<F]sF ``` This defines my first (ever) dc function, `F`. It takes input on the top of stack, and leaves its output at top of stack. Example usage: ``` 36893488147419103232 lFxp 32 ``` [Answer] # Mathematica, ~~47~~ 44 bytes ``` If[#>70,#0[{1,-2}.{⌊#/10⌋,#~Mod~10}],#]& ``` Simple recursive approach. Could probably be golfed further. [Answer] # R, 43 bytes ``` x=scan();while(x>70)x=floor(x/10)-x%%10*2;x ``` Explanation: ``` x=scan() # Takes input as a double ; # Next line while(x>70) # While-loop that runs as long x > 70 floor(x/10) # Divide x by 10 and round that down -x%%10*2 # Substract twice the last integer x= # Update x ; # Next line once x <= 70 x # Print x ``` Sample runs: ``` > x=scan();while(x>70)x=floor(x/10)-x%%10*2;x 1: 9999 2: Read 1 item [1] -3 > x=scan();while(x>70)x=floor(x/10)-x%%10*2;x 1: 32767 2: Read 1 item [1] 28 ``` [Answer] # C, 56 bytes - 75% = 14 Although this doesn't give the exact same numbers as the test cases, it satisfies the spirit of the question (and arguably more). It correctly identifies exact multiples of 7, and gives the exact remainder for other numbers (since it doesn't ever use negative numbers). ``` n;f(char*c){for(n=0;*c;)n-=n>6?7:'0'-n-n-*c++;return n;} ``` There is no multiplication or division in the algorithm, only addition and subtraction, and digits are processed in a single pass from left to right. It works as follows, starting with 0 in the accumulator: 1. Subtract 7 if necessary, and again if still necessary 2. Multiply the running total by three, and add the next digit The "multiply by three" step is written as `n-=-n-n` to save a byte and to avoid the multiply operator. When we hit the end, we don't subtract sevens, so the result will be in the range 0-24; if you want a strict modulus (0-7), substitute `*c` with `*c||n>6` in the `for` loop condition. It qualifies for the enhanced bonus, because it * supports arbitrary-precision integers * performs only one pass on the input, in left-to-right order * has space complexity O(1) * has time complexity O(n). ## Test program and results ``` #include <stdio.h> int main(int argc, char **argv) { while (*++argv) printf("%s -> %d\n", *argv, f(*argv)); return 0; } ``` ``` 540 -> 15 541 -> 16 542 -> 17 543 -> 18 544 -> 19 545 -> 20 546 -> 21 547 -> 22 548 -> 23 549 -> 24 550 -> 18 99 -> 15 999 -> 12 12345 -> 11 32767 -> 7 700168844221 -> 7 36893488147419103232 -> 11 231584178474632390847141970017375815706539969331281128078915168015826259279872 -> 11 ``` ## Alternative version Here's one that recurses (you'll want to enable compiler optimizations to do tail-call transformation or you may overflow your stack; I used `gcc -std=c89 -O3`): ``` f(c,n)char*c;{return n>6?f(c,n-7):*c?f(c+1,n+n+n+*c-'0'):n;} ``` Call it with '0' as the second argument. Both versions calculate the remainder-modulo-seven of a 60,000 digit number in under 50 milliseconds on my machine. [Answer] ## ~~JavaScript ES6, 38 bytes~~ ``` a=i=>i>70?a(Math.floor(i/10)-i%10*2):i ``` Fails with `36893488147419103232` and using `~~(1/10)` will also fail for `700168844221` Test: ``` a=i=>i>70?a(Math.floor(i/10)-i%10*2):i O.textContent = O.textContent.replace(/(-?\d+) +(-?\d+)/g, (_,i,o) => _+": "+(a(+i)==o?"OK":"Fail") ); ``` ``` <pre id=O>1 1 10 10 100 10 13 13 42 42 2016 0 9 9 99 -9 9999 -3 12345 3 700168844221 70 36893488147419103232 32</pre> ``` [Answer] # Mathematica, 33 bytes ``` #//.a_/;a>70:>⌊a/10⌋-2a~Mod~10& ``` **Test case** ``` %[9999] (* -3 *) ``` [Answer] ## Perl 5, ~~47~~ 46 bytes Had to use `bigint`for the last test case. (It returns 20 without) ``` use bigint;$_=<>;while($_>9){$_-=2*chop;}print ``` Not really sure it's a candidate for the bonus, so I didn't take it into account. (I think it does, but I'm not really accustomed to the concepts) [Try it here!](https://ideone.com/zd6hCN) [Answer] ## ES6, 108 bytes ``` f=(s,n=0)=>s>1e9?f(s.slice(0,-1),((1+s.slice(-1)-n%10)%10*21+n-s.slice(-1))/10):s>9?f(((s-=n)-s%10*21)/10):s ``` Works for 2²⁵⁷ and 1000000000000000000001, but could use further golfing. [Answer] # JavaScript ES6, ~~140~~ 142 bytes ``` f=s=>s>9?eval("t=s.replace(/.$/,'-$&*2');for(i=-1;0>(n=eval(u=t[c='slice'](i-4)))&&u!=t;i--);n<0?n:f(t[c](0,i-4)+('0'.repeat(-i)+n)[c](i))"):s ``` This is true arbitrary-precision math, even works on the largest test-case. This function recursively removes the last digit from the string, then subtracts 2 \* the last digit from the remaining numerical string by iteratively incrementing the amount of digits to apply to the minuend until the difference is positive. Then it appends that difference to the end of the string with appropriately padded `0`s and calls itself recursively until its numerical value is less than or equal to `9`. * Golfed 7 bytes thanks to @Neil (yes I know I gained 2 bytes but I fixed a few bugs that caused the function to freeze or return wrong output for some cases). ``` f=s=>s>9?eval("t=s.replace(/.$/,'-$&*2');for(i=-1;0>(n=eval(u=t[c='slice'](i-4)))&&u!=t;i--);n<0?n:f(t[c](0,i-4)+('0'.repeat(-i)+n)[c](i))"):s;[['1',1],['10',1],['100',1],['13',-5],['42',0],['2016',0],['9',9],['99',-9],['9999',-3],['12345',3],['700168844221',7],['36893488147419103232',-1],['231584178474632390847141970017375815706539969331281128078915168015826259279872',8]].map(a=>document.write(`<pre>${f(a[0])==a[1]?'PASS':'FAIL'} ${a[0]}=>${a[1]}</pre>`)) ``` [Answer] ## C#, ~~111~~ 104 bytes ``` int d(int n){var s=""+n;return n<71?n:d(int.Parse(s.Remove(s.Length-1))-int.Parse(""+s[s.Length-1])*2);} ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~368~~ 360 bytes [Try it Online!](http://brain-flak.tryitonline.net/#code=KFsoWyh7fSldPCgoKSk-KV0oPD4pKXsoe30oKSk8Pn17fTw-e317fTw-KCh7fSkpe3t9e308Pig8KCgpKT4pfXt9KHt9PD4pe3t9KCh7fSkpKDwoKCgpKCkoKSgpKCkpe308Pik-KTw-eyh7fVsoKV0pPD4oKHt9KClbKHt9KV0pKXt7fSg8KHt9KHt9KSk-KX17fTw-fXt9PD4oWyhbKFsoKHt9PHt9Pjw-KTwoW3t9XXt9KSg8KCgoKSgpKCkoKSgpKXt9KDw-KSk-KTw-eyh7fVsoKV0pPD4oKHt9KClbKHt9PCh7fSgpKT4pXSkpe3t9KDwoe30oe308KHt9WygpXSk-KSk-KX17fTw-fXt9PD57fXt9KHt9PD4pPil7fV17fSldPCgoKSk-KSg8PildKXsoe30oKSk8Pn17fTw-e317fTw-KCh7fSkpe3t9e308Pig8KCgpKT4pfXt9KHt9PD4pfXt9&input=MjAxNg) ``` ([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>){{}(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>([([([(({}<{}><>)<([{}]{})(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)>){}]{})]<(())>)(<>)]){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>)}{} ``` ## Explanation To start off all of the code is in a loop that runs until the top of the stack is less than zero: ``` ([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>) {{} ... ([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>) }{} ``` Inside of the loop we run the divisible by seven algorithm: Duplicate the top of the stack ``` (({})) ``` Take the mod 10 of the top of the stack (last digit) ``` (<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>) ``` This is a bit of a mess but it does the rest of the algorithm I might explain it later but I don't entirely remember how it works: ``` ([(({})<([{}]{})(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)>){}]{}) ``` [Answer] # PHP, 50 bytes ``` for($n=$argv[1];$n>9;)$n=$n/10|0-2*($n%10);echo$n; ``` uses alternative output; works up to `PHP_INT_MAX` --- string version, works for any (positive) number (64 bytes): ``` for($n=$argv[1];$n>9;)$n=substr($n,0,-1)-2*substr($n,-1);echo$n; ``` [Answer] ## Java, 133 bytes ``` int d(int n){String s=""+n;return n<71?n:d(Integer.parseInt(s.replaceFirst(".$",""))-Integer.parseInt(""+s.charAt(s.length()-1))*2);} ``` I hate how verbose `Integer.parseInt` is. Ungolfed: ``` static int div(int n) { if (n <= 70) { return n; } else { String num = ("" + n); int last = Integer.parseInt("" + num.charAt(num.length() - 1)); int k = Integer.parseInt(num.replaceFirst(".$", "")) - last * 2; return div(k); } } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` Ω≤70§-ȯD→d÷10 ``` [Try it online!](https://tio.run/##ASIA3f9odXNr///OqeKJpDcwwqctyK9E4oaSZMO3MTD///8yMDE2 "Husk – Try It Online") Tied with Pyth, using a modified method. ## Explanation ``` Ω≤70§-ȯD→d÷10 Ω≤70 until the number is ≤ 70, §- subtract →d the last digit ȯD doubled ÷10 from the number floor divided by 10 ``` ]
[Question] [ *This question was inspired by [this HNQ](https://math.stackexchange.com/questions/1566017/what-happens-if-you-repeatedly-take-the-arithmetic-mean-and-geometric-mean/1566049#1566049).* ## About the series This question is now part of a series about the AGM method. This first post in the series will be about actually calculating the `AGM`. You may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. ## What is the Arithmetic–Geometric Mean The [Arithmetic–Geometric Mean](https://en.wikipedia.org/wiki/Arithmetic%E2%80%93geometric_mean) of two numbers is defined as the number that repeatedly taking the arithmetic and geometric means converges to. Your task is to find this number after some `n` iterations. ## Clarifications * You take three numbers, `a, b, n` in any reasonable format. * For `n` iterations, take the arithmetic and geometric mean of `a` and `b` and set those to `a` and `b`. * For two numbers `a` and `b`, the arithmetic mean is defined as `(a + b) / 2`. * The geometric mean is defined as `√(a * b)`. * `a` and `b` should be approaching each other. * Then, output both `a` and `b`. * You don't have to worry about float imprecision and such. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins! ## Test Cases ``` [0, [24, 6]] -> [24, 6] [1, [24, 6]] -> [15.0, 12.0] [2, [24, 6]] -> [13.5, 13.416407864998739] [5, [24, 6]] -> [13.458171481725616, 13.458171481725616] [10, [100, 50]] -> [72.83955155234534, 72.83955155234534] The next one is 1/Gauss's Constant: [10, [1, 1.41421356237]] -> [1.198140234734168, 1.1981402347341683] ``` ## Leaderboard *Stolen from Martin's series.* The following snippet will generate a leaderboard across all challenges of the series. To make sure that your answers show up, please start every 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 ``` ``` /* Configuration */ var QUESTION_IDs = [66068]; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!.FjwQBrX2KXuFkv6p2lChi_RjzM19"; /* App */ var answers = [], page = 1, currentQ = -1; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_IDs.join(";") + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function getAnswers() { $.ajax({ url: answersUrl(page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); if (data.has_more) getAnswers(); else process(); } }); } getAnswers(); var SIZE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;((?!&gt;).)*&lt;\/s&gt;|((?!&gt;).)+&gt;)[^\d&]*)*$)/; var NUMBER_REG = /\d+/; var LANGUAGE_REG = /^#*\s*([^\n,]+)(?=,)/;// function shouldHaveHeading(a) { var pass = false; var lines = a.body_markdown.split("\n"); try { pass |= /^#/.test(a.body_markdown); pass |= ["-", "="] .indexOf(lines[1][0]) > -1; pass &= LANGUAGE_REG.test(a.body_markdown); } catch (ex) {} return pass; } function shouldHaveScore(a) { var pass = false; try { pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]); } catch (ex) {} if (!pass) console.log(a); return pass; } function getAuthorName(a) { return a.owner.display_name; } function getAuthorId(a) { return a.owner.user_id; } function process() { answers = answers.filter(shouldHaveScore) .filter(shouldHaveHeading); answers.sort(function (a, b) { var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0], bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0]; return aB - bB }); var users = {}; answers.forEach(function (a) { var headline = a.body_markdown.split("\n")[0]; var question = QUESTION_IDs.indexOf(a.question_id); var size = parseInt((headline.match(SIZE_REG)||[0])[0]); var language = headline.match(LANGUAGE_REG)[1]; var user = getAuthorName(a); var userId = getAuthorId(a); if (!users[userId]) users[userId] = {name: user, nAnswer: 0, answers: []}; if (!users[userId].answers[question]) { users[userId].answers[question] = {size: Infinity}; users[userId].nAnswer++; } if (users[userId].answers[question].size > size) { users[userId].answers[question] = {size: size, link: a.share_link} } }); var sortedUsers = []; for (var userId in users) if (users.hasOwnProperty(userId)) { var user = users[userId]; user.score = 0; user.completedAll = true; for (var i = 0; i < QUESTION_IDs.length; ++i) { if (user.answers[i]) user.score += user.answers[i].size; else user.completedAll = false; } sortedUsers.push(user); } sortedUsers.sort(function (a, b) { if (a.nAnswer > b.nAnswer) return -1; if (b.nAnswer > a.nAnswer) return 1; return a.score - b.score; }); var place = 1; for (var i = 0; i < sortedUsers.length; ++i) { var user = sortedUsers[i]; var row = '<tr><td>'+ place++ +'.</td><td>'+user.name+'</td>'; for (var j = 0; j < QUESTION_IDs.length; ++j) { var answer = user.answers[j]; if (answer) row += '<td><a href="'+answer.link+'">'+answer.size+'</a></td>'; else row += '<td class="missing"></td>'; } row += '<td></td>'; if (user.completedAll) row += '<td class="total">'+user.score+'</td>'; else row += '<td class="total missing">'+user.score+'</td>'; row += '</tr>'; $("#users").append(row); } } ``` ``` body { text-align: left !important} #leaderboard { width: 500px; } #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; } td.total { font-weight: bold; text-align: right; } td.missing { background: #bbbbbb; } ``` ``` <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="leaderboard"> <h2>Leaderboard</h2> <p> Missing scores are shown as grey cells. A grey total indicates that the user has not participated in all challenges and is not eligible for the overall victory yet. </p> <table class="_user-list"> <thead> <tr><td></td><td>User</td> <td><a href="http://codegolf.stackexchange.com/q/66068">#1</a></td> <td></td><td>Total</td> </tr> </thead> <tbody id="users"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><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] ## CJam, 16 bytes ``` {{_2$+2/@@*mq}*} ``` Takes input on the stack as `a b n` where `a` and `b` are doubles. [Online demo](http://cjam.aditsu.net/#code=1%202dmq%2010%0A%0A%7B%7B_2%24%2B2%2F%40%40*mq%7D*%7D%0A%0A~%5D%60) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~22~~ ~~21~~ 15 bytes ``` .5∘(+.×,×.*⍨)⍣⎕ ``` Takes (*a*,*b*) as right argument, and prompts for *n*: `(`   `+.×` dot product of 0.5 and the right argument  `,` followed by   `×.*⍨` "dot power" of the right argument and 0.5\* `)⍣⎕` applied numeric-prompt times. \* "dot power" is like dot product, but using multiplication and power instead of plus and multiplication, as follows:       *n* `A ×.*⍨ B` is **∏** *BiA* = **∏** *B*1*AB*2*A*       *i*=1 -3 bytes thanks to ngn. --- Old version: ``` {((+/÷≢),.5*⍨×/)⍣⍺⊢⍵} ``` Takes `n` as left argument and `a b` as right argument. `⊢⍵` On the RightArg `(`...`)⍣⍺` recalculate LeftArg times `(+/÷≢)` sum divided by tally `,` followed by `.5*⍨×/` the square root of the product. All the test cases: ``` f←{((.5×+/),.5*⍨×/)⍣⍺⊢⍵} 0 1 2 5 10 10 f¨ (24 6)(24 6)(24 6)(24 6)(100 50)(1,2*.5) ┌────┬─────┬────────────────┬───────────────────────┬───────────────────────┬───────────────────────┐ │24 6│15 12│13.5 13.41640786│13.45817148 13.45817148│72.83955155 72.83955155│1.198140235 1.198140235│ └────┴─────┴────────────────┴───────────────────────┴───────────────────────┴───────────────────────┘ ``` [Answer] ## TI-BASIC, 22 bytes ``` Input N For(I,1,N {mean(Ans),√(prod(Ans End Ans ``` Does exactly what the algorithm says. Takes N from the prompt, and A and B through `Ans` as a two-element list. If N is 0, the `For(` loop is skipped entirely. [Answer] # JavaScript ES7, ~~48~~ 43 bytes -5 thanks to Downgoat! ``` f=(n,a,b)=>n?f(n-1,(a+b)/2,(a*b)**.5):[a,b] ``` Very simple recursive function. [Answer] # MATLAB/Octave, ~~69~~ 65 bytes ``` function [a,b]=r(a,b,n) for i=1:n;j=(a+b)/2;b=(a*b)^.5;a=j;end ``` [Answer] # Jelly, 9 bytes ``` SH;P½¥ðṛ¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=U0g7UMK9wqXDsOG5m8Kh&input=&args=WzI0LjAsIDYuMF0+NQ) ### How it works ``` SH;P½¥ðṛ¡ Input: x (vector) -- y (repetitions) SH Take the sum (S) of x and halve (H) the result. P½ Take the product (P) of x and the square root (½) of the result. ¥ Combine the last two instructions in a dyadic chain. ; Concatenate the results to the left and to the right. ð Push the preceding, variadic chain; begin a new, dyadic chain. ṛ Return the right argument (y). ¡ Repeat the pushed chain y times. ``` [Answer] ## C++, ~~108~~ ~~102~~ 100 bytes Thank you to @RetoKoradi and @AlexA for saving me 6 bytes. This is non-competitive, because C++ is not a good golfing language. Did this for fun :) ``` #include<cmath> std::string f(float a,float b,int n){return n==0?a+" "+b:f((a+b)/2,sqrt(a*b),n-1);} ``` This is a simple recursion function, very similar to the JS answer. [Answer] # K5, 15 bytes Very literal: ``` {(+/x%2;%*/x)}/ ``` In action: ``` {(+/x%2;%*/x)}/[0; 24 6] 24 6 {(+/x%2;%*/x)}/[5; 24 6] 1.345817e1 1.345817e1 ``` Unfortunately, this does not work in oK because that interpreter does not currently support projection (currying) of adverbs. Works in the real k5. In oK, it would currently be necessary to wrap the definition in a lambda: ``` {x{(+/x%2;%*/x)}/y}[5; 24 6] 13.4582 13.4582 ``` [Answer] # J, ~~18~~ 13 bytes ``` -:@+/,%:@*/^: ``` Usage: ``` agm =: -:@+/,%:@*/^: 5 agm 24 6 13.4582 13.4582 ``` [Answer] ## Seriously, 11 bytes ``` ,p`;π√@æk`n ``` Hex Dump: ``` 2c70603be3fb40916b606e ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c70603be3fb40916b606e&input=[3,24,6]) Explanation: ``` , Read in the list as [n,a,b] p pop list to yield: n [a,b] ` `n Push a quoted function and run it n times. ; Duplicate [a,b] pair π√ Compute its product and square root it (GM) @ Swap the other copy of the pair to the top æ Compute its mean. k Compile the stack back into a list. ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), 24 bytes ~~25 33~~ *Saved 9 ~~7~~ bytes thank to @ETHproductions* ``` Uo r@[VW]=[V+W /2(V*W q] ``` Takes advantage of ES6 destructuring. [Try it online](http://ethproductions.github.io/japt?v=master&code=VW8gckBbVlddPVtWK1cgLzIoVipXIHFd&input=MTAgMTAwIDUw) ### Ungolfed && Explanation ``` Uo r@[VW]=[V+W /2(V*W q] // Implicit: U: 1st input, V: 2nd input, W: 3rd input Uo // Range from 0 to 1st input r@ // Loop over range [V,W]= // Set 2nd and 3rd input to... [V+W /2, // Add 2nd and 3rd inputs, divide by 2 (V*W q] // Multiple 2nd and 3rd inputs, find square root // Set's to the above respectively // Implicit: return [V,W] ``` [Answer] # Matlab, 54 bytes ``` function x=f(x,n) for k=1:n x=[mean(x) prod(x)^.5];end ``` Example: ``` >> f([24 6], 2) ans = 13.500000000000000 13.416407864998739 ``` [Answer] # Pyth, 12 ``` u,.OG@*FG2EQ ``` [Test Suite](https://pyth.herokuapp.com/?code=u%2C.OG%40%2AFG2EQ&input=%5B1%2C%201.41421356237%5D%0A10&test_suite=1&test_suite_input=%5B24%2C%206%5D%0A0%20%20%20%0A%5B24%2C%206%5D%0A1%0A%5B24%2C%206%5D%0A2%0A%5B24%2C%206%5D%0A5%0A%5B100%2C%2050%5D%0A10%0A%5B1%2C%201.41421356237%5D%0A10&debug=0&input_size=2) ### Explanation ``` u,.OG@*FG2EQ ## implicit: Q = eval(input()) u EQ ## reduce eval(input()) times, starting with Q ## the reduce lambda has G as the previous value and H as the next .OG ## arithmetic mean of last pair @*FG2 ## geometric mean of last pair, uses *F to get the product of the list ## and @...2 to get the square root of that , ## join the two means into a two element list ``` [Answer] # Minkolang v0.14, 23 bytes Try it [here](http://play.starmaninnovations.com/minkolang/?code=%24n[%24d%2B2%24%3Ar*1Mi2%25%3F!r]%24N.&input=24%206%202)! ``` $n[$d+2$:r*1Mi2%?!r]$N. $n C get all input C [ ] C pop N; repeat inner N times C $d C duplicate stack [1,2] => [1,2,1,2] C + C add top two elements C 2$: C divide by two C r C reverse stack (get the other two) C * C multiply them together C 1M C take square root C i2%?!r C reverse the stack if an odd step number C $N C output stack 1M C take square root C i C get step in for loop C ``` [Answer] # Pyth, 15 bytes ``` u,^*FG.5csG2vzQ ``` [Answer] # Python 3, ~~65~~ 55 bytes Thanks to mathmandan for pointing out a shorter version using the `lambda` operator. ``` f=lambda a,b,n:f((a+b)/2,(a*b)**.5,n-1)if n else(a,b) ``` ## My original version: ``` def f(a,b,n): if n:f((a+b)/2,(a*b)**.5,n-1) else:print(a,b) ``` To my chagrin, a recursive function (a la the JavaScript and C++ answers) was shorter than a simple for loop. [Answer] # R, 66 bytes ``` f=function(a,b,n){while(n){x=(a+b)/2;b=(a*b)^.5;n=n-1;a=x};c(a,b)} ``` Usage: ``` > f(24,6,0) [1] 24 6 > f(24,6,1) [1] 15 12 > f(24,6,2) [1] 13.50000 13.41641 > f(24,6,3) [1] 13.45820 13.45814 > f(24,6,4) [1] 13.45817 13.45817 > f(100,50,10) [1] 72.83955 72.83955 > f(1,1.41421356237,10) [1] 1.19814 1.19814 ``` [Answer] # Mathematica, ~~31~~ 30 bytes Saved one byte thanks to Martin Büttner. ``` {+##/2,(1##)^.5}&@@#&~Nest~##& ``` Usage: ``` In[1]:= {+##/2,(1##)^.5}&@@#&~Nest~##&[{24, 6}, 5] Out[1]= {13.4582, 13.4582} ``` [Answer] # Lua, 62 bytes ``` n,a,b=...for i=1,n do a,b=(a+b)/2,math.sqrt(a*b)end print(a,b) ``` Uses command line arguments from `...` to assign to `n`, `a` and `b`, a nifty trick I learned about Lua recently. [Answer] ## Haskell, 40 bytes ``` (!!).iterate(\(a,b)->((a+b)/2,sqrt$a*b)) ``` An anonymous function. Example usage: ``` >> let f=(!!).iterate(\(a,b)->((a+b)/2,sqrt$a*b)) in f (1.0,1.41421356237) 10 (1.198140234734168,1.1981402347341683) ``` The lambda function `(\(a,b)->((a+b)/2,sqrt$a*b))` takes the arithmetic and geometric mean on a tuple. This is iterated starting with the first input (a tuple), and then `(!!)` indexes the second input to specify the number of iterations. [Answer] # Perl, 60 bytes ``` perl -ape'F=($F[0]/2+$F[1]/2,sqrt$F[0]*$F[1])for 1..shift@F;$_="@F"' ``` **N.B.:** Per [this meta post](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), I *believe* I've got the scoring correct. The actual code (between single quotes) is 58 characters, then I added +2 for `a` and `p` flags as that's the difference from the shortest invocation, `perl -e'...'` ### Vague complaints I have this nagging feeling I'm missing an obvious improvement. I know, "welcome to code golf", but I mean *more than usual* I believe there's an easy opportunity to shorten this. Early on, I had messed around with using `$\` as the second term with some success, but the above approach ended up being 2 bytes shorter, even with the extra `ap` flags required. Similarly, avoiding the explicit `$_` assignment would be nice, but the loop makes that difficult. The `shift@F` bugs me, too; if I don't do it that way, though (or use `@F=(0,...,...)` instead, which doesn't save any bytes), there's an off-by-one error with the `@F` assignment. ### Example ``` echo 5 24 6 | perl -ape'F=($F[0]/2+$F[1]/2,sqrt$F[0]*$F[1])for 1..shift@F;$_="@F"' ``` ### Outputs ``` 13.4581714817256 13.4581714817256 ``` [Answer] # Julia, 49 bytes ``` (a,b,n)->(for i=1:n;a,b=(a+b)/2,√(a*b)end;(a,b)) ``` Pretty direct iterative algorithm. Using the`√` symbol and the multiple return saves a few bytes, but the for loop syntax costs a few. [Answer] # Haskell, 47 Bytes ``` f a b 0=(a,b) f a b n=f((a+b)/2)(sqrt$a*b)(n-1) ``` [Answer] # Julia, 42 bytes ``` f(a,b,n)=n>0?f((a+b)/2,(a*b)^.5,n-1):(a,b) ``` This is a recursive function `f` that accepts three numbers and returns a tuple. Ungolfed: ``` function f(a::Real, b::Real, n::Integer) if n > 0 # Recurse on the arithmetic and geometric means, decrementing n return f((a + b) / 2, sqrt(a * b), n - 1) else # Return the pair return (a, b) end end ``` [Answer] # LabVIEW, 21 LabVIEW Primitives Primitives counted as per [this meta post](http://meta.codegolf.stackexchange.com/a/7589/39490). [![](https://i.stack.imgur.com/cbTT4.gif)](https://i.stack.imgur.com/cbTT4.gif) pretty staightforward not much to explain. [Answer] # Python 2, 62 61 62 bytes ``` def f(a,b,n): while n:a,b=(a+b)/2.,(a*b)**.5;n-=1 print a,b ``` [Answer] # CJam, 16 bytes ``` {{_:+2/\:*mq]}*} ``` This is an anonymous function. The input is a list with the two values (as doubles), followed by the iteration count. [Try it online](http://cjam.aditsu.net/#code=q~%0A%7B%7B_%3A%2B2%2F%5C%3A*mq%5D%7D*%7D%0A~%60&input=%5B24.0%206.0%5D%202) with I/O code for testing. I wouldn't normally have posted this because @PeterTaylor posted an equally long CJam answer before I saw the question. But since this is advertised as the start of a series, I wanted to keep my options open in case the series is interesting. While the length is the same as Peter's answer, the code is not. I chose a different input format by taking the two values in a list, where Peter used separate values. So while there's not much to it with either input format, the code looks quite different. ``` { Start loop over number of iterations. _ Copy the current pair of values. :+ Reduce pair with + operator. 2/ Divide by 2. \ Swap second copy of pair to top. :* Reduce pair with * operator. mq Calculate square root. ] Wrap the two new values in a list for next iteration. }* End iteration loop. ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 66 bytes Uses newtons method to approximate the square root in 15 steps ``` iii>:?v~naon; *&f:?v\1-@:&$:@$:@+2,@ $@:$@//,2+,@: 4{~$~/\@@1-21.0 ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaWlpPjo/dn5uYW9uO1xuKiZmOj92XFwxLUA6JiQ6QCQ6QCsyLEBcbiRAOiRALy8sMissQDpcbjR7fiR+L1xcQEAxLTIxLjAiLCJpbnB1dCI6IjEwMCA1MCAxMCIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6Im51bWJlcnMifQ==) [![enter image description here](https://i.stack.imgur.com/FSiff.png)](https://i.stack.imgur.com/FSiff.png) [Answer] # [Scala](http://www.scala-lang.org/), 58 bytes Golfed version. [Try it online!](https://tio.run/##fZHPa4MwFMfv/hWP0kOyZc5Y7UBQKOziYewwdioenpq0Dhc3kw2K9G93qbYdrJ2B5MH7ft7P6AJr7Jv8TRQG0lI0SkDnfGMNMgKSKsPgsfnKa3GyFOIEXkxbqQ3E0BPFkOU0TipJVOJR@95xRvA2p/c@e0KzdfVnawje5JSKWgvQszmyeT7rAUoh4R0rRbDd6AhWbYu79Zg7oxG8qsrYGp0D9hxaMkKbArXQ1jvAZJDgGLlSu4x4DPygZLAsKbtU@aTqT6rhdGZbmHue1UPvf8DK3A144PNFuPQXDyUdQOoM5jyfK5tWYLGF7uyzaz/m/LD7MbUi8jT9byDxqIs6VdqgKsSzXNsPzNglxv9g49deI/3r5BGkY/t753D3/Q8) ``` (n,a,b)=>if(n>0)f(n-1,(a+b)/2,Math.sqrt(a*b))else s"$a,$b" ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` {[m;pƭ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSU1QjI0JTNCNiU1RCUyMDUmY29kZT0lN0IlNUJtJTNCcCVDNiVBRCZmb290ZXI9JmlucHV0PSZmbGFncz0=) Takes input [on the stack](https://codegolf.meta.stackexchange.com/a/22106/114446). This default was [+11/-5](https://i.stack.imgur.com/uu1bk.png) at the time of posting ([Wayback Machine](https://web.archive.org/web/20230605031557/https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?page=3&tab=scoredesc)). #### Explanation ``` {[m;pƭ # Implicit input { # First input no. times: [ ; # Parallelly apply: m # Arithmetic mean pƭ # Square root of product # Implicit output ``` ]
[Question] [ # Task Write a polyglot in two languages that when run, outputs the name of the language it is run in. Additionally, this program must *also* output the **other** language's name if the source code is reversed # Example: Program `ABC` in language `foo` outputs `foo`. `ABC` in language `bar` outputs `bar`. `CBA` in language `foo` outputs `bar`, and `CBA` in language `bar` outputs `foo`. This is code-golf, so the shortest code wins [Answer] # JavaScript, HTML, 68 bytes | | HTML | JavaScript | | --- | --- | --- | | Normal | ``` <!---->HTML<!--!<tpircSavaJ>-- alert`JavaScript`//`LMTH`trela <!--!< ``` | ``` <!---->HTML<!--!<tpircSavaJ>-- alert`JavaScript`//`LMTH`trela <!--!< ``` | | Reversed | ``` <!--!< alert`HTML`//`tpircSavaJ`trela -->JavaScript<!--!<LMTH>----!< ``` | ``` <!--!< alert`HTML`//`tpircSavaJ`trela -->JavaScript<!--!<LMTH>----!< ``` | JavaScript is a strange language that support 5 kinds of comment and 5 kinds of link breaks. Comment: * Multi line comment `/* ... */` [Ref](https://tc39.es/ecma262/#prod-MultiLineComment) * Single line comment `// ...` [Ref](https://tc39.es/ecma262/#prod-SingleLineComment) * Hashbang comment `#! ...` [Ref](https://tc39.es/ecma262/#prod-HashbangComment) + Must at the beginning of source code + Some script host support an extra BOM in front of hashbang * Single line HTML open comment `<!-- ...` [Ref](https://tc39.es/ecma262/#prod-annexB-SingleLineHTMLOpenComment) * Single line HTML close comment `--> ...` [Ref](https://tc39.es/ecma262/#prod-annexB-HTMLCloseComment) Line breaks: [Ref](https://tc39.es/ecma262/#prod-LineTerminatorSequence) * `<LF>` * `<CR>` * `<LS>` * `<PS>` * `<CR>` `<LF>` [Answer] # Python + ><>, 49 bytes ``` #o<"><>" print("python")#)"><>"(tnirp "nohtyp"<o# ``` **Try it**: * [Python](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3DZXzbZTsbOyUuAqKMvNKNJQg8kqayppgYY2SvMyiAi6lvPyMksoCJZt8ZYhGqH6YOQA) * [Python Reversed](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3DZXzbZQgYkpcBUWZeSUaSnY2dkqayppKefkZJZUFSholeZlFBVxgYZt8ZYhGqH6YOQA) * [><>](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiI288XCI+PD5cIlxucHJpbnQoXCJweXRob25cIikjKVwiPjw+XCIodG5pcnBcblwibm9odHlwXCI8byMiLCJpbnB1dCI6IiIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6ImNoYXJzIn0=) * [><> Reversed](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiI288XCJweXRob25cIlxucHJpbnQoXCI+PD5cIikjKVwibm9odHlwXCIodG5pcnBcblwiPjw+XCI8byMiLCJpbnB1dCI6IiIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6ImNoYXJzIn0=) [Answer] # Java and [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 175 bytes ``` v->"Java"//"ecapsetihW">-vSSTTN SSTTTN SSTTSTN SSSTSTSN SSSTTSTN SSTTN SSSTTTSN SSSTTN SSSTSN SSTTTTTN N SSN SSSTTSSTTSN TSSSTN SSN SN N N N SN SSN TSSSTN SSSSSTTSSSN SSN N STTSTTSSN TSSSN STTSTSSSN TSSS ``` Above, the spaces, tabs, and newlines are indicated with `S`; `T`; and `N` respectively for readability only. The TIO-links below contain the actual spaces/tabs/newlines. * [Try it online in Java.](https://tio.run/##PVBBCsIwEDwnrxh6ag@tDxD7AMFeBD2Ih5hGTa2xmDQg4tvrpokGsrszs7sw2wkvyq69TbIX1mIjtHlzQBunnmchFZoAga17anOBzHcP3cIXS2I/nIJ1wmmJBgaryZd1tqaN2WKRKSkGq5y@7rO69ABjPIQYERIoYc4Rs0iyHxlb4hQhKlJz@JyFeuY4vSD9qdQ1c3zezpIaERKalmHpMJ56cpCM@ODvTmfIo@XDURTpBC/r1L16jK4aSHG5qWRuxr4v0jU@0xc) * [Try it online in Whitespace.](https://tio.run/##PYzBDcAgCEXPOAXhbtzAAbpAz8aY6M1EY8enIrQk8PmPr09ts4yecmFePtKVVqIQqOTUR5mt3hT9QgRwMnSiCG7Bo@pBIXxQI/pqu71YWNqB7Ie5XXL6kaUOc@d3sKs6NMf8Ag) * [Try it reversed in Java.](https://tio.run/##RZDBbsIwEETP668Y5ZQcEj4AkQ@oVC5IcKh6MCYtTo2JsGOpqvj2sJsY6sPK82ZkebbXSdf96WcyToeAd239nwKsj93tS5sOW5HALt6s/4Yp91d7QqrWTO@KR4g6WoMtPDYTB0niBCKorGhRfJsJyXNQlF3FDnvqH0liTglTJEfuM8mc6KUUPcOUI1hwnkCq2@JwtrELAxcqVquCO78VbZ2mtfxqGI@OG@QiSfpdeA3lUvnjU1d5Bb8hdpfmOsZmYCeWvjGlH52r8jbu0wM) * [Try it reversed in Whitespace.](https://tio.run/##RY5BDoAgEAPP3Vc03Ak/4AF@wDMxJHoz0eDzkYUVe2i20x722Y87X2facq0kIWoEKJYwUrs6AVUCa6U1rZMf6aKvlAlUendiHJhJ8I1hEw5sThYf3TqfdCG4VNLioi@1vg) **Explanation:** *In Java:* ``` v-> // Method with empty unused parameter & String return-type "Java" // Return "Java" //"ecapsetihW">-v // No-op comment // No-op spaces/tabs/newlines ``` *In Java reversed:* ``` // No-op spaces/tabs/newlines v-> // Method with empty unused parameter & String return-type "Whitespace" // Return "Whitespace" //"avaJ">-v // No-op comment ``` *In Whitespace:* ``` v->"Java"//"ecapsetihW">-v // No-ops SSTTN // Push -1 (e) SSTTTN // Push -3 (c) SSTTSTN // Push -5 (a) SSSTSTSN // Push 10 (p) SSSTTSTN // Push 13 (s) SSTTN // Push -1 (e) SSSTTTSN // Push 14 (t) SSSTTN // Push 3 (i) SSSTSN // Push 2 (h) SSTTTTTN // Push -15 (W) NSSN // Create Label LOOP SSSTTSSTTSN // Push 102 TSSS // Add the top two integers together // (which will implicitly stop the program with an error if // there is just a single value on the stack) TNSS // Print the top as character to STDOUT NSNN // Jump to Label LOOP NNSNSSNTSSSTNSSSSSTTSSSNSSNNSTTSTTSSNTSSSNSTTSTSSSNTSSS // No-op whitespaces ``` *In Whitespace reversed:* ``` SSSTN // Push 1 (a) SSSTSTTSN // Push 22 (v) SSSTN // Push 1 (a) SSTTSTTSN // Push -22 (J) NSSN // Create Label LOOP SSSTTSSSSSN // Push 96 TSSS // Add the top two integers together // (which will implicitly stop the program with an error if // there is just a single value on the stack) TNSS // Print the top as character to STDOUT NSNN // Jump to Label LOOP NNSNSSNTSSSTNSTTSSTTSSSNSSNNTTTTTSSNSTSSSNTTSSSNSTTTSSSNTTSSNTSTTSSSNSTSTSSSNTSTTSSNTTTSSNTTSS // No-op whitespaces v->"Whitespace"//"avaJ">-v // No-ops ``` The constants `102` and `96` are generated by [this Java program](https://tio.run/##fVLda9swEH/vX3Hck4xSk8H2UDuitNCBYemgTrdBKUN21USdI3vSORBG/nZXrj/ibKMvkri734fu7kXu5PnL06@myQvpHCylNn/OAKo6K3QOjiT5a1fqJ9j6FEvJarN@eAQZtGUAXQCscnVBIEA@zB/jt4w2BG4ri0K5NpEYUmtlw@XVj5/frr7c38wgERfxlGSovhvIELv81/vVzV30XFrWkmqRxHrx4dM81pz3No5GBOKMZpUYsAAtLtuTgizqbIZrRdc@4Fgwwr3fZ2CZEDqAvDSkTa063XisIOHlV@X3jfbYSubqWhtp950yy851EE/YGIXqdy0Lx6qpDHiLNrSqKjzBZ20dsWpWcUxvU5zgD6AKp@AUR9xOKsZXJWgID0Evb8NCmTVtWACLsbUTI/90e8I9mduR5phOfFyfSnZnunektmFZU1j5plBhGHZwgXwg5Rj7GSJPOEIEyN9rahL0sn8zs1P7b1WHM3/0K9uvw3vc7S6ZviE7af14MU2RMyPE/BIxMgt/rTDCcTDDBubRsM1UnlC22WApaRPKzDETBP9bNeIiX3y8uPS8keePJ/2zimprfAXeYvejQ9M0R/@v) based on [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) and [Y](https://github.com/ConorOBrien-Foxx/Y), 15 bytes ``` "Y"gxg"E1BA50"R ``` * [Try it online in 05AB1E.](https://tio.run/##yy9OTMpM/f9fKVIpvSJdydXQydHUQCno/38A) * [Try it online in Y](http://conorobrien-foxx.github.io/Y/) (you'll have to copy-paste `"Y"gxg"E1BA50"R` into the Code-block, and click on the 'timeout run'-button). * [Try it reversed in 05AB1E.](https://tio.run/##yy9OTMpM/f8/SMnA1NHJ0FUpvSJdKVLp/38A) * [Try it reversed in Y](http://conorobrien-foxx.github.io/Y/) (again, by copy-pasting `R"05AB1E"gxg"Y"` manually). **Explanation:** *In 05AB1E:* ``` "Y" # Push string "Y" # STACK: "Y" g # Pop and push its length # STACK: 1 x # Double it (without popping) # STACK: 1,2 g # Pop and push its length # STACK: 1,1 "E1BA50" # Push string "E1BA50" # STACK: 1,1,"E1BA50" R # Reverse it # STACK: 1,1,"05AB1E" # (after which the top of the stack is output implicitly) ``` *In 05AB1E reversed:* ``` R # Reverse (without input, it'll push an empty string) # STACK: "" "05AB1E" # Push string "05AB1E" # STACK: "","05AB1E" g # Pop and push its length # STACK: "",6 x # Double it (without popping) # STACK: "",6,12 g # Pop and push its length # STACK: "",6,2 "Y" # Push string "Y" # STACK: "",6,2,"Y" # (after which the top of the stack is output implicitly) ``` *In Y:* ``` "Y" # Push string "Y" g # Pop and print it x # Stop the program g"E1BA50"R # No-ops ``` *In Y reversed:* ``` R # No-op character "05AB1E" # Push string "05AB1E" g # Pop and print it x # Stop the program g"Y" # No-ops ``` [Answer] # Python + Javascript(Node.js) 150 bytes Uses the differences between javascript objects and python dicts to change code passed to `eval` in both languages. Uses both quoting styles with escaping to evaluate different code when reversed ``` "'\",)]'0'[}')'\nohtyP'\(gol.elosnoc':0,')'\tpircsavaJ'\(tnirp':'0'{(lave,'",eval({"0":"print(\"Python\")",0:"console.log(\"Javascript\")"}["0"]),'\"' ``` [Python normal](https://ato.pxeger.com/run?1=NY69CsMgFEbf5S5XwQbH4iNkyh4ziNhEEBW1gRDyGl26ZGnfqW9T05_5cL7v3J9xKVPw-_64lsvp_LoBSmB0QI79hhSlD1NZOpRkDK4xLmQfNArODlaiTTqrWbWVF29TRFHFlTg1G4bAzKwcWYGDgJisL0RC9_mTQIFxATr4HJxpXBgra-tU1snGcvCtr-JAWQ3Cb90v8h_7Bg) [Javascript normal](https://ato.pxeger.com/run?1=Nc4xCsMgFMbxu7zlRbDBsXiETNljBrE2CYhP1AZCyDW6dMnQHqq3qaHt_Of7-D2eni5231-3fD2d33dABZz1KLDbkKHyNOalRVUN5GrrKHkyKAU_Wg5TNEnPuik9-ykGlGW4Vk7PliNwO2tXrSBAQoiTz5WCdskjeQUMuJBgyCdytnY0lNaUq2TiFPLRt64Me8YLCL-6H_KP_QA) [Python reversed](https://ato.pxeger.com/run?1=Nc49CsMgGMbxu7zLq2CDY_EImbLHDCI2EURFbSCEXKNLlyztnXqbmn7Mf56H3_0ZlzIFv--Pa7mczq8bgkRGB-DQb0BBlmiTzmpWLUgyBtcYF7IPGgRnR_dhKktXW_E2RRB1uBKnZsMAmZmVIytyFBiT9YVIbOtV1snGIpEi4wJ18Dk407gw1t59PEfb-jocKKsg-Op-yD_2DQ) [Javascript reversed](https://ato.pxeger.com/run?1=Nc4xCsMgFMbxu7zlRbDBsXiETNljBrE2CYhP1AZCyDW6dMnQHqq3qaHt_Of7-D2eni5231-3fD2d33cEhZz1IKDbgIHKYYom6Vk3oKqBXG0dJU8GpOBH9zTmpS0t-ykGkGW4Vk7PlgNyO2tXrShQYoiTz5XCplwlE6eQFTLkQqIhn8jZ2tFQervkkfzRtq4Me8YLCL66H_KP_QA) [Answer] # C/C++, 119 bytes ``` #include<stdio.h>// int main(){puts(sizeof!0-1?"C":"C++");}//};)"++C+0\C0"+0!foezis(stup{)(niam tni //>h.oidts<edulcni# ``` [Try it online!](https://tio.run/##ZY5Bi8IwFITv/RXPCNISNqk9aqmHsnvdP@AlptE@qEkwL3to199e210F0cMwwzB8zEGFdtSKoCw/v7@gWgs9LtHqLjamDNSgE20lZYKW4KzQptngI4U0YG/ccZF/rHesZhtWc86y7VXK6zZjnNc839c54/ni6EyP056iH7LUojoDWUykrFrhsKFQmiZ22uJynA4k2sN0YZb3yUn/JVitQEglXKRH5f1zSep/9wsX8wMVFELPoMlm3UHFO6h4AY03 "Bash – Try It Online") [Reference](https://stackoverflow.com/a/12894970/6023984) Old: C/C++, 167 bytes ``` #include<stdio.h>// int main(){puts("C"// #ifdef __cplusplus// "++"// #endif// );}//};) //fidne# //"++" //sulpsulpc__ fednfi# //"C"(stup{)(niam tni //>h.oidts<edulcni# ``` [Try it online!](https://tio.run/##ZYzLCsIwEEX3/YqhBW0REuxW6cYPKTEPO1Cng0ncqN9ek6ogurjcy5nhHJUfZquHCdZzhaTHaOzeB4OTGDopC6QAZ4VUNzeOwdfloUy0Qmesg77XPEafk2C52Sw3SwZdGs3uIeVj1xRSOjRkqzTyTyofR87RfQ/OGnK4HA9l7UPkW1MTqjMEwkS7QUxogt9bE0dNWM1r6GArdKE5Vw5zcdLLgtUKhFRiiuGDmL9hUK@/O1zsNYnalyhVzlvU/ovaH9H8BA "Bash – Try It Online") ~~Not that elegant due to `#ifdef` but resolving it also save bytes~~ done [Answer] # [PHP](https://php.net/) [Perl 4 or 5](https://www.perl.org/), ~~45~~ ~~43~~ 41 bytes ``` print-true?php:perl;#;php:lrep?eurt-tnirp ``` [Try it online PHP](https://tio.run/##K8go@G9jXwAkC4oy80p0S4pKU0Fcq4LUohxrZWsQM6cotcA@tbQIKJuXWQRVqaAUkxeTF@Qa5hoU7OpiFZOnZM2FbARQuxVQM9AIkHYQE9kIAA "PHP – Try It Online") [Try it online Perl](https://tio.run/##K0gtyjH5/7@gKDOvRLekqDTVviCjwKoAKGqtbA1i5hSlFtinlhYBZfMyiwogKhWUYvJi8oJcw1yDgl1drGLylKy5kI0AarcCagYaAdIOYiIbAQA "Perl 4 – Try It Online") A simple take at it, I assumed it was not mandatory to specify the Perl version as it is not a polyglot between different versions of perl (though I could do one). Works in Perl 4 or 5 Takes advantage of the fact that PHP converts `true` to `1` for numerical operations while Perl 4/5 ignores it EDIT: saved 2 bytes by removing `1`, `-true` is enough (with swaped languages names) EDIT 2: thanks to Neil for saving another 2 bytes removing the spaces [Answer] # C and Python, ~~163~~ 119 bytes ``` p=0//1;print("Python")#//# #define p;main(){puts("C");}//# p #//};)"nohtyP"(stup{)(niam;p enifed# #//#)"C"(tnirp;1//0=p ``` [Try it online!](https://tio.run/##dU69DoIwEN77FJc2wXbA6lxxMbrK7k/SAIYOlAscCQZ4diwOxkGHG777fnPblnNmCXa74/kEe0hnTDZabw02zpPk6ZPK2nMltBZM5MXD@QLQVNZ5qQbsqJX8wJWZFh5ZkE1GcV@X9Ey5bKnDQUnvbGUQCu8eRS4WkVDBJcm7Bs1W602Cc@hnbJmSwgj4rv3ALIO4DwdRBGtt13VHjJENnwbiFlb9dbzc@9vq2/uP/pE1vwA "Dash – Try It Online") --- ###### `warning`-less & C`99` compliant version, 235 bytes ``` #include<stdio.h>//# #define p int main(void){puts("C");}//# #if 0//fidne# print("Python");p=0//1#//# #endif//0 fi# p #if 0//fidne# #//#1//0=p;)"C"(tnirp #endif//0 fi# #//};)"nohtyP"(stup{)diov(niam tni p enifed# #//>h.oidts<edulcni# ``` [Try it online!](https://tio.run/##nZBPa4NAEMXv@ykGhUQPugk9haiX0l7jrYf@gcVdccCMi47BkOSz24mHUgK99LALO@/3Zt6sNUMzV4Yhy14Or1BAOasQqWpH67KBLXZpU2gdqtC6GsmBBySGo0GKTh3a@OJHHqLgOYj3t4XDGjZa12jJhcr3QkdBeeamI0F8Lto2XEBHFmutN1CjgA/GO7IVMff7WJpHTNj7B48wN1Gpa/hcBtHAo7/EkvgUEZojiEXSOsLa2QUumlQS85A5O7YVSYdZdlbqvn4JV/BLyp9nVUEiP5BXux0khydI3kzbyu0m7g0k3llDjAJNcmC1glSbtBtZKTZS6cUN6@nj@v41fa5/D/hL/u/A@Rs "Dash – Try It Online") Turns out, since C99, `main()` does implicitly [`return 0`](https://port70.net/%7Ensz/c/c99/n1256.html#5.1.2.2.3) which indicates [successful termination](https://port70.net/%7Ensz/c/c99/n1256.html#7.20.4.3p5). A single `#` (with optional whitespaces and/or comments after it) followed by a new line is also allowed; The standard calls it ["Null directive"](https://port70.net/%7Ensz/c/c99/n1256.html#6.10.7). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/) + [JavaScript (Node.js)](https://nodejs.org), 95 bytes ``` 1//print("Python")#1//)"nohtyP"(gol.elosnoc console.log("JavaScript")//1#)"tpircSavaJ"(tnirp//1 ``` [Try it online! (Python)](https://tio.run/##jY69CoNADMf3e4ojLt6gIl2K0BfoJDhKB7mGVpDLkUtFn96ethbcuiX/j/ziZ3mSO509L5bueGEAWMqi8Nw7SaHebDBJlAw4espcQ/qgIceBgiOrLLlAA@YDPVK4dmPXWO69gCmKMjEgvmfbRPkKqbiefZSXyGjLKitvSn05WZbplV/pOIFRwrOulNYfe3XMb9vC9JI9qzVOaL8hnCx62apdCIf7jCNywPveWyFHRlutT/1F2qNH3vIG "Python 3.8 (pre-release) – Try It Online") ``` 1//print("Python")#1//)"nohtyP"(gol.elosnoc console.log("JavaScript")//1#)"tpircSavaJ"(tnirp//1 ``` [Try it online! (JavaScript)](https://tio.run/##jY/LCoMwEEX3foWMmww0EbeFrrrrSvAHlBg0EjIhSQW/3sY@oGIX3QzDmcvhztTNXZBeu8gt9WqVaeSXvF2rsnRe28igXuJIFrBICMHSGJca2EBGKEPBkswk2UBGCUMDg1syNk8jYFlWBUJ02ssm4RuwaLV3Ca@tCEZLxaoTrzDbKzjn@VbknKcNcHfcOB7jdI@ftJo7845lXs3KB9VfX29tVARndHoLULyvDMVE2m7oKP4YfnX5tv/RaRdfHw "JavaScript (Node.js) – Try It Online") The python programs error after printing [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) and [Fission](https://github.com/C0deH4cker/Fission), 35 bytes ``` [dc]P[;"cd"R"Fission";][[P]noissiF[ ``` [Try it online! `dc` in dc.](https://tio.run/##S0n@/z86JTk2INpaKTlFKUjJLbO4ODM/T8k6Njo6IDYvH8R1i/7/HwA) [Try it online! `Fission` in Fission.](https://tio.run/##S8ssLs7Mz/v/PzolOTYg2lopOUUpSMkNIqpkHRsdHRCblw/iukX//w8A) [Try it online! `Fission` in dc reversed.](https://tio.run/##S0n@/z/aLbO4ODM/LzYgOjrWWikvH8R1UwpSSklWso4OiE1Oif7/HwA) [Try it online! `dc` in Fission reversed.](https://tio.run/##S8ssLs7Mz/v/P9oNwooNiI6OtVbKywdx3ZSClFKSlayjA2KTU6L//wcA) ## Explanations ### dc → `dc` ``` [dc]P[;"cd"R"Fission";][[P]noissiF[ [dc] push the string "dc" P print without newline [;"cd"R"Fission";] push the string (psuedo comment) [ push the rest of the program as string (ditto) ``` ### Fission → `Fission` ``` [dc]P[;"cd"R"Fission";][[P]noissiF[ R start an atom going right "Fission" print "Fission" and set the atom's mass to 7 ; destroy the atom ``` ### dc reversed → `Fission` ``` [Fission]P[[];"noissiF"R"dc";[P]cd[ [ ] push the string "Fission" P print without newline [ push the rest of the program as string (psuedo comment) note that dc's [strings] nest and also doesn't complain with an unterminated string ``` ### Fission reversed → `dc` ``` [Fission]P[[];"noissiF"R"dc";[P]cd[ R start an atom going right "dc" print "dc" and set the atom's mass to 2 ; destroy the atom ``` [Answer] # Minecraft Function and C, 243 bytes ``` #include <stdio.h>//a fednu# #define w int main(){printf("C");}//a fednu# w #undef a//>h.oidts< edulcni# #undef a//};)"noitcnuF tfarceniM"(ftnirp{)(niam tni w enifed# #if 0//fidne# tellraw @a "Minecraft Function"# #"C" a@ warllet #endif//0 fi# ``` The C code is hidden behind preprocessor directives, which are interpreted as comments in the Minecraft function. The Minecraft code is hidden with `#if 0` and `#endif` which is completely skipped by the compiler. The code is written symmetrically with appropriate comments to comment out the reversed version. `#undef a//` (a comment in Minecraft and a no-op in C) is used to hide the reversed code. The `w`, which is interpreted in C as `int main(){printf("C");}`, is also a valid Minecraft command. It has the wrong number of arguments, which causes a silent error, but the rest of the function still runs. Try It Online: * [C](https://tio.run/##TY6xDsIwDET3foWVLO0AYQchJCQ2PsJKbLAUXJQ66oD49uKR8XT37i7vHjlvWxTNtReC02JF5v3znBICU9Eeh1iIRQlWEDV4oeg4fd7NBY/hGqbj9y@8DrGrA4ApnZ/7WYotJ6DSa1aJf@b3OAWdxbL2Gxhjy6RyDyObSnt/plEFX@DCd93xeqeF4ZASS1GKg1GtDVe4IIS7H8wN2eDWNZvMGjzu7wAvsGKrlWyIpEU4pQOwxG37AQ) * [C Reversed](https://tio.run/##TY6xDsIwDET3foWVLO0AYQchJCQ2PsJKbLAUXJQ66oD49uKR8XT37i7vHjlvWxSGQ0osRSkORrU2XOGCEK4hDjHoLJa138AYWyaVewC8wIqtVrIhkhbhlA7A4vFCLEqwgqjBC0XH6fNuLngMd3dyQza4dc0ms4bp@E0Jgalod1o0114ITosVmffP85@5DrGr1wOm9D1O/m5kU2nvzzSq4Atc@K4fdCD@hc/P/SzFlhNQ6TWrxG37AQ) (Minecraft Function not available on TIO) [Answer] # Python, JavaScript (Node.js), 107 bytes ``` 00000000: 2321 2f2f e280 a863 6f6e 736f 6c65 2e6c #!//...console.l 00000010: 6f67 2822 4a61 7661 5363 7269 7074 2229 og("JavaScript") 00000020: 2f2f 2922 6e6f 6874 7950 2228 676f 6c2e //)"nohtyP"(gol. 00000030: 656c 6f73 6e6f 63e2 80a8 3b60 230a 7072 elosnoc...;`#.pr 00000040: 696e 7428 2250 7974 686f 6e22 2923 2922 int("Python")#)" 00000050: 7470 6972 6353 6176 614a 2228 746e 6972 tpircSavaJ"(tnir 00000060: 700a 2360 e280 a82f 2f21 23 p.#`...//!# ``` No TIO link available... All you need is comment out whatever you don't want... [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) + [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes ``` "‛₴ŀ,Q,`E1BA50``"i0"laxyV"}"05AB1E"0i0` ``` [Vyxal code](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJcIuKAm+KCtMWALFEsYEUxQkE1MGBgXCJpMFwibGF4eVZcIn1cIjA1QUIxRVwiMGkwYCIsIiIsIiJd) [Vyxal code reversed](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJgMGkwXCJFMUJBNTBcIn1cIlZ5eGFsXCIwaVwiYGAwNUFCMUVgLFEsxYDigrTigJtcIiIsIiIsIiJd) [05AB1E code](https://tio.run/##yy9OTMpM/f9f6VHD7EdNW4426ATqJLgaOjmaGiQkKGUaKOUkVlSGKdUqGZg6Ohm6KhlkGiT8/w8A "05AB1E – Try It Online") [05AB1E code reversed](https://tio.run/##yy9OTMpM/f8/wSDTQMnV0MnR1ECpVimssiIxR8kgUykhwcDU0cnQNUEnUOdow6OmLY8aZiv9/w8A "05AB1E – Try It Online") [Answer] # [Clip](https://esolangs.org/wiki/Clip) and [Fission](https://github.com/C0deH4cker/Fission), 18 bytes ``` "Clip";"noissiF"L+ ``` [Try it online in Fission!](https://tio.run/##S8ssLs7Mz/v/X8k5J7NAyVopLx8k4qbko/3/PwA "Fission – Try It Online") [Try it online in Fission reversed!](https://tio.run/##S8ssLs7Mz/v/X9tHyQ3CVrJWKsjMcVb6/x8A "Fission – Try It Online") No online link for Clip. In Clip, most things after the first entity and its parameters recursively don't matter. (Some operators also wait for input, but not in this case.) Strings takes no parameters. `L` is an empty list. `+` is for concatenation. In Fission, `L` emits an atom to the left and `;` destroys the atom. Strings in double quotes on the path of the atom are printed. It wraps around on the edges like most 2D languages. # [GolfScript](http://www.golfscript.com/golfscript/) and [Fission](https://github.com/C0deH4cker/Fission), 25 bytes ``` "GolfScript"K}K"noissiF"L ``` [Try it online in GolfScript!](https://tio.run/##S8/PSStOLsosKPn/X8kdyAkGc5S8a72V8vIzi4sz3ZR8/v8HAA "GolfScript – Try It Online") [Try it online in Fission!](https://tio.run/##S8ssLs7Mz/v/X8k9PyctOLkos6BEybvWWykvHyTjpuTz/z8A "Fission – Try It Online") [Try it online in GolfScript reversed!](https://tio.run/##S8/PSStOLsosKPn/30fJLbO4ODM/T8m71luppCCzKDk4LSffXen/fwA "GolfScript – Try It Online") [Try it online in Fission reversed!](https://tio.run/##S8ssLs7Mz/v/30fJDcJU8q71ViopyCxKDk7LyXdX@v8fAA "Fission – Try It Online") In GolfScript, `K` is a no-op and `}` is a super comment. In Fission, `K` works like `;` but also does something else that doesn't matter. Using `;` here would break GolfScript. ]
[Question] [ You want to make a string where the (**1-indexed**) character at index `n` is `n`. When `n` is less than 10, this is easy: `"123456789"`. When `n` is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: `"020406081012"`. Now the index of the end of each *substring* `n` is `n`. This can be generalized for any `d`-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number: ``` Index: ... * 97 98 99*100 101 102*103 ... * * * *---+---+---*---+---+---*---+ Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ... *---+---+---*---+---+---*---+ ``` If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings. The given integer will always be positive and **divisible by its length** (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length. Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. ## Test cases ``` 1 => 1 9 => 123456789 10 => 0204060810 105 => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105 1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004 ``` [Answer] # C, 64 bytes ``` l,i;main(n){for(scanf("%d%n",&n,&l);i<n;)printf("%0*d",l,i+=l);} ``` Takes a single integer as input on stdin. [Answer] ## JavaScript (ES6), 83 bytes ``` n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${+`1e${l}`+l*++i}`.slice(1)).join`` ``` Yes, that's a nested template string. 79 bytes in ES7: ``` n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${10**l+l*++i}`.slice(1)).join`` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` VRUmLDUz0ZFU ``` I/O is in form of digit arrays. [Try it online!](http://jelly.tryitonline.net/#code=VlJVbUxEVXowWkZV&input=&args=WzEsIDAsIDVd) or [verify all test cases](http://jelly.tryitonline.net/#code=VlJVbUxEVXowWkZVCkTDh-KCrGrigbc&input=&args=MSwgOSwgMTAsIDEwNSwgMTAwNA). ### How it works ``` VRUmLDUz0ZFU Main link. Argument: A (digit array) V Eval; turn the digits in A into an integer n. R Range; yield [1, ..., n]. U Upend; reverse to yield [n, ..., 1]. L Yield the length (l) of A. m Modular; keep every l-th integer in A. D Decimal; convert each kept integer into the array of its digits. U Upend; reverse the digits of each integer. z0 Zip/transpose with fill value 0. Z Zip again. This right-pads all digit arrays with zeroes. F Flatten the resulting 2D array. U Upend/reverse it. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes ``` VntG3$:10YA!1e ``` [**Try it online!**](http://matl.tryitonline.net/#code=Vm50RzMkOjEwWUEhMWU&input=MTA1) ``` V % Implicitly input number, n. Convert to string n % Length of that string, s t % Duplicate s G % Push n again 3$: % 3-input range (s,s,n): generates [s, 2*s, ... ] up to <=n 10YA % Convert each number to base 10. This gives a 2D array of char, with each % number on a row, left-padded with zeros if needed !1e % Reshape into a string, reading in row-major order. Implicitly display ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes Code: ``` LD¹gÖÏvy0¹g×0ñ? ``` Explanation: ``` L # Get the array [1, ..., input]. D # Duplicate this array. ¹g # Get the length of the first input. Ö # Check if it's divisible by input length. Ï # Keep those elements. vy # For each... ¹g # Get the length of the first input. 0 × # String multiply that with "0". 0ñ # Merge with the number. ? # Pop and print without a newline. ``` The merging is done like this: From these: ``` 000 12 ``` It results into this: ``` 012 ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TETCuWfDlsOPdnkwwrlnw5cww7E_&input=MTA1). [Answer] # Python 2, ~~78~~ ~~70~~ ~~68~~ ~~64~~ 63 bytes Actually basing on the idea of Destructible Watermelon makes it even smaller (using `input` is even better)(filling the string backward saves 4 bytes)(no `()` at `while`): ``` n,s=input(),'' l=len(`n`) while n:s=`n`.zfill(l)+s;n-=l print s ``` Here is the old 70 byte approach (Saving 8 bytes by using backquotes instead of `str` and dropping the square brackets around generator thanks to Dennis): ``` def f(n):l=len(`n`);print"".join(`x`.zfill(l)for x in range(l,n+l,l)) ``` [Answer] # Python 2, 63 bytes ``` def f(n):l=len(`n`);print'%%0%dd'%l*(n/l)%tuple(range(l,n+1,l)) ``` Test it on [Ideone](http://ideone.com/eUup3m). [Answer] # JavaScript (ES6), 66 Recursive, input `n` as a string (not a number) and limiting the output string size to 2GB (that is above the string limit of most javascript engines) ``` f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l)) ``` **Test** ``` f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l)) function test() { var v=I.value; Alert.textContent=v % v.length ? 'Warning: input value is not divisible by its string length':'\n'; Result.textContent=f(v); } test() ``` ``` <input type=number id=I value=105 oninput='test()' max=500000> <pre id=Alert></pre> <pre id=Result></pre> ``` [Answer] # R, ~~66~~ ~~64~~ 62 bytes edit: `x=nchar(n<-scan());paste0(str_pad(1:(n/x)*x,x,,0),collapse="")` first golf attempt... [Answer] # [2sable](https://github.com/Adriandmen/2sable), 13 bytes Code: ``` g©÷F®N>*0®×0ñ ``` Uses the **CP-1252** encoding. [Answer] # Python ~~3~~ 2, ~~79~~ ~~74~~ ~~69~~ ~~65~~ ~~68~~ 67 bytes Thanks Dennis! ``` def f(n):i=l=len(`n`);s='';exec n/l*"s+=`i`.zfill(l);i+=l;";print s ``` byte count increase from bad output method [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~53~~ ~~45~~ ~~42~~ ~~37~~ 28 bytes ``` ~~lB,?ybeN:B%0,N:ef:{,"0":"9"y:?m.}acAl:Br-:"0"rjb:Acw\~~ ~~lB,?ybeN:B%0,10:B^:N+:ef:{,"0":"9"y:?m.}acbw\~~ ~~lB,?ybeN:B%0,10:B^:N+:ef:{:16+:@Prm.}acbw\~~ ~~lB,?ybeN:B%0,10:B^:N+:efbe:16+:@Prmw\~~ lB,?ybeN:B%0,10:B^:N+:efbew\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=bEIsP3liZU46QiUwLDEwOkJeOk4rOmVmYmV3XA&input=MTA1) [Answer] # Bash, ~~31~~ 22 bytes ``` seq -ws '' ${#1}{,} $1 ``` Test it on [Ideone](http://ideone.com/pSwn21). *Thanks to @izabera for golfing off 6 bytes!* [Answer] # Ruby, ~~52~~ 48 + `n` flag = 49 bytes ``` ((l= ~/$/)..$_.to_i).step(l){|j|$><<"%0#{l}d"%j} ``` [Answer] # zsh, 28 bytes ``` printf %0$#1d {$#1..$1..$#1} ``` # zsh + seq, ~~21~~20 bytes This is pretty much the same answer as Dennis but in 20 bytes because zsh ``` seq -ws '' $#1{,} $1 ``` [Answer] # Haskell, 51 bytes ``` f n|k<-length$show n=[k,2*k..n]>>=tail.show.(+10^k) ``` [Answer] ## Perl, 40 bytes **39 bytes code + 1 for `-n`.** ``` $}=y///c;printf"%0$}d",$i+=$}while$i<$_ ``` ### Usage ``` echo -n 9 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_' 123456789 echo -n 10 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_' 0204060810 echo -n 102 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_' 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102 echo -n 1000 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_' 0004000800120016002000240028003200360040004400480052005600600064006800720076008000840088009200960100010401080112011601200124012801320136014001440148015201560160016401680172017601800184018801920196020002040208021202160220022402280232023602400244024802520256026002640268027202760280028402880292029603000304030803120316032003240328033203360340034403480352035603600364036803720376038003840388039203960400040404080412041604200424042804320436044004440448045204560460046404680472047604800484048804920496050005040508051205160520052405280532053605400544054805520556056005640568057205760580058405880592059606000604060806120616062006240628063206360640064406480652065606600664066806720676068006840688069206960700070407080712071607200724072807320736074007440748075207560760076407680772077607800784078807920796080008040808081208160820082408280832083608400844084808520856086008640868087208760880088408880892089609000904090809120916092009240928093209360940094409480952095609600964096809720976098009840988099209961000 ``` [Answer] # k4, 27 ``` {,/"0"^(-c)$$c*1+!_x%c:#$x} ``` Not really golfed at all, just a straight-forward implementation of the spec. ``` $ / string # / count c: / assign to c x% / divide x by _ / floor ! / range (0-based) 1+ / convert to 1-based c* / multiply by count $ / string (-c) / negative count $ / pad (negative width -> right-aligned) "0"^ / fill blanks with zeros ,/ / raze (list of string -> string) ``` [Answer] # Javascript - 76 ``` n=>eval('c="";for(a=b=(""+n).length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)') ``` or **71** if allowing for string arguments: ``` n=>eval('c="";for(a=b=n.length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)') ``` Thanks to @user81655! Ungolfed: ``` function x(n) { c = "", a = b = (""+n).length; while(a<=n) { c=c+"0".repeat(b-(""+a).length)+a a+=b; } return c; } ``` much place for improvement, but i'm tired right now [Answer] # R, ~~149~~ ~~142~~ 138 bytes ``` x=rep(0,n);a=strtoi;b=nchar;for(i in 1:(n=scan()))if(!i%%b(a(n)))x[i:(i-b(a(i))+1)]=strsplit(paste(a(i)),"")[[1]][b(a(i)):1];cat(x,sep="") ``` Leaving `nchar` in the code gives a program with the same number of bytes than replacing it with `b`, but having random letters wandering around in the code makes it more... *mysterious* **Ungolfed :** Each `nchar(strtoi(something))` permits to compute the number of numerals in a given number. ``` n=scan() #Takes the integer x=rep(0,n) #Creates a vector of the length of this integer, full of zeros for(i in 1:n) if(!i%%b(strtoi(n))) #Divisibility check x[i:(i-nchar(as.integer(i))+1)]=strsplit(paste(a(i)),"")[[1]][nchar(as.integer(i)):1]; #This part replace the zeros from a given position (the index that is divisible) by the numerals of this position, backward. cat(x,sep="") ``` The `strsplit` function outputs a list of vectors containing the splitten elements. That's why you have to reach the `1`st element of the list, and then the `i`th element of the vector, writing `strsplit[[1]][i]` [Answer] # [SQF](https://community.bistudio.com/wiki/SQF_syntax) - 164 Using the function-as-a-file format: ``` #define Q String"" l=(ceil log _this)+1;s='';for[{a=l},{a<=_this},{a=a+l}]do{c=([a]joinQ)splitQ;reverse c;c=(c+['0'])select[0,l];reverse c;s=format[s+'%1',c joinQ]} ``` Call as `INTEGER call NAME_OF_COMPILED_FUNCTION` [Answer] # PowerShell, 77 bytes ``` $x="$($args[0])";$l=$x.Length;-join(1..($x/$l)|%{"$($_*$l)".PadLeft($l,'0')}) ``` Uses string interpolation to shorten string casts. The parts before the second semicolon shorten the names of reused things. Then, every integer up to the input - and only those that are multiples of the input's length - are padded to be as long as the input string and finally joined into one. [Answer] ## Actually, 30 bytes ``` ;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H ``` [Try it online!](http://actually.tryitonline.net/#code=O-KVnVLilZskbDspKkAjIiUwe31kImbilZdgI-KVnCVgTc6j4pWbQEg&input=MTI) I'm not happy with the length of this code, but I'm not sure that it can be made much shorter (if at all). Explanation: ``` ;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H ;╝ duplicate input, push a copy to reg1 R range(1, input+1) ╛$l push input from reg1, stringify, length ;) duplicate and move copy to bottom of stack * multiply range by length of input @# swap range with length, make length a 1-element list "%0{}d"f "%0{}d".format(length) (old-style Python format string for zero-padding integers to length of input) ╗ save format string in reg0 `#╜%`M for each value in range: # make it a 1-element list ╜% format using the format string Σ concatenate ╛@H take only the first (input) characters in the resulting string ``` [Answer] # CJam, 19 bytes ``` q_,:V\i,%{V+sV0e[}/ ``` [Try it online](http://cjam.aditsu.net/#code=q_%2C%3AV%5Ci%2C%25%7BV%2BsV0e%5B%7D%2F&input=105). No one has posted in CJam yet, so this is the script I used for the test cases. ## Explanation ``` q_,:V e# Store the length of the input as V \i, e# Push the range from 0 to the input % e# Keep only every V'th number in the array { e# Do this for each number: V+ e# Add V to get the right number of leading zeroes s e# Convert to string for left padding V e# Push V, the length to bring each string to, and... 0 e# The character to add to the left e[ e# Left pad }/ ``` [Answer] ## PHP, 83 78 bytes ``` <?$a=$argv[1];$i=$y=strlen($a);while($y<=$a){printf('%0'.$i.'d', $y);$y+=$i;} ``` Tips are more then welcome. Manage to golf it myself by one byte by changing it from a for loop to a while loop. This code assumes that this is being execute from the command line and that $argv[1] is the int. ## Thanks to: @AlexGittemeier His suggestion (see comments) golfed this by 5 bytes to 78 bytes. [Answer] ## Perl 6, ~~69~~ ~~59~~ 46 bytes ``` {my \a=.chars;(a,2*a...$_).fmt("%0"~a~"s","")} ``` ]
[Question] [ # File Permissions [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") *Adapted from the UIL - Computer Science Programming free response question "Carla" for 2018 District.* # Introduction In UNIX-like operating systems, each file, directory, or link is "owned" by a "user", who is a member of a "group", and has certain "permissions" represented by a ten-character string such as "drwxrwxrwx". The first character is 'd', '-', or 'l' (directory, file, or link), followed by three sets of "rwx" values, indicating "read, write, execute" permissions. The first set is the user's rights, the middle set the group's rights, and the third everyone else's rights to that object. Permission denied for any of these rights is represented by a '-' in place of the 'r', 'w', or 'x'. For example, a sample directory permission string would be "drwxr--r--", indicating full directory rights for the user, but "read-only" rights for the group member and all others. **Each "rwx" combination can also be represented by an octal value (0-7) with the most significant bit representing read permission, the next most significant bit representing write permission, and the least significant bit representing execute permission.** # Challenge Given a four-character code string made up of a character: 'D', 'F', or 'L', followed by a three-digit octal integer value, like 664, output the resulting 10 character string that represents the permission value indicated. # Input Your program or function may either read the input from standard in (four characters will be entered, optionally followed by a newline) or be passed the input as an argument. Your program may accept uppercase or lowercase inputs but must be consistent (either all inputs are uppercase or all inputs are lowercase). # Output Your program must print the resulting ten-character string that represents the permission value indicated in the exact format specified above. Tailing white space is allowed. # Test Cases In: `F664` Out: `-rw-rw-r--` In: `D775` Out: `drwxrwxr-x` In: `L334` Out: `l-wx-wxr--` In: `F530` Out: `-r-x-wx---` In: `D127` Out: `d--x-w-rwx` # Scoring and Rules * [Standard loop-holes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply. * Please provide a link to test your code as well as an explanation. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] ## bash, ~~59~~ 53 bytes ``` chmod ${1:1} a>a;stat -c%A a|sed s/./${1:0:1}/|tr f - ``` Right tool for the job? Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving 5 bytes and [HTNW](https://codegolf.stackexchange.com/users/50062/htnw) for saving one. [Try it online!](https://tio.run/##S0oszvj/PzkjNz9FQaXa0MqwViHRLtG6uCSxREE3WdVRIbGmODVFoVhfTx8kbQBUoF9TUqSQpqD7////NDMzEwA "Bash – Try It Online") ``` chmod ${1:1} a>a; # call chmod with the input with its first character removed # note that the redirection creates the file a *before* the # chmod is run, because of the way bash works stat -c%A a| # get the human readable access rights sed s/./${1:0:1}/ # replace the first character with the first char of input |tr f - # transliterate, replacing f with - ``` [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda a,*b:[a,'-'][a=='f']+''.join('-r'[x/4]+'-w-w'[x/2]+'-x'[x%2]for x in b) ``` Takes input as a character and three ints. [Try it online!](https://tio.run/##VYvLCsIwEEX3fkU2Mo1OfMTWgpAviVkklGBLTUooNH59nG6kcjaHw73TZ37FIItn6llG@3adZRYP7qEtggCjrVLgwRwBTkPsQwUigc7nmopYxLK6XD2T7aXxMbHM@sAcL1Pqw8x8RX@8EzXf/VIH2BLNJo2AN2K7omND6fJ/vKLElpcv "Python 2 – Try It Online") ### Explanation `[a,'-'][a=='f']` takes either the input character or `-`, if the character is `f`. `'-r'[x/4]+'-w-w'[x/2]+'-x'[x%2]` is essentially an octal conversion to get the `rwx` string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` “rwx“-”Œp⁺;Ṁ⁾f-yị@~ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yi8gogqfuoYe7RSQWPGndZP9zZ8KhxX5pu5cPd3Q51/x/u3nK4/VHTmsj//9PMzEy4UszNTblyjI1NuNJMjQ24UgyNzAE "Jelly – Try It Online") ### How it works ``` “rwx“-”Œp⁺;Ṁ⁾f-yị@~ Main link. Argument: s (string) “rwx“-” Set the return value to ["rwx, "-"]. Œp Take the Cartesian product, yielding ["r-", "w-", "x-"]. ⁺ Take the Cartesian product, yielding ["rwx", "rw-", "r-x", "r--", "-wx", "-w-", "--x", "---"]. ;Ṁ Append the maximum of s (the letter). ⁾f-y Translate 'f' to '-'. ~ Map bitwise NOT over s. This maps the letter to 0, because it cannot be cast to int, and each digit d to ~d = -(d+1). ị@ Retrieve the results from the array to the left at the indices calculated to the right. Indexing is modular and 1-based, so the letter from s is at index 0, "---" at index -1, ..., and "rwx" at index -8. ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-p`, 37 bytes ``` s/\d/(<{-,r}{-,w}{-,x}>)[$&]/ge;y;f;- ``` Takes input in lowercase. [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFX8OmWlenqBZIlIOIilo7zWgVtVj99FTrSus0a93//9PMzEy4UszNTblyjI1NuNJMjQ24UgyNzP/lF5Rk5ucV/9ctAAA "Perl 5 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes ``` \d $&r$&w$&x f|[0-3]r|[0145]w|[0246]x - \d ``` [Try it online!](https://tio.run/##K0otycxL/P8/JoVLRa1IRa1cRa2CK60m2kDXOLYISBmamMaWA2kjE7PYCi5dLqC6///TzMxMuFLMzU25coyNTbjSTI0NuFIMjcwB "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in lower case. Explanation: ``` \d $&r$&w$&x ``` Triplicate each digit, suffixing with `r`, `w` and `x`. ``` f|[0-3]r|[0145]w|[0246]x - ``` Change all the incorrect letters to `-`s. ``` \d ``` Delete any remaining digits. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 51 bytes ``` f - 0 --- 1 --x 2 -w- 3 -wx 4 r-- 5 r-x 6 rw- 7 rwx ``` [Try it online!](https://tio.run/##DctBCsAgDADB@/4loEbNewpWKJQepND83uYyh4Vd53s9R957IiREhBw6BfkEDZ3Kit5Cp7OiW@gx9V4ZZo1btTKbJkYu9gM "Retina – Try It Online") No idea how to use Retina, so please let me know how to do this better. I just figured I'd try to learn at least one language that isn't Pyth. ### Explanation: Replace `f` with `-` (leaving `d` and `l` unchanged), then replace each digit with the appropriate `rwx`. [Answer] # JavaScript (ES6), 63 bytes Expects the input string in lowercase. ``` s=>s.replace(/\d|f/g,c=>1/c?s[c&4]+s[c&2]+s[c&1]:'-',s='-xw-r') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yryi1ICcxOVVDPyalJk0/XSfZ1s5QP9m@ODpZzSRWG0QZQSjDWCt1XXWdYlt13Ypy3SJ1zf/J@XnF@Tmpejn56RppGkppZmYmSpqaXGjCKebmpliEc4yNsalOMzU2wGaIoZE5UPg/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` s => s.replace( // replace in the input string s /\d|f/g, c => // each character c which is either a digit or the letter 'f' 1 / c ? // if c is a digit: s[c & 4] + // append '-' or 'r' s[c & 2] + // append '-' or 'w' s[c & 1] // append '-' or 'x' : // else: '-', // just replace 'f' with '-' s = '-xw-r' // s holds the permission characters ) // end of replace() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` FS≡ιdιlιf¦-⭆rwx⎇§↨⁺⁸Iι²⊕λκ- ``` [Try it online!](https://tio.run/##bc@/CsIwEAbw3ac4Ml0gDgqi6KROHYSCvsCRpLYY03JJbUV89prin8nhlt8H38fpkljX5IahqBkw800bj5Erf0YpIXRV1CVgJeEx0RQsCCPWkKc8Jtx8zP2x4mdiKpIaW1Dr4hffGwdqUHDXCwUny574jtuYeWN73KUWzF0bcKVgT2Hslgrm6TKv2V6tj9agG/GiYByRaeaZHlkuZsP05l4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string F Loop over characters ι Current character ≡ Switch d Literal `d` ι Implicitly print current character l Literal `l` ι Implicitly print current character f Literal `f` ¦ (Separator between string literals) - Implicitly print literal `-` Implicit default case rwx Literal `rwx` ⭆ Map over characters ι Input character I Cast to integer ⁸ Literal 8 ⁺ Sum ² Literal 2 ↨ Base conversion λ Inner index ⊕ Incremented § Index into base conversion κ Inner character - Literal `-` ⎇ Ternary Implicitly print ``` [Answer] # [Haskell](https://www.haskell.org/), ~~84~~ ~~83~~ 81 bytes ``` f 'f'='-' f y=y t#n=f t:((\x->["-r"!!div x 4,"-w-w"!!div x 2,"-x"!!mod x 2])=<<n) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P01BPU3dVl1XnStNodK2kqtEOc82TaHESkMjpkLXLlpJt0hJUTEls0yhQsFER0m3XLcczjcC8iuAvNz8FBAvVtPWxiZP839uYmaegq1CSj6XAgQUlJYElxT55KkAbVKONtMx0zGJxZRLAcqZ65jrmGKRywHKGesYY9UHMtMUKGeAw0xDHSMd89j/AA "Haskell – Try It Online") Ended up being pretty similar in concept to Mnemonic's Python 2 answer. f creates the file type, the rest is the gets permissions from the octal number. This one really made me wish & was a bitwise and operator included in prelude. [Answer] # Java 8, 100 bytes ``` s->s.replaceAll("(\\d)","$1r$1w$1x").replaceAll("f|[0-3]r|[0145]w|[0246]x","-").replaceAll("\\d","") ``` [Try it online.](https://tio.run/##hU/JbsIwEL3zFSMrh1hqIky2AwKJD4ALR8jBdRLkYExkm02Qbw/T1pdWqiLNaLY38960/MqjtjoOQnFrYc2lfk4ApHa1abioYfNVAmydkfoAIvSJpXPs9@ho1nEnBWxAwwIGGy1tbOpO4fpKqZCE@31FyQcJmAnYLWB3Qn/Nm9duGiWlwcDSrLxhnKV5eceV6A8UL2GX0GH@w9xdPhUyewHXs6zghC94lbuSUy//YV19is8XF3c4cUqHOhZInecpod@//A@qiiIbBakkGb/UZMl0nI7NCg/qJ/3wBg) Port of [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/163713/52210). **Explanation:** ``` s-> // Method with String as both parameter and return-type s.replaceAll("(\\d)","$1r$1w$1x") // Replace every digit `d` with 'drdwdx' .replaceAll("f // Replace every "f", |[0-3]r // every "0r", "1r", "2r", "3r", |[0145]w // every "0w", "1w", "4w", "5w", |[0246]x", // and every "0x", "2x", "4x", "6x" "-") // with a "-" .replaceAll("\\d","") // Remove any remaining digits ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ ``` A full program printing to STDOUT. (As a monadic link the return value is a list containing a character and a list of three lists of characters.) **[Try it online!](https://tio.run/##y0rNyan8///hjkWPGvel6VaenOzv9HDn6kdNa0wSHzXMKSqveNQwNx@IdR/uXPv///8Uc3NTAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjkWPGvel6VaenOzv9HDn6kdNa0wSHzXMKSqveNQwNx@IdR/uXPv/4e4th9uBckf3OACZWUAWUI2Crp0CUEHk//9pZmYmXCnm5qZcOcbGJlxppsYGXCmGRuYA "Jelly – Try It Online"). ### How? ``` Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ | Main Link: list of characters Ḣ | head & pop (get the 1st character and modify the list) ⁾f- | list of characters = ['f', '-'] y | translate (replacing 'f' with '-'; leaving 'd' and 'l' unaffected) ɓ | (call that X) new dyadic chain: f(modified input; X) O | ordinals ('0'->48, '1'->59, ..., '7'->55 -- notably 32+16+value) B | convert to binary (vectorises) (getting three lists of six 1s and 0s) ṫ€4 | tail €ach from index 4 (getting the three least significant bits) “rwx” | list of characters ['r', 'w', 'x'] a | logical AND (vectorises) (1s become 'r', 'w', or 'x'; 0s unaffected) ”- | character '-' o | logical OR (vectorises) (replacing any 0s with '-'s) ṭ | tack (prepend the character X) | implicit print (smashes everything together) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, 37 bytes ``` s:g[\d]=[X~]('-'X <r w x>)[$/];s/f/-/ ``` [Try it online!](https://tio.run/##K0gtyjH7/7/YKj06JiXWNjqiLlZDXVc9QsGmSKFcocJOM1pFP9a6WD9NX1f///80MzMTrhRzc1OuHGNjE640U2MDrhRDI/N/@QUlmfl5xf91CwA "Perl 6 – Try It Online") Port of Dom Hastings' Perl 5 solution. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 bytes Inspired by [a comment](https://codegolf.stackexchange.com/questions/163691/file-permissions#comment396365_163694) from [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only). ``` \d ---$&* ---____ r-- --__ w- -_ x f - ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyaFS1dXV0VNC0TFAwFXka4uF4jJVQ6k47kquNK4dP//TzMzM@FKMTc35coxNjbhSjM1NuBKMTQyBwA "Retina – Try It Online") The idea is converting each digit to unary (the default unary digit in Retina is `_`) with three leading `-`, and then converting binary digits from the most to the least significant. [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` lambda s:("-"+s)[s[0]!="f"]+stat.filemode(int(s[1:],8))[1:] import stat ``` [Try it online!](https://tio.run/##VYtBCsMgFAX3OUX6V0raktQmlkBOYl1YzKeCRoluenoTNwVXD@bNhF/6@o1lXN7ZKvfRqo0zgRt0kYooenlZAEF2Mal0R2NX5/VKzJZIFMMsry9KyzbGBb@ntmg57OVHAjhNT6C0@QPN@VgBy1ht4Mj6Ohke/AT5AA "Python 3 – Try It Online") Python 3.3+ has a built-in for that, although due to the need for an import, and differences in expected input format, it is not very golf-friendly. [Answer] # [Tcl](http://tcl.tk/), 139 bytes ``` proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?"[expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]":$c==f?"-":$c}}] ""} ``` [Try it online!](https://tio.run/##XY69CsIwFEb3PMXlEtwE@w@FklfonmaQtJVKtCGpWAh59nip4OD0Hc5yvk2blKxbNfTgIdzX5QnSPK4WNEhvzbIB94CoIEy7dRCkm25EMAwjcK0EysNzfSoFOmzxjOqncoHvP5UJ3L8KW667bhbERDEqysR0tOkJm@u6ZGPTVMwURcnmqriwMcsbFiHY1@bpVzuA7GlVTB8 "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 144 bytes ``` proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?[list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]]:$c==f?"-":$c}}] ""} ``` [Try it online!](https://tio.run/##XY7NCsMgEAbvPsWySG@F5h8CwVfIXT0Uk5QU24haGhCf3UoKPfS0w3yHHa90SsZuCkZwEO7b@gSuH1cDCrgzevVAHSBKCPNuLARu51smEGICqiTjenUe@DFSdaoZWuzxjPKnSobvP1Uw3L9K9lQNw8IyZ4pR5l8xHQE5hyxtW5Op6xqiq6omS1NdyFSUHYkQzMu7HNcL4GO@MqYP "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 149 bytes ``` proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""} ``` [Try it online!](https://tio.run/##Xc5LCsMgEIDhvacYRLorNG8IBK@QvXFRTCwpthG1NCCe3Q4pdNHVMB8M8wdlcrZuUzCCh3jf1icI87haUCC8NWsA5oFSCXHVINxyW3YL0zQDU2hm9QEEksP9VHPqaE/PVP6o5PT9RwWn@5cSxAMjU8OgOVLPVEpJ4sOUjwpsIrptazJ3XUNMVdVEN9WFzEXZEby3r@CxsJ9AjDhlyh8 "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 150 bytes ``` proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {set v [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""} ``` [Try it online!](https://tio.run/##Xc5NCsIwEIbhfU4xhOBOsH8WCiVX6D7NQtJGKtGGJGoh5OxxqODC1cADw/cGZXK2blUwgId4W5cHCHO/WFAgvDVLAOaBUglx0SDcfJ03C@M4AVNofg7wAoHmEA41p4529Ejlj0pO339UcLp9KUHcMTLV95ojdUyllCQuprxnYBTR53NNprZtiKmqmuimOpGpKFuC//YZPCZ2I4gBr0z5Aw "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 180 bytes ``` proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {[set R regsub] (..)1 [$R (.)1(.) [$R 1(..) [$R -all 0 [format %03b $c] -] r\\1] \\1w\\2] \\1x} {expr {$c==f?"-":$c}}}] ""} ``` [Try it online!](https://tio.run/##HY9Bi8IwEIXv@RWPkoX1UGmsWhDEvyBekxxq2kiXuA1JRKHkt3dncxjm48G8eS8Zt64@zAZXRCw/8/QL6Z69h4GM3k0JPKKqNJbJQobxMX48lBrADWkyjgk3kBxfd43v7XYjIPmNaCNoCot/uVDdO4cG0s7h2Sd8Ne29@NQaQSmhyVi8ldoV@GQs9Cxg4eZ8tpeqrk7c5Jw15clrCUmRmT0e92zougNzbbtn9tA2bBC7jtG9f6VIBU4K8kpb5/UP "Tcl – Try It Online") **Still very ungolfed!** [Answer] # [Java (JDK 10)](http://jdk.java.net/), 118 bytes ``` s->{var r=s[0]=='f'?"-":""+s[0];var z="-xw r".split("");for(int i=0;++i<4;)r+=z[s[i]&4]+z[s[i]&2]+z[s[i]&1];return r;} ``` [Try it online!](https://tio.run/##VU/BbsIwDL3zFVYkRrvSiEEBiRCmadJuO3GseshawsJKWjkuGyC@PWsBTdrB8rPfs/28UwcV74ovb/Z1hQS7tuYNmZLrxuZkKssfRS8vlXPwroyFcw@gbj5Kk4MjRW06VKaAfcsFa0Jjt2kGCrcuvEoB3u57lvmnwjQb3kQr0NK7eHU@KASULh1lUg704JnFbMFY1DVEx50ki3@@ARl3dWkoYCwUusLAWAIjRyKKzDIRIUbylLrUZA9JFt3R@A89ZQI31KAFFBcvrr66JTcvQBtHi3@mAdZHR5s9rxridSsiHbB@4iBeQd/1LRteh4aguarr8hh0Fafqtf3xBVEdgzAMb3cuvS4u3uvZLPHFfD715WSSeD2djHzxNJ7/Ag "Java (JDK 10) – Try It Online") ## Credits * 13 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # Excel, 224 bytes ``` =IF(LEFT(A1,1)="f","-",LEFT(A1,1))&CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,3,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,4,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx") ``` Done in 4 stages: ``` IF(LEFT(A1,1)="f","-",LEFT(A1,1)) Replace "f" with "-". ``` And 3 times: ``` CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx") ``` Trying to be smarter, adds `25 bytes` per set of rights, 75 in total: ``` IF(INT(MID(A1,2,1))>3,"r","-")&IF(MOD(MID(A1,2,1),4)>1,"w","-")&IF(ISODD(MID(A1,2,1)),"x","-") ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ 27 bytes ``` ćls8βbvyi…rwx3*Nèë'-}J'f'-: ``` [Try it online!](https://tio.run/##MzBNTDJM/f//SHtOscW5TUlllZmPGpYVlVcYa/kdXnF4tbpurZd6mrqu1f//bmZmJgA "05AB1E – Try It Online") Golfed down 7 bytes by [@MagicOctopusUrn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn) --- ``` ć # Remove head from string. ls # Lowercase swap. 8βb # Octal convert to binary. vy # For each... i ë } …rwx3*Nè # If true, push the correct index of rwx. '- # Else push '-'. J # Repeatedly join stack inside the loop. 'f'-: # Repeatedly replace 'f' with '-' inside the loop. ``` [Answer] # [Python 2](https://docs.python.org/2/), 238 bytes ``` lambda m,r=str.replace,s=str.split,j="".join,b=bin,i=int,z=str.zfill,g=lambda h,y:y if int(h)else "-":r(m[0],"f","-")+j(j([g(z(s(b(i(x)),"b")[1],3)[0],"r"),g(z(s(b(i(x)),"b")[1],3)[1],"w"),g(z(s(b(i(x)),"b")[1],3)[2],"x")])for x in m[1:]) ``` [Try it online!](https://tio.run/##fc7NCsIwEATgVwl72sW1@IMIhTxJLdJoY1PSNiQR2758jcWrXgYGPoZxU2yG/rBoIcVlsVWn7pXo2MsQfeZrZ6tbzWFtwVkTuZUAWTuYnpVUKY00feR5FbM21vJDfmcanvJJGC2SwIZqG2oBW8g9dsWuZNDAqdKmxRaLB84YUKHBkYhBARX7ko@0Sg/EP0FKeP0DhwRGoJL04MWY3oiu2OclLc5/nmn01etqeveMSETL/Xw@vQE "Python 2 – Try It Online") I had assumed this would be a drop in the bucket, but I was wrong indeed. Probably should have realized that a lambda wasn't the best idea at some point. [Answer] # APL+WIN, 55 bytes Prompts for input string with leading character lower case: ``` ('dl-'['dlf'⍳↑t]),⎕av[46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75] ``` Explanation: ``` 9⍴69 74 75 create a vector of ascii character codes for rwx -46, index origin 1 1↓t←⎕ prompt for input and drop first character ,⍉(3⍴2)⊤⍎¨⍕ create a 9 element vector by concatenating the binary representation for each digit 46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75 multiply the two vectors and add 46 ⎕av[.....] convert back from ascii code to characters, 46 being '-' ('dl-'['dlf'⍳↑t]), append first character from input swapping '-' for 'f' ``` [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` lambda a,*b,k='-xw-r':f'{a}-'[a=='f']+''.join(k[x&4]+k[x&2]+k[x&1]for x in b) ``` [Try it online!](https://tio.run/##XYvNCgIhFEb3PYWrrjbXaP4aCHySyYUySDaTDjKQET27GUFUnMUHh@/Mt@XkXZ0MEcc0qYseFFG40TgK4PHKAxwM3NWDQ6@EAAOyANievXV07OO6kcVrqveU0vhAIrGOaJbmYN1CDc0R7jMNY6uPGwC7TPvtJsA68/PLbZvd7q8tscKOsfQE "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 57 52 bytes 5 bytes saved thanks to FrownyFrog! ``` -&.('-DLld'i.{.),[:,('-',:'rwx'){"0 1&.|:~1#:@}."."0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ddX0NNR1XXxyUtQz9ar1NHWirXSAAuo6VupF5RXqmtVKBgqGano1VnWGylYOtXpKekoG/zW5uFKTM/IV0hTU3czMTNThPBdzc1MEz8fYGEnOzdTYAEmloZG5@n8A "J – Try It Online") Yet another long solution... I don't know how to make `}` work in tacit verbs and that's why I used the much longer `{"0 1&.|:` for selection. ## Explanation: `@}.` Drop the first symbol and `,.&.":` convert the rest to a list of desimal digits `]:#:` convert each digit to a list of binary digits (and cap the fork) `('-',:'rwx')` creates a 2-row table and use 0 to select from its first row / 1 - from its second one ``` '-',:'rwx' --- rwx ``` `{"0 1&.|:~` uses the binary digits to select from the table above `[:,` flattens the result `('d-l'{~'DFL'i.{.)` formats the first symbol `,` appends the fisrt symbol to the list of permissions [Answer] # PHP, 68 bytes ``` <?=strtr(strtr($argn,[f=>_,___,__x,_w_,_wx,r__,r_x,rw_,rwx]),_,"-"); ``` translates `f` in lowercase input to underscore and every octal number to its `rwx` equivalent, using underscores instead of dashes (to save the need for quotes), then replaces the `_` with `-`. Run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/fc954b2f180b55b9c250179105dec22bf2e4cbef). [Answer] # [C (gcc)](https://gcc.gnu.org/), 109 104 bytes At least C can convert octal input.... :-) **Edit:** I realized that the size modifier wasn't strictly required, and that `putchar()` is shorter than `printf()` in this case! ``` f(a,b){char*s="-xwr";scanf("%c%o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;putchar(s[(1&b>>a)*(a%3+1)]));} ``` [Try it online!](https://tio.run/##PcrRCoIwFIDhe59iLJQdc1GESC3tpreILo7HloPawmkFYq@@6qbLn@8neSEKM2PpOjRntvN9Y9yirYIWmNUwUotd6ksuX8@OK09oteAxxY5nCWZJDeo@9L9JoCyWe9ymHpR23yw36i0l/t0fxSqpqwohFRiv5ys4AagpGNuzGxorHs40wMaIMS1ARVM4FHn@AQ "C (gcc) – Try It Online") Original: ``` f(a,b){char*s="-xwr";scanf("%c%3o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;printf("%c",s[(1&b>>a)*(a%3+1)]));} ``` [Try it online!](https://tio.run/##HcvRCoIwFIDhe59iLJQd2yIRkVraTW8RXRxny0Ft4rQCsVc36/KH71fiptS8Mlbdh/pKDr6vjds05awZ8gpG1WAX@4KK96uj0iu0mtFQhamjPEIeVSDbof8phiLfHnEfe5DaLVns5EcIlG1nbP@/KPdnlkRVWSLEDMN0ncAFQE7zIsgDjWVPZ2ogY0CIZiCDaT7lWfYF "C (gcc) – Try It Online") ]
[Question] [ **Background:** Take this input as an example: ``` 1 1 2 1 1 2 1 3 1 3 ``` If you look only at the first few digits, between `1 1 2` and `1 1 2 1 1 2 1`, this input appears to consist of the pattern `1 1 2` repeating indefinitely. This would make its period 3, as there are 3 numbers in the pattern. Given only the first number, the period appears to be 1, as only the number `1` is in the input. Given the first two numbers, it still appears to be the number `1` repeating, so the period does not change. **Task:** Given an array of numbers (or strings, or similar), determine the period of each prefix of the array, and return the unique ones. For example, the above input would have periods of: ``` 1 1 3 3 3 3 3 8 8 10 ``` Thus, the output would be: ``` 1 3 8 10 ``` **I/O:** Input should be an array of any set of a large number of different values. For example, numbers, strings, natural numbers, or pairs of integers. Booleans wouldn't be allowed, but chars/bytes would. Output can be any reasonable representation of the numbers, such as an array/list, or a string with the numbers joined by newlines. **Test cases:** ``` 1 -> 1 1 2 1 1 2 1 -> 1 2 3 1 1 2 1 1 2 1 -> 1 3 1 2 1 2 1 2 1 2 4 -> 1 2 9 1 2 3 4 1 2 3 1 2 1 -> 1 2 3 4 7 9 4 4 4 4 4 4 4 4 4 4 -> 1 ``` [Answer] # [J](http://jsoftware.com/), 23 bytes ``` 1+[:~.(i.~]{~#\|/i.@#)\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbWjrer0NDL16mKr65RjavQz9RyUNWP@a3KlJmfkK6QpGAKhEZw0BmGwlLo6RAVIzELBEGiiFR7VQIYtSBqhB1M5TM5IwRIma4SCTRQQSoyBPHNkhSABCI1iGMhWEyzwPwA "J – Try It Online") We do the heavy lifting of creating the periods using integers, and then use those to index into our input. Specifically... * `(...)\` For each prefix: + `#\|/i.@#` Create a table of indexes to represent the possible periods. An example should make this clear: ``` (#\|/i.@#) 1 1 2 3 1 1 2 3 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 1 2 0 1 2 0 1 0 1 2 3 0 1 2 3 0 1 2 3 4 0 1 2 0 1 2 3 4 5 0 1 0 1 2 3 4 5 6 0 0 1 2 3 4 5 6 7 ``` + `]{~` Pull these indexes from the input: ``` 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 2 1 1 1 1 2 3 1 1 2 3 <-- Input matches here, index 3. 1 1 2 3 1 1 1 2 1 1 2 3 1 1 1 1 1 1 2 3 1 1 2 1 1 1 2 3 1 1 2 3 ``` + `i.~` And find the index of the original input within this list. In this case, that index is `3`. * `[:~.` De-dup. * `1+` And add one. # original approach, 24 bytes ``` [:~.1+i.&1@(-:"1#$&><\)\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9Ay1M/XUDB00dK2UDJVV1OxsYjRj/mtypSZn5CukKRgCoRGcNAZhiBSIY6FgCDTLCr8yW5A0Qg@mcpickYIlTNYIBZsoIJQYA3nmyApBAhAaxTCQrSZY4H8A "J – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-pae) ``` ṁƤi$ƤQ ``` A monadic Link accepting a list that yields a list of the unique period lengths. **[Try it online!](https://tio.run/##y0rNyan8///hzsZjSzJVji0J/P8/2lBHAYiMUZEFGBkaxBKSBwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzsZjSzJVji0J/H@4/VHTmqOTHu6cAaQj//@PjjaM5dKJNtRRACIjMAllQIWNkGTgpAlC0hjIgwkbo2g2ActgRzjshBlhHMsVCwA "Jelly – Try It Online"). ### How? ``` ṁƤi$ƤQ - Link: list, A Ƥ - for each prefix (p in A): $ - last two links as a monad - f(p): Ƥ - for each prefix (x in p): ṁ - mould like (p) -> Z = list of copies of x each "extended" to the length of p i - first 1-indexed index (of p in Z) Q - de-duplicate ``` [Answer] # [R](https://www.r-project.org/), ~~88~~ ~~82~~ 81 bytes ``` unique(Map(function(i)Find(function(j)all(a[1:i]==a[1:j]),1:i),seq(a=a<-scan()))) ``` [Try it online!](https://tio.run/##XU5NC8IwDL37KwJeEsjAzp1ku3rz5k12KLOTjlG7dsWB@Ntnhx9zBpLHy3v5cGMNeQJ1MFWvrwYHgjv4SppFlwZYw1H5XpsL3Jy0VrkxGN0FhQdp8WvUtNfmPPOGZNuiPImdLotiwqYkjozYqw5lIfNkuoYUY3ysgmm177FGQTSTCgULTvldoxWWYsq/mdH/cMpbzviFnxWzwymLUd1MLzwB "R – Try It Online") Thanks to Giuseppe for fixing a mistake and -6 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ¹Ƥṁ€ẹƊṂ$ƤQ ``` [Try it online!](https://tio.run/##y0rNyan8///QzmNLHu5sfNS05uGunce6Hu5sUjm2JPD///@GOgpGOgrGOgomOgpwNoRhCAA "Jelly – Try It Online") ## Explanation ``` ¹Ƥṁ€ẹƊṂ$ƤQ Main Link [....].$ Group these two into one monad so Ƥ runs the whole link to its left [][].Ɗ Group these three into one monad so it accepts the link left argument as the right argument to ẹ instead of grouping ẹṂ into a dyad-monad monadic link Ƥ For each prefix of the list: let it be the "sublist": ¹Ƥ Map identity over prefixes; get all prefixes of the sublist ṁ€ Mold each prefix to the shape of the sublist; repeat elements until the two lists are the same length ẹ Find all indices of the original sublist in the list of looped prefixes; essentially, find all prefixes that work for the period Ṃ Take the minimum of these; this returns the period Q Deduplicate; find only unique potential periods ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 69 bytes ``` a=>a.flatMap(x=>(j=1/a.some(v=>v-a[++j],j=i++)+j)>p?(p=j,i):[],i=p=0) ``` [Try it online!](https://tio.run/##bZDfboMgFIfvfYpzVwiKczZZtubQq13uCaxJidUOgkCUmL29w1m3dBuEP/m@3zkhaDnJsRmUD5l1l3bucJYoJO@MDG/Skw8URGORSz66viUTiimTFWO6TjUqxijTVPgj8ahTRV@qOlXo8YHOARDOSQH/jUwAFNE9QgHr/stFViabu0@svrxV/6z9XfXzly8jXc@tx3f3aJ5iag9/5/a@Mw@D6gnlozcqkN3J7ijv458YQAFmw5m44WnBU7yG5p3kpwvLr6uwi2CWUnpIAu/c8CpjglQqhbami2ycHZ1puXFX0hG1JOdP "JavaScript (Node.js) – Try It Online") ``` a=>a.flatMap(x=> // for i := 1 to a.length do (j=1/a.some(v=>v-a[++j],j=i++)+j) // j := prefix size of repeating first i elements; >p?(p=j,i):[] // if j > p then p := j; add `i` to answer; endif; ,i=p=0) // endfor ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` ηε¼ηÅΔ¾∍Å?]>Ù ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3PZzWw/tObf9cOu5KYf2PeroPdxqH2t3eOb//9GGOgpAZAQm4QxjCBkLAA "05AB1E – Try It Online") **Commented:** ``` η # push all prefixes of the input ε ] # iterate over all prefixes: ¼ # increment the counter variable ηÅΔ ] # find the index of the first prefix of the prefix which satisifies: ¾∍ # if extended to the length of the outer prefix (value of the counter variable) Å? # this is a prefix of the (implicit) input # (and therefore equal to the outer prefix) > # increment the 0-based indices Ù # only keep unique ones ``` [Answer] # JavaScript (ES6), 73 bytes Returns a set. ``` a=>new Set(a.map((_,i)=>(g=m=>a.some((v,j)=>j<=i&&v^a[j%m])?g(-~m):m)``)) ``` [Try it online!](https://tio.run/##dczNCoJAEAfwe0@xl2QG/EBXiKK1h@golout4uK6kmK3Xn0TSZG04c8wDPMbyXveZs@y6ZxaP4TJmeEsqsWLXEUH3FW8AbjbJbIICqZYxN1WKwHQ23LYyTMrLau/8VjuVYKXApy3wpPCNEU0ma5bXQm30gXkEPvkfyWIxPOIv/s1NhkSjP07rAyhGypYwLmHSxWQ47ajw@Ek6Pxg4ejw6LDW4ei2M2nzAQ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array new Set( // build a set from the following array: a.map((_, i) => // for each value at position i in a[]: ( g = m => // g is a recursive function taking a modulo value m a.some((v, j) => // check if there's some element in a[]: j <= i && // that it is not located beyond the position i v ^ a[j % m] // and is not equal to the element at j modulo m ) ? // end of some(); if truthy: g(-~m) // recursive call with m + 1 : // else: m // return m )`` // initial call to g with m zero'ish ) // end of map() ) // end of Set() ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┼↓Φ:'ñ╪⌐ñ∟M╕LbN ``` [Run and debug it](https://staxlang.xyz/#c=%7C%5B%7Bc%7C%5B%7Bn%25%3Amn%3D%7Dj%25mu%0AJ&i=%5B1%5D%0A%5B1,+1,+2,+1,+1,+2,+1%5D%0A%5B1,+2,+1,+2,+1,+2,+1,+2,+4%5D%0A%5B1,+2,+3,+4,+1,+2,+3,+1,+2,+1%5D%0A%5B4,+4,+4,+4,+4,+4,+4,+4,+4,+4%5D&m=2) Output is as a string representing the codepoints of each period. Pretty printed with spaces for verification. ## Explanation ``` |[{c|[{n%:mn=}j%mu |[ prefixes of input { m map to c|[ dup and take prefixes { }j first element which satisfies: n%:m when extended to current iteration length n= equals the current iteration? % take the length u uniquify ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 14 bytes ``` {a₀{ġz₁=ᵐ!}l}ᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzrxUVND9ZGFVY@aGm2BAoq1OUDxGf//R0cbxupEG@ooAJERmIQyIKJGSBJw0gQuZwzkwESNkbWagCWwo9hYAA "Brachylog – Try It Online") *-4 because I remembered which zip I was using* ``` { }ᵘ Find every unique output from: a₀ for some prefix of the input, ġ split it into groups of the same length except the last can be shorter { !} with that length being the smallest possible for which z₁ the non-cycling zip of the groups =ᵐ contains only elements all elements of which are equal; l output the length. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 50 bytes ``` {∪{1⍳⍨⍵[⍴⍵]≡¨⍵}¨{L←⍴,⊃⌽⍵⋄L⍴¨⍵}¨{⍺,⍵}\¨{⍺,⍵}\⊂∘⍕¨⍵} ``` I'm fairly certain there's room for improvement, but it's just out of my reach, for the moment. ``` ∪ ⍝ list unique values 1⍳⍨ ⍝ get the index value of the first occurrence of 1 in the bit mask ⍵[⍴⍵]≡¨⍵ ⍝ create a bit mask by checking which padded strings match the last string in the expansion ¨ ⍝ for each list of padded strings L←⍴,⊃⌽⍵ ⍝ assign length of last string in expansion to L ⋄ ⍝ statement separator L⍴¨⍵ ⍝ for each string, reshape to length of longest string ¨ ⍝ for each list of strings {⍺,⍵}\¨{⍺,⍵}\ ⍝ expand twice. (A, B, C) -> (A, AB, ABC) -> ((A), (A, AB), (A, AB, ABC)) ⊂∘⍕¨⍵ ⍝ for each element, encode as string and enclose ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRx2rqg0f9W5@1LviUe/W6Ee9W4BU7KPOhYdA/NpDK6p9gMqAwjqPupof9ewFCj7qbvEBCsAVPOrdpQNixiCzH3U1PeqY8ah3KkQZ0DYFQy4gBkIjGAnmG6FgE6iYsYIJlIapNMGEILWGYGSEzAAKqycmqsOIJHVsXIiiJBBSBwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` nub.map(\x->[p|p<-[1..],and.zipWith(==)x$drop p x]!!0).inits import Data.List ``` [Try it online!](https://tio.run/##bY3PT4MwFMfv/BVvCckgoVXcEmNCOXnc3QPj8BiwvQjtC62RGP92sY5Ng9qmbfo@3x8ntM9N103UsxkcPKJDuSPrglbtJ/1SyR452o8iL/idM1GkUpYJ6lq@ET@RO0VKxWNYD4aBYSxXq9tYkiZnAyGWiVOPpFVtAoCIEhNnwjLq6EatxTrOwvzYuB3pxuOucVBgUpXKl8PQYC1fzVBbLyooOXfdgSm9kgfSLqyUagH996thSuG/JXKANEi9MYX5/sX8bBNc2VIx883F/XO2C/fDmW/8dH6vGd/pntx71Rb@7ovq49B2eLSTODB/Ag "Haskell – Try It Online") Implicit function, taking a list of integers as input and returning a list of integers as output. Not really satisfied with this answer, but I can't seem to avoid importing `Data.List`. ## How? ``` nub. -- remove duplicates from map(\x-> -- the list obtained replacing each x with [p|p<-[1..], -- the integer p>=1 and.zipWith(==)x$drop p x] -- such that x is periodic of period p !!0). -- take the smallest such p inits -- where x ranges over the prefixes of the input list ``` [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` def f(l):r=[];p=i=1;exec"while l[p:i]!=l[:i-p]:p+=1\ni+=1;r+=[p][p in r:]\n"*len(l);return r ``` [Try it online!](https://tio.run/##dYzBCgIhGITvPYXtSVs7uHlSfBLXUyn7g9jPj0v19ObSITaIYWZgPhh81eVeptZuMbHEszDkfLDowCkbn/E6PBbIkWWPBsLRZW/gjMHg6NRcoKel0XkMHhkURibMZTjlWPqVpVhX6mNDglJ54l7JSV6klp/eUgUhDjuu/u5f6x3V8kcbbW8 "Python 2 – Try It Online") This uses the fact that the periods of prefices are non-decreasing. Ungolfed a bit: ``` def f(l): r=[];p=i=1 for _ in l: # for each prefix of l (tracked by i) while l[p:i]!=l[:i-p]:p+=1 # find the next p s.t. removing a length p prefix or a length p suffix result in equal lists i+=1;r+=[p][p in r:] # then add p to the return value if its not already there return r ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~19 17~~ 21 bytes ``` 1+?{((#x)#',\x)?x}',\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLszLUtq/W0FCu0FRW14mp0LSvqAXSXFxpCoZAaAQnjUGYK81B0QAsZaxgoWAIZDroGKIrBfONULAJVMxYwQRKw1SaYIEKAJkhG1s=) Modeled after @Jonah's [J answer](https://codegolf.stackexchange.com/a/222912/98547). * `{...}',\` for each prefix of the (implicit) input... * `((#x)#',\x)` expand each prefix (of the current passed-in prefix) to the full length of that prefix (e.g., transform `1 1 2` from `(1;1 1;1 1 2)` into `(1 1 1;1 1 1;1 1 2)`) * `(...)?x` get the index of the first transformed prefix that matches the prefix itself * `1+?{...}` add one to the distinct indices [Answer] # Scala 3, 119 bytes ``` _.inits.toSeq.reverse.tail.map{a=>1.to(a.size).find(Seq.fill(a.size)(_)flatMap a.take zip a forall(_==_)).get}.distinct ``` [Try it in Scastie!](https://scastie.scala-lang.org/ERJ9KnBcTKKKxw9n3but7Q) This is annoyingly long. ``` _ //The input .inits //Iterator of all prefixes (biggest to smallest) .toSeq //Conver to Seq so we can do stuff to it .reverse //Reverse so the smallest prefixes are first .tail //Drop the first prefix, which is empty .map { a => //Map each prefix a to its possible period 1.to(a.size) //Range of possible possible periods .find( //Find an i such that Seq.fill(a.size)(_) //when you make a.size copies flatMap a.take //of the first i elements of a zip a //and zip those with a, dropping extra elements forall(_ == _) //they all equal the corresponding elements in a ).get //Unwrap the Option to get the possible period }.distinct //Remove duplicates ``` [Answer] # [Haskell](https://www.haskell.org/), ~~110~~ 133 bytes Sorry, got longer, fixed bug. ``` h v=l<$>(l v#v) 1#v=[1!v] n#v=(n-1)#v++[[i!v|i<-[2..n],n!v==r n(i!v)]!!0|notElem(n!v)$r n<$>(n-1)#v] r n=(n!).cycle (!)=take l=length ``` [Try it online!](https://tio.run/##bU7LqsIwEN3nKya0iwTHclO7NO7u0i8IWRQJt8HpKDYELvjvNVZEQRnmcc7MOczQT8dANM8DZEvbeqcIcpW1MFW2zsjsBZdJ8droKq9WzkWZr3G7dm3TsEeW2doLsCq09lL@XPmUfimMqmx0XTZ3z4faiwKLldTN4f9AQSipbeqPQZClwH9pmClOabIOBIAzHpeGLRpc6pP4QrX4nt2L3mCHj/523@FHfPFeNBvvxdhHtmN/3sP5EjlBDQXAAMu38w0 "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` W⁻⊕Eθ⌕E⊕λ……θ⊕μ⊕λ…θ⊕λυ⊞υ⌊ιIυ ``` [Try it online!](https://tio.run/##ZY69CsMwEIP3PoXHO3AHN2NGQ6FDIK9gXIMPzk7in5Q@vZvQoQkFDUL6BLLeJDsZbu3liZ2AgWLN8Ig2ueBicU8YzAyLFHeKX3/sGKXQb8tO@2mGn9v4IxYQzwEjnpbLf70DFVGMNXuoUmzHKNQAhNhfxkSxgDa5wMb0rSl129Wprl1X/gA "Charcoal – Try It Online") Link is to verbose version of code. Takes input by default as a character array, but it's also possible to feed it integer or string arrays by using JSON format. Explanation: ``` ⊕Eθ⌕E⊕λ……θ⊕μ⊕λ…θ⊕λ ``` Loop over all prefixes of prefixes, extending them to the original prefix and finding indices of the first prefix where this results in the original prefix, then adjusting to give the periods. ``` W⁻...υ ``` While the list of periods contains a value not in the deduplicated list... ``` ⊞υ⌊ι ``` ... push the smallest missing value to the deduplicated list. ``` Iυ ``` Output the deduplicated list. [Answer] # [Haskell](https://www.haskell.org/), ~~96 95~~ 92 bytes ``` import Data.List r=tail.inits f=nub.map(\p->[length x|x<-r p,and$zipWith(==)p$cycle x]!!0).r ``` [Try it online!](https://tio.run/##bUxNa8JAEL3vrxjBg8IkuMlCKbiePOq5h3QpWxuboZvtstlCFP97uiSmanWGeQ/ex1S6@SqN6Tqq3bcPsNZBpxtqAvMyaDIpWQoN20v7857W2s1eXbIqTGk/QwXtqV0mHhxq@zE9knuhUM2knLvp7rAzJbRqMlnMU9/VmixIiP3tGzhPNkCxB3Myy6RgAAVX2BNmyLHHUXggZXh94iLnKHDgq7zAu1VKdRweTbIC4IxDBhwG/OdFLWejd5sY/Pzcvpy4aT/3fh7Vgccff9@j8xRTAu73nPoF "Haskell – Try It Online") * saved 1 thanks to @Unrelated String r=tail.inits * all prefixes(excludes empty) f=nub.map(\p-> ... ).r * we map every prefix(.r`list`) by doing the job below and we return unique elements. [length x|x<-r p, .. ]!!0 * list of prefixes of the current prefix being tested (x<-r p), which satisfy condition below. We take the length and we return first element (shorter) and$zipWith(==)p$cycle x * True if difference of each elements of prefix and `possible period` is 0 [Answer] # [Ruby](https://www.ruby-lang.org/), ~~79~~ 75 bytes ``` ->x{(1..x.size).map{|i|(1..i).find{|j|i.times.all?{|k|x[k]==x[k%j]}}}.uniq} ``` Accepts an array (e.g. of strings or integers) and returns an array of ints. Previous code: ``` ->x{(1..x.size).map{|i|(1..i).find{|j|x[0...j].cycle.first(i)==x[0...i]}}.uniq} ``` [Try it online!](https://tio.run/##bVD9SoRAEP9/n2IQSoUcMA@iYO1BLglL5cbbW@1cwXJ9dhs9rax2mRn4fcHMuX15Hwv5NAZx13shYocNfeQ@ntK6t2QniHwsSGe9LS2hoVPeYKrUY2@PttsfEym5X5XJMAzYanobxhqKvRNCCLew9mgqB5takUmEMCCBFf@9IAYIxU/vL46xSGzTt3y0uL9rt3Hfz3zE6GWuGV/pzNyxagd//6JyeAXM09fDsyKdQ1aBVVYAkK5bcwNVa3jyjuqysecGsTvf1Lt@aMyZan8Vs2ieqxDciWKg4SPOTIJlRXpmQMolW@Q6E@Mn "Ruby – Try It Online") [Answer] # Java, 105 bytes ``` a->{var s=new java.util.TreeSet();int p=1,i=0;for(int c:a)s.add(p=a[i++%p]==c?p:a[0]==c?i-1:i);return s;} ``` [Try it online!](https://tio.run/##pY@xboMwEIb3PIWXSrYCViCZoE63bp3ohhiuYCJTYizbUEWIZ6eGEsTQpenpdD777v/0u4IO/Kr4HFX7UYsc5TUYg95ASNTvkIvl3Viw7ugaUaCrm@LEaiEvaYZAXwz52Z2ickDaWlHTspW5FY2kr0vzLKRNM2@zknB7RiUbwT/3HWhkmORfm/m75tztYBI7KVIs8AQ7xGWj8XTPIyCGQlFgxSAV@/2TyhjLX1QE6WHuhB9EgsSa21ZLZOJhvNuMV8PJzVh@pU1rqXJfsrXEJQWl6huezMye@2Ag5K8SL/QCb66PiJHLcK5L8xAk3HDWenoUdXTaO@T4D2OnmfN7rrRhN4zf) ]
[Question] [ This is the logo for [LAPACK, a widely used software library for numerical linear algebra](http://www.netlib.org/lapack/). [![enter image description here](https://i.stack.imgur.com/zpKoi.png)](https://i.stack.imgur.com/zpKoi.png) Your task is to print the logo (color and matrix brackets not required) as this exact string. Trailing newline is allowed. ``` L A P A C K L -A P -A C -K L A P A -C -K L -A P -A -C K L A -P -A C K L -A -P A C -K ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` print"L %sA %sP %sA %sC %sK\n"*6%tuple(' - - - --- -'+'- -'*3) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EyUdBtdgRiAOgtDMQe8fkKWmZqZaUFuSkaqgrgIAuGAJpXSCtrq0OZOuqaxlr/v8PAA "Python 2 – Try It Online") Kind-of a boring solution. Makes a string template for the output with slots to put in minuses, then inserts in hardcoded string of minuses and spaces for those slots. I didn't find a way to compress or generate this length-30 binary sequence shorter than hardcoding it. The only optimization the code uses is that the sequence ends in 3 copies of `'- -'`. The output includes a trailing newline which the challenge allows. The template could also use `%2s` in place of `%s` which would allow also putting in empty string for the spaces, but I don't see how to use this. [Answer] # Python 2, 91 bytes ``` i=0 for c in'LAPACK'*6:print' -'[chr(i+33)in'(*,12467;<@AD']*(c!='L')+c+'\n'*(c=='K'),;i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgCstv0ghWSEzT93HMcDR2Vtdy8yqoCgzr0RdQVc9OjmjSCNT29hYEyivoaVjaGRiZm5t4@Dooh6rpZGsaKvuo66pnaytHpOnDuTb2qp7q2vqWGdq2xr@/w8A "Python 2 – Try It Online") I know most previous answers already beat this, but it's my first golf and I quite enjoyed the result :-)! Edit: Thanks very much to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for ~~the tip with `'\n'*(c=='K')`~~ all the tips! [Answer] # x86-16 machine code, IBM PC DOS, ~~54~~ ~~48~~ 49 bytes **Binary:** ``` 00000000: b106 be25 01ad cd29 84e4 740e b020 cd29 ...%...)..t.. .) 00000010: d2ec 7302 b02d cd29 ebeb b00d cd29 b00a ..s..-.).....).. 00000020: cd29 e2de c34c 1541 0350 1641 0c43 194b .)...L.A.P.A.C.K 00000030: 00 . ``` Build and test using `xxd -r` on your favorite DOS VM. **Listing:** ``` B1 06 MOV CL, 6 ; loop 6 rows ROWLOOP: BE 0121 MOV SI, OFFSET LS ; letter string into SI COLLOOP: AD LODSW ; letter into AL, dash pattern into AH CD 29 INT 29H ; write to screen 84 E4 TEST AH, AH ; is AH = 0? 74 0E JZ END_NL ; if so break loop, write NL B0 20 MOV AL, ' ' ; space char into AL CD 29 INT 29H ; write to screen D2 EC SHR AH, CL ; shift dash bit into CF 73 02 JNC NO_DASH ; is a dash? B0 2D MOV AL, '-' ; dash char in AL NO_DASH: CD 29 INT 29H ; write to screen EB EB JMP COLLOOP ; loop until end of string END_NL: B0 0D MOV AL, 0DH ; CR char CD 29 INT 29H ; write to screen B0 0A MOV AL, 0AH ; LF char CD 29 INT 29H ; write to screen E2 DE LOOP ROWLOOP ; loop until end of rows C3 RET ; return to DOS LS DB 'L',15H,'A',3H,'P',16H,'A',0CH,'C',19H,'K',0 ``` **How?** The "letter string" data contains two bytes for each letter - the high byte is the letter and the low byte is a bitmap describing if that letter should be followed by a dash for each row. The rows are indexed 6 to 1 starting from the top, where the bit in the corresponding order represents whether or not there's a dash. *Examples:* Row 5, Col 0: Data `'L'`, `0x15` (0**1**0101) The fifth bit is a `1` indicating that for the fifth row after the `L` there is a dash after. Row 2, Col 3: Data `'A'`, `0xC` (0011**0**0) The second bit is a `0` indicating that for the fifth row after the `A` there is not a dash after. Or looking at it a different way, the odd bytes `[ 0x15, 0x3, 0x16, 0xC, 0x19, 0x0 ]` form the bitmap of the dashes (only rotated and flipped): ``` 0x15 010101 0x3 000011 0x16 010110 0xC 001100 0x19 011001 0x0 000000 ``` **Runtime:** A standalone IBM PC DOS COM executable. Output to console. [![enter image description here](https://i.stack.imgur.com/rR0mY.png)](https://i.stack.imgur.com/rR0mY.png) [Answer] # JavaScript (ES6), ~~74 72~~ 71 bytes ``` _=>`L A P A C K `.repeat(i=6).replace(/ /g,c=>c+' -'[863064083>>++i&1]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i7BR8FRIQCInRW8uRL0ilILUhNLNDJtzTRB7JzE5FQNfQX9dJ1kW7tkbXUFXfVoCzNjAzMTAwtjOztt7Uw1w1jN/8n5ecX5Oal6OfnpGmkampr/AQ "JavaScript (Node.js) – Try It Online") ### How? We build a string consisting of the pattern `"L A P A C K\n"` repeated 6 times and match all spaces. We replace each of them with either `" "` or `" -"` depending on the result of a test on a bit mask. In binary, the constant **863064083** is: ``` bit 31 bit 7 bit 0 v v v 00110011011100010101000000010011 \___/\___/\___/\___/\___/ \___/ row: 4 3 2 1 0 5 ``` Because we start with `i=6` and pre-increment `i` at each iteration, the first row is encoded by the bits 7 to 11 (0-indexed). As stated in the [ECMAScript specification](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-signed-right-shift-operator), bitwise shifts are processed modulo 32. So there's a wrap-around when `i` exceeds 31 and the last row can safely be encoded by the bits 0 to 4. --- ### Alternate version For **69 bytes**, we could do: ``` _=>`LAPACK `.repeat(i=6).replace(/\B/g,c=>' '+' -'[863064083>>++i&1]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i7BxzHA0dmbK0GvKLUgNbFEI9PWTBPEzklMTtXQj3HST9dJtrVTV1DXVlfQVY@2MDM2MDMxsDC2s9PWzlQzjNX8n5yfV5yfk6qXk5@ukaahqfkfAA "JavaScript (Node.js) – Try It Online") But the corresponding output includes 2 trailing spaces on the last row1. Because the challenge looks very strict about leading and trailing whitespace, this is probably invalid. ¯\\_(ツ)\_/¯ *1: Now, would you have noticed them if I didn't tell ya?! :-p* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 27 bytes ``` E?*<)3&✂⭆⍘℅ι- ⁺ ⁺λ§LAPACKμ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUBDyV7LRtNYTUlHITgnMzlVI7gEKJUOknFKLE6F8DT8i1Iy8xJzNDI1dRSUdBWUgFRATmmxhpKCEpSVo6PgWOKZl5JaoaHk4xjg6OwNlMnVBAIdBSMgaf3//3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes by appropriating @KevinCruijssen's custom base conversion idea. Explanation: ``` ?*<)3& Literal string of code points E Map over characters ι Current character ℅ Take the ordinal ⍘ - Convert to custom base `- ` ⭆ Map over characters and join λ Current character ⁺ Concatenated with LAPACK Literal string `LAPACK` § Indexed by μ Inner index ⁺ Prefixed with a space ✂ ² Slice off the leading spaces ``` [Answer] # APL+WIN, 58 bytes ``` n←96⍴¯2↓∊'LAPACK',¨⊂' '⋄n[⎕av⍳'ì↑⍋+.28;EHRU^']←'-'⋄6 16⍴n ``` Explanation: ``` 'LAPACK',¨⊂' ' concatenate 2 spaces to each letter in LAPACK 96⍴¯2↓∊ convert to a vector, drop last 2 spaces and replicate to form a 96 element vector ⎕av⍳'ì↑⍋+.28;EHRU^' convert characters to ascii code point integers n[.....]←'-' use integers as index positions to assign - character 6 16⍴n reshape vector as a 6 16 matrix ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` puts"L%sA%sP%sA%sC%sK "*6%(0..29).map{|i|' -'[644276896[i],2]} ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFjJR7XYUbU4AEw6qxZ7cylpmalqGOjpGVlq6uUmFlTXZNaoKyjoqkebmZgYmZtZWJpFZ8bqGMXW/v8PAA "Ruby – Try It Online") Builds the output string by successive substitution from an array of prefixes. For each letter other than `L`, the appropriate two-character prefix (either or `-`) is selected by using the binary digits of `644276896` (`100110011001101110001010100000` in binary) to index into the three-character string `-`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •x—o—Õ•₃вε„ -Åв’la•Î’u.ι2ôJðý¦, ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcOiikcNU/KB@PBUIOdRU/OFTee2PmqYp6B7uPXCpkcNM3MSgeKH@4CsUr1zO40Ob/E6vOHw3kPLdP7//6@rm5evm5NYVQkA) **Explanation:** ``` •x—o—Õ• # Push compressed integer 251957282837 ₃в # Convert it to base-95 as list: [32,53,35,54,44,57] ε # Foreach over the integers: „ -Åв # Convert it to custom base-" -", # which basically means to convert it to base-2 and index it into " -" ’la•Î’ # Push dictionary string "lapack" u # Uppercase it: "LAPACK" .ι # Interleave the characters in the two strings 2ô # Split it into pairs of characters J # Join each pair together ðý # Join the list by spaces ¦ # Remove the first character in front of the "L" , # And output it with trailing newline ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’la•Î’` is `"lapack"`; `•x—o—Õ•` is `251957282837`; and `•x—o—Õ•₃в` is `[32,53,35,54,44,57]`. (`[32,53,35,54,44,57]` is `[100000,110101,100011,110110,101100,111001]` in binary.) [Answer] # [Perl 5](https://www.perl.org/), 57 bytes ``` $"=" { ,-}";say+(<"@{[L,A,P,A,C,K]}\n">)[0,21,3,22,12,25] ``` [Try it online!](https://tio.run/##K0gtyjH9/19FyVZJoVpBR7dWybo4sVJbw0bJoTraR8dRJwCInXW8Y2tj8pTsNKMNdIwMdYx1jIx0DI10jExj////l19QkpmfV/xf19dUz9BAzwAA "Perl 5 – Try It Online") ## Explanation First `$"` (which is a magic variable that is used as a field separator when lists are interpolated into strings - default is `" "`) is set to `{ ,-}`. Then `say` is called which is a newline-terminated `print` function, passing in the listed indexes (0, 21, 3, 22, 12, 25) from the result of the `glob` (`<...>` is shorthand for calling `glob`) `<"@{[L,A,P,A,C,K]}\n">`. This glob expands to: ``` L { ,-}A { ,-}P { ,-}A { ,-}C { ,-}K ``` Which, due to the `{ ,-}`s, will generate a list containing all permutations of the string with either or `-` before every letter (except the leading `L`). The chosen indices are the ones we need for the logo. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 62 bytes This is way too long. ~~The markdown parser breaks terribly if I use the TIO's post snippet generator, so there's an extra leading newline in the snippet below: there is actually only 1 leading newline!~~ ``` bbcccbc-cc-b--b-- c b c - L`.{6} . $0X Y`X`\LAPACK .L L ``` The first 2 lines replace the empty string with `bbccc... c`, the next 4 lines decode it into spaces and dashes by simple substitutions (`b` -> 3 spaces, `c` -> `-`), the next line splits it into 6 lines of length 6 (producing a 6x6 sign matrix), the next two lines replace each character `c` by `cX` , the next line cyclically transliterates all `X`s into `LAPACK`s, and the last 2 lines remove leading whitespace. [Try it online!](https://tio.run/##K0otycxLNPz/nyspKTk5OSlZNzlZN0kXhBSSuZK4FBQUuJK5FHS5fBL0qs1qufS4VAwiFLgiEyISYnwcAxydvbn0fLh8/v8HAA "Retina – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~92~~ ~~91~~ ~~84~~ 83 bytes Saved 7 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(i){for(i=30;i--;i%5||puts("K"))printf("%c %c","CAPAL"[i%5]," -"[22141337>>i&1]);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPT1tjAOlNX1zpT1bSmpqC0pFhDyVtJU7OgKDOvJE1DSTVZQTVZSUfJ2THA0UcpGqgqVkdJQVcp2sjI0MTQ2Njczi5TzTBW07r2f25iZp4G0FQNEOdfclpOYnrxf91yAA "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 107 bytes ``` s='LAPACK';e=enumerate for i,_ in e(s):print(*[' -'[(j%2+i%2==2)^(i//2+j//2==3)]*(j!=0)+k for j,k in e(s)]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v9hW3ccxwNHZW9061TY1rzQ3tSixJJUrLb9IIVMnXiEzTyFVo1jTqqAoM69EQytaXUFXPVojS9VIO1PVyNbWSDNOI1Nf30g7C0jY2hprxmppZCnaGmhqZyuAjMjSyYYZEav5/z8A "Python 3 – Try It Online") How it works: blue squares are in the form \$\begin{pmatrix}1&1\\1&-1\end{pmatrix}\$ hence `j%2+i%2==2` and red squares (when `i//2+j//2==3`) are in the opposite form \$\begin{pmatrix}-1&-1\\-1&1\end{pmatrix}\$ thus we simply xor the expressions with `^`. \$\$ \begin{array}{rr|rr|rr} \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{A}}& \color{blue}{\mathrm{P}}& \color{blue}{\mathrm{A}}& \color{blue}{\mathrm{C}}& \color{blue}{\mathrm{K}}\\ \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{-A}}& \color{blue}{\mathrm{P}}& \color{blue}{\mathrm{-A}}& \color{blue}{\mathrm{C}}& \color{blue}{\mathrm{-K}}\\ \hline \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{A}}& \color{blue}{\mathrm{P}}& \color{blue}{\mathrm{A}}& \color{red}{\mathrm{-C}}& \color{red}{\mathrm{-K}}\\ \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{-A}}& \color{blue}{\mathrm{P}}& \color{blue}{\mathrm{-A}}& \color{red}{\mathrm{-C}}& \color{red}{\mathrm{K}}\\ \hline \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{A}}& \color{red}{\mathrm{-P}}& \color{red}{\mathrm{-A}}& \color{blue}{\mathrm{C}}& \color{blue}{\mathrm{K}}\\ \color{blue}{\mathrm{L}}& \color{blue}{\mathrm{-A}}& \color{red}{\mathrm{-P}}& \color{red}{\mathrm{A}}& \color{blue}{\mathrm{C}}& \color{blue}{\mathrm{-K}} \end{array} \$\$ Other techniques used: `print(*[x])` instead of `print(' '.join(x))`, `s*(j==0)` instead of `s if j else ''`, `[falsy,truthy][expr]` instead of `truthy if expr else falsy`, where the former list is just a string `' -'`, the rest is pretty straightforward. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 37 bytes ``` ' -'[(6⍴2)⊤⎕A⍳'AVDWMZ'],¨6 6⍴'LAPACK' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGIBaQVlfQVY/WMHvUu8VI81HXEqCg46PezeqOYS7hvlHqsTqHVpgpgGTVfRwDHJ291f//BwA "APL (Dyalog Unicode) – Try It Online") * `⎕IO←0`. We encode the dashes matrix by * encoding dashes as `1`s (and spaces as `0`s) * converting each column from binary to a decimal number (`0 21 3 22 12 25`) * indexing into the alphabet (`AVDWMZ`). We decode it the same way: * `⎕A⍳` - retrieves index into alphabet * `(6⍴2)⊤` converts to binary columns * `' -'[...]` - `1` becomes dash. Then we generate the `LAPACK` matrix with `6 6⍴'LAPACK'`, and concatenate each pair with `,¨`. [Answer] # [///](https://esolangs.org/wiki////), 83 bytes ``` /$/ -//#/A@//!/ L //@/ /L@#P@#C@K!-#P$#C$K! #P@A$C$K!-#P$A$C@K! A$P$#C@K!-A$P@#C$K ``` [Try it online!](https://tio.run/##FYqxDcAwCAT7TAGC1voVQC7twiukiJQiHfuLQHe6u/jueJ/IhIIGIHADGNcmwECEbXJMpi0eclSmLqYyrk2tiiqSa9feiqy/zB8 "/// – Try It Online") [Answer] # [R](https://www.r-project.org/) + magrittr, 312 bytes ``` library(magrittr) A <- matrix(c(1,1,1,-1),nrow = 2) B <- matrix(c(1,1,1,1,1,-1,1,-1,1),nrow = 3) kronecker(B,A) %>% apply(1, function(x) {paste0(x,strsplit("LAPACK","")[[1]]) %>% gsub("-1","-",.) %>% gsub("1"," ",.)}) %>% apply(2,function(x){paste0(x, collapse = " ")}) %>% cat(sep = "\n") ``` [Try it online!](https://tio.run/##bU9Ni8IwEL3nVwwBYQLpsnWvKtQ9ugfv6iGGKMGYhkmKLbK/vZtqWRWcgTm8eR8z1PfO7klRh2d1JJsSCRiLsQpmBZxVItuixlIOXZRCeqovMIepYMs3jDtrHP/kL8FOVHujT4ZwKSsBk8UEGIAKwXVZCofG62Rrj62Aa1AxmU9sZUwUg7MJ@U@1rr5XXHIuNptyt7s5ZINjbPbIizJvCi4/7sYjOoAwgL/5rZfAqXzKe8SBrp1TIZp8clY@67RKGE0YFlvPRd//AQ "R – Try It Online") This gives on my console: ``` L A P A C K L -A P -A C -K L A P A -C -K L -A P -A -C K L A -P -A C K L -A -P A C -K ``` With the function kronecker() we construct a block matrix by replicating A by B coefficients. A is a 2x2: ``` > A [,1] [,2] [1,] 1 1 [2,] 1 -1 ``` which are the signs that we want to replicate in 3x3 blocks multiplied by the coefficients in B: ``` > B [,1] [,2] [,3] [1,] 1 1 1 [2,] 1 1 -1 [3,] 1 -1 1 ``` Then we explode LAPACK with strsplit() and prepend 1 or -1. With gsub() we substitute 1 and -1. Then, we collapse the strings and print out to the console. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 30 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Happy to be beating 05AB1E after quite a bit of work on this but still feel I could do much better. Originally based on Neil's Charcoal solution. ``` "?*<)3&"¬®csSi-)í"LAPACK")ò ¸x ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=Ij8qPCkzJiKsrmNzU2ktKe0iTEFQQUNLIinyILh4) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~62~~ 57 bytes Port of the [Arnauld's](https://codegolf.stackexchange.com/a/206683/80745) alternative answer. Very nice! Delicious! Thanks. We avoid the problem with `2 trailing spaces on the last row` because we use the array of strings, not the string with repeated `LAPACK\n`. ``` ,'LAPACK'*6-replace'\B',{' '+' -'[(214811968-shr++$i)%2]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0fdxzHA0dlbXctMtyi1ICcxOVU9xkldp1pdQV1bXUFXPVrDyNDEwtDQ0sxCtzijSFtbJVNT1Si29v9/AA "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes port of [C (gcc)](https://codegolf.stackexchange.com/a/206688/80745) answer. Thanks @[Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) and @[Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). ``` -join(29..0|%{'CAPAL'[$_%5];' ';' -'[(22141337-shr$_)%2];'K '*!($_%5)}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPw8hST8@gRrVa3dkxwNFHPVolXtU01lpdQR2IddWjNYyMDE0MjY3NdYszilTiNVWNgJLeXOpaihoglZq1mv//AwA "PowerShell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~94~~ 77 bytes -17 bytes thanks to mazzy ``` -join("L A P A C K "*6|% t*y|%{"$_-"[++$i+12-in' &,:=BHKYVdgp'[0..12]]}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPQ8lHQcFRQSEATDorKHhzKWmZ1agqlGhV1qhWK6nE6ypFa2urZGobGulm5qkrqOlY2Tp5eEeGpaQXqEcb6OkZGsXG1mr@/w8A "PowerShell – Try It Online") Just checking for the indexes we need saves 9 bytes over just writing out the block. However, if we represent the indexes using their char values, we save loads more. We add 12 to the current iteration to get everything into the printable ASCII range. `' &,:=BHKYVdgp'[0..12]` converts our index string into an index array so we can use `-in`. [Answer] # [Io](http://iolanguage.org/), 125 bytes ``` " - - - -- - -- -- -- - "foreach(x,i,("LAPACK"exSlice(x%6,x%6+1).." ".. i asCharacter .. if(x%6>4," ",""))print) ``` [Try it online!](https://tio.run/##y8z//19JAQx0wRDEALN0ISwIoauglJZflJqYnKFRoZOpo6Hk4xjg6OytlFoRnJOZnKpRoWqmA8Tahpp6ekoKSnp6CpkKicXOGYlFicklqUUKIIE0kCo7Ex0lLiUdJSVNzYKizLwSzf//AQ "Io – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 132 bytes ``` s,a,i="0"*19+bin(0x208200090824009002402)[2:],list("L A P A C K\n"*6),0 for c in s: if(int(c)):a[i]="-" i+=1 print "".join(a) ``` [Try it online!](https://tio.run/##XY09D4IwEIZn@ysut9BCa47GGCFhMI44uCMDkhBrTCHAoL@@FgLGuNybPO/Hde/x3lrt3CAraTIkDOMkuhnL6aXpoIko8bKbhLxoUei0lE8zjBzPAEeAy3xPAPnVYrgXkljT9lCDsTCkbGMabuzIayHSqjBlhgo9jLKYdb03AHH7aP3DSrggCNj/qAdqBmoGKv9NqAV8E2qpTN5aWTfUOuor/pP7AA "Python 2 – Try It Online") Yes, I realise this is longer than a simple print statement, but I spent too long trying to get this to work and I liked the approach (for larger matrices, this method would become much more efficient). There must be at least a few ways to shave a couple bytes off this answer [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 356 bytes ``` ++++++++[>+++++>++++++++>++++>+++++++++>+<<<<<-]>+++++>+>>++++>++<.<..<.>..>++++.<..<.>..<++.>..>-----.>.<+.<.<<.>--.>..>++++.<.<<.>.>..<++.>.<<.>>>-----.>.<+.<..<--.>..>++++.<..<.>.<<.>++.>.<<.>>>-----.>.<+.<.<<.>--.>..>++++.<.<<.>.>.<<.>++.>..>-----.>.<+.<..<--.>.<<.>>>++++.<.<<.>.>..<++.>..>-----.>.<+.<.<<.>--.>.<<.>>>++++.<..<.>..<++.>.<<.>>>-----.>. ``` [Try it online!](https://tio.run/##dU9bCoAwDDuQrCcIvYj4oYIggh@C56/LdHOFrRTWZEkfyzXv53avh9nwxajp0YzVoViBEaYs0yyAQGKqSGIKQqxJBkaswC@ARC0m88uJ1FsE3pC6U9czdGcUkzQnvK2aa/WucJb6bL@W2QM "brainfuck – Try It Online") There is the version, line by line (The 1st one is used to store the different chars) ``` ++++++++[>+++++>++++++++>++++>+++++++++>+<<<<<-]>+++++>+>>++++>++ <.<..<.>..>++++.<..<.>..<++.>..>-----.>. <+.<.<<.>--.>..>++++.<.<<.>.>..<++.>.<<.>>>-----.>. <+.<..<--.>..>++++.<..<.>.<<.>++.>.<<.>>>-----.>. <+.<.<<.>--.>..>++++.<.<<.>.>.<<.>++.>..>-----.>. <+.<..<--.>.<<.>>>++++.<.<<.>.>..<++.>..>-----.>. <+.<.<<.>--.>.<<.>>>++++.<..<.>..<++.>.<<.>>>-----.>. ``` ]
[Question] [ We all know of different fancy sorting algorithms, but none of these give us numbers in a way that's easy to pronounce. To remedy this, I propose using PronunciationSort™, the most natural way to sort lists of numbers. ## Pronunciation The official rules for pronouncing numbers (in this challenge) is that the digits are pronounced one by one, and the resulting string is sorted in lexicographic order. As an example, this means that the number `845` is pronounced `"eight four five"`, and should be sorted accordingly. ### Negative numbers Negative numbers are pronounced by prepending the word `"minus"`. Thus, `-23` is pronounced as `"minus two three"`. Note that this causes negative numbers to end up in the middle of the output, right between numbers starting with `4` (four) and `9` (nine). As a guide, the official order of words for PronunciationSort™ is: * eight * five * four * minus * nine * one * seven * six * three * two * zero That is, ``` 8, 5, 4, -, 9, 1, 7, 6, 3, 2, 0 ``` ## Input A list of integers in the range \$[-999, 999]\$, containing at most 100 elements. Input as a list of strings is not permitted. If your language does not support input as list, it is permissible to give input as separate integers. The input will not contain any invalid numbers, or any number starting with a 0 (except the number 0 itself). The input will generally not be sorted, it can be given in any order. ## Output The same integers, in PronunciationSort™ order. Note that the numbers should only be converted to their pronunciations to get the sorting, the output should not contain any strings. ## Examples For the examples, the middle step (wrapped in parentheses) only serves as a guide, and is not a part of the output. ``` [1, 2, 3] -> (['one', 'two', 'three']) -> [1, 3, 2] [-1, 0, 1, 2] -> (['minus one', 'zero', 'one', 'two']) -> [-1, 1, 2, 0] [-100, 45, 96] -> (['minus one zero zero', 'four five', 'nine six']) -> [45, -100, 96] [11, 12, 13, 134, 135] -> (['one one', 'one two', 'one three', 'one three four', 'one three five']) -> [11, 13, 135, 134, 12] ``` There's also a [script for verifying your results](https://tio.run/##XVDLboQwDDyTr7By2aCmqO32re6XoNUKFQNuwYmCYbv9eRpCL@3JM5E9Mxl/kc7xfllo8C4IVKMoVWMDLcrJB8du4nc0nL@qjBpgeIObCLOAMgUGPRBPI2i4@ndwzbnKzi7UIxygPKqsppYkEf2NwWkL2jGuQ86JSRcw8cZNQdvooRua08tIX2ngjLwCpLaTFTBFiSjeuADJAIhhlLDl3fyLynvk2mwBSmLZYH6MCX@/sYNd8eGITbrIlVI8DWvYWEfRk2Co@hPOVW@I/SQmz5UPq9IYO8ParNsWPvFy@NNCXFuW8tbe2b29tw/20T7ZZ/ty/AE). [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` import Data.List sortOn$map(`elemIndex`"54-9176320").show ``` [Try it online!](https://tio.run/##dY1PC4JAEMXvfoqHeDBYxfVfKdSpixB06CiCS226pJu4G/Xtbeze4c283@MN0wvzkMOwLGqcnrPFUVgRnpSxzn1vKDhrbxST38pBjpW@yU/rZmlQ8G2exJG7CU3/fC8d9lgNQtxJ/izFDWWJi52V7hAcUFfaNhtnFEpTV2krZ3G18PDSg9LS0BW9QUf7x0vNGWKGpHHqgGzEsAY/igjSjKHICTnFnIo8WZWuI/sTM@yaLw "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṾV€ị“Þ⁽3Z6»µÞ ``` **[Try it online!](https://tio.run/##y0rNyan8///hzn1hj5rWPNzd/ahhzuF5jxr3GkeZHdp9aOvhef///4820FGwNAViEx0FEyBtAqR1LUDYEERYxAIA "Jelly – Try It Online")** A monadic link accepting a list of integers which yields a list of integers. ### How? Sorts by the ordinal values of the digits of the integers (where `-` is a "digit" of -1) converted to strings using the characters at their 1-based & modular index in the magic string "murgeon lix". The sort is effectively alphabetic where a space is considered less than any letter. The magic string "murgeon lix" was found by inspecting Jelly's dictionaries used in compression. There are no words of 11 letters which satisfy the requirements (and none of more that would upon de-duplication). since a space sorts before letters the next most obvious choice is a word of length seven followed by a space followed by a word of length three. "murgeon" and "lix" is the only satisfying combination, although without a space others may be possible (e.g. `“£Py:ƥ»` is "murgeonalix" which works for the same byte-count) ``` ṾV€ị“Þ⁽3Z6»µÞ - Link: list of integers Þ - sort by: µ - the monadic link: -- i.e. do this for each integer, then sort by that Ṿ - unevaluate (e.g. -803 -> ['-','8','0','3']) V€ - evaluate each as Jelly code (e.g. ['-','8','0','3'] -> [-1,8,0,3]) “Þ⁽3Z6» - "murgeon lix" (compression of words in Jelly's dictionary plus a space) ị - index into (1-indexed & modular) (e.g. [-1,8,0,3] -> "i xr") ``` --- [Previous @ 15 bytes](https://tio.run/##y0rNyan8///hzn1hj5rWPNzd/ahhzqGFUfmPGrc9aph5dJL9oSWHth6e9////2gDHQVLUyA20VEwAdImQFrXAoQNQYRFLAA "Jelly – Try It Online"): ``` ṾV€ị“¡Zo⁶’Œ?¤µÞ ``` Here `“¡Zo⁶’Œ?¤` finds the first permutation of natural numbers which would reside at the index 21,340,635 when all permutations of the numbers are sorted lexicographically - which is `[6,10,9,3,2,8,7,1,5,4,11]`. (`“¡Zo⁶’` is a base 250 representation of 21340635, while `Œ?` does the calculation and `¤` groups these instructions together) [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 15 bytes ``` Σε•Koéa₃•'-3ǝsk ``` [Try it online!](https://tio.run/##MzBNTDJM/W/i9v/c4nNbHzUs8s4/vDLxUVMzkKmua3x8bnH2/9panf/RhjpGOsaxXNG6hjoKBjoKQNIIzDMAckxMdRQszYBcQ6CwoREQG4OwCYgwjQUA "05AB1E (legacy) – Try It Online") **Explanation** ``` Σ # sort by ε # apply to each sk # index of the element in •Koéa₃• # "85409176320" '-3ǝ # with "-" inserted at index 3 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes ``` *.sort:{TR/0..9-/a5982176043/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS684v6jEqjokSN9AT89SVz/R1NLCyNDczMDEWL/2vzVXcWKlQpqGSrymQlp@EVe0oY6CkY6CcawOV7QukG2gowASgXANgDwTUx0FSzMQ3xAoYQhUa2gMwiYgwjTW@j8A "Perl 6 – Try It Online") Port of G B's Ruby solution. ### Original 35 byte version ``` *.sort: (~*).uninames».&{S/\w*.//} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS684v6jESkGjTktTrzQvMy8xN7X40G49tepg/ZhyLT19/dr/1lzFiZUKaRoq8ZoKaflFXNGGOgpGOgrGsTpc0bpAtoGOAkgEwjUA8kxMdRQszUB8Q6CEIVCtoTEIm4AI01jr/wA "Perl 6 – Try It Online") Convert each number to a string, get the Unicode name of each character, strip the first word ("DIGIT" or "HYPHEN"), then sort. [Answer] # Python 3, ~~68 bytes~~ ~~67 bytes~~ 64 bytes ``` lambda x:sorted(x,key=lambda y:[*map('54-9176320'.find,str(y))]) ``` Uses built-in `sorted` function with an anonymous lambda for the key. Hard-code the sort order and compare each digit in each value in the input list to its position in the sort order list. *Edit: Saved 1 byte by removing `8` from sort list to take advantage of `str.find` returning `-1` when parameter is not found. Thanks to maxb.* *Edit2: Saved 3 bytes by using starred unpacking syntax in a `list` literal instead of `list` constructor* [Try it online!](https://tio.run/##XcxBCsMgEAXQfU/hLgqmaNSkCeQkbRcWI5UmRtRFPL1VKIV2YGbx/mdcis/dsqznW17l9lASHFPYfVwUPPBrSfNH07SaEOEmHWwugrcjHXrWkeasjVU4RA8TKpOdNzZCDa8Ugw4Ddkfo9LW2IMGgRn9OCnOBwdj/BLRUaXlDWV1ejyiF/AY "Python 3 – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes ``` a=>a.sort((a,b)=>(g=n=>[...n+''].map(c=>':598217604'[c]||3))(a)>g(b)) ``` [Try it online!](https://tio.run/##bZDNcoMgFIX3fYq7A6ZK/Ilp0xl4EYcFsWhoIzhg0p/Ju1sxOpM6WQAXLnzncD7kRfrK6a6PfafflWut@VQ/Q80Gybik3roeYxkdCOO4YYbxklJqnhEStJUdrhhHb8X@NUtfdskWlZW4XnNCsCS8wQdChsoab0@KnmyDa1ymEWQR5IIQ2Gwg5oBLZI1CEaD@y07L0SmFBAnNcD0fX4inFSYeG0kEgfYP1Wpz9jADf5WbiHf8GRue35wkD9DJSN4WEex3j9kQwLDQa3t2UOvLpGH02Pb6exEKmBtwhK2V0uBi9JDmYWzDVKyDWf4SyjmgqZxCut9A8LE6CaaWINNFp1jEMjH8AQ "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~21 20~~ 22 bytes ``` {x@<"54-9176320"?/:$x} ``` [Try it online!](https://tio.run/##JYrLCsIwEEX3fsVQutBFMJOXJCPof5RA3USkUqF0kVLqr8eJhZnhnnNnEONzLCWFNd@vjTXC48VpJZvbObR5K3NY2275TiFBpv4z0LFPj9ebMi00neJ2mDsEBZoQNKjIKBAksCMOtZK7lBKMBe@I75@8qwXykwLUPIbXUhWV7G5ULD8 "K (ngn/k) – Try It Online") `{` `}` function with argument `x` `$` format as strings `"`...`"?/:` find indices of individual characters in the given string (or \$-2^{63}\$ for not found - note that the `"8"` is missing) `<` compute sort-ascending permutation `x@` the argument at those indices [Answer] # Pyth, ~~17~~ 16 bytes ``` oxL"54-9176320"` ``` Try it online [here](https://pyth.herokuapp.com/?code=oxL%2254-9176320%22%60&input=%5B-100%2C%2045%2C%2096%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=oxL%2254-9176320%22%60&test_suite=1&test_suite_input=%5B1%2C%202%2C%203%5D%0A%5B-1%2C%200%2C%201%2C%202%5D%0A%5B-100%2C%2045%2C%2096%5D%0A%5B11%2C%2012%2C%2013%2C%20134%2C%20135%5D&debug=0). ``` oxL"54-9176320"`NQ Implicit: Q=eval(input()) Trailing N, Q inferred o Q Order the elements of Q, as N, using... `N Convert N to string xL Get the index of each character of that string... "54-9176320" ... in the lookup ordering (if character missing, returns -1, so 8 is still sorted before 5) ``` *Saved 1 byte thanks to @ngn and [their K answer](https://codegolf.stackexchange.com/a/172893/41020), by omitting 8 from the start of the dictionary string* [Answer] # Japt, 19 bytes ``` ñ_s ®n"54-9176320 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8V9zIK5uIjU0LTkxNzYzMjA=&input=Wy0xMDAsNDUsOTZd) * Save 2 bytes thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` T`-d`3:598217604 O` T`3:598217604`-d ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg8z8kQTclwdjK1NLCyNDczMCEyz@BKwRZACj/PyaPS@e/oY6RjjGXrqGOgQ6QCWQYGOiYmOpYmnEZGuoYGukYGgORCRCbAgA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` T`-d`3:598217604 ``` Translate the minus sign and digits to their position in pronunciation order, using `:` for 10th position. ``` O` ``` Sort in pronunciation order. ``` T`3:598217604`-d ``` Translate the order back to the original minus sign and digits. [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes ``` ->a{a.sort_by{|x|x.to_s.tr('0-9-','a5982176043')}} ``` [Try it online!](https://tio.run/##HY1BCsMgFET3PYU7W/iKRk3rornIR4JZZFcSjAFD4tmNdjHDvGFgwj4dZf4WNvjT820JcZyO80pX4nEZNx7DkwpmGQXqjf108t0Lregr54IogXRAlANkNQogrfiTqKANENtXlLWWdShVk25mnOM/v7ajx0owwYzJuVxu "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 58 bytes ``` function(x)x[order(mapply(chartr,"-0-9","dkfjicbhgae",x))] ``` [Try it online!](https://tio.run/##bZDBboMwDIbvewqLHkikRIJSKiFNfRHEgUIysq5JlcJG@/I0DkRlVQ9J7Nj@ftt2kvDJJznopldGk5GOpbGtsORcXy4/N9J0te0ti3jCi4hF7Ul@q@bYfdUiYiOl1SRJQ1IGWwYZpRvgByBlbLSIGcT9n/FPZ4WIK4rB0uVmLr36wELuvIQB1j@Lz0oPV1gQd2E9Y0VcQFg7CycBljjWLmdQ7N/QAFEQeNIMFqT69VStXPiqxoBGxkwr9jM7RTEnlWZ4dnjl/8YN/aK5jO1NP/raAVR@@cE2wnrSIJIHJber6QE "R – Try It Online") Input is a list of numbers which is implicitly converted as string using `chartr`. `order` then uses lexigographic order to retrieve the order by which the original list should be sorted. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 123 bytes ``` l->l.sort(java.util.Comparator.comparing(n->{var r="";for(var c:(""+n).split(""))r+=11+"54-9176320".indexOf(c);return r;})) ``` [Try it online!](https://tio.run/##dZHJbsIwEIbvPMXIJ7skFmErEBKp4lSpVQ8cqx5c4yDTxI5sBxVVPHtqh660HLzMfL9n847tWbzbvLSyqrVxsPM2bZws6VXa@@MrGsWd1CpAXjJr4Z5JBW89gLp5LiUH65jzx17LDVSe4bUzUm0fn4CZrSWdFGCllW0qYZZ30rrlrXJiK0yeQwFZW8Z5Sa3Pi7/zrnRVM8OcNpR3Vx8Sqzh/2zMDJkMoLbTBweALjFBfEWrrUjp/J8T0syTpo8k4nifX09FwgKhUG/H6UGBOUiNcYxSY9EhIm3bVdUWdVeaEdRYyuDGGHSxlNnDcyeHMmUQwjGBEon9p7PEggiC6qBh4wXgSwXx6QZL454lPkozCGodtcinaLIIZ6RA5tRdG9au7rrnFqcXPHwJYH6wTFdWNo7Wft8OBQx/QAtBHJB@LMs5FfYJf3vOnpfrJj72wju07 "Java (JDK 10) – Try It Online") This is a naive Java implementation. Should be much golfable. ## Credits * 3 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~87~~ 73 bytes ``` a=>a.sort((p,q,F=b=>[...""+b].map(x=>"54-9176320".search(x)))=>F(p)>F(q)) ``` [Try it online!](https://tio.run/##dY1NDsIgGET3HqMriPMRKNDaGLr0EsYF1vqvYDFGT1/ZuDGazMzmJW@O/uFTNxzinVI8bPrhEq6n/jVu3ehd60UKw52xiBsWbu3apRCiKKbrlbj4yJ6uLayhRtWVLmUhUu@Hbs@enHPXLljkeW6cj/MuXFM49@IcdmzLlgol9IrzyTcgBYlMfzMpYSya6hdVCqqE0jkm1/4xgBrQDFSDKpAFGZAGlfg8Q8PAokKNGRoomUXjGw "JavaScript (SpiderMonkey) – Try It Online") Thanks @Arnauld for telling that the sort in SpiderMonkey is stable, so the `||-(F(q)>F(p))` part can finally be dropped. [Answer] # [Red](http://www.red-lang.org), 114 bytes ``` func[n][g: func[a][collect[foreach c form a[keep index? find"854-9176320"c]]]sort/compare n func[x y][(g x)< g y]] ``` [Try it online!](https://tio.run/##VYzNCsIwEITvPsXQkx6KSf@0RfAdvIY9lHRTi21SYoX69DEoiMIO8813WM9duHCnaGOaYB5WK0uqb/DGlpR248h6UcZ5bvUVGpEmtOrGPGOwHa9nmNjJsSzSWh6qPBOJJqK788teu2luPcN@Hq54ktr2WHcn9JEpzH6wCwyURIacNt@dSghE@aeEQFGirn6klJAZZB6viCkpvAA "Red – Try It Online") ## More readable: ``` f: func [ n ] [ g: func [ a ] [ collect [ foreach c form a [ keep index? find "854-9176320" c ] ] ] sort/compare n func [ x y ] [ (g x) < g y ] ] ``` [Answer] # C++, 353 bytes This is kind of a comedy entry, but I was wasting time and wrote it, so I can't not post it... Enjoy a chuckle, and let me know if there are any space-savers I missed! ``` #include<algorithm> #include<iostream> #include<iterator> #include<numeric> #include<string> using namespace std;auto f(int i){auto s=to_string(i);for(auto&c:s)c='A'+"854-9176320"s.find(c);return s;}int main(){int a[100];auto b=begin(a);auto e=end(a);iota(b,e,-50);sort(b,e,[](int l,int r){return f(l)<f(r);});copy(b,e,ostream_iterator<int>(cout," "));} ``` Output: > > 8 5 4 48 45 44 49 41 47 46 43 42 40 -8 -5 -50 -4 -48 -45 -44 -49 -41 -47 -46 -43 -42 -40 -9 -1 -18 -15 -14 -19 -11 -17 -16 -13 -12 -10 -7 -6 -3 -38 -35 -34 -39 -31 -37 -36 -33 -32 -30 -2 -28 -25 -24 -29 -21 -27 -26 -23 -22 -20 9 1 18 15 14 19 11 17 16 13 12 10 7 6 3 38 35 34 39 31 37 36 33 32 30 2 28 25 24 29 21 27 26 23 22 20 0 > > > [Answer] # Mathematica, 68 bytes ``` SortBy[If[# < 0,"m ",""]<>StringRiffle@IntegerName@IntegerDigits@#&] ``` Function. Takes a list of integers as input and returns the sorted list as output. Just separates the digits of each number with `IntegerDigits`, converts each digit to `"zero"`, `"one"`, etc., with `IntegerName`, converts the list into a space-separated string with `StringRiffle`, prepends an `"m "` if the number is negative, and sorts based on this string. Indeed, this was the shortest approach I can find, since Mathematica only natively uses lexicographic sorting for lists of the same length; thus, an approach based on `854-9176320` ends up taking more bytes since string functions are so expensive. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σ•t∍ýJ•(ÁÁsSk ``` -1 byte thanks to *@Emigna*. -1 byte thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f//3OJHDYtKHnX0Ht7rBWRpHG483FgcnP3/f7ShoY6hkY6hMRCZALFpLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c4sfNSwqedTRe3ivF5ClcbjxcGNxcPb/Wp3/0dGGOkY6xrE6CtG6hjoGOkAehG1goGNiqmNpBuIZGuoYGukYGgORCRCbxsYCAA). **Explanation:** ``` Σ # Sort by: •t∍ýJ• # Push compressed integer 917632054 ( # Negate it: -917632054 ÁÁ # Rotate it twice towards the right: "54-9176320" s # Swap so the current number to sort is at the top of the stack S # Convert it to a list of characters k # Check for each its index in the string (resulting in -1 for '8') ``` [See this 05AB1E tip of mine (section *How to compress large integers*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•t∍ýJ•` is `917632054`. [Answer] # [Nim](http://nim-lang.org/), 110 109 105 103 bytes ``` import algorithm,sequtils,strutils func p[S](n:S):S=n.sortedByIt join mapIt($it,$"54-9176320".find(it)) ``` [Try it online!](https://tio.run/##Vcw7C4NADAfw3U8RxEEhiuezCoXSzdlRHMRHveI96p1DP709Swc7JITfPwmnbN8pk2LV0C0PsVI9M1Tja9N0Uaj0@h2saeM9yKZuXV7WXllfeaDMzTjc35WGp6AcWCcr7TpUo2OniV@QPIuj0A4mygeXas/bx34WcGsIQoQQt4G0fuIbChGO4E9Dg0mKUGQnJmaNmAckPio5WnqKc4SLuTCyfwA "Nim – Try It Online") For some reason, Nim can't compare `seq`s, so I had to turn the results into a string, which cost quite a lot of bytes. ]
[Question] [ Our boolean operators are `AND`, `OR`, `XOR`, `NAND`, `NOR`, `XNOR` and, in conjunction with one of those operators, `NOT`. Our numbers are \$1\$ and \$0\$. The challenge is to write a program or function that calculates the results of the input. ## Input A string, array or other input format of your choice; containing alternating numbers and operators, e.g. `1 NOR 1` or `["1","OR","0","AND","1"]` or `0XOR0XNOR1`. **As an exception, `NOT` must always come directly after another operator (e.g. `0 AND NOT 1`).**. You can't implement `NOT` by itself, and you won't ever get a chain of multiple NOTs (so `1 AND NOT NOT 0` is an invalid input). The input must contain the *strings* for the operators (upper or lower-case is fine); no other representation can be used e.g. `.+^¬||&&` etc. ## Output Return or print a single number (\$1\$ or \$0\$), derived using the calculation below. Invalid input can lead to any output you choose, or none. ## Calculation We're ignoring any precedence rules here - just calculate them in the order they come in (i.e. left-to-right) - as if someone was typing it into a calculator and pressing Enter after each number. `NOT` is the only one that might cause some difficulties with that logic, as you need to figure out what it's `NOT`-ing before you can apply the other operator. ## Truth Tables ``` INPUT OUTPUT A B AND NAND OR NOR XOR XNOR 0 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 1 0 1 1 1 0 1 0 0 1 IN OUT A NOT A 0 1 1 0 ``` ## Examples * `1 NOR 1` = `0` * `1 NOR NOT 0` = `0` (equivalent to \$1\$ NOR \$1\$) * `1 NOR NOT 0 AND 1` = `0` (equivalent to \$0\$ (from above) AND \$1\$) * `1 NOR NOT 0 AND 1 OR 1` = `1` (equivalent to \$0\$ (from above) OR \$1\$) * `1 NOR NOT 0 AND 1 OR 1 XNOR 1` = `1` (equivalent to \$1\$ (from above) XNOR \$1\$) * `1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0` = `1` (equivalent to \$1\$ (from above) NAND \$1\$) * `1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0 XOR NOT 0` = `0` (equivalent to \$1\$ (from above) XNOR NOT \$0\$ = \$1\$ XNOR \$1\$ = \$0\$) ## Scoring This is code-golf, but with a twist. Your score is the number of bytes in your code, *divided by* the number of operators your code implements. Smallest score wins. For example, if you only implement `AND`, your score is the number of bytes of your code. If you implement `AND`, `OR`, `XOR`, `NAND`, `NOR`, `XNOR`, `NOT` (the full list of operators); then you get to divide the number of bytes by 7. You must implement at least one operator, and you cannot implement `NOT` by itself; as it *must* be preceded by another, different operator and so doesn't count as implemented otherwise. *Just because someone has a low score already, don't let that put you off trying to get the best score for your language! It would be interesting to compare across different numbers of implemented operators too - e.g. you might have a bad score for 2 operators, but you might be able to implement 7 really efficiently.* [Answer] # [Python](https://docs.python.org/3/), 3 bytes ÷ 1 op = score 3 ``` min ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPzcz7395RmZOqoKhVUFRZl6JRppGallijkZmXkFpiYYmEPyPVjJQiuUCkToKSo5@LiDKEIsIuiyyiAEKGyKLrgabCPGyOHUBAA "Python 3 – Try It Online") Implements `AND`, with inputs like `["1", "AND", "0", "AND", "0"]`. Simply takes the smallest string value, which is "0" if present and "1" otherwise. Since "AND" is later alphabetically, it can be ignored. Another solution is `all`, using inputs like `[1, "AND", 0, "AND", 0]` since only `0` is Falsey. Python 2 could also do `min` with such inputs, since it has numbers as smaller than strings, whereas Python 3 refuses to compare them. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 1 byte ÷ 2 = 0.5 ``` v ``` [Try it online!](https://tio.run/##K6gsyfj/v@z/fyVDhcS8FIW8/BIFCMtQ6V9@QUlmfl7xf90UAA "Pyth – Try It Online") This works for `and` and `not`. Works by evaluating the input as python code [Answer] # [Python 3](https://docs.python.org/3/), ~~16~~ 4 bytes / 2 = 2 score ``` eval ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzP7UsMed/QVFmXolGmoaSoUJiXoqCoZKmJheaWF5@iYIBirgBDnEk9XDT/gMA "Python 3 – Try It Online") This works for `and` and `not` in any combinations. It partially works for `or` but only when not used in conjunction with `and` in certain cases due to operator precedence in Python. As such cases exist, my official score will only be divided by two (if half-points are allowed, this could maybe be divided by 2.5 instead to get a final score of 1.6) [Answer] Sorry to report that the task is trivial in some language, but anyway here it is. # [J](http://jsoftware.com/), 2 bytes, score 2 ÷ 1 = 2 ``` ". ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm5Amf@a/w2AAoZA6OjnAmYBMRdMzD8IQygCSSxNQR2iD0qqcwEA "J – Try It Online") Implements any one of AND, OR, or XOR. The three are defined in the J standard library as infix functions, so calling `".` (eval) on the string automagically evaluates the given expression as-is. The only problem is that J evaluates from right to left, so the three cannot be used at once. Since it is boring, here are some attempts at adding features one at a time: # [J](http://jsoftware.com/), 10 bytes, score 10 ÷ 3 = 3.33 ``` [:".|.&.;: ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/o62U9Gr01PSsrf5r/jcAShgCoaOfC5gFxFwwMf8gDKEIJLE0BXWIPiipjiwCVogkYgAVAQA "J – Try It Online") Implements all of AND, OR, and XOR. Since all six operators (except NOT) are symmetric, in order to fix the evaluation order, it suffices to reverse the order of words. ``` [:".|.&.;: NB. Input: the expression with space-separated tokens NB. Example input '1 AND 1 XOR 0' &.;: NB. Split into words ['1', 'AND', '1', 'XOR', '0'] |. NB. Reverse the order of words ['0', 'XOR', '1', 'AND', '1'] &.;: NB. Join the words back, with spaces in between '0 XOR 1 AND 1' [:". NB. Eval it ``` At this point, adding a feature is a matter of defining a named infix function. # [J](http://jsoftware.com/), 18 bytes, score 18 ÷ 4 = 4.5 ``` NOR=:+: [:".|.&.;: ``` [Try it online!](https://tio.run/##y/r/388/yNZK24or2kpJr0ZPTc/a6n@arRUyT0HdUAGoSsFAIQJEqgMA "J – Try It Online") Adds NOR (`+:`) to the list. # [J](http://jsoftware.com/), 26 bytes, score 26 ÷ 5 = 5.2 ``` XNOR=:= NOR=:+: [:".|.&.;: ``` [Try it online!](https://tio.run/##y/r/P8LPP8jWypYLTGlbcUVbKenV6KnpWVv9T7O1QuYpqBsqgFQrGChEAElDdQA "J – Try It Online") Adds XNOR (`=`) to the list. # [J](http://jsoftware.com/), 35 bytes, score 35 ÷ 6 = 5.83 ``` NAND=:*: XNOR=:= NOR=:+: [:".|.&.;: ``` [Try it online!](https://tio.run/##y/r/38/Rz8XWSsuKK8LPP8jWypYLTGlbcUVbKenV6KnpWVv9T7O1QuYpqBsqgFQrGChEAElDdQA "J – Try It Online") Adds NAND (`*:`) to the list. Using the same strategy to add NOT is a bit more tricky, since the word order would look like `1 NOT AND 1` instead of `1 AND NOT 1`, and it should negate the number on its left. I solved it by making it a "conjunction", which has higher precedence over regular functions or "verbs" and consumes two tokens on the both sides of it. It is defined as ``` NOT=:2 :'y v-.u' ``` and it evaluates like this: given `0 NOT AND 1`, `u`, `v`, `y` become `0`, `AND`, `1` respectively, and `y v-.u` becomes `1 AND -. 0` (where `-.` is a prefix function for logical negation), successfully negating the number on its left before applying the infix function. # [J](http://jsoftware.com/), 52 bytes, score 52 ÷ 7 = 7.43 ``` NOT=:2 :'y v-.u' NAND=:*: XNOR=:= NOR=:+: [:".|.&.;: ``` [Try it online!](https://tio.run/##y/r/388/xNbKSMFKvVKhTFevVJ3Lz9HPxdZKy4orws8/yNbKlgtMaVtxRVsp6dXoqelZW/1Ps7VC5imoGyoAVQFxiIKBAlC/gqECkGuoADICSIGMBEpEwJSoc5kaqZoDAA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 1 (1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage), 1 operator) ``` ß ``` Input as a list of strings for each digit/operator. Implements `AND`. Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/207094/52210). [Try it online](https://tio.run/##yy9OTMpM/f//8Pz//6MNdZQc/VyUdAxgdCwA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w/P/6/yPjlYyVNJRSsxLAZKGSrE6yHwDMN8ATd4ATR5ZP26TkGRiAQ). **Explanation:** ``` ß # Pop the (implicit) input-list and leave its minimum, # which is "0" if the input contains a "0", or "1" otherwise # (after which this is output implicitly as result) ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~7.857 (55 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), 7 operators) ``` 1Ý„€– ìs:„€ƒ€—#„nxvDyìì}„&~SD'_«ì'^õšD'_«ìì:#ðš2ôí˜J.V ``` Input is a single lowercase string. Implements all 7 operators. [Try it online](https://tio.run/##yy9OTMpM/f/f8PDcw02PGuY9alrzqGGywuE1xVYQ3rFJYKEpykBuXkWZS@XhNYfX1AI5anXBLurxh1YfXqMed3jr0YVQzuE1VsqHNxxdaHR4y@G1p@d46YUBDVfIyy8C4hIFA4XEvBQFQwUg11ChIg9M5YGEDBQqYEoA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf8PDcw83PWqY96hpzaOGyQqH1xRbQXjHJoGFpigDuXkVZS6Vh9ccXlML5KjVBbuoxx9afXiNetzhrUcXQjmH11gpH95wdKHR4S2H156e46UX9l/nv6FCXn6RgiEXhM7LL1EwQGYrJOaloMpCRBTQNSEJK1TkEZZVyAMJGRClSKECpgQA). **Explanation:** ***Step 1:*** Replace the `not 1`/`not 0` with `0`/`1` respectively: I.e. `1 nor not 0 and 1 or 1 xnor 1 nand 0 xor not 0` is converted to `1 nor 1 and 1 or 1 xnor 1 nand 0 xor 1`. ``` 1Ý # Push list [0,1]  # Bifurcate it (short for Duplicate & Reverse copy): [1,0] „€– # Push dictionary string "not " ì # Prepend it in front of both: ["not 1","not 0"] s # Swap so the [0,1] is at the top of the list again : # Replace all ["not 1","not 0"] with [0,1] in the (implicit) input ``` ***Step 2:*** Replace all other operations `xnor`/`xor`/`nand`/`nor`/`and`/`or` with `^_`/`^`/`&_`/`~_`/`&`/`~` respectively: I.e. `1 nor 1 and 1 or 1 xnor 1 nand 0 xor 1` is converted to `1 ~_ 1 & 1 ~ 1 ^_ 1 &_ 0 ^ 1`. ``` „€ƒ€— # Push dictionary string "and or" # # Split it on spaces: ["and","or"] „nx # Push string "nx" v # Loop `y` of its characters: D # Duplicate the list at the top of the stack yì # Prepend the current letter to each string in the list ì # Prepend-merge the lists together } # Stop the loop. We now have the list: # ["xnand","xnor","xand","xor","nand","nor","and","or"] „&~ # Push string "&~" S # Convert it to a list of characters: ["&","~"] D # Duplicate it '_« '# Append "_" to each: ["&_","~_"] ì # Prepend-merge it: ["&_","~_","&","~"] '^ '# Push "^" õš # Convert it to a list, and prepend an empty string: ["","^"] D # Duplicate it '_« '# Append "_" to each: ["_","^_"] ì # Prepend-merge it: ["_","^_","","^"] ì # Prepend-merge it: ["_","^_","","^","&_","~_","&","~"] : # Replace all ["xnand","xnor","xand","xor","nand","nor","and","or"] # with ["_","^_","","^","&_","~_","&","~"] ``` `&~^` are builtins for bitwise AND, OR, and XOR respectively. And `_` is the `==0` builtin (which converts `0` to `1` and vice-versa). ***Step 3:*** Convert it to Reverse Polish notation: I.e. `1 ~_ 1 & 1 ~ 1 ^_ 1 &_ 0 ^ 1` is converted to `1 1~_1&1~1^_0&_1^`. ``` # # Split the string by spaces ðš # Prepend a leading " " to the list 2ô # Split the list into parts of size 2 í # Reverse each pair ˜J # Flattened join everything together ``` ***Step 4:*** Execute/evaluate it as 05AB1E code, and output the result: I.e. `1 1~_1&1~1^_0&_1^` results in `0`. ``` .V # Evaluate/execute it as 05AB1E code # (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 `"not "` and `„€ƒ€—` is `"and or"`. [Answer] # [Python 2](https://docs.python.org/2/), score 15.714 (~~132~~ ... ~~114~~ 110 bytes, 7 operators) Input is a single string with lowercase operators. ``` b=c=d=49 for a in input().replace('t ','a').split():a=hash(a);c,d=[a|d,a&d,a^d^1][b%65%3]^b%45,c;b=a print~c&1 ``` [Try it online!](https://tio.run/##jU7LisMwDLz7K3RJnUAozfYBbfGxvfayt9KAbKskbLCN6rIpLPvrWYcuZR@XgoRGMyM04RYb714G4y0pKeWglVFWLdbi7BkQWpcqXGNeTJlCh4ZyGUGWEmUxvYSuTcoGVYOXJsdia0qrjvhhS5ykrm1dnY46Wy2z@anW2WJZmq1WKAK3Ln6aSTWkl0K8N21H8MpX2giAyLdxAFBPBsZgYsSGQoTdYb9j9nw3aCZ8G2QFLmWtpPhGzkeY/d4Anf3ruHPw//SHAL17Rgc3UrMnbdA/Qn4B "Python 2 – Try It Online") The code uses the following numbers produced by Python 2's `hash` function: ``` +--------+----------------------+-----+--------+--------+ | string | h=hash(string) | h&1 | h%65%3 | h%45&1 | +--------+----------------------+-----+--------+--------+ | and | 1453079729200098176 | | 0 | 0 | | nand | -4166578487142698835 | | 0 | 1 | | or | 14208085359128317 | | 1 | 0 | | nor | 5261102140395498078 | | 1 | 1 | | xor | -5999452984713080668 | | 2 | 0 | | xnor | 485507670233933377 | | 2 | 1 | | | | | | | | 0 | 6144018481 | 1 | | | | 1 | 6272018864 | 0 | | | | noa0 | -4166584487129698722 | 0 | | | | noa1 | -4166584487129698721 | 1 | | | +--------+----------------------+-----+--------+--------+ ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~43~~ 36 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ÷ 6 = 6 Thank you user41805 for the idea of combining definitions that are negations of each other and to tsh for noticing stray spaces. ``` DNAN←~DNA←∧ RON←~RO←∨ ROX←~RONX←= ⍎⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///38XP0e9R24Q6IA2kHnUs5wryBwsE@YP5K4D8CAjfD0Tbcj3q7XvUs/d/GkgayOxqftS75lHvlkPrjR@1TXzUNzU4yBlIhnh4Bv9PU1A3VPDzD1IwVOfCzlZw9HPBJqKAXSFYWCHCj7Csgh9IyIAoRQoRYPMA "APL (Dyalog Unicode) – Try It Online") Since APL is right-to-left, we define the functions with reversed names, then reverse the expression (`⌽`) and execute it (`⍎`). --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~57~~ 50 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ÷ 7 = 7.14 Thank you user41805 for the idea of combining definitions that are negations of each other and to tsh for noticing stray spaces. ``` DNAN←~DNA←∧ RON←~RO←∨ ROX←~RONX←= TON←{⍵ ⍵⍵~⍺⍺} ⍎⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///38XP0e9R24Q6IA2kHnUs5wryBwsE@YP5K4D8CAjfD0TbcoWA5asf9W5VAGIgqnvUuwuIarke9fY96tn7Pw2kEcjsan7Uu@ZR75ZD640ftU181Dc1OMgZSIZ4eAb/T1NQN1Tw8w9SMFTngrP9/EMUDND5Co5@LpiqIKIK2AxAklKI8CNOhYIfSMiAaIUKEXDnAgA "APL (Dyalog Unicode) – Try It Online") Since APL is right-to-left, we define the functions with reversed names, then reverse the expression (`⌽`) and execute it (`⍎`). NOT (`TON`) requires special treatment. We define it as a dyadic operator (`{`…`}`) because this makes it bind stronger to its operands. We then negate the left (original right) operand (`~⍺⍺`) and apply the right operand (`⍵⍵` — originally on its left) with the right argument (`⍵` originally from its left) as left argument. The arguments' sides doesn't matter since all functions are commutative. [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ÷ 1 = 1 ``` e ``` [Try it online!](https://tio.run/##y0osKPn/P/X//2hDHQUlRz8XJR0FJFYsAA "Japt – Try It Online") Implements only `and`. Works by checking if every element in the input has a truthy value. [Answer] # [FEU](https://github.com/TryItOnline/feu), 33 bytes, 2 operations, score 16.5 ``` m/NOT 0/1/NOT 1/0/.*1.*/1/[^1]+/0 ``` [Try it online!](https://tio.run/##S0st/f8/V9/PP0TBQN8QTBvqG@jraRnqaQH50XGGsdr6Bv//Gyr4BymAZQE "FEU – Try It Online") Implements `NOT` and `OR` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 84 bytes, score 12 ``` NOT0 1 NOT1 0 ^(0A|1NO|(0NA|1O))[A-Z]+. $#2 }`^(1A|0O|0XO|1XN)[A-Z]+ }`^.[A-Z]+ NOT ``` [Try it online!](https://tio.run/##jYyxCsJQDEX3fEVAhRSxJP7BA@cEpMNDsT4HBxcH6Ri//flKW2hddLqXc27yuneP5y1viJqE6ZrVGgaBEgIMLXFwUXNiLcWq6hx2p8u2hvVqD@/UkgRnc47mEnW00Jt67OVTzoJqRxQYsiDkecegh6UdCH4fzTBG/W1Re8R/jTBOkw8 "Retina 0.8.2 – Try It Online") Link includes test suite that deletes spaces from the input for the convenience of the user. Explanation: ``` NOT0 1 NOT1 0 ``` Handle the NOT operator. ``` ^(0A|1NO|(0NA|1O))[A-Z]+. $#2 ``` `0 AND` and `1 NOR` are always `0`, while `0 NAND` and `1 OR` are always `1`, regardless of the RHS. ``` }`^(1A|0O|0XO|1XN)[A-Z]+ ``` `1 AND`, `0 OR`, `0 XOR` and `1 XNOR` leave the RHS unchanged. Repeat the above operations until an operation that inverts the RHS is reached. ``` }`^.[A-Z]+ NOT ``` Replace this operation with a `NOT` and loop around to start processing operations again. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ÷ 1 = 2 ``` ~⍲ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v@5R76b/aY/aJjzq7XvU1fyod82j3i2H1hs/apv4qG9qcJAzkAzx8Az@n6ZgoKCemJeiDqcNuRBihkhihljUGaKrAwA "APL (Dyalog Extended) – Try It Online") `⍲` (nand) returns 1 if and only if argument has a 0 anywhere (it ignores all other data) `~` negates that --- # [APL (dzaima/APL)](https://github.com/dzaima/APL), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ÷ 1 = 2 ``` 1∊ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsZ/w0cdXf81/6cpGCio5xepwykuuIghQsQQQ40hqpp/@QUlmfl5xf91iwE "APL (dzaima/APL) – Try It Online") Simply asks *is there any 1 in the argument?* [Answer] # [Perl 5](https://www.perl.org/), 86 bytes / 7 operators = 12.29 ``` s/not/!/g;s/\d//;$\=1*$1;$\=eval"$\ $_"=~s/(.*?[^a])n(.*)/!($1$2)/r for/.*?\d/g}{$\|=0 ``` [Try it online!](https://tio.run/##FY3LCsMgFER/xYS7iIHkaiGbBMkPtMuualuEpkEQFZVS6OPTa83qDHMYxi/BDDlHtC5hhesUUd4QJ5CCt8A3Lg9lapAErrX4Rmz6dj5d1JnakihWDXDYUQzk7gIWV@br5wXyLVjOnLhAGHnagvJA2M/5pJ2NuTvsdUzjeEzaCK902KqhZ5zlzv8B "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/), 9 bytes / 3 operators (`or`, `xor`, `not`) = 3 ``` $_=0|eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tagJrUsMef/f0OFxLwUhbz8EgUDhYr8IgVDBRDxL7@gJDM/r/i/bgEA "Perl 5 – Try It Online") [Answer] # JavaScript (ES7), 77 bytes / 7 operators = 11 Expects a string with no separator, such as `"1NORNOT0"`. ``` f=s=>1/s?s:f(s.replace(/..*?\d/,s=>10142470953/2**(parseInt(s,36)%873%34)&1)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbY1s5Qv9i@2CpNo1ivKLUgJzE5VUNfT0/LPiZFXwcka2BoYmRibmBpaqxvpKWlUZBYVJzqmVeiUaxjbKapamFurGpsoqlmqKn5Pzk/rzg/J1UvJz9dI01DydDPP8hQSVNTAR/Q11cw4MKi0c8/xACvXnwaHf1ccFtMSCNORwM1GhLQGIHVy8Rq9ANyUDxNksYIpEAD@fE/AA "JavaScript (Node.js) – Try It Online") Or try [all possible sub-expressions](https://tio.run/##ZdDLCoJAFAbgfU9xNjUzaqOm3bEIatHGIFoE1WKysQviiEfaRM9uI12hzfnhfD8zcC7iKjDKz1nRTNVBlmUcYDBybRzjIKbIc5klIpLU5twYbw@2Vanj@i2/6/Tbnt0yDJqJHOU8LShaXofVe12v7vms4TJWDjdkEk6JBWSxrOb6GeFrGb62Ve54rPKZiE5UZRCM4FYD2JBna/WjqSrerAuOBe7XxFf@bP9rAAgBCDBBf2ZC9aYJ@@FHI5WiSiRP1JGiJqLbRKc@CWPv2p3VPqHHnZUP). ### How? We use a recursive function to simplify the input string `s` until we get a single digit. When this happens, `1/s` is either `1` or `Infinity`, which are both truthy. As long as `s` still contains at least one operator, we use the following regular expression to isolate the next sub-expression: ``` /..*?\d/ . a single character (must be 0 or 1) .*? followed by several characters, non-greedily \d followed by a digit ``` We use this hash function (which was brute-forced) to get the result of the sub-expression and replace it in `s`: ``` 10142470953 / 2 ** (parseInt(s, 36) % 873 % 34) & 1 ``` [Answer] # SimpleTemplate, 361 bytes ÷ 4 operators = 90.25 It is a very big piece of code, but was very challenging! ``` {@fnP S}{@fnT.AND a,b}{@ifa}{@ifa is equalb}{@return1}{@/}{@/}{@return"0"}{@/}{@fnT.OR a,b}{@incbyb a}{@ifa}{@return1}{@/}{@return"0"}{@/}{@fnT.XOR a,b}{@ifa is equalb}{@return1}{@/}{@return"0"}{@/}{@whileS matches"@([01])(AND|X?OR)(NOT)?([01])@"P}{@callT.[P.2]intoR P.1,P.4}{@ifP.3}{@setT 1,0}{@setR T.[R]}{@/}{@callstr_replace intoS P.0,R,S}{@/}{@returnS}{@/} ``` This implements the AND, OR, XOR and NOT operators. This was entirely implemented **without** using `AND`, `OR` and `XOR`, as those don't exist in my language, at all! It was even more challenging due to a bug in the compiler, where `{@return 0}` returns null ... :/ 6 bytes right there ... --- You can try it on: <http://sandbox.onlinephpfunctions.com/code/cb1855c48e83924bd7c81f4cda95f032c23b4abe> --- **Usage:** Simply call the function P and pass a single string without spaces. Returns either 0 or 1, or the whole string for invalid inputs. Example: ``` {@call P into result "1ORNOT0"} {@echo result} ``` --- **Ungolfed:** Since this is a massive mess, I've also prepared an human readable version: ``` {@fn parse string} {@fn this.AND a, b} {@if a} {@if a is equal to b} {@return 1} {@/} {@/} {@return "0"} {@/} {@fn this.OR a, b} {@inc by b a} {@if a} {@return 1} {@/} {@return "0"} {@/} {@fn this.XOR a, b} {@if a is equal to b} {@return 1} {@/} {@return "0"} {@/} {@while string matches "@([01])(AND|X?OR)(NOT)?([01])@" pieces} {@call this.[pieces.2] into result pieces.1, pieces.4} {@if pieces.3} {@set tmp 1, 0} {@set result tmp.[result]} {@/} {@call str_replace into string pieces.0, result, string} {@/} {@return string} {@/} ``` This works exactly the same way, except the function is called "parse". --- --- **Alternative**: Below is a SUPER boring one that has EVERYTHING pre-calculated, but has a score of 276/7 = 39.428571428571... (428571 is recurring). ``` {@fnP S}{@setL.AND"001"}{@setL.NAND"110"}{@setL.OR"011"}{@setL.NOR"100"}{@setL.XOR"010"}{@setL.XNOR"101"}{@whileS matches"@([01])(N?AND|X?N?OR)(NOT)?([01])@"P}{@ifP.3}{@setT"10"}{@setP.4 T.[P.4]}{@/}{@incbyP.4 P.1}{@callstr_replace intoS P.0,L.[P.2].[P.1],S}{@/}{@returnS}{@/} ``` It implements all operators, but ... It is kinda cheating... Below it the ungolfed version: ``` {@fn parse string} {@set table.AND 0, 0, 1} {@set table.NAND 1, 1, 0} {@set table.OR 0, 1, 1} {@set table.NOR 1, 0, 0} {@set table.XOR 0, 1, 0} {@set table.XNOR 1, 0, 1} {@while string matches "@([01])(N?AND|X?N?OR)(NOT)?([01])@" pieces} {@if pieces.3} {@set tmp 1, 0} {@set pieces.4 tmp.[pieces.4]} {@/} {@inc by pieces.4 pieces.1} {@set values table.[pieces.2]} {@call str_replace into string pieces.0, values.[pieces.1], string} {@/} {@return string} {@/} ``` [Answer] # [sed](https://www.gnu.org/software/sed/), 8 bytes ÷ 1 = 8 ``` /0/c0 c1 ``` [Try it online!](https://tio.run/##K05N0U3PK/3/X99AP9mAK9nw/39DhcS8FAUDMInCBgA "sed – Try It Online") Implements only `and`. ## Explanation ``` /0/c0 # Set contents of line to 0 if line contains 0 c1 # Otherwise set contents to 1 ``` [Answer] # Haskell, \$225 \div 4 = 56.25\$ ``` b(_:'A':'0':s)=b('0':s) b(c:'A':_:s)=b(c:s) b(_:'O':'1':s)=b('1':s) b(c:'O':_:s)=b(c:s) b('N':'0':s)=b('1':s) b('N':_:s)=b('0':s) b('0':'X':'0':s)=b('0':s) b('1':'X':'1':s)=b('0':s) b(_:'X':_:s)=b('1':s) b x=x f=(b.map(!!0)) ``` Defines a function `f`, which given a list of the format `["1","AND","0"]` returns either `"1"` or `"0"`. Implements `AND`, `OR`, `NOT`, and `XOR`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes ÷ 6 = 10.33 ``` Boole@ToExpression[Capitalize@#~StringRiffle~"~"]/.a:0|1:>a>0& ``` [Try it online!](https://tio.run/##PYvNCoJAFEZf5TKCKyndGokUCUWLSHfDLIacqQvjXNEJpB9f3Uyp3cc536mku6lKOrzIQcN62BAZlRa06@pGtS2S5VtZo5MGHyr1@tw1aK9n1NqonvVMLBcyDl9RnMgk9IfTaB0vaL5xL4C9re8uo6YSAbAYWACae0KAD8sUMjLlEVvHD4Q2gLnKa4OOP1kElhqIxoJJW87jB7q/sl8XTmxCbyFWwwc "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list of lowercase strings as input and returns 0 or 1 as output. Supports every operation except NOT. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 87 bytes ÷ 7 = 12.43 ``` Boole@ToExpression@StringReplace[Capitalize@#~StringRiffle~"~","t~"->"t@"]/.a:0|1:>a>0& ``` [Try it online!](https://tio.run/##PYtPS8NAEMW/yjCBnlabXCOGpWJB8SC2t2UPQ7vRgc3OkowQ/JOvHtNWPTze473360jfQkfKB5pbuJ03IjHYvdyPuQ/DwJLsTntOry8hRzoEd0eZlSJ/BFtMvxO3bQwTTmhQJ7xqUC369TXV5VdVN9SUq/l5Oarby4VwhYGHlN91K33nDWANaKB1hfewgrWFrcTjEw/qHoWTgQu1y5HVfWIFSfpFCuVCIaUjVKewlGcf019Kp@18Gv@Jb@9v5h8) Similar to the previous solution, but it also supports NOT. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ÷ 1 = 15 ``` Boole@*FreeQ[0] ``` [Try it online!](https://tio.run/##RcqxCsIwGEXhV7kkUFQCVrspQnAodFPsFjIE/VsLTVLSdCp99pjN7eNwrIlfsiYOb5M63NLd@5HkoQ5ET1Xq9AiDi6r1r5jRKy7QuGmJtQ9WC7ALmECnuNYocJTYrflgxn1y5uc/qw3FHlJKtMs00qzWUuC0CVT6mn4) Function. Takes a list of strings and integers as input and returns 0 or 1 as output. Only supports AND. [Answer] # [JavaScript (V8)](https://v8.dev/), 141 bytes ÷ 7 operators, score 20.14 ``` f=i=>'01'[i]||f(i.replace(/NOT./,n=>'10'[n[3]]).replace(/(.)(..)\D*(.)/,(_,a,o,b)=>({AN:a&b,OR:a|b,XO:a^b,NA:a&b^1,NO:(a|b)^1,XN:a^b^1})[o])) ``` [Try it online!](https://tio.run/##jVXxb5pAFP65/hXPxnh3G0PZfthCZxvTdsmSBhZdMhKK66Fg6QgQwG6L8re7d6ACCl1NlPO77/vee8fduyf@zJN57EXpu@dP26078kaXZKgQ07M2G5d6cuxEPp87dKDp3@WBFOC0MiRmYH6wLFbOUplRWWb3N29wNJDoT4lLoWSz0SVdjzWV921Jn6h8Y0uGrvKZLWljAc4USdNVijjDoaGJqZmSMTO0GNu6q2CeemEAqZOk1AuiVSqB8ydy5qmz0Fcp/mew7gB@5mGQpBDmGIzALdjsojK5F@I0XQ9VMiQSKCpR8OFyP3FUyKE0XomhQjCLeiyr6hbxJEGn0nQ02oUvWaHvyH64pA@9dU6/AgLwbTydEsAIBnwZf70jGeSpotd5b50Ps/OHXeKeC7QrpPsyj52JAPY5qKRcHazjb@SE7gHYOTYa8Hm64r4KgAZFDQd58XcnzvLf2ElXcZAvwEUn63R8J4XfYfzLC5Z6JNbExIXqmDnXJBzG2g3Y6Nw5o1wCm8HoEjj0wbakA0efNFA2NYrRyJnVOFpTrC7No7Eqr8FL0DZ1mtHGm9V5Iioej8Yqu0dlNvM2dZ7RSpzViVpb6KLo7knVbdzNEdd4iTxrM85XgrfZY0K8XSUW51hKa1qGw/8ZFImfpkAbrBgWwtnrDNu21kvOTbvuZfvWF/@KQPutYcluGN/y@SOlZhhhb8Mmakng5T5FFxEnVhxfZzH2fTywouUVJxylQMU0Bzz85hA7pMVK1K6iZUcqvfqjolfj1JmYCaPyiuCDpYTJloAtALsCgAAIYdJeLnIvFqFzVutBojFWovbBg8/wkVX6kBytkkcaRijL8Nup9eP74EdBBD1yYi7umEQF2ltX9L4TLNPHjIleXBVXKE@hF1ByHxAGbyF/7gKl2GMXzl3uIG4jOQ2naYwqyna@KKA12Avm/mrhJJS4FP2u4D3eEcOTzK/RFwpjpkJvXcbJHo7JZHqtT27FrVDJZgAnNR7rMIEhbschvgjYjZXdWKngSoEfLY8Q6JODVp8cpCWq5GiD0KgojYq0givGXrz9Bw "JavaScript (V8) – Try It Online") Takes input as a string with capitalised operators and no padding, like `0AND1OR0`. Recursively calculates the next value based on the first two characters of the operator. (not before replacing `NOT`s with their counterparts) [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 36 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ÷ 7 ≈ 5.14 ``` e/..*?\d/@1&#e4#÷0953÷2pXn36 %873%34 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=ZS8uLio/XGQvQDEmI2U0I/cwOTUz9zJwWG4zNiAlODczJTM0&input=IjFOT1JOT1QwQU5EMU9SMVhOT1IxTkFORDBYT1JOT1QwIg) [Try all testcases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LW0&code=ZS8uLio/XGQvQDEmI2U0I/cwOTUz9zJwWG4zNiAlODczJTM0&input=WyIxTk9SMSIsICIxTk9STk9UMCIsICIxTk9STk9UMEFORDEiLCAiMU5PUk5PVDBBTkQxT1IxIiwgIjFOT1JOT1QwQU5EMU9SMVhOT1IxIiwgIjFOT1JOT1QwQU5EMU9SMVhOT1IxTkFORDAiLCAiMU5PUk5PVDBBTkQxT1IxWE5PUjFOQU5EMFhPUk5PVDAiXQ) [Try all possible sub-expressions](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LW0&code=ZS8uLio/XGQvQDEmI2U0I/cwOTUz9zJwWG4zNiAlODczJTM0&input=WyIwQU5EMCIsICIwQU5EMSIsICIxQU5EMCIsICIxQU5EMSIsICIwQU5ETk9UMCIsICIwQU5ETk9UMSIsICIxQU5ETk9UMCIsICIxQU5ETk9UMSIsICIwT1IwIiwgIjBPUjEiLCAiMU9SMCIsICIxT1IxIiwgIjBPUk5PVDAiLCAiME9STk9UMSIsICIxT1JOT1QwIiwgIjFPUk5PVDEiLCAiMFhPUjAiLCAiMFhPUjEiLCAiMVhPUjAiLCAiMVhPUjEiLCAiMFhPUk5PVDAiLCAiMFhPUk5PVDEiLCAiMVhPUk5PVDAiLCAiMVhPUk5PVDEiLCAiME5BTkQwIiwgIjBOQU5EMSIsICIxTkFORDAiLCAiMU5BTkQxIiwgIjBOQU5ETk9UMCIsICIwTkFORE5PVDEiLCAiMU5BTkROT1QwIiwgIjFOQU5ETk9UMSIsICIwTk9SMCIsICIwTk9SMSIsICIxTk9SMCIsICIxTk9SMSIsICIwTk9STk9UMCIsICIwTk9STk9UMSIsICIxTk9STk9UMCIsICIxTk9STk9UMSIsICIwWE5PUjAiLCAiMFhOT1IxIiwgIjFYTk9SMCIsICIxWE5PUjEiLCAiMFhOT1JOT1QwIiwgIjBYTk9STk9UMSIsICIxWE5PUk5PVDAiLCAiMVhOT1JOT1QxIl0) A direct port of @Arnauld's [answer](https://codegolf.stackexchange.com/a/207143/91267) to Japt ## Explanation ``` e/..*?\d/@1&#e4#÷0953÷2pXn36 %873%34 e // Repeatedly replace /..*?\d/ // the regex /..*?\d/g with output of @ // a function which takes the match as arg named X 1&#e4#÷0953÷2pXn36 %873%34 // and returns 1 & 10142470953 / 2 ** (parseInt(X, 36) % 873 % 34) ``` The expression `1 & 10142470953 / 2 ** (parseInt(X, 36) % 873 % 34)` was brute-forced by @Arnauld [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 130 bytes / 1 operator = 130 `+>>+<,[------------------------------------------------[<->[-]]<[>>[-]<<-]><+>,]>++++++++++++++++++++++++++++++++++++++++++++++++.` [Try it online!](https://tio.run/##nZJdSyMxFIavk1/x3mmprjPgxaLDgKwfFJYK9c6ikGYyNkyaUzKZ9ePPd09SxbruhRjCMJyc95znfCyCsr4ddLfZ3JgIZ9oIbZxDJJTYH3rToKUATT4GciM5rmWJAoUE7qVMmmAflp9F/BuTybasH3wDhWIk63GV5eVW/ptojbgMNDwsYf16iFDs6oi6nLU4xeRVf4LG6GBWxu9mlAdzjvcL5VECQg4qboZFDEpHHP9EG2gF1Wtrt/GlOEwH3/hKwZlWHDMlE2/JmC@Xbnt48i8m0C7ph36yai6FOP/wyoaKQwu@V4SF0l1yXdmmcSY3YxGM6kDcGmpTZ9bsWc8P76TgO7nE9Hp6ezG7lqJIfd2i3eeXrbncNWfedyiGLk/QfxpigX2XR8MkqjPoh2Bg416PVGDGmqAhv8fz0to2XIxy7hn0x4TW0eNIioqLrRNnVSXW@kusRd6sV9KZ6Xc3kkPy7v1bzsyoBt48sc9SpaGbcJp2LnM@qv5tef7TxQMp72Qtx@ngG98fm02Js@l5auFf "brainfuck – Try It Online") Link is for a readable, commented version. Only implements `AND`. Although technically all it does is print `1` unless there is a `0` in your input, in which case it prints `0`. It might be possible to shorten this by replacing the spots where I add/subtract 48 times, but I'm lazy, so I'm going to leave it as is. [Answer] # [Scala](http://www.scala-lang.org/), ~~183 bytes~~ 164 bytes / 7 ops = ~23.43 ``` "OR".+(_).split("(?<=\\d)")./:(0>1){(b,o)=>val s=o.replace("NOT","") val c=s!=o^(o.last>48) s.count(_==78)==1^(if(s toSet 65)!(b&c)else if(s toSet 88)b^c else b|c)} ``` [Try it online!](https://tio.run/##jY9Pa4NAEMXvforJEsoMDVahfyR0LSm91kDSQw7BsK6rWBZXsttSsH52axJahOaQ27zfezzeWCm06E32rqSDV1HVoL6cqnMLi6aB1vM@hYZyDmu3r@oSeAzPxmglauA9W66Yf4078m2jK4cMnx75dpsTI/9mjkEcUovZzBCPDy2WG3@vGi2kQpYs39iMMTr2S24n3KRofC2si28j8qwvzUftcMf5Q0SchylWBVpwZq0c3N/RBLMrSUpbBSMjiihLpXfE2bekrs9VAYP/@wEBh2Y4nK7Rsqkd5LQt0VI3bPEKZCEkyxWEg/oTw1YI/gFYJC9ncicMZztGHmySCyOQHFBweRI2o81e1/8A "Scala – Try It Online") The operators are uppercase (whitespace doesn't matter), and the output is a `Boolean`. ]
[Question] [ Who doesn't love a good fractal? The [Sierpinski Carpet](http://en.wikipedia.org/wiki/Sierpinski_carpet) is a classic example of a fractal. To complete this task, you will be required to generate a carpet of type \$n\$ and print the resulting image to the `stdout` (see example below for formatting) \$n\$, representing the level carpet. Steps can be found on this [Wikipedia](http://en.wikipedia.org/wiki/Sierpinski_carpet) article. This value will be taken from `stdin` or equivalent. For example, an input of 4 would produce a level 4 carpet: ``` ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ``` An input of 3 would produce a level 3 carpet: ``` ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ``` An input of 2 would produce a level 2 carpet: ``` ■ ■ ■ ■ ■ ■ ■ ■ ``` And a input of 1 would produce a level 1 carpet (just a square): ``` ■ ``` Note the spaces between the columns. The idea is to use the ■ character for blocks and space for gaps The line starts with the ■ character. As always, the smallest solution wins by character count (due to non-standard characters). Alternatively, # can be used instead of the ■ character in languages that do not support Unicode. [Answer] ## CJam, ~~38~~ ~~37~~ ~~31~~ ~~30~~ 28 characters Oh well, we're counting by characters, so let's do some Unicode unpacking: ``` "B胷맋풽巓뱖ᮨ㣙¬䙧੥墱륋청"2G#b129b:c~ ``` [Test it here.](http://cjam.aditsu.net/) Just put the desired level into the input field. ### Explanation After base conversion, this is ``` 3li(#,{3b1f&2b}%_f{f{&S9632c?S}N} ``` which is the same as the following, just with the Unicode character written as `9632c`: ``` 3li(#,{3b1f&2b}%_f{f{&S'■?S}N} ``` This code is based on the following observation: if we look at the coordinates *(x,y)* of each cell, then we get an empty cell, whenever both *x* and *y* have a `1` at the same position in their base-3 representation. If you think about it, the small-scale repeating pattern is the significant base-3 digit, then the next more significant digit governs the next larger-scale repetition and so on. ``` 3 "Push a 3 on the stack."; li( "Read input, convert to integer, decrement."; # "Raise to that power. This yields the dimensions."; , "Turn into a range array."; { }% "Map the block onto the array."; 3b "Convert to base 3."; 1f& "Bit-wise AND each digit with 1."; 2b "Convert to base 2."; _ "Duplicate this list."; f{ } "Map this block onto one list, with the second list as an additional parameter."; f{ } "Map this block onto the second list, with the first list's current element as an additional parameter."; "I.e. this iterates over all coordinate pairs."; & "Bitwise AND to check that the base-3 representations had a 1 in the same position."; S'■? "Select the right character."; S "Push a space."; N "Push a newline"; ``` The contents of the resulting array are printed automatically. Thanks to Dennis for shaving off three bytes. [Answer] # Matlab (113)(110)(99)(85) You can try it [here](http://lavica.fesb.hr/octave/octave-on-line_en.php) (You'll have to replace `input('')` with your desired input.) Now 99 thanks to feersum! And now down to 85 thanks to RTL! Golfed: ``` a=ones(3);a(5)=0;c=1;for i=2:input('');c=kron(c,a);end;disp(char(kron(c,[1,0])*3+32)) ``` Ungolfed: ``` a=ones(3);a(5)=0;c=1; %creating the template / anchor for i=2:input(''); c=kron(c,a); %recursive iterations end; disp(char(kron(c,[1,0])*3+32)) ``` ``` d=[c,c]*0; %this is all just for adding the additional spaces d(:,1:2:end)=c; disp(char(d*3+32)); %converting to spaces (32) and # (35) ``` Explanation: I am abusing the kronecker product for this task. (It is a special product defined for two each arbitrary sized matrices. Example: ``` A = [1,2] is a 3x2 matrix, B is a nxm matrix. [3,4] [5,6] ``` Then ``` kron(A,B) = [1*B , 2*B] is a 2n x 2m matrix. [3*B , 4*B] [5*B , 6*B] ``` So heres an example for n=5 (In the old counting method it's 4); ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] # Haskell, ~~114~~ 108 ``` s 1=["# "] s n=k j++k(map(>>" ")j)++k j where j=s$n-1;k i=j%i%j (%)=zipWith(++) main=interact$unlines.s.read ``` [Answer] # Perl 5: 68 characters *n* on stdin. ``` #!/usr/bin/perl -l //,print map/2/?" ":"■ ",map$_+$',@,for@,=grep!/[24-9]/,0..3x<>/10 ``` A decimal coded ternary representation of the list of coordinates is first generated in `@,` (name chosen so there is no need for space between `@,` and `for`) using digits 0, 1, and 3. Now adding x and y coordinates in the decimal domain will have a 2 in the result if and only if there were two ones at matching positions. `//` is used to propagate the default variable `$_` from the outer loop (`for`) to the postmatch variable `$'` when it is shadowed by the default `map` variable in the inner loop. [Answer] # Python – 100 ``` r=range(3**~-input()) for i in r:print" ".join("# "[any(i/3**k%3==j/3**k%3==1for k in r)]for j in r) ``` [Answer] # Racket ~~230~~ ~~229~~ ~~225~~ 220 Not Racket's finest hour for golfing. Golfed: ``` (define(s n)(letrec([t(λ(x y)(if(or(= x 0)(= y 0))"■"(if(=(modulo x 3)(modulo y 3)1)" "(t(floor(/ x 3))(floor(/ y 3))))))][i(expt 3(- n 1))])(for-each displayln(for/list([r i])(string-join(for/list([c i])(t r c))" "))))) ``` Ungolfed: ``` (define (s n) (letrec ([t (λ (x y) (if (or (= x 0) (= y 0)) "■" (if (= (modulo x 3) (modulo y 3) 1) " " (t (floor (/ x 3)) (floor (/ y 3))))))] [i (expt 3 (- n 1))]) (for-each displayln (for/list ([r i]) (string-join (for/list ([c i]) (t r c)) " "))))) ``` [Answer] # C: 123 118 111 104 characters Based on a similar idea as my perl solution. After adding some spaces: ``` m=0x55555555; x; main(n){ scanf("%d",&n); n=1<<2*--n; for(x=n*n;x--;) printf(x&x/2&m?"":"%c%c",x&x/n&m?32:35,x&n-1?32:10); } ``` Uses ternary system coding each digit with 2 bits. Illegal values (having two ones in odd-even position) are filtered with `x & (x>>1) & 0b01010101`. Both coordinates are stored in one value, so checking the pixel color is down to `x & (x >> 2 * n) & 0b01010101`. `n` is stored as a power of 2 for convenience. ## Edit Replaced `define` with a simple constant `m`. ## Edit 2 `0x5555555` mask can be represented with `(1LL<<32)/3`, but we only need `n` of those bits so `n/3` is sufficient. ``` x; main(n){ scanf("%d",&n); n=1<<2*--n; for(x=n*n;x--;) printf(x&x/2&n*n/3?"":"%c%c",x&x/n&n/3?32:35,x&n-1?32:10); } ``` ## Edit 3 Minor tweaks. One 2 char gain relying on scanf being executed before the loading value of `n` for the execution of `--n`. The eol can only follow `#`, duh. ``` x; main(n){ n=scanf("%d",&n)<<2*--n; for(x=n*n;x--;) x&x/2&n*n/3||printf(x&x/n&n/3?" ":x&n-1?"# ":"#\n"); } ``` [Answer] # Mathematica, 71 bytes ``` Grid@Nest[ArrayFlatten@ArrayPad[{{0}},1,{{#}}]&,1,#]/.{0->"",1->"■"}& ``` **input** > > 3 > > > **output** [![enter image description here](https://i.stack.imgur.com/uiOLy.jpg)](https://i.stack.imgur.com/uiOLy.jpg) [Answer] # HTML/JavaScript, 205 Chars ## [Obfuscatweet](http://xem.github.io/obfuscatweet/), 205 Chars ``` document.write(unescape(escape('🁳𨱲𪑰𭀾𬰽𙰦𫡢𬱰𞰧𞱮🐴𞱭👍𨑴𪀮𬁯𭰨𜰬𫠭𜐩𞱦𫱲𚁩🐰𞱩🁭𞱩𚰫𛁤𚀧🁢𬠾𙰩𚑻𩡯𬠨𪠽𜀻𪠼𫐻𚑩𩠨𨰨𪐬𪠫𚰩𚑤𚀧𘰧𚐻𩑬𬱥𘁤𚁳𚑽𩡵𫡣𭁩𫱮𘁣𚁸𛁹𚑻𭱨𪑬𩐨𮁼𯁹𚑻𪑦𚁸𙐳🐽𜐦𙡹𙐳🐽𜐩𬡥𭁵𬡮𘀰𞱸👦𚁸𚐻𮐽𩠨𮐩𯑲𩑴𭑲𫠠𜑽𩡵𫡣𭁩𫱮𘁦𚁡𚑻𬡥𭁵𬡮𘁍𨑴𪀮𩡬𫱯𬠨𨐯𜰩𯑦𭑮𨱴𪑯𫠠𩀨𨐩𮱤𫱣𭑭𩑮𭀮𭱲𪑴𩐨𬰫𨐩𯐼𛱳𨱲𪑰𭀾🁳𭁹𫁥🠪𮱦𫱮𭀭𩡡𫑩𫁹𞠢𠱯𭑲𪑥𬠢').replace(/uD./g,''))) ``` ## HTML/JS, 298 Chars Due to how HTML plays with whitespace, a few characters had to be dedicated to the nbsp char. In addition, the default font of most browsers is not Courier, so I had to set it to that, too. About 20 characters worth of styling. If this requires a direct input method, I can add it, but changing the input currently is setting n to a different value. [Demo](http://c99.nl/f/114334.html) ``` <script>s='&nbsp;';n=4;m=Math.pow(3,n-1);for(i=0;i<m;i++,d('<br>')){for(j=0;j<m;)if(c(i,j++))d('#');else d(s)}function c(x,y){while(x||y){if(x%3==1&&y%3==1)return 0;x=f(x);y=f(y)}return 1}function f(a){return Math.floor(a/3)}function d(a){document.write(s+a)}</script><style>*{font-family:"Courier" ``` ## Readable HTML/JS ``` <script> s='&nbsp;'; n=4; m=Math.pow(3,n-1); for(i=0;i<m;i++,d('<br>')){ for(j=0;j<m;) if(c(i,j++)) d('#'); else d(s) } function c(x,y){ while(x||y){ if(x%3==1&&y%3==1) return 0; x=f(x); y=f(y) } return 1 } function f(a){ return Math.floor(a/3) } function d(a){ document.write(s+a) } </script> <style> *{font-family:"Courier" ``` [Answer] # CJam, ~~38~~ ~~35~~ ~~32~~ 31 characters ``` "■ ""՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~ ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Example run ``` $ cjam <(echo '"■ ""՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~') <<< 3; echo ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ``` ### How it works ``` "՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~ ``` converts the Unicode string from base 60,000 (`6e4b`) to base 128 (`128b`), casts to Character (`:c`) and evaluates the resulting string (`~`). As a result, the following code gets executed: ``` "■ " " C := '■ ' "; li( " J := int(input()) - 1 "; { }* " for I in range(J): "; z]A* " T := [zip(C)] * 10 "; ):, " U := pop(T) "; Sf* " V := [ ' ' * len(u) : u ∊ U ] "; 4\t " U[4] := V "; 3/{:+z~}% " C := { c : c ∊ zip(concat(u)), u ∊ U.split(3) } "; zN* " print '\n'.join(zip(C)) "; ``` [Answer] # Python 3 – ~~116~~ 113 characters **EDIT:** Well, used the trick I don't like too much myself and compressed the code by 3 bytes. Dunno if that's the best possible way, but I'll go with it. ``` exec(bytes('ⱴ㵬❛離₠崧氬浡摢⁡㩺癥污稨✫潦⁲湩琠❝਩潦⁲⁩湩爠湡敧椨瑮椨灮瑵⤨⴩⤱爺瀬氽✨㍛✪Ⱙ⡬嬢⭫‧✠⠪⨳椪⬩⤢琻爽瀫爫昊牯椠椠㩴牰湩⡴⥩','utf-16')[2:].decode('utf-8')) ``` It may contain some unprintable characters, so here's a printable version of the string. ``` 'ⱴ㵬❛離₠崧氬浡摢\u2061㩺癥污稨✫\u206b潦\u2072\u206b湩琠❝\u0a29潦\u2072\u2069湩爠湡敧椨瑮椨灮瑵⤨\u2d29⤱爺瀬氽✨㍛✪Ⱙ⡬嬢\u2b6b‧✠⠪⨳椪⬩⤢琻爽瀫爫昊牯椠椠\u206e㩴牰湩⡴⥩' ``` Not too great, but at least beats some languages. What it expands to: ``` t=['■ '] for i in range(int(input())-1):r,p=[k*3for k in t],[k+' '*(3**i)+k for k in t];t=r+p+r for i in t:print(i) ``` Somewhat ungolfed in case someone can't see how it works: ``` t=['■ '] # iteration 1 for i in range(int(input()) - 1): # do n-1 more iterations r = [k * 3 for k in t] # first & last rows are the last carpet x3 p = [k + ' ' * (3 ** i) + k for k in t] # middle row: last carpet, space, last carpet t = r + p + r # and put them to the new carpet for i in t: # print final iteration print(i) ``` [Answer] ## CJam, 76 characters ``` 3ri(#:M_*,{_M/:I\M%:J;;{I3%1=J3%1=&0X?:X;I3/:I0>J3/:J0>|}gX'■S?1:X;}%M/Sf*N* ``` This is a direct translation of the formula given [here](http://en.wikipedia.org/wiki/Sierpinski_carpet) [Try it here](http://cjam.aditsu.net/) [Answer] # Bash+coreutils, 105 unicode characters Since we're counting characters and not bytes: ``` eval `iconv -tunicode<<<潦⡲眨㌽⨪␨ⴱ⤱琬〽琻眼眪琻⬫⤩笻戠ꂖ昻牯⠨㵸╴ⱷ㵹⽴㭷㹸簰祼〾砻㴯ⰳ⽹㌽⤩笻⠠砨㌥ㄭ籼╹ⴳ⤱簩扼尽簠硼〽紻瀻楲瑮⁦␢⁢㬢⠨╴⵷⭷⤱簩敼档㭯੽|cut -b3-` ``` --- In its decoded form: # Pure Bash, 143 bytes ``` for((w=3**($1-1),t=0;t<w*w;t++));{ b=■ for((x=t%w,y=t/w;x>0||y>0;x/=3,y/=3));{ ((x%3-1||y%3-1))||b=\ ||x=0 } printf "$b " ((t%w-w+1))||echo } ``` Input is taken from command-line args: ### Output: ``` $ ./sierpinskicarpet.sh 3 ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ $ ``` [Answer] # C - 154 Input from stdin. I tried to find a good way to avoid an extra function, but couldn't come up with any. The character count includes only necessary spaces. ``` p(l,x,y){ return l?x/l&y/l&1||p(l/3,x%l,y%l):0; } x,y; main(v){ scanf("%d",&v); v=pow(3,--v); for(;y<v;y++,puts("")) for(x=0;x<v;) printf("%c ",p(v,x++,y)?32:35); } ``` [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` r=input()-1 for i in range(3**r):x,s='# ',' ';exec"x+=[x,s][i%3%2]+x;s*=3;i/=3;"*r;print x ``` [Try it online!](https://tio.run/##DchBDkUwEADQvVNMiJQiQq00PYlYiPR/sxnNqGScvmze4oUnHieNKbFDCnes6m7IficDAhLwRn9fGa25nqW9nCpAtQpAWS9@z6Vxy9frgqUpx7URe2lnLPYfuWYbGCmCpDS9 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’3*Ḷb3ḂḄ&þ`¬ị⁾# G ``` **[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4oCZMyrhuLZiM@G4guG4hCbDvmDCrOG7i@KBviMgR////zQ "Jelly – Try It Online")** ### How? ``` ’3*Ḷb3ḂḄ&þ`¬ị⁾# G - Link: integer, n ’ - decrement -> n-1 3* - three raised to (that) Ḷ - lowered range -> [0,1,...,3^(n-1)-1] b3 - convert to base three (vectorises) Ḃ - least significant bit (vectorises) -> i.e. make 2 trits become 0s Ḅ - convert from base two (vectorises) ` - use that as both arguments of: þ - outer product with: & - bitwise AND ¬ - logical NOT (vectorises) ị - index into: ⁾# - list of characters ['#', ' '] G - format as a grid ``` [Answer] # oK, ~~40~~ 45 bytes ``` `0:" "/'" #"{(x-1)(,'//3 3#111101111b*9#,)/1} ``` [Try it online.](http://johnearnest.github.io/ok/?run=%20%600%3A%22%20%22%2F%27%22%20%23%22%7B%28x-1%29%28%2C%27%2F%2F3%203%23111101111b%2a9%23%2C%29%2F1%7D4%3B) It starts with `1`, and then draws it in a grid `(1 1 1;1 0 1;1 1 1)`, which it then draws in a grid the same way, etc. repeated the necessary number of times. [Answer] # [Haskell](https://www.haskell.org/), 77 characters ``` f n|a<-mapM(:[0,1])[2..n]=[do x<-a;"■ "!!(0^product(zipWith(+)x y)):" "|y<-a] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybRRjc3scBXwyraQMcwVjPaSE8vL9Y2OiVfocJGN9Fa6dG0BQpKiooaBnEFRfkppcklGlWZBeGZJRka2poVCpWamlZKCko1lUC1sf9zEzPzbEGmKRSUlgSXFPnkKagopCmY/AcA "Haskell – Try It Online") [Answer] # PHP, 194 characters The `n` received as first argument in command line. ``` <?php function d(&$a,$n,$e,$x,$y){if(--$n)for(;$i<9;)$p=pow(3,$n)|d($a,$n,$e|$i==4,$x+$p*$j,$y+$p*($i-$j)/3)|$j=++$i%3;else$a[$x][$y]=$e?" ":■;}@d($a,$argv[1]);foreach($a as$s)echo join($s)," "; ``` ## Readable ``` <?php function draw(&$array, $n, $empty, $x, $y) { $n--; if ($n != 0) { for ($i = 0; $i < 9; $i++) { $j = $i % 3; $p = pow(3, $n); draw($array, $n, $empty || $i == 4, $x + $p * $j, $y + $p * ($i - $j) / 3); } } else { $array[$x][$y] = $empty ? " " : "#"; } } $array = array(); draw($array, $argv[1], false, 0, 0); foreach ($array as $line) { echo join($line), "\n"; } ``` [Answer] **Scala 230 characters** Golfed code: ``` object T extends App {def m=math.pow(3,args(0).toInt-1).toInt-1;def p=print _;val x=0 to m;x.map{n=>x.map{j=>if(q(n,j)==1)p(" #");else p(" ")};p("\n");};def q(n:Int,j:Int):Int={if(n>0|j>0)if((n%3&j%3)==1)0 else q(n/3,j/3)else 1}} ``` Ungolfed code: ``` object T extends App { def m = math.pow(3, args(0).toInt - 1).toInt - 1; def p = print _; val x = 0 to m; x.map { n => x.map { j => if (q(n, j) == 1) p(" #"); else p(" ")}; p("\n");}; def q(n: Int, j: Int): Int = { if (n > 0 | j > 0) if ((n % 3 & j % 3) == 1) 0 else q(n / 3, j / 3) else 1 } } ``` Only necessary spaces are included. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 27 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ■¹.H{³³┼┼≥: ■@ŗ;┼┼⁴++}{@∑P ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJXUyNUEwJUI5LkglN0IlQjMlQjMldTI1M0MldTI1M0MldTIyNjUlM0ElMjAldTI1QTBAJXUwMTU3JTNCJXUyNTNDJXUyNTNDJXUyMDc0KyslN0QlN0JAJXUyMjExUA__,inputs=NA__) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 162 bytes ``` n=>{var f="";int s=(int)Math.Pow(3,n),z=0;while(z<s*s){int x=z%s,y=z/s,h=1;for(;x>0|y>0;y/=3,x/=3)if(y%3==1&x%3==1)h=0;f+=" #"[h]+(z++%s<s-1?" ":"\n");}return f;} ``` [Try it online!](https://tio.run/##NY@5TsQwFEXr8VdYRkE2ySxRqHAcCiQqRhqJggIoLGMTS8FBfs5MFvLtwcPSvFu8o6t7FKxV6/XSgXXv@HGAoD84Uo0EwIcJQZDBKnzfOVVaFzIIPnIVNl6qIBss8OJENR2lx0YQwiODQdAYbC9DvTm0J1pkjmWj2PFTbRtNxxKugE1nshdjAtkgxi1ktci5aT3lfbX7GqodH7aiyPp4mDV0SAoh8sv@J1gdy0wqCL4gz/VrSsc0TaCEdX5LMLkhL44wPnsdOu@w4fPC0b/IsbVveC@towxNaHXeraT/1CGa/DnRa8bR6q510DZ68@Rt0A/WafrLxd@M5uUb "C# (.NET Core) – Try It Online") ### Degolfed ``` n=>{ var f=""; int s=(int)Math.Pow(3,n),z=0; while(z<s*s) { int x=z%s, y=z/s, h=1; for(; x>0 | y>0; y/=3, x/=3) if(y%3==1 & x%3==1) h=0; f += " #"[h] + (z++%s<s-1? " " : "\n"); } return f; } ``` [Answer] ## [Canvas](https://github.com/dzaima/Canvas), ~~17~~ ~~16~~ 17 characters ``` ■;╷[⌐ +2×;┌∔∔;3*+ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNUEwJXVGRjFCJXUyNTc3JXVGRjNCJXUyMzEwJTIwJXVGRjBCJXVGRjEyJUQ3JXVGRjFCJXUyNTBDJXUyMjE0JXUyMjE0JXVGRjFCJXVGRjEzJXVGRjBBJXVGRjBC,i=Mw__) -1: *Used `[` instead of `{` to delete the first `;` inside the loop.* +1: *Fixed errenous behavior: `■` now corresponds to level 1, as specified in the original post.* [Answer] # [Pip](https://github.com/dloscutoff/pip) `-S`, 30 characters ``` "■■ "@MX{{aTB3R2i}MSg}MC3**a/3 ``` [Try it online!](https://tio.run/##K8gs@P9f6dG0BUCkoOTgG1FdnRjiZBxklFnrG5xe6@tsrKWVqG/8//9/3eD/JgA "Pip – Try It Online") The basic idea: consider a coordinate grid in base 3. The holes in the carpet occur where 1) a trit in the x-coordinate is `1`, and 2) the trit in the same position in the y-coordinate is also `1`. ``` "■■ "@MX{{aTB3R2i}MSg}MC3**a/3 i is 0; a is 1st cmdline arg (implicit) 3**a/3 Width/height of the carpet MC Make a coordinate grid that size and map this function to the coordinate pairs: g Take each [x y] pair MS Map this function to each coord and add the results: {aTB3 } Convert to base 3 R2i Replace 2's with 0's E.g. 15 -> 120 -> 100 and 16 -> 121 -> 101 When we add the results, we get [15 16] -> 201 MX{ } Take the max of that list (0, 1, or 2) "■■ "@ Use that to index into this string (resulting in a space iff two 1's coincided to make a 2, or ■ otherwise) Print the resulting nested list with each sublist on its own line and space-delimited (implicit, -S flag) ``` Similar solution, same number of characters but -2 bytes: `{2N({aTB3R2i}MSg)?s'■}MC3**a/3` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~50~~ 49 bytes thanks @DLosc for reminding me I should output spaces between the columns thanks @coltim for -1 byte ``` 1@"\n"/("# "1_,/1,'+/')'a*/:\:a:+2!!1_(. 0:"")#3; ``` [Try it online!](https://tio.run/##y9bNS8/7/9/QQSkmT0lfQ0lZQckwXkffUEddW19dUz1RS98qxirRSttIUdEwXkNPwcBKSUlT2dj6/38TAA "K (ngn/k) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` ‛ #3?‹eʁ3τ∷vB:v⋏†İ⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJsgIzM/4oC5ZcqBM8+E4oi3dkI6duKLj+KAoMSw4oGLIiwiIiwiNCJd) ## How? ``` ‛ #3?‹eʁ3τ∷vB:v⋏†İ⁋ ?‹ # Push input - 1 3 e # Push 3 to the power of it ʁ # Get range [0, that) 3τ # Convert each to base 3 (ternary) ∷ # Modulo each by two to convert twos to zeros vB # Convert each from binary to integers :v⋏ # Outer product bitwise AND with itself † # Logical NOT for each ‛ # İ # Index each into " #" ⁋ # Join each by spaces, and then join on newlines ``` [Answer] # [R](https://www.r-project.org/), 92 characters 94 bytes with the special character. ``` write(c(" ","■")[1+Reduce("%x%",rep(list(matrix(c(1,1,1,1,0,1),3,3)),n<-scan()-1),1)],1,3^n) ``` [Try it online!](https://tio.run/##K/r/v7wosyRVI1lDSUFJR@nRtAVKmtGG2kGpKaXJqRpKqhWqSjpFqQUaOZnFJRq5iSVFmRVAtYY6EGigY6ipY6xjrKmpk2ejW5ycmKehqQsUMtSMBcoax@Vp/jf8DwA "R – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 27 bytes ``` mJ' ´Ṫȯ!"□ "¬nmḋ†%2mB3ŀ`^3← ``` [Try it online!](https://tio.run/##ATMAzP9odXNr//9tSicgwrThuarIryEi4pahICLCrG5t4biL4oCgJTJtQjPFgGBeM@KGkP///zU "Husk – Try It Online") Translation of Jonathan Allan's program. uses the '□' character. [Answer] # [J](http://jsoftware.com/), 35 50 bytes ``` ' #'{~1|:@}.[:,/0,:"1]9&([:,/_3,./\0"+4}(#,:)),:@1 ``` [Try it online!](https://tio.run/##JY7BasJAGITveYohAdfguibaS5cKQaGn0kOxJxUJ8U@zEndld0MNbfrqMdrDwAx8M8ypDwUrsZRg4EggB00F1h9vrz1DxH7@0l@ZdWIr@SzhMkz3z6PxPRwWXMx2STh56sYRl3HMZZb2cfC@EliZKznkljTzuOTWw5Rwpm68MtrBNP7SePFANxW1zBJOjfPwBkeq1VkNtiLk2n2TdShqym3d/hc@3TCdTJU@0lXpLxEEVFQGXOAlK8PJcD/FHIv@Bg "J – Try It Online") *+15 thanks to DLosc for pointing out there had to be spaces between columns.* This was a quick fix to satisfy the spec and could likely be re-golfed further. ## [J](http://jsoftware.com/), original answer, cleaner, 35 bytes ``` ' #'{~]9&([:,/_3,./\0"+4}(#,:)),:@1 ``` [Try it online!](https://tio.run/##JY5BCwFBHMXv@yleq4zNGMu6mChRTnIQJ6SN/9rRmtHMbEh89bVxePUOv/frXapQsAxjCQaOGLJOR2C2WswrhgZ7ffbDZmsrefeQcNHdxWF78G41uIwiLie9KgqWU4GpeZBDakkzj1tqPUwGZ4rSK6MdTOlvpRc/dJ3Tk1nCpXQe3uBEhbqquuaEVLs7WYdjQaktnv/BxtXquKP0iR5Kn0UQ0DE34AKjSRa267899JFUXw "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „# 3I<mݨ3δвÉJCDδ&Āè» ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/205210/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##ASsA1P9vc2FiaWX//@KAniMgM0k8bcOdwqgzzrTQssOJSkNEzrQmxIDDqMK7//80) or [verify all test cases](https://tio.run/##yy9OTMpM/W/iquSZV1BaYqWgZO@nw6XkX1oC5en8f9QwT1nB2M8m9/DcQyuMz225sOlwp5ezy7ktakcaDq84tPu/zqFt9v8B). **Explanation:** ``` I< # Push the input-1 3 m # Take 3 to the power this input-1 Ý # Pop and push a list in the range [0,3**(input-1)] ¨ # Remove the last item to lower the range to: [0,3**(input-1)) δ # Map over each integer: 3 в # Convert it to a base-3 list É # Check for each trigit if it's odd, converting the 2s to 0s J # Join the inner bit-lists together to strings C # Convert each from a binary-string to an integer D # Using a copy of itself, δ # apply double-vectorized over this list of integer: & # Bitwise-AND the integers together Ā # Check for each integer whether it's NOT 0 (0 if 0; 1 otherwise) „# è # 0-based index it into the string "# " » # Join each inner list by spaces, and then each string by newlines # (after which the result is output implicitly) ``` ]
[Question] [ Using the fewest Unicode characters, write a function that accepts three parameters: * Total number of dominoes * `n`th affected domino * Topple direction of the affected domino (`0` or `L` for left, `1` or `R` for right) Once a domino is toppled, it must also topple the remaining dominoes in the same direction. You should output the dominoes with `|` representing a standing domino and `\` and `/` representing a domino toppled to the left and right respectively. ## Examples `10, 5, 1` should return `||||//////` `6, 3, 0` should return `\\\|||` [Answer] ## Ruby, 38 (46) characters ``` e=->n,k,r{k-=r;'\|'[r]*k+'|/'[r]*n-=k} ``` This function takes the direction as an integer (`1` for right, `0` for left). A function that takes a string is 8 characters longer: ``` d=->n,k,r{n-=k;r<?r??\\*k+?|*n :?|*~-k+?/*-~n} ``` Usage examples: ``` puts e[10, 5, 1] # or d[10, 5, 'r'] ||||////// puts e[10, 5, 0] # or d[10, 5, 'l'] \\\\\||||| ``` [Answer] **Haskell, 70** ``` f R i l=(i-1)#'|'++(l-i+1)#'/' f L i l=i#'\\'++(l-i)#'|' (#)=replicate ``` assuming there is a type *Direction*, which has constructors *R* and *L*. [Answer] # J - 32 26 char J can't handle more than two arguments without using a list, and it can't handle non-homogenous lists without boxing. So having the input as a list of three integers is ideal. The parameter order is the reverse of the standard one: 0 for left or 1 for right, then position, then total number of dominoes. The reason for this is because J will end up going through them right-to-left. ``` {`(('|/\'{~-@>:,:<:)1+i.)/ ``` Here's what's going on. `F`G/` applied to a list `x,y,z` will evaluate `x F (y G z)`. `y G z` constructs both possible ways the dominoes could have toppled, and then `F` uses `x` to select which of the two to use. Below is a back-and-forth with the J REPL that explains how the function is built together: indented lines are input to the REPL, and responses are flush with the left margin. Recall that J evaluates strictly right to left unless there are parens: ``` 1 ] 3 (]) 10 NB. ] ignores the left argument and returns the right 10 1 ] 3 (] 1+i.) 10 NB. hook: x (F G) y is x F (G y) 1 2 3 4 5 6 7 8 9 10 1 ] 3 (>: 1+i.) 10 NB. "greater than or equal to" bitmask 1 1 1 0 0 0 0 0 0 0 1 ] 3 (-@>: 1+i.) 10 NB. negate _1 _1 _1 0 0 0 0 0 0 0 1 ] 3 (<: 1+i.) 10 NB. "less than or equal to" 0 0 1 1 1 1 1 1 1 1 1 ] 3 ((-@>:,:<:)1+i.) 10 NB. laminate together _1 _1 _1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 ] 3 (('|/\'{~-@>:,:<:)1+i.) 10 NB. turn into characters \\\||||||| ||//////// 1 { 3 (('|/\'{~-@>:,:<:)1+i.) 10 NB. select left or right version ||//////// {`(('|/\'{~-@>:,:<:)1+i.)/ 1 3 10 NB. refactor ||//////// {`(('|/\'{~-@>:,:<:)1+i.)/ 0 3 10 \\\||||||| ``` At the expense of a few characters, we can make the order the standard order: just append `@|.` to the end of the function: ``` |. 10 3 1 1 3 10 {`(('|/\'{~-@>:,:<:)1+i.)/@|. 10 3 1 ||//////// ``` Adapting this to work with a string argument for direction would be much more costly, however. [Answer] ## PowerShell, 66 ``` filter d($n,$k,$d){"$('\|'[$d])"*($k-$d)+"$('|/'[$d])"*($n-$k+$d)} ``` Probably the same idea every one else had. * Takes either 0 or 1 as the direction parameter (for left and right, respectively) [Answer] ## Golfscript (44 ~~53~~) My first ever Golfscript program. Took me way longer than it should have and can probably be done in a smarter, more concise way (I'm sure someone will prove that :) ): ``` :d;:j;:^,{:x j<d&'\\'{x^j)->d!&'/''|'if}if}% ``` A sample input is `10 5 0`. Ungolfed: ``` :d;:j;:^ # save input in variables and discard from stack, except total length ^ , # create an array of numbers of length ^ { # start block for map call :x # save current element (= index) in variable j< # check whether we are left of the first knocked over domino d # check whether the direction is to the left & # AND both results '\\' # if true, push a backslash (escaped) { # if false, start a new block x^j)-> # check whether we are on the right of the knocked over domino d! # check whether the direction is to the right & # AND both results '/' # if true, push a slash '|' # if false, push a non-knocked over domino if } if }% # close block and call map ``` [Answer] ### GolfScript, 28 23 characters ``` '\\'@*2$'|/'*$-1%1>+@/= ``` Arguments on top of stack, try [online](http://golfscript.apphb.com/?c=MTAgNSAxCgonXFwnQCoyJCd8LycqJC0xJTE%2BK0AvPQ%3D%3D&run=true): ``` > 10 5 1 ||||////// > 10 5 0 \\\\\||||| ``` [Answer] # Python - 45 ~~52~~ This requires `1` for right and `0` for left. ``` x=lambda n,k,d:'\\|'[d]*(k-d)+"|/"[d]*(n-k+d) ``` Here's a version that takes `r` and `l` correctly, at **58**: ``` def x(n,k,d):d=d=='r';return'\\|'[d]*(k-d)+"|/"[d]*(n-k+d) ``` Some usage examples... ``` >>> print(x(10,3,0)) \\\||||||| >>> print(x(10,3,1)) ||//////// >>> print(x(10,5,1)) ||||////// >>> print(x(10,5,0)) \\\\\||||| >>> print(x(10,3,0)) \\\||||||| ``` [Answer] ## JS (ES6) - ~~79~~ ~~74~~ ~~72~~ ~~65~~ 62 thanks to @nderscore! The 3rd param is a boolean (0: left / 1: right) ``` d=(a,b,c)=>"\\|"[a-=--b,c].repeat(c?b:a)+"|/"[c].repeat(c?a:b) // Test d(10,3,1); // => "||////////" d(10,3,0); // => "\\\\\\\\||" ``` [Answer] **Python2/3 - 54** That last added on rule was quite nice (the 0/1 instead of 'l'/'r'). Made mine actually smaller than the existing python solution. 0 is left, 1 is right ``` def f(a,b,c):d,e='\|/'[c:2+c];h=b-c;return d*h+e*(a-h) # Usage: print(f(10,5,1)) # => ||||////// print(f(10,5,0)) # => \\\\\||||| ``` [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` (n%k)b=["\\|/"!!(b-div(k-b-c)n)|c<-[1..n]] ``` [Try it online!](https://tio.run/##NY1NDoIwFIT3nuJBJGmTFiHGHb2BrlwWFi0/8aWlIVBdmN69Fo3Lmflm5qE2M1obI3GFoVrIvG3DKc8yovmAL2K45j11NPQNl3VZuq6LkyAFPcwKHQiY1XKD5envfr06OIKcYMP3COjQo7Iw4ArhZzUc5JnBhUFddeybpNEqyaT@/A6ln72Qrj4 "Haskell – Try It Online") Takes input like `(%) n k b` for `n` dominos, `k`'th domino toppled, direction `b`. Finds the character at each position `c` ranging from `1` to `n` by using an arithmetic expression to compute the character index 0, 1, or 2. Test cases taken from [here](https://codegolf.stackexchange.com/a/173928/20260). --- **[Haskell](https://www.haskell.org/), 44 bytes** ``` (n%k)b=take n$drop(n+n*b+b-k)$"\\|/"<*[1..n] ``` [Try it online!](https://tio.run/##NY1NDoIwGET3nmJCIOFfCHFHb6Arl6WLEiA2LZ@k1I3h7hU0Lt/Mm8xDrno0xvuYIp30zEk9gsLBPpeYMkr7rC90EgZdt52DNuV1WZLwE4uj5DRLRWCY5XLD8nJ3Z6@EEHzCqt4jFCmnpMGgLLZf1BbgTY5LjroS@bdpC17tuNPfP6T95hgI4T8 "Haskell – Try It Online") An interesting strategy that turned out a bit longer. Generates the string `"\\|/"<*[1..n]` with `n` consecutive copies of each symbol, then takes a slice of `n` contiguous characters with start position determined arithmetically. [Answer] ## Python 2.7, 68 65 61 59 58 chars Use `d=1` for left and `d=0` for right ``` f=lambda a,p,d:['|'*(p-1)+'/'*(a-p+1),'\\'*p+'|'*(a-p)][d] ``` Note: Thanks to @TheRare for further golfing it. [Answer] **Javascript, 46 characters** Seems like cheating to do 0=l and 1=r but there is is. Shrunk it with a little recursion. ``` f=(a,p,d)=>a?'\\|/'[(p-d<1)+d]+f(a-1,p-1,d):'' ``` edit: missed an obvious character [Answer] # JavaScript (ES6) 61 ~~63~~ **Edit** It was buggy - shame on me. Not so different from @xem, but found it myself and it's shorter. Parameter d is 0/1 for left/right ``` F=(a,p,d,u='|'.repeat(--p),v='\\/'[d].repeat(a-p))=>d?u+v:v+u ``` **Test** In Firefox console ``` for(i=1;i<11;i+=3) console.log('L'+i+' '+F(10,i,0) + ' R'+i+' '+ F(10,i,1)) ``` **Output** ``` L1 \\\\\\\\\\ R1 ////////// L4 \\\\\\\||| R4 |||/////// L7 \\\\|||||| R7 ||||||//// L10 \||||||||| R10 |||||||||/ ``` [Answer] ## Perl, ~~67~~ 65 Characters ``` sub l{($t,$p,$d)=@_;$p-=$d;($d?'|':'\\')x$p.($d?'/':'|')x($t-$p)} ``` Assign the first three params (total, position, direction as an integer [0 left, 1 right]). Extras go into the ether. Subtract 1 from the position if we're headed right so the domino in position X is flipped, too. [Answer] # [Haskell](https://www.haskell.org/), 57 bytes *4 bytes saved thanks to [this tip](https://codegolf.stackexchange.com/a/96371/56656)* ``` f 0 b _=[] f a b c=last("|/":["\\|"|b>c])!!c:f(a-1)(b-1)c ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BQCFJId42OpYrTSERyEy2zUksLtFQqtFXsopWiompUapJskuO1VRUTLZK00jUNdTUSAISyf9zEzPzbAtKS4JLinzyVNIUDI0UjBUM/wMA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), ~~69~~ ~~61~~ ~~60~~ 58 bytes ``` (0!b)_=[] (a!b)c|b==c=a!b$c+1|1>0="\\|/"!!c:((a-1)!(b-1))c ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X8NAMUkz3jY6lksjEchKrkmytU22BTJVkrUNawztDGyVYmJq9JUUFZOtNDQSdQ01FTWSgKRm8v/cxMw824LSkuCSIp88FQ1DI0VjTcP/AA "Haskell – Try It Online") Not a very complex answer but it beats both of the existing Haskell answers. [Answer] # [R](https://www.r-project.org/), ~~75~~ ~~68~~ ~~61~~ 57 bytes An anonymous function. I'll post a fuller explanation if there is interest. ``` function(t,n,d)cat(c("\\","|","/")[(1:t>n-d)+1+d],sep="") ``` [Try it online!](https://tio.run/##FcuxDkAwEADQ3Vc0N93FiTbCIOFH1CCtJpYj1ObfD8Mb36lp0HRLyNsumFk4UlgyBgTvgeH51EATuj6PUkUqXRlnvtZjACBN6Cyblo2j4m/gBahI2LFp2FhSfQE "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 51 bytes ``` f a b c=("\\|"!!c<$[1..b-c])++("|/"!!c<$[b-c..a-1]) ``` `a` = number of dominoes, `b` = 1-based index of the touched one, `c` = direction (`0` is left and `1` is right). [Try it online!](https://tio.run/##NY29DoMgAIRf5SQOGoFKmm76Bu3UERmQakqKxihdGt6dYn/G@@673F1vj8G5GEdo9DBtQboukCwzTS4F5z0zqqyqgoTDDybCuWZClXHSdkaLSS8XLE9/9et5Rg45YrOvAXa23mqHm10RvqhhkEeKE4WoFf00DZN1iin9/V1K1/tAqfgG "Haskell – Try It Online") [Answer] # PHP - 64 ``` function f($a,$b,$c){for($w='\|/';++$i<=$a;)echo$w[$c+($i>$b)];} ``` A simple loop, and echo-ing the character. Generates a `Notice: Undefined variable: i`, here's another version silenting the error (65 characters) : ``` function f($a,$b,$c){for($w='\|/';@++$i<=$a;)echo$w[$c+($i>$b)];} ``` And a version withtout any error (69 characters) : ``` function f($a,$b,$c){for($w='\|/',$i=0;++$i<=$a;)echo$w[$c+($i>$b)];} ``` --- Other functions in PHP : `sprintf` / `printf` padding ``` function f($a,$b,$c){printf("%'{${0*${0}=$c?'|':'\\'}}{$a}s",sprintf("%'{${0*${0}=$c?'/':'|'}}{${0*${0}=$a-$b+$c}}s",''));} ``` padding via `str_pad` / `str_repeat` functions ``` function f($a,$b,$c){$f='str_repeat';echo$f($c?'|':'\\',$b-$c).$f($c?'/':'|',$a-$b+$c);} function f($a,$b,$c){echo str_pad(str_repeat($c?'|':'\\',$b-$c),$a,$c?'/':'|');} ``` using both `printf` and `str_repeat` functions ``` function f($a,$b,$c){printf("%'{${0*${0}=$c?'|':'\\'}}{$a}s",str_repeat($c?'/':'|',$a-$b+$c));} function f($a,$b,$c){$w='\|/';printf("%'$w[$c]{$a}s",str_repeat($w[$c+1],$a-$b+$c));} ``` [Answer] # Scala 75 characters ``` def f(l:Int,p:Int,t:Char)=if(t=='l')"\\"*p++"|"*(l-p) else "|"*(l-p):+"/"*p ``` [Answer] # CJam - 20 ``` q~ :X-_"\|"X=*o-"|/"X=* ``` The main code is on the second line, the first line is just for getting the parameters from the standard input (otherwise you need to put the parameters in the code). Try it at <http://cjam.aditsu.net/> **Examples:** ``` 12 4 1 |||///////// 8 5 0 \\\\\||| ``` **Explanation:** `:X` stores the last parameter (0/1 direction) in variable X `-` subtracts X from the knock-over position, obtaining the length of the first sequence of characters (let's call it L) `_` makes a copy of L `"\|"X=` gets the character to use first: `\` for X=0 and `|` for X=1 `*` repeats that character L times `o` prints out the string, removing it from the stack `-` subtracts L from the number of dominoes, obtaining the length of the second sequence of characters (let's call it R) `"|/"X=` gets the character to use next: `|` for X=0 and `/` for X=1 `*` repeats that character R times [Answer] ## Common Lisp This won't win in a code golf, but it highlights Common Lisp's justification format directive: ``` (lambda (n p d &aux (x "\\|/")) (format t "~v,,,v<~v,,,v<~>~>" n (aref x d) (+ d (- n p)) (aref x (1+ d)))) ``` The arithmetic isn't bad: `n` is the total number of dominoes; `p` is the position of the first toppled domino; `d` is either `0` or `1`, representing left and right (as allowed in the comments), and is used as an index into `x`; `x` is a string of `\`, `|`, and `/`. The format string uses two (nested) justification directives, each of which allows for a padding character. Thus: ``` (dotimes (d 2) (dotimes (i 10) ((lambda (n p d &aux (x "\\|/")) (format t "~v,,,v<~v,,,v<~>~>" n (aref x d) (+ d (- n p)) (aref x (1+ d)))) 10 (1+ i) d) (terpri))) \||||||||| \\|||||||| \\\||||||| \\\\|||||| \\\\\||||| \\\\\\|||| \\\\\\\||| \\\\\\\\|| \\\\\\\\\| \\\\\\\\\\ ////////// |///////// ||//////// |||/////// ||||////// |||||///// ||||||//// |||||||/// ||||||||// |||||||||/ ``` [Answer] **PHP, 89 Characters** ``` function o($a,$p,$d){for($i=0;$i<$a;$i++)echo$d==0?($i+1>$p)?'|':'\\':($i+1<$p?'|':'/');} ``` Just because I love PHP. **EDIT:** The following code does the same. ``` function dominoes ($number, $position, $direction) { for ($i=0; $i<$number; $i++){ if ($direction==0) { if (($i+1) > $position) { echo '|'; } else { echo '\\'; } } else { if (($i+1) < $position) { echo '|'; } else { echo '/'; } } } } ``` [Answer] # [J](http://jsoftware.com/), ~~23 21~~ 19 bytes ``` '|/\'{~{:-(>i.)~`-/ ``` [Try it online!](https://tio.run/##y/r/P81WT0G9Rj9Gvbqu2kpXwy5TT7MuQVf/f2pyRr6CRpqOlZKVZlF@ebGCqYKJgqGOgpmCIYgyBUIDHSsFQzMFYwWD/wA) Input is a list of integers in the standard order. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` αα©„\|³è×¹®-„|/³è×J ``` I still have the feeling it's a bit long, but it works.. And better than the initial 23 bytes solution I had with if-else construction, which I quickly dropped.. Input order is the same as in the challenge: total length, index, `1`/`0` for left/right respectively. [Try it online](https://tio.run/##yy9OTMpM/f//3MZzGw@tfNQwL6bm0ObDKw5PP7Tz0DpdIL9GH8L3@v/f0IDLlMsQAA) or [verify both test cases](https://tio.run/##yy9OTMpM/W/k5ukS6unpEvb/3MZzGw@tfNQwL6Ym8vCKw9MjDq3TBfJq9ME8r/86/w0NuEy5DLnMuIy5DAA). **Explanation:** ``` α # Take the absolute difference of the first two (implicit) inputs # i.e. 10 and 5 → 5 # i.e. 6 and 3 → 3 α # Then take the absolute difference with the third (implicit) input # i.e. 5 and 1 → 4 # i.e. 3 and 0 → 3 © # Store this number in the register (without popping) „\| # Push "\|" ³è # Use the third input to index into this string # i.e. 1 → "|" # i.e. 0 → "\" × # Repeat the character the value amount of times # i.e. 4 and "|" → "||||" # i.e. 3 and "\" → "\\\" ¹®- # Then take the first input, and subtract the value from the register # i.e. 10 and 4 → 6 # i.e. 6 and 3 → 3 „|/ # Push "|/" ³è # Index the third input also in it # i.e. 1 → "/" # i.e. 0 → "|" × # Repeat the character the length-value amount of times # i.e. 6 and "/" → "//////" # i.e. 3 and "|" → "|||" J # Join the strings together (and output implicitly) # i.e. "||||" and "//////" → "||||//////" # i.e. "///" and "|||" → "///|||" ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 23 bytes ``` [-‹\|*₴+\/*,|-\\*₴+\|*, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%5B-%E2%80%B9%5C%7C*%E2%82%B4%2B%5C%2F*%2C%7C-%5C%5C*%E2%82%B4%2B%5C%7C*%2C&inputs=0%0A3%0A6&header=&footer=) [Answer] ## C++ 181 ``` #define C(x) cin>>x; #define P(x) cout<<x; int n,k,i;char p; int main(){C(n)C(k)C(p) for(;i<n;i++){if(p=='r'&&i>=k-1)P('/')else if(p=='l'&&i<=k-1)P('\\')else P('|')} return 0;} ``` [Answer] # PHP - 105,97, 96 ``` function a($r,$l,$f){$a=str_repeat('|',$l-$f);$b=str_repeat($r?'/':'\\',$f);echo$r?$a.$b:$b.$a;} ``` Example results: ``` a(true,10,4); -> \\\\|||||| a(false,10,5); -> |||||///// a(false,10,2); -> ||||||||// ``` [Answer] # Javascript, 81 85 characters ``` function e(a,b,c){l='repeat';d='|'[l](--a-b++);return c>'q'?d+"/"[l](b):"\\"[l](b)+d} ``` First time trying codegolf, was fun thanks :) [Answer] # JavaScript - 85 chars ``` function d(a,b,c){for(r=c?"\\":"/",p="",b=a-b;a--;)p+=c?a<b?"|":r:a>b?"|":r;return p} ``` 1 = Left, 0 = Right ``` d(10,3,1) \\\||||||| d(10,3,0) ||//////// d(10,7,1) \\\\\\\||| d(10,7,0) ||||||//// ``` [Answer] **Clojure, 81 chars** ``` (defn g[a,p,d](apply str(map #(nth "\\|/"(+(if(>= % (- p d)) 1 0) d))(range a)))) ``` ]
[Question] [ ### Backstory Disclaimer: May contain made up information about kangaroos. Kangaroos traverse several stages of development. As they grow older and stronger, they can jump higher and longer, and they can jump more times before they get hungry. In stage **1**, the kangaroo is very little and cannot jump at all. Despite this, is constantly requires nourishment. We can represent a stage **1** kangaroo's activity pattern like this. ``` o ``` In stage **2**, the kangaroo can make small jumps, but not more than **2** before it gets hungry. We can represent a stage **2** kangaroo's activity pattern like this. ``` o o o o o ``` After stage **2** the kangaroo improves quickly. In each subsequent stage, the kangaroo can jump a bit higher (1 unit in the graphical representation) and twice as many times. For example, a stage **3** kangaroo's activity pattern looks like this. ``` o o o o o o o o o o o o o o o o o ``` All that jumping requires energy, so the kangaroo requires nourishment after completing each activity pattern. The exact amount required can be calculated as follows. 1. Assign each **o** in the activity pattern of a stage **n** kangaroo its height, i.e., a number from **1** to **n**, where **1** corresponds to the ground and **n** to the highest position. 2. Compute the sum of all heights in the activity pattern. For example, a stage **3** kangaroo's activity pattern includes the following heights. ``` 3 3 3 3 2 2 2 2 2 2 2 2 1 1 1 1 1 ``` We have five **1**'s, eight **2**'s, and four **3**'s; the sum is **5·1 + 8·2 + 4·3 = 33**. ### Task Write a full program or a function that takes a positive integer **n** as input and prints or returns the nutritional requirements per activity of a stage **n** kangaroo. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); may the shortest answer in bytes win! ### Examples ``` 1 -> 1 2 -> 7 3 -> 33 4 -> 121 5 -> 385 6 -> 1121 7 -> 3073 8 -> 8065 9 -> 20481 10 -> 50689 ``` [Answer] # Coffeescript, 19 bytes ``` (n)->(n*n-1<<n-1)+1 ``` Edit: Thanks to Dennis for chopping off 6 bytes! The formula for generating Kangaroo numbers is this: [![enter image description here](https://i.stack.imgur.com/P4608.png)](https://i.stack.imgur.com/P4608.png) ## Explanation of formula: The number of `1`'s in `K(n)`'s final sum is `2^(n - 1) + 1`. The number of `n`'s in `K(n)`'s final sum is `2^(n - 1)`, so the sum of all the `n`'s is `n * 2^(n - 1)`. The number of any other number (`d`) in `K(n)`'s final sum is `2^n`, so the sum of all the `d`'s would be `d * 2^n`. * Thus, the sum of all the other numbers `= (T(n) - (n + 1)) * 2^n`, where `T(n)` is the triangle number function (which has the formula `T(n) = (n^2 + 1) / 2`). Substituting that in, we get the final sum ``` (((n^2 + 1) / 2) - (n + 1)) * 2^n = (((n + 1) * n / 2) - (n + 1)) * 2^n = ((n + 1) * (n - 2) / 2) * 2^n = 2^(n - 1) * (n + 1) * (n - 2) ``` When we add together all the sums, we get `K(n)`, which equals ``` (2^(n - 1) * (n + 1) * (n - 2)) + (2^(n - 1) + 1) + (n * 2^(n - 1)) = 2^(n - 1) * ((n + 1) * (n - 2) + n + 1) + 1 = 2^(n - 1) * ((n^2 - n - 2) + n + 1) + 1 = 2^(n - 1) * (n^2 - 1) + 1 ``` ... which is equal to the formula above. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes ``` ²’æ«’‘ ``` Uses the formula (*n*2 - 1) 2*n* - 1 + 1 to compute each value. @Qwerp-Derp's was kind enough to provide a [proof](https://codegolf.stackexchange.com/a/96386/6710). [Try it online!](http://jelly.tryitonline.net/#code=wrLigJnDpsKr4oCZ4oCY&input=&args=MTA) or [Verify all test cases.](http://jelly.tryitonline.net/#code=wrLigJnDpsKr4oCZ4oCYClLFvMOH4oKsJEc&input=&args=MTA) ## Explanation ``` ²’æ«’‘ Input: n ² Square n ’ Decrement æ« Bit shift left by ’ Decrement of n ‘ Increment ``` [Answer] # Java 7, 35 bytes ``` int c(int n){return(n*n-1<<n-1)+1;} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒḄ¡S ``` [Try it online!](http://jelly.tryitonline.net/#code=xZLhuITCoVM&input=&args=MTA) or [verify all test cases](http://jelly.tryitonline.net/#code=xZLhuITCucKhUwoxMFLCtcW8w4figqxH&input=). ### How it works ``` ŒḄ¡S Main link. Argument: n (integer) ŒḄ Bounce; turn the list [a, b, ..., y, z] into [a, b, ..., y, z, y, ..., b, a]. This casts to range, so the first array to be bounced is [1, ..., n]. For example, 3 gets mapped to [1, 2, 3, 2, 1]. ¡ Call the preceding atom n times. 3 -> [1, 2, 3, 2, 1] -> [1, 2, 3, 2, 1, 2, 3, 2, 1] -> [1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1] S Compute the sum. ``` [Answer] # Python 2, ~~25~~ 23 bytes ``` lambda x:(x*x-1<<x-1)+1 ``` Used miles's formula. Thanks to Jonathan Allan for -2 bytes. [Answer] # Lua, 105 bytes ``` s=tonumber(arg[1])e=1 for i=1,s>1 and 2^(s-1)or 0 do e=e+1 for j=2,s-1 do e=e+j*2 end e=e+s end print(e) ``` De-golfed: ``` stage = tonumber(arg[1]) energy = 1 for i = 1, stage > 1 and 2 ^ (stage - 1) or 0 do energy = energy + 1 for j = 2, stage - 1 do energy = energy + j * 2 end energy = energy + stage end print(energy) ``` Entertaining problem! [Answer] # [Actually](http://github.com/Mego/Seriously), 8 bytes ``` ;²D@D╙*u ``` [Try it online!](http://actually.tryitonline.net/#code=O8KyREBE4pWZKnU&input=Mw) Explanation: This simply computes the formula `(n**2 - 1)*(2**(n-1)) + 1`. ``` ;²D@D╙*u ; duplicate n ² square (n**2) D decrement (n**2 - 1) @ swap (n) D decrement (n-1) ╙ 2**(n-1) * product ((n**2 - 1)*(2**(n-1))) u increment ((n**2 - 1)*(2**(n-1))+1) ``` [Answer] # [GolfScript](//golfscript.com), 11 bytes ``` ~.2?(2@(?*) ``` [Try it online!](//golfscript.tryitonline.net#code=fi4yPygyQCg_Kik&input=Mw) Thanks Martin Ender (8478) for removing 4 bytes. Explanation: ``` Implicit input ["A"] ~ Eval [A] . Duplicate [A A] 2 Push 2 [A A 2] ? Power [A A^2] ( Decrement [A A^2-1] 2 Push 2 [A A^2-1 2] @ Rotate three top elements left [A^2-1 2 A] ( Decrement [A^2-1 2 A-1] ? Power [A^2-1 2^(A-1)] * Multiply [(A^2-1)*2^(A-1)] ) Increment [(A^2-1)*2^(A-1)+1] Implicit output [] ``` [Answer] # CJam, 11 bytes ``` ri_2#(\(m<) ``` [Try it Online.](//cjam.aditsu.net#code=ri_2%23(%5C(m%3C)&input=3) Explanation: ``` r e# Get token. ["A"] i e# Integer. [A] _ e# Duplicate. [A A] 2# e# Square. [A A^2] ( e# Decrement. [A A^2-1] \ e# Swap. [A^2-1 A] ( e# Decrement. [A^2-1 A-1] m< e# Left bitshift. [(A^2-1)*2^(A-1)] ) e# Increment. [(A^2-1)*2^(A-1)+1] e# Implicit output. ``` [Answer] ## Mathematica, 15 bytes ``` (#*#-1)2^#/2+1& ``` There is no bitshift operator, so we need to do the actual exponentiation, but then it's shorter to divide by 2 instead of decrementing the exponent. [Answer] # C, 26 bytes As a macro: ``` #define f(x)-~(x*x-1<<~-x) ``` As a function (27): ``` f(x){return-~(x*x-1<<~-x);} ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes ``` n<¹<o*> ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bjzCuTxvKj4&input=MTA) **Explanation** ``` n< # n^2 * # * ¹<o # 2^(n-1) > # + 1 ``` [Answer] # C#, 18 bytes ``` n=>(n*n-1<<n-1)+1; ``` Anonymous function based on [Qwerp-Derp](https://codegolf.stackexchange.com/users/49561/qwerp-derp)'s excellent mathematical analysis. Full program with test cases: ``` using System; namespace KangarooSequence { class Program { static void Main(string[] args) { Func<int,int>f= n=>(n*n-1<<n-1)+1; //test cases: for (int i = 1; i <= 10; i++) Console.WriteLine(i + " -> " + f(i)); /* will display: 1 -> 1 2 -> 7 3 -> 33 4 -> 121 5 -> 385 6 -> 1121 7 -> 3073 8 -> 8065 9 -> 20481 10 -> 50689 */ } } } ``` [Answer] ## Batch, 30 bytes ``` @cmd/cset/a"(%1*%1-1<<%1-1)+1" ``` Well, it beats Java anyway. [Answer] # [MATL](http://github.com/lmendo/MATL), 7 bytes ``` UqGqW*Q ``` Uses the formula from other answers. [Try it online!](http://matl.tryitonline.net/#code=VXFHcVcqUQ&input=Mw) ``` U % Implicit input. Square q % Decrement by 1 G % Push input again q % Decrement by 1 W % 2 raised to that * % Multiply Q % Increment by 1. Implicit display ``` [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), 9 bytes ``` 2n<mn²<*> ``` I'm surprised there isn't a built-in for `2^n`. [Try it online!](http://oasis.tryitonline.net/#code=Mm48bW7CsjEtKj4&input=&args=OQ) ### Explanation: ``` 2n<m # 2^(n-1) (why is m exponentiation?) n²< # n^2-1 * # (2^(n-1))*(n^2-1) > # (2^(n-1))*(n^2-1)+1 ``` [Answer] ## Racket 33 bytes Using formula explained by @Qwerp-Derp ``` (+(*(expt 2(- n 1))(-(* n n)1))1) ``` Ungolfed: ``` (define (f n) (+ (*(expt 2 (- n 1)) (-(* n n) 1)) 1)) ``` Testing: ``` (for/list((i(range 1 11)))(f i)) ``` Output: ``` '(1 7 33 121 385 1121 3073 8065 20481 50689) ``` [Answer] # Ruby, 21 bytes @Qwerp-Derp basically did the heavy lifting. Because of the precedence in ruby, it seems we need some parens: ``` ->(n){(n*n-1<<n-1)+1} ``` [Answer] # Scala, 23 bytes ``` (n:Int)=>(n*n-1<<n-1)+1 ``` Uses bit shift as exponentiation [Answer] # Pyth, 8 bytes ``` h.<t*QQt ``` [pyth.herokuapp.com](//pyth.herokuapp.com?code=h.%3Ct%2aQQt&input=3&test_suite_input=1%0A2%0A3) Explanation: ``` Q Input Q Input * Multiply t Decrement t Decrement the input .< Left bitshift h Increment ``` [Answer] ## R, 26 bytes Shamelessly applying the formula ``` n=scan();2^(n-1)*(n^2-1)+1 ``` [Answer] # [J](http://jsoftware.com/), 11 bytes ``` 1-<:2&*1-*: ``` Based on the same formula found [earlier](https://codegolf.stackexchange.com/a/96382/6710). [Try it online!](https://tio.run/nexus/j#@5@mYGulYKhrY2WkpmWoq2XFlZqcka@goaOXpmSgqWBnpZCpp2Bo8P8/AA) ## Explanation ``` 1-<:2&*1-*: Input: integer n *: Square n 1- Subtract it from 1 <: Decrement n 2&* Multiply the value 1-n^2 by two n-1 times 1- Subtract it from 1 and return ``` [Answer] # Groovy (22 Bytes) ``` {(it--**2-1)*2**it+1}​ ``` Does not preserve `n`, but uses the same formula as all others in this competition. Saved 1 byte with decrements, due to needed parenthesis. ## Test ``` (1..10).collect{(it--**2-1)*2**it+1}​ ``` > > [1, 7, 33, 121, 385, 1121, 3073, 8065, 20481, 50689] > > > [Answer] # JS-Forth, 32 bytes Not super short, but it's shorter than Java. This function pushes the result onto the stack. This requires JS-Forth because I use `<<`. ``` : f dup dup * 1- over 1- << 1+ ; ``` [**Try it online**](https://repl.it/DzVG) ]
[Question] [ This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge in which each answer builds on the previous answer. Taking no input, you are to output the most recent submission to this thread. I would HIGHLY suggest [sorting by oldest](https://codegolf.stackexchange.com/questions/161757/print-the-previous-answer?answertab=oldest) and skipping to the last page to find the most recent answer. # Scoring The winner will be chosen based on a point system. Every valid submission from each user is scored 1 point. But here is the Fun part: ***If your submission is shorter (in bytes) than the previous answer (your output), your submissions score is multiplied by the difference in bytes.*** This being said, your answer does not have to be shorter than the previous one. The winner is the user with the highest total point count and will be chosen after 2 weeks of inactivity on this thread. # Rules * Each new answer must be in an **UNIQUE** language, check the list below before posting an answer. * You must wait at least 1 hour before submitting a new answer if you have just posted. * You may NOT submit two answers in a row, you must wait for **TWO** more submissions before posting a new answer. * of course, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed * Different versions of languages, e.g. Python 1, Python 2, and Python 3 are considered Different Languages. * Output to stdout or your language's standard for outputting text * Your code must not produce any errors * Check to make sure that no one submitted an answer in the time that you were writing your own, and if so, please adjust and resubmit your code. * **Please make sure that your answer is valid** * Your output will be the previous answer and ONLY the previous answer. Whitespace and newlines are permitted provided that the output still runs as intended in the previous language. * Please check your output to ensure that it runs correctly. # Notes * I'd like to encourage the use of esoteric languages to keep things interesting * I'd also like to encourage the addition of [TIO](https://tio.run/#) links to make for easier testing and validation. # Commencement I will start off this challenge by posting a very simple Python 1 script: ``` print 1 ``` The next submission should print this code EXACTLY. # Formatting Please format your post like this: ``` Answer Number - (language) [code] (preferably a TIO link) [Submission Score] [notes, explanations, whatever you want] ``` ## Used Languages: ``` $.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/161757/answers?site=codegolf&filter=withbody&sort=creation&order=asc",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}}) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="https://codegolf.stackexchange.com"><ul id="list"></ul> ``` *And a special Thank you to all of the other users who have posted [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") questions, you have made writing this question a breeze.* [Answer] # 2. [Brain-Flak](https://github.com/Flakheads/BrainHack), 98 bytes ``` (((((()()()){}){}){}){}())(((((((((((()()()()){}){}){})[[]()]){}){})[[][]])[[]()])[()][][])[()()]) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAww0QVCzuhaOgDwNJKCJriI6OlZDMxbBiY6NhYlFAwmQAIgB4v///1/XEQA "Brain-Flak (BrainHack) – Try It Online") Starting off ~~strong~~ long. Outputs [`print 1`](https://codegolf.stackexchange.com/a/161759/76162). [Answer] # 20. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 24143 bytes ``` ``` [Try it online.](https://tio.run/##jVxbjhzHEfyOPkVczTAEWH8GbMDHp6nZ7e6MR9ZKIihxZjlTXZXPiMj637/@/O8f//n3P/75x69fJMDf/4DX5/ff/wLX59W/ft0vfv6Lz4/i8@t@435nfsbn1@cPn095Xv76B9@f9/k44H7v/mLi@6s/P3w963t@8Osvzo@8l/f@7c/vxLPq@zn@Wtj9kWO1uL@asiS@W/B5wu9VPc/19c78qXsZ@F6a/N3xgOMr702FPP7XT9MO4vutz9vPIr@/7l7/@FC@y333LD/@XfI4i/tn34e5xiE9H3bv4/chfa93nMW7I3Ea9wrfRY4zGcuVs7pt7t2Dselg30N5QbZ9buW0A6ZBySm7Rd/PNM7XN/P5aWKa3ti953/FDd4XxIw/r/GHFb7OAHXl76elW8u9j288AGmWStlUPrb1nsTzxbdRPJb6tSO2PvGV21Me9xoGgxEH4ssek0Du@HCD98PG4w8z@N6K1@5LhJKoA2JbSRzNNN/pEN9f8KwA5tcj/OASL/o@rDvceeB5NlhekNg44oSEej34sGHOx49ojPEEzHXx2ajxyJeEg7AUX@l7Nk@ckUQFytJG/C0frDmg5qt3DeLAHOny9QKPEGJSw1jeP7yuZ9FSTN1D2nTHez1PEI4HpEdlMX6ghLY3tmIe1rtXkotmAHxDthcPHiKeHXxrkJ7F7kMSb@IbJ97nQ5QD70bPNbpVzsrA4l2c3e1Muj2R@uGhBziezR3/ZqAeVQs8OaDZJkaVFnF7xi6PUmFKEqQx8lbk7HfZsgfjCR7X83WhB3@Lvi3gva/XqDvSxUgpYeQzTgx36PHlMcLx6VoKn9J6KwOsdnaHyMMeHzviFUrgNWcsDxxRF1mvwCPOEwqGN7@Lgp/3U7G9O4oMNOZJ70@P8PjarFSs9hDDAOhJdX5V2RgvQQEpi2bxj7S4CHf@FVh7goiGrxlKbcFz8JAoYa2Cl9trv9GqRDIKFl7aFL1pDhaYoB@Pfkpb@q4RXWzMN3J66bbHt2Ghx4zeMmC44Ujr8uSSCHAttikl1CiH3v9CQ7CW3sPWRl/7xijxmS2Sa6fCnv/VWiiFzjgf/BBBp2OtTcKTtkqys6OZWTL7ba33pJvhFt4iN1FwDB79cPysHsICfkgD3n2lNgcgWpM3G0XJJ1b4OgTj0et1afQyiYu1vLl/POOoTXsT8fVKLxC9BjV4RiocS5BWOsyc@C5ymqg0zxNbmNAKS9XbvRmzKZ5tzqzkir@8VsoKvK0e4Y1GdTK2zKQxINs5iptLgZiwIBzXAJEo2GMcGVhQqkdpCEaVDWwYQrwr@BfUNEfPXpsuaegC0MRqq9O4BC7QP0xnme5gWJcnIS6YCwcQJ7DP2B8HFBU5mk3euzKF2qLbI2ntPHYrepZT2vEAeOdmXIHYOeD8nEpf8TxRePKdKLKVfxUEruFZytu/VQU5mnKfSaDQUTe9YCzJWsXI0c7qWrAknspg7RPlpBVll1ze2hDPMVRMcKB3XppqvdKwx6wrCAOINKtFm51BnQs4HFwAJsg5rIa9IM3OfEO7PU8WA9QY5BAmF7@qlnyftbd2rLUP2t8LQgAr5/CYCXAFwg9F@L3vXApCP3FLUi2fuNe9KTvKlka@WFyWDYwCRcC7FZx63/PKNrKYUHGkxiwG3uJl4QqeTzgwy2vlRhyM0apfMus8L@kiWpp9ahRETHiyMzeUnyu2/lodg5YogGd2Scg6wWDsTr3spEoNNWOdaJnhXRIXfpJMlga1m5bKaSmJuJCrFFCEgdoNak7AM64YgPmfhjLpSQOKoCJmFZ5tBtoLAQGrZmMIA@iM8ZwQJjSKRgunlTMSLuKx@vBWBisxcGmDFkF4NpjY2ItZ2akPXVSIrtA6Iy/UqBtJWeFC8zTWOtzgUMzqcelCUCHmjQkLdMOSF43lN4jUaKpu0Frdrx0eEkoY7hhWaxATAiGENg57q5iFNU7FwJLpnOfD4uRmBSWChtsbgbCTzVz5Aqlx9Miic8y6UaqNUAqczz7sBWudksRDUu7opWU4VBR5pdwa9oHGLBhGTkkRWJrvY7TjIM61RADWfdIWPdNIJI2E3gUw60IKaENfEoq20KHEgRKegdoE4Y@A27l3W8@yLwrWcu4A3KHpXarD0jzUKSyl6FxSFH9bZwcFn5Jlkd5nSZYm70FWZRL1ZYsLf1NIMnITI2SvKV12Afpn/VCQH42uwXBIODWLVO0EDLUr2ofGCMsGhRKJR2GfIm1erzeECJXiWlVVgciqSsPFI2TWOzP5t/4/a8IOKbK3DcZC5YdrJ0vOtL1QGVo1Lewzapux0iauw0OILqIdmO07iSRcZwZ3@mrT3b102EYcmYinhTIngA3i6jxCMZYmNjQJlvkJHLw@qRkauqLuVEhubpRW1WvNBW3oT9V5ja0xlRP2Qq/AaxSiqVDVQYCoBgoO/WYFtFQyU7lyAsKycr0W5QpX@sUiIbQXzkdpcavJM1kgVMUBNVQbkLMw4Um5g1WOXQD8RYyEWFIpjASptii3lzWuzKbKtlpTHoLBVpQ1NCmIDldGmSNJ5tJaKsUxnm@al/Z2BIskcQZtlXGJyp@ig90o2El7L4hiQG9HZRuOcA7hgAaLbkxasBW9l6zEIl5Ye@DiT4vUFieuFILAByNArKpnUUpZnPD8zsuaQJMdJU@SylmF4xsTIZU@FlUcmUHSIcl9JsTeA9jr3vJC0VVZ3eoK3RFgsqW5StGKVMFBKjSsoxoNcnfJseVsTMVriiiBBnUqz3k5mu7CpRzIEHg@o1WTKfFHCbtjhqHzTlruCOBXMYArnmqi46Ud/mWhL0/1MqhwzyZdSqDGj45Nb@kTo1TpivIiFNxoU5keyePoSKmUI/hBNpu8MTSqcg04KzoqXXhWBHVgRoVZjiQkztdCCXhUKHtqQVdUokCYOTEEDwMntE@m84YeCyeue2HUppB2cz6nH4nkKbOBsnGXlIzvZCFx0PDatrJFwcNME1gJxBzvgGXVaA@wY8Azc7NxTEfqZ90JqYlULNZqSBQxemO44Lbgug@qILUKD1TvqEHiSj00Cg0kPfVC4GtZpUDGqVTYBNfHXk1LFHXK2s@HuNPmX7yDpFOo0BhbRm2LemSiJYXcR/bGldwDtokYZwkmwsJ9rVIEXlt0sAraxq9a7771PNuoLpZ@1SdbgCOcC6aeNLGBNptbMAGVls10mR2ZAZ1TT7gvOKYmBtgmlDijCMahh/BI7NCeYUeIUT0UgfzWjdOI6sF4nqe3UIQF0bl0GTjZ2Jg2s6ZjezuxzJNOFNmWFy1ELyywWic0zSYpHow@C77SudFnfxbhM6Vxx6nVbRjyYYsSPWYQdDKWYKBRlWezC93WvplQhf9VYo7DMBKEfR7ptcuDLtamSbjQMxvloqahKftvjrkKY8llvn6fFVR1G85YLWxkAg1z8qoyhpA6@365hECmE4ieMWUwLWbkFvKBRTC7QIiqkYG7cZMOcrkmY1SAy@AN95HG4f9574Qm2CYLSsD@R62Wa1d7d6F6UJ2@c7IoFK5E3g6ydHRtLhhl7k22CS73NlXKD0oOg1B8HpCN5t5ur/CC2tVDyyADjo1EBLNq7OGtK34TnXDyHIrddbNCvdhE0ctAvBYKB1FAR2zcSFpGonbcawO6HdyoAaDWq01bYBzpXtfobqb5CbS9YYdN41TnLdpQOepkCg6DT/Flke1hc0S7Phh9nApA042c0OfMLk4vn8dIjT4LyhExoaE3mxSED9kAtBljLmLlmHA/TZZVqAubJFc0TKXHsQtxys0voeur6EChZ7kPmgI9t2kTv08mSqpB4XZDlrYOXZ0xnJDx2Rf@LC4lN@EJSZwntX4YOww40nh8LGDFrlF1lqIiZ8Gxcq3EUnXDnfFW@K@rG1YUPK5DQpOJYXRROnGLXX5ppTAO4qe1q9wmVFUdtF@gVYcqWcMF@g0NPrOHI6Nsc2rt4gESR01CW/PSjbi2Dkh10qbojhuxllnUfuMZrLlIolx0HgcRCvaJD0HoxOu43w1QRGxXGQNmmaY6kni1wVyNtQzj4jy4ewhpFu1dhBaDpXHBm49ZdblyzLHa1Uw8t4@sY7utI1hH@0ufuCsxVlHdQUhYJkaE4s@ZIiNkSsm2GDBOuRM1Fmi1aWLtSjbsAgIsOhO70SWmpDqNand4lC4XK06ZXea8d2R0xftNmHqpxUE@uvFQK1gjsH5IQZJv92Ga0RvQpmooXKfoK/MazryAcsMiXU3pvqAToT2CsKo7tOeVO8AWa2G/n8qAnH7pXbR@KNcBWtV@ntFem5dQjrQxdx20TFBO9EuH@yscbDUd7DadrUv2yxXsctpUkdrljjzH@DeYuPGGdbWbYa0WrwzEwq1SIhzK2A200pRbMNfryfJDY39MGr/QPfj78xBtWrKOR9ktOyd5yZrBnwe4ugjKhoEOIn4vsfSeHI2b5f5RlitngJPM1rEJxUn7PWz9OgKQ7ebEFVBVJn3eKmq6MgSTzX77n3XdGmJIHsajewWkKD5xkj61a8LitqgqfI5YE5fz6nBMRxIOc0rWhKzJcpM/r4IlkVEcWi76zRwn7LddIYJTVdpmelkvMem6ObvKAZTbTQ7DI2ycvc11bCxr3B7l1bVdBll7dav81IUqRm/QsrLmdEbf7lieYgr6MGMBTlyukXKMZy@u4dq///f@uuv3O79@/R8) Generated with [this Java program](https://tio.run/##bVdrU1PJFv0@v@IYkYcICo7IS3mpoOgootcHAYkQIPI0CaCDWAkK0QRUoIrAzBUSyKOYASZBgXNOIFR1n3Sd5F80f8RZfXDmTt17qxRIuk/33muvvdY@zywjloJnnb3fvnX0WRwO6ZbFNjD2gyQNDT/ts3VIDqfFiV8jg7ZOqR9Luc1Ou22gu6VVsuSJbZJ0/IU0ZB/stlv67w3WDQ6MWO1O6ZI0YB39vlo73NVltedaWs615hXarVh3WHPz8k2min8e0XH8pLUTz/611DVoz@3osdilDqn8f@4odA7WYa3Gbre8zM37Ho8k2Qackg1ndBQUnTtX8f3L73c8tQ1Y7C@xeH3Aae222nFErfHV8XqurfJcVYGt3Jb313P/CSofUUmSKd/YYzI7TeUmyfT3PhGouLiz/PiKwm6rs/al0@r4R2D/dVrnpUs/lkpVONWE5MSJfx02/n8vNw983zAufhwj99LhtPYXDg47C4cQvzP37yfysV2SxH/J7DQ7xU/xUfwUXxyv4fPAcQrjP4x/@/YNAHdYHY5Ch7NTHDlqtzmtkunI9W/Ny9xkm8tvLtYOcSXAvOOp@ZtcWWvqZp@5/OVyaq6Oqx@Gj9zJjK@4mavzqQQJHbn3tFgXVxYzPq5O5XM1cEvz8cQ0Vz/ebmEbz@kiNnL57chVHKF5tXiNdsiV30e44mJhNk/jNKbFb5JEBQK4xuUJ6qGfuPK2OFePjFIPT8zwRPheysVmc8gq2eCJEJfXtGARVzwkaOl@ceQ@4Oq7K2e48tuRe/c2@YIjuJJMbx9NbDh62LscophN17JsY805R26lki4ThUaoP4v60/tn22iUq0E9SiPs3SPNW9WJENl8JpBXT1aP3DsnyVZBC1c2W@gyUpK/cOVXs9leksWWGrhyiLho/BW@prO55TyxQ9b70vFKrkzokdQ@EtbDZVqcfMnvIqGus/XApZGsDb1mbq78Qta4PF2bmXiKqLmydO8q2SmiEW3hFFsiq5eBZWqezqYjmYDmB5J0uUCPnuaqIg1wJViP/LnqLUFcjspmLXDebCKrXJns4vIkl73PUR3Aq0dZqAbAWyvYZmYCSRYBEffBiLZADtPxI/dXrs5xxY0tHlyXK@JI7HB5pZdtnhvj8h6Xw@O5ABaX/YzbShlgnzxzFqCm/chN7FcVcnCBJ3xajCt@8S8RlnjiawUIQWNkC9Wgn0j4FIgkHtnOe8UVxLlIpxxHbpW59QiXfeV3bfiQx2XALdNFutfOlQ2uylyZqkL0hQJjv@bl8kw68FyPaoGU686YAYAHOaS3wQKRi5JsRQCZCS1mZB98wFVfUdovEn9/mybTKAMQwof2LiTDlTd0ls0Xss855AAR49HUHMqNUJNsQ99DTuPgoBx@8qOgHxBKhA1iIHugjmV8nWeEoILybbfppx6sH8W3NF8BUZAw9bA5wZfEzB3AVIgVRAnOrOGGcT1M1mvZBvB5STacoCubJ6HrdAoNMzSGR7SFbFyEZ1D6fhJqFtQ6JJF24KH5XosE5T2p6wJdRPBqAAHpURGS8guSZrNFZPVRD13uFzErAXzVjRBxyYlbbWyJelIJsfsrLjeC2knHLz7teSoSn6XLdPYGavscxcLh62RXJKskLwsajZ7h8m41OdS8p0mov6CSbNEkqhwR1ypvtRiIKof78WTjNaMTk3l6lOykEnTlyL2vh8D6RLiF7GRXC23wPqlnqOkqTQq0gmzRbKafnKPFdnSoIJI8jTDqUy6wxSbQlHvS@4i1LA9aApYqgTYnuESnsJ1GUSPva8FY9T1RALO2cAlnolUhFeeaWxuAor0elJ/YuDWC58FB9cP99sJCckhnx8G6JuauY59pHKmjQ3C6C80Xwz1YQw3HBZCJmXQcaY2CsYOjQp6CVgeJCd1JzaNsuAmkR1zVZJ1O6dHqMSzd1PxEGbKMlgMMskb9GV8KnFghOygWGjbho3sPSVDwsUDfa0E7dpBQ5Wk9WvkoHf/5Gki@rG8ZfO7ITQcASRkSpCDqs2ZR14S38g5a5TGK22CUaZVscWVBpCdPM3c9lR8LZMPUU8Bl9O7K82sItAuZ1HXdSSWgUohnHoqA0xba0vtQIXAFvwWToE44ZtdsgrSA8ckmXH0lEwDdgQkMYZHE2muFlKPmD0uRuiRaVp4BGS5DAN1ITw63Xrbjq8ambvRyycVnZA21NiSmgmzgYQYp3/kJH3OoB2tBwYuZHgLS@vUtNvsotY8o1XmyjlAvUr9x@q9jQ/ntJaUgZmIa1BN96HtUgiRK0CTTQ9CO5CVyoEfuIl4WFkmoH@5cqdUWus/D1MCp4j4SBEVK0ZQDJ2AqF7QYmLSUCXRrXhrLb4B47goZVeduYBuNDaHWOOoz2aFTbJNBbn5jS@Aa9Q@hMDmjBUaXQdU2a7E/W7ieHC5zoChavMdszj51im0jUSiIPGOIyFsSNNTNY88E2OaJLLjgZj8A1RaK4HXyiiCg6h0SrILqTHdQwIqCvGXvtAXmQcumXLfJbiZgBUwUsMszgqXK72SV@vHXkRuVDcB9lEPIGAR6nawxTyP@uk73SNiK/STMgP3YI2HKymQeik2j5IAcFo9UIzVlqZL6kafq62SzDWYTPApypP8BUBj2e7Sg6LSEV0wH8w7B7BgJP6Hg/qIQQ2WyBGn2Xu8FCVA@eaXzLtlgm5AAuldFwi@Y8JxbNSjbBYh4vnjEcGuEPpiOXOnTt4oJdBaZD4LcRXSxG0Wsa3qW8YF1rqrxfLJFvozRFWzIHu8Fwicrc0EbB1FuZFey7dScHn4NmjihAIDvKwv3lCCVs1IHDBA0fYbINX9zo5MutxpuKbxL/ahHYBTKJIM4wDAwxShCHt37/YblYwyiSaCprL1AJwls35AtzU@Xm7EL8xIaxF@DEoxRDzz6w4O6lOs@Mk8HyEEJWLQDi/QKWilJHJzxdRVk4If6FllvxALgi5XRKHBRPzYbWEy0kAjZPfWk766Gx3a0wMmq1n8NwNhbG@xIG1mUC6U7HL0NSpc9TvvTgWFoRWqOua@i/waOxR2TFYq52ttaTKPDP8EolKXngN6hh0Qt12pxUud1ZFLFZgGs5i8GaoKoH7UgXTmFS5x34SA7141BYQogfpSatBgucEPJVaiuHmooxZMgWITGbsKI1XfZeqgXJFb8KNo2ewdIhM64tOBtZNXLlhzCegXqkBffQ7bU1VSFjSdqsRGkAhKK@CsxnZnoY@E@YVPIVsGYoM5VoxLFJALEpgUNXZmAwAreLE@KgW8VXSWHSzKBLIiZ2YxankUHiIFHLa642p2D2tUhwVYh4m@ofAEntpBVm5CjxHQR2UbAyzU0Sj3pbeYdaaDJvswECp0ICzsB1@G@1HOXbWMoDmJyCEFSJ0FibwFbtFbpW3qklrnF1BNNzUnGQOU2WmRVzD0h6kcPLmVp8bYWfHsOMq2@h9qgX76yRUwRH9DeDtH3x1NNfKsjE2gmStnxtKQF4FOfUq76Bw21qX2YhzzD3pFDYTfqeyvw0YKXT2cm0vuQ9lAF0rcY0znUUZ5@RQ5FiupcFTQy@dNpMbTJuyjbb8JXEtrCCNiuhwSU8lqNqBjQpMsPMgHqv6fF2sCj9D6aTQ7nXDxNDkQ23vxH4LZwgA09XH9emNmM0SVrYqgXXvMFrwFKECxT5WdIQWCdf74SrOxncyWodxuMWDi7Rwyg8m5bqdGqvnTEQMLfcKuxkYjC3RgBH5VV7Kafsuns8FVEQ1bPp/Zz9AiYIvuQwaiYkzA3LpvN/WUYoOSZx8xDI3jabIKJLN7HVJh8IIxLfiV4s5Zy2QxVHBZ2oPpojM1mZSZuCJUNM5howA5IvNUGUDM16A1Ao87R5Ry6rIdEe50wxscpYD0kjOoP@qnyyQVI1cvHRkbvR/F@EdECmg/h7p1JB8Bida4cR8tevFipHsvD5/reCVRbKhWiKQalQfEetS9eniDkSWGAGyj0BkxOXskym9MRQRWZBNN@TP8bR64lvCdlIYt6QN9uuOj9O8bA49L3aCSVOMnC0J5tvO18fSLesTx0j84a9gfxgtuBucIYvUbTb7I5nPorRvNgp7aAyW8alo@5UMUgs9IFZxUr0Kd5MWmizvL2dep5yBZRg@0bQB@vYHq0rI5OPR27Yifr7U3YkY0wB9txk@siPiG7NATdl0U9WvwW@g3D@CGbr4XnIOalbrzlTJyAMaYSeQCjhHn1yAuIycBFkjD9CQ) based on [this Whitespace tip I wrote](https://codegolf.stackexchange.com/a/158232/52210). Only three characters used. Byte-size may have been through the roof by now, but at least we're back to printable ASCII. ;p [Answer] # 29. [Unary](https://esolangs.org/wiki/Unary), 1.15733 × 101780573 bytes A string of [this many](https://www.mediafire.com/file/3q4gaxco2d5jigp/number.txt/file) `0`s. Hey, at least it's ASCII. [Answer] # 3. - [Stax](https://github.com/tomtheisen/stax), 92 bytes ``` 4623432647156191461770769737389993883892004479277184806029798113267866678080 6|Er{"()[]{}"@m ``` [Run and debug it](https://staxlang.xyz/#c=4623432647156191461770769737389993883892004479277184806029798113267866678080+6%7CEr%7B%22%28%29[]%7B%7D%22%40m&i=&a=1) [Answer] # 5. MATLAB, 331 bytes Luckily, it is not specified that only free languages can be used. This works the same way in Octave. Used MATLAB here instead of Octave, since Octave offers more golfing options and is more forgiving when it comes to strange syntax, thus it can be used later more easily. ``` disp([97,108,101,114,116,40,98,116,111,97,96,227,173,183,227,125,186,227,189,121,235,95,117,227,173,123,239,78,250,247,189,251,223,207,125,247,60,223,207,118,211,78,56,239,221,187,239,95,56,243,78,180,219,222,253,243,93,119,219,174,252,235,174,187,243,79,52,96,43,39,32,54,124,69,114,123,34,40,41,91,93,123,125,34,64,109,39,41,'']) ``` [Try it online!](https://tio.run/##RVA7DkIxDDvOAylD8@knZ0EMCBiYQAJx/eKkSG@I5Dq2k@Z5/Vy@9zlvj/frcPJOXAaKidlQjayQj0TMTBB4IxHouhIPXVgq8J8fjjeTaCUHzX2XC@Tq1AdJLSS21FKhjlZZScG3slMMOUbDVVv6BfE8emKMCNY0@jxg4xAIUjVpx9ygUNwNtORqgTMjnE5g8S9gRKpQRVOMmq8zYBO1uIThApyRorkr6AZB8TCiu23n45w/ "Octave – Try It Online") (Runs in Octave) I'll bring it back to the realm of printable ASCII. It's horribly long, but I hope I'm making it a bit easier for the next one. Hopefully it won't just go back to a compressed string. ``` disp([str2num(reshape('097108101114116040098116111097096227173183227125186227189121235095117227173123239078250247189251223207125247060223207118211078056239221187239095056243078180219222253243093119219174252235174187243079052096043039032054124069114123034040041091093123125034064109039041',3,[])'),'']') ``` [Answer] # 15. [Octave](https://www.gnu.org/software/octave/), 1146 bytes Shortened it 104 bytes :) ``` k='#include <';m=~(1:10)+77;disp([k,'iostream>',10,k,'string>',10,'using namespace std::string_literals;',10,'int main(){std::cout<<"$><<\"Fb["+"泫Aѹ୽Ñ຃Á຃°ʂÑ຃Ñ຃Ñ຃Ñ൒±๳mBय़൘\0੝ЌࡢѬɳάΊ֬ୱҌݨٻ๺ӁणёĚҡ੝2Ś`ɪ¿࡯\0੯μݑלٶԋ๥ّࠜЂพѿࠠҏԢ΢ܚ؁g\0ࢆ̌ɿ׼މԌɕ؜ɸѼљ̌ંΌࡼμʇл๺ӟܜ̏ฤ֐วͯࠜעఢѢढ۲ԟ͢ਛϱࠣײРͱ̟֡ؠկഞԲܦՐНف؝ۢണڿటұฦԀచҢࢊ¯୲`ͯ‚XP੭ƈ඄Ќމ؋๤Ԡ\"ҰԢՒఢհढүଛտଟհ̠ڏचӂż൭Ѽख़Ӭࡸ׼զ".unpack("U*").map{|i|47882-i}*'' ''+")=+kCb)Fb["+"',[93+[148,0,0,0]'+reshape([~(1:154),'MMMLMMMLMMMMLMLMLMMMML',~(1:24)+77,'LMLMLMMMMMMLMLMMLLLMLLLMMLML',m,'MLMMMMMLMMMMMLMMMLLML',m,'MLMLMLLLLL',m,'LMLLMLLLMLMMMMLMMML$Q&\(()`&$/=YIZ=WQ/91Y25*Q&D$,,$&,-$$0%42838*9Y1[%WQ-Q%P2X.`/%XUY5X]W=(`,Y-1&('')+Q3<*`&0-0+`-@,,/X*$/aZAWA0A.Q$8*D*)Z1Y,Z]ZUWM2%,A0Q08.X*aZ%Y]XAW=%Q+T1L/SO:3/S7466.T]4E5&U[PE07PN_NF5%5C2$5S:E6C06:4.5^4#%@U:/96:&0T.E1%15I#=TR@`PK`)``0KO94;F:S0V6S8#/5:S:E.VNTKT(`=_935V.S.$HSaC#EBUGP7@=/M55%.DPT%S:6(T4O858U3&S'],[],4)'](:)','".unpack("U*").map{|i|481339-i}*'' ''+'')=+kCb)+++"puts "NkN''']) ``` [Try it online!](https://tio.run/##dZJrTxtHFIaVv9BfYBmvZ9e7Xu/au74sdoTDpY1Yg13b@Iab3YCVWmCDsOmXpBdo1TapJSBSpYZAbJZLk9TIBkJkEldITlOJCFzb2FwSEs2n/g26YJrmSzWao/POPGeOZuYdGUiKX0ROT4dsoCUaHxgeH4worKA1ZvsKpTmawnCTqXUwmhhFQ0MEiI4kkmMRMXYZEDRFyAuyjMZvNCUYT8i5Ii7GIolRcSCiSCQHOa5JXBuOJiNj4nCitYlG40lFTIzGUezmOTUwMp60WpWqy1Zrv7LrekiJK//e@M1e3foIrv7@YgY@@/bFhBxK@VeTTfVh2LxbWoNbG6Xp2BW4nC5Nwc1f@in4aL6SggtSNbuzUc6W7xxk4epaLfX24fFzuPVsfwIuLVZn/pitLcig/uWssPO4tA0XcmeFuXLx7czh3PHT@k9wa/l4BmbmKpOw8KC6DTOZ2lRdKksns0cTN2RW@n43tbN9WHx3u57a@flobqdQLVbv7abg48my3L1YLr76oXLeMH0ytzsFC0sH07Dw615OPvNQgnmpKsEl6c16Pb0nwYf3/1qDmcXD9Upmb203fbBwlGnk4JMH9fWTlcZ0Zf544mj@jQSfLL7ehvl0bQ0WVurfwPxsTYLSnVIOrq4Le7nSpN8JH61@/eePl@DT7yqpd7eP5Fss1TP9ylq@LjXuyk0beblpLQez9xvbMJtu5Hczr6fg0uz@5MviJbi5Wi3C5Xv7WbhQOCw2VpTkeFz@zyFU6dUoMTImjt68Fb3FmMxmvTb6pQYABQC4ErPhQ@3XsebfASJkMeAhmjET1NkIA3wskvhcHI2goXNfsQxGAIfDwV9MOfAXCSDOCD1z5jwCvF9vIg6e58/nmQJETD6Ev9j8N/If7JyzfFPyjotS/j2pcqn7URQT1CqdLXA1aPO5dBY6oGc1LnWHiiBUakKrUlEIozcbzBpLgA4hPpfWhTj1flLQIX5vgPWHfTZUIAJaWo0CgOEug1UjqCkthQvaNoLQ@TUqnRi0@@yUnXSpzJoODRakA0QwHPT6HHqEsFMuykz6NWIQCYT9dp8NceEemte5ezmDzm1ijEbSE2Y6WbU35OykTM6eaz1dLMK261Wsm@s0tlNGjiHZz5gWpM3L6SxGTk15yE4aodmrLTbPp22Cs1vABIHq7rUwrV2cm@ozus0tOpaTq8m@Hk@3BxVs1ywGto90k6pP3GJ7S@cV78dOU5tN52BZhOxwehA3Z0Q9TK@ZNXsNajcIE6EwwWAgjHIYIMD/2MNMGwyW//whP07TIDiOK0fHkwmFsmeoBwAQxk5P/wE "Octave – Try It Online") **It was time for some golfing!** Some of what has been done: * Stored `#include <` as a variable and used it twice * Stored `m=~(1:10)+77` as a variable (`MMMMMMMMMM`), and used it three times * Ripped apart the following combined Unicode characters, and created them manually. ``` '񪁬񪮗񪃐񩹌񪅰񪅔񪆑񩽓񪃓񪁋񪌱񪚺񩶑񪦢񩷒񪚃񩴲񪮸񪌭񪖢񪎍񩶔񪏭񪒫񪇼񪮫񪃣񪡒񪁂񪉒񪉠񪁏񪃁񪉒񪊰񪁗񪁢񪍓񪂠񪑍񪏓񪕗񪐑񪕋񪇒񪖻񩶑񪎀񩸂񪂝񩴲񪮗񪊌񪮖񪂓񪭗񪏃񩵍񪋱񩽋񪌢񪂎񩵂񩲎񩶒񪒦񩵀񩺚񩴱񪚯񪅝񩽽񪉭񩶨񪊽񪎆񪃽񪅽񪄍񪆨񪈬񪮖񪐑񪙘񪇣񩽗񪃰񪍍񪊳񪍓񪈰񩽕񪊀񪝌񪉒񪉗񪌰񩵗񪇢񪁋񪌳񩾫񩷱񪞨񩴱񪞅񪍽񪞚񪋼񪮖񪁐񪕒񪇳񪡋񪇰񪆋񩷁񪎥񩶰񪉾񩷠񩺀񩷢񩲟񩴲񪪤񪏭񪂔񪉝񪞚񪍌񪮪񪍒񪕒񪋂񩵋񪇡񩾭񩷱񪂂񩶰񩺗񩵓񪞅񩴱񪚑񪂬񪮕񪈒񩱕񪎲񪩐񪌃񩰰' ``` The table below show the first 12 unicode characters from the string above, with the four code points that are used to create them below. ``` 񪁬 񪮗 񪃐 񩹌 񪅰 񪅔 񪆑 񩽓 񪃓 񪁋 񪌱 񪚺 241 241 241 241 241 241 241 241 241 241 241 241 170 170 170 169 170 170 170 169 170 170 170 170 129 174 131 185 133 133 134 189 131 129 140 154 172 151 144 140 176 148 145 147 147 139 177 186 ``` As you can see, all start with `241`, then there's either `170` or `169`, while the two last numbers vary a lot. The shortest way to create long numeric arrays in Octave is to create a string, then convert the code points to numbers. If we subtract `93` from the bottom three rows, we get code points that are within the printable ASCII-range. (`93` was chosen to avoid `'` as much as possible, since they require an extra escape character. There's quite a bit more to it than that, for instance some reshaping, transposing concatenation etc, but the explanation gets long and messy if I keep going, so I'll just leave it like this. [Answer] # 1. - Python 1 ``` print 1 ``` This is the beginning of the chain. Good Luck to all! [Answer] # 18. [Jelly](https://github.com/DennisMitchell/jelly), 1889 bytes ``` “ĊƁ²ḃ7BpṠƊ}œLṣQgƝḳ>ŒCẎu⁾ʋ2Sẓݤ⁷İfṘʋẆ+ẠMċỌẏO[ƬqØẓḄvEḳĊıAĿṫvṀƥƓñðıL»;“FḂÇÐṄ2(ȦwÇọụTŀƑ'¢¬Ụḣġ1ṇ¡agx⁽ẈD,Ṫ⁶O³ḂṾɲ€shƈ'¹"F$i{S'⁹<Þ¹æ×$×ɼ/^çạȧæƈYĊ?dḳƓʠ)G¢⁵#®-[ṭ[Þċḳṛ\r6$ƙHṿụñ|ḳÑ(:ỵ©lɱ<ṂȦżḄȥ9ı³+f¤f/GẠK£p~ƁṚ£ḌBʂbṪṙTEµ1æĖ%ƙ¢>ṘœÑɦʠėỌÞ-ȧ*ẹ nṡGḣẊ6ṭs<SĠ3"¢ṅfḅḊq⁾ṫȧƤAẓe;ƭʂạ1ɲ⁽vĖ¿ɱ⁴ẒṁAẇṘ(Ṫỵḟkƭ0{ḷḥ}(ẈḣzẊ8Ƥḅ,/€ɗḄṪẹ½5ịİṗṗụ Ỵ;⁷ð®⁶Ð¥%ṠɗḲ)|ṢṘÆs⁺ƁȦḋ:Ri⁺)Ḣ⁸Ø÷`ṬẸṆ?ẓ.ụ×ĊḍɠqȧĠŀP{ḣẇ⁴ɲṇ⁴Ṿ]ṗʂİ⁾ṡWẋ1ɗʂẉOþɱ³ṅẉ`fẊṃÑƓ.Ɲ'½ỴṗŒ⁵%ṾƬȷị}Ðḥ_4ọẇụḳƓ€ṭịọ)ẇ⁺Ẇ^OÐhḳⱮċ-¹ṠǃḳọPẹ.Ɱ⁴HṣṾ}ȥ©BƬ⁶y¬tḂƓ¤IÆẏp{ọĖ&€ⱮỌm¤Sỵ¿¦`ẓċ~⁾ḷ f5ؽẠṭȧịṚẋƑ1¢YhÞmụṠẋgẆḂ!M^ƙÇŻȧỴ⁶Ɱ⁵ɱ7bhbṾƑÞÑJḄqḲØ©¶ṭṾ>ẓew,Ḷ@¿Ċ*¤m-<®þð¦ṚṄİėḥmḲKFṪ⁾)ȧµŻß⁼ȤƁụ[µ&@ċỊ_GƊḢþ¹ṡƘ\Ðtw2r⁹ṗḌḄGŀṘiṠøhɼ⁵9)ØỵṠ^tṢÆ⁹ç4Ị~ḷẉ¹⁴Ė=ṡṛỤ0S]HỌrGɱ€MvØṢẎU`..¿Ñ}⁸QƁCƝñJḲ⁵Ṁœðỵ⁸ḳ}ụọɱṪwḋowÐṡes°ẈDœẏỤ⁷Ṡ@©Æȧ@{ẈLė¹paw:⁾£×ʋŒḟµị¢ị÷X¡fẊ-ȷ[Ẓc¤<*ȧ<YɱzF{ḞȮİ⁾c(ɠḌ9ẉ׌jSṠỊ<PṬZẆHṭṢ®ṖṢḌƁGøZṡƥÇ-ḤḟqFẏfọCfPŻṂʋœ⁽SṖ^ɼṙẋɼịṣḢḶ""¬ṾQẉDʠ⁺⁸LṘ°`BĊıḥX8⁷ ẸḍṚ><ṁ¢ḥ]>rḍKQgṆ67j£¹ỵḟ;¬BĊƬỵNḟ'Ç£¡ċọh¥ṗȮƑYżŻẓ©Ṃ7×ḍṛ{p+`68¶Ọ¦ịịY6⁽6SỌp`Ṿ=½ȦRẉƥḢẎPDBĖg3ḃḄ2l¡⁴8ẹn!Tŀ5İtṙʠgĊð+Hq⁶ḅẒJ⁴ðpÐẉƝµÆƭƲṪƙḷ×p⁾'w-ụṢṭB⁴&Ọḥ9sẆıh\&%%ƲƬẇḍụḄ¡Ẹṇrʠƭ!$vṭmṘĖ1Çḟ⁵ẊpœẇỌcøḋṄƈĖƇⱮŀO¶ʠeṗ÷ ḍ⁸ṫ¢×⁸⁻Ṡżṿȷẹ©£ƇKẹI÷¥eḍ¥ƊƬ{Yẓṅ)ṣ罿2v@ƙṙ<×ƲẋdƑH"BʂĖ&ȯḅƓṇġḷỊṠƓs⁾°¥_÷Ṙ⁺ṅ6ụkIkṁŻḟdR¬ƭ⁼÷?¥xƒṁMAị5ḣ+⁺ḂṾ⁸oɦDlȮ2³ƓỌoṬ1ØgḢCQjʋLṀ?}+®³{ßỌ&}kh\#<(ọs¹J&<ƲŒȥ~ṛt=ṇỴƥh6ẋ/ cạ⁷jỊėSKtÞ]ḅḋİẏȦʂṅƘṂẋẹ⁶⁼mḳṠƊþȷṣxḤżṃ®ėÞS⁶Ɓ¬ṗAṫ{Ç*ẎWCŀUḟɠ½6J⁵5Ị⁶Ṿẹʋf-ʠɗȮ©KỊ°°9çƒẏSḂṂ[¦¶%_lRĊ⁵Ġ#?]VnḊ]HrỌ⁷:ẉ¿wOḃ9ZɗɠuḞŒƁEṚnỴ⁶ƥƙṢk]2çuN½ṙqṁsȤȯḣBỌdIṃ?ƑṀė2ṛƬẏġß%⁷tRmỵI⁴Ẇ6ẏ QİEṁƁẹçȤH8Ṁ©¦ðLɲẈ&ȤkÇṗgḲƈṫŻṀġOṂkƙsẊḅḣḋXƙfQ?Ḳ!Bṫḷ°¹ṫỌʂlƥlȧỌ⁹ȦẒ@ḳ2¦KỌƓṀʠḂọḅ³Ḣ¡ḥ6ʠ$Ṗ\ṅ/ṿɲ⁺2;Eg'ṣCṛ]ɱṃø5Ẓ[¢iỵỌ1²gḞAçÇɲƊvHþlʂżụ⁴Ċṿ¦ÇRƲpṡÑƤ-ḅAỊ-Ƙe?ȮȦBƁ⁷çŒ ẇṁỊṢɗḤ×£ƙ$ı^[Ị0®ẉĊØ⁴Ƙ)ẎṄs⁵ḣẇⱮcʠS¹9ṢṘĠ¿ÐŀGWHBżµḍƈ¿⁷ẉe⁹ġ>*ʂɼfỤ;Ṗa⁾ʋ¦Ḍ|¿ỵẒ?6⁾N*ṪḶ8Ṫİ⁻ĖvẋȤḂḣAƈṅ³ÞWʠ×Tİ^⁶ɼßḥ'7*½ɗḊ+YḟṘ¬ȥG3µọḳṣĿṇ-ḳʋṡȯẸjṢ5Ẓ+3<Ỵmƒ6Ḳ^€ŀṇẒḶ^8ṇịɦẎṗHMKK²⁺JvƬṢ€Ð&ÑuE⁶¢3ż'Ȧ¹ḋ⁻w€⁸Þ\m9ÆḍZƇæ⁺"ȮƘU]ṾWʠ⁸|Ɠṣŀiẹ©uḃẋðƑ$ʂJøḥƭṠrvẊ@ṪḍAƑḂẒÞ'ÞȤEṚ!ẊṆỤpṗȯÐ<_5ṬyZṇẉwÞ¦ĠċE⁷,ɠȧẒ:ƭḊ²ẇaXqȷ!⁵ 8÷Ṫ⁾oẓżʋẸṾ¥Ṭż¬¶ḟ$\ɦØ⁸¡ɗnṬ’“$ẹGọ`ƬỵUPṡṀȷæŻ#ƥɠ²'⁴_ṀƇ÷ÑḃḤżtṅAḢẊė2ṭƒnṛ|ṡdĖqḌ"®⁺©ßf⁽|ṡçƓẠḳḲIÇXƘȦ²J€¡aȧ9CÆb{Dr©`QḲ&Ṭo`tṀ7Ḳẓɓị$ÇıMỌɱ¿ƓB½¡ṙgɦʂ!ḄŻ)⁾6ƊȦxẈn7» ``` [Try it online!](https://tio.run/##JVeLUhPZFv0VQAQR0QGvPJSRlwqKDiLjVeQhPngooDwUdBArQSGYgJJQRWDmCp2QToqZwCQo0KcbQtU5nVPd@YuTH/Gu01ZRRZI@j73XXnut3c97h4be/viRdf3P9HI33RXah4r6EUEU7p1OL98UZLO1n38V2rfL6UCD0D@/zrpTGV9Zm9CX0waNZN0HZqJPkNWMT@hzxUJXbpk@YSwI/UtLB4@PslUsFNrHias4wvSayTrzWJB/JgRxcZUvsyRLmMmb1LiEAK4JbYZ52JIgH8tOWdFJ5hHGojDU39Mu7i@kYRoXRkRom2aoVBAPDT3qf5N1Hwl9/soZQf7Ouvdb6DccIUjK3s3OxMcH@HwhJXnX8p9NtRVm3aSarVPCoiyYz4L24bluFhN6yIqxKJ9vN701TxEhX84oRY00nHXvnaA7JR2CbHewdWSkfRPkr86x8ny@1iTIMaJiyXf4lflPXRTGHt0aspPVgsxY0fQh0rXUKjNJvxX30UjfuUag0kw3R95ztyB/0k2hLdRnZh4jZkHWfr9K90pZ1Fw5yddo@DKQTC8zvx3NKGYQOLL1Eit2Wugk54UgoUZkL3RvOcIar24zlfN5NCzIbJ/QZoXmHUVpgK0V45E6oN57iW9nZpBiKeBwH02YK/TYTmbd34UeEMSNJR7cdkqGYewJbWOQb/8yJbQDoanTp4Aq7voDl1VyYD575hwQtYNITa7XCT26IAyfmRAkKP8MNUcY3y@BDSxBd1AKtkTVk2CR3LJb9E4QxLnK5sazbp27rajQfBfvPMOXIqEBbI2tsoMeQeJC1wSZq0H0ZyXEQdMrtEVbGbVippJ23Z5y8vcgB3sXFJC5kFQXAsjMmAkn@9A9oftK7aBM/FMLS9moAhDCl54@JCPIB@bny2f510J6hIixNR1AsRFqisetA@Q0DQJq6sP/SO4BIUN1aIHsAToe4@ciJwQdfO9uYUsDeJ5N7pi@EkqQMPPwgGSLsXgbMJ3FE0QJymzihmlLpVv1PA583tL4K3CVL9PIdTaHbhmZwhZzpQAXYQ8qP0wjbZJZxzTaAzxM33uZoHaQ03eBrSJ4XUFAVkyGRP5E0txfSsPtA2x9WMZMFPzUjxBxSe6tbr7GPGlDrv6Oy52g9uxkxeOBxzJxP1tn/huo7SiKhcO36L5MlqQuSxpNnhHafi09Nr2naWS4pJrusBSqHJXXko9mAjzV1GHsbL7mtGGqyIrRvbTBNrLuQysC0htqB90rqJXC4H3YyFHTMEtJtEJ8tZMtvZosG0N7Sh5pC4iiMe0CWZ5JMLUB@xChVhVBR0BSonS/ApXYHJazGErkfS8Jq3@iBCibK7/iSPQpZOKXtq4mgDjWCMbPxG9NYD8oqH@@23P2LD1m/mmQrpW7G/hXlkTmaBCc7kLrJXAPnqGE0xJHY9FOIqtJEPblpJSmUO84TUjNSS@jargJnEdctXSLzVmx2ik8umkGKRl5NHkRWNBNFsz40qDEBt1DrdCvho8d3KchSccS66AD3fiERqpPW7Hqdjv5xzVwfN3acej85JStAJIqJMjA0@dtsqyGt/o2OuUBatvkVClMdwRZkelpC9zdyLQHEliVeUqEhtbdGL2GQPuQSUPf7bQBjUI8yxAEnLbSbR9Cg0AV/JdEgjbhmP28PGgtSbXi4isZBVwHIrCCVZroqZcijoLfr0TiObJftUUw4TLEz43kNLXr8hh@am7tRyOXVzynmyi0oy@XaBybOUR87zd8LWQePAtJUiwOUDA2aO1wf3v6EDHqy3QLgVawoHP6X1MjxT3llWClsQDeySb0tZcjhXJ0yMIIhCP1Kz2yoncQL1dlCvrn21fqzZX@87AzMKpsiIZAkEp05Itc2MkFMwEerWWUftPLEsVNUM59qaF64AaWscQIKo2jvtI9Nse3ObTmb74GprHgCMpSOFnitBgkbbse6wuk32lq1ThKYiYHOgtOnuS7yBPqoS06AvKRhhxl84xlFL6dmw/72x4GnuZKKUxO25Ds070jklJQnIUnDKiiGh/5vLnCPWjXtKuF7meUXqDEgLq2KClK/qFhFsSnrBtlVWA85BgSBnHeopvc04xP19kBVXuxnqoc0E@1Szcms0WoNIvRI3pcNlGLzMhaNQsiTd33lPub8uBOUCLrX0DCsdxjhmSXGV45FSyPS1YnqPqQgferUgfJbDmyHLw@CAqgeNrG0zs0zrfR/eyghqpvuLSbW3Uo2gXod7Hc4rg0In9pR68MWTtlFBKLxF@C2KVstR8lbGh9nvGBc66a6WK6Q79NsQ0sKJgeHOg8UX0KnBmn5EZBNd9NByz1PTjyCs0P8L5zdaAciZzLeQLrA0efI3Az2Nb8iq13OT4pXUv/YkVhEWSWQxdgFRheiBRG9@GwY/WYflgKWJLNN2giiewHumMG2XobVmFMQncE61CAKeaBOX@@15B23UXitkKPykGhPZijV3KKpHBwxtdXkoETWjt0qxkPgF6iisUAi/6lzYFipoNG6f7Jh0N3TGzbM5UTNV3/fQFL72oaQ9bI4qIUuePJFvC56oEdtJXXkIl0gLuvovle/JR1DFQoZXiwq4zFXv8GiyBro0B@3IrIUm7W46Sn15FJDfcDVzNYBtQkTb@YIbZxEpe8ugPv2LvujAhzAPFLTquZwAVuaLgOwbUiTZXYCXpFWeImLFifL7Aig6AwCaJmu3wekEiJcZmhFmQ1yNfGpelK1KEsvvt8ra@1Bgtz67EQnAISRH4yFjIzQ1wdkgaFbAkGBD1Qi0qU0SgQW5AsdGUUiRVcWZuVc14YPaWp5RklHzrWiVKeA/3lpKOXXbraX4jSNSC/LinfH5h2AQd20PAzKUXGQindRbzrdSzGPPYu9040sdRQZgZ1NlRpJGA6bJd57vBdjMIhjAwRiOksKOwt4au9NdaOFa3nbjnuxNKBHGeScjsNEpYDT4QF0YBr@WayuwO//gKB1j9BadAt3/kqxofP6O1x2fQ/x5nkzpOM0kZJ1c8xyVTgUEtpV@O9pvr0IWxDW@Tz9Fgajf6pF/CYocunMzP2IUQ9cgnZP3JmciijtvCOHssU9UAN9DH122k5rWn7qNrf0lEMc2UCZLciEklts04WDGCy9XsZhQV/NxPdoJF9iFbT1MKK0/RIZuMtbge1pfrHLbXxvLSxRadJNuUoL13mG4Z/EgLJdO05UpBYF5@vBimHeaAc5e6GBUtP98jJU9vvrnQ61WdHHSSCTbeam6ks3I0J0JGEsZotFTD/66uIhobPpw8LrSiIovmQwaQckDAwrncOV2Fw0hYfcA@LYnMe7GP1LobB1D1pWdo7SZrNtOuZI4ivpRHoPpbg/vzMzA0psCqHeSpjAMRb68C0WIfGADB6gK0XsnUrInsr15ka54D0iLSof9lS9cMLkKm3D5x8Pk3ipSJqKqYPwR6csRVQWA9cxNGaFy9TuufR/VHrIBe1zqmUginno5fy3elQvjBBw1PS@uIocxz2pm3kd9pRyRONhuwgRv541rWGV6N8JNEI3Hsc@7x725lzXNYBi6aNE1yF7uziDef7Q/la5WEHzO/4HoQLNgfaSkf0Og2/zQM49S8M5KGn5grmvYU8Oa/rGF82@uCo8gGkaVmOl6ixtnudee7zVeC/ewPI46XLilU1sLnHU1fG6FZPK1YUIMqXPbjIVYFvyM2GlPvymcdM3kKvYQI/5sv1MBuEvNaPN5uZXDhi2igCFOXca0XfQEdeVFDjx4//Aw "Jelly – Try It Online") I believe this gives me a score of **2427**. Text before and after the long string of digits are each compressed with `“...»`. The string of digits is compressed individually into a base 250 integer. Whenever a long ASCII submission gets posted it is a prime time to score some points. [Answer] # 6. [Python 3](https://docs.python.org/3/), 196 bytes ``` print('disp('+''.join(str([ord(c)for c in"alert(btoa`ã­·ã}ºã½yë_uã­{ïNú÷½ûßÏ}÷<ßÏvÓN8ïÝ»ï_8óN´ÛÞýó]wÛ®üë®»óO4`+' 6|Er{\"()[]{}\"@m')"]).split())[:-1]+",''])") ``` [Try it online!](https://tio.run/##FYmxasJAAIZfJdxyd0SFohSRDl26pg8Qj8SqxSuaC5erEmKeoUNHsR0cRTOkEIhmuf/BUp2@j@@LU7NQUb9tYy0jw@hMJjGjLqW9DyUjlhjNfKVnbMrflXamjozIZDnXhr0ZNQlxsCdb4ZDb@qZNimPweW8ZCg81Ktvggl985aie7lzj2xuiwN5eUARDlJ79ww4/aFCKDXb2jCuO9nzb5esgdKnzuH3R2Zgw7ossH5PnFeVE8F4SL6VhnPuj7oNwSYdSwQlv238 "Python 3 – Try It Online") Not bad for score, 135 bytes shorter than the previous answer. [Answer] # 7. Java 8, 209 bytes ``` v->"print('disp('+''.join(str([ord(c)for c in\"alert(btoa`ã­·ã}ºã½yë_uã­{ïNú÷½ûßÏ}÷<ßÏvÓN8ïÝ»ï_8óN´ÛÞýó]wÛ®üë®»óO4`+' 6|Er{\\\"()[]{}\\\"@m')\"]).split())[:-1]+\",''])\")" ``` [Try it online.](https://tio.run/##LZDNSsNAFIX3fYpLNjNDbUAQKVbFjUvjQnCThHaapDI1TUIyiZSYZ3DhsqiLLkvbRYVCazdzHyxOaDf355wLl/ONecE7Y/@19kKeZfDARVS2AEQkg3TEvQCsZgV4kqmIXsCjz7HwoWA9rVYtXTLJpfDAgghuoC46t0aiLyUlvsgSStqEmONYRDSTKbXj1KceG8UpePqFY/AwSCUdypgPcK6WaovzSu30eJjiop83WolrC3e4VQfc4w9@VLi9bnqBn1YX1/il9rjud3FjqV@c4TcecOO@4Uyt8A8XaqXtzePFoE3g8v0@LR3HMSiz3bJqprsJYY7hMjNLQiEpY/ZV59xtO8YZIa52mFH3mpBJPgx1yFPWokEw0aTokYrtAmcnTNNMBhMzzqV5xBCZHo3yMGQnYlX9Dw) [Answer] # 17. [Java (OpenJDK 8)](http://openjdk.java.net/), 4316 bytes ``` import java.math.*;interface Main{public static void main(String[]args){BigInteger k=new BigInteger("361465645787803556642041740125333791157289109836690832678496621620620476938008188755961262952961045044334883735032022649132976542429391791957032215373603493060060908973231820754365849983880098639334885407908312678706946342237930056305671352578126483085654455450990325300036187422582180640564627709845866957795417075379794457771084260885275651423270277115376273619152526268960916671775297982081324848038299273109785484955540448632255751457983092806398161815414681140205940443983929094227240892016130222081735443463765266530750906013199766831562981062206883501821081948064356413314877295359005754551748620326652056931891130304022998598456117784613831331553499645105355499572823602652224584622340127230019203445570907108390902756251280829226959356401632317493087775163844632433847320732669180722866971084641603496667699643270544307016691969256813927566081197091024786683700593068316853133329853126916980565101295672302657842521145965496959516667557604187718961737197699807729922479014391244358641964407038005042698897145981486166558111528268648754750105761790156735705908529827044494532735373542074188931773995823743175708985242811138374833461925235558545552543239298858693639120903294102768096905451200672090144132989460345783811846857389850888625728879562355642107076889151634052467151465205669235281987289146702267527528337652765227579834772607096297867378167970398026817606005667187750254267940709328271716135213654213584876566950507963838908925435608432108543211988380043373863076684282181314428196820459900560624029445930562805108606439494597377667022934949909491248650257423941442501130465637115392123710138139320285578930995693580243682019990534044973098092357106401611806537055780798006419839968127797560014488960920640815497049798937939978802170728965447020215687663299085285135712460422589432498713019435076232304133799479163312692117165385441054909324684626318749880002741865347863181414553280961072341916597070153405988301052811964133454660365664326014933265975677282033389713733987900066870015915215592230373098864436569203037855204983481186013802629322959015235254953356454611632992424153992307118239942840069852191457611354149092159274929329165426494771788810351821419395270672924908000688485483415366648629467837741559472196172641833145440295355695638904300466360749980832149475326839625824180597090035758161747631566626294378588544433795467707770969803888994908945743924524092368150546763216300781506983452769047662620172149595341272974866879383765780753650149826124453578901148919524983399484586399519164831435118868114641416056484708317549382655513941592665766107754640311775988857536833503400184150046460874444462574370426007012825320369557554303147313398461850454111000186338871401985456785254838518366172829415397040132093408711221497234248435036427390549018005682773833150973835234655369632873294078395344645151807175961277939873402540463065930241499535840653603495768603632925007799294792786898241888229504684122524052210587758223645174725998848750958165288764789127336269132371823288331209150791866640989489138808098191189590355822424507961982835596641625445961077819053329957513727274473281659012240134633338620306528063546531509291823793582673621854840157379632497150667941992447112735994344255393555754542931084167792498011617817577811858484359459303990519025217546545426128120668058213732780269207184049475513140841508071171466489179571732148022085619865421226980087686463817810882555691541238702979414090919943348838792478685887433470060823164562205755506913403025258116930323322200035144350860063326517842814125393604394558124262604094433995875688276997577049389085643903344779813236853388709369241795685568599627908894295210291487809974734882698802431466163144590822266263386642120435740609962270983909896397378387628019919833263785731297232046119724885501188522648477713389060005303782524378329767919011556972617597217583067932552147331643458090790141659918288419722529366943890533673108818328410954166228146653384682119894555378618098353742188919187416715990821349955676320230531868940883985817821677233033834934236649460409157978074244277935");BigInteger a=new BigInteger("27884");while(k.compareTo(BigInteger.ZERO)!=0){System.out.print((char)k.mod(a).longValue());k=k.divide(a);}}} ``` [Try it online!](https://tio.run/##ZZhLa13ZEUb/itIjKRCx37UL40mgBz0IgXTIIKEHN5YiX8t6IMtugvFvd9Y6BDqQpk3LuufuXfW9qk5/OH05/eHp@fbxw8399@/nh@enl9eLD/zy@uH0@v7692/Oj6@3L/86vbu9@NPp/Pj1@fM/P57fXXx6Pb3yny9P55uLB35/@fPry/nx7h@/nF7uPl19/eP57ie@d3f7cnH/9vH214vffnH5Q191rLnGjB279DnXGq2MGqPUNnvvkbXOaDtryd3XyrJ7W7FHrtXqaoV/R6zsu5Rd9445c9W2Ws7GD2XMMkbvY@8efZbeSmtrZO0tY83RRsuelVtyBp@2OnlulT6yl1X4lwszeut1txJz9DW5m1I2F@ZePY/D5yhhadXaoqwcq4/WKL@XMlfnT9Q@G33yyNi97Mn1Y04KzOTmyYMFOHbwvblb3WUNvjZWi@CmMTfdz4icwEMpnB3JCRFRyx5tFcpowbF1tN6i8L1qOxzAuVm5HVzWTpqqi3oiwCiSxjZ4jD1gYLdMngftoClanZQIhHRKWTM4fPKVXrJRYM9dKblS0li71lFamenzfNKzZUm6iTYAsRUe7cDvdXDBM4AECW0tmg9wAO7aa8LMAsoJibtCMCRD3yxQQKc1h9B0oKm917EjILvPBGgImhPxbFTRPZdy0EZFPlzdC/XR357CuSoA7EFN3MVBc0J6IsVaOG3ys7priKFxTmsQABetq8xosFVpqUsh9BQ56LRbZKDNCjpAidZypqXSvCIKdUXF4Lj6HgDQUOceKKyEFSe8R2tyfdBKk4caF4Qty5NZsSvBkTyeK9sEe9DmZkRQa1JQLW3EFscAF8VMl2tPW0X7/kBtdeUuKoaeEonSFs2CClKBTawEDrZAuRRAqwtzUj@ILkgM7qIqSg51w5VZKtzXRoUIdlDewBpFe@JErtzYyZM3zC1OnZOK0eZGmRgDBlECFATncxhFdQCGXcSNVANtjRwTGLpWxcIlKGnDckSHNCiLwV/41qZPHO4FkIws8CpOoDkInluxYAogVaq4Z6OVZfVFR@YAxFi7gACQwyl5EH5WxzBANi6HG/DqXAFXe0b3TpyIApXPxq7L24i1Cg4chxYlH2@3gQmnAahM4ZGAQN77iDs@M6pCSzcK1yj@4a/6b4D44sDEJPAMFTiRRCgYDw5x2DK/pj6Hr1nok9NSMrKDNvbXj/DczUF@wv9cYMhAVST6pBmNOzUbWuzaT7iQGIaEUrRLx8SbjgVoUgsDDyHPRa7As7akFCKgmVZpFGIOJLeXNk7ZJGGDI@w4ETveIzhU0V5WTiTynOciDYzsyOhHuGWr0I18uw4w3TciRQyEqs6fgEFmUwqxAovdbOI2ArWIN189vFmNW/RU/DbN05vixdL0gd9Bli4kfh/52fyauQfiwwxNo57kYiw04xkKzXc64u/4k@5QzKHiPasXw345oj5BdMA6jZFt5ByJjSSL8RaZeAq5HHYFeEibHRLQJpdLJbIjl1Z3cqRTCdFiCB4zAPh1BTnCrSlkNEiCMQwWmBshIjJlU8/plDxidcxBlnTlQHXEMrnFf6cwhLFYiBGdDP8oDqcCGF0C0XTSkKbEAZF7QI2xHZzLwORXUIQ0FLG2MfOVLMzD/tTzGoHumP@uBli2HuBh5SHnEEfeMg34EakNrtbodDWMDdClY7ChCkJxpCfb8XDyY5wKSwyWPh0ogNHZFUJrcwMM2crGDIy/7n0knwMFs2P0AFt6G8F1JBQn1u0UgpFyjCG6RJwYh4hGqIv5ES4M7i3V62GCLMa3JBVfLhIBfEhiOkyDbcbZx3rjnaLleuES4@gHfcJW36fTGjWmNeMhQo/6CRWFjWhxMU8DHOCVEv5iibkxku5MXlBogaoIeFplrKWzEx7TvFyHFwBgyj8BbazTIv7ChmO7NKncLg/HgmL@Ki6QYwxMONrHWgBKzjHYZNS5JhHzXIGgGNdaG6IYBdSEQPkMc3XHs8okVCmBS9jeoJqcpROQxT4o3n@MWoByvBQ1jTwBGfWmCwuBxWFM2KpSERP5DF3MhOJpWIuUZnPB7YQ8HKs90g11QH1V7HnIjguQKvlPGXyjNpHTTq5OVkfGM4EOX1bnHbHDSFIe7Db@gLCJLrohXNsORwzEdMEfLh7T4Q82brBhnvDMMLlplwlueDalrc6QPRY/dgNw25qV8whIAMQhxkbD/4wjVba33ipmBXUrEiYJjnc08FH3dpTXyGul7zKmGqcTbJEjZDFGX64M3cDFe3xkKrFqOC0AEpsUZyIPux0TN0wBJKCn8QXXgNQxWYCakeam7nrT3IOPaEKkZrRed9PsgSKhGKCsBVQ5AgoAw/RxxyuWyB6KZOYBM0bfx9rNfUxF3hGONZZQYcQIO5TpBEdhNVKGTLJHIOHugIFolwM3Sd8N3MEYrGE0bFSPILa7RRhdjkyYz2OsdecL9bs6KeHjAIhkfBiNxZ2eOISUYpRDNGUdgTCdmeXQtfyT8cPI8bWEORHmBt9pvjKA3DGtXSx945F54NhWxdZB@eSP63jrhLHbPXohXrBq/vc1aNuLyiBXwt@FrzmAhm2ny7aeMSsAGoBpxw1t2WGDGh4wrKoLniMc8B0M1aXRUdMEkMmGq13t4BzV4Jw0wVzPmCAU6toojMUccCy6CjBU4INpqshcVrUmfgOuIRj8yj/M5ObbFlrzNY8tLX0NQHDEV9jksWc6@UWS/KsqjB6BzVGJdtzHGEKE2fAljxObb1mu8Ezu7kIiVK4qQOcmQJeGMTnSdD1fXq7azbc/1xLfvtoRcEwYh6P7F2p24Ok4D/Sl03dNHpcoxoduDwXDBOYj3gNpiCZkg6zevlq4cKp/pY07vZQD07fh4T3gtHxlY6hxBQ8U3xHpVEJ8uerupsfWJimsOWze2tMNGhxcSdP1obqPuqSgVFNmHvOjMG4xl1mCSoEI5UB30xYoAtK2r8vsaMv5epCN3dLhgePHEWXzh6s3//N/Ak7/938C8MUePPTr@/PH28v763dPD8@nl9u/Pl3@9tT133/8y5@vfve2XH39@d@fXm8frp8@v14/v5wfXy8v370/vVzdXz883Vyerq4/Pj3e/e308fPt5dXVm/u399c35y/nm1s@evPt27fv3/8D "Java (OpenJDK 8) – Try It Online") No one likes unprintables :) [Answer] # 4. Javascript ES6, 89 bytes ``` alert(btoa`ã­·ã}ºã½yë_uã­{ïNú÷½ûßÏ}÷<ßÏvÓN8ïÝ»ï_8óN´ÛÞýó]wÛ®üë®»óO4`+' 6|Er{"()[]{}"@m') ``` Base64: ``` YWxlcnQoYnRvYWDjrbfjfbrjvXnrX3XjrXvvTvr3vfvfz333fzzfz3bTTjjv3bvvXzjzTrTb3v3zXXfbrvzrrrvzTzRgKycgNnxFcnsiKClbXXt9IkBtJyk= ``` [Answer] # 27. Python 2, 26028 bytes ``` import zlib,base64;print zlib.decompress(base64.b64decode(b"eNpdnUmuLUFyXDf0Bhl9xJgAN0FwQEgENBEIFDQTtHem2zGPvCWArKr//3v3Zkbjjbm5+b/+47/+97/8r//4x3/8j//zn//4l//6n//5b/93n1P/yq5/p+/+V573D+X8ldr/znz/R53nb++n/K36t1d7/lpr70+t91/X3+7r+Tuj/LUy/9p4/+E8f7uW/dfq5PfL8/5E/+vxcefv7PeTx995f72f+IGtry6lvV/yt9v7YSe+pv/V96v2+mvvD7xftObf+w/n/dC53197f7q9v3pqPNNfWftvvF/Xpp5D33/6el+mvh/4PsH4e/9pj17+dnl/+/1jKX/vf70/xDvtVY8+5v3d8zf08e2vnuPfeh+3lvdJz19/1+X99/c1+3w/ub8/0OIh3gcsO752x4eV+ID1N7Ye6sx46BG/1kc8aY2f0t//1bF4YH3R+5mxvPFe5Xm/nK15l+B5H6mO6tee71fGIrwf259YzM23vz/f2MYzH357j3fx3wUs78rHBsWqj3c79AHxw7GtNd44lmC927xip89hj8f7nbG/75fFm8fb6DniiLwLGZu/3/+If3q8gPGv7/NPDkb84Hz/dejbV4sHGu/KvvtQF3/Qmp/3s+Lj3hXY7Yk33qzhu0UsxftR8ZGxayceqsUJHPGRpYz4Bx+c2IX3e98Nef9u6hffddbpKpWTF++83707NZ6nV61vWfG+cU7a+3AtPjJOSlyFx+/7LndtPNYZK7Zm/BV9WhwoLdjR+V5xNp+/dbwlY7KM2u1x4rDHodw+q/FM8YCr6Hd0nwpXMP6+vSdpxd68x6b6Er1P/56XU2JPuhb86L19id+Vep9Yp5g3/ouLGsfmvSDv/g8u0vtN7+NMnY74jFji2Li4l2ERtKZ5tAun/8R2visepywuWW9ah3fXOobi/daHxX7X9tFRi12L0/Z+Jyajdk6mFjvuWfzEfPQFMj9LZy7OTF1Dp0MPyuWdWuT333Xr41sfNqTpVMQ5aoVFsUWp72e3MBuVZXlfNU75iMM1eQ9ZrLrjdo/tO1E7n4l55PW1K3Fga9yVMD9hEoYejaP7LlYc8BY3Li/r5O/1EjJt8cxxmsKMxBGKp9OzvG+m/WuY2PfftSN+7PcghT3UB74LOZvu0RnsT5zJFQe+cOhb3JwRBiJs0ntt+ECd+/ibxhroR8JMhn3Ssd/9fd04rW3q/MdTvR8YtjAONEZ92YiU9z5gpRbv5a2KxXr/sevaL13T+MVSYm3e38XmxYmOfwqbGM/Ln5tWqejXGu/X9doY9TLSC7BSeIC4xjidtXmfKdOydQjifMlVcLzi+cJdHS1v0/7rWp6Cz9CdmFiiOMhldh81XY+4F3GUX/umhWc9xpJz0EPHzusKtsaqhgMJf9AxfrIj4YYmX7B9KpusGmYuTFzsUpMNjcWUI3nPW2xLWP+pu9HjIGBG5bHDsC58MgfEdnM9mOjY0HPy6uja6JCtzu/GCsvfvO9fdGCmjGec4UeO+N2LRwcibkrsQXi0d2HeN+heKBk0zpMcbCls8TXOYZEw/++JbUevEMdb27R1NrXYmN1nc8tfo3HiNL7/13rD8oSVIHapLPxr5PQP7we/jxOfPdMGxM55wbXVE7sVty1egEdUhBPGQqtV+IhwhwoCdL3k+3Qbq3d+KGjiY44MSKyN1qeyN+9jyqiWh0fQ2scRm1r4ep2m7obMf/x3bO17LOLLwvZ0nFrY3djZOM6s9Rz6+ViJ1w6EFdJisRKLh4sLFB+kO6hLGtvyp3jpibAovFecIfyi7GIsewRLEVL0nXc/orfYnUYUFKuEoZk4cA79+6GNjZGdiffQm8ppyjoPH2025fHCd304VrM7tJRfLOwVYVP48bDLYazC6usR4/HjewmB5IIfvI+/eLF5sR26kIezGHv8YPHjxHf52fcvO5cWNx5LEVFLf/xCcZXicMXF6zKqOhQEL695wWu3jckpzWb20ckI4xkH4xBzO5zgu+JShYOcjZ0lWtBCxaZWnZ/352Qyb/gih9vSFk1ZvUVkGoslBxz/UomasZdLV1hniWu4bWnCM2RQLY/6vtr0VslYELbOwh2OTf/OXXyQdvl9wLDnuPfKAXktjALheI24vRtryP16D1++nb46fnNjgeKExZNoG5ss9LK7852KtVJQiKFvS186iBoXhvbIEXRF8/GI7/EJD1z8wF644pgmfETlq9+l0s9XvZGOkUK6OIDxPjoO8a9HUatOX/xvDB4/HhGmQusysCvVt1KfG5/wnnpZGAUV79eFydkYx0b+UnQWYtN17uMzdAvjFMV5jXNHMDEU8uvATfs4sp54s1jYVRzZhasLzx+HUj8SNq3omuh+RfrCteSahct0osMBmdyj+IdYStmqxUIpdegEKP5t+0F94z6EPE0nIC573KGw4npUbUrdOmSv1YssCSMap6fZtDjY9v9wrqTXlg8n65zcyveR42wodDlycgpID3bYF0+fHvZGEa4C1hZHfTSH8vEzD/a/EBeGO1GKO/Fq48jp6OQVDpR2b3NtdQw4HlvXRTElmU4apvfwKQa1azo+ozrrilriwWRvCf670qjw2ZE967kUQMiLxrWUy4uXjGP9yI9GTD3TlvEy4S63Y9f4MEXJhPy6OGHEIizURcKDyuzEig9nlXGlIk7C7oVbIpxPgMFnwive7ZyLvGPDjut4xPkt3ZkLXvUhWtgLO4390UoqktZJjdz3cJ9IMomzZQLrewzi3oXxWAQ/c+lvY2u12ooG9fokRN3mP/ZKrpdPjBA4As6IvOMYK4YoymcVFstZhuWLpMZnUB5ZEdBdtqJN2isy3oXDlFd4MmQhElm8czjWQvzjUxtfGVZvgeKw24I5FJIMezXFu/Vx7j3YiAsttOH8LUxanLJFtqe7WfXWwheq48zYindZZsarQnWGj6K2Llan+oK/tz1+K8ykdkw+pZM46GiHvVfIOgh5q+NLDEacuIdD/eAriJcU2es8NWxq2C/DVDJN4eQJEFqmLDUTxWo/F2a1+5+FJvhixoGpin1umow1msr+eFuQrqbbHjd98RGK3+xNMzrFleh6x4FwoLn+Oq+t+6r3ID9U9D4dYUyOLR91oZ6wzn19xkKRz+ZoNcfmy3elcU5fRx9xQ0+7zZc6cYsjHrF952Mb2I8uTZxzPZW2N+yU1oNIRDeD0xx3oq8PUgv7GRvQl78jHEwk5e8ijkZYhgsvitcVQE8iDAELirYip9Bt20SoMlNDCFCJEOLc3d2Oh7b9IgdIruD95omRECRmpz7kM2PPdLaK31cJiI6JL07RNeikoXKtTQZZ26P4KnLGsCfaOUC0yQEaoG5yhYp2FAwQ5ilTr7xvcYoTl4mDr8jBTkq7SgrPRe2JeUSe3kkmG39SVNaafytOkT+6lMfp2PtlC0Ouw1qbsZvjEBYAVP8h2ETRRHEgrTBUbii+UWEab5eHWnFlInqV5VTsV3Q85QHn8gfhQrYOyruC4XojmXhfPt6/+hSfm9rrqRU+LWf0gkQD/Hi2l34LmhkGCLVp5fnL6Fi7yq9EChXbJ08oUyTHnlBc9Q7j+LU405hJfDA+bGB0SFpiSXRvZIP0zeEIgNnsaHS9aqTMyl9B6wLMfb+XIxMBhiJfgaOKmtgwpVaPUQbgw6Kzp2Mm3ORR/Dl4tklw77y6EyK9j6vv3RwcPduTTsmoZObJQJEjtjQeNMzi2vgJbPvESXTQsgYsuKYzcftEb3LkH44bw+3omfbjTXoM7yr4bwpmAnvpxobCzWaSGVe4sN8RTHC4wvcXslLAz07COv3foxionHhbMjEQVGyoPPegNPG+71y+leXH7A6Qp/i/5ocduvmKE4YzcoWJh3fQEZ1a8Xj+SDy347zw6o8y6Qi5FEavH+QEG5iRYVeS3gSzKDiarK28ycBwbduC0+0lm2sBkWMcQwwdexYW4l3UBsS9/INaIr2aQ2SZ5E24YYdLDpiInT461kZ+hX0pLpAEDNbtWN/nXhmQvDctvmPZ3nLEwbLiU6Kko8fXShTgFgF4NYGb54sUwiaFoepC2DYWSd9HcIO75JoEfCL0XEFQwOJhTdbjl4uYsnKUl4EsbYLcHZFTU+IrCDHQZq3klhtpzotdWGk9r+7Rd6qYoCxxVsKYeGB+LpLw3M5rEr2IqppEviAbJaBgOb5fceCEkMhxHMP6j6txYZnWjV3jgcPr5rr4xUhSnIO2czPSk1ECuZcSbCJivZOBTMyNAF+Mx/SJr1RT2nDyoXyOfOr9U9g9Klvx1+NGFuRspabvkpd/fBLCMQaIwWMWMnGlVo+Ldu/fY3+bX/jRa9gCD4H8wga1V4QvurSYsKVzVLPekmD3cPkikLitWFQbJFDP+UHc9wFUEViAUlMAC8E48vOL4JyETgFF1wEkQr04YGJHY3GZgFx8R1hFuTpFnXHUI5wq5H+YT8d1k8SL00OuwpnqN81SCPCA9CiIeQDRD08VBy4eOb69fHWFSoUTeFOHchH2LNfi3m8ZxC1KzIAP9BB4Nr2WkoS4f9QUde98fGeAjUII44ZRWag8pdZIcfECVnrdfbxi/eDJIYBcDg2MvMhh6ETGY8V3Ktong+dpFKrEQVcVNw5S3kN5XVdvCfi3E6a4HMN3DixY+dRzjMl37NUe9uXxIEUhXRZUFD71vKzKPZoO1VAcrQSyORRpTuimoGRFzQtA3be74eGri7gk8UPWSZlXXFD2WkGyS2rEYkMnKX51yYWGl4o4PLPhMS8yjQ9sfDCFNZdDcXT7q/0UValbY43jvixjUELJVWZSwFod7yuNCXCsGgRJZzltSQRihVOhwMJqDoMrDhczESVGoBqcRUSO5+CaET6GF3u2bW51ZVDR2s4SffvxOnE9Ymmx2zpHzmu85NVpTKW+VBKtlrl7d23c+zYiNFEIHRb6UgISbgl4YoNh2hFiNlW1i6MKC8M38vghamKMcQ/0mfFjUcQLxO/RXW3eYbLRKMJVP08BFGxOBqpJCdpZ6jAOhH2UOxUwl2umazA7jYxB4d4yJeYoajsIS8qxtXJoVXWcxmCNj/6rg0zK12/XSB1JdmcHnOJHIf3F7FTrdwDRFcSmfesUyvnmAnCnBwTvxTsW6BMXjBxmWsQHzMQhdSR0clQXbmTXUaVyHTyOlGICQby6wdVh5uTwaX9114tKrdQAIiEuYIhNVftu0JVr1bSJsXe4UdXd5GWISQhc5ZhjE+9ZbYQHB2ZLRG8FKKlSIk7+TGz5++KLNaMSU1Q7NKxkaD5M4HPDX9XAB+tGPDpulWhScK2GZeP6KNwqiuwCNZigEYo0woyskuyXx+5DJ7MSw4RNmkA6hCsnj2IAp+OP0rkyDGDu0m3HIqdO0IEUCXDtkKl2EKGss+gGyyA1Z6VHv/AYXQxjSsbhu6mE7KHElVVzyipsa1l8puGkzu0O9JQUf6gaR+gTd3Z6nbaLmrr7LGm3RYy1n1SMFSgN27PuymvLkLkaliyqpGKKZXz9iZWizX6y5nzYC2hCj8FyFZ8OeXxWBAXIySuIlKB8R3iIajCQUwImMFFEqxZIkJIt7D+G+NoLEMhOcBY1tixgyuofyEyDJL0rqex+NkUbIiAJ9KJcqeN1nMMrugtY+UljRPmM3FqvjRHtwrRVYKhUndYxF87UueM/bO0eEG5zET2eSzjMocqquiKVf8Fq4l7En/QFcwFhxk8BRFOandfWdCWvpPY968xCei5I7ZiW35Cp0PoAPRkuqeyBiRFEx5Q3tIMR6EC3K3YApCxKLIfSSP2KM/mwctPluOKqrQhduuLi2RwtTwOGjwIEX7aARDlEIBsOmaljZPncZ5cS9eCpjyyGuWqqHA7gy0qNk8vdita/w3/A2ilYPs6NqUhQqlESLBxHl1KP2dOGZaGE0ykeTuOeKF3VY6gC0f3/yZSrnPNhgKGdy9Brf933FFZBpgblElSKobHiKgZGDvcTF1+kifi2uKxZH5q6m66Dt0xb+2NIRJjWY5sBYBgv9ySlo9usRcR2b+tDeFGdMMQzRTzmyomu0HTd9xh/LAmGF7JQVTcf45EqIm0DfZ3FmE6AT23mFLlSkEDnwNoTmgRn0rn9eyMNLorPZdO5nZsEVqRiBP/bPpGahqlJh2gm1kAnQTBuUz4j8JeCz2nz1oZcYi2uSDbDBEnX6myLklKBaOZ0CHeJL62Ja7wbF6FJpXwkVE0GOuujVShoW1nYzaP6pPuKDEmOsphc2mwoyENcgYVRurCQyynFpHKd6a3pAhtzlQlObHMzfhmuSO//RAzs5G7xiaqE7STG6QSu40we00Y1S/4KviDu5n2CTvgTl0rraX+j05ZGR6ZXV41TDTLRkucmJMDI8SRKNu1PBJpd7eGp9SsMKomPmWEUHrSDbkWsoHuFd2an608eIrrrFPwibC+5fkWfQsUC/6cbWyCqKOo4jtyeCBFXBikuI/uxA1HoKz09RDkhrcBCsQjiPYSdaMZ5szyayJBWr3FTTnIvRc64HnuTRi1Ts7qi1pMBOuVaW67mWqZ9qjGlJiTmackwevACD0k/8GxJ4k0ecp37vn6g88I5Ep48yChM0mtAtZAxxfeDRsgT6Y9Vxa2Kd+4rQ3Kb3wW4Fyc00m/lLYM10SMo3YDjpRfpI0t9zelR7Ym/HqOS9fgSN8DKwmFuKi0tIrgNuBE/H7nXILj76K8HNG0rCDGwIEfTxAVoyoFEFLUP1aE2Zb0J1JZ1ES41eZ5pNHE69Nmije4kem4cm2xsTyz1QEfvrqzNhNvKBX+oPwu6r/LURPqFGEtoQzGnPoMpBSMddygsA/6echo5ce2tmBQdxy4gdoiunCbWhJ7mq9tERRTmvI2MxYXpINMJ9i1ByrFdccnUFkBo9UCe1hEFJor1nKbSTIwb/NJMqWRmlGHjuA3whKW8xSjcYrxOxsPdZS1DGAbgInWoGfWFHc5XbKZiHQPIbGJiUPwMhdesG3bzA5QTlJ94ZVDqqHBw4VcJGoRBnEVFuhJW85VT0gvBLS4SdQNBDzKLxUZT5R+DWlUZEzaiwRopFRboj48UscW1OxiVovWND2cdMFFA5c3ZlVmp/pNXTRVLmEtGCJdCpvct4xfFflkkbkRFVcgK+Lb4ksflon5jaxUcm/kDFcsylQ/oVRSKa91VTLFnLmllXWhWuBr2iFp2g5txlL5p0U4ilxlHZfl2yOPdeGRVJ0SmvNl88Rdy+Npg566mkCcrepk9AoQuuFPxZCUqT7qYOaomi8H3EUa1QJyUBcl7ASu6eiHE9JgceVse5H2miGKiKWf8vgrpuzdigzM0p8sC7uAJuIuDCk4kxmJXxjcp6CT+1Her3DLIqqCDNarvy2A5TSiBPITHSwunwMRuc5sjKc6KuCr1tuuIc5h0QSg7F7nxdaMM3JrfuyRKXF2TkfGKxZ9OaAz2vUa8q1Hiixr7R4yrzXyr4XpCGGwxppw62XINWWv5O0W/GFc3+7DyyTgZy+0MJtiGJ3QELosbjIf90yCkmM0MDBL7hOgNjMM+9NHtLg00B8s+ytOtMS70d+M17z5EoWZXc/yaabDO+Cf+cZr4u92QU1oWjV10i51xQDW3s/OZrPtpV3rXk9uqA61dVt4WScGkGvpxWONYNA6vyJ7e+0ZVpRIdm4dQfb9m/7HVs7vmcHjiQfkrXm6XLP401+R+ELh9Mh0VxxDC0hIL1SmHqOB1+BYrHLg5UALyOok6JCRQAzMx8ZcfK94/5fKZK1COx5SKCi/upmsP0/4HOJPAxelMo/u6Fdf7BwdsQLioxuxkaV0riL0mgCiGzMkLRJcs0NhVXZbRf9RRtC6IZJs3R3L2dRFnriyZTl++7HNfCumTZHoTQGT0VJFVQvXMhAwEB4FZqyQ4HixU3DKMMCUh9wPqKg3FZSDKTjvGTzjNq0D2xKw2c/7Coi/dDhv6wxLD/uLjh2nV6idzlcPUFFew5W6r/1F9fYBqdd4SuyogMubheadjrZlewKf1MoJVFXIgRspo2E/B6FRyfdwOsZqZNOwdlMWoNMlDjZrQKlSuBpRjrrxdNFCHvKsaRbqNrsHiU7PICM8j+844BmdQ42pJ/5u8We/3902DSPzRhMYIDBoEwy6TedFHXV9Fe7Be4/LfZVJbjHmwlzjZrrEl2SqgNhOag9sSIUeNpOkYEY3Fk3WBZDBhmChAqgAxIMKC1CmQ9WzlnIY+Hj+Z/A4wRO98SBdUMAtvMIxgCz6+14E2o+KvkUGkZF8WxOth4/HQ1DJAE7lIERw95qKuLHKONEQRmOmphA/5IMpcZjBFXD4cuFAVdZQrO1/ln1XQVwhit8G2YVQhSsugDqKGMMbye5xp4bj9Hs6JgWwkq4SkqvjsfSENrVUbpo50ID/VHhvnrMhLQjNxrOVmm54QgUKZCZuHbDHpvR1UxqSs42aa3U1BGISJSuRb+xhn8zFo7UKbjCuf2JqL+llPCsZ2cXuxMBbcv/EhE+yh7x731sE80CtkR0kD2xbril2cFMFVcs8mTzWYCTGM7VqynAJ7CoFPP9ns0JM18j7WomVLgMNj8ldx72yyM8/AfCnpMvFomDhegS3CnnQ3ei3TowI+8sfeesqkvEEEPR8Hhs5QYLwlyf+xf8XrgX00sATIS5Viz6IpqjXXiMkyTHqpWTBxd1CHjmx02FWimcDlSQu41EPosP0Qt22qkqpntp5EkfWDEo358QXMelDnR7hahUj6VCPoOLRV3Abi/jSVTZaPTxdFsLt+Srw5/tLlBkalhkctUff1+ekOVi47HbbRJyfKzaTSYSLenkYxEn8byTwyeuUszkwM+UQIAfQ7Y6HgCRLCNR7EDA3xq+KXym3fExrTS3aBJNNULHp46CK9lj9emDKGSSC0e7rLkpWazzVIPGo1zM5H0v1Ll4b+v6oHpDieQEJhmgmh4urt9UhTtIGqVCNf8undJ7NkBDzdoT4cGjijF4C0gN5bww5lvL3s3+S9FCsNEomhzN98zTCZMvy1GrqjHDlG1hSSqoGf79Qmp3HKYthtPpd8TVmMJj26ntXRTlkyqaEroSiia3yegjvTZ9bXEjvmSDLKgFmPdESKChg+7e4EENkLMnCXa29UFQ0K1/nTdjEJ97PTej9fd+twlZdXcLkj/F3YH6QgXDSiehu208ZDYDimbpXb59ZMOQw7W5r7AQcmqV34qQlbojFBF6kP077MVbNZoLWkZJmE8DPJ6/2mNUQD01gbFqiYKD+dk8ts9fPnnJpWiWn8eRriqfIu3DpHt0Kshc7gUAhGk8Q4lf3D0OcqEunGXUj6USxPdqvKeXQjq7vd3SMDckzY8x5431RH9lGKdqHlTvV9o81h/xVnYzlQI8goln7oWZHZrnks60SYgqaPmc2bpsh6oC8R1Rbd2LGTw+eKTTNiMSlkXOdnqi+FShf8VPhurheBx85s2h6JI1VrDSREXwxeC0cQbU8mSBb9tJ9qTkTjikez72yDQmj3FsW7vliuZg/bWupaQKaaYTLc5/6AJiiOVsDdBkQqAkzTsFy55eSJ1VJF7TtJPQgWdaeqz25EEwUR8lanWTNDDhfm4LkbOeOANXqVl1nRNgHuYFjZzO/G9VvYWOeXQrapxSOOMCHCHKhRQzCJVDAGQMPMbiL1wRogsFmTg9tJzUio2botYEjLWjQ16d1VKLY+uhsChVt1gC5XtuQqK+FElfPTlqzrS0kdoQV6HOVd8Omp4SF4bxA9Cdlxo0CBwAP42c0KrqpiUE8nAy1ED8sHWYTAASwmCvFdfadNQF/FlLG53be2gF86RMTGZ9fsE69Zoz2Gk2lrqRkvAf3TCJYsnpPkz0LkQvN7gX3nJindVQmCHMduVOHA5CHYSz1Fz6dQqbjWubGqwmPcFROeRcXUBpumLIcNxSkQxcuMkjKcGZd77ZLHjuhlEJJMdwGheKP1Vo2pWXnhlrafjCOm6U4mm8OrXwm0nuao6cCsbpAcyFHoTmvmOta021EJiWpGdmhPmATRazaPqcaShSDMk4ncf242pwm2QmKr95S0qxcRPwD5ECRKnMRm/4SKzyNYphnepl17ZBeJl3HBnP3yS1NM+tcfJWMxE5WilZqItNs7CBYrWSKLRR5EmrSmio7kfsSS1IRJXEYqdC9wo1gZFqSe8hGMC6oZxaQq4xUo/wgntLOoNxK0ORDlLlYiXM6C+JSo87SChGpiI1MBgc0CzZqrmS5fmtNhmQ/zK8yuvD086oUaKb6UNNhUnKI0x4Gla07EFfg+xrKWvIh6o4473btprKMmU9XhaWA4DUKbRWtuuNCo8ikPtUpQVDHN70zH5H7nlTCYXBOQ7EwTSBGGVDduYhEzZAjSig8bUJ42TPowOrcXBdaOBXAgVxWfBdOMlLGniYXIrTY+bKXqIuImTtPvBBHAjOyWEhrLN5QfcMW6Phby6V/Qj2GLTlaXN+RkVTguXNmvQ+zKawBtB513urZPjL8p3jSLKM2V3cmbALa7IkNv07C+j26chXZcoJv1U4NRIFFdHXT71uP+4WIFn+HmfnfJDxeHRBdObS59eCmmLJHJC49rFBKI/ms2ItT5XOmzLI4W17WLfVQ1VlN2FsETcLQw0CTggHWgbhrJRxUyg6xklBQFKk9WYqhArZ7Vk4yERahYt/dZYU1igNAhBCaJ82utEwVP87b96iOi4eD411danP6X4hRhc1Q/oHslOebispH4dl4xTZP9bu9/bklblMgBgZeS1eOW52WefBecM1MCQFmKPE7LCplDFvd1J6FAqhodRoRXnYTYkg/GcLtblgWA0twCs1nmj9jHTQfx9Zsi4GOFCtsvJ7/WR4HJM8g8pyUNt09PLOWY1sHrrpItN4VXf9ewO6/cNxB+VxF6KktVKh6xVlPhqPo5SOmnw/Rzu3WuBt24SkJqfiVGWDMbcQXRXmW2x+4TYb3sTnzodOEIxwVYMBASVhZkYt2nhxsHK0kJQG8/hGozaYcZF63m7W/5EZmSzfYZoU+koiTB1OH9otudblNa46ZpDT+uhRhdHLlsoKN0UpZ7kBy3ZF+NajXu/R4ZgYPwy66gKtPhJZonCwzknl3UrJYVpxztGSZC48xBFOUv7rYAiUVZTEmOqk7PclFo/R0n3CPj7HEpOpGUjekz9tjVAu+MvyR2xnqKLsKFELMYAJEu+kstPpZuexTYwf4onKWSZO5F12t3fOhW8iOQAjKWmy8wbPWkXxtQsjrwOndNdw/NQIOF8LytsimC0eRWwUyH4AJKS/lwGtZYSc+D9KeQyeHWQF8oDtFyR3RcnUWtyGkv9mRJUAalGtViHMuK2vGY7aBMNyXFrH403eTgtqNaoBjMBAw4IGJ9AcboxCtidn+WUuamZFQ5qiyOgnklmJhoe86jJEh5QubyjfZ3Q62idj1XEpUuUMuoiBog9cAoUyRRcTtKdYxbpuUCs4NeaH3qVADJHlO4T01xLuwVbXqcSujo+2RJaeP33IEob+5vbSAHLnTrJg33+XjNh7odhxuY8w5LiKsY/hTH2m2UknjNZ3+ccEOkcstQBwntRnzjXsFph5JtCTU9VjIt+TtRK4+kuIqVW9MyVZsdKhid3plJFgbpZ7ZkXfUkkPLD7VzC8zSRLtvI6DKldlRSS6mpk+PUjE8dbqTO3XBVKTuFw0uYj548euF39FW52ewCzbisLaOuGL0AwZRjrZqWbP6LOzSc4J5ffyULrVz1EzJxrwJSUyqR2mTs28lSrbsZhRy3qFBPX4hkTEBfMrSuuK2bjAxopm6s5dKuYzDVGS2I20RIXyhWduNpzSasmhTxNJPPXFFGJ1CGZMBW2gmJuwOPM2LCMWE9kPdBycAnDo8NW3sbs5su+4Zpi0t+Ejls/Qf4VBTTTHIQoBSOMoMBIE9doYZMFewrlTmM0PMdKNpoJSDtOKie1m2cSRF/PUEXcBB71tFLOt2FVTWCWYbQ5dTpvtyeR7IKJrENnRRRt/3ysuCN4Jfkd4NuTyDPp6Swo4+e08Wr9SfhMDE9zEIgvYmf0ZGQBxrFErvIPFfi8I7nA+RKtpmw/Dl+al8dsRUn/mr+FIBDOWdmg/M1zCnO1dqllroJ1d1/lVpcpTZCEvyYh5I9NKvC0WioUVgEiXrLdjcKsKG7NZLtXJdlqYYxYxDdrqKIEGvYr9vmSdyjjeROsfUxBSkFMyAVDtVUCCFtFFO2ZTxfg9kYrlFVK8m5JanbieaxHU6QL0o8pAOndKsbgzFzW5hcxpjbZTtR96oFrylnmz6TOIdu1a02CIup3fbryRYctlh5GAlzP2hSKp5L2Q4ZPzQY1XBOwTuM8LSOZ1HmNUQxcytwkvk2UhSrmcw1tq1LN0IjBvqTLeAr6Vqp1wAD5EdRS74LQWlKZ9Vq1GposKRZteYse6jPmDubemfSZX6Y3cQZQH32S726/ySXj/b8u8BWTvPqWlctY3tLlM7sGHIPvZQPi8sQ5t0fyxr61YdFkMDgYe2pypw6zVf69nwd++QQZNpumVQe4vZsuciTXM5mjC0sxFJZY7kVr1iDC6gzM1H6SHoWqKyKHTAyZZ8GsnxMlESftf+UEFviFxMtgN9m6OZ6Sh5XGqoVPz7ryqMUPHS3ZK0CDYWZlTQsX1Tx8740cRXyxGJFEPCCGPGX/Vh1vGWb0jHx3EaZM4YISAaXeZZn+iKeEebacUpGT6w64GQRu/DMKY7lTpwpvloLb+7LoCFkyE/32tIxi/Xr3nILvKeKzWN+gKztSExXHXMYziuX2ywXTaE2CXUoWUzENUTfmn/u7XU78aH431rK66togUAZ6skJ2e/lYuJyV8ayKyqXdK3AXjQDd6Ny+wSZpwJqc8QBJRghGQrm5vg+Vw0b3GhYgZwsc35QoYBalJdu37ha7mhaLtDtinsAm9UmLEn/47qmRZ+PBYdGSVn7rDNVsQMrbQ5ihfb9A7akkBZ91ZBak2OktGjB616pJSxL8tSs0KLAkRSJ+mS7J9kAyOyEIreyD3r6JTj11QDWLLc5kiizpnnYKr1R/UeRvU2rxqnLnq7ikgoF1Vw+rau5iVfjJNktCYGGQxyU468wFAWtnbCiZCQ4kz0JmfEHEYJNxJ5Cpsol8hWX/l131xkz16nWq5dmOR1gM82XONy4BR2jpAJgB3XSpq0sxqmEvSmFT6tNpGqpO13cgNHs9B9aLQcb12eKUO9UCbfb2il0mvCrtAGA7RDEKheHbTifpvtsxPZ2FnO5h3Z2DINKaYY/kQpXGw6e/dJfG4W+lMSEvawOszLQnjFKCgDuKJNDNkUZgZVyfigD7Wro/FQpUgdUoGV3sQoAQapeyImRRT4268P0pJpgYuzjtDxCvz07SmHDxQw3nVQjgLY4XNT5mNSVd2Yq0J0oL9SG7um0pl9P6tx2ElEtOaBXKqbnwQFEOrRwGBZFkPmYQe8thXRN/Wwj49tps6Q1ZyI0u47FZDC1bZkjupNL7FLNHpk/t/oj8Gb0Q2Llf+kXmgk463EN8XnMJN8Awy6UNifE2x16JsC5Id9bc34IYYO+QLYoXLlFLdTsc/btYEQfOJFZCmy3hixAfFpQ0uW0pvEoaJgadHSNbabMYHH2AIi1Tto5/Oq+zaZukXdtxZpa0wXVlaViJQqqmpd5W2TJEUlqPI8FHdcwDSqfJbXXZXQBP9u8NsRWKSFxRVJhVGwLCYlAdCzT+j7zcQthp4e09+zJFSDf2m0rggS6aPxtbsFNmEI6LtLObSb/VpMl1lXv5TrQAjbzP6i711TkDNNN3/FtetogzVzP8Q2uyF5a6xkXDFVLr0fuq4PQUF5qjszX+tGEXJQnpQb3Z10A2IYgnTA/BMTj1nMgz5Ikh/nDx1Wy8SkaWHrmEVnDzoSqpSTqT8m2RxVw6mM1q+a2i++qf9cttVhvucdTIlpJDW5jYqNZ8TPbC5TUFJMraF6azT2D2TCSEbTM8UxicCt/KXIKJCzOYEeEWIFUp6hTlIq570fkXg0KWUaZy3QQb2Cxn5QEMWarBznoyy3PDcgQdBd6rePGOHN22mjFwpaCncJfRfpOeUI0p/Czw5TshTorVJaV3VEy/W5A6sv4bMtHgQ3cUkJE3iOMfra/5mIJuFkp4QJc2BytDuthpAA0XUPZ/e7S20itR71CHe3HD7Sf6VRkY0LkKKrvBPyeq6OmfHsSjRYU7tHdTOxz7I+oK0T3qI5pCdjmTs04TNNiCIk+N0tZFUMddw7MOhaaTzmAta+lNZn0Aw63BrI01/CO9RkZjAEZj1jJjpFmP3ctbFSekpYntjsTiVTLTW2tkjOm3O+RSnByZWV902E67vGYbYvoqVC7DABTsbHjAdpK8UTiKCTDBoeUxIoVjwqQktD9I6T/uOdiPvYKSBgmENhyGs1s33SlbLyfv3PDqgI6es+OhZWu7Jr7HKZI+taca832W3gVksoe7zUIIn3mJEN6CPcigGPwhQH5K+ypdyVRY0gXHbac7uIdpdowoeY2sK2ZPWeSvIPyudn0ZT5jzVbu9jho/EtqC/Uotf7oLA3Ox8qifGHnyrCwpc9zP4lF1DulCZHEnQDi8fwJUo2y8oxM4DDHyBfbpSZPM6IFhVKxezhKPaYopkRBcv33YxKSNWuFmjLMKBX0Kc9ZMHr/pdYnrUDZtFSvPhMzSlLFAYzNEsmI42WXJZVqHq+IBtBTlXteqcWdTGm3VbZEysyZtKoUyzqVYXQPvGrmA99ogs4WnQCIG4kuIUQnr28+noWVF5Iaw+Ivbi+vqapvoraZvvQcM8iC8R8ez5CT+qjzxXPJnH19MOTvSp+UXlgjcJRsEa8/+g2gbz0jatXZ4/Maxcyk9mT5zzQq4jR5BV8V1bFiFbNtSPe5FodW2QajDM/tTgwaSS0oWJ60QDM+iPkv0ud+vn5z2cBWvoEP5GQzfQKE5IUGTipIr6s89jFr6lcE2cq2SrEqlpyfkEaZye5wsh1PgfR0r1FuawOuijKwStXLkHtnWOAB17l13ZM9Pk6FUy+UG7TXjZTQi8/gFOkd9XAsE4rlQhz0FEcIiitMpMdT64T4DqbMHQzvwiKulSoFzlGMZktC78rPQ+YXYOJsbeEOs5yAxsDYfznaBvQ/9e0PuSVJBTML1LG6UhQT7o0FiUsGhISG+//TMP9MCtiVyc4Ow6aYQ65CHMpb3SXlS8MxOWczuYP6f7vEWFEKUJSzwWRNQVRS0+eqX8+KAzAVeB5HjiXpYkXLNjCqqTNNSWclweNZSdgyCW6eS4izOvRyXXX6rHWKtH2kSKFkGq9+FqalDbOfaF2ciXEsiWjqQ/u06PyknzVR3Q5q7N6d1i6xY9mrV6rYagdXN4NQr80jzifpMEvuHmEWJ2WmNJ6W0Eqnubed3AOLplfIycPENOywG+QQAejA2DpDt2+p5ujGRg0aEmK2Uwrk/9zS9nWo5m/SE72/svGwKj7tyNDdqn+JAiC8RNsMdxpSKFrNIlr1J3nKMhJq4sPBRfmzRo2MjaeAqgpBE4JEWoaDwZ08+Mc9GfMKJ0+FklkQ8TRAmlg9peFka2a5AqXbQ6YoXakoC9RWL2s1u7Z60tcP6nojWegm/h6j9JmAV480Mpyq9h1rS4xyU4U276BZggAZi2kuAAwpF67K/hq1Bw2qw0RkAy4bOtmn3oEeEs5V3Tg9BSrOnfvGGVyMdjgZKB/vaksZ2eFmfPjwjKcpKQtR3dFmsuFOhZhOz8katCqIsyRg7KrRX9AvXd3MaaT5LYkRX6mlftl2lojtRBUY6JZsaHdSTbfaZxEUl3NAJaxz3lKmOfUKqjtyl13hBLy56h0eoGQps1REBZWxniX5jxaynmxf5TjMmYNMk8DQhgHDihaY7Ekv2Z/jdJhWl+75isOd8IpSF7xVrc2QeYL2pWvkyO9Y1ItpP27yEu2s7tRzPzc7bBkZyYA8ZovPmU0SqDo24osv7RgWpgAcV8JrxiK9yZaj0klh6NcsHvLiVG/7js4rPg9hjjknOcei0ivTJYO7XfdO3Zq9E89Qjuh3QmBy/3QGyNMrqoD77Kksf2N/ZQUEe4S/zUPKSPXQUlmFYROVPqBpvZeVPfmGHk1QntYXfBZVinW165wJeE6HubXAMuYD0Jc4PXWJIbcHQv4Z6Bm3842jOraozLjwxO/JaBGLpsg2F5IIDwngvtJNWf7AeUpCBNPpRF/ZNHWyf7TnAL5IDDzuzmfFBFtX1OXFEBEvKWxm4sRy44l6NxgZ7iAnxxLd+TspdoneRXfvnL3/yeS7o9fChNx2yTX2w+pYkentd9CI1qkzgKzRpI2OpUUggDb3vh0c5CEc9M40dneKHCK0hmjQA3o7zNJSscjtAnekmVHsHJupaPHKhcPnqKmSknJfI6Gfq5DecugGfeR7Z05mnxrr2HO+z8lS7qSScruqjI15Yrf6RJI1mvLnz8I8NoqT+0lSFmhBdbTUh+tBiLmKham6CzLfKdAHZto9VakJnMnpQbJRw3e8A+y7Ab977PPctDx0I7pJiYtvcmNlS/mZlhoINUtc1AGcKGfvgJsScjRT9QDUznRpA2ICGTw+M96U8h/dmkkPcyVrEzzUYdrrJygHTcZd6WjsVGsSuhZH8cTTEdyJj9rTSC6WznXN4ZSrXUWUjnTrINQ8COxOJ8kO7mA7EvPnwMJKDGkRJcqe7m9dEPoS12Fg9CkGnqiEKYExOHHM8b1aoB57b51HCLq7ZyxOJVxwihNVb3jFIy2lFIX5mz7LJ2WIi0vCjYLZcoXPDafHaMOwhhbw2Vim5VrVZGYbSxaTEvy96b9FIZgbN13hpOwrcZtuavC+3DFyvHVVvZ8bqn7Kewc1Q4vxXXEJIj7pSnb0/ChzHf+Gta4uDdVE3pUNeH0kq9zO2U165AIV0N1liEwuTobQyjSILtbK5zuWJRiTGuIcqTeY1JEc3E1uDSzjGn+rGdknkWvCZ76tJ7chEC4sPXee20WbPKwUVxLkCAwLQHFxq+Rg+MWT4tzobVshq3xieVRexxVv2xdQcU6Zw2tA+Fba1yzfp/5HnSivzGwEbgLDGmi4yrVI2NZkfz7banxArcwbeyzS1Yqrxjd1ZtE2KgCt58mqn8qisAXZuAYhoCRdwfMkJrSDLMBQmk7i7EmmwPgZrkT/kABoz+zcX51PH0nqvzIPUauPiALD8iLNVLZhgJ1IHBd3cm7D02+LAOMUagaXRJRqaFkz8dL5tSS4c6clvTnHLqqjz0i5NfHFZzU1DdG99ZWAR/tUikQIMFuvYe/kPByUYeK8EqZn43FWditRamrDklb7z6q/0zHM6IwBpTXbQ6+7ZD+yb8VI13PyNpTfttBhgSzIIselqZ9z7ZqZwsBaclb3+mkTQ4q6NBeRrR9H9GyH37O253LdwVwcjzu8w2E8zfB2vufMicc3aV4BR4FMI2VJbM0289c4CgrmPY3wEySemol8zEMWrX9ZyYa2C2QljukVM2+qRDFSjSZrN5Yw1MHImRTovqW2fv0d4zKOc4der3xHxxzKDcJU6tdymyVcetLLzIaY+7p+PAl0lGrN3Wlibg6rvU/9ZLfKbAkFO2tGDZAWOpOZXWhevl1qNer3g11kOz2H1RTThO0jSWNzRWZao0N4zfipbzNL4g4pc3CS69M9FnVNN5uMr/ltusdgeTp1ekgN3OqLYO7Qe1Kk5jHVZwZ1XeWO6SKQ+d8Uhg88lmYKXup37B+pQ8EFl7dGQQv+OsTYWyBcSUQBu84JdtJIGw5dx4+ORs2J2PMOfEEjKx5PX4/7r6rIbYu8pIj6fnKcbrYxazNQJsuxqnCuPBoW55gDw2fK/jw5Ubow+kjkqUlX+7wMbJPPh5HzDJHXSC7Pp/OM9EbrVhhH31zJNMXVnb17qGTWpMxML5u7B1f2ZVlpSVZ8pbrOkz04mCb7ob5+5qrtHLbsr84pQrC2XJbnvaFSqlOlt0/lK5lUTjmHZdY8TkEVeIRe3C7r4WwEJt2Nzb7wmSrV89tEOz7U/0r6IjlRUtCkAOiYulQt2IHik0DaqyPc7vzaxw/are5Ycyanp8y7wYRhCnSpKgl/9NfLzwAwxCc1D1W0slIStS//w2mSVTEFBqUn1S0SBcJNpwe6fr0yld4W/aGgmeXeYtPUQNumi2TDRHAiiyXIfsFjJ8aYSRZDG4pzRMtODg+rjFaqnq5D3FjMrtHD9qsTptNJOvjJFXZbTQ+eX4mIzZpNqcCBJtt1nbgUAq4Q5TxeQqogK+GfOW5QqDCvpTTmN0P1/FATrfuyyCnlFhdApdR5qvK3K+NdLSR0+9v5W0hbKShu6dCmp1czYv+mHc/+TyIq4s8fHxJLknnCgnEg21dtEDO15lVrlhx7Idc8tlIpwfHYm/Tyl6NkynNVNcoVzzSreCMFOmHkTkaHqpxsWX+mZSmmc70655foiVey454EOui/7B7J2/JOLrOOMKPrMv15r05tduYxMaCWSC8nuVqhJm47/cQNPQUBrYtZAaTU4YRNKepucF9qXGgg94v+mLOzSLZTD2kk2n0yVzEgNjYNh9uQwHITlKW5GKEF9ijScTOXFYHQO6qkolfrEiaJnUcQLYuqFWoqa5EmL+iIploU+iqneQyLhp+TfMkObajn7Lpu9O78aD5+19Nptass1rD14J1swJw5uhSBwhTPV3hAu8nwp0zr/Ezmf8jkdXj90CCwFOcbg2Z5jbKuKXTu6o67ORCboa+/UjTWIKzyz21W5WaxasNQeJBdY9J7BmKczQvo0OvqLtZh9tNKbJt1u8r6T+qop7YuD28tTOj3NTtz10gdkm59cwa3i4w13M+rI5GmN7l/ZeUSX0xnW5Sg3plsLYtKRLZJP3GFet35zpBnkOBa589UF4+R2maIPh74SVn8jwkSI1XxJipnV/cbbISWDWZtFLMUd9YCm6fuOLNlNDOyDJleHpKTLm5loVmJCzFNHEA46yuJun0dE1CywRAC1wDYztHih7Ggl7eQTLrDNPExblPqyVYTj5R4bpl4GKGrVv5bORlxGhrBLGzrEKrwe247MVGC1czgTdLBN+dzgQmLelm9wCHPfO50SAr3RQV24RXbMvUPvSGWPHOvfArcTcvZTOHptvVXL98ij5WG6EougloM/cWaFsBN0NTiTwRyA8rt58fpK8Wo4+aIVjoBnkvAzaO2NTtkWibJEGbJ3uVPMluyJMmdp/Nhgwf5fOcOCSvKGUE7gfgU+iZQV73kkiw2PQpajsYpm54YpS4h6Y7eCZqq7dOT2bHQicq3mUzgDFC7+Kzd/sRj/WDR9jxYOs818bzhZmsEFCjL5Ky91jKsvGH3LSCZuwSi0Uo24F4c4LmkED2PQpknXVzOvbJuHgP4rqpn8fgINXcRuJkD3KXBFoU5sX36vAT8dlBWOlYpsFWNDfSgoPYDI/Xs2/VsAUl8V0TZ9qfpVhhlsT5QywxPaFsKSeKS23DKpi13TVZGyT3OIctMG1lM8zGwMB8iv8dyEjk8iB4b9JFRVnP7z5PXKHVfEdTmmFFqFhlZcHozUXRSlbbGfTX9lGxrMccebq8E3nYqIzoJIvA42eSeLUvqxH2ypLBteM1TGjmCZdNaLjP/KNI199l97bpDvV3R13k7uQooo/kFytUFSTEvr6lhsHoYFV2LWqS+kwuQ+Um9cWy1drqgmpVlYapg2+QJuwpqtTnOXsa5b5uynOZ9kqhvYjCFhVQcRieg3rYF6XZJ8Vw3zlQTBraq4sMIcLgt0w1Kq/2wgZglOuuPgxvzyrXe4afiLt2Yo132VorRWEqaCcPMjkdx5igWNYABvmb17n3ARE2cyU+Gtazu1Jwxn/PFLPhe/igPWiKsnNtyZmucrNqHsXICxDj1rVzZXnTqGa+Me26+UEnsyIEDjDBR3pUEQuudjP5NpKPTLPkxZadXQJjo0AqNazfJoj8ufooSOtGnFVSc8hb6jvmNrG7tG1V8cmT1mTl/9dBsmBNhz48qjtKg5JNOaw3qTpjzYkTeSByTWIdoCQR9pmogAL7GbWbqVkjPocGt32H3IpWcnWyA8jGAFek8DGxJLVDd5vLcmeqAuAdtbuSrupHilDBU6+UmS0w+85B2IbxtA1Cr3NqkdapTclaWFs6XohDxs5BDKJ5E7PBqNFKFDmvCI/WsN7yvKHwmJlke6qmABh6PhmOq1kp94WpWSfGj9qujeUFEKqbF/LyZor4dMEtIPpBlcRS9XTSdWfmo9RM1NdNo3CvgdnQh91Pzh1fL/ujlSzZ0F3tPVZTm1MhlOwYDZPQ0W3abLmsnUwR2rXrVX4zSmiz9RzAH42AnLwbUZHprzoTLWhZfMxKoKtlZVywZLAJEtzSD1WmVeD+p0++BoHqUZQ3Xah0A5H6gcRUAbuPyZi7LDs9mZj+CZLZuz9UVeDyV7HGVv93RdDY69WTlTgGqejFB52oKfvQ7TVKN/Qej5cf2+MIB3IK0f/X4MtViEq7c2WdrGlSzWAXE2yQYU2xd1fPtN1WkqeaM1ODPWQjGjERWTBp2TRuaDLgcm4WY/EjuoNiLP0qrVsNOgQUXLnc17zVDpePc4FM4ScEAykQmPgdb5yAZtP88Ti2BAjWbebjLvt9LLGrSE7IZec8t1Q7VrVq8YKu8IKA8z4X8H1oU2WU4F0Il5RN1nqm7mVMhFvOj2/kzmuGW1SdF79wDuSx6XlM4UL/AmGpE7Kb1o5WFPEmHaQLu0WojTys7+42nacIruZM9heUi9SqMqtj0HvNqlcd8kFXdit9cTq7zZKdy+UtNCUeKdXwT1sTQY1RcAbZdz6dcW03ZKKmGpDbr2qmPHncZiXCRnc4zofTBPEHGDrkEtSzdXP/ugAFd/WpeV3ZZMQkxqfyNqA1CiTEH2cTH4yeM1UPpRDAbloevf2+Zj4yVqe/VzJiPNds8gLP/tJRCn2sfu0Z+gTJ0TSqzztq4c9IwXETGhwHfdGA813n/VL5ThL1YbzsRn5uTfs1Dlz0v4zPdUolMmePaOGQDVaVMzXOoQbI8eSKkO/RQlFhpd8spiC0Zx9R+Js2EhEOF7tursUlr9lWjmcOHw+TL6fqBLNswALv6Ly6HOJZ1A7LOhgzVuVUx2vA91wVU25OWVG/KFpcEnmGQMxHqo/SWOzbcNJBsaQTEcAaXg5Zdjl45jHlfQnKqAjIFc3kGds24reXQNFyBZnyv9YOMD4vy4XSSdLVyXO1xa3pTk4hyceOhLesu5fHokEyCGlivS3AU0Bfwt3loOfCLDOghrO7fPFA33WRTLFp2yKIjsVjLL+vmjrXbj+sM2phJQtDMOvfAHBOZYSI/eVzG/ruldGeguycZo1siK0tFQ9a9VUuUqnm1GFXsHmU8pmkxlsAfQAYnZdx6+5E9QS7yZGEZJvA0eI0reoSINvrhUhmV2cY153EM60HRVjkowszUn6DKqzzYZVZ3P/sRgfgkKseJWBbUPvhvnN65mmmEDBCEPgjLU0wvlZSe2tpSVLkk0kbDJzJ5LUdPzezz4u9TAunkGM+WpVSjZhgiIWDbnQtF3MbZbSmtOkgo/QFmzcJI5Y5XE68v+Q8zL1xxqbW1nxTMA+Tv6Lx8pzHR7xRW2e24enJ2weJWNqU63reMRk6TZDR4z+YpBrkTcaHjNH8YgxNiV2MAXeHlGxT87WBXNdr5KWcQ5FqAMPEzteSTUWTxVNFNzoGmrgXXdXoMonyOo4BJU0tHDWo6PfNE0okLdLe6X6KXlObizkwUxuN01izmZxPvgQNvEZ6+rCRh5XMP3bglzkeKUbrVjV2gOWevHyhDlOqes3Xlm3zmyZ0txIj4oeD6chX5Ugc/29t6dsQ6JSVRMCX9K1ibbGatsJGqjSOrEG6clSrs+DuXwlOu+/DQxuMJlZYyrVdKUbOO3Uhioli22zfJeRto24wEa56yPPG2HqqK7C1p77I66boTHoxrel76vlqujJoDl3h+pp5WKIhc6QZb9he174CQM9dwwIvY5oayJ5eWcWHl4zYO+DrVgchJN47haJlCi5VWzKl1QnCul4QAM72/S5Iu07tkGhJ5/lFPRlK2vgo9g7r4UVS00Z2Y1pCUAs2kDKVIjSK98JlnmWZLgrR+9LeFe3qYUBHV18ObN6L4tK6nHF5fnhln+ZhmJQNliBsaZjufvlpx96Wo74+LBCvnXQDKTPocB49+dX3MqSvLSOIdfXecREykchYcoWk63cOEioTqk6xNA4I7adytsBKTtswY5pMJR5dPaTVBd+mKxtWLPU0tiQTZ5dNrnJScVAdOKmfLOZZm5z1OeViGFBHMQQ1NYwWOaTOoCjgroW+mU2ybZjykKpbp9tV3ymyAYxOb6l+zeEjEIKCmpdpinh5E4aC8nm+QIYjswyCUYWWpeVfZHA4FT64vCWkcd5SCYEBaigjx3LRLu+zq37S7kv5Q+ZEmC3D5F32N7qC88m04ZECJ50o5Udyg6y71i5CYS9eKccRqPsY4U7RJRFiPYIxUR+Q8CNq80DcOqlp9ztQOVS4X84mqR4sPaig1mX0/wwnw63c2TU598ZL686Ad5fyK3mi+nynMcFJPZVarcZn+YzqkJ/bCS5LZMnnjFpB+xS7nFQSf3OdsCurOFGmVg1n1aXcdywMjZp8z1tSzpH0ZNLnYRqU06bltL9VQ91SMszy3sDwZbOsON6Y21iuTfEUCHaq4/pFoqMqhsSGlZRe+RBNy+3KCpAeUW/jVPTQOwFpOp5jZ+m962zD0sHx6ElOP6z2zQOP+V5QeZ0s06fxT++i8wsiPrzlG5WT/kws/7TtUPUW3GKilIOonWqLbx8jysBbwupPjruCkBR+nZcpEkqbH62dYm+CWqgOAVpabLQeqXNNjTE/OhGvlt2HC2gIPIxxcnvgwm+FxKJ/n+hRUG+3zVqrc5IImgXdGko08gvUbtOAZ0C3nk5tiYUuUuiHPHcOeTbDZ+73o9Z0pCGzYMG+M/HjiLct4C1uAvIXcRbcSePKR7S+yufhn8Oax4kW5w7B7+8GK+7rzEj38cd1BOOfO7oxPX4xbdzW5QkRWcmsBIJpITWUsKf3SnsulmOVHxv0kxCZ3h+KO253OHemhYDDFgJd5J5JQ6+V24h7zOl3MMxK7qsvj54OEHEFRYhB3vmQnzszBKPv2o7u/KVs0K5Sk4XrSuMImOaZ3JbLnZLg6c3wS774IqIKBZqI9U0Bd+TIolBSkzrBtVtFheM/R3GM6PA5Y41bOwkpVn1SP3hsAQosRE4Ii/7JwRGDzGIsvxvPFM421iJzQ051mllXjGk43YmqO5yblXCaw3xHuZJYfB/eTpJqMCb9YmHYJ7YBtGHvDGvc0jaGiyyrZXEF9SlFchSBO7QT01TAV6piX7+wJ4tsATE0dkjMv+/owKvLQavJpo85yrp4ePmi7+myrM0YO1Z0Wpp4WZ6HUGVb9KJs2IlfRDnYzvAexpmTJneLhCn1NtXHhrNGNk9SMnIhsfVrUhzQjC4QgEowF3SYj4JJIuIO9q9cs9HT7jDWzXGU4zTJRSiSldXRsLJBpB3ghAbXExFXT3AjT8FIjxxmmLD2iMTKIkODM/1oWem2WrWkqL4joaf6AHXBWEspzZwhtM0cgv7ruTtHKk35Nm9rzGzc3swoPBOMZyRPtmJU9oPRcWZamQ+m0jPzPJ5SVuJZ7p5dpP1sDIxcrZYxQkwtoMtvfLIUO3QYJ0qysFQ81QVjjd/B3hKHxMyslFpyzDOamyLYuZ7SejLAzY3WSb43SInmukpLinX52hKLd293cgW9N/7G+kSUtmaKJjDwtkURTJkXwvKj5zAzesUd/PBTmZDaZFJ5iIb3MUX+wizGrQeYzP+4gnezdmETPtsdbdQID8iyHnEpVPF3ZIvBG70eqwD22njZO/dy4FigLQciqNUEFkPT0ZIUCuHaYEoDW0UqZ02oVEpgkOvF1JqwHkKJY38BhTzOrpKqdn5vMq3hVJroviQh+c9STGYmYWXazujJyclCdlSsrvS/Tof82f4Qd725vSIZ98z1nqAw8l+6sGGJ397T67oba1e/wORXZjmeqdjTi18g+vMPIoG1ZYhN3VK31DlVrqmHRVkm3xXxeJNPo3MiaZOpQdLcSZSNM6uJ5EFLZZgBkgfNkr+Ht8J3HGdydwuCuBNUUPeZLfsmax8AoQwvLzC1Hl806pG4F5hx7lNG88mV2mS1H3ucggMWdpSUGUl4CPINr0ch/3s8AT0hggykRERNLg6Gr6DQrHae13O6NwYVFBFA/zQCobLFk81f3sO8f8fWRMsInuVG07hZaTper47SrfFpxO/XfXUQ5Oe5ZNAktdMoZ0OmUxI1jpMudKI53aOScOQhpDqhzJgXSM1qStGxulOUy9M7pJCFpet1Pq7YOuFalaV2+2uJmLgTa7LaachSIwSveGz+jJSZDIXqxKkK3aCiYsxFH+qQ8m+6BHdGmR0czkoc0UCC7JyeSn7r7B5w9U4g4bZ6eIWzA2D+tb5ZwIRiYCodPSk8bhJLnRGHpwBPzAL71USvop2iOyXtLFSiTEi6xjNuIbVy/l09QMeJBy9hLHhemVxojMlvLLAEi7mKunloMckj8Ayg2t/nQjVB5P9kGJS6nmdycMI8pWTlr9kms6/kzWnp/zDM0SqOTpeeLP1e2gRV1rzxtI4/VWjJnUOjtDkZXecSJG9lsvU+iQVcaZQKDuXKSClQYm24pBYywJcVF9ljJ+6O9hPoJzVPElYUa8zpOGT1p9HlMrjie+upJecM5Dk1BTSXK1OS51Lic4Ra/mGI5mpj1GNlW8KfHax2tYo2OaJABzxU6fu5sYUe7OcOhmkewV7ZUuBlIDCcOl6ckpfro4yJ543bOq8HwuA5kfsWyOO2dcUTJBVR8J8k6Ge8jRfyPqjgSQ7CrHjvpK2beeKqWicwlYQ0DdwM2bucAebTC03/7MvRanqKExrKO/cB/jpZNjucq6NDpfdE3ayFPxKHonhiQMI+Lk9dSfmMUisfXU8dYxe346HuoRAQVrvL+40OO7OAncIYH28C5UnPYXyqvTZHb7whP0Z1Ma5w0RZds5zTtsFtX6lgKVzg8d5hqqsvp1bl/z8yQ+Vi0eX617aSNzGx1QwHH5V9XvjBr1AooT9AixjTKTEnmlUqHxCaziZlQX5A8EJ25hELPzKasFE6zdGPxCMor+TmPNRNlhd2SOZNPvIh/lsPF4aHGFioBi5uCdGd+VtZWaKERWJ8a3tbuvpSC6dZM0WdzMmHeoqn/KaW62jwOpkmqE7t9i23uyGrWh6IsyPFyGkW3ZS+eBOdihcq/JVHTywL40YsddLoN5KkgwaV2ZrcjO8MU6u2z9WRlYFog2EfQwKmOwbGAnOUExshpytLhzv6+RyWyhcG+rYfDjDjLmPSboCEx7pLvHRvRPINUuPPKctO0+JOjIEKHvgwsZYsFg+Y9+IkiQJtfpsxMowLu8N1kLCfsUEE0rlJNCrObCYx6KLffWN+f59R0HW/DFXGjGvGpICFPvEHcAByWhseQ3cFZ13O3r1aRk6k6mjnq//+GuLsFI+17K192PdEzABFHfAt4WV/mitAGb4+2Doq28qZl/tB8fnLqMO6ybMnSVWq9EKlfl/z5kLnVxB56Do5kBlLJAQvr+bttgCOnry4C9+OJxO4ddJ3VVX3RoNftWDOQmVI2QOUtZ3I2I2TQ7idoPUqcAn4kkTMZV4oFtqbtVZtzz0XeEeI5F2hl+BVZrunB15ligkQiowAjM5XdtH2O3h1LLlwQSo9M484rgd3LFvJGS2vOUgp/Jgt2EpeXS6Aw7wgKTClnSA8TU5p0pzsUt2EgPif8pXJkmI6aQ+yg/YBMa5raMFKwrOUio5RzGXXZnE8X80hPMt7b/oQguit+6+qpILbTHJXeuSKpgO+8HMvTjZTkBG4XMKSutXoOC4HEXE7qFSY5zYDK8oQbT808l6/5jbF/Ut1WspY9pS9mMZDz9Y+je1hzEhQCxFtFQXAMrkF8gI9cloQnzC/AWAcsouF4thJEiRwutDBGXKWKPsrTv1JfhKFIICUWDJ10u0styf0MEvlj8m5KsQEDpU7lsQCY/sdlop15e8nJuf/fv/83w8H7gw==")) ``` Nothing fancy, but it is after all my first ever codegolf. I deliberately kept it ASCII friendly, just for you, @hakr14. And yes, Python 1 and Python 3 have been done, so I'm just filling the gap. [Answer] # 28. [Win32 EXE, 231624 bytes](https://paste.ubuntu.com/p/JHd8xwRQHy/) Self unzip program [Answer] # 12. Pyth, 2017 bytes ``` Fb[19999 47817 46737 47864 44941 47673 44167 47689 44167 47706 47240 47673 44167 47673 44167 47673 44167 47673 44472 47705 44183 47738 47773 47816 45483 47739 44466 47882 45229 46846 45736 46750 47255 46942 46976 46430 44953 46718 45986 46223 44176 46665 45543 46777 47600 46697 45229 47832 47536 47786 47264 47691 45723 47882 45211 46926 46009 46382 46228 46591 44197 46265 45806 46856 44268 46731 45802 46715 46568 46952 46064 46345 47779 47882 45700 47102 47243 46350 45953 46590 47285 46318 47250 46734 46769 47102 45192 46974 45710 46926 47235 46799 44176 46635 46062 47099 44262 46458 44259 47003 45806 46376 44776 46760 45544 46104 46571 47016 45295 46873 45799 46360 46826 47001 47083 46441 46314 46491 44524 46552 46052 46522 46829 46281 46317 46120 44519 46155 44779 46681 44260 46602 44784 46696 45696 47707 44952 47786 47003 47752 47794 47802 45213 47755 47490 47881 44422 46846 45953 46335 44198 46570 47848 46682 46568 46520 44776 46490 45544 46683 45039 46475 45035 46490 47082 46203 45552 46664 47502 47881 44445 46734 45489 46622 45714 46350 46500)=+kCb)Fb[47055 44196 46955 47599 46795 46823 46762 47336 46952 47088 46346 45441 47786 44697 47721 45496 47881 44163 46350 45721 46254 47783 46158 45968 46655 44176 46936 45033 47097 46569 46555 47084 46970 46569 46475 47076 47065 46312 47003 46062 46184 45796 46122 45808 46697 45696 47786 46267 47673 47006 47881 44196 46511 44197 47016 44260 46200 47854 46410 47344 46361 47021 47865 48045 47785 45973 47867 47521 47882 45452 46814 47294 46542 47763 46462 46261 46910 46782 46894 46739 46607 44197 46122 45539 46680 47332 46923 46318 46472 46312 46603 47334 46523 45295 46569 46564 46347 47844 46681 47088 46344 47248 47690 45203 47882 45238 46270 45217 46399 44197 47083 45801 46664 45040 46667 46768 47738 46230 47755 46525 47707 47547 47705 48028 47881 44439 46158 47015 46558 45217 46319 44177 46313 45801 46457 47856 46682 47246 47690 47033 47755 47524 47848 45238 47882 45482 46991 44198 46633 48102 46217 44523 46392 48139)=+kCb)+++"puts "NkN ``` [Try it online!](https://tio.run/##fVW7bhwxDPyVgzvjGj34UpHKQEr/QDpXAdwYiFPk6y@c4WrXSJErFgKPIofDIfXx5/Pn4/H97Udf@buJR/ebmE/H2eQmsqTnOU157ga7xTrP3iy/Q9q/Pv895w3eVdhj4jwDX/ybGDKmymFHLjFkichbOkZaLAQ@Pg1oFdmHZjRbMvB12GU24NcJn57xdQXsYxAPfczylqrQx4mwNdiX71weE2gVudyD9YIZt9WBYcwLW@/IPhC5NeCcsGfGzG4Kf@mIbIN5A@xZaH5lWJD5TvsgZlSktC@FpSGvTVFytc68DszecSt7gVomONGqXRf5CUSb4CG5asyFaFnGvqt9FXuCmL3tWrJE3PW1Lt5oaYaMjfaBsyV2nBUxW5tnjRO3EjT7ZY2cI3tv@GYy@LPvYyFyQAnKjDbhb0EkrdET2jCBMrMiRBByq4PRiit@s4W8izgjyh/89wFtZME4QzlCPs3gk7VQA@AkKRbqAdj4Td06dTVOPbBS97IsaIMdTD2UHf0SdiEYXwoVNVw9mpOzsKgTp6cE8YxTA0rMxSGjHRwa2NCGSbHUKc@6fZIrKpC9KGaM6lWq5cAjuvWQc0ceBnVFbqkl09aev93fX96ec11kWC3ARnGiQGWzvNo3OFCUx5y2BZxgggLmgHOxkEDhuLkPiF@WncC6XWLmvzZUeGuycRxqkmOFh@QsZEwSJsXpJHBRGEoMQpG3007SsqtspdWYjN3WErn14FCw3k5yosW5KA5h1Hq5Fl1G@FIL72o/l0AJ/hDb4AiHUswYvewGyTcKHrVn@MQWrcYf46yrFiYzavlwIQgbHWifj8WhEIqTfAorGsZlxTF3iiToyZWb4vdzWVW9WvYgtslFwS5zpRhXevGWdyd9mBc@x1AfXTiWGJ@YQ8D9izaIGeLPzYS@U7p7weKZsOG0c5BnLaXiM2rh9C1ybcJBNj5qFvuhsYGnoQYzEeoealfx/TDlBMc1IHNtvWXXeIvaOzD0Wox1vjCkXthT24Ocddmuy0uftRy4uGrkq8bdR/ZlHQ8H9YZbwXVtzC5aXcDqjj7XMaT3@/3p4/fnr9vT6/vr4/EX) Let's keep things ASCII friendly, yeah? [Answer] # 10. [Sclipting](https://esolangs.org/wiki/Sclipting), 993 bytes ``` 丟뫉뚑뫸꾍먹겇멉겇멚뢈먹겇먹겇먹겇먹궸멙겗멺몝뫈놫멻궲묊낭뛾늨뚞뢗띞란땞꾙뙾뎢뒏겐뙉뇧뚹맰뙩낭뫘린몪뢠멋늛묊낛띎뎹딮뒔뗿겥뒹닮뜈곬뚋닪뙻뗨띨돰딉몣묊늄럾뢋딎뎁뗾뢵듮뢒뚎뚱럾낈띾늎띎뢃뛏겐똫돮럻곦땺곣랛닮딨껨뚨뇨되뗫램냯뜙닧딘뛪랙럫땩듪떛귬뗘돤떺뛭듉듭됨귧둋껫뙙곤똊껰뙨늀멛꾘몪랛몈몲몺낝몋릂묉궆뛾뎁듿겦뗪뫨뙚뗨떸껨떚뇨뙛꿯떋꿫떚럪둻뇰뙈릎묉궝뚎놱똞늒딎떤럏겤띫맯뛋뛧뚪루띨런딊놁몪꺙멩놸묉것딎늙뒮몧둎뎐똿겐띘꿩럹뗩뗛러띺뗩떋럤럙듨랛돮둨다됪닰뙩늀몪뒻먹랞묉겤떯겥램곤둸뫮땊룰딙랭뫹뮭목뎕뫻릡묊놌뛞뢾뗎몓땾뒵뜾뚾뜮뚓똏겥됪뇣뙘룤띋듮떈듨똋룦떻냯뗩뗤딋뫤뙙런딈뢐멊낓묊낶뒾낡딿겥럫닩뙈꿰뙋뚰멺뒖몋떽멛릻멙뮜묉궗둎랧뗞낡듯겑듩닩땹뫰뙚뢎멊랹몋릤뫨낶묊놪랏겦똩믦뒉귫딸밋 ``` Stickin' with the theme... This can be run in @Timwi's [EsotericIDE](https://github.com/Timwi/EsotericIDE). [Answer] # 13. [Ruby](https://www.ruby-lang.org/), 1125 bytes ``` $><<"Fb["+'泫Aѹ୽Ñ຃Á຃°ʂÑ຃Ñ຃Ñ຃Ñ൒±๳mBय़൘\0੝ЌࡢѬɳάΊ֬ୱҌݨٻ๺ӁणёĚҡ੝2Ś`ɪ¿࡯\0੯μݑלٶԋ๥ّࠜЂพѿࠠҏԢ΢ܚ؁g\0ࢆ̌ɿ׼މԌɕ؜ɸѼљ̌ંΌࡼμʇл๺ӟܜ̏ฤ֐วͯࠜעఢѢढ۲ԟ͢ਛϱࠣײРͱ̟֡ؠկഞԲܦՐНف؝ۢണڿటұฦԀచҢࢊ¯୲`ͯ‚XP੭ƈ඄Ќމ؋๤Ԡ"ҰԢՒఢհढүଛտଟհ̠ڏचӂż൭Ѽख़Ӭࡸ׼զ'.unpack(a="U*").map{|i|47882-i}*' '+")=+kCb)Fb["+"񪁬񪮗񪃐񩹌񪅰񪅔񪆑񩽓񪃓񪁋񪌱񪚺񩶑񪦢񩷒񪚃񩴲񪮸񪌭񪖢񪎍񩶔񪏭񪒫񪇼񪮫񪃣񪡒񪁂񪉒񪉠񪁏񪃁񪉒񪊰񪁗񪁢񪍓񪂠񪑍񪏓񪕗񪐑񪕋񪇒񪖻񩶑񪎀񩸂񪂝񩴲񪮗񪊌񪮖񪂓񪭗񪏃񩵍񪋱񩽋񪌢񪂎񩵂񩲎񩶒񪒦񩵀񩺚񩴱񪚯񪅝񩽽񪉭񩶨񪊽񪎆񪃽񪅽񪄍񪆨񪈬񪮖񪐑񪙘񪇣񩽗񪃰񪍍񪊳񪍓񪈰񩽕񪊀񪝌񪉒񪉗񪌰񩵗񪇢񪁋񪌳񩾫񩷱񪞨񩴱񪞅񪍽񪞚񪋼񪮖񪁐񪕒񪇳񪡋񪇰񪆋񩷁񪎥񩶰񪉾񩷠񩺀񩷢񩲟񩴲񪪤񪏭񪂔񪉝񪞚񪍌񪮪񪍒񪕒񪋂񩵋񪇡񩾭񩷱񪂂񩶰񩺗񩵓񪞅񩴱񪚑񪂬񪮕񪈒񩱕񪎲񪩐񪌃񩰰".unpack(a).map{|i|481339-i}*' '+')=+kCb)+++"puts "NkN' ``` 892 bytes shorter [Try it online!](https://tio.run/##TVLfbxJZFI7/wv4FZmKClWjUbrLdRDdREx@NLyYm@mC7DxvTuGnW7cNGjZ2phQLDT221WGAYKHZuGRmgVMCpJPgjwVAECoVqNedp3@9fUL/pdH883HvuOfec73znu/eP6Ym/9veP/XLunHB54obgdPxdXLvQqfxA@ubbMFVn34rY6sZHyfb@v5Ui9TxVivXQnYu0kqgHqfTs5mnSYm2Zkmon2yi2si3vTpb0fFf@urr7mirVbZHSqU74XbSbROLZ99FbDVavUTJnFeZa5tfwYHl3o@ejyspumJTltkTleKdGitIN9tSWuhcdir8hV3U15UZtYH7z9OTGwnC5Ue6YnaWmTExqobvZMj@62wcNE3vLzSCV0zshKr/YygFzoJKhdlRKq18KvcSWSqvPP@VJSQ0KbWUr30zsJIdKP0fr8V5hL9MPtWO74jD2RaX11OcaGYlunsqZ3gwZ0a5KqreeI71waytXl65fJU1/@GH@CG08asvfPENMke4pQtfoqf0IevYN9OzmKPu8X6Nsom80lc9BSke3pffmESrpHZNWlrazlCwPzH7GcWr696nxXyePj58Xrp0QRk7dGZ@6d//2/R9/Ghs7e/L2gxOOow6nMHLeOXlpYuTg6QTOxCxnL59yNhviWkXmbM7AesKZK8y1zceIY4k@zuQ8Z9Eq1zbCnGVUrr2KwJ/l2noB9WXc65wtqpwF/MhBfRB@ZI0zt4l72NkUZ0nUiBJnHliPgnMQcdH2vegrgocIDD96SrgP@4GD8wLiIfRdAA83chdf2zwCM1wrA0@KHfJAnhczvFxEDHU6/CA4loDjy2Meaw7gSwHEJK4VYDeAF8nAB1Y1Chxrzhw0AObmJrjpyFkFLs4BF/jCzmE9AqYL8fms3c/it/QM/FKos/TEPH7keIv2PPMG4gvwZziLyYcaIE9GvATrVg91LnLtzRr0BY/4qs0nPgcM9IxHMYdp9xND0AMYbuAnLV3Qz@VDHfQMrIAzfM8b@Armwmyv8GaFhK0TS9vvI@GdPDEb12/pxmAjNq4P@pQs3CT46DYfSTrA1apPcff4gJetF2aXLB0w33yEa3nYAPpo4ChDf8MQ/v2a//3KsTOjoz//8y0dh9/S6XQKU9N/3j0qXJm84tjf/w4 "Ruby – Try It Online") [Answer] ## 22. [Perl 5](https://www.perl.org/), 13410 bytes **13410 bytes using Windows-1252 codepage.** -8632 bytes! ``` %h=(k,'BA¶CBA¶C',U,'¶ADA ¶ADA ',e,'¶C ABA¶C ABA',N,' ',w,'¶C C¶C C',V,' D ¶C A D ¶C A ',i,'¶CD ¶CD ',Z,' ',T,' ¶C C ¶C C',I,' B B',R,' ¶AB ¶AB ',g,' ¶C4* ¶C4*',o,'C¶AB4* ¶ABC¶AB4* ¶AB',x,'¶AD ¶AD ',j,'¶A7* ¶A7* ',M,'C4* C4* ','m','¶AB4* ¶AB4* ',c,'¶CD¶CD',a,'D D D ',F,'B B ',u,'A ¶C A ¶C ',h,'¶C ¶C ',b,' ¶C ¶C','s','B ¶CB ¶C',f,'¶AB¶AB',K,'D D ',L,ABAB,'q','¶C A¶C A',p,'¶AD B ¶AD B ',r,'¶AB ¶AB ',Y,' ¶C ¶C ',X,' A A A',l,'¶A4* A¶A4* A',n,'¶C4* ABAD¶C4* ABAD',D,' ','y','¶¶',t,'¶CD 5* AB¶CD 5* AB',E,' ',v,'¶C4* ¶C4* ',C,' ',W,BABA,P,'¶ABC¶ABC',Q,' C C',H,'C C ',A,' ',G,' A A',d,'¶AB ¶AB ',J,CBCB,B,' ',O,' ',S,' ¶CD ¶CD');$_=" AB4* ¶CED¶AF ¶CE¶C4* CG¶C A¶CD4* ¶CGB ¶AB D ¶C 8* B ¶A4* B¶H D¶CD B 5* ¶AB4* B¶C 4* 4* ¶C 7* ¶CB¶CD 5*E ¶C4* ¶C BA ¶ABC ¶C A 4* ¶C I¶C 5* B ¶C4* AB C¶AB D¶CBAB ¶J¶AB6* ¶C4* ABAD¶C4* 4* ¶C4* C 4* ¶CD DAD ¶AF ¶CKDA¶C 4* ¶ABA¶C B¶C4* 5* C¶A6* ¶CD DAD ¶L¶ABA¶H ¶CD ¶AB5* ¶C D¶AB ¶CBC ¶AB4* ¶AB B¶CD4* B¶AD¶C4* ¶C 6* A C¶AD ¶C AD ¶CD4* ¶C AB A¶ADA¶J¶AD B¶CD DAD ¶CD DA4* ¶MA¶C A 4* ¶C 5* B¶CD 7* ¶CBC¶C 8* BA ¶C ¶C4* B¶H ¶C 8* B ¶C AE¶AB4* ¶ABC¶CD BNC¶CB ¶C BA ¶4* ¶CD 7* ¶CBC¶CD 5* D¶CE¶C A D ¶C4* 5* A ¶ADA ¶C BAB¶C4* C AB ¶CD B 5* ¶ABCB¶CD 4* 4* ¶C 4* ¶C CBC¶CD D6* ¶CD BA5* ¶CF ¶CGB¶C A CB¶CKDA¶AB ¶C 8* 4* ¶A5* ¶C AD ¶C7* A¶C 5* ¶AB5* ¶H D¶C 5* ¶CD AB¶CKDA¶CD 7* ¶AB A¶A5* ¶C4* A C ¶C A C¶ABA¶C4* AB A ¶A4* ¶C4* AO ¶AB6* ¶C6* DC¶C6* BN¶C4* 5* C¶CE¶C5* AB¶C4* ¶C 8*NA¶CD A¶C 7* P¶AB6* ¶CD B D B¶C A ¶C A C¶C CBC¶C4* 5* C¶C 5* ¶C4* 4* B ¶C4* AE A¶HAD¶C CBC¶C4* C 4* ¶C B¶C 8* B ¶C4* 6* B ¶CGB¶AB BA¶ABC A¶C 8* C ¶AB4* B¶CD AB¶CB ¶ADA¶AD¶C4*QB¶C AD ¶CD B AB ¶C G ¶ABN ¶C4* C D ¶CD4* B¶C7* A¶A4* C¶C 8* AB¶A6* ¶C AD¶C 4* A¶C 4* ¶C4*E¶C AB¶C4* C A ¶CD 4* CB¶AB ¶CE ¶C4* 5* C¶AB 4*R C¶CB BA¶CDA B¶CD 5* AB¶CBA¶C4* 7* ¶CD 4* C ¶C4* C AB ¶AB4* B¶CD 5* B ¶A6* ¶CD6* ¶C4*E¶A5* ¶C4*E¶C4* C D ¶CD BA4* ¶C A B ¶ABCB¶CD BNA ¶C4* 6* B ¶ABA A¶C4* C AB ¶C A S 7* A¶C G ¶CD D5* ¶C A A¶AD ¶C 4* 4* ¶AB6* ¶C A B ¶C CBA¶C4* C AD¶CD BA5*T ¶C4* AO ¶C ¶CB DA¶CD 9* ¶C A 4* ¶CBC¶C 8*NA¶C C4* A¶AD ¶C4* 4* B ¶A4* ¶A5* ¶C AB A¶CDAE¶AB4* ¶ABC¶C 8* B ¶C 5* ¶C A CB¶AB ¶CD BNA ¶CBC ¶AB B¶C A P¶C4*E¶C 8*NA¶C 6* A C¶C AB¶C 8* D¶CD B AD¶CO ¶CD4* ¶A5* ¶C CBC¶ADC ¶C5* ¶C 8* A ¶A6* ¶H¶CF ¶A6* ¶CB BA¶C 6* A C¶CD 8* ¶C A C¶C A ¶AD ¶C 8* B ¶C AD U¶AB D¶A4* A¶CD 5* AB¶C4* CO¶C 7* ¶C4* ABAD¶CD 4* CB¶AB BA¶AD ¶CK A ¶C4* C D ¶CD 4* CB¶CB DA¶C 6* A C¶AD ¶CD DAD ¶ABV¶C4* A 4* ¶AB C¶ADC ¶A4* A ¶C4* C D ¶AB 4* ¶CD 8* ¶CB ¶C4* AE A¶CDA B¶CD 7* ¶HAD¶CD DA4* ¶AD D¶CD 4* CB¶CFB¶CD 9* ¶CD DA4* ¶C4* AB A ¶C C ¶ADC ¶A4* ¶CD5* ¶C A C¶CD 5* A¶CD B D B¶AB B¶A4* A ¶CD B AB ¶C5* AB¶C BA ¶A4*E¶AF ¶A5* ¶CD D5* ¶C4* B¶C 4* BC¶C 8* A ¶AD ¶CW¶AB4* ¶CDAB¶C C4* A¶AD ¶C4*E¶C A4* ¶CD 4* 4* ¶CX¶ABCB¶CD B 6* ¶CD BA4* ¶CD6* ¶C4* C AD¶C A ¶C BA ¶C 8* D¶CW¶C4* 6* B ¶AB BA¶CK A ¶C4* 6* B ¶A4*E¶AF¶C 8* B ¶AB D ¶ABA ¶C4* C D ¶C4* A C ¶C I¶CBC¶CD BNC¶C 4* ¶HAD¶C 8* B ¶AD¶CD 5* A ¶AB A ¶C4* 7*Y4* BC¶C 4* 4* ¶A4*E¶L ¶C 4* ¶C 8*Z¶C ¶C4* C A ¶C 8* AB¶C I¶CX¶CD BNA ¶C C ¶C CBC¶ABC ¶A4* A¶AD ¶A4* ¶CB DA¶CB BA¶C I¶C 4* A¶CD 5* A¶CD 8* ¶AB B¶CO ¶ABC ¶C C4* A¶AB¶C B6*N ¶C4*QB¶CD B 6* ¶C 8* C ¶C4* ¶CD 4* 5* ¶C4* CO¶A4* B¶C AB A¶C 8* 4* ¶CD A¶C AB ¶C4* C A ¶C AE¶AD A¶C4* L ¶ABA ¶AD ¶CBAB ¶AB6* ¶C ABN¶C6* ¶CDAB¶CD D6* ¶C5* AB¶CD 8* ¶C4* L ¶Ca ¶C4*QB¶ABC A¶CK¶C 5* B¶C 8* AB¶C CD ¶ABC ¶CD4* ¶CDAE¶ABA b AB A¶AD D¶C4* L ¶ABCB¶CD B 4* ¶AD D¶C 6* ¶CF ¶CD 7* ¶CBA¶C AD ¶ABA ¶J¶C 4* ¶C4* 4*I¶C AB ¶C 8* 4* ¶C4* 6* ¶C CBC¶C 4* 4* ¶C C¶C AB ¶A4* A¶C A ¶CGB ¶C 5* D ¶J¶C 5* B¶ABCB¶CD B D ¶CB¶C AD ¶ADAB¶C4* AB C¶C4* A C ¶C ¶C5* ¶ABA ¶C4* C D ¶AB 4* ¶C A A¶CK5* ¶C 5* B ¶A4* ¶CD 5* D¶AB4* ¶CD 9* ¶A5* ¶CB¶A6* ¶AB A ¶ADA ¶C 8* B ¶C 5* D ¶C4* 4*I¶ADN¶CD 4* 4* P¶CD 5* A ¶AB6* ¶C C4* A¶AB D ¶CD D5* ¶C4* ¶CD B 5* ¶C A4* ¶CD B 4* ¶C4* AB A ¶CD BA4* ¶C C4* A¶CKDA¶C A 4* ¶C4* AB C¶ADA ¶C 4* ¶ADA ¶CD DA4* ¶ABA A¶C4* C D ¶CD4* ¶C 8*Z¶C4* AB C¶CD4* B¶C C¶C 5* ¶C C¶C 4* 4* ¶C4* AB C¶C4* 6* D¶CO ¶C ABA¶CK AB¶C4* 6* D¶ABC ¶AB4* B¶CD DAD ¶ABA ¶L¶C ¶C ABN¶ADA¶CD B AD¶CD B 6* ¶CD B 4* ¶C4* C AB ¶C4* ¶C ABNc D 4* ¶ABN¶C 4* ¶CKDA¶H D¶C4* 6* D¶CX¶CD DAD ¶CB¶CD 5* AB¶Jc6* ¶A6* ¶C4* CG¶C 5* D ¶ADC¶C CBA¶C 4* ¶H ¶CKDA¶AB BA¶A4* A¶CD6* ¶C 5* B¶C4* AO ¶C CD ¶Ca ¶A6* ¶CW¶L¶ABC A¶C4* CEB¶AB D ¶C4*Q ¶C 8* 4* ¶AD B¶C4* A C ¶C A ¶ABA ¶C 4* ¶C 8* AB¶A7* ¶C4* B¶C 4* ¶C4* CEB¶C A C¶CD 5* D¶ADA ¶C BAB¶CKDA¶C A B ¶ABA ¶CK5* ¶AD B¶4* ¶C4* AB C¶ABC ¶CD B 6* ¶CDA B¶CD6* ¶C4* ¶Ca ¶CB ¶CD 5*E ¶C BA ¶AF¶H¶C 5* B¶ADA ¶A4* c 8* ¶C ABN¶C 5* ¶C 8* A ¶C4* A 4* ¶CE¶CD 5* B ¶A6* ¶C CD ¶CK¶CD B D ¶H¶C7* A¶C5* ABdB¶CD BA5* ¶ABN¶C AB¶C I¶C4* C A ¶ABN ¶C 8* AB¶C4* AB C¶CD ¶A4* A¶A4* ¶CD B AB ¶CE¶A4* ¶A4* ¶ABA ¶AB5* ¶C 4* A¶C 8* C ¶C AB ¶ABA ¶C C¶AB ¶A7* ¶C A ¶C 4* ¶ABA ¶CK4* ¶CD BA4* ¶ABC ¶C4* CEB¶C A D ¶C 5* B¶AB Be¶C4* L ¶ADA ¶H ¶CDAE¶C5* AB¶C C4* A¶AD D¶C ¶HAD¶C4* AO ¶C4* 4* B ¶C 8* A ¶C4* L ¶AB 4* ¶C 8* C ¶AD ¶AB D ¶C BA ¶C7* A¶CD B D B¶A5* ¶CB DA¶AB4* ¶AD ¶C4* CO¶A4*E¶J¶C D¶C4* 6* D¶ABCB¶CD 5* AB¶C A C¶C CD ¶C 8* A ¶ABC ¶C4*E¶C BAB¶C AE¶CK5* ¶C CBC¶CD D6* ¶C A¶CD 9* ¶CD AB¶C AB ¶CGB ¶CD 7* A¶CD DA4* ¶C A ¶C 8* BC¶C 8* A ¶C4* AO ¶C4* C AD¶CK4* ¶C AB A¶CD 4* 4* ¶C 4* 4* ¶CD4* ¶C4* CEB¶CW¶CD B AD¶CD B 4* ¶A4* ¶C4*E¶C 4* ¶ADA ¶ABC ¶C BAB¶C4* L ¶CB ¶C 8* AB¶M fC A¶ADN¶C4* C AD¶AB D ¶C A¶C 5* ¶C4* A 4* ¶CD 4* CB¶ABAD¶C 4* ¶CD 5* D¶CB ¶CD5* ¶CK¶C AD ¶AB C¶A6* ¶AD ¶COg AB A ¶A5* A¶AB C¶AB5* P¶C A¶CD¶CBA ¶A6* ¶C4* AB C¶C4* B¶C D¶C A4* ¶C AE¶A4* A ¶CBA ¶ABA ¶CKDA¶ADC¶HAD¶CB ¶L¶AB4* ¶CD B 5* ¶CB¶CD A¶ADAB¶C4* 5* C¶C B¶C4* AB C¶C A 4* ¶C A4* ¶ADA ¶CDAE¶C C¶AB5* ¶C 7* ¶C B¶C 8*NA¶C4* 4* B ¶CD BA4* ¶C 8* B ¶A4* A ¶CD B 6* ¶AB 4* ¶C4* ABAD¶ABCB¶AB D¶Ca ¶C A D ¶C A¶C 5* ¶ABA ¶CGB¶C 8* BC¶C G ¶C A C¶ABA ¶4* ¶CD B D B¶H D¶Ca ¶CD¶AD B¶CD¶C4* 6* ¶AB D ¶CD 4* 4* ¶C 8* B ¶CD 5* A¶CGB¶AB ¶C 5* ¶C ABA¶C 8* B ¶C4* ¶C A 4* ¶CD 7* A¶C4* L ¶CK AB¶C 4* ¶CD 4* CB¶C A 4* ¶CD B 4* ¶CDA B¶A6* ¶C BA ¶C 4* 4* ¶ABC ¶AB4* ¶ABC¶A4* A¶C A B ¶4* ¶C4* C AD¶C AD ¶CDAB¶AB C¶CD 5*E ¶C ABN¶ABA A¶C A ¶ADA ¶C I¶C BA ¶C 5* B¶CD 9* ¶A4* B¶CD 4* 4* ¶C4* C 4* ¶AB B¶C D¶C A C¶CGB ¶C 5* ¶CD BNAb 5* ¶CGB¶AD B¶C4* AO ¶ADA ¶C A CB¶C6* ¶H ¶C4* AO ¶CD AB¶C4* 4*I¶C CBC¶CD 7* A¶C 8* D¶C 8*NA¶CDAB¶C5* ¶C4* 6* D¶C 8*NA¶CD BNA ¶ABC A¶CGB¶CD 5* ABhC4* A¶C A ¶ABN¶CB DA¶C B6*N ¶C A CB¶C BA ¶CX¶CD 4* 5* ¶CD B AD¶C A A¶AB¶C4* AB C¶C4*QB¶CD 4* ¶CBA¶C4* C AB ¶C 8* C ¶CD B D B¶J¶ADAB¶C BA ¶CD 5* A¶C A ¶C4* 5* A ¶C A ¶AB6* ¶AB4* B¶C G ¶C C4* Ai4* CB¶C4* AE A¶C4* ¶CD B 5* ¶C4* 6* ¶CD BNA ¶C4*QB¶C A C¶C AD j¶A6* P¶C A¶CBAB ¶C4*Q ¶C4* ¶AB B¶CD D5* ¶C4* AB C¶A6* ¶C 8* 4* ¶ABC ¶C4* 5* A ¶CD 8* ¶C4* 6* ¶AD D¶C AB¶A5* ¶C 8* B ¶CBA¶CDAB¶CK AB¶C ABN¶C4* 6* B ¶C AD ¶C G ¶CBC ¶C C ¶C ADA ¶C4* C A ¶CB k CBA¶C 8* 4* ¶AD ¶C4* C D ¶CD B 4* ¶C 8* A ¶CB l ¶C CBA¶C AB ¶CB¶C C4* A¶CD 5*E ¶C 4* ¶CW¶AB 4* ¶CB DAmB¶CE¶C4* AO ¶AB BA¶C 8* 4* ¶C4* ¶C C¶ADA ¶CD B 5* ¶CD BA5* ¶ADC ¶CB¶C BA ¶ABC ¶AB5* ¶AB A¶C4* CO¶CD B 5* ¶C 5* ¶C4* C A ¶ABA ¶CD4* ¶C BA ¶ABAD¶C4* 4* B ¶Ak4* AB C¶ABC ¶AB D ¶C 8* BA ¶AB D ¶AB Bn¶C 4* ¶C4* AB C¶C A ¶AB BA¶AB D ¶ABA¶A4* A ¶CBA¶C D¶CD 5* D¶CD BNA ¶CDAB¶AF ¶CK4* ¶H ¶C4* C 4* ¶H D¶C CBC¶AB B¶C A B ¶CDAE¶CD 5* AB¶C 5* ¶C A¶C4* AB A ¶C AD¶C4* ¶C6* ¶J¶A5* ¶CD B D B¶AF¶C4* A C ¶C A C¶C AB ¶ABC ¶C A C¶AB A ¶CD B D B¶C4* A C ¶CO ¶C6* ¶CB ¶AF ¶AB D ¶CD 4* C ¶CB¶L¶ADA ¶CD BNA ¶CD ¶L ¶A4* ¶CD D5* ¶C5* ¶Ca ¶AB C¶L ¶CD 5* B ¶CD BNA ¶C4* AE A¶ABC A¶C 8* AB¶AB BA¶ADA¶CD D5* ¶CBAB ¶C AB ¶ABC ¶ABA¶C ABA¶CD 5* A¶ADC¶C 8*NA¶C 8* B ¶C C4* A¶AB5* ¶C4* C A ¶L¶C4* 4* B ¶C A oC¶CK A ¶CD B 5* ¶CD 9* ¶C4* ABAD¶C 4* BC¶C4* C AD¶CD 5*E ¶C 4* BC¶AD ¶CD 5* A ¶ABC ¶C 8* BA ¶CD 4* ¶HAD¶CK4* ¶H D¶AB A¶C ¶AB4* ¶C4* AB A ¶C ¶C4* CEB¶A5* ¶CB ¶CD B D B¶CD D6* ¶AD D¶J¶C 5* ¶CD 7* ¶AB ¶C A A¶A4* ¶C CD ¶CD BNC¶CD 8* ¶CD 5* A ¶C AE¶CD 8* ¶C4* 5* A ¶A4* A¶C4*Q ¶AB ¶C4* 5* C¶AB A¶AB C¶C4* L ¶CD 7* A¶ABC ¶CB ¶CK¶CDAB¶C4* C A ¶AB B¶CD BNC¶C7* A¶A5* A¶AB¶C 8* B ¶CW¶CDAE¶CD B D ¶C D¶A5* ¶C B ¶C 5* B ¶AB B¶AB C¶CD4* B¶A4*E¶AB C¶C 6* ¶AB¶C4* C D ¶ABA ¶CD AB¶AD D¶C4* C AB ¶C ¶C4* ¶ADA¶CGB¶C4* ABAD¶C5* ¶C4* ABAD¶C C ¶CD B D B¶CK¶HAD¶CDAB¶C6* ¶C 8* B ¶ABN ¶C AB¶AD¶CBA¶CO ¶C BAB¶ADC¶C4* CG¶C D¶ABA A¶CD4* B¶CBC ¶H ¶ABA A¶CD 7* A¶C 8* AB¶C4* 7* ¶C4* CEB¶CD 4* ¶AB5* ¶C4* CG¶C ABA¶C4*bD 7* ¶CB BA¶C AB¶C B¶CD B AD¶C AB¶C4* 6* B ¶C 5* B ¶C4* AB A ¶C4* 6* ¶CBA ¶CD DA4* ¶C 8*NA¶C4* A C ¶C CBA¶CD 4* ¶CKDA¶C 8* C ¶CD DAD ¶AD ¶C CB ¶C ADA ¶AB4* ¶C CD ¶L¶C 8*NA¶CBA ¶CF ¶C Ip¶ABA¶A5* ¶C4* CO¶CD 8* ¶CD A¶C A ¶AB D¶C 6* A C¶C 5* B ¶A4* ¶CD ¶C4* AB C¶A4* A¶A4* ¶ABC ¶AD A¶C4* 7* ¶CD 5* D¶CD 7* ¶ABAD¶C BA ¶C 8* 4* ¶CO ¶C4* C A ¶CK AB¶CB ¶C4* L ¶AD4* ¶C 5* B¶C 8*Z¶CBC ¶CD 8* ¶C 4* ¶AD ¶CD 7* A¶C4* A C ¶CD A¶A4* B¶AB B¶C 8* C ¶C 4* BCq A¶CD 7* A¶C ¶CD 5* A¶CB DA¶A4* ¶CD B 5* ¶CD BNC¶CD 5* AB¶C 8*Z¶CD ¶ADA ¶C AB¶C 4* ¶CB BAP¶C AB A¶CD 7* ¶CO ¶C AB ¶CD B 5* ¶CGB ¶A4* ¶AB ¶C4* L ¶C AD¶ABA A¶A6* ¶C C ¶ABA ¶C4* 6* ¶C CD ¶CD6* ¶C 8* BC¶C4* B¶H D¶C C ¶CD4* B¶A4* B¶C 8* B ¶C4* 6* B ¶A5* ¶ADA ¶CD DAD ¶C A ¶CD D5* ¶C BAB¶CW¶CD 4* 5* ¶CD 5* B ¶C 4* ¶C CBA¶C AB ¶C AE¶AB C¶AD D¶C A ¶C 6* ¶A4*E¶C AB ¶C I¶ABA A¶CK A ¶A4* C¶C AB¶C ¶C4* C 4* ¶L ¶C4* 4* B ¶C4* 5* A ¶C A ¶H ¶CD A¶CD DAD ¶CB ¶CD B 5* ¶AD ¶CF ¶C4*E¶C A B ¶C4* 4* B ¶AB ¶C ArB ¶C 5* B ¶C 8* C ¶C B6*N ¶C 8* A ¶C4* A 4* ¶CD4* B¶H D¶J¶C ABN¶AD ¶AB D¶AB4* B¶CD BA4* ¶C4*Q ¶CB¶C4* C AD¶CD 7* A¶C4* 6* ¶C A ¶C4*E¶C A¶AB B¶C5* ¶ADAB¶C A B ¶C4* C AD¶CD 5* B ¶C4* ABAD¶CD4* B¶C4* 5* A ¶MA¶C BA ¶CD A¶AB 4* ¶C ¶ABC A¶CK AB¶C 8* s AD¶C4* C 4* ¶ABA¶C 4* ¶C I¶C4* A C ¶ABC ¶C 6* ¶C A ¶C4* AB C¶C B6*N ¶C 6* A C¶A6* ¶C BA ¶C4* AB A ¶C D¶CBA¶C4* CEB¶CBC ¶AD B¶C 6* ¶C A 4* ¶CD BA4* ¶C 4* ¶C A C¶CE ¶C 8* A ¶C A C¶ABC ¶H ¶CD5* ¶CBA ¶C4* 4* B ¶CD 9* ¶A4* A¶C 8* 4* ¶C B6*N ¶AD B ¶C4* AO ¶AB A¶C4* AB A ¶CD DA4* ¶C A D ¶J¶CD 7* A¶CO ¶AD D¶C AD¶C B6*N ¶CD DA4* ¶C A¶CB BA¶ABN¶AD ¶C4*Q ¶C 8* B ¶C4*QB¶A4* B¶C4* AB A ¶C4* ABAD¶C4* 5* A ¶C 6* A C¶C A 4* ¶CD DA4* ¶C4* 6* ¶C4*QB¶C4* AB A ¶AD4* ¶AB ¶CD D5* ¶CB BA¶CBA ¶C4* ABAD¶CD AB¶C A C¶C4* 4* B ¶A7* ¶C 8* C ¶CK¶CD 5* AB¶C4* A 4* ¶C BA ¶A5* ¶C ADA ¶AD B ¶C A 4* ¶CF ¶CK5* ¶C4* C AB ¶C ¶ABA¶C4* C A ¶CD 4* 4* ¶C A4* ¶C 5* B ¶C AB ¶ABN¶C4* C A ¶C 4* 4* ¶C5* AB¶ADAB¶C4* C AD¶AD ¶CD 7* ¶C 8* B ¶CW¶C 4* 4* ¶CD 5* AB¶A4* ¶C4* 4* B ¶C 8* 4* ¶CD 4* CB¶C 5* D ¶C 8* 4* ¶C4*QB¶CD B 6* ¶C D¶AB A¶CB DA¶C 4* A¶CD4* B¶CB ¶C7* A¶CD BNA ¶C AB ¶CDAB¶C4* 6* ¶AD B ¶C4* C 4* ¶ABA ¶CD 4* C ¶C4* AE A¶C4* 5* C¶ABA¶CGB¶CD A¶C 8*NA¶CD B 5* ¶A4* B¶C 8* B ¶C ¶ABA ¶ABN ¶CD B AD¶CD4* ¶C CD ¶C 8* B ¶C4* ¶CBC ¶CD 5* A¶CD 8* ¶CBC¶A4* B¶CD DAD ¶C5* AB¶CD 7* A¶A7* ¶C 5* ¶CB BA¶C 8* A ¶C AE¶C CBA¶C 8* AB¶AB A ¶C4* A 4* ¶ABC A¶C4* 6* t¶CW¶C4* ABAD¶AB 4* ¶C BA ¶C4* AO ¶C4* 6* B ¶CD B 5* ¶C5* AB¶C 6* A C¶ADN¶A4* C¶CD B 4* ¶C 6* ¶AB BA¶C4* C AB ¶C B ¶CD B 6* ¶C4* CG¶A5* A¶CBA ¶CD D5* ¶CK AB¶C D¶AD A¶C G c B D B¶C4* A C ¶C4* 6* B ¶A5* A¶CD 5* A¶C4*QB¶ABCB¶Ca ¶C4* C D ¶C 8* 4* ¶C 5* B ¶C I¶C Bu8* BA ¶C 5* D ¶ADAB¶M ¶C 4* 4* ¶C G ¶AB Ab4* C 4* ¶ABCB¶C 6* ¶CD4* B¶C4* 6* D¶C 8* B ¶CB ¶CD B AB ¶CD B 4* ¶C ¶CD 4* 4* ¶C5* ¶AB4* ¶ABC¶ADC ¶C 4* A¶ABC ¶AB Cv5* A ¶AB D ¶C4* C AB ¶CD B 6* ¶A4* ¶CD 7* ¶CE¶ABC A¶C4* AO ¶A4*E¶CD4* B¶AD D¶C4*E¶C4* AB C¶C BAB¶C C4* A¶C 7* ¶CF ¶CD 4* ¶CD 5* A¶L ¶C5* ¶C ABN¶A7* ¶C BA ¶C 5* ¶ADAB¶C C ¶A6* ¶AB4* ¶CD 5*E ¶C4* 6* B ¶AB ¶C 4* 4* ¶ABC ¶CD BNC¶C6* ¶CD 5* B ¶C CD ¶CB ¶CBA¶C6* ¶ADA ¶MA¶A4* ¶ADN¶C ¶C 6* ¶C ¶A4* A ¶C A4* ¶CBAB ¶AB B¶CD5* ¶CD B 5* ¶C CBC¶CD4* ¶CK4* ¶AB C¶C 5* B w ¶C4* A C ¶ABN ¶A5* A¶CF ¶CD DA4* ¶CBC¶C CB ¶C4* 6* ¶C4* 4*I¶A4* A¶C ABN¶AB6* ¶AB D ¶CD P¶CD 5* D¶CD DA4* ¶C AD¶C4*E¶ABA ¶C4* 5* A ¶ABA ¶AD D¶C AE¶AB5* ¶C 8* C ¶C5* ¶A4* ¶A4* B¶C C4* A¶C A 4* ¶CD DA4* ¶4* ¶ABA ¶C AB ¶AB B¶CX¶C 5* ¶CD4* B¶M ¶C 5* Bx ¶C 4* BC¶CDAB¶AB6* ¶CDAB¶C 5* ¶CO ¶C4*E¶AB C¶C 8*Z¶A5* ¶ABC ¶C D¶C ¶AB6* ¶A5* ¶AB4* ¶ABC¶CO ¶A5* ¶CX¶C A¶C4* ¶C 6* A C¶C 5* D ¶C4* 4* B ¶CD BA4* ¶C A4* ¶ABN¶C 8* A ¶C4* 6* B ¶A4* C¶AB5* ¶C4* CG¶C 8* BA ¶C A¶CB¶AD¶C4* ¶CD 4* CB¶ADAB¶C 4* ¶CD B 6* ¶C4* 7* ¶C A C¶C5* ¶A5* ¶C A B ¶CB DA¶AB4* ¶C4* 6* ¶C4* AB A ¶J¶C AB¶CD4* ¶A5* A¶ADA ¶CD 4* 5* ¶CB BA¶J¶CD BA4* ¶A5* ¶C6* DC¶AB A ¶CED¶ADC¶CBAB ¶C CBA¶C CB ¶C A 4* ¶C 5* ¶CKDA¶C A ¶C4* 6* D¶CFB¶ABCB¶CBAB ¶C AB ¶CD DA4* ¶A6* ¶C A ¶CD B 5* ¶C4* C 4* ¶CD A¶CB ¶C A C¶ABA ¶ABN¶C4* CEB¶C4* AB C¶C AD¶AB D¶MA¶A4* A ¶C4*Q ¶HAD¶CD 5* A¶C ¶CW¶C 8* AB¶C 6* ¶H D¶C4* C 4* ¶ABC ¶ADA ¶HAD¶C 8* B ¶H¶C4* CO¶AB4* ¶CK¶L ¶CD DA4* ¶C ADA ¶CB¶L¶CD 9* ¶ADC¶CD 4* ¶CBA ¶CGB ¶CD 7* A¶CBA¶ABC ¶AF ¶CD BA5* ¶C AD ¶C CD ¶C AB ¶C6* DC¶AB4* ¶ABC Ah4* ¶C ¶CD ¶C AB¶AD B ¶C 4* ¶H¶C B¶4* ¶C 4* ¶C4* ¶AD B v¶C ¶AB¶C B¶CD ¶CBAyA¶CBA A¶ C ¶A¶ y";s/\w/$h{$&}||$&/ge while$G++<10;print ``` [Try it online!](https://tio.run/##fVtrj1tFEv3c@ytaKMvdvVyJRbI9WbF86L7tsTOeeDK8EtBKqyQEEggQwiOgZf9WfkD@WPZ21@tUO6Aotsf31Y@qU6dOlZ89ev50/fr1Xx9/8LdvpiGnVy/n9jJMn0zDq5eppECvw/SofjGH1I7Xt2E6TkMMcTn2go7N7WWYPl2@L7GdFvTDMD1pZ7W/Sxymz@nqev3H0xDatYHvcGs5lmMepg/bkZQjvQ7TV3TqaqTXYfp@GuZ6bDUu96of/F/D9CvNJLaXYfq6/XlWr6@vw3R7ucFyu/p/mIZvh3a83oDfhukhDbz@H6b701Bi/TdM58uSxTqon6chBZlwfRumx7Qk9McDnl9b2eHHoV7XTuS3YfqSnkojPtAjhulyWtY5T8MPAy9@exmmZzylHPltmJ7TDSIv02fLAtaTeTT3lgGk@m@YnrYTl8kmfhum79rd6@ecin0aprJcFuqq/NYG8OrlMP3Em7iu59inYdou5y6zGaZf5G70OkzzMpa4HLg7LZNJ0x0aadumZebXy3Vtz/fLPoQ62FTPH6YdjXmYvuCp0Ya2Z1xMc57zlOv4humKHl0PfETzJiMb/v7@jf988NZf1Bzm7TK9dF5HtqXRzbu2Sm1li5y142Uk0705Rn72cn5c5ryPzRTqt2u1kroWYXmv59SPZ3wvWaMtL0dshhBzc6w8q9XQeoVb9WXdnigbEcNMo2nO2Q5c1C829dl@16Ku@iyfF0Mi22@zPpTE46x3SDQUumJ5aHvQhiYg113yifsYeF1TbrNerixscTPNg5aZ9yjzglaTLjj1ZdjLfOdmuDx72i1Z/Tbl1GCHZlroZjyg9qHN7Xbya7ce@cQzflaeZf9SEGfQPQx8LDQvWu6z7VGkbvFxJi@VTVuOtcXrn9LcoG3RFnGP11VQNPJtsmwSLV81pfXIz6UpLEdpMXmzFs/g55QNPz@ndZt329hdpse2y9sup2xTpP1eyxbQOp6NhCfNigPvaxDzbl/Sg8jRyXR02rJJ61ENOzF@y/42@2ITbisgNlC/uwpmw9Xkyswf8tHZY1tPARs1opvjMfHY1Nnu2A3rgpLVtMGwj822jHB/nv1MK86AXEe4rffeN@O1q9SvyMINHOrBzUi2tGs4HnMiF0@yDXMAsJB1pdDWdoz85DqDU9S7k5GEuGuXH6OORP0m63bWNRarb/ev/szr0GYSV7zt4m6rkSzWbDKwq9e/siLvLAgmQJGXEz4M5B9tq6uBZxccxAJi3SG9Z4jO/GFFqoW2r2jQRSBuC9ZL48UFWJ4uqFtHQNbJfpSPKbjNWawyJO9@y1UfRfWGHaMmm0VbjgRopRgvxqYPrWZity7qpB97q58ZNiI71D/H4HBMUKtZeKMl/PjOSAkE2QEFNJdNOMUxhLm1oqzbXF0pgXKG8OW0O2YkMijFcLYbeoBGxTb3NlUBdcOeNr1UGlKsedearQbd9z2DmoQiNi94aok3@VIbR4iwSYjrJX4i8ZNpD1ho3asrjNcWT9EBcmIKOR8YT5wB8omypy7GYQzOnxpWcgwmX2rr0UYX3L2bkwWccXbwBD7HuLznsXOMXJ7r5jKfZzA6PQ1hui5qG44OivDAHMICHq8mo21dKJgGgJcstxAfcunzAJZhLschurma2a9s8PL3XSXoy/zzm7yEIE2WzoLpPYSGyChj@KGAIw4cLGaDYRUag0MVslGwDjnCU/VMMvPuJoWG2RiDRdJbRi@IiQhqc1iyGxa1anHfFAx7P9OVNPRq47qMEhMkrn7OeQqGAg0mNKJ7iBdsLOLYDB@4HWpB7B3izrcwHDlzujk6DLpiqowbzca0GTkcXvs91XA7gw2sdXOvjMwbchpTUl4h5usWowEsn7EcuOSNFOPMkqxKdGiEhk2NUya2M8uh2Ln5dvP9oJMSAnEAhgv7MZcIiYRyaI4Cy5AfGJ2OBUesXsC@wceXSdLgzoNnubIgariNnCOPWD7ewlWDBW0msBkhBLhkaZZ9MNsR19tp2CryRFoFmEGxVIvHVwTcGWB7gqrBh3buTYgrgX8@rC29EHtGxi9pj6CqIpqyLyXAJZ2EJ56YLl8qR8SsO51fs1GpG0gEQuwMLqUAHNS9dnCP/InvK3ligoxSQ1UKsO0yJQs4yK9il9kRvMC2CHklC5BMhP80A/EbuayBEgzWow4azelggow0uwhMXnyp2khzz1SS4y4uOOCizQYIfPHDWJQPHh2YtjXci9PxoO9hJuvI8sXDtrdCelSbYANJZTaGqWHAHiQkRfCUDYURw7gnAUZDGGbZdznJn3XfttlMa0Gh4J2Z83HnUSkoKGjCqhnI2eiieoQ0sD3KWJz5VJcsmz0yuDIYk2/SiFZj7CSTWaitbKaQJQ3zgrU5BtRphKacExkVxKFB1SV@qARUdl1NV7mKI3otjT1JcGQ3Dg7I9pacN9v4ImO@zw@0cAzBibNDiw/oatHJfp6fbTkgalaR5YYyLc0bNbIKzuu@zyrUnmnOqRYBYHsQtqXAw9HdDEJ1Y8H6ipePIHw1FGJNKqFEAFSwsJPvVdS8Okn0/XZdugCgKXtB0ibGIVtk7JfiBLEc1cI0b2PSseUg5nFBg5lOQ@SK0lmVLtUW3KNxEg1UnVKktEo4vzwhg9pJkT65nICzgZsnLNytJTPlg6bgkoh2GpZsOvAF2uy7J9ArjERiz9Y0y5KADJqSdqmpkdr@7Ri@nMkSjjhS3UYnfnlnhdSPiLZ8LSKfZM188cFxI9RRJSO9@spksLXEbvKYNYd5WrVGtYKLA8hhstpO0F3aQs6Vk4NHkpVm8YEsgq4yFmUJWWmvkSeVyGKHJSC6SpqZjHfOOi9MrFUwO6beCZGBKDVyaaTQKGAjSd2GtfH7wSEHU3jRNnlFdtmZNKk9qleivMtevbd7F9OiPaU1GgYmbxwPchtWBgPojlJRc0qiW2N1TTH0gyTTxvYkvcerjLlw4BObsnQWxCyQ8LWMBlS8DXrVp8dRdMqU1aIhjBK5YkYoGTw/@hZAqUn3xKDF0nFBQXwlnUH8QMiDZQpBEtQH8ldb9@KokBBZ1sxJefJCXbEoyqmNQOsZBMNYUJFuF6xHUAHcYU6bhW3tAPUfC/kOCvVH0JQ02ZUR6y7e8wmuYalqlyfJ0LWuLqi0M@Ztc0AvuFBY0KeCVavWILWO2aUrVh9jd2tjeSIma2IWJi@WrWviCGrutaONZIZfs4ErlnImrhRWbEdsC3ImD9pIdrPK1To5TNcVAphupIxip/l0NuM4aPw9@rKBehOvk1QHhW@xxaIYkeM3khIgPz9VKA0LIIwvXz4F3VoTd@RR4M3k/XcBiKttfputmspVndiNyOo2M2aMusnGbUkXRjtTYFqLXppAtsU0F0O5EeLkWYdWXoUTmpz@jU8dugpwCiDbxfxdJ31oZFTf5fKPCH0uRit4GaNQ4yYoPQeivO/xjyt0rLiJTs9FCArBwCQ1zpzKvK4y2xDwwimywmzP/6DEBznADFU2lBbiabZ4pU9rhIRkYAyhszCSS4VpW55IqqXmMOLFbAb3gwaiy@hyLlcNIsRx1bmEUn9y9xYk6aZrvTAODzlVl2IJiD0q26zHTla8PElMUvh@BkUZLF2YvJUqVCnH0hO4bYZShGlJc3DlcQ4He6Tze67xc1wC6ugtCYUDIZTehjQfIaS8cB7rqsoRI5chR9EY4CpANiHOghCdtfa@EgJ1rcpyX8wETq5ESwI9r1XbxIMCucMZjSo0Pr5uDWq1BYO74KaqXpLuoWCmZEZan5BgcV8FlRYEeTjWdmpmAiJjErCGekBnMvpddpa1HruqWOipQV0QLjolJVKu1sGsRTpBmrdcQQJH/mLNOMU4o@iD5G/7CAKjJ2HWHnA2uuyyCGU0l9uZ067GByBxR/FnTVeQS@UuWvddOlZw2Qhq@Bob5D6GpMwMOKCyzgUErEjnGmssOQIXUG9k97iEp9DTz6mO9ExikLZrcPhUL0KKTvkUVnlR@9ZGICROKCxx9LQSiZX/Ldqpw7NVYYGNSMNVT3YO2jCBck1ZOaWTNWbV/kSnE2rU5VO6EcXwJmP92@SuhqM/qJpi7TOeDLP@8wYua9ilsZkGWzAvStm4VrXIO15UEWO9CqjhQHTYSfIctXFS8YxDPruQpYPcmXJiwYq6G5V084xNVA4RFJX@pDeGAU6jOivhQhe0yMzSzt0@tdFgruRLyKuFji3U1ZmVBwNIUc4EAW8ZpHCs1R4a2grPvS7jG3qFLO9h@ifdcqqoFR8SuXGQvfoci9bBUGUF9eJ27LlJB9DdJWKY5Id/oEDz/uw1/HLpQz0eqiWqx0julDtygR600cYAmIYyU93w3E8PmApvKjRfrEZsTEza7hctoqFWG6FSaj0pPwLHNfHAtT@JhC5AILRIe3t6fq/LbE0evaziuVHBFHtr0Yz1CHuSCTeqhq1G6F3bdumbNdrNYHNrDD6dzKbqSpef6ay4pxhzuZO8wQnEWpVVk7hytWRBd140vFYjrtmhrzbJUK4RVbpga4mc@SB2J2Eb7Grs8Y2FBOxRLNqX4zOAmBOuqvYICVvgJzqvPet6EQ5965E5p@Sl0KPJLQXZW8e5lb16IpdAyAFdUChCWo0deGhP9bHvcTC9nkebkPIWrWtYPOroLSr@MmPbgK7@0onuVhR3EkLf4oGpiYpkIloIb4y@UqM9K9x4axuhMo41fERXCuuaF02y0hQCBD1xMBH9pL0XY2NQ1Ud1CubKUA2xKFd6WVm6BXs1zlrFZielchCyphPOUc5GlKNRvMG0CmUmEXtTOGlnm31Y@Mk6pUSxt/7ZFLpSklBr4EzKlKCl7mgh2glbUVKgeKJo2n036jk7zc@MqUs9R7y6GI@totzDN@oZnt103UzaxZOtr0d1OYRgc0tWxn@2xnXtAeDCVtc@w53BywMfOMNlIY0jDIRUU6Wj/RDFV4T9ynZYIr0zrlhQZiwUq4QW5l80DdeeAtf6vhl9ZiGQsnUGRfGI6IX@sIDz2e1JkHa1YCtCnYPQAbt0GaEblcLR2RhcXrLWfpcMlJnrUlYe3Pbdxm8ss2gqsIGBZPRzlI03o5YrbkNqQXXNEIFDYNlM8F770UShsAKJOJmUNQRsDittwIPs70WIoedKRzD6cx9n8wz5qg@63Omk1SWqEonzco52p0sYlTgopdtizmI2llCO32IPgwZiQGMsN5m9nPIG@clM6ITAduE994MJMs7bRtV/tahKC00AusEOVrn6KtjcorTyf27MQGvfxWLHZoTMyrd@XyGpuAcy8GmCX@Kf1WUltT@eZBjW6Ip1XxVa4Oc3hLXdD4Ks1l5OqpoA16Ih8IB5skaXJK@A9otTu5OgdaHZHTaoJyxOaM5J0eTC96swVsgPVzQYtt@XNTlLJWOOmyrc2A9IJORac5ND53OLG73@DO12m9HqbV3hDH4DxiSp@3lOQO63zaeVjCKp4e3k2tOvra0Gy4BK/qw/tZnmPp7kYLM1DfS9zHvolxF966BqvuUPJCFQlUBzmzK7wmY47W@RX@Xob@Lsl1RSfhOuJatt22y@FdJjYe6qh4nImi1324uUyCevrPOsnfgLKQxOcmyD/I15yfJGWPvqZfztrfd/fPffL9698fi/N97@3@@/33j73a8exRePnzx9dGP3zjv/eu8f7z97/uS7n16//j8 "Perl 5 – Try It Online") [Generated using this.](https://tio.run/##jVxdjxvHEXzu@xXtCyPp5qSjZHNJWeeLZMBAkCfDechDTMc4J4JlQJZPOhmCIss/Kz8gPywKP5a7XdXVe0KUhDySu7MzPd3V1dVz9fTV8@7Dhz98crV54ffuXx0dPXl@cefLs7O/3708O/v33e/v/vjq6dUn82/Xb9btu/ndny@v/J/PXt397LOzswefLk/Oj67nd85O1g9O57O3F7Nn72a33v/22@z5t7N7p6ffne//cDF7O//x6fX50ZtnPz1/eufO7N4XT56f@K1bvv3x6cf9@sTfvT86@vX6qX91@fry0aOvfv15M@jzo1l8@@jRX1786@mL1xf3Nx98fbH/4/qPz3bvfr9@sr5utzd3fHxy2y/@5P3Lx09mlxezB@ezHy5mn57PXl7c2bz6ff6P9ZvT2fzWrdkPn/w@//blz9dvv5ufPD4@frT79Pb88e3j24@Obx@fz77Z/OIy/uKSf3GJvzievZz9MHt5d/bN7HL2zfGT3eTsRri5xuxvX/71gV/4@t1v6/fns/n8x/Ojo9n3Fy9fvts8yeZWX5@crzfvj2ffH59fz9frN/P1ZqbWu7nb/O9msnw30evZn09Pv3hw//zq1U8vXr8///DhyN1s0dz8v//xzevtf8y2r812/4Y/714smu3ebv8Nn/Sv8Dq7f/t3uysdPnjYdu9377ZXs8MdfLz17uvbf13rL7C9cv/R5uX2d/s3q/GO4y@7tnuMYcDDM2yH1A/IYaSbb43fOVypa@ME7J57N24Pj9Tf0cNE2TAUs2Vz@PHwk@0fDrc8zOgwhH62himDdeg/3H1hmI7DIw2PcLjw9gn6AS@HKRPXH0Y8XMM93nL/Yb8YYCHhocNKHYYdFmVYwDgH/afL1ttLfwmLazPehMxrsLwwGXH2493xice/4CLs/lcYRdfipVYNFjta9WBp4xNantDtd8e5GzdXeMBw5X75PfwFDXrz10Xz6eEdNoXRdrZ@NR0tZpjB4BYGKwk@AKZzd4dxd40Ttvn@wSgGc93PCD3lsGH6C26vODzy@NQ@DsUOF9K7w2DO@1t3LV7q8AyrsPa7WRhsXvqnLvgdiwPKGzSuyWi0XbC8w1OMDjW4GWf/Y4PnDJ/44PHGWVy2fhzxbXSMwT2MJtE1XGkwWodnJhdscdSOYzmYcdiVbuiDXRkGj3JYj96oMDBZHOOwwPqyzn4/h6ftx8uGW9VjcAzmHh2BDztoAZ4jmknYY@wV0aaT24KddxjU6HHxAdl9Ghr7/mtx5PtvLFtcpGEowUGOvnhvweNgGSeAI/A4gQFyiMW2YXkMdo8HlzDOCwQbMGLYQ1tr5fG49Gq8eHv/6TA7GOKN3EuYGLUc3gcg8MQRn1gKAJat0gIWy47Zo5cCdyTs5@C4os@DIGueEFjY4fEBhu3G4zLt34P3c688W7Al8q@fNxNhm0w7OobBkC0ivAVC0@imAXAMBjcRtjHIdwSM8yZIqwygyiOSMO1sYSPiEyPAin6oH6Yl/zLu/7CDhweFGBrHMq5k1wwdC24dd0@xPWDUsLl58JtPHjbyf2Tu0VgT2rLxOxHoIKoPno7cybCVPecgCegrrxcsDyGDT3qLeBnaARk/T2QSEvlF37J7M2YVYm33jymHapjIPAwrWoTp5LtXaFvsNUbUbmblRB/MyrKPkNjf4s6LERweergCukhG2V5gnuFFmMAc0yF2jVnFuLvDjumaFb47Jh97v@ZiO1pM4UbLjPlETGG02wyuLa49wP7IGYjotmxWhEXKognSYXri0qdhIILIabhUtAfHr/LcZ6hohvl0sT0k3LeIVMqsD5JfmAYcB4OgsI9NwCBXJhICPDx68KM5NejfFfAvokt8aKSTchxkdACBbxwk2mXcrUgQAFHiCtqKbfywqUgcci4YYhjOcKdlEyRatQtiEsF7qqPtoLm0CFZC7ouZW/Q6ecUiwjHnRBTwp3IlluHhaCVxv1PqfPgBQvgQSngEkHPrLApTNAiDgdshEw3WBHwh8FAIBJ22QaKpIM2jWWTAPxJpQNyMGTXSgsj7QPYWRsc0GSVyPQK2bB9gRTtbWza1K4mfBcjJuzUxALgqarRdgyW1FGiRDGa4p8lc6ZUBxNpHAR5nimTvSRKbHHd0oOUsxMsRsMQQHxB08Ogmgp@YR1peM@PkPFC3LmhIiCdhX0d/l9AnAhJFFzJuiLYvwJlInMl5E/8Wc8JM448XDlkc5s2IOXO6XVDUEBaTyQEfE1k4YBzzjlK2uwMqImFzDXAs/y4x@DZRKxiNxIDvBhdvlkI655nLyUWn4CSCCOcFCwjSGaco03DwyTCRGZYgF1eSTeEzwrDLVpbRwk4NnC3QKAkCTrDekd9jIB1inqBYIrhPkXXZTKQLMswGfGLsG0J8ztElcMTCLwfjc6ooxPi9ajkNYtLcCcx5VS8pKyGFt4mwgaeya1CeWjSv6ovkgwgzuSkOssBDsKCxOoo1UYvWleKtOVJjsP8eNuUE0J/FxJOJBgcmTHGt0jCr8D88wEh1hl0KWZtrTtLIj6aUgQFzZN8RSirfj7uTwx8S/Ievhm@CHw4RI@x3yCHMCbEjPDvM66qJ2gywm9rjpqhsllJBTPgEAGeW0wA6VtmHKeYYYDkRKpwtphjmVKgH/8hlp2zUBOsXKqczxRvEzRgpemaRoCgaKRvLzExKEAWk1gGQ8TVNIkUoU3ucjEA6UNr4gJgnK8Qu@X8ssmGViSvWqwQaAWdAXb9ebMZ4irBcNCVbkLXxuKOwxIZ7KGM7AbCGSy9aXoYQbQWJIbKlKPeovNwYYjMiMKunipjpFDtStMi8@vjw8Uugeoim1jUZSihjZvWMUdmSKBrOVrqYGA2@tptIs8YlHdc5I8eUu/JWJluOiTddWGGUWJX2opyetUOLVuV3xtQTJeOkQ6iiJhbsYxVA0jE440kuRiUwd@3fU7oZE@zM44/ZOduEcKxmyVUY6lzQMFECYUzWkYZBl3hRW8LiIZZoZE0ewkohtcoEkeVK1qJpMRRTr6S4IA0IOEEWbqiCcHT6NY3oKmPIBaYs2nPcA4ONLZusU0AZnfJv9AvEmO2nYlHXRVg0EhFWYrlNJe/upoqqEMRzjYqlcn1cji6K1p@EOCZ9WarxIsFVFQ6EtQh1YNZP8WYx4qwnJQrMsRCjypBmRYDdrNJbHa7RNZPETxZoxdlABtxJsQbgTrFqjpUkVVmhGgcp8yjrIGollDWUBiGqUOogmCoqUQhS6GMwScoOEPWk@mmEzxJqSs/cKTKA5KWJ09Q@KFXTE8kK5aJA2StREQvPcNsFn9Knif3/LVsl//Ooy1XFGXDWORlH/KfwGBFHcE2YfC4gheAEqMmYc3@IaEBsSBU3SGgJIkJwzqS/iokosl65AoH70HmEzsEx0mvTqjQOz@HxjXkLV4IvpDAqm4bwM6IQYBYXVbKrNlDhz/U8QGeAF8S/s1@K/J1DXQa8AsTzLmppCg1RKomQ7TsR71ITj6DeJGORLUVTj0XfRvrATOSJxR84o0V0DyEmF5RM2FwMPlbkfFlXRyLeOldP6eqiSWBMqgTkuSQllYJuRCkTqqTcPBEZ@ey9pALJP0J4nhhDIdUWZblp7l7V/1nRZFr2Fl2JGQbliYUm3Qox5MOkd62SEtC@ME1SV/HUInLJKnGpCdTVU2wy0msjGVOCJ1aqYlknGWnSrnntigpiNNrJQrQIlL0u5skLw/p83qbcS4aEVnSGwdfNrCh0O3OBAmDeTPthW51H8ZVNVbs1/9c181zYYewaCVOjhrUQtCCFwk6VhL8XbapQ6FbJdHFSE@0boVmAbYtmrguGgGGwZyAzbjrVXzXztMTmurw0XfSp5mC4RceCsIQqTUrLZWnL2AZI7uGYSVeiA9Q0etASc6LlpG3MiW6SNmEJC0MWFUtL@NC1UlV9Q9KGZDJvzZTPs44zdbOYCWGVCa7clPvx3DXJPbMK/rskYwRlAAF31cqKQSBZhD@XtbZICLDEDKMNcaoyiZfpUNFkazJp5fojVdeslnPRDlOl8poSIBmZQYYlUjQD4TPKCAu6RnRDRJLNRuAGL3MvYUorwAkLUm9cIm60QMUaoaqE4LmYbVTtLHqwGKzHABQ3vEmtSFF/8zIzt7pUO16TNaGm8nOY2pBbF1Qz2qNhRM2xBK0Q1dnuWm4IbV2FlHm09Joq0sEc0hWaFkUQey7HYctkooosP04laivTZgew71g5yDgAS5CH2y9bJmGsckqMg5bNRRWmPukAzQLD8409qV3LOogsVav7@wyVazZBykK6Q0o0EypfFJBjd79xmb2fNJQJwDqZy@iJ@UJsZyVCOxcaPAtjNXeIMmWm@kt9oBdHWUTcV7TR4AdE30QnoI6IiBE1qYCQo59WZLFCtcogSPWJYSXLSZ3ErJ4SfJ27kT@NO1DNIZIxuFFMT3SRL0409y1aKmNXB0ok6JzU42WngtWJg3BkytTzrq2JmpgPxe6NkrdDm0IUoUufityyolhjAh5HtA/9x4uyj2zR1FEDpnluLpMX27/LyFTpB0IVVCOYOIFmppolTTHImYBLug/ZRJFawE12miD@gkUWNxMxnpxCIft1K9qiQgiUmQGTzeC0RctzPmIHdFHLVpXC@O5msT@24usso3vZH2xFyY1MaSWbwxJTkY7vQI1tVCbJzIVOplmoE1hIqFdk/KLs6mV36KKp6JWkusX1onAOdL5WhhSrmqcmqBnS58VbBUvK@tBKtUZ9TlycmmwRVHQi1uOh2AYsQyUxTcUGTYBR7dRLfJWlM16WrZHEK3QKpqlrzAIYOUcUifUzyxW4HN5rmWvqTqH0sGoiRV1PeUgVN0AO67VqqWjENU7NtKaSMAqDqhMAsCiFIgIeJPfCKOW2JeRjqmwi6SJKVeF26hgx47QgVbgD5TmlFOEhLJPzI6o301VJcmpZhJ37c112O01W2lKKqG1Sd8naDT212l@R307qsNTvicUU7n7SmmLuLeWzj/yGhM9VFy1ieFZUmVf5XDr@LNqUDHNjDqLqYTFNW@TaBNUz5HltAmlpq0XuB4kW3cgVtiT0EcC5fliergv9VolC4mmOOOOpZTbXZDvZgrRqyg477PVMVMwg401a8uIMpilFpyDUlk3nmMwmJeHRsnHhmzJNKLMYGeQSTn1A9c6imWjfB04/iS276jA/7JBPzZkunYZr4QXlpvGcLS@xqToFyokKBMQfdZoot80n6zHmvqFnujq/Rkg6crM5bnCtWYtKI5UkADIS565W517CeAMeKHQIunMWTkpctNK1Q6dhMmBkwGPFbanOqula0aahSp6RzO6ayW4YQwS5bES/KjWDuCpPDpfaZAnGPrY1gaSUmuPDU20mFB76ZNNx0xWHuabOnFpPTzAqHEozTsFhimkKTYmQrTigQpAlxF/KA86kJhBYcVcnz6aFGQITHsjJ4i5LNWQS/WR1p8kTjDPOtHzgBmEdYtjdbpAdJWe2bCaOHGQFcnIv4kxb6lApkv@pPiHuK6viZCVILoVDeGaSVekUkJJuU8SsOmq3Pt3JZVuty/4rk6K1RBHGLIVr1CN3aeh8ASt8RHulC6kaA2o8alHjoXgP3kzogYd7M/tLVWySsLg4pDhIG4a/LxpJ1zMbAPIJJZAIc7N9OU7o9vVw581/t5//75er1z/98uL6w737V/8H "Perl 5 – Try It Online") [Answer] # 25. [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 13209 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ⌠¶┌fw|▓č≡H√ōkχ№ηļš¾‚ņ▓d^,ωb}aε▒¶qXSο∞æW&§L;ΞDσ⁾ΚW²8Ψļ‚│{ i$⅝QυķAγ√∙²‛5⁹ī⅝WΙ½ƨ5Z.h⅔≈¼δ∑⁽:Ψ◄║α8øVφā‚⅝.ōΚm⌠¼g‼⁾■σD(aV¼⌡┌π⌠→CÆš1κ*□─‽∙GMHck═η?ƨΨ‼w▲╬ΜZ²‼z<ηw@_šI↓ģΟ↓‛ζ2β⁴l⁽/mYnλ└ι○Is╗∞X[°╔Y¦X⁸a─≤Λ⅞g±μ⅓Χ╝'xwψƧ⁽╤¹׀⁷kc}NΘO⌡╚ηā↑≥&‚a┐∆O3ķ|┐%9G0čbh)ΒΦzb[┌dΗ⁹aγFΤΔ68Dη↔Æzn<▒Rο≈¼ΗƨτΓT│+¹⁰≡⁶⁸⅜*λΥψ№Μ→⅓ī7πƨw«?šēζ↔υļ}?8]≠╤š▲Σz]ο⁄ū‛⁸¬νj│ņΠ5:‽′š¶^ƨΜεθMW|7υ⁴¼ģ&#■◄¼↔æ≠Ƨ.׀ūjΝdΩχ.<ω⁸>§◄F?ΟξΗH³¡¦⁵↕∑\C.Λ∑ ν↕iα╝℮ā$xΝB)⌡d─□u¼k≠↔τ\rIWsdož ⅝čs0⁵čqæ»qξγφ{Γσ⁶ΩN8g▓²i▓ξοπ²;«τ¾πσņ≥Ηib~l⅜¤≠▒≈FcEH─╥Zq■⁹!╝½$^Ο⁽υ`⅜R¬ΧI└○ Φ_r║7x(▲⅟Ρζč↓LšΟλ└F‼Νc≠║`ωJ↓Γ4SeΛ>aXPΞ▼)‽ΩVΖH,≠∆╝∙o⁵°╔Τ‛ρ'Ρ§²:ν▒Ƨ⁴╤⅛BBŗ⁰ēfp■6⁰=,'▼ū≈⅜‛j≡χΖ⁵k▓‼Β'═Y*¦╬§Κ╥6░Ζι‽ιΤζē;∆⅜║l@←ηw⅝┐)ΡΧ§1ε¦¹λ«∆►)fOģ⅛⁰C░{§žτΙSJxANωRgņ╤/⌠0─▒v+⅔Β∑ψl╝x p↕Χ←⁷ο↓r⅜P▓Tv¼⅟¾⁷oχ‚≤ƨāΣ⌠ωx⌠⌡Zψ←⁽╬ē$┘Τ'Zš{@h'.^╚╤-‰↕Ν▼č) §Ε/█č&τqαζιu2ī|׀S╚%⅓?►‚Β⅛‰╚č±μ⅞┼╥▼±δ≤№IΠ8▓±Ω7³ΡT║at‚zχ@⅜J⅝.=ρ&_ģ⅛Ρķωæƨpψsø‰K»υY*R(╚‚ƨRa∑z⁽ņk¦S⅜►s «Ωp4ιFRÆ;,5ķ9?wķ ▼r≡<\∑Mķ4æ╬↑āøΝθīY⌡ī╔╬⅓═Γ'θ{¡4ΝXB╝⁷*½§#ķvΕ_Σθ⅔|.█Νiκζφ≥√≡ƨGƨ█℮u√I3ēāα6v⌠Ξ⁽:‚¦ΤΞw1γæΨ′³⌠ΜΟ℮½ΩΧY¾Cκ√⁷ΠρUō∆‰ ↕⌡ν⌡⁾▲█↕┘/►GΕ½e→τ↕⅓‰o¹→S=5ā⅓PΚΒεj}ωρ;ūιGr⁷¶č═īξΡM∆╔┘π5¼⁵Ηķ⅜ņ→l┌hβΛ&r^ΦƧ⅛j↕<ZBļ§Ν`Βπž◄Λ││1,-ΝD;≡┼▲4‽?°Jqfēο|φ′↕⅟≈n⅔ω℮6Β68‽ZΡ»@eρīσi6^EΝ‛θū№÷4k°ωC÷ā¼≥◄▒′╤ξU_θō²³½Ζ⁶2¼׀Μ«C┘⁰8Σ┼ρΦ∫¬pīg≈‼Ε»AyŗTτ⁶sJfƧUA░║{πΘ↓U|θ⁾Χ⁶↑ķJΓΩ\U┌Θč‽*?└ε►┌℮!|½ΟčøeΖ|k⁵╚5ΝΦΙ‽⌠αZ&nυRηπ|■Γu!k:R$āΥ□p▲Τ║Χŗ□╗4īū÷YÆz⁷χW►▓g;šM╗┐ΡTfp<\╔«k░+Νr■ZƧΟυ▼<÷fq┌○÷┘πxXΣΥΩ∙»&³7>ø‚rσ↔╤<,÷Υƨ№²Ƨ┌∆z‰╤_┼ō/²‛¹ā/↔Ε⁄C5←¦⁷,ΖπJ⁰‰≠ō¼ωΒ╥oK]□v±ξθU⌠2░Eσb#∑K.╗nΒ№9▲ΥπΕ\.{i]Η▼≤~L Οkμ÷⅞σΨ»╬R%⁵RJ⁸⅛ε⌠μ_e⅓]Λ⁶⅟▲Θ┘⅟Θρ□⅓υ\⅛no⁸KΝ┐æ⁸χΕ⅝⅝⁸iη←⅛⅜ŗΖ*Ψk░M]⁴f9◄oΣčχ⅛≡ξāL(yμ8Ο∙biρΝ'ν«σD=lkξ7λ╗{n ╥!◄=G≤ļm╬Ιķz▼Sāχχi╗*↓!l¼ŗƨW:{׀zu÷÷ΤHēqaVy÷⅓TR2└ΚK╝g■┐Q~⅞WnY⅞↔7²:κ⌡!Kv┘zjΣν┐(‛┐#MqūN↑½ΞΩ^¶Υ¹L6⁴⁶≡╥Ε:⁾:╬╗fι╚Sβ¤1č³yψÆķlφ◄i3+↕│─@─3≡V∫2┼b┘▲¹¶±C⁸Qq┌ζΩ%ō╚8L′3∆āYβ«φKyΨb╔Εl+ž¦a╝∙⁰W∆^AI,℮8⁶Gi№P┘αR┼→¡[wTΕ□O'ψH→≡ōa½vψT▼|(Jčq¡┌ø⁷e⅔⁹+╗,M║mōJ№└]Ρø$ž╝∆§;¬j≠ΦΙ←)℮ΠΖ1,⁾┌ρ~BrΧUΔΝF▼¤|¶F∆⁰z↓⅓.¾Σuψ.Φ⅝‽∞└ΡrwΝ╚υ℮∞Ω8⁶O≡η⅔ģ═ļ׀Wrγ3¾⅛c↔d‚_%╤╬]5,⁾⁰{ι¡4'{¡δ‚ρ⅜`▒\Ο⁽n⌠oνB«ΙΧš⅛√¹⅛ē‼√5┌W█{⅓╥f╝εFH'pærPī⅛ŗƧ╬Zδ׀}56=Φ‰θ3Ω─)øčZ─ξ№#¹Z≡ē:′ā6Rδ ∑y?⁵HƧ¼⁽ΜΔāΦ←ν█ā⁷⅜F└√¡g;Ζ<=hιμrφfģ║²η⅜⅔○Θt≤m²`āļƧFΔ⁵←:ΥΤļ³ΟO∞37eīα6║⅓⁷℮ļΗυ|↔j0;⅓d←t←υχƨkģø─▲(jζ⅝ÆΙλt□ZΚ⁷⁴¡∑⅛O≡K╔ø▓¼Χ‚;↔Κ═⁵Ρκ¬¹TR)t_)⌡+Β‚ο4#:5/HΛķ{░υ;¦≈═╬&κīkžυψøoZt±υļčυΖīG+Ψ<N≥μ⅝┌ζ#ψ‛U׀G◄rI∆a!⁷ēK√ιW$ΘΜ⁰πsņ┘$b╝š≥⁹⁹ļ_6⁷8Ο►┐ķ╔↔υ∞7νa«El≡ΟjΚv‚⅔j≠²ž∞□`ΕWžΜΖΘσv≤‼B2t≥@ŗ╤ā‚J│°Wp╝Wē↕¡№_←;Ε∑═▲ā№BƨF³ŗΨ╔s*≥=GƧ⁸ΛΚ«█νāρt─γ▒.■:⅜↓ģ+┐Πø↔→wrτζΡU7žYž,uΙ≠ΩIΕ/∙č█=U→≤_∆0#m²(Ηrρ}┐Z\⁾⁽Æκ√:⌡²?∆≠eΚM øB>⅜Ο)R4░Θ¹¡Ep_HΔ)╚ķ)ūΨD.⁽∆]ŗs‼≠⁵Gu⁸⌠{Φ□Ψd ΙqqTΟ.│{«6Km⅟sc░_ƨ‚2L′¼āÆ№⅟⅔▼■█∞¤u;/¤σ(◄«‼⁰║Ƨ‽,μ?p¡└γ▼7E⁾ξƨΒμ↓¦⁷↔9»\9αŗ‰μvņΣμ;9i‛±↕_↕Qxο⌡dT═ķ°v⁷τ╝23]ζA╥|L¤v=,¡⅔τ≥′A ╝ξ≡)⁵$≠\׀ΗB√ΜS⅔ΙωPr╗◄∙F→╚ģčH▒ηΧ►ΔKL p6d*[⁶±⁄¶|⁵l[+┌Γ)ΩEƧ§ļο*υzγ:,╚6ο@³:v¤cχωZ62↔⅞ιg╗═τ4⌡\ņ³ōf┌ΥfQ]¬q4Sγ!→xh#`№i┘⌡○uh¼XxB∆≤V⅞⅟‽□′╤(θ∆∆Κβ»«■⁶<²׀¡5Χδbσ{Κ╚┘_[׀u:⅜Bkv⅟β∞j└Q ūa=5a\οH╝eyBΛΤζ≠ΝNζ²γ§═*‼<ƧΠķ⅓!№‽q=m┼Y|ūξHl¤ν=(⅟V§Ι+◄IPv$═?hhm▲\⁄8▲'⌠↑0≡Bξ¼⁷¾πeξwθ└b?≥§hrΗķVģx⌡↓⅜│Κπ′?ΘVe‽^‛oģ⁶mΕēΘξšC÷↔EΡ'ρ░╗Γ%Ν≡υαΠyκ↑B⁶ΛkXΖ{▲ιp⁸β&┌ODoJ ╥¶ļÆō~Æ⌠zUΓd[teū` ΩO<ΓθΨ≥φΝeō√⁰E⁸/hī‛[┐ΕΓ}∆r0 Ζ↑׀a℮~8%█\ū╬⁷⅓«‚Vσ≤⁵ΘΨ⌠»,╥ķ§ø:№±┐→#‚š z°i█&īγ╥N²W|ģ³{U○≈≥≡SΙδ-H◄ōX∙ē┘_Ξ²$⌡‚σ↕√ny○↑‛Χ¶»ΛwΨp┼⁴νAƨ(Βh¤μe ╝š‼§3φH◄uA≠#L└Βā¦Yŗn>O⁾Βε↑′÷¡⅛sΞ[η$VS¾ ↔‽ZrγēΤβZΜ⅛Κ▒ξ⁹O°β>δ↔οx8■Μ¤³╤ι'g░xkmαlρ⁽┼Ζ∆׀↓!wγ½╤│¾]∫š»No&■Np&zņ/≠m▲KF╥)¡sβ─YU'λg-z⁹╔|∆┘žΡΓ{øķSΥbIζTļžB-3Φ→⅛`ψ6:▓⅟'M#7Ƨ,j○P∙ @ī№$Γ¤∞E@²>»↕¼¤⁶1¬mφøωσfηļƧ‼╥ΡH′rοīsγP↔′^?l5╤⁷-N¾ν⅜ΝΔνF≥▼►ž»!>č»⁷ε0T╬ZaJ∆ŗļ⌡█hx׀○VΕ╚°Γυ‼⌡P_▲ ═FÆiωΕ¾ģč/⅛ņ└ģΣΞ№»-▼Ψ▓βΦ¤∑⅛▼Λδ╬′ī¤ol¤═@Ξτ‰F=⁸E⌠◄╥γ¼Z>ν&-R°⁴ΕΛ±wκ~9↔ΨΒ~ΖΨ≥►\∙▓‚¹─)ā<ΞB▓╤θ▓ΣΞo√X↔«B@B┌±α≥}@⁰¦½ķhh¼ξæ|ΟN¤2~○{┘^↑t‽Ζ±eoš↑y'AΛ³←o⁶{⁶7HÆ⌠H±‚ƨmυ‚?κλ↓dƧφ{J∫┌⅝¦θBlΕκ░⅔}`ΘχJ┘UA≈κ└7wšz⁷jS<I Τ╝«(`≥½Ι%i⁹⅔!○JΙ4 -wģYo7o.4qķΛ]ΕντZ¼ēτ⁶γΓΞWμS*ε\∑⁸RGΩ׀Κ⅜Θ′z□j⁷∑‼ļΔ┌C\κ‼#,+≥φ^γæΛΒ▲≡²Jt∞⌡▲1■p′┌πΤο┐νņΙο≠;Γ¾ΙN⌠→N¬¦→║⅓Κ⁸½⁶|²σtg⁶?⁽f9*⁰@Hž½Υτn¶¤ļ<Pψ⅞q⁴⁰zG_≠Dg╚─τ⅛æΛ┘γJ1ΛVJ$Rν@⅜Ξ! ΒX׀Υ;Ι§y╚∫τ▓βτøε⁴3ν¶Q∑{c↑Φ□Y№‰u!±?ΩOη}¦οM{▲N≥j∞Qκ:?ψžēft∞╝─Ƨ⁽_'∑αxšeη,s⁄⁷/νΔΩ╗≥kΘ◄Yļ⅝nƧ‚žTģεt¹v╤Z+«Χυκ╝⅜′~∑~σ/⁶ψΧYfηsλ░‽℮j═ƨc.σ=ζ⁹pƨl¡ī⅜;77∆/√4▒ξ╤Β⁽JΨ⁰mM*±‛,qΝ⅜7⅝/c⁹⁰ļTρΨΡ⁹š(*Ξ╗,Ο┘∙D¾ψΕο⁴φ≥oa⅜⁵^╗⅟@Oc‼I{t¹∫kū═↓¡,Σy↕Μ±[B○d∫׀№←⁵Uψ|τ╝↓&┼η▼ψ,№↓№ΔKF↑-S5ΜΤ±⁄ε‼Pž;aο⁵J◄Θ↓⅛┐_Zo¼V+╥s⅜š■ξΔ{;Μ|CC∙ΛΘķψ25W*→Bp⁵⁵ļ`Ν,∙.8=a║‰L¡s═ΧoψνCBuCλēd6▲θλ▲fΕ³Ρ╔∞↔ļΘκΟ▓○{∆#φ}T⅛φGΛ*r≈cΥ]ΜQ∙M↑═ β9 φ⅞α∫jQ┼ι:\ρ¼z°║#ΠΒ(↔ūη[¬←,∫)f,¤λJCl∆ ┼τVπY↕⌠TΦ‽³¾ōz▼<v¡t◄⅔□ģθ░πļø≈Qοķ⅛Ω┌Ρ»rΔf1‰Ψ³.¦ΘEO←^≡↓FVΛI=ģpκ1╬⅝⅜δLŗ:⁴⁾ok2░_,ΛPYv4ēΡΚy*■O⁰00⁴ķτ▓Bυ⁄ēφΖ┘y‰mMyηδ⅔ņ⁹*9kgōΟi}o╤Pr‰⅞ΓPv‛°⁸┘○³E┌↔ΙYrčΦ⁽Ο⁾Βμ‚οø│.ƧDmEBΛ⁹«ζ▒ιυ¬░.71█▲-(′>LFy└ρ≈¼Ε-?⁴4Yδ¤#a│VjσwΧ{┼↔┌«⁴Ν⁰`)Δu╗¤⅟ρ≡Kr}Q▓‽b)█⅛≡»DeæQ2-⅜D¡≠π▲¬▼cΥ┌¬ģy»¼īΗΗΙ;qp√ū⁷«2╔┐z¹FΠ÷Ξ/yΓ≠BΧ║⁰⌠►χ'□Cgτu‼↓⁶θp:Z!¹αēzαd3λķV$Θ═⅟|>÷u≠<ξθΥhƨ≠0%≡,⁴∆1±τ5W~ κ±I└╝≥╗T¼SģΟε→Γs5kκžŗδ‛ΞΦ∫¡§⁸>P‽Ω7‛≠/÷∞OVhHl3]¦ņ⁾W⁾«»υļΝ.qζ╔y#υ‽ωŗτ#-¡eΩΕΟGCv{╤Ε▲┐׀║⁄Ν┘░ξσ⅔⅞19τpφ⅛¤~ΞQ≡JΨ↑√VfΞο≡ρ%]σ█(7ūļč«'⁰╬ƧøSκž{◄|.Χη§⁄n1r9dδB○6≡ΓI╥≈Δ⅓-∆¼š%Λ⅓d○?qοD8X≤÷ξ←μ%□ķ○ε⁴⁸¦]Π⁷Æ['‛ø▼‼ο←}⁴0↔¹'Βψ`cΔ7]┐→Σš═īWæ↑LEγB■■!c}┐$:IZdΙ±№ΧEfΧΟ▲≠⁄╚ņ0`√Ωŗ§≈ΞOΜT-ŗΒ«╗Μ*Æ≡□ņJ℮→Ε⅝N~j▼↔οO⁹ļ╬i∑$.┘s6NΗ-æ□□JU╚≡,σ¶τX׀■σ□«υ ⁰∙0æε╤t┘½J║οSķΗ╚╤⅔=5dvG╔█▓ƨ A⅔O½Y⅞°‰~,{ΘTƧΞT[ιa⁴⅝ιj5¤→Β◄+≡ā◄ŗ№Ξ.±$TΚ↕Π⌠ÆΨ⅟Κ³E⁷ZυB⁷b─Γ(⅛⁹v÷εX⁄'}qn№n^Η№▒Γ█RΕBη⅝k,┼Η«≠tΘēβ¼Γ⁰κ⁾SΔξK9D¤⁸nκ[{æΞΤ╥g⁷§▼∞^m%⁹↑uοW□ξl∙T$ΚzΞ╚¾ø‰=xKč<=ΛEδΛX<±jz)θ⁴⅟)‽jŗΤƧƨI║∞≤c!φÆ;:⁶U⁰I+a▓χ└TΛ⁶╗<◄⁷ƨ#γdΦη>»æ3Δ′⁵}Φ¦⁶CΞ≡R⁰∞¾iģt□¼Pyω▼▒a¶←╚╔┌∙m≤KCƧo∑<⅜»#‚θ#Aι'║╔‽┘ω⁶Νž↑½◄Al⁷Οl■Δ╥Δ∑I0ku‛ILχ¾⅓,│4№ο□&ΦvO¡ο≡ō>³,⅓NEčΤ■┌k⁹#$8τ?dwAarKΒ 5@č4¡QgΠJ№▲Ξx□‛}\‼³«╔⌡1RƧ\<L?=⁵@ξā,Μ╥↑⁵<mΘ³¤Γ≠─Ψēτfb6~μ└Κ\⁷Υ =L°ααQjū8χ«CX3│Ιōλ¼hI8gHθ>Ξ▼æ‛κ╚⁰ΓΖγο¾B}λ½■9─SHq↓τωa ž≥Ξ⁵⁄⌡δ╬‛¬u⁴÷)v↕»׀Yπ¦O╤^3zΣ∫⁰@Æ~n■qΕJ¦↔↑⁹M|½≈ ξbρ¬R_TvΧBƧΟ⁹8ī≈L≡T<r∞(p3Ζ≤|!b,Yτ¾g№,.«Fŗ≥«;σ÷K∞,1?│╔§■⅜ZεδeHm[9+Υ↕½Ι℮¼┼(x∙└∆]mV½⅝│b4n√H↑►ψΒ⁴║h>w¶ž≈8κƨΙ╥pΡ⅝4Η~ē√7░-▓ΟΘ÷@*)Y2╚}⌠√¼⁸_═YχPēLKΝs[↔¾⁴‼~▲eø׀⁄OΕ;ΜhχλZ¾DuΣŗ‼⁰Cļ2≥ │Λχ╗⁰σ─Ψ∆╔n∆⁄νTi²ΣtβΧl⁷℮⁸(Σvξ°≤↑w↔═+¼λæπΔ/θψ-Θ∆XQσā\S¬‛№o▓xΟ▼šfqM○x±∑kl§ {λ╔υ○P¹8ƨΘžU¹KZπ׀č,¼ņr′ō┌Υa.Θ%′ģ_η׀Ε+⅞╥⁸→Om┐ΠΣ∙□‼Ζ,Q⅝εVΤ[ι`čLļ∞B¶$¤ģΧΡeμζ╥↕≥XRR»ātnM÷╚MΜ‼θmO1ƨ◄Ο□¦e¦┐‛ρ▼°ΙsK∑-t⁄qāg.q;⁽η⌡šΦT§↑Γ⁽UīX3┘5ΕD['&f¬ρ'F,ω╚◄;V^ģš9ΛvΦοχΔūečω.?÷≈½Χ└⅔ΗΟļ°ƨ→½p⁴3|←æTοΦΣø└S:.φ┐: šž°≤ωwq½zξ∞čω(∑#ω⅜⅞¹.uυ (κν∆UΣA≠∆VYc)»Ι⁄╤℮≡⅟ŗDSτ2?∑⅝○≡⅛ΘξC↕A∞Ƨ║#«ƨΧ2\k⁽׀='Νūκ⅝⌠=m⅜BΕ─^²&ģyΙ╬DΟo±Æ▒&׀׀■ wV|↔⅜≠»►σγ'§Τ¼ΠPο⌠8]+2AκjIπ>Υ⁰Jaŗ≤qκ_Kψ¬YZ6Bā ?G\@ξ⅛mΙ}g9→±▒*n47¶►Θσ≠QSΞx¹εN⅞¹⌠‛Ζ○π↓Ρ3c╥∞↑√x⁾žļΨP╚l(øΥν}█Μu↓Ιπā'Γ‛╚Ν▒↑%0Kγ*ωαφdSι′rE∞/⁽}(!¦>βT⁸OÆÆ]γν3Ψ8≡∙uÆΟlp↕ēģ^∙<mlŗ∙ηxuL4Oκ┌ķ[⁷i5Aμ‚βLa└ķ2^Q2<⅔η┘8}□▼▲ιQ}ΡEΚpķΘυζΚ─7⅛³‽ƧC»§┘wθΖ∆ē6α8Xο⅜0r8νQ⅟§¼Ƨxξ∫`╬θo:%LKUΣ)⅝2⁷τ7»¶§š→+¦¶ļ_5@═ī53⁵0⁶׀⅟\Z¾Q⁴ģ‽αōyīR╚○┼⅞γ|ÆπξH‚ΚΩ,└gāζ┼o}φ3;ķƨEkΔ 2Pķ═zψM╥β►}h▒│m≡M‰r∞┐ζΘ↓(Ugd3ģ°ōRω⁄σ╬┐ψē↔y→ī№⁽⁷¡○*φΚγ{F\╚ω℮*γ≈p│aΖτrΕƨo oƾ]aøa‰2Ε╗ΘPcBēζq■ d←╗Yπ9iΣ&┐k⌡ΕΨ⁶ŗK'I╗½Æ▼T╔i≤⅛¡ΒΚXB]$℮π░Β≥╗ņ▼?Z╔s*Sψ○┼4υ-kōar²0ν╤∑ƨχ&┐čN¾ģ¡{Σ¶⌡δ{1w■z←═bÆgfWf¬a╥`x⁽ōī↓²λEqB8(C>GP─Η I]ηθδ26Ƨ@ξ ]№?I⅟že≈□6≤◄O³6░Ψτ]k/√h╝:↑.\γ⅟↑ρ!║β,Ƨ└χRΕWƧ÷ζ№mpH±§V)<¶īTWΔ‚%→ΘR~Aē#,(u¼∫↑ο▓¡╔⌠#v^eΚ^⁄7³co¾'¼╝'▼▲ωζģ∆3Λ⅟□{(ēVžø∙└ρΝ║1βD⅔ā¬ΤG⅛≈f╬*χ(▲x∞mš⁹$Zu⌡j'φ¶‰p=8▲⌠4┐lN└θšū←ø@dz«Ρ‼eγk○Θ█υQj»7ļ3≡⅝╬⌡ξ^√1⁹√>W′τb§∙Δ⁾׀╤²ozŗΖ⅜ψe½1]╥¹{Ογ-Ρ│ƧΝIX|@ΖΣ‰█i►%¶ly2*β⅜ξΟ║d:S=7τσT℮±C¶≥Ω{'6↓■⁶CΨ387Λ▼░∑═⁷Ρā ⅝/'E∫¬╝░s:Ω⁹~κ∙⌡§I÷w◄|+F└χ¾⅔k³[0⅟=φ8G+⁄ζƨ►ΝR8κψ?sε▼Ν.ņ6hz_ν§⅟▼Β║⁹?A@K{8⁄ρδ⁾»}Ν↕χo↓≈≈‚iJKπg_℮¾+χ┐¦.²9<<ņOžσβ%ēl⁴τ⅓U⅝■⁾:╤ρGWL□ņΦFΛ≠kΠ(|⁾$Εbλhμ⌡\⁄ο⅟ρ⅔NΝ′V│æÆ¤³2π⁸ιo─Γ«8v³║ cøfψ+╔A╗pp%ΜO¶′Η⅔⁴⅟┐h▒ΞδΟ⁰_X◄ļ-Hρπ┘4w^θƧō=ψξ⌠A⁵κf÷s▼@-4Xgļψ⁄»⅜Μ,┘ξ4!░⅓pG³#↑Οož-_$}Rσ»īσ▼╤╚╚ΕBā▲jī^∫┐t ƨμxΝ↑‰žΗ6SΝλ¦E2'4ō╬M≤ļ«οFW@νryμ≡(Ov┐⌡HA3[¾æ⅔ζ≤ρlG′ωA╬ģ»!¾xζ⅛≥↓≈■⁾╤_g№▲⅓′«⁄5æ⁰ļ∞Η⁷‼ūE⌡⁽░Β╝E←Σ/⅞R$λŗUET(]p2@ļv6\GιΔ¡Δ┐1⁵it⌡YB±r↑№QL┐ ¼ƨ└<|#╗(,L┼⁹πu-κ‽H%TΒL→►]╚/vΥr↓o!gμGz5╤\Σ0KG⅔_2ΤΕ←οīgΦυΞ±■7№⅔‽Ν↕Ψh⅔■ΥS>²»▲←►HD^uķβ¡⅛ξ{┼wÆb⅛⅔▓æ=ōU└⁾JΗ⅜sd³u≈≥Nv³/uŗ≤¹bžžτ|ΡΥq{\⁾~W2θPΗ:←f-Υ~»pΗnοJ█¡⅝Ε≥Η..Æχ%^y`§∑⅔÷Μ%ρ⅟T∞► ¶δķ┐!ZVΤΞi▲<ΟS}7▒⁾≈?№Μ αj‼⁾Ι7!Yψ«ΘΜVūψL/HΥ#↓8±θzA2ƧΝ℮;CΩ /π∆№└¶║δ[~χΦΒ|cΦEΞķ:CνΓ;Χξq«šΚ○⁵EWR↑ΡiS≤:~O≈ķ`s`ρ⅔εΨ⁸.׀Θv□ωņfe±≥π¾¶≤u→!ΛV@4Vπ}wωjρ¡vΒ╬}Ψ∫η²;′↔č⌠ξH╬8=↓⅔ηΧ§Β³θΩ;{∞:g═Yw▓?,⁰V─►‽Φ⅜%‰²Η⅔Κε<:+jΥ█┘ξ□čΠ÷Bē\Λī █X{±¦:oN¹Κρ]∞I≈!χ6r5!ιL◄ΦTΥæB¦Θ¡η2§Mjη{└▓⅟℮,┐¤Cæ m¤Γ╚φkpļGU║ )²c↕‼‛#⅞■%¹∫8ξ′┼OΓΟ1ZI░F±‚pΣ◄ΛķΞ^u‛ēθ6⌡J≥‚↕¶⁾žSFpQΤ\ƨ§∫⅜'¶t{η║⁴»‼□W³‰βaƧK∑1ē◄Σ←t╬»≈σKΧ↑δ y²≡~⌡⁷⁹┐─═ΕæE′F⅟ε⁾ΛM«B⁄θΩ-c#∑GΩšV‚KN»§ae::s╬ξθ→h⁴Yū¡ē6⁽½‽∆▲№ψ╗*↓'′↑οæσ⁵¤.∫ωPκ°Ƨ►π√T6╥⅓≠p[;φ≥─ζ>S‚╝∙>CθÆωļo─⁹V8@5+║Q«▓k■tαω°α⁾γΙ╚□-ū-∞¡E(│ρ]#Z┘GυΛ○=γβnņU▓■,²⌠□%′N⁾ī)ΩJ9ūX╚<+¼J ╥Μ┘¡QΤ⁷^a⅛≠olΝβ4ξ█βΖ║⅝ƨ⁽?⁷|⅓æD 6y¼x9′↔Y⁾čč⁽NκjKzvφī∙⁾ķΕX9∫=ģπ╥}∑′ωbπ└ΧΒycs¶׀≡&√└āpb‰xÆΔ²ηE:a‰▒WT↓eΥģΕIΕ⁷9ā║Rd4$8ω□@Γ(─s▒[∑EP│┘Ξ/φ¶⅞/æη■7$‚⅞η⁴@↔āΝgvΜ±κΦ;≤⌡ΠDq○JžΞ!η¤′└↕Φa≈(χ∑a∫ļ─;.○9|η⅞pgωδ¶▓εfKT*[ΝΜø⁶└▒p◄№9| ○\,jβ▲mrαΚ‚I╥Γ┘B∙Q⁴╬Ætē‽═ν⁶Ο┌M⅜?ōņΙσ°○⅜◄ļ►vΥoaģη^φ¦‽⁄↓#}ΚZΛX)≠R┼TNβŗ↕ο}«¬βο)ģ]&⅜%─↕č7ūΠΠ⅓ο└⁹Cæyh│Bκ⁸*⁾↓2ƧκsWγΨ{χ↓Osω┘/=.λΗvģΔ√5⁸⁸h¶ΤA⅝6P׀!○Xp2)[└‽vR⁰W#≡¾B□U:√1⅝¤-E%τχ-Nu% J╚οaλυ╗Æ~CΓk>≈e ↓→¶½⅟pš↔Ν?⌠MWΥ>_>⅛‼ΕΓ¶β³d□K╚∑‛w⌠wf≠)X1w⅜D‽/■ωƨ≤Mķ÷ |Bκ¼⁶┐.[sļøχ`╥Τ)RļRæ░⁄⅛εΕē{ršκρc⁾∫Oφ)%⁽~¡⁶‚T┼bOh4gBΞ&ΡΛī┐║λB§Ψ)HV┌cæ&Ji4←8│-τ¼≥║ ƨāūy═]\\℮kwλ┼v≡ΛΙ↑υX█≡&⁄1χ→╝8+‚Γρz3°│8ζκ│kM⅛βP○τcΠ⁾-ΩSY~5ņ:(δķ≥⅞μΦ%«σΠζ׀0+ωΦ,εψ>Μ3[;⌠ņš║Yf'╬‼⁷¶‽ΦqΕv←⅛x▓/Wv³f|p- ΝOγ‛μ⅔¹(ΝΙtΦ¤}▓Ι«Τ-3∑ιρ7tT«²υķ[~~╝√↓⅟BUa↑=§jΖφ⅝≥δ┌xDδε¹}⁴HnK⁵⅝ģƧΙδψc▓ΓK↕√bšβγ3┌ņUø∫ιFqωΟæL@o*1χZ≠Β√&¦L6k⅝]≈3ΚV±9ΧβcΨΞ⁴f░←U║┌←<τ∙IXΔJΦξ8ν‽≈√Θa‰‚¹c_ω‚⁽Ο±ο .Βømc_@øģyb∞M▓α∙τs⁰I′‰,⅓‽⅝Z▒⅝)¬M_ω]¹μ:╝↔]░]ņ≠θCM█■√δ│¤ο¼┼⁷ƨ⅜∙gƨ⁄Μ]¼ƨK~⌡žj╚;Ud≤∆ΞΩ[⁷jπi′┐ēθ│ω⅛%ηG↑a¶k⁾ΞVΞSķ&X'Υ< ƨƧ′l`≤Βēnļ⅓o⅟║PδY9Φν‼┌±ē4'%Cs{Ξ╔D%|└χw╥Y↓υ∆⁰δlLΝ‚jī╔EļJ⌡ΒS/#│⁽ƨ6►⁴ ūÆ⌡h‛▒.‚↓s∆≈⅔μ╚M_═ō⁰/┘ā-↓>ģuK≤¾Ο′Η5φ⅞zc℮ nfŗpδ▒j?γ⌠%Ρ⅟g#Τ²/ēEεκAσ¤ē$0Z7╔⌡⁵ƨ⅝↑½▲ε⅜οοģ⁷j-κ¶Ι¾⁽§■≤⁹»UΔ]p8ζ^⌡⌠<¾,⌡ΛΜ⁰⅓ω╚μ′iθχ׀\;_u≤ø¹y⌡׀ķΣ∆׀@GcκΧ±¤šed┘≈=G↔Q=≡Ξi⁰}>▼7‛0σz¡№╗v′▲┌_○Sļ6‚⁹§r¡═⁄DtΦ║▼Κ¾╝ōv⁶=≡Z&f?◄Κ▒3,ž∆ē╤╥Æ→Jōv-Υα↕n¾W⅝ļ▼7⁄ļ→ρN`C׀ΙΠD⅔=Ρ⌡(÷°wsχλ◄¬N¦ν‽Δ÷>Ρ#▓D>+ēī?B⁸2Κ‽OG√ωΠ⁷PƧ‚αb└οΞ5Ad⅔÷Ο³2ēρ℮Z#2δ#▲≠æ⁷>≠⁾4ΚƧ≈∙CV░K┘P⌠└‼⅝<YωΒ∫vr⅜P≡.⅟xƧ⅓`Η[Da¡ƨE⁷►─5║Kbλ≥▼i∞Μ¡$‽y`R‛W?Μ▒○ρ:°K⁽Pū⅔a╔x='χσ↓γ└√V‼ιy→≥ν;ī⅓δ∑\+v‛C┐χ`6Δwo²Æ[eHģλ¼β⁵○⁾ΓΡ↕½Ν→hκ░tΙ⁹ķRξ³Λa⁸:x7↓g▼≠Δrt¶╗iΣωαÆ![⅔xαMtο)ΔqFφ§⁰⅛@ļp'οMƧC-↓‚ī¬ΨbM\⅜⁰≥(⁶Π℮¶σ═╚■8℮‚°GOΘī╝′‛\⁽øΨ↔ΡG}ξ⅜∆⅓ī׀▼▒]Y±↑κ╤ ½k⅓╚№rMYžγ;∞⌠FΡ⁸{ēυ╝VΞ≤Σ▼]β¤_ε▼½YJp¹°ēņƧ=$≥Ν]┘↑≥Οī⌠▼⁵%Y÷TΨ»τ█RΕk'Δs⁶8ew⅝√O\Mņ∑⁶_¹abrT∞i⁄)Aen┌∑⁵⁴N┌Τ?Ζ@Π¦5ø!ΨģjΥ≡▲8N⁄k→`½0Q{Ι⁽(,≡/δ{ņ∫1`↑θβt►═Θn░ž⅛¾č97ƨxō2Τ)╥K-&qJEÆ«▒οO;rεi‰⅛:DΠ²○⅛6ž↔8C►ō⁹Ρ╬⁷‽(╬μ:π²M∞vWMcΩXjfn\¡Χ³ķa⁰γŗ+⁸α{Æ┘y▼▒<τs░ū[¾Ε─?⅛↔└◄ī=Β2τ¦¼░A§T^RΗ∆←▼□λup'█σγ╝CΡΜī#Ω=ģ‽α|⅜SIķ?x╤*ΞūnΞ▼ ↔Νn╥○U{B┌kΓΝ№□_ōΘzā∆KΚ\ƧΒō¶P9υ╬Pī║Δu└ω▓Ζ ─αŗ ↕║►‽⁵§≡VΒκX³Oθ≠ΠxΘ¡∆υPZ9ξ▼d/τ■.eΝ¤¼1X▒∞⁵∆⁶GΜi∆⌠;+EzX╬▒Λ◄0φīsKΘo┘oΘ9`Κuī¦ķ⁹uŗΣT7P╚λ³╬‰a⅛7δΞ⅛K┐τ⁄‰≡Ω¼¾≠½α0æL↕,▼ƨƧΨ⅝׀⁵▼Πø▓sZ缬f4╤⅓š:→φχ¦&⁵⁸′a¡z xW‛³m/[nΧ#P‽bU╬⅜∆λΝΧ±Υ↑XZ‚wT▲$‛GƧ[±ρ↓¡κ)■∫²%ι⁵a⅛EU′ø↑◄¾[.≤L≥┌ψ⁸&Λ=‚{-Fč█æ@Æ0π2κΨ⁽○⁾)01Æn±κ‰‰◄Ƨ¹═¹⁽↔ν═□⅔|≥η‛nIτAΣ³‼μ‰─⁾1ņ(«░,νΗλ`‛≠¾¼ΘX]‽H,[-<E.ρπ'L³uφ▼) ┘!⅔μ┘╬;Ιψ4Wψ╥g¤ZK│⁾≈I▒!īīλθL⁶ø≠℮Δ║▒╗′▼JnΔ$$Γ╝ΖεaτσP⁸‼⅟Qι.X¦№∫]θ~aī,p7!γ│AJ¹Æ:□²β‰↕0K*β≡FΖ◄X▓æ║↑YηΠmY>²OÆ⅛+¡§C′▓ļ0¶d⌠>π H÷š@]τδΓ└⅜‛⅝‼맬⁰‚ΖžΘ⁶≈y←³δ&⁰φm∞[▲C9ΗΗ╚Κļ«hN\¹VωΖ2ιΤχηBz╥█β╝╚▒∞8«'‛±′Ix╥∙>╥⁶′≥>Ο,Q^E4Κeh▓Y uāΘ╥ΘΛ]GΙρ⁽∫e@c⁵‛░∙Tτ╬j_╝&εļ⁾∆#F_╬Ψ║Æt№↔<≤b≡½z6ny┼e¤‚▲ū¬bk┘¬β(M⅓U=-℮ž►z8ΟjΥκ√┼j`p6be)⁵ΓK∑Τ>■ūo′\‚‚eΠEƧ9%∆H*⁴4KΞδ-oc░ΦāΦ}Æf≡ξ□ΘjRΠ⌠Πnκ¬⌡¾¬≥ŗΜX⁷╤»bg═3Ifi≥G⅝≤≠ŗΒīč:ē¤[3⁹ƧWŗι?⅞M⁹O≡Ζ‰⅟⁸`ΩΒ(xZ74#⅝Nī4‛T%ƨ)‽⅔÷}⁹⁷Cæ⅜V↑³G¬αXc◄↓zη⅝⅜►∆š1uUD=IīTO⁵5G,∞⅓Β:╝p╬⅜?║kX≠D`Φ¬⌠└U⌠+κ⅝▓⁾1Υ¤ūW⁷⅟λ║3⅔vΟ⁷□āŗRχ◄βj⁸Δe└NΓ‼υ«*ΟΕn‚⁴»ΚūωlQ h█○ζķdf{׀χ╬Ρ≤Η/ņL¶ēUΦŗnqEFη└8|;Δ▲ƧΖ¹Ε┐b¬╚⁸'⁄Æτ⁴≠╤ΖΠ7╝;Kr¬Pq┘Jβ╬~║nΟ`┌?|6′ηχΞ≡øφ╤W⅓¶Μ│⁾\╤Cš↕⅟′d№B1*v_d{Æi¼_bøφ≥ ΕΒΕM⁹‽υūæhW>x(‚′℮□╬CEeSķΔō╗┌∫!'-{π⁶ψ-∫│9f¾⁵-ōix?ο‛F≥⅓D2ν,▒⁄◄Νa▒r⁸⅓ķY»χ℮Ρ-eQ»0δYč↕ρ4δ4~Νz□Ηi⁷8№ω⁶÷ι}▒Νƨ?└║±2g╝⁾οΣdWļχΗ¬\╝⁸ΟOψ⁾⁴Δ⁄ΤΘ┌%≡īPQ░½]ō5afτ█+,ν9▼Ι≈▼Η\ļƨ┐⌡wg§j %.āæ└′5╚^Γ↑⌡Χ∫P∆H∆≈≈Ξz³№■∫±Β³⁾γn¦┼yΚΘ≥;ΚC¦'ŗ`κ⁹ΧƧγPdγSmυ⁹○Μ▼s℮ķ(N⁸θψq■A?┘□<⁰Æμ∫J▼□Ν(D|≠⁷iΒ⅜⁾½°WkL¡╔/⅜∑⁴ηš○⅜ρ═?│□q¦&║ψīᱬz²‚Iūe±γ ╤‚g∑|;]^M┌∑6č╬Ν⁵∞→`δΧ'nL└&℮nz└⅜!(Τa š«/ΗΙF←Θ⁴t(ΞB┐γ←┼ κΕDΙ≤∆]⁽╬ΕjW=@Ω∑ø─β└⁴q►=═P↕Tp┌ļ╝′2(ņ═³)Θ¤½╔Ξηāμ³b↑ŗ▲⌠ &¾ω\%◄┘ø█ Λ═+╥*JΨ5FΜ|8»@zοΒÆQ$⁄u3ā⁄W*č╥d¾~⁹Y}Ρ╚‼^κ)▒ƨ℮k█{∫⁷nΦE╚g.¦E‰╚f←cWμķ²¡κ⁾◄»κΓ3@§iK▓T↑◄#²[Bp√!◄υ±«κ□℮ž\UΕ⅜⁷nμ9Κ41⁶.┌┌○S≥⅝⁴ψε⁶>+⅓⁵ΠΠN╔░←@Β$+ΒΓ%čQ□αLμ⌡j⁴Μ8‰v9}4╚‽ļƧ0Qš╝7√^»▼4ŗIV¾±ņχf‽Π╔)πρ¤¦gÆē⁽ΡiΩ ⁹∫_$└Λ¶ε▼j\qΤ1QΥW▒∞Ψ,κ╔'č╤jā'93EyƧx∑I⅓≤─π¬‼π┐⁰≥↓u╤;αυ∆π²◄7^║ρηš≥wƨgŗ>xu½!ņaΡYu∞1!²Qζ'ΣσmHτš]ē«mW±j⅔λg0ω(⅛]z2↑ΦΠ`‰ι6l→φβ$τ─θģX⅝č═ιx‰ωģΓī÷nπ□f⅔‛⁽r←′m╤‛ω=Ƨ°AC╤׀Λι_N№λ;∞Wy׀│Θ|<υ│čθæΣφ`kc_~╥χ╗βV%▒8 }W #`╔i/Φ⁰_⁴¡ŗ»w'h╝¬ζζhψ∞¦≡╝Zοθ ⁾6øuιΦ‰→▒EøG`τΧiι─⁽√═Σ[δ≥K╝χ(┌┘c′ΗΣ&⁹εD){∑⁷ξ─¶rΔo⁄γ┘$∞Xσlr≡κπ▼mΩ)ZΔ~O}░WαP░k⁶C∑θm∫δΔƧI¹¡Μ═yž⁷τ}\■∙‰m‛fTζΒ░√┘↕D/²β-⁄⌠>AλL^pΔαJy»r□⁾№1]¬$2x²└Γ3└2λh≈JjƧōfλΕUυ↓nΥζ⁸Ω\o╚ OIž⁄℮→ΛjšøΩ²+‼q2øæωZx∙n_≤c⁰√┘0Ωσθq⅟OΔ⌠ο⅛╚JK⅓ηļ┘∑O┼Q╥μ┘≤⅛¦χΔEhV┌0⌡ƧνƧžσ┘d∑gø⁽z2:>θæDēYΜ3Θ≤B9NznjWΣΦ`Ƨ∞⅜▲¤Β‚[⁸σ[%q²≤C℮↕│→═oqΕΕ⅟╔¦←sgοč∆ΥM⅓l=‼Νg‚ū⁾Ρ⁶└φOÆi░─Æ█P‛ŗ‼r¡⁰{Ƨ,»▼▓-¤ζ0u%□→Θ▲φιp<8γ■■»ƨ0āροηp>9m┐⅓M█σsζTl▲č↕η∫æΣ`╗ņ%Ι'¼Tn⁽¤5iž■▼š○g∞κ■⁄Y⅔Θ§y⅜▼╥¬[χζθη╥μƧ¤█I,ιƧķ\ε(¹Δ▼⁷θ▓ Γ≠EJ≡c‼+j⁸γpφņ⁽╚⁵≠BķGαE.Ο>┼ōZ‽r¶ΓΨ√↕,=↔⅜δδ∑№γ3ε │ņγ≈OzY^)⁹CΥ[′I′╤¾½z³←‰V∆t≠χΘø⅞/f▒⁶Κ*ξeν‼⁄ēa▒Π¾Π{PUΦ<⁶┘Χ⁰ģΘ┼ķ(ƧΒƨC√≥→■╔u∆F┼h“šιο:|Oρ÷ )≤iζŗof~Gø8;Θ¦╝┐@ā%GXυMλ┘∙ķoωαΕ≥▲5s℮½׀v¼╬æ4θ9XG⌡ΙΖuΞPSλ⁷7⅜³Ζ∑ΚΧ¼Ι‼→`⁽PΨ:δZ§∙▓«ο∑»η@l═ģ~ƨty¬8Γ¾.⁷f]lΥ¬l?⁵η⌡0Γ÷|°▓8┘]υ°'ψ÷ū7²īHø ⁾p⅓Wα■zΞ¹→ļsæZ¼ΦΝ5.a╤χqi⅝⌡←'\k[η═‼āΖK¬c§ķ⁽β⅔═ļ!O3▲⁸◄-∆ΜhS▒ģgΘ○ν≠OmV'║░∫κΒ¬č¤L⅝‚U½‰\¾¾░∫Ε╥ƨ┼KΣ»$Ii┐┌Swb↓Ι(;ξν׀▓Φ▒Εyη│׀L►¤Χ8°№IΦb]┌─┐⁴λv;¾╔+/Χ,┐┼½∫`9»Ι⁶←<ρg╔Θī[?ΧƧωΣ▓ŗ(.?Ξ╥P⁸ÆžH│⅓≤╚ī┘⁹u~¤²τj╝∫^7∙η0׀wΞd↓⁹4¶ζρø╬1≤⅔@\GΞ9ŗXζ¾≈⁴sΠoēHļ¶η¡hļņ√ōρq3κT┘W}'α■׀pī►aυ±▒ι┐τΥ▒⅝⁾┘⁵⌡YēbA⅓P↔⁶T\⅟≥Σ═ƨΣρ-K_)κδ⅟⅝J⁹Mρ;Κ⅞¬K⁹½?øh{x┘HζΞ:pzG¦μΞILοM{πA╗1ωχ┐≥█fv?╗┌⌡½╝↔Ež‚│~ƧQ¹Θ⅜§oφ►AƨΛ○#ŗ√┌²ø┘≥‛׀#(‰╔±ΧrnK[׀μ¤&z‘o5─r∑"-+<>.”{ē;ŗ}o"ģ#ģ⁸ƨJΕ\f╬-⁴↕ΘιPΒ¾G¶[}⅞■X∙κΕφ■3U~ņšīU╬↓;W⌠Ji`]¤Ƨ╝0¼¦⅜ηoε≡³φ}¹→«π╔ΤøηWb=18?¡○Κ┐ Ι→dΒ-k⌡τΚ)Ιrqy¤─οΛ℮⁴¹$~dā└ +Zŗ℮⅓ī□Z⁷┌øaΩ┌δb╚ο¼Ψ*c─Δ∞¬ēJZū─Ωq┘‽+³⅟¶⅟‽¬bmχ¶╥╗┌½%ģIō}⅞|»²Φ}2νΧ⁷h╤.⅛k)ψΥ⅛ρP±↓*Hfī⅞γN■Zž⁶Eθc⅞ωNq&r³⅜Οæ¼Ω⁾jdc⁶⁶╝ΘƧ◄ρ):▒½q2y═@p⌡mδ¹ƨ1‚+⅜π′∑┼░!0≥Λ7nD³ņ⁰@dķ⌠Ψāt6ģ►┼P>⅛nκ|←Ψķ÷g2Ƨ³3*∞!d3#KY→▲#‚⁾u⌡{⌡Wθ≥⅛Q ╗ 7⅓↓P°√ΒD┼⁴╔⁴Εψ°╬οy~ξφ◄↑ν¾↔,ķ'►:◄Π′<ā⁸‛↕bΩξΖ(¼IXh╬▒╗λ»Ψf.6{5§⁵\℮‛Ƨž▒JψR≡ΧΓOKρoε■⁶²~⅔∆ε√Π7⁾ƨķ9□↑ø¡θ8sΟ▲]/ļυ<⁄νφWŗ◄>tqI⅔*≈ΥωΗγN²ΖqΟf┘⁽§γ-W◄ε┼~═Ρ/P╚=η⅟√κ¦Mc∞C≠L¾x⁸ū^³≡≡§`⁹j←τφ¡γΒ‼H═ωΝ─Φ⌠@τνA╤ī┼9░]ρ╚Q>ωΙ╝a¼2Γ↕┼σ³)○ņΦē≡D┼=Dm{ģ∞.Φ|l←ƧΤ8^Yv~┐└M)T⁽∑ļ)⅓d~⁷◄Λ6^⅝Hæi∞׀ē_Ψξŗ█└■Κ⁄═rΡ1ūΝΥλ≈ņ.-{jVFy!⁹κ9kΦδ⁴_/r╔⅟ρ%÷χ№┌τε╬→q/ƧΔ║ο<∑Ƨθ$ν≠√r°⅔∆≥Ylæ:─=ζR¼÷Zκb╤÷σ$ķφpš`0↕√{δ*║.KIu|b∑+Δ⌠{Σ,οPX4№[F[⅓⅓ν׀C³Æψ(█░xx¶ΝK1÷δt←┼─┐↔ķ4χψ;GβJ│⁵α÷κδ⅛{(«′F4≠θ◄95└(]Β┼}─`1«׀⁶Κ↓▲č&ΟqΧ¶6▼87$Ν8DBY`υoγ{r╚█└‽hψΠ:aLψΗ⌡≤hΜ℮═]θT⌠I─GΧŗ⅔(╔⅞H▼]ΩAk○žEΡy⅞*x‚½◄/╗⅟Β%F+q5ķΩ,─↕ič℮\cΥΕ&6⅔Ky⅓׀7≠V⁶wi_Xc&╔x*q96‚δ■ī∫┐↓8⅟Xņ,ī─⁄∞λcJοFη▓÷ ⁽|⁴pι╚╬‛i∑↓J?Μ=Æ&ņ∫┐ƨΖ]=┌V׀{(?c`χ√░3∑wƧ¦q~′§o∫Z′HB⁰Ƨ∞nģt⁽≈ΠL⁸⌠░[@20∫≤R↓⌡¹⌡č╥π⁷‘o ``` Try it on [here](https://dzaima.github.io/SOGLOnline/) (no SOGL permalink because it's too long). Warning: takes a loooong time to run because SOGL is very slow. [Answer] # 30. Java 10, [1780676 bytes](https://s18.postimg.cc/sed8qz8qh/Capture.png) ``` v->{var b=new java.math.BigInteger("X");for(;!b.equals(b.ZERO);b=b.subtract(b.ONE))System.out.print(0);} ``` With `X` replaced by the number in [*@hakr14*'s link](https://paste.ubuntu.com/p/XMH7hmKZZb/plain/). No TIO link, because the link is too long to fit in this answer (1,116,442 characters), and URL shorteners are crashing.. >.> Hmm, I think my score should be quite high.. [Answer] # 8. [05AB1E](https://github.com/Adriandmen/05AB1E), 179 bytes ``` •y˜Çr-ñāt¿&ãx^ÇlBËÔáA∊z^a’Ù;Ò êþ2¤´ñ¡ηjƒĆαs½ζ!é/‰.*<œéÊŒfº}ÎjþŒ1ø–Îи:tÂβιne‘ʒÒƒŒNyÕ9îK<ÊýÇM∞iº§ΘT]µ¯šÍθβ©X#ûÿ±7SÝ`0ð_oPw°<G¶¦L“LJoN¨₁A+Ù¨ðè›eÞfRÃkδÑ)©vC‚λB₂Á©Bí²W>ÝÅιµн'sͦ•254вçJ ``` [Try it online!](https://tio.run/##DdDdSsJgHAfgWymCoqJSSaKSQDsIzCIqqJMsA4UsElIqg2AuSjEUmgUaKlihLqi2oeYHKvx/zoOCF6/hvZHVcwmPyeo5NHsNgwsv4d8somdTUHuREHVH8XrpRvTEgXs8omDnsfiV28OFDDKLkIbwjo6F3qgClQrs29@XendMDVKb1YYhz3BBmZ6w6SnIiOuSj5rXSPrR0SUz6lxIITmoL4QgMo01Tr1cSP9IkPqSLq2H8TSPz1Ub4mgjusZj@SNqUomlt/eoSl96AQlWZxrJuyNooUvq3BZyByYo@4GNC1JsK1SjoosLWZczsE5lLkbsk8hQGQrKXGh6kfdt4uaYVfAwTvL5MheeWcvBRRERkh34IG1nCTncsgZVB@2xIBJU/L@xWGcHGkpOw/gD "05AB1E – Try It Online") 30 bytes less1 than the last submission, by using the 05AB1E [codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage). 1Because saying "shorter" seems way too unfit when it isn't readily apparent by the character count. [Answer] # 21. [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22042 bytes ``` 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 8* ¶ 4* ¶ ¶ 5* ¶ 4* ¶ 4* 4* ¶ 7* ¶ ¶ 5* ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ 5* ¶ 4* ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ 4* 4* ¶ 4* 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* 5* ¶ 6* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ 6* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* 4* ¶ 4* ¶ 5* ¶ 7* ¶ ¶ 8* ¶ ¶ 4* ¶ ¶ 8* ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶4* ¶ 7* ¶ ¶ 5* ¶ ¶ ¶ 4* 5* ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ 4* 4* ¶ 4* ¶ ¶ 6* ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ 8* 4* ¶ 5* ¶ ¶ 7* ¶ 5* ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ 7* ¶ ¶ 5* ¶ 4* ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 6* ¶ 6* ¶ 6* ¶ 4* 5* ¶ ¶ 5* ¶ 4* ¶ 8* ¶ ¶ 7* ¶ ¶ ¶ 6* ¶ ¶ ¶ ¶ ¶ 4* 5* ¶ 5* ¶ 4* 4* ¶ 4* ¶ ¶ ¶ 4* 4* ¶ ¶ 8* ¶ 4* 6* ¶ ¶ ¶ ¶ 8* ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ 7* ¶ 4* ¶ 8* ¶ 6* ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 4* 5* ¶ 4* ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* 7* ¶ 4* ¶ 4* ¶ 4* ¶ 5* ¶ 6* ¶ 6* ¶ 4* ¶ 5* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 4* 6* ¶ ¶ 4* ¶ ¶ ¶ 7* ¶ ¶ 5* ¶ ¶ ¶ 4* 4* ¶ 6* ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ ¶ 9* ¶ 4* ¶ ¶ 8* ¶ 4* ¶ ¶ 4* 4* ¶ 4* ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 8* ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 8* ¶ 6* ¶ ¶ 8* ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ ¶ 5* ¶ 8* ¶ 6* ¶ ¶ ¶ 6* ¶ ¶ 6* ¶ 8* ¶ ¶ ¶ ¶ 8* ¶ ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ 4* ¶ 7* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 6* ¶ ¶ ¶ ¶ ¶ ¶ 4* 4* ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 8* ¶ ¶ 4* ¶ ¶ 7* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 9* ¶ 4* ¶ 4* ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 5* ¶ 5* ¶ 4* ¶ 4* ¶ 8* ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ 4* 4* ¶ ¶ ¶ 6* ¶ 4* ¶ 6* ¶ 4* ¶ ¶ ¶ 8* ¶ ¶ 4* 6* ¶ ¶ ¶ 4* 6* ¶ 4* ¶ ¶ 8* ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ 8* ¶ ¶ 5* ¶ ¶ 4* 7* ¶ ¶ 4* ¶ 4* 4* ¶ 4* ¶ ¶ 4* ¶ 8* ¶ ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ 8* ¶ ¶ ¶ ¶ 4* ¶ ¶ 6* ¶ 4* ¶ 6* ¶ 8* ¶ 4* ¶ 4* 5* ¶ 4* ¶ 4* ¶ ¶ 8* 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 6* ¶ ¶ 6* ¶ ¶ 6* ¶ 5* ¶ 8* ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ 8* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 6* ¶ ¶ 7* ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* 4* ¶ ¶ 8* 4* ¶ 4* 6* ¶ ¶ 4* 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ 4* ¶ 4* ¶ ¶ 5* ¶ 5* ¶ 4* ¶ 5* ¶ 4* ¶ 9* ¶ 5* ¶ ¶ 6* ¶ ¶ ¶ 8* ¶ 5* ¶ 4* 4* ¶ ¶ 4* 4* ¶ ¶ ¶ 5* ¶ 6* ¶ 4* ¶ ¶ 5* ¶ 4* ¶ 5* ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ 8* ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ 4* 4* ¶ 4* ¶ 4* 6* ¶ ¶ ¶ ¶ 4* 6* ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 4* 6* ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ 6* ¶ 6* ¶ 4* ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 6* ¶ 5* ¶ 4* ¶ ¶ ¶ 6* ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ 8* 4* ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ 8* ¶ 7* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶4* ¶ 4* ¶ ¶ 6* ¶ ¶ 6* ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 8* ¶ ¶ 5* ¶ 8* ¶ 4* 4* ¶ ¶ 5* ¶ 6* ¶ ¶ ¶ ¶ ¶ 7* ¶ 5* ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ 4* ¶ ¶ 8* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 5* ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ ¶ 7* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ ¶ 5* ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 5* ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 4* 4* ¶ 8* ¶ 4* ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ 7* ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 4* 6* ¶ ¶ 5* ¶ ¶ ¶ 8* ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ 6* ¶ ¶ 9* ¶ ¶ ¶ ¶ 7* ¶ 4* ¶ ¶ 8* ¶ 8* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* 4* ¶ 4* 4* ¶ 4* ¶ 4* ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ 8* ¶ 4* 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ 4* 4* ¶ 4* ¶ ¶ 4* ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ ¶ 6* ¶ ¶ ¶ 4* ¶ 4* ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ ¶ ¶ 4* 5* ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 5* ¶ 7* ¶ ¶ 8* ¶ 4* 4* ¶ 4* ¶ 8* ¶ 4* ¶ 6* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ 8* ¶ ¶ ¶ ¶4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* 6* ¶ ¶ 4* 4* ¶ 8* ¶ 5* ¶ ¶ ¶ 5* ¶ ¶ 8* ¶ 4* ¶ 4* ¶ 7* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 6* ¶ ¶ 4* 4* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶4* ¶ 4* ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ 9* ¶ 4* ¶ 4* 4* ¶ 4* 4* ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ ¶ 6* ¶ ¶ 4* ¶ ¶ 4* 4* ¶ ¶ 7* ¶ 8* ¶ 8* ¶ ¶ 5* ¶ 4* 6* ¶ 8* ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ ¶ ¶ 6* ¶ ¶ ¶ ¶ 4* 5* ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* 5* ¶ ¶ 6* ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 5* ¶ 4* 6* ¶ ¶ 4* ¶ ¶ ¶ 7* ¶ 7* ¶ 6* ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 5* ¶ 4* ¶ 6* ¶ 8* 4* ¶ ¶ 4* 5* ¶ 8* ¶ 4* 6* ¶ ¶ ¶ 5* ¶ 8* ¶ ¶ ¶ ¶ ¶ 4* 6* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 8* 4* ¶ ¶ 4* ¶ 4* ¶ 8* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ 4* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ ¶ 8* 4* ¶ 4* ¶ ¶ ¶ 5* ¶ 5* ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* ¶ 5* ¶ 5* ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 4* 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ 8* ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* 4* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ 5* ¶ ¶ 4* ¶ ¶ 4* ¶ 6* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ 6* ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ 5* ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 8* ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ 8* ¶ 8* ¶ 4* ¶ 5* ¶ 4* ¶ ¶ 4* 4* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ 9* ¶ 4* ¶ 4* ¶ 4* ¶ 5* ¶ 4* ¶ ¶ 5* ¶ ¶ 8* ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 5* ¶ ¶ ¶ 6* ¶ ¶ ¶ 5* ¶ 7* ¶ ¶ ¶ 4* ¶ ¶ ¶ 8* ¶ 5* ¶ ¶ 8* ¶ 4* 5* ¶ 4* ¶ 4* ¶ ¶ 4* 5* ¶ ¶ ¶ 4* ¶ 7* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 7* ¶ 5* ¶ ¶ 8* ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 6* ¶ ¶ 4* ¶ ¶ ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ 5* ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ 6* ¶ 8* ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 7* ¶ 8* ¶ 4* 7* ¶ 4* ¶ 4* ¶ 5* ¶ 4* ¶ ¶ 4* ¶ ¶ 7* ¶ ¶ ¶ ¶ ¶ ¶ 4* 6* ¶ 5* ¶ 4* ¶ 4* 6* ¶ ¶ 4* ¶ 8* ¶ 4* ¶ ¶ 4* ¶ ¶ 8* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 8* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ 6* ¶ 5* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ 4* 7* ¶ 5* ¶ 7* ¶ ¶ ¶ 8* 4* ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ 4* ¶ 5* ¶ 8* ¶ ¶ 8* ¶ 4* ¶ ¶ 7* ¶ 4* ¶ ¶ 4* ¶ ¶ 8* ¶ 4* ¶ ¶ ¶ 7* ¶ ¶ 5* ¶ ¶ 4* ¶ 5* ¶ ¶ 5* ¶ 8* ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ 7* ¶ ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ ¶ 6* ¶ ¶ ¶ 4* 6* ¶ ¶ 6* ¶ 8* ¶ 4* ¶ ¶ ¶ 4* ¶ 4* ¶ 8* ¶ 4* 6* ¶ 5* ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ 4* 5* ¶ 5* ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* 4* ¶ ¶ 4* 4* ¶ 4* 5* ¶ ¶ ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 4* 4* ¶ ¶ ¶ ¶ ¶ 5* ¶ 8* ¶ 6* ¶ 8* ¶ 4* 4* ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 7* ¶ 4* 6* ¶ ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ 5* ¶ 4* ¶ 4* ¶ 4* 5* ¶ 4* 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 8* ¶ ¶ ¶ 4* 4* ¶ ¶ 4* ¶ ¶ 4* ¶ ¶ 6* ¶ ¶ 4* ¶ 6* ¶ 6* ¶ 6* ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ 6* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ ¶ 8* ¶ ¶ ¶ ¶ 5* ¶ ¶ 4* 4* ¶ 9* ¶ 4* ¶ 8* 4* ¶ 6* ¶ ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 7* ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ 8* ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ 4* 5* ¶ 6* ¶ 4* ¶ 4* ¶ 4* 6* ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* 4* ¶ 7* ¶ 8* ¶ ¶ 5* ¶ 4* 4* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 5* ¶ 4* ¶ ¶ ¶ 4* ¶ 4* 4* ¶ 4* ¶ 5* ¶ ¶ ¶ 4* ¶ 4* 4* ¶ 5* ¶ ¶ 4* ¶ ¶ 7* ¶ 8* ¶ ¶ 4* 4* ¶ 5* ¶ 4* ¶ 4* 4* ¶ 8* 4* ¶ 4* ¶ 5* ¶ 8* 4* ¶ 4* ¶ 6* ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 7* ¶ ¶ ¶ ¶ 4* 6* ¶ ¶ 4* 4* ¶ ¶ 4* ¶ 4* ¶ 4* 5* ¶ ¶ ¶ ¶ 8* ¶ 5* ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ 8* ¶ 4* ¶ ¶ 5* ¶ 8* ¶ ¶ 4* ¶ ¶ 5* ¶ 7* ¶ 7* ¶ 5* ¶ ¶ 8* ¶ ¶ ¶ 8* ¶ ¶ 4* 4* ¶ ¶ 4* 6* ¶ 5* ¶ 5* ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 4* 6* ¶ 5* ¶ 5* ¶ 6* ¶ ¶ 4* ¶ 4* ¶ 6* ¶ ¶ 4* ¶ ¶ 6* ¶ 4* ¶ 5* ¶ ¶ 5* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* 6* ¶ 5* ¶ 5* ¶ 4* ¶ ¶ ¶ 4* ¶ 8* 4* ¶ 5* ¶ ¶ ¶ ¶ 8* ¶ 5* ¶ ¶ 4* 4* ¶ 4* 4* ¶ ¶ ¶ ¶ 4* 4* ¶ ¶ 6* ¶ 4* ¶ 4* 6* ¶ 8* ¶ ¶ ¶ 4* ¶ ¶ 4* 4* ¶ 5* ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ 4* ¶ 4* 5* ¶ ¶ 4* ¶ 6* ¶ 4* ¶ 7* ¶ ¶ ¶ 4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 7* ¶ ¶ 4* ¶ 5* ¶ ¶ 5* ¶ ¶ 7* ¶ ¶ 5* ¶ ¶ ¶ 6* ¶ 4* ¶ 5* ¶ 4* 6* ¶ ¶ 4* 4* ¶ ¶ ¶ 6* ¶ 5* ¶ ¶ ¶ ¶ 6* ¶ ¶ 4* 4* ¶ 4* ¶ ¶ ¶ 6* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 5* ¶ 5* ¶ ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ ¶ 4* 6* ¶ 4* 4* ¶ 4* ¶ ¶ 6* ¶ ¶ ¶ ¶ ¶ 5* ¶ 4* ¶ ¶ 4* ¶ ¶ 4* 5* ¶ ¶ ¶ ¶ 5* ¶ 8* ¶ 5* ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶ 4* ¶4* ¶ ¶ ¶ ¶ ¶ 5* ¶ 4* ¶ 4* 4* ¶ 5* ¶ ¶ ¶ 4* ¶ ¶ 6* ¶ ¶ 5* ¶ ¶ 4* ¶ ¶ 8* ¶ 5* ¶ ¶ ¶ ¶ 6* ¶ 5* ¶ 4* ¶ ¶ ¶ 5* ¶ ¶ ¶ 4* ¶ 6* ¶ 5* ¶ 4* 4* ¶ 4* ¶ 4* ¶ ¶ 8* ¶ 4* 6* ¶ 4* ¶ 5* ¶ 4* ¶ 8* ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 6* ¶ 4* 7* ¶ ¶ 5* ¶ 5* ¶ ¶ ¶ 4* ¶ 4* 6* ¶ 4* ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ 4* 5* ¶ ¶ ¶ 4* ¶ 5* ¶ 6* ¶ ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 5* ¶ ¶ ¶ 4* 6* ¶ ¶ ¶ ¶ ¶ 4* ¶ 6* ¶ ¶ 5* ¶ 4* 4* ¶ ¶ ¶ ¶ ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 4* 4* ¶ 4* ¶ 4* ¶ ¶ 5* ¶ ¶ ¶ 8* ¶ 6* ¶ ¶ 4* 4* ¶ ¶ ¶ ¶ 8* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ 9* ¶ ¶ 4* ¶ ¶ ¶ 7* ¶ ¶ ¶ ¶ 5* ¶ ¶ ¶ ¶ 6* ¶ 4* ¶ ¶ ¶ 4* ¶ ¶ ¶ ¶ ¶ 4* ¶ ¶ ¶4* ¶ 4* ¶ 4* ¶ ¶ 4* ¶ 4* ¶ ¶ ¶ ¶ ¶ ¶¶ ¶ ¶ ¶ ¶ ¶¶ ``` [Try it online!](https://tio.run/##jVxBluy2DVwjp8Cau7wnqcfHySKLbLLwy9lyAF/se1otkVWFguY/j@3u6R6JIkGgUCjwz3//7z///dc/f/36R2bENjLyr//n9@v3PxHv1xHnz/z1@WIbcb59/8xPrld8nfPn8@680v3B1zjfn@/eV4v7DrlufX79/bOP6wLvK18ffb98/93nzWvdcf3lPs7HmAOez/Ae0jWgpJF@f2t9577SPtYEnM99jjvhka47JkxUzKFEHCPpj@efvH9x3/Ke0TmEa7bmlNE6XB@eX5jTcT/SfIT7wu8nuAZ8zCkz158jntfIxFt@PrwWgywEHhpW6h42LMpcQJyD69NjXPZyXSJwbdZNxLym5cFk4Ozj3fmJ1294Ec7/GqPYB17qNWix0aqnpa0njDqh7@@uuVubCx4Qrnwtf8Jv2KC/f7uNfB7evSlCtnNcq5lsMXMGwS1MKwEfQNN53mHtrjVh39@/jWKa62dG5Cnnhrku@L7ifOT11LmGEveF/O4ImvPr1vvAS93P8IK1P2dh2rz1Tzv4ncAB1Q2Ka7KMdgfLu59iOVRwM6n@J6bnhE9yerw1i8e4xoFv0TGCe1gmsQ9eaTLapGcWFxw46uSx3GYMuzKDfXA6w9BRzvW4jIoDU@AY5wL7y6b6/Rqe3h8fg7dqYnAEc0dHkHMHbeQ50Exgj6lXZJsubot23j2o5XH5AdV9Bhv752s48s83joGLNIcCDnL54o8Fr8EqTiBHkDiBADnMYsdcnqDdk@AS1rxQsCEjpj30tlYdT1qvpov38Z9Js8MhPsS9wMS45cgrAJEnRnwSJQBEtcoALFYdc6KXIndk7Od2XOjzKMhGFgQGOxwfYG43HVd4/w7eL7PzbGBL4l//GGHCtpg2OoZpyIEIb2Noim6aAMc0uIewzUF@F2BcN0FZZQJViUgivLOljchPzAAL/dA1zCj@Ze1/2MHzQSmG4ljWSu4j2LHw1snMEtsBo8Lm1sF/f/I1xP@JuaOxFrQV6zsIdBjVg6cTdzK3ctYcpAB95/XA8hgy5KO3wMvIDqj4@SGTsMgPfcv5ZmUVZm0/j2mHGpzIfMGKNmG6@O4X25Z6jYXaI6Kd6NusovoIi/0Ddx5GcHroeQV2kYqys8E88wVMYI3pFLtWVrF2N@yYfUTjuzH5@Pi1NNsxMIVblon5BKYw3m2Ca8O1J9iPnIGJbseIJixKFi2QjtOTtD6NAxFFzuClkj24vqpzX6FiBOfTzfawcD8QqbRZHyW/NA08DgVBsI/DwKB0JgIBnh4d/GhNDa53DfxDdMkPzXRSjYOKDijwrUGyXeJuZYKAiJJ00NZs46/hIjHkXDREGM680zEMidbtAkwidE/tsh08l4ZgBXJfztzQ69QVQ4QTqYko4U/nSqLCw2UluN8ldb7/gCE8hBIdAeXcPoviFI3CIHA7YqJgTcQXEg/FQDBlGxSaitI8mUUF/ItII@JmZdRMCzLvQ9kbjE5pMknkLgQc1T7Iik5bO4bblcLPEuTU3VoYAF4VN9p90JJGCbRMBivc82Su9coEYuO3AE8qRfLxJIVNxh0NtFxAvFyABUM8IGjw6GGCn5lHWd6I0OQcqNs0NCTFE9jX6O8K@mRA4uhCxQ1o@wacmcRZnLfwb5gTVhp/XRiyOM6bGXPWdLuhqCksFpMjPgZZOGIc645ytnsCFZOwpQc4Uf@uMPjxUCtYRhLEd5OLjyghXfPM43HRJTiZIKJ5wUZBuuIUZxpJPpkmssIS5uJasgk@Ewx7jLaMBjsVOFuiUQoEfGC9kd9TIA0xz1AsCO5LZD1GmHTBhlnAJ6G@AeJzjS7AERu/DMaXUlHA@P0aNQ1S0jwFzGVXL2krIY23QdigU7kPKk9tI7v6ovggwUwZjoNs8BAtKFZHuSYaaF0l3kYyNUb772s4J8D@DBNPJRqSmDDHtVrD7ML/fIBFdcIupawtPScZ4kdLyqCAGdl3hpLO9/Pu1PDHBP/9Vfgm@WGIGLDfKYeIFMTO8Oye19cwtRliN73HLVE5oqSCnPAZAK4sZxB07LKPcMwxwXIhVDRbLDEspVBP/lHLTtWoBdZvLqcLxxvgZkSKXlkkKooiZROVmSkJooHUPgAqvpZJlAgVbo@LEVgHKhufEPNjhTgt/89FNq4yacX6VUAj4Qyq6/eLrRjPEZbbcLIFWxvHHcUlNt5DFdsZgDUvvY26DBBtDYlhsiWUe3ReboXYiggi@qkSZrrEjhItKq@@Hh6/RKoHNLV92FAiGbOqZ0LKlkLRaLayY2I0fe3@kGatJV3rXJFjyV11K4stY@ItF3YYBavS2ZTTq3ZoG11@F0o9STIuOoQuanLBHqsAlo7hGS9yMSmBZXr/XtJNTLArj7@yc7UJ41gjiqsI1rmwYbIEIpSsEw2DL/GytkTFQyrRqJo8hpVGalUJoqiVrG14MZRSr6K4EA0IOUEVbriCMDr9nkZMlzHUAlMV7SXvgWljx7B1CiqjS/7NfkEYs89UbH1dREUjiLAKyx0uec8MV1SlIF5rVCqVu@IyuihZfxHihPVlpcbLBFdXODDWYtSBVT@lmyWEs36UKCjHIoyqQpqXAPaITm91X2MfYYmfKtDC2WAGPEWxRuDOsWrJlSRXWZEahyjzJOsQagXKGk6DgCqUPgiWigoKQRp9DCdJ1QGyntQ/jfFZRk2ZlTtlBlC8tHCa3geVanohWalcBJS9ExWp8Iy3HfiUK028/neMTv6XqMt1xRly1jUZZ/zn8JgQR3RNmnwtIEFwItQUyrl/MRowG9LFDRFakoiQnLPorzARZdarViB4H6aOMDU4Ir32rErT8AyPH8pbpBN8MYXR2TSFn4VCiFncumTXbaDGn/t5oM6AbIj/VL@E/F1SXYa8AsXzHbU0jYaolETE9lOId6uJZ1AflrGoluKpx6Zvo3wQYfLE5hea0TK6pxBTC0phbA6DTzQ5X9XViYi3z9VLuroNC4xFlcA8l6WkStBFlPKgSqrNE8jIV@9lFUj5G8LzwhgaqbYpyz1z967@r4qm8LI3dCURHJQfFlp0K8KQz0nfRyclkH0RnqTu4mkgcqkqcasJ9NVTbjLya2MZU4En0apiVSeJNOk@sndFDTGKdrKZFoG21yWyeGFanz/Gk3upkDCazjD6ekQ0he5ULtAAzJ9pP26rSxRfxVO12/N/@4ishR3FrkiYhjSsQdCiFIo7VQr@3sZToTCjk@nypBbaF6EZwLZtRPqCIWEY7hmojJtP9V8jsixxpC8vPRd9ujmYt9hVEFZQZVhpuS1thdqAyD2SM@lOdMCaxgQtsSZaKdrGmugWaROXsDhkSbG0hQ/7aFXVPyRtTCbr1iz5vOo4SzdLhBFWheHKw7mfrF2T2jPr4H9aMsZQBhRwX6OtGADJYvy5rbUhIaASM442wqnaJN6mQ02TbdikVeuPUl2LXs4lO8yVyntKQGRkQRmWSdGChM8sI2zoGtMNgSRbLOBGL2svYUkryAkbUm8tkTZasGJNUFVB8FrMDql2Nj1YCtYxAOGGD6sVaepv2Wbm0Zdq1zVVExouP6ephdy6oZrZHoMjao0lbIWszs70ckNq62qkzMvSe6rIB3NKV2RaHEGctRzHLZOFKor6OJ2orU2bk8B@cuWg4gAuQd63P0YlYaJzSoqDjpGmCtOfdMBmweH5x57UfVQdRJWq9f19wcq1eCBlKd0RJVoYlS8LyLm7P7TMfk0aywRonSJt9OR8AdtZhdCuhYaswljPHbJMWan@Vh@YzVEWiPuaNhr@QOgbdALuiAiMqEUFxBz9syJLFapdBiGqTw4rVU6aImbNkuD73E38Ke5AN4dMxvBGCT/RTb740Ny3jVLG7g6UKNC5qMfbToXoEwfjyJyp113bEzWYD2H3RsvbsU0xivClT0duRVOsCQOPEe1T//HW9pFtwx01EJ7n1jJ5s/33ikydfgCqoB7B4ARGhGuWDMcgVwKu6D5sE0VpAQ/bacL4ixbZ3MzEeHEKjew3o2mLghBoMwMlm8lpm5bnesQO6aKO0ZXC9O4R2B/b8XVR0b3tD46m5Cam9LLNYYWpKMd3sMYWlUk2c5GTaTZ3AosI9ZqM35Rds@0O3YaLXkWq21wPhXOk8402pETXPPVAzYg@D28FllT1oZ1qTfqctDj12CLo6ESux1OxjViGTmJaig2eAJPaabb4qkpnsi1bM4nX6BTCU9ecBShyRhTJ9bOoFbga3nuZa@lOkfSwayJlXU97SJU2QM71eo1SNNIap2daS0mYhUHdCQBclGIRgQ5Se2GccjsK8glXNrF0kaSqdDt3jFhoWlAq3EB5PilFdAhHcX5C9Va6qkhOo4qwa39u2m6nx0pbSRG9Tfou2fihp9b7K/HbRR1W@j25mKLdT15TrL2levZR/pDwpeuiZQyviqrILp8rx5@hTdkwt3IQVw/DNG2rtQmpZ9jz2gzS8lbL3A8TLb6RC7Yk9RHQuX5cnu4L/dGJQvA0R57x0jJba7K7bUF6DWeHO/d6FipmyniLlrw5g@lJ0WkItWP4HFPZpCI8OoYWviXTpDJLiEEedOoDq3e2EaZ9nzj9Irbcu8P8uEO@NGemdRrphReSm@I5W9liU3cKVAoVSIgfdZost60n6ynm/qFnuju/xkg6arM5b3CvWUOlkUsSCBmZc1e7cy9pvIAHGh2C75ylkxK30bp26jQsBswMOFbcDndWzT6aNg1X8kQyex9hu2GCEeQxhH51agZzVZ0cLbXZEkz8bmuCSCk9x8en2jwoPPzJpmvTNYe5ls6cXk8vMAoOpVlTcE@xTGE4EXI0B1QYskT4S3vAmdUEEiue7uTZsjAzMPGBnCruilJDFtFPVXeGPcG44syoB24I1hGGPeMH2VFxZscIc@SgKpCLezFn2kqHSpP8P/UJaV9ZFyc7QXIrHOIzk6JLp4iUzHgiZt1Ru/3pTmnbatP2X4UVrRWKELMUrVEv7jLY@RJW@I32yjRSNQXUfNSix0N4D91M7IHnvZX9lSq2SFjSHFIM0ob5@22IdL2yASSfcAIJmJv3yzWh79fzzt//vj//9etv "Retina – Try It Online") Basic RLE compression; pilcrows mean this is Windows-1252 rather than ASCII. [Answer] # 23. C#, 14991 bytes ``` using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace crashTest { class Program { static void Main(String[] args) { string e = "klbahihjnihihojklhlhijnihihjnbainikikjnihikjnobahihjnikiklhjklhohjnifahlhihjkbaihljninihojnohlhicahjklbahljnibahbaihjnieahihjnljnohcaihihijnbaihijnihlkijklnihjnikihbaijnihlhljnicahlhijnbaiklhinjklhojnlklhijnlnljkldahjnbaiklkojnbaihbaijnbainihbaijnohokohjklhlhijnohohokjnibahjklkjnihljnbaicahinjkdaihjnohokohjklkljklkjninihijnohjklcahjnihojklhjnlnihjklbahijklhihljnobahljkojnbaihijnidahikinjkohihjnikohjnobahihjniklhikjkokjnlnljkohljnohokohjnohokbaijnbainbaikjnikihbaijnicahljnoheaihijnlnjnifahlkijnihjnbaihljninihijnifahihlhjnikihihjklbahihjklnjnohlhihinjnlhijnihlkihjbahjnoheaihijnlnjnohcaihojnihihjnikihohjnbaicahikijkokihjnihlkljnbainiklhjnohlhcaihjklnljnohbaibahijnibahjninlnjnohodahjnohlkcaijnlhlhijnikikljnikinljnohohokjklhijnifahibahjkcaihijnikohjneaikjnihicahijklcahijninihojnicahihjnohikljnohohokjnoheaihijklhikjkcaijnbaihikinijnihikinjklkjnbaiklhikijkbaihijnbaikihihihijkldahjndaihonjndaihlhihijnbaicahinjnihihjncaikljnbaihijnifahihikjnohikjnieahihjklnjklnjkldahjnohlhohljnihikihjnikinjninlnjnbaicahinjnicahijnbaibahlhihjnbaikihihikjninikojninlnjnbainihbaijnihljnifahlhihjnbaidahlhjnikikljklhlkjklnikjnifahinijklbahljnohikljnlhijkokjkojnbaininljnikohjnohlhiklhjnihikikijklhihihjnbainihohjnobahljneaikjkbainjnifahikljkdaijnihikojnihbaikjnibahihjnbaihihjnikljnbainikihijnohbainljklhihjnihihijnbaicahinjklhbaijklhijklhinjnlhlkjnokihljnohcaikljnlkjnbaihieahjnohbainihjnbainiklhjklbahljnohcaihlhjkdaijnodahjnbaihihjkcaihijnbaihihjnbainihohjnohlkbaihjnikihlhijklnljnohlhihikijnbaidahlhjklkikjnbainiklhjnikihjnohjnoheaikjnihikikijnohocahijnikihikjkohihjnibahbaihjkldahjnikihlhijninlkjnbainikojnohlkcaijninijninihijnbaikihihihijnihijnlhokjnohgaijnikihbaijnlnjnifahihikjninbaikjkohijnbaibahlhihjkbaijkcaijniklhikjnokihihjklbahihjklnjnifahihlhjnicahihjnikinljklhihjnohlhihikijnlnihjklhihljnikijklnjklnjnbaihihjnifahihikjnidahikinjnikljnifahihojnohlhikojnihihihijnobahihjkcaihijninlnjkonijncaihjnifahikihjkdaijninijnlhlhijkdaihjnlhlkjnidahikinjnohfaihjnihikinjnikihjkohihjnifahihlhjnikohjkokijkokijklhojkbaikjnohcaikljnbainihihihjnieahihjnbaiklkojnohbainljklhlkjkohjnohohikihjnbainihohjnohbainljnlhokjnidahikinjkohjnohokohjklhohjnikihohjnikijnbaihikibahjklhinjkonijkbaikijnbainihohjklhbaijnohfaihjnlhjnbaikihihikjnokihljnoheaihijninikojnohokbaijkohojnohbainljnlhlhljnohgaijnohokbaijnbaiklhikijnihinijkonijkbaihijnocahijnikinjnohcaihikjnohlhohljklhljkbaikijnohlhiklhjncaikljnihlkijkbaihihjklhlhijkcaihijnohocahijnbaihljnibahlnjnifahikihjkohjnlklkjklbahjnokljninbaikjkohijnbaihihjnikbaijnohbaibahijnikikikjklnljnohlhdaijnohlkbaihjnodahjnbainikojnikihjnihlkihjnifahihojnlklkjnbaidahlhjklhlkjnohohikihjnbaidahlhjkbaihihjklhlhjnifahlhihjklhohjklkihijnbainihohjnbaihikinijnihlhljnlnjnohlhihinjnibahihjninikojnifahlhihjkojnohcaikihjklhikijnbaihieahjnihjnibahlnjnibahbaihjkbaihihjklklhjnihbaihijnifahihihijnijnbainikihijnifahikljnihlhljnikikikjnohlhihikijnihinijninlnjklnihjkbaikjkohijkbaihijnlhokjnlhlkjnihlhljnihbaikjnohcaihikjnohfaihjklhihljnihihihijklnijninbaikjkljnihldahihihjnbaininljnohlhdaijnifahinijnbaijnohbaicahjnbainihihihjkbaihljniklhikjnifahibahjnohikjnihiklhjnbainikihijnikihihjkohikjnbaiklklhjklkijkohjnlklhijkldahjniklhihijndaijnokljnohodahjncaikljnohfaihjnbaiklklhjnohohohijnbaininljklnikjnohohjnicahljnifahikljninohijklnihjnobahihjnokihihjklkihijnijniklhikjkohojnbaiklklhjklnljnohlhibahijkohojnihidahjnlhlhijnoheaihijnlkjnihikohjklkihjnlnljnibahihjnbaibahlhljnihiklhjnifahibahjnbaihidahijninlnjnibahbaihjninjniklhihjkbaikjnikihjnikiklhjnicahohjnlnljnicahljklnljnohlhohihjnljnikohjkokljnbaiklhinjnbaihikinijnihijncaihjklkijnbainihohjklhbaijnikihikjnohohcaijnicahlhijkbaijnohcaihojklbahijnohgaijkcaihijnljkdaijklhikijkokihjnifahihlhjnicahohjnbaibahlhljkohihijnohbaibahijklnjklnjnohcaikihjkldahjninbaikjklhohjnohocahijnbaihijnohlhcaihjnikbaijnohlhibahijnbaiklhikijnohlkbaihjninbaikjnohohokjnikihbaijnbaiklhinjkokijnibahihjkokihjnohokbaijklkikjnbainihohjnobahihjnifahihihijnbaiklhinjnobahljninjnihicahijninjnibahbaihjnbaiklhinjnbaidahojnihihihijniklkjnohohikljnbaidahojklnihjklbahljnohokohjklkihijklkljnihjniklhihijkokjnohlhikojnohlhdaijnohlhibahijnbainiklhjnbaijniklhihijnojnohohbaihjklhihijnihbaihijnohohokjninihojnbaidahojnikikikjnohokohjnljnohcaikljnlnljnojnodahjkdaihjnbainikikjnicahohjkonjninlkjnibahihjninihijnohohokjklhlkjkbaikjnodahjnicahljnbaikihihihijninohijnohohohijkdaijnlklkjklkljklnikjnbainihihljklhohjnbaininihjnifahibahjkohljnbaihikinijnikijklkihjnibahjnifahikljkeaijnbaihljnihbaihijnbainihihljnihikinjnohcaihojkokihjnihlkljnohohokjnikihlhijklkihijnohohcaijkohljbahjnbaiklhinjklnihjnohlhdaijnokihljnodahjnbaijnohohohijnlhijnohcaihihijnihlkijklhlhjninijnicahljkokihjkbaijnojnohfaihjniklhihijnihicahijnifahikihjnbaihikibahjnihihjnohcaihlhjkdaijninohijnohohjnohlhohihjninijneaikjncaikljklhihjklhihljnohlkcaijklhihijnikljnihlhljnbainikihijklhihihjnifahikljnbaiklhinjnohjkbaikjkbaijnohlhiklhjnihihjkbaihjkbaijklkihijklcahijnihbaikjnifahinijnihiklhjklkihjninjklhijkeaijnihikihjnibahihjklkijnohohbaihjnohlkbaihjklnijnbainihihljnikihohjnicahljklhihljniklkjniklkjnbaiklklhjkokijninihijnokihihjncaikljninbaikjkohojnihjninikojnbaikihihihijnbaibahlhihjnifahikihjnbaiklklhjklhbaijnifahinijkohihjklhohjnihlkijneaikjnohlhohljkcaijnlhokjklbahijkohijnbainihihihjkbaihihjnlnljnihojnbaidahojklnljnohcaikljnikinjninohijnifahikihjklnijnbaihihjnihlkljnikihihjnohohcaijninlnjnohodahjnihikjnohgaijnohikljniklhihjnikiklhjnoheaikjnohokbaijnikijnifahlnjnifahikihjnbaikihihihijnbainikojnohohbaihjniklhikjnohbaibahijnibahbaihjnobahihjnbainihihljnlklkjnohlhikojnohlhibahijkbaijnbaihihjnibahjkokijklnijnihlkljnbaiklklhjnlhjnifahikljnbainbaihijkljklnikjkohihijnbainikojklhohjnikjnihicahijnbaihikibahjnohbainljklkojnibahjnohcaihojnlhihjnocahijnohohjnihikohjklhinjkdaihjkohihjnihihihijnbaijnbaiklhikijkcaikjklhinjklcahijklnjklnjnikjnojnlkijkdaihjnbaiklhinjnbaihljnihojnikbaijnikihihjkbaikijnlkijklkihijnohohokjkonjninikojnlhjklkljklbahijnohlhcaihjnljnohikjkokljnbaicahinjnihljnbaiklhinjnikihbaijnikbaijkokihjnokihihjninjklcahjnieahihjnihljnifahihikjnbaibahlhihjnohlkbaihjnifahihlhjkbaikijnohlhdaijklhbaijnbaiklkojklnljklhojnohohohijnikihohjnihikjnicahijklkihijnikikljnifahlnjnihikikijnikinjklkihjbahjnohlhohljninihojnohohohijnojkohljnojnbaihidahijklhohjnohbaibahijnifahihlhjnohcaihikjnikikljklhijnicahijniklkjnifahlhihjnbaijnikihbaijnoheaikjnbaiklklhjnohohikljnihbaihijnohbainljnikihbaijnohlhibahijnokihljkdaihjnihlkihjnibahbaihjklnihjklbahihjklnjkbaikjnikihlhijbahjnbainikojnihikohjnokljklhinjnohcaihihijniklhihijklkikjnikihjkokihjnihlhljnihlkijnicahljnohgaijkbaihljnohbaibahijnbainihbaijklhljnihojnihikinjnikiklhjnicahijnohlhihikijnijnicahijnikikljkohljnbaikihihihijkokijnikinljndaijninihijnbaikihihihijnohikljnbaibahlhljninlnjnoheaikjnifahihojnifahihikjnokljncaihjnbaidahojnifahihikjnohlhihikijklnikjnikikljnohcaikljnijninbaikjnihikihjklhihijnlhokjnihldahihihjnikinljnihlkihjnikikikjnohbaicahjnohlhikojnikihikjkljnbaiklhinjnbaininljnohbaijnlkjnbainiklhjnifahinijnohlhohljnlnljkokljnihlkihjnohcaihikjnikijnbaicahikijnikihjkldahjklbahljnihikikijninbaikjnohjnohbainljnbaikihihikjnbaihijnohlhicahjnbaihidahijnohlhihikijnbaininljnihikinjnihikohjkeaijkeaijkdaihjklnjklnjnikjnlklhijnbaininihjnbaijklhihljnohocahijnbaiklhinjkdaihjnifahibahjklnihjnbaicahikijnohfaihjnbaihidahijkohojnikljkcaihijnifahlhihjnlkjnokljnohohikljniklhihijnbaidahlhjnihikohjnihikikijnlnihjnihinijnikokijnbainikihijnlhlkjnlkjninlkjnifahibahjkohihjnbainihohjnohlhibahijnifahikihjnlhijkbaikjkbaikijninlkjnihiklhjnljninbaikjnohcaihihijnibahjnlklkjklhbaijnlhokjklbahjklbahljnihihjnbaikihihihijklhlkjnifahibahjnbaihijninjkokihjnohlhicahjnohlkcaijkonijnljnihlkihjklnihjklcahjklhikjnbainihihihjnohlhcaihjnihicahijnbainikihijklkihjnobahihjnihlkijklkojnbaibahlhihjklkjnlkjnbaiklhinjklnijklhohjnifahlkijklhohjklhljnbaiklkojnbaiklkojnibahihjnbaiklhinjnihikihjklhlkjklhohjklkjkbaikijnlkjnihojnohcaihojnohlhihikijnokljklhlhijnohohbaihjninihijnbainihbaijninihojninlnjklhljnikihlhijnokihihjnohcaikljnicahijnikjnbaiklhikijnihikojnbaihijndaijnlnljkcaihijnohlhohljklhlhjnbaihikinijnihikinjnihiklhjklnihjnikinjklhikijnohlhohljnbaihikinijnihihihijndaijnlhjklhlhijklhohjnohbainihjnljklkljkokijnohlhihikijnohjklklhjkbaijnohocahijncaihjnohohohijklhinjklklhjnohcaihlhjnohlhihikijnbaikihihikjklnikjnifahikljklhlkjkokjnohocahijnlklhijnihiklhjklnihjklkjniklkjnohcaihikjkonjnifahihikjnifahihlhjninbaikjklcahjnbainikihijklkljnbaibahlhihjnikinjklbahihjklnjklbahihjklnjnohohikihjnohlhcaihjnohgaijnbaiklkojnibahlnjnbainikojnohcaihihijnibahlnjkohjnohcaikihjklnijnifahlkijnohbaijninikojnohohbaihjninihojklhikjnihjklbahijnbaiklhikijnihjnbainihihljkcaihjnlhijnohlhohljnohodahjkohojnlnljnihicahijnoheaihijklhihjnikihikjkbaihijninohijnohlhihinjnohfaihjnohcaikihjnikihihjnohfaihjnbaicahikijkbaikjnbaininihjklhihjnbaicahinjklhikjklhinjnbaiklklhjnoheaikjklnijnlhjnohohjnokljnbainikihijklhihljnohlhihinjneaikjkcaikjkljnifahlhihjnlklkjnokihihjnohlhohihjnihojkcaihjnihlhjnicahlhijklhljklhinjnobahljkbaihihjklhinjnidahjkljnbainihohjklkijnohikljkohojnbainiklhjnihjnbaihijkokjnikikljnbaiklkojncaihjnbaiklkojnihinijnohlhohljnohohjninikojnokljndaijnifahlhihjklhihihjnikljkojnlkjnihihihijnihlkljkonjnbainikikjnihojklkikjnobahljnlnihjninihijklkikjnoheaikjnifahikljnbaihieahjnbainihihljnohbaijklcahjnbainikikjniklkjnbaijnijnoheaihijnlhlkjnikljnihljnohlhikojnikljnbaidahlhjnicahlhijnbaiklhikijnbaihidahijnlkijnohokbaijnifahihikjnbaihikinijninlkjnohbaijnohohokjnifahinijnohokohjkohihjninlhijnikokijklbahijninohijklkljnifahihikjnlkijnlhlhijnihlhljkohlhjkohlhjklkjkcaijnbainihihihjnohfaihjnohikjnikihjklhojnidahikinjnicahlhijkbaihijnohjnbaiklhinjkbaikjkbaijklnijkohikjnbaihieahjnohcaihojnoheaihijklkojnihlkihjnifahibahjnihihihijnbainikihijnohohikljnlhihjnbaiklklhjkobahjnicahljnifahihihijnlnihjnohfaihjnibahjkohjnoheaikjnbaihikinijnohikjkbaihljklhihljnifahinijnibahlnjnikjnikihikjnoheaikjnihijnohcaihikjnlhokjkbaihijnohlhicahjnohlhihinjnohcaikljnifahihihijnohjkokihjnikljnibahjnlhlkjklnjklnjniklhikjnoheaihijnihihihijniklhihjnohlhcaihjnikiklhjkbaihijklhijnbaiklklhjnihikojklkikjkdaihjnihinijklkijnbaihidahijninohijnodahjnifahlnjnbaihljninihojnihinijnobahljkbaihljnifahlhihjnbaidahlhjkcaihjkokijnohokohjnikijnohocahijnihlkljnlklkjnohbaicahjnohcaihlhjnibahihjninlkjniklhihjnikihihjklhinjkohojnikijnidahjkbaihihjnihiklhjnihlhljklkikjnohohikihjkbainjnikljnijnbainihbaijklklhjnbaibahlhihjnbaicahikijnihikihjninihijnohikjnohokohjnlhijnohlhicahjkohihjnlhlhijnbaihihjnikihlhijnbaibahlhihjklhjnikjklhjklhlhijnicahlhijnifahinijnihldahihihjnifahikihjnbaihikibahjnobahljninihojnlnljniklhihijkohjklhojklbahljnohlkbaihjnbaininihjnljnbainikojnoheaikjnbaihidahijnikijnbaihihjnikjklhljncaihjkokljnikihlhijnbainikojnohcaihlhjnbaiklkojnobahljnbaicahikijnbainbaikjnihlkijnohikjklhbaijnihjklnikjnohohikljnifahlhihjnlhihjnihikojnbainihbaijklkjnibahihjnihlhljnbaihikinijklnijnidahjnikijnbaiklhinjnihldahihihjnidahikinjkdaihjnihlkihjnbaiklhikijnihojnlkjnbainihihljnlnihjkohljnidahjnikihbaijnohlkbaihjnibahjnikinjnihihijnifahikihjnihikinjklnihjninihijnocahijnlkijnbaibahlhihjnohgaijkbaikjnifahibahjnihldahihihjkohlhjnbaikihihihijklhikjnbaiklhikijnohokbaijnikihohjnlnljnoheaikjnihihihijkohojnihikojnihldahihihjnohokbaijnikjnlhlkjklhihijkohjnbaininihjnifahihlhjnbaininljkbaihljnbaiklhikijnbaiklkojnbaicahikijnidahikinjnikihbaijnohokbaijnbaihidahijnbaininljnbaiklhikijkobahjklhijnohocahijnlhlkjnlkijnbaiklkojnohikljnihikinjnbaibahlhihjkeaijnifahinijnohohjnohcaikljnbaihikibahjnihlkijkcaihijnikokijkohlhjnikihbaijnlhlhijnohohcaijnbainiklhjnihjklkjnbainikihijnohbaibahijnikbaijnicahlhijniklhihjklhihijnbainikihijnibahbaihjncaikljkokljnbainikojkohijnoheaihijnifahlhihjnlklkjnibahbaihjnohcaikljkbaijnbaibahlhihjnifahibahjnohbainljnicahohjnifahibahjnbaininljnohlhdaijnihojklhikjnlhokjnihbaikjnobahljnlhijneaikjnohlhihikijnihiklhjnokljnbaihidahijkohlhjnbainihbaijklkihijnohbainihjnbaikihihikjnbaicahinjklkjnikikljnohikjnifahihikjnohlhcaihjkbaihljnifahihlhjnihijklkihjklhihihjnohlhikojnobahihjninohijnifahihlhjnbaijnlnihjnohcaihikjnohfaihjnlnjkbaihljnohokohjncaikljnoheaikjkeaijnicahijnlhlkjnifahikihjnikihihjninlkjnifahikljklhikijnbaihikibahjklnikjnbaihidahijnohcaikljnohcaikljnlklkjnbaiklkojklhbaijnihlkijnbaikihihihijnbaidahlhjnohlhicahjncaikljnidahikinjkohihijkbainjnohlhibahijnihidahjklhlkjnbainiklhjnihlhjnohlhdaijnbainikikjkcaikjnlkijnohocahijnohohikljnihojkohikjnihikikijnojnohlhohljnbaihikinijnbaidahlhjkcaikjnohcaihikjnbaininljklnljnohohohijnbainihohjnifahibahjnicahlhijnihlhljnihlkihjnikihjnifahlkijnicahohjkokljnbainbaihijnibahbaihjnihikikijklhikijnijnbainihbaijklnljnihidahjnobahljnbaidahojnifahlhihjnlhijnohlhiklhjnohlhibahijnihjnohbaibahijncaihjklbahihjklnjkonijnihbaikjklnijklhinjnbaijnbaicahikijklhohjnbainiklhjnohlhdaijkbaihijnoheaihijnihihjklnikjnbaikihihihijkbaihihjnobahljkohojnbaihihjnbaiklhinjnihlkljninbaikjnieahihjnlhlhijnohbaijnohcaihikjklklhjncaihjniklhihijkeaijnihlkihjnicahihjkokljnihinijkdaijklbahjnohcaihihijnbaidahlhjklhjnibahbaihjklnihjnohlhihinjndaijnohcaihlhjninohijnlhihjnlkjndaijkokijnbainbaikjkbaihijkohihijnihjnidahjnihjkbaikijnikbaijnlklhijklhihljnocahijnohlhicahjninlnjnobahihjnohohbaihjklhinjnicahlhijninjninihijnbaihikinijklhihihjkcaikjnlhlhijnohokbaijnlnjninlhijnbaihidahijnbaibahlhljkbaikjniklhihijkldahjklhohjnohjklnjklnjnohcaihojnohokbaijnihikojnbaihihjklkijnbaicahikijklkijkohojnikihihjklcahijnifahinijncaihjkbaihijkbaihljninbaikjnikihbaijnohokbaijbahjklkihijnihiklhjklhljnikikikjnicahihjnobahljnbainbaihijnicahljkohjkohihijnibahlnjnokljkldahjnokljnicahihjnihihihijnbaihihjklhinjnifahihihijkcaihijklnijnihojnihijkldahjkcaihjklbahihjklnjnihihihijkcaihijnikikikjnikjnbaijnidahikinjnicahohjnbaibahlhihjnohlkbaihjnikbaijklhihijnifahikihjnbaidahlhjkbainjklcahjnbainikikjnifahlkijnihikjnljkojnbaihijnohbainljkokljnihbaihijnohlhdaijnbaihieahjnikinjncaihjkcaihijnikihlhijnlhokjklbahjnbaihidahijnbaiklhikijnlnljnikljnobahihjkcaikjkokihjnohbaicahjnlhlkjnlnljnohlkbaihjkcaihjndaihonjklhikijnihihojkonjnlklhijninlkjninlhijnikihbaijnihicahijnohohokjnikihjnbaidahojnlhlhljklnljnlklhijnihiklhjnohokbaijkdaijnikihjnohlhicahjnbainihbaijnohikjnlhijnihikinjklkijklhihijnbainihihljnbaiklhinjnihikojklhojnbainbaikjkbaikijnbaininihjninikojnohcaihikjnihjnlklkjnifahikljnidahjninihojnbainihbaijklnijkokihjninikojnifahlhihjninijnbainihihihjklbahijnohohjklklhjnohokbaijnikokijnljklkljnohgaijkonjnohbaijnlkijnikiklhjnoheaikjnlkjklnihjklhlhijnohlkcaijnikohjninohijnihiklhjndaihonjklbahihjklnikjnijnibahjnihijnohjnikljkohlhjnibahjninijnihljbahjnibahjnbaijkohlhjnbaijnbaijnijkljnihljnohjnlkmkjnlkikjinijkjh"; var o = ""; var v = new Dictionary<char, string>{{'a', "1*"},{'b', "14"},{'c', "15"},{'d', "16"},{'e', "17"},{'f', "18"},{'g', "19"},{'h', "1 "},{'i', "1\t"},{'j', "1¶"},{'k', "2 "},{'l', "2\t"},{'m', "2¶"},{'n', "3 "},{'o', "3\t"}}; foreach (var c in e) { var a = int.Parse(v[c][0].ToString()); o += string.Concat(Enumerable.Repeat(v[c][1], a)); } Console.Write(o); } }} ``` [TiO](https://tio.run/##dVvbjty4EX2fr2j4xePEMbK5B47zsgnykgCLrIE8OH5gqzVDDjnkpnvWycLwb@0H5Mccsa6n1M4C65HUkkgW63LqVGm5/Oxx9PH58/eX0u8P3/5weVofX9/g2auvR2vr8lRGv7z6y9rXc1l2d7xd//O0u/TX0v/1@uamp8f18l1a1sNyTpf8dr083Xy8OWz/LS1dLodvzuP@nB7pCl@f/12e0lNZDh9GOR3@lkq//fbpvL373ftDOt9fXth9/gQ/NW86rIc34fKz2o4pl/zQy/bveKgtt1z47KEft9eXWiqdb/8OvXe71vK8ecyzuzQf2s63@3PbLvT5qj7m1SXN@7bn5vXtz7xlO1r5RW3etaQ5WqHheOxWy/ZQl6HmM3SV3rEknuF2cRu/dJrF9qZKV9v2ytpOKcsNdfBr6RW0HD4cedSRbbnb6XaBZ7hdpAU3emAbbo5xomnbU7XJXb3w49vpXGkXGc6JFFn4XEqm1w0Sg05prmmb6LbA7f1D5Drl6VJuU@p1TozWNeglPAf6a6uaa0VZLYlvXXmc1mWXKgmSx282/fnTFC@/weY9/3bZximE3mx38sMUVByAN3Ko7sxXjWwynDs6KivaFJ/oVss8wHx0Dkez3n4iufF2bLPk148Tj9nqMhepmjp1kf7ww7SRrAy0LtrRReRNkluTaPTCm7PwWKy0dJGGodeqYuhKZUuWpOq6DcvmQts4dUIUcy5YtnleIRWnF9Aqpj6Nzn@baT8rmwhwSUXk5HtERkj/igXNHeL/VTiZtIQmxLvQVYIwAC@Z5dzU1HmOrNVTSe2p7iYI1j5/OSVVG7KIbWvIbqvMtxezfZHn3Jep0GIEnTZN1H6@lhSCJl/FbswPZbWNJls4xSuKTcOfkuwE6aCYhNgSSZFtytwaW@48aTwUSx63Yrs8V07qxN6m0yL7VGV1XrSuKmOsvA08Y9Byl8NCWy7THeqqaDOX5H4wLnsbVDxnJYUxWyER1QK7sSlhqWhfrAlD7bW6gKd6i/bXwr6GxaCOWtRKB53bZa8eYItsBP1K2/lKExO6TwWclDol1TnasDmBoJjk42QQNj6S/d5JgQtbLEb5voKcxDGzR2YtYxNyHfFJqX9mveEfNLJVcXWsRzIXdTRzdXVMqSzJ3jn3QbS0mwOT0MJq5QOOfJdKNs/Cm6jbA/56hp4hzpVDYWXNN9VkLZKlrWYOHBtB/xtJn10eqwzqH98mW4lxC2PpAL@vSjlv5KhKBjVlQjMs8H4xM1t02zkks7ZVxSvqxyFwG32EOTa@@14jvcZJ8ctTHHMaOhfaQLMDC2UsRXaoUz42b/dUImJBLGrGsrGiC2ZjGnSnandUiSmuVsl3clild@4MQpRa5OQhshJAc3fAbsX8hTkY8ekWgl2RhoyOLoSdHGqC/IJrROjXeB@ruoBu0d9jJG1LhBTqn3V69r6hGizWatq0MswCOZqzsrlJFImhkw6D89fIYdiSZYnegjVF7Jldh2@L6g4bhViwvCqDFYom3SX0PIYH@P38Vp7LKWHcCxurYbW7Hiy2wfyUoXBxl4aCFDmI7qIgxKPyDewcJJKYdjp2KVUQC6uawCT6SexB7djexDjKVIMcTi@iYoZXfT/6yJYBKBw2t191Kw0g5xFmbZGR0fcQUEozNMCvyFUkotrLUBtxA0Wi5nJzedL2n5I5fExwuspJ/bHhsapRathgtHyf99DcSN17g3RnBzslwNBWXTtUCesk5sUyA1Fdh@ySp4jLVMclkErB7Ki72CNLcBFReAruyWIr2DLrkCq8hBdwkQUyAnd4upvoxgEVdTU3yeOqp3waeGqxbZW1WPwAxJRDBuaew@UvEFSAuiYPuPlhr7blIlAo1T1r8xuq54sN80x2EewX3PLqqABC0OuDlLqZOZgsR00Fd4rRTOwiPU6FfPLmFzn1DMCXziTOCJYB2oB1pI6u2BEcPgwp8EM2kTWEfUJEk@QXzJkwlpLIWc2nqC9sql7scwraLufSaEq1qAOQrFPTijVB7M6e0skYhtDMmEKaixrJPrTawhfGLu3hmHIgNLpiVvGwjH40koM3FV9mDIpSJ2yg3agAnpPYEoBLVwFVZAUlCN0kId2lLrAZ6LZoVE4zWEWqAgTBcJwy2MgQfz0iWeZnIQHsz2KwuwZNGyX6PZhZY4KvKaGGUHHouutd0rxV00jVBXOvZjnueTh8ozYo/BWfrldJ950foIHZJYkh1JD1O/obYvoMkII5YP4eNk4DoQQBTcWHIzXRFNkoQ7lCrIxq1NVAbQeQJZEL/YQGMF2CUA8j6JUJLIORCP6AMBUoH41hgufl7Q2pSEttDe4zfLvbYe0rAVomoYFbk8zIQsm2OyrQ/W7iz8EXS@g7JlwoO51qgM9IMAFIbafsEgrNq2ls1SlbtgXGiybriR3harkmDJ0kxUtyAzYM5HSnZpsgrcBuLRLByXKWEO5JglM4BWIC4BdVnVIdpmTLr1qNfpL4om420IyBVdSiaEF4JodMRqgFD@I8qaSPFfBl1@V4tmy8V1F8bGYHEESBEWaJgp9cclXMhElr8@PmNbJGTZeAEpyqysrdKOPoZKxyf0q/y8uHMseIWA15uZobsvOkxYi9YqShuDJkAUGiaoYR@YuTN5ghiTo8ZcCFg50ojeWpzkf1HfMD6HrO8hiz3SzUoiyix2CpaIrhn@TiGryz5fVOpxM6Fv0FyTlFWpurthM3hvhLzC1BpiTmsQc8EiGY2lbi6IpjcyhpqYq4z9UDXh6BQ54PLMlT@/irzVHJ3Cppnbp2R9wlW4ruqTDmsDJ720rDkpq6OpkmHOQ@29EUmFnDSG1qLDfl50JJhRGDNmM9okNCYiUqsy7LKEBhkZOCVMVScM0GIy0rJLfqgzjaCTP4n1MCIp/kLcUsx61KQktysKRYATulCG6bPqQrhYRc7Z@RRW3OWZpJt@ppPUbbEjh/sS2TmNTrBFux6gLHwPQIF81ajVD8iuzO6JM4K5eQWs2/Fsvdm2TLPXAuXkCSDEEUyNANbnreV2lymKNVYbrnjrrvhmiJ7nXFU1@1CPlZIxULOS7Eb8O/FfGGwnpBgMaNq0RD6hDKsrUYNWcxsA44AKJDo6NZdKvO60FwftD4ImgCtF0crdVUNTsv0U1asY1pNcXNDYGwOxv1kXsKFwqpnAj2BqSr87b5S6U6R//d6mTAK@Sr/FC9LQ/lLC/E0c4YhMHJqNERDCUmNW0RK160sswprWxjbZhw7RyK@iAstXn9jbkBebt4krBYyEXMNzK@8sKHszxK1DjNCKREyEBYhBCaYxVZuWRXfEH0QRet5GgMsFtys4KDkUm9QGV7mHLtML2W5TlgGXAM6hR4A4GTqEmajbDjlOzHgrpXh7MHMnMaA4IC1HZsHZAAmZ/WovkxmeewylWsUBoKD6iLS6SNC02WptfrNLvh1PipxchoiAmtonFauj8lq35McY4YhoMubnzw2gEZIMfdwFpWgzNG6mqkNydchyMSU50lhbJW2aECyXFEMaqhKShfeH2YcoyKnF1mi@6xI2YochRGsHV3dvoLQjCr5q8p5pBDsCOaGNIFDz0w1lnsVxITwE8tBOhdp4xVUE7iGbA4FrIb83mMBLJzTjVALiYplfaRbgzOcSV8C49fQ/5EI1ufkRDHLeu/DforIFqqyThUpxQKSrRAbUtTDgRGZ4w4Rg5f7BpyY7dlViSolBkXVmK0dpzUcmRgxjHtyhsCkzsuSmFQSJ90E4a5EqCTjMLSGlhFrt@K/Ah@GfdcoVb0ShpwfZ7DM6LaDE5Jm4fi1ebD5hKp7j3Skb6xo3lL9Fkc0tlyLAHkHpKd7qpHPSlR23roaQIP4J7ny70r7Ls0WjO/vWuNYKpGiR5PWzQ4O6UthpkLtlJx9UF4dHV7ToCpe2N3qTy7YDDpcJGcC/NM5faxgcfyGiUvu@WHQN6H/RfrbeYpMjaZRLDJdFN17OMuBjhVyPy@yCVb@aR4HLWyhli110GUXfFUqAV8AOZy0lQa1yHoUje5xbUhymihLeKYoP@vxi67bGHKKdaMBc2yC52202O3h6A7xoCL3Qu00fabCNBBxtaJERmTAG0GpM3CWvaiNRAbwqgYJbSOyRvIconpmDW8dVS0xSNLJMmUOKnRk9o62PXvU7Ad5Edq14un4O5UiQa0gbmo4HHzYaZ2@xpRblB@V/cRA6klUmZ20C0EbabOA58SVsCRSh3aIYPQXRLmEtp1JO7zOGiea2gP0KoMNhFaMafVgi2RXORvqAWQwnkoVhxWnYPZlXuNzzW/AMWfXe@FkepSJQJoOqTs4CFlB0OBkZcVmpRjQSRQ4VaxDmn9vsHCMwXlsoRVEJCXQ9XE20QYdpuwlWQxPcpQkooNgkgpKahH0s0TMh11Sdjn4bmaMQeGZ70wYUFqRLJXevEiU2aNWB34To4f1uLBqcKanMYE0iRkNUD4CBF71RvWd27cNBc6LL14NsDxtlquqzoCgR3mKLQJDddFAywyTlnykrxjGu2FJzcIy5UMTXtJRQx1KNT0nssvEwwBkYTOIWiZaftOmp0@u@EBgW0toN4CrmX5WGzC/hVowa3lCn1I9nuCgB54ZAt8WJ8NUg5uQ1pYgDoY3Su2SmqJxwvZMRT4K26QA11ApaBnHmYUK2hzfh6hAddjLpRl/fsF9ZPQTlOqwrMlFNm1sCw7smgnSjOYy9UiKNVFda7tuhQC@P3kU2hu6M7onpIWFAzLKBAfmucaHPAylrj0Zj3Q5AygmLFAj762amGLSUe17MgGGtTJ1v5cMfZU7xPujk9PoXe9eQWoQYO90XK7FqQ8EAgAhwgtVKZb1WlyuQOaJKy3V4Vo@cfuYwwdTj4tKYGPw7ZD@/TADMrsUpo4sm@VJH5MuJ68a3RJV0Vb5FwstZP4r9XoodHjlCwnCv3V8TGfszEUIQ8f@f@WSesRuz8wRfAO0/4FMsQ/XyElwc9orNY9dnVGd9baN0oz5OX5SljhoDCwUzR1gpqshHbv6hUBTQ0FuXXMYIQjk@8@gMWmCNGdqdUSSS7h46fikWVYN6H53CbpY297yteb3E4KnXdFK/8kiq0vfM5SInbL@0p61l6EnVepoXwV6VwmYRXKWc@n9AWWvMuSuvce7pqEe@m75hTrCDC2HWE/OT/h5zUpGR1Ki@W6n0S@aMFPxfSbB@YKBE@JtG1/zXZouZZNKTGl9V7PsyR75gq2oVOAkEYFAvM35/fI8KM@kC99yM9e34RP/D6k82Ec3hyebT/sr3/Yrvf134c/FfqEMZ1/@MOS0/mlfC74x48fn6fnLw/PvvrJs08vPz4/0vGv6Hih41/T8YmOf0PHKx3/lo7v6Ph3dHxPx7@n40zHBzoudPzPJzp5oJP//kgndZ78gu9qdCx3PdKJ3NXnyS/5rkHH865POyHcjfOalny4nateDqUf1hfhhvi1pMonbfIp/enVN@l8WW8/vFvev/v5@1dvB39yefvixeurx8bhp29EfK@@Hpuvebr9c//@cT2nY1tf/X39bt2u0Ju@ev/ykPav@BTOthdcxvbYP87lab0d272fbj59@vz5fw) [Answer] # 26. Mathics, 52954 bytes ``` FromCharacterCode[{8992,182,9484,102,119,124,9619,269,8801,72,8730,333,107,967,8470,951,316,353,190,8218,326,9619,100,94,44,969,98,125,97,949,9618,182,113,88,83,959,8734,230,87,38,167,76,59,926,68,963,8318,922,87,178,56,936,316,8218,9474,123,9,105,36,8541,81,965,311,65,947,8730,8729,178,8219,53,8313,299,8541,87,921,189,424,53,90,46,104,8532,8776,188,948,8721,8317,58,936,9668,9553,945,56,248,86,966,257,8218,8541,46,333,922,109,8992,188,103,8252,8318,9632,963,68,40,97,86,188,8993,9484,960,8992,8594,67,198,353,49,954,42,9633,9472,8253,8729,71,77,72,99,107,9552,951,63,424,936,8252,119,9650,9580,924,90,178,8252,122,60,951,119,64,95,353,73,8595,291,927,8595,8219,950,50,946,8308,108,8317,47,109,89,110,955,9492,953,9675,73,115,9559,8734,88,91,176,9556,89,166,88,8312,97,9472,8804,923,8542,103,177,956,8531,935,9565,39,120,119,968,423,8317,9572,185,1472,8311,107,99,125,78,920,79,8993,9562,951,257,8593,8805,38,8218,97,9488,8710,79,51,311,124,9488,37,57,71,48,269,98,104,41,914,934,122,98,91,9484,100,919,8313,97,947,70,932,916,54,56,68,951,8596,198,122,110,60,9618,82,959,8776,188,919,424,964,915,84,9474,43,185,8304,8801,8310,8312,8540,42,955,933,968,8470,924,8594,8531,299,55,960,424,119,171,63,353,275,950,8596,965,316,125,63,56,93,8800,9572,353,9650,931,122,93,959,8260,363,8219,8312,172,957,106,9474,326,928,53,58,8253,8242,353,182,94,424,924,949,952,77,87,124,55,965,8308,188,291,38,35,9632,9668,188,8596,230,8800,423,46,1472,363,106,925,100,937,967,46,60,969,8312,62,167,9668,70,63,927,958,919,72,179,161,166,8309,8597,8721,92,67,46,923,8721,32,957,8597,105,945,9565,8494,257,36,120,925,66,41,8993,100,9472,9633,117,188,107,8800,8596,964,92,114,73,87,115,100,111,382,9,8541,269,115,48,8309,269,113,230,187,113,958,947,966,123,915,963,8310,937,78,56,103,9619,178,105,9619,958,959,960,178,59,171,964,190,960,963,326,8805,919,105,98,126,108,8540,164,8800,9618,8776,70,99,69,72,9472,9573,90,113,9632,8313,33,9565,189,36,94,927,8317,965,96,8540,82,172,935,73,9492,9675,32,934,95,114,9553,55,120,40,9650,8543,929,950,269,8595,76,353,927,955,9492,70,8252,925,99,8800,9553,96,969,74,8595,915,52,83,101,923,62,97,88,80,926,9660,41,8253,937,86,918,72,44,8800,8710,9565,8729,111,8309,176,9556,932,8219,961,39,929,167,178,58,957,9618,423,8308,9572,8539,66,66,343,8304,275,102,112,9632,54,8304,61,44,39,9660,363,8776,8540,8219,106,8801,967,918,8309,107,9619,8252,914,39,9552,89,42,166,9580,167,922,9573,54,9617,918,953,8253,953,932,950,275,59,8710,8540,9553,108,64,8592,951,119,8541,9488,41,929,935,167,49,949,166,185,955,171,8710,9658,41,102,79,291,8539,8304,67,9617,123,167,382,964,921,83,74,120,65,78,969,82,103,326,9572,47,8992,48,9472,9618,118,43,8532,914,8721,968,108,9565,120,32,112,8597,935,8592,8311,959,8595,114,8540,80,9619,84,118,188,8543,190,8311,111,967,8218,8804,424,257,931,8992,969,120,8992,8993,90,968,8592,8317,9580,275,36,9496,932,39,90,353,123,64,104,39,46,94,9562,9572,45,8240,8597,925,9660,269,41,32,167,917,47,9608,269,38,964,113,945,950,953,117,50,299,124,1472,83,9562,37,8531,63,9658,8218,914,8539,8240,9562,269,177,956,8542,9532,9573,9660,177,948,8804,8470,73,928,56,9619,177,937,55,179,929,84,9553,97,116,8218,122,967,64,8540,74,8541,46,61,961,38,95,291,8539,929,311,969,230,424,112,968,115,248,8240,75,187,965,89,42,82,40,9562,8218,424,82,97,8721,122,8317,326,107,166,83,8540,9658,115,9,171,937,112,52,953,70,82,198,59,44,53,311,57,63,119,311,9,9660,114,8801,60,92,8721,77,311,52,230,9580,8593,257,248,925,952,299,89,8993,299,9556,9580,8531,9552,915,39,952,123,161,52,925,88,66,9565,8311,42,189,167,35,311,118,917,95,931,952,8532,124,46,9608,925,105,954,950,966,8805,8730,8801,424,71,424,9608,8494,117,8730,73,51,275,257,945,54,118,8992,926,8317,58,8218,166,932,926,119,49,947,230,936,8242,179,8992,924,927,8494,189,937,935,89,190,67,954,8730,8311,928,961,85,333,8710,8240,32,8597,8993,957,8993,8318,9650,9608,8597,9496,47,9658,71,917,189,101,8594,964,8597,8531,8240,111,185,8594,83,61,53,257,8531,80,922,914,949,106,125,969,961,59,363,953,71,114,8311,182,269,9552,299,958,929,77,8710,9556,9496,960,53,188,8309,919,311,8540,326,8594,108,9484,104,946,923,38,114,94,934,423,8539,106,8597,60,90,66,316,167,925,96,914,960,382,9668,923,9474,9474,49,44,45,925,68,59,8801,9532,9650,52,8253,63,176,74,113,102,275,959,124,966,8242,8597,8543,8776,110,8532,969,8494,54,914,54,56,8253,90,929,187,64,101,961,299,963,105,54,94,69,925,8219,952,363,8470,247,52,107,176,969,67,247,257,188,8805,9668,9618,8242,9572,958,85,95,952,333,178,179,189,918,8310,50,188,1472,924,171,67,9496,8304,56,931,9532,961,934,8747,172,112,299,103,8776,8252,917,187,65,121,343,84,964,8310,115,74,102,423,85,65,9617,9553,123,960,920,8595,85,124,952,8318,935,8310,8593,311,74,915,937,92,85,9484,920,269,8253,42,63,9492,949,9658,9484,8494,33,124,189,927,269,248,101,918,124,107,8309,9562,53,925,934,921,8253,8992,945,90,38,110,965,82,951,960,124,9632,915,117,33,107,58,82,36,257,933,9633,112,9650,932,9553,935,343,9633,9559,52,299,363,247,89,198,122,8311,967,87,9658,9619,103,59,353,77,9559,9488,929,84,102,112,60,92,9556,171,107,9617,43,925,114,9632,90,423,927,965,9660,60,247,102,113,9484,9675,247,9496,960,120,88,931,933,937,8729,187,38,179,55,62,248,8218,114,963,8596,9572,60,44,247,933,424,8470,178,423,9484,8710,122,8240,9572,95,9532,333,47,178,8219,185,257,47,8596,917,8260,67,53,8592,166,8311,44,918,960,74,8304,8240,8800,333,188,969,914,9573,111,75,93,9633,118,177,958,952,85,8992,50,9617,69,963,98,35,8721,75,46,9559,110,914,8470,57,9650,933,960,917,92,46,123,105,93,919,9660,8804,126,76,9,927,107,956,247,8542,963,936,187,9580,82,37,8309,82,74,8312,8539,949,8992,956,95,101,8531,93,923,8310,8543,9650,920,9496,8543,920,961,9633,8531,965,92,8539,110,111,8312,75,925,9488,230,8312,967,917,8541,8541,8312,105,951,8592,8539,8540,343,918,42,936,107,9617,77,93,8308,102,57,9668,111,931,269,967,8539,8801,958,257,76,40,121,956,56,927,8729,98,105,961,925,39,957,171,963,68,61,108,107,958,55,955,9559,123,110,32,9573,33,9668,61,71,8804,316,109,9580,921,311,122,9660,83,257,967,967,105,9559,42,8595,33,108,188,343,424,87,58,123,1472,122,117,247,247,932,72,275,113,97,86,121,247,8531,84,82,50,9492,922,75,9565,103,9632,9488,81,126,8542,87,110,89,8542,8596,55,178,58,954,8993,33,75,118,9496,122,106,931,957,9488,40,8219,9488,35,77,113,363,78,8593,189,926,937,94,182,933,185,76,54,8308,8310,8801,9573,917,58,8318,58,9580,9559,102,953,9562,83,946,164,49,269,179,121,968,198,311,108,966,9668,105,51,43,8597,9474,9472,64,9472,51,8801,86,8747,50,9532,98,9496,9650,185,182,177,67,8312,81,113,9484,950,937,37,333,9562,56,76,8242,51,8710,257,89,946,171,966,75,121,936,98,9556,917,108,43,382,166,97,9565,8729,8304,87,8710,94,65,73,44,8494,56,8310,71,105,8470,80,9496,945,82,9532,8594,161,91,119,84,917,9633,79,39,968,72,8594,8801,333,97,189,118,968,84,9660,124,40,74,269,113,161,9484,248,8311,101,8532,8313,43,9559,44,77,9553,109,333,74,8470,9492,93,929,248,36,382,9565,8710,167,59,172,106,8800,934,921,8592,41,8494,928,918,49,44,8318,9484,961,126,66,114,935,85,916,925,70,9660,164,124,182,70,8710,8304,122,8595,8531,46,190,931,117,968,46,934,8541,8253,8734,9492,929,114,119,925,9562,965,8494,8734,937,56,8310,79,8801,951,8532,291,9552,316,1472,87,114,947,51,190,8539,99,8596,100,8218,95,37,9572,9580,93,53,44,8318,8304,123,953,161,52,39,123,161,948,8218,961,8540,96,9618,92,927,8317,110,8992,111,957,66,171,921,935,353,8539,8730,185,8539,275,8252,8730,53,9484,87,9608,123,8531,9573,102,9565,949,70,72,39,112,230,114,80,299,8539,343,423,9580,90,948,1472,125,53,54,61,934,8240,952,51,937,9472,41,248,269,90,9472,958,8470,35,185,90,8801,275,58,8242,257,54,82,948,9,32,8721,121,63,8309,72,423,188,8317,924,916,257,934,8592,957,9608,257,8311,8540,70,9492,8730,161,103,59,918,60,61,104,953,956,114,966,102,291,9553,178,951,8540,8532,9675,920,116,8804,109,178,96,257,316,423,70,916,8309,8592,58,933,932,316,179,927,79,8734,51,55,101,299,945,54,9553,8531,8311,8494,316,919,965,124,8596,106,48,59,8531,100,8592,116,8592,965,967,424,107,291,248,9472,9650,40,106,950,8541,198,921,955,116,9633,90,922,8311,8308,161,8721,8539,79,8801,75,9556,248,9619,188,935,8218,59,8596,922,9552,8309,929,954,172,185,84,82,41,116,95,41,8993,43,914,8218,959,52,35,58,53,47,72,923,311,123,9617,965,59,166,8776,9552,9580,38,954,299,107,382,965,968,248,111,90,116,177,965,316,269,965,918,299,71,43,936,60,78,8805,956,8541,9484,950,35,968,8219,85,1472,71,9668,114,73,8710,97,33,8311,275,75,8730,953,87,36,920,924,8304,960,115,326,9496,36,98,9565,353,8805,8313,8313,316,95,54,8311,56,927,9658,9488,311,9556,8596,965,8734,55,957,97,171,69,108,8801,927,106,922,118,8218,8532,106,8800,178,382,8734,9633,96,917,87,382,924,918,920,963,118,8804,8252,66,50,116,8805,64,343,9572,257,8218,74,9474,176,87,112,9565,87,275,8597,161,8470,95,8592,59,917,8721,9552,9650,257,8470,66,424,70,179,343,936,9556,115,42,8805,61,71,423,8312,923,922,171,9608,957,257,961,116,9472,947,9618,46,9632,58,8540,8595,291,43,9488,928,248,8596,8594,119,114,964,950,929,85,55,382,89,382,44,117,921,8800,937,73,917,47,8729,269,9608,61,85,8594,8804,95,8710,48,35,109,178,40,919,114,961,125,9488,90,92,8318,8317,198,954,8730,58,8993,178,63,8710,8800,101,922,77,32,248,66,62,8540,927,41,82,52,9617,920,185,161,69,112,95,72,916,41,9562,311,41,363,936,68,46,8317,8710,93,343,115,8252,8800,8309,71,117,8312,8992,123,934,9633,936,100,9,921,113,113,84,927,46,9474,123,171,54,75,109,8543,115,99,9617,95,424,8218,50,76,8242,188,257,198,8470,8543,8532,9660,9632,9608,8734,164,117,59,47,164,963,40,9668,171,8252,8304,9553,423,8253,44,956,63,112,161,9492,947,9660,55,69,8318,958,424,914,956,8595,166,8311,8596,57,187,92,57,945,343,8240,956,118,326,931,956,59,57,105,8219,177,8597,95,8597,81,120,959,8993,100,84,9552,311,176,118,8311,964,9565,50,51,93,950,65,9573,124,76,164,118,61,44,161,8532,964,8805,8242,65,32,9565,958,8801,41,8309,36,8800,92,1472,919,66,8730,924,83,8532,921,969,80,114,9559,9668,8729,70,8594,9562,291,269,72,9618,951,935,9658,916,75,76,9,112,54,100,42,91,8310,177,8260,182,124,8309,108,91,43,9484,915,41,937,69,423,167,316,959,42,965,122,947,58,44,9562,54,959,64,179,58,118,164,99,967,969,90,54,50,8596,8542,953,103,9559,9552,964,52,8993,92,326,179,333,102,9484,933,102,81,93,172,113,52,83,947,33,8594,120,104,35,96,8470,105,9496,8993,9675,117,104,188,88,120,66,8710,8804,86,8542,8543,8253,9633,8242,9572,40,952,8710,8710,922,946,187,171,9632,8310,60,178,1472,161,53,935,948,98,963,123,922,9562,9496,95,91,1472,117,58,8540,66,107,118,8543,946,8734,106,9492,81,32,363,97,61,53,97,92,959,72,9565,101,121,66,923,932,950,8800,925,78,950,178,947,167,9552,42,8252,60,423,928,311,8531,33,8470,8253,113,61,109,9532,89,124,363,958,72,108,164,957,61,40,8543,86,167,921,43,9668,73,80,118,36,9552,63,104,104,109,9650,92,8260,56,9650,39,8992,8593,48,8801,66,958,188,8311,190,960,101,958,119,952,9492,98,63,8805,167,104,114,919,311,86,291,120,8993,8595,8540,9474,922,960,8242,63,920,86,101,8253,94,8219,111,291,8310,109,917,275,920,958,353,67,247,8596,69,929,39,961,9617,9559,915,37,925,8801,965,945,928,121,954,8593,66,8310,923,107,88,918,123,9650,953,112,8312,946,38,9484,79,68,111,74,32,9573,182,316,198,333,126,198,8992,122,85,915,100,91,116,101,363,96,9,937,79,60,915,952,936,8805,966,925,101,333,8730,8304,69,8312,47,104,299,8219,91,9488,917,915,125,8710,114,48,32,918,8593,1472,97,8494,126,56,37,9608,92,363,9580,8311,8531,171,8218,86,963,8804,8309,920,936,8992,187,44,9573,311,167,248,58,8470,177,9488,8594,35,8218,353,32,122,176,105,9608,38,299,947,9573,78,178,87,124,291,179,123,85,9675,8776,8805,8801,83,921,948,45,72,9668,333,88,8729,275,9496,95,926,178,36,8993,8218,963,8597,8730,110,121,9675,8593,8219,935,182,187,923,119,936,112,9532,8308,957,65,424,40,914,104,164,956,101,32,9565,353,8252,167,51,966,72,9668,117,65,8800,35,76,9492,914,257,166,89,343,110,62,79,8318,914,949,8593,8242,247,161,8539,115,926,91,951,36,86,83,190,32,8596,8253,90,114,947,275,932,946,90,924,8539,922,9618,958,8313,79,176,946,62,948,8596,959,120,56,9632,924,164,179,9572,953,39,103,9617,120,107,109,945,108,961,8317,9532,918,8710,1472,8595,33,119,947,189,9572,9474,190,93,8747,353,187,78,111,38,9632,78,112,38,122,326,47,8800,109,9650,75,70,9573,41,161,115,946,9472,89,85,39,955,103,45,122,8313,9556,124,8710,9496,382,929,915,123,248,311,83,933,98,73,950,84,316,382,66,45,51,934,8594,8539,96,968,54,58,9619,8543,39,77,35,55,423,44,106,9675,80,8729,32,64,299,8470,36,915,164,8734,69,64,178,62,187,8597,188,164,8310,49,172,109,966,248,969,963,102,951,316,423,8252,9573,929,72,8242,114,959,299,115,947,80,8596,8242,94,63,108,53,9572,8311,45,78,190,957,8540,925,916,957,70,8805,9660,9658,382,187,33,62,269,187,8311,949,48,84,9580,90,97,74,8710,343,316,8993,9608,104,120,1472,9675,86,917,9562,176,915,965,8252,8993,80,95,9650,32,9552,70,198,105,969,917,190,291,269,47,8539,326,9492,291,931,926,8470,187,45,9660,936,9619,946,934,164,8721,8539,9660,923,948,9580,8242,299,164,111,108,164,9552,64,926,964,8240,70,61,8312,69,8992,9668,9573,947,188,90,62,957,38,45,82,176,8308,917,923,177,119,954,126,57,8596,936,914,126,918,936,8805,9658,92,8729,9619,8218,185,9472,41,257,60,926,66,9619,9572,952,9619,931,926,111,8730,88,8596,171,66,64,66,9484,177,945,8805,125,64,8304,166,189,311,104,104,188,958,230,124,927,78,164,50,126,9675,123,9496,94,8593,116,8253,918,177,101,111,353,8593,121,39,65,923,179,8592,111,8310,123,8310,55,72,198,8992,72,177,8218,424,109,965,8218,63,954,955,8595,100,423,966,123,74,8747,9484,8541,166,952,66,108,917,954,9617,8532,125,96,920,967,74,9496,85,65,8776,954,9492,55,119,353,122,8311,106,83,60,73,32,932,9565,171,40,96,8805,189,921,37,105,8313,8532,33,9675,74,921,52,32,45,119,291,89,111,55,111,46,52,113,311,923,93,917,957,964,90,188,275,964,8310,947,915,926,87,956,83,42,949,92,8721,8312,82,71,937,1472,922,8540,920,8242,122,9633,106,8311,8721,8252,316,916,9484,67,92,954,8252,35,44,43,8805,966,94,947,230,923,914,9650,8801,178,74,116,8734,8993,9650,49,9632,112,8242,9484,960,932,959,9488,957,326,921,959,8800,59,915,190,921,78,8992,8594,78,172,166,8594,9553,8531,922,8312,189,8310,124,178,963,116,103,8310,63,8317,102,57,42,8304,64,72,382,189,933,964,110,182,164,316,60,80,968,8542,113,8308,8304,122,71,95,8800,68,103,9562,9472,964,8539,230,923,9496,947,74,49,923,86,74,36,82,957,64,8540,926,33,32,914,88,1472,933,59,921,167,121,9562,8747,964,9619,946,964,248,949,8308,51,957,182,81,8721,123,99,8593,934,9633,89,8470,8240,117,33,177,63,937,79,951,125,166,959,77,123,9650,78,8805,106,8734,81,954,58,63,968,382,275,102,116,8734,9565,9472,423,8317,95,39,8721,945,120,353,101,951,44,115,8260,8311,47,957,916,937,9559,8805,107,920,9668,89,316,8541,110,423,8218,382,84,291,949,116,185,118,9572,90,43,171,935,965,954,9565,8540,8242,126,8721,126,963,47,8310,968,935,89,102,951,115,955,9617,8253,8494,106,9552,424,99,46,963,61,950,8313,112,424,108,161,299,8540,59,55,55,8710,47,8730,52,9618,958,9572,914,8317,74,936,8304,109,77,42,177,8219,44,113,925,8540,55,8541,47,99,8313,8304,316,84,961,936,929,8313,353,40,42,926,9559,44,927,9496,8729,68,190,968,917,959,8308,966,8805,111,97,8540,8309,94,9559,8543,64,79,99,8252,73,123,116,185,8747,107,363,9552,8595,161,44,931,121,8597,924,177,91,66,9675,100,8747,1472,8470,8592,8309,85,968,124,964,9565,8595,38,9532,951,9660,968,44,8470,8595,8470,916,75,70,8593,45,83,53,924,932,177,8260,949,8252,80,382,59,97,959,8309,74,9668,920,8595,8539,9488,95,90,111,188,86,43,9573,115,8540,353,9632,958,916,123,59,924,124,67,67,8729,923,920,311,968,50,53,87,42,8594,66,112,8309,8309,316,96,925,44,8729,46,56,61,97,9553,8240,76,161,115,9552,935,111,968,957,67,66,117,67,955,275,100,54,9650,952,955,9650,102,917,179,929,9556,8734,8596,316,920,954,927,9619,9675,123,8710,35,966,125,84,8539,966,71,923,42,114,8776,99,933,93,924,81,8729,77,8593,9552,32,946,57,32,966,8542,945,8747,106,81,9532,953,58,92,961,188,122,176,9553,35,928,914,40,8596,363,951,91,172,8592,44,8747,41,102,44,164,955,74,67,108,8710,9,9532,964,86,960,89,8597,8992,84,934,8253,179,190,333,122,9660,60,118,161,116,9668,8532,9633,291,952,9617,960,316,248,8776,81,959,311,8539,937,9484,929,187,114,916,102,49,8240,936,179,46,166,920,69,79,8592,94,8801,8595,70,86,923,73,61,291,112,954,49,9580,8541,8540,948,76,343,58,8308,8318,111,107,50,9617,95,44,923,80,89,118,52,275,929,922,121,42,9632,79,8304,48,48,8308,311,964,9619,66,965,8260,275,966,918,9496,121,8240,109,77,121,951,948,8532,326,8313,42,57,107,103,333,927,105,125,111,9572,80,114,8240,8542,915,80,118,8219,176,8312,9496,9675,179,69,9484,8596,921,89,114,269,934,8317,927,8318,914,956,8218,959,248,9474,46,423,68,109,69,66,923,8313,171,950,9618,953,965,172,9617,46,55,49,9608,9650,45,40,8242,62,76,70,121,9492,961,8776,188,917,45,63,8308,52,89,948,164,35,97,9474,86,106,963,119,935,123,9532,8596,9484,171,8308,925,8304,96,41,916,117,9559,164,8543,961,8801,75,114,125,81,9619,8253,98,41,9608,8539,8801,187,68,101,230,81,50,45,8540,68,161,8800,960,9650,172,9660,99,933,9484,172,291,121,187,188,299,919,919,921,59,113,112,8730,363,8311,171,50,9556,9488,122,185,70,928,247,926,47,121,915,8800,66,935,9553,8304,8992,9658,967,39,9633,67,103,964,117,8252,8595,8310,952,112,58,90,33,185,945,275,122,945,100,51,955,311,86,36,920,9552,8543,124,62,247,117,8800,60,958,952,933,104,424,8800,48,37,8801,44,8308,8710,49,177,964,53,87,126,9,954,177,73,9492,9565,8805,9559,84,188,83,291,927,949,8594,915,115,53,107,954,382,343,948,8219,926,934,8747,161,167,8312,62,80,8253,937,55,8219,8800,47,247,8734,79,86,104,72,108,51,93,166,326,8318,87,8318,171,187,965,316,925,46,113,950,9556,121,35,965,8253,969,343,964,35,45,161,101,937,917,927,71,67,118,123,9572,917,9650,9488,1472,9553,8260,925,9496,9617,958,963,8532,8542,49,57,964,112,966,8539,164,126,926,81,8801,74,936,8593,8730,86,102,926,959,8801,961,37,93,963,9608,40,55,363,316,269,171,39,8304,9580,423,248,83,954,382,123,9668,124,46,935,951,167,8260,110,49,114,57,100,948,66,9675,54,8801,915,73,9573,8776,916,8531,45,8710,188,353,37,923,8531,100,9675,63,113,959,68,56,88,8804,247,958,8592,956,37,9633,311,9675,949,8308,8312,166,93,928,8311,198,91,39,8219,248,9660,8252,959,8592,125,8308,48,8596,185,39,914,968,96,99,916,55,93,9488,8594,931,353,9552,299,87,230,8593,76,69,947,66,9632,9632,33,99,125,9488,36,58,73,90,100,921,177,8470,935,69,102,935,927,9650,8800,8260,9562,326,48,96,8730,937,343,167,8776,926,79,924,84,45,343,914,171,9559,924,42,198,8801,9633,326,74,8494,8594,917,8541,78,126,106,9660,8596,959,79,8313,316,9580,105,8721,36,46,9496,115,54,78,919,45,230,9633,9633,74,85,9562,8801,44,963,182,964,88,1472,9632,963,9633,171,965,32,8304,8729,48,230,949,9572,116,9496,189,74,9553,959,83,311,919,9562,9572,8532,61,53,100,118,71,9556,9608,9619,424,9,65,8532,79,189,89,8542,176,8240,126,44,123,920,84,423,926,84,91,953,97,8308,8541,953,106,53,164,8594,914,9668,43,8801,257,9668,343,8470,926,46,177,36,84,922,8597,928,8992,198,936,8543,922,179,69,8311,90,965,66,8311,98,9472,915,40,8539,8313,118,247,949,88,8260,39,125,113,110,8470,110,94,919,8470,9618,915,9608,82,917,66,951,8541,107,44,9532,919,171,8800,116,920,275,946,188,915,8304,954,8318,83,916,958,75,57,68,164,8312,110,954,91,123,230,926,932,9573,103,8311,167,9660,8734,94,109,37,8313,8593,117,959,87,9633,958,108,8729,84,36,922,122,926,9562,190,248,8240,61,120,75,269,60,61,923,69,948,923,88,60,177,106,122,41,952,8308,8543,41,8253,106,343,932,423,424,73,9553,8734,8804,99,33,966,198,59,58,8310,85,8304,73,43,97,9619,967,9492,84,923,8310,9559,60,9668,8311,424,35,947,100,934,951,62,187,230,51,916,8242,8309,125,934,166,8310,67,926,8801,82,8304,8734,190,105,291,116,9633,188,80,121,969,9660,9618,97,182,8592,9562,9556,9484,8729,109,8804,75,67,423,111,8721,60,8540,187,35,8218,952,35,65,953,39,9553,9556,8253,9496,969,8310,925,382,8593,189,9668,65,108,8311,927,108,9632,916,9573,916,8721,73,48,107,117,8219,73,76,967,190,8531,44,9474,52,8470,959,9633,38,934,118,79,161,959,8801,333,62,179,44,8531,78,69,269,932,9632,9484,107,8313,35,36,56,964,63,100,119,65,97,114,75,914,32,53,64,269,52,161,81,103,928,74,8470,9650,926,120,9633,8219,125,92,8252,179,171,9556,8993,49,82,423,92,60,76,63,61,8309,64,958,257,44,924,9573,8593,8309,60,109,920,179,164,915,8800,9472,936,275,964,102,98,54,126,956,9492,922,92,8311,933,32,61,76,176,945,945,81,106,363,56,967,171,67,88,51,9474,921,333,955,188,104,73,56,103,72,952,62,926,9660,230,8219,954,9562,8304,915,918,947,959,190,66,125,955,189,9632,57,9472,83,72,113,8595,964,969,97,32,382,8805,926,8309,8260,8993,948,9580,8219,172,117,8308,247,41,118,8597,187,1472,89,960,166,79,9572,94,51,122,931,8747,8304,64,198,126,110,9632,113,917,74,166,8596,8593,8313,77,124,189,8776,32,958,98,961,172,82,95,84,118,935,66,423,927,8313,56,299,8776,76,8801,84,60,114,8734,40,112,51,918,8804,124,33,98,44,89,964,190,103,8470,44,46,171,70,343,8805,171,59,963,247,75,8734,44,49,63,9474,9556,167,9632,8540,90,949,948,101,72,109,91,57,43,933,8597,189,921,8494,188,9532,40,120,8729,9492,8710,93,109,86,189,8541,9474,98,52,110,8730,72,8593,9658,968,914,8308,9553,104,62,119,182,382,8776,56,954,424,921,9573,112,929,8541,52,919,126,275,8730,55,9617,45,9619,927,920,247,64,42,41,89,50,9562,125,8992,8730,188,8312,95,9552,89,967,80,275,76,75,925,115,91,8596,190,8308,8252,126,9650,101,248,1472,8260,79,917,59,924,104,967,955,90,190,68,117,931,343,8252,8304,67,316,50,8805,32,9474,923,967,9559,8304,963,9472,936,8710,9556,110,8710,8260,957,84,105,178,931,116,946,935,108,8311,8494,8312,40,931,118,958,176,8804,8593,119,8596,9552,43,188,955,230,960,916,47,952,968,45,920,8710,88,81,963,257,92,83,172,8219,8470,111,9619,120,927,9660,353,102,113,77,9675,120,177,8721,107,108,167,9,123,955,9556,965,9675,80,185,56,424,920,382,85,185,75,90,960,1472,269,44,188,326,114,8242,333,9484,933,97,46,920,37,8242,291,95,951,1472,917,43,8542,9573,8312,8594,79,109,9488,928,931,8729,9633,8252,918,44,81,8541,949,86,932,91,953,96,269,76,316,8734,66,182,36,164,291,935,929,101,956,950,9573,8597,8805,88,82,82,187,257,116,110,77,247,9562,77,924,8252,952,109,79,49,424,9668,927,9633,166,101,166,9488,8219,961,9660,176,921,115,75,8721,45,116,8260,113,257,103,46,113,59,8317,951,8993,353,934,84,167,8593,915,8317,85,299,88,51,9496,53,917,68,91,39,38,102,172,961,39,70,44,969,9562,9668,59,86,94,291,353,57,923,118,934,959,967,916,363,101,269,969,46,63,247,8776,189,935,9492,8532,919,927,316,176,424,8594,189,112,8308,51,124,8592,230,84,959,934,931,248,9492,83,58,46,966,9488,58,9,353,382,176,8804,969,119,113,189,122,958,8734,269,969,40,8721,35,969,8540,8542,185,46,117,965,9,40,954,957,8710,85,931,65,8800,8710,86,89,99,41,187,921,8260,9572,8494,8801,8543,343,68,83,964,50,63,8721,8541,9675,8801,8539,920,958,67,8597,65,8734,423,9553,35,171,424,935,50,92,107,8317,1472,61,39,925,363,954,8541,8992,61,109,8540,66,917,9472,94,178,38,291,121,921,9580,68,927,111,177,198,9618,38,1472,1472,9632,32,119,86,124,8596,8540,8800,187,9658,963,947,39,167,932,188,928,80,959,8992,56,93,43,50,65,954,106,73,960,62,933,8304,74,97,343,8804,113,954,95,75,968,172,89,90,54,66,257,32,63,71,92,64,958,8539,109,921,125,103,57,8594,177,9618,42,110,52,55,182,9658,920,963,8800,81,83,926,120,185,949,78,8542,185,8992,8219,918,9675,960,8595,929,51,99,9573,8734,8593,8730,120,8318,382,316,936,80,9562,108,40,248,933,957,125,9608,924,117,8595,921,960,257,39,915,8219,9562,925,9618,8593,37,48,75,947,42,969,945,966,100,83,953,8242,114,69,8734,47,8317,125,40,33,166,62,946,84,8312,79,198,198,93,947,957,51,936,56,8801,8729,117,198,927,108,112,8597,275,291,94,8729,60,109,108,343,8729,951,120,117,76,52,79,954,9484,311,91,8311,105,53,65,956,8218,946,76,97,9492,311,50,94,81,50,60,8532,951,9496,56,125,9633,9660,9650,953,81,125,929,69,922,112,311,920,965,950,922,9472,55,8539,179,8253,423,67,187,167,9496,119,952,918,8710,275,54,945,56,88,959,8540,48,114,56,957,81,8543,167,188,423,120,958,8747,96,9580,952,111,58,37,76,75,85,931,41,8541,50,8311,964,55,187,182,167,353,8594,43,166,182,316,95,53,64,9552,299,53,51,8309,48,8310,1472,8543,92,90,190,81,8308,291,8253,945,333,121,299,82,9562,9675,9532,8542,947,124,198,960,958,72,8218,922,937,44,9492,103,257,950,9532,111,125,966,51,59,311,424,69,107,916,32,50,80,311,9552,122,968,77,9573,946,9658,125,104,9618,9474,109,8801,77,8240,114,8734,9488,950,920,8595,40,85,103,100,51,291,176,333,82,969,8260,963,9580,9488,968,275,8596,121,8594,299,8470,8317,8311,161,9675,42,966,922,947,123,70,92,9562,969,8494,42,947,8776,112,9474,97,918,964,114,917,424,111,9,111,198,190,93,97,248,97,8240,50,917,9559,920,80,99,66,275,950,113,9632,9,100,8592,9559,89,960,57,105,931,38,9488,107,8993,917,936,8310,343,75,39,73,9559,189,198,9660,84,9556,105,8804,8539,161,914,922,88,66,93,36,8494,960,9617,914,8805,9559,326,9660,63,90,9556,115,42,83,968,9675,9532,52,965,45,107,333,97,114,178,48,957,9572,8721,424,967,38,9488,269,78,190,291,161,123,931,182,8993,948,123,49,119,9632,122,8592,9552,98,198,103,102,87,102,172,97,9573,96,120,8317,333,299,8595,178,955,69,113,66,56,40,67,62,71,80,9472,919,9,73,93,951,952,948,50,54,423,64,958,32,93,8470,63,73,8543,382,101,8776,9633,54,8804,9668,79,179,54,9617,936,964,93,107,47,8730,104,9565,58,8593,46,92,947,8543,8593,961,33,9553,946,44,423,9492,967,82,917,87,423,247,950,8470,109,112,72,177,167,86,41,60,182,299,84,87,916,8218,37,8594,920,82,126,65,275,35,44,40,117,188,8747,8593,959,9619,161,9556,8992,35,118,94,101,922,94,8260,55,179,99,111,190,39,188,9565,39,9660,9650,969,950,291,8710,51,923,8543,9633,123,40,275,86,382,248,8729,9492,961,925,9553,49,946,68,8532,257,172,932,71,8539,8776,102,9580,42,967,40,9650,120,8734,109,353,8313,36,90,117,8993,106,39,966,182,8240,112,61,56,9650,8992,52,9488,108,78,9492,952,353,363,8592,248,64,100,122,171,929,8252,101,947,107,9675,920,9608,965,81,106,187,55,316,51,8801,8541,9580,8993,958,94,8730,49,8313,8730,62,87,8242,964,98,167,8729,916,8318,1472,9572,178,111,122,343,918,8540,968,101,189,49,93,9573,185,123,927,947,45,929,9474,423,925,73,88,124,64,918,931,8240,9608,105,9658,37,182,108,121,50,42,946,8540,958,927,9553,100,58,83,61,55,964,963,84,8494,177,67,182,8805,937,123,39,54,8595,9632,8310,67,936,51,56,55,923,9660,9617,8721,9552,8311,929,257,9,8541,47,39,69,8747,172,9565,9617,115,58,937,8313,126,954,8729,8993,167,73,247,119,9668,124,43,70,9492,967,190,8532,107,179,91,48,8543,61,966,56,71,43,8260,950,424,9658,925,82,56,954,968,63,115,949,9660,925,46,326,54,104,122,95,957,167,8543,9660,914,9553,8313,63,65,64,75,123,56,8260,961,948,8318,187,125,925,8597,967,111,8595,8776,8776,8218,105,74,75,960,103,95,8494,190,43,967,9488,166,46,178,57,60,60,326,79,382,963,946,37,275,108,8308,964,8531,85,8541,9632,8318,58,9572,961,71,87,76,9633,326,934,70,923,8800,107,928,40,124,8318,36,917,98,955,104,956,8993,92,8260,959,8543,961,8532,78,925,8242,86,9474,230,198,164,179,50,960,8312,953,111,9472,915,171,56,118,179,9553,32,99,248,102,968,43,9556,65,9559,112,112,37,924,79,182,8242,919,8532,8308,8543,9488,104,9618,926,948,927,8304,95,88,9668,316,45,72,961,960,9496,52,119,94,952,423,333,61,968,958,8992,316,188,161,8309,954,102,247,115,9660,64,45,52,88,103,316,968,8260,187,8540,924,44,9496,958,52,33,9617,8531,112,71,179,35,8593,927,111,382,45,95,36,125,82,963,187,299,963,9660,9572,9562,9562,917,66,257,9650,106,299,94,8747,9488,116,9,424,956,120,925,8593,8240,382,919,54,83,925,955,166,69,50,39,52,333,9580,77,8804,316,171,959,70,87,64,957,114,121,956,8801,40,79,118,9488,8993,72,65,51,91,190,230,8532,950,8804,961,108,71,8242,969,65,9580,291,187,33,190,120,950,8539,8805,8595,8776,9632,8318,9572,95,103,8470,9650,8531,8242,171,8260,53,230,8304,316,8734,919,8311,8252,363,69,8993,8317,9617,914,9565,69,8592,931,47,8542,82,36,955,343,85,69,84,40,93,112,50,64,316,118,54,92,71,953,916,161,916,9488,49,8309,105,116,8993,89,66,177,114,8593,8470,81,76,9488,9,188,424,9492,60,124,35,9559,40,44,76,9532,8313,960,117,45,954,8253,72,37,84,914,76,8594,9658,93,9562,47,118,933,114,8595,111,33,103,956,71,122,53,9572,92,931,48,75,71,8532,95,50,932,917,8592,959,299,103,934,965,926,177,9632,55,8470,8532,8253,925,8597,936,104,8532,9632,933,83,62,178,187,9650,8592,9658,72,68,94,117,311,946,161,8539,958,123,9532,119,198,98,8539,8532,9619,230,61,333,85,9492,8318,74,919,8540,115,100,179,117,8776,8805,78,118,179,47,117,343,8804,185,98,382,382,964,124,929,933,113,123,92,8318,126,87,50,952,80,919,58,8592,102,45,933,126,187,112,919,110,959,74,9608,161,8541,917,8805,919,46,46,198,967,37,94,121,96,167,8721,8532,247,924,37,961,8543,84,8734,9658,9,182,948,311,9488,33,90,86,932,926,105,9650,60,927,83,125,55,9618,8318,8776,63,8470,924,9,945,106,8252,8318,921,55,33,89,968,171,920,924,86,363,968,76,47,72,933,35,8595,56,177,952,122,65,50,423,925,8494,59,67,937,9,47,960,8710,8470,9492,182,9553,948,91,126,967,934,914,124,99,934,69,926,311,58,67,957,915,59,935,958,113,171,353,922,9675,8309,69,87,82,8593,929,105,83,8804,58,126,79,8776,311,96,115,96,961,8532,949,936,8312,46,1472,920,118,9633,969,326,102,101,177,8805,960,190,182,8804,117,8594,33,923,86,64,52,86,960,125,119,969,106,961,161,118,914,9580,125,936,8747,951,178,59,8242,8596,269,8992,958,72,9580,56,61,8595,8532,951,935,167,914,179,952,937,59,123,8734,58,103,9552,89,119,9619,63,44,8304,86,9472,9658,8253,934,8540,37,8240,178,919,8532,922,949,60,58,43,106,933,9608,9496,958,9633,269,928,247,66,275,92,923,299,9,9608,88,123,177,166,58,111,78,185,922,961,93,8734,73,8776,33,967,54,114,53,33,953,76,9668,934,84,933,230,66,166,920,161,951,50,167,77,106,951,123,9492,9619,8543,8494,44,9488,164,67,230,32,109,164,915,9562,966,107,112,316,71,85,9553,9,41,178,99,8597,8252,8219,35,8542,9632,37,185,8747,56,958,8242,9532,79,915,927,49,90,73,9617,70,177,8218,112,931,9668,923,311,926,94,117,8219,275,952,54,8993,74,8805,8218,8597,182,8318,382,83,70,112,81,932,92,424,167,8747,8540,39,182,116,123,951,9553,8308,187,8252,9633,87,179,8240,946,97,423,75,8721,49,275,9668,931,8592,116,9580,187,8776,963,75,935,8593,948,32,121,178,8801,126,8993,8311,8313,9488,9472,9552,917,230,69,8242,70,8543,949,8318,923,77,171,66,8260,952,937,45,99,35,8721,71,937,353,86,8218,75,78,187,167,97,101,58,58,115,9580,958,952,8594,104,8308,89,363,161,275,54,8317,189,8253,8710,9650,8470,968,9559,42,8595,39,8242,8593,959,230,963,8309,164,46,8747,969,80,954,176,423,9658,960,8730,84,54,9573,8531,8800,112,91,59,966,8805,9472,950,62,83,8218,9565,8729,62,67,952,198,969,316,111,9472,8313,86,56,64,53,43,9553,81,171,9619,107,9632,116,945,969,176,945,8318,947,921,9562,9633,45,363,45,8734,161,69,40,9474,961,93,35,90,9496,71,965,923,9675,61,947,946,110,326,85,9619,9632,44,178,8992,9633,37,8242,78,8318,299,41,937,74,57,363,88,9562,60,43,188,74,9,9573,924,9496,161,81,932,8311,94,97,8539,8800,111,108,925,946,52,958,9608,946,918,9553,8541,424,8317,63,8311,124,8531,230,68,9,54,121,188,120,57,8242,8596,89,8318,269,269,8317,78,954,106,75,122,118,966,299,8729,8318,311,917,88,57,8747,61,291,960,9573,125,8721,8242,969,98,960,9492,935,914,121,99,115,182,1472,8801,38,8730,9492,257,112,98,8240,120,198,916,178,951,69,58,97,8240,9618,87,84,8595,101,933,291,917,73,917,8311,57,257,9553,82,100,52,36,56,969,9633,64,915,40,9472,115,9618,91,8721,69,80,9474,9496,926,47,966,182,8542,47,230,951,9632,55,36,8218,8542,951,8308,64,8596,257,925,103,118,924,177,954,934,59,8804,8993,928,68,113,9675,74,382,926,33,951,164,8242,9492,8597,934,97,8776,40,967,8721,97,8747,316,9472,59,46,9675,57,124,951,8542,112,103,969,948,182,9619,949,102,75,84,42,91,925,924,248,8310,9492,9618,112,9668,8470,57,124,9,9675,92,44,106,946,9650,109,114,945,922,8218,73,9573,915,9496,66,8729,81,8308,9580,198,116,275,8253,9552,957,8310,927,9484,77,8540,63,333,326,921,963,176,9675,8540,9668,316,9658,118,933,111,97,291,951,94,966,166,8253,8260,8595,35,125,922,90,923,88,41,8800,82,9532,84,78,946,343,8597,959,125,171,172,946,959,41,291,93,38,8540,37,9472,8597,269,55,363,928,928,8531,959,9492,8313,67,230,121,104,9474,66,954,8312,42,8318,8595,50,423,954,115,87,947,936,123,967,8595,79,115,969,9496,47,61,46,955,919,118,291,916,8730,53,8312,8312,104,182,932,65,8541,54,80,1472,33,9675,88,112,50,41,91,9492,8253,118,82,8304,87,35,8801,190,66,9633,85,58,8730,49,8541,164,45,69,37,964,967,45,78,117,37,32,74,9562,959,97,955,965,9559,198,126,67,915,107,62,8776,101,32,8595,8594,182,189,8543,112,353,8596,925,63,8992,77,87,933,62,95,62,8539,8252,917,915,182,946,179,100,9633,75,9562,8721,8219,119,8992,119,102,8800,41,88,49,119,8540,68,8253,47,9632,969,424,8804,77,311,247,32,124,66,954,188,8310,9488,46,91,115,316,248,967,96,9573,932,41,82,316,82,230,9617,8260,8539,949,917,275,123,114,353,954,961,99,8318,8747,79,966,41,37,8317,126,161,8310,8218,84,9532,98,79,104,52,103,66,926,38,929,923,299,9488,9553,955,66,167,936,41,72,86,9484,99,230,38,74,105,52,8592,56,9474,45,964,188,8805,9553,32,424,257,363,121,9552,93,92,92,8494,107,119,955,9532,118,8801,923,921,8593,965,88,9608,8801,38,8260,49,967,8594,9565,56,43,8218,915,961,122,51,176,9474,56,950,954,9474,107,77,8539,946,80,9675,964,99,928,8318,45,937,83,89,126,53,326,58,40,948,311,8805,8542,956,934,37,171,963,928,950,1472,48,43,969,934,44,949,968,62,924,51,91,59,8992,326,353,9553,89,102,39,9580,8252,8311,182,8253,934,113,917,118,8592,8539,120,9619,47,87,118,179,102,124,112,45,9,925,79,947,8219,956,8532,185,40,925,921,116,934,164,125,9619,921,171,932,45,51,8721,953,961,55,116,84,171,178,965,311,91,126,126,9565,8730,8595,8543,66,85,97,8593,61,167,106,918,966,8541,8805,948,9484,120,68,948,949,185,125,8308,72,110,75,8309,8541,291,423,921,948,968,99,9619,915,75,8597,8730,98,353,946,947,51,9484,326,85,248,8747,953,70,113,969,927,230,76,64,111,42,49,967,90,8800,914,8730,38,166,76,54,107,8541,93,8776,51,922,86,177,57,935,946,99,936,926,8308,102,9617,8592,85,9553,9484,8592,60,964,8729,73,88,916,74,934,958,56,957,8253,8776,8730,920,97,8240,8218,185,99,95,969,8218,8317,927,177,959,32,46,914,248,109,99,95,64,248,291,121,98,8734,77,9619,945,8729,964,115,8304,73,8242,8240,44,8531,8253,8541,90,9618,8541,41,172,77,95,969,93,185,956,58,9565,8596,93,9617,93,326,8800,952,67,77,9608,9632,8730,948,9474,164,959,188,9532,8311,424,8540,8729,103,424,8260,924,93,188,424,75,126,8993,382,106,9562,59,85,100,8804,8710,926,937,91,8311,106,960,105,8242,9488,275,952,9474,969,8539,37,951,71,8593,97,182,107,8318,926,86,926,83,311,38,88,39,933,60,32,424,423,8242,108,96,8804,914,275,110,316,8531,111,8543,9553,80,948,89,57,934,957,8252,9484,177,275,52,39,37,67,115,123,926,9556,68,37,124,9492,967,119,9573,89,8595,965,8710,8304,948,108,76,925,8218,106,299,9556,69,316,74,8993,914,83,47,35,9474,8317,424,54,9658,8308,9,363,198,8993,104,8219,9618,46,8218,8595,115,8710,8776,8532,956,9562,77,95,9552,333,8304,47,9496,257,45,8595,62,291,117,75,8804,190,927,8242,919,53,966,8542,122,99,8494,32,110,102,343,112,948,9618,106,63,947,8992,37,929,8543,103,35,932,178,47,275,69,949,954,65,963,164,275,36,48,90,55,9556,8993,8309,424,8541,8593,189,9650,949,8540,959,959,291,8311,106,45,954,182,921,190,8317,167,9632,8804,8313,187,85,916,93,112,56,950,94,8993,8992,60,190,44,8993,923,924,8304,8531,969,9562,956,8242,105,952,967,1472,92,59,95,117,8804,248,185,121,8993,1472,311,931,8710,1472,64,71,99,954,935,177,164,353,101,100,9496,8776,61,71,8596,81,61,8801,926,105,8304,125,62,9660,55,8219,48,963,122,161,8470,9559,118,8242,9650,9484,95,9675,83,316,54,8218,8313,167,114,161,9552,8260,68,116,934,9553,9660,922,190,9565,333,118,8310,61,8801,90,38,102,63,9668,922,9618,51,44,382,8710,275,9572,9573,198,8594,74,333,118,45,933,945,8597,110,190,87,8541,316,9660,55,8260,316,8594,961,78,96,67,1472,921,928,68,8532,61,929,8993,40,247,176,119,115,967,955,9668,172,78,166,957,8253,916,247,62,929,35,9619,68,62,43,275,299,63,66,8312,50,922,8253,79,71,8730,969,928,8311,80,423,8218,945,98,9492,959,926,53,65,100,8532,247,927,179,50,275,961,8494,90,35,50,948,35,9650,8800,230,8311,62,8800,8318,52,922,423,8776,8729,67,86,9617,75,9496,80,8992,9492,8252,8541,60,89,969,914,8747,118,114,8540,80,8801,46,8543,120,423,8531,96,919,91,68,97,161,424,69,8311,9658,9472,53,9553,75,98,955,8805,9660,105,8734,924,161,36,8253,121,96,82,8219,87,63,924,9618,9675,961,58,176,75,8317,80,363,8532,97,9556,120,61,39,967,963,8595,947,9492,8730,86,8252,953,121,8594,8805,957,59,299,8531,948,8721,92,43,118,8219,67,9488,967,96,54,916,119,111,178,198,91,101,72,291,955,188,946,8309,9675,8318,915,929,8597,189,925,8594,104,954,9617,116,921,8313,311,82,958,179,923,97,8312,58,120,55,8595,103,9660,8800,916,114,116,182,9559,105,931,969,945,198,33,91,8532,120,945,77,116,959,41,916,113,70,966,167,8304,8539,64,316,112,39,959,77,423,67,45,8595,8218,299,172,936,98,77,92,8540,8304,8805,40,8310,928,8494,182,963,9552,9562,9632,56,8494,8218,176,71,79,920,299,9565,8242,8219,92,8317,248,936,8596,929,71,125,958,8540,8710,8531,299,1472,9660,9618,93,89,177,8593,954,9572,9,189,107,8531,9562,8470,114,77,89,382,947,59,8734,8992,70,929,8312,123,275,965,9565,86,926,8804,931,9660,93,946,164,95,949,9660,189,89,74,112,185,176,275,326,423,61,36,8805,925,93,9496,8593,8805,927,299,8992,9660,8309,37,89,247,84,936,187,964,9608,82,917,107,39,916,115,8310,56,101,119,8541,8730,79,92,77,326,8721,8310,95,185,97,98,114,84,8734,105,8260,41,65,101,110,9484,8721,8309,8308,78,9484,932,63,918,64,928,166,53,248,33,936,291,106,933,8801,9650,56,78,8260,107,8594,96,189,48,81,123,921,8317,40,44,8801,47,948,123,326,8747,49,96,8593,952,946,116,9658,9552,920,110,9617,382,8539,190,269,57,55,424,120,333,50,932,41,9573,75,45,38,113,74,69,198,171,9618,959,79,59,114,949,105,8240,8539,58,68,928,178,9675,8539,54,382,8596,56,67,9658,333,8313,929,9580,8311,8253,40,9580,956,58,960,178,77,8734,118,87,77,99,937,88,106,102,110,92,161,935,179,311,97,8304,947,343,43,8312,945,123,198,9496,121,9660,9618,60,964,115,9617,363,91,190,917,9472,63,8539,8596,9492,9668,299,61,914,50,964,166,188,9617,65,167,84,94,82,919,8710,8592,9660,9633,955,117,112,39,9608,963,947,9565,67,929,924,299,35,937,61,291,8253,945,124,8540,83,73,311,63,120,9572,42,926,363,110,926,9660,32,8596,925,110,9573,9675,85,123,66,9484,107,915,925,8470,9633,95,333,920,122,257,8710,75,922,92,423,914,333,182,80,57,965,9580,80,299,9553,916,117,9492,969,9619,918,32,9472,945,343,32,8597,9553,9658,8253,8309,167,8801,86,914,954,88,179,79,952,8800,928,120,920,161,8710,965,80,90,57,958,9660,100,47,964,9632,46,101,925,164,188,49,88,9618,8734,8309,8710,8310,71,924,105,8710,8992,59,43,69,122,88,9580,9618,923,9668,48,966,299,115,75,920,111,9496,111,920,57,96,922,117,299,166,311,8313,117,343,931,84,55,80,9562,955,179,9580,8240,97,8539,55,948,926,8539,75,9488,964,8260,8240,8801,937,188,190,8800,189,945,48,230,76,8597,44,9660,424,423,936,8541,1472,8309,9660,928,248,9619,115,90,275,188,172,102,52,9572,8531,353,58,8594,966,967,166,38,8309,8312,8242,97,161,122,32,120,87,8219,179,109,47,91,110,935,35,80,8253,98,85,9580,8540,8710,955,925,935,177,933,8593,88,90,8218,119,84,9650,36,8219,71,423,91,177,961,8595,161,954,41,9632,8747,178,37,953,8309,97,8539,69,85,8242,248,8593,9668,190,91,46,8804,76,8805,9484,968,8312,38,923,61,8218,123,45,70,269,9608,230,64,198,48,960,50,954,936,8317,9675,8318,41,48,49,198,110,177,954,8240,8240,9668,423,185,9552,185,8317,8596,957,9552,9633,8532,124,8805,951,8219,110,73,964,65,931,179,8252,956,8240,9472,8318,49,326,40,171,9617,44,957,919,955,96,8219,8800,190,188,920,88,93,8253,72,44,91,45,60,69,46,961,960,39,76,179,117,966,9660,41,9,9496,33,8532,956,9496,9580,59,921,968,52,87,968,9573,103,164,90,75,9474,8318,8776,73,9618,33,299,299,955,952,76,8310,248,8800,8494,916,9553,9618,9559,8242,9660,74,110,916,36,36,915,9565,918,949,97,964,963,80,8312,8252,8543,81,953,46,88,166,8470,8747,93,952,126,97,299,44,112,55,33,947,9474,65,74,185,198,58,9633,178,946,8240,8597,48,75,42,946,8801,70,918,9668,88,9619,230,9553,8593,89,951,928,109,89,62,178,79,198,8539,43,161,167,67,8242,9619,316,48,182,100,8992,62,960,32,72,247,353,64,93,964,948,915,9492,8540,8219,8541,8252,955,167,172,8304,8218,918,382,920,8310,8776,121,8592,179,948,38,8304,966,109,8734,91,9650,67,57,919,919,9562,922,316,171,104,78,92,185,86,969,918,50,953,932,967,951,66,122,9573,9608,946,9565,9562,9618,8734,56,171,39,8219,177,8242,73,120,9573,8729,62,9573,8310,8242,8805,62,927,44,81,94,69,52,922,101,104,9619,89,32,117,257,920,9573,920,923,93,71,921,961,8317,8747,101,64,99,8309,8219,9617,8729,84,964,9580,106,95,9565,38,949,316,8318,8710,35,70,95,9580,936,9553,198,116,8470,8596,60,8804,98,8801,189,122,54,110,121,9532,101,164,8218,9650,363,172,98,107,9496,172,946,40,77,8531,85,61,45,8494,382,9658,122,56,927,106,933,954,8730,9532,106,96,112,54,98,101,41,8309,915,75,8721,932,62,9632,363,111,8242,92,8218,8218,101,928,69,423,57,37,8710,72,42,8308,52,75,926,948,45,111,99,9617,934,257,934,125,198,102,8801,958,9633,920,106,82,928,8992,928,110,954,172,8993,190,172,8805,343,924,88,8311,9572,187,98,103,9552,51,73,102,105,8805,71,8541,8804,8800,343,914,299,269,58,275,164,91,51,8313,423,87,343,953,63,8542,77,8313,79,8801,918,8240,8543,8312,96,937,914,40,120,90,55,52,35,8541,78,299,52,8219,84,37,424,41,8253,8532,247,125,8313,8311,67,230,8540,86,8593,179,71,172,945,88,99,9668,8595,122,951,8541,8540,9658,8710,353,49,117,85,68,61,73,299,84,79,8309,53,71,44,8734,8531,914,58,9565,112,9580,8540,63,9553,107,88,8800,68,96,934,172,8992,9492,85,8992,43,954,8541,9619,8318,49,933,164,363,87,8311,8543,955,9553,51,8532,118,927,8311,9633,257,343,82,967,9668,946,106,8312,916,101,9492,78,915,8252,965,171,42,927,917,110,8218,8308,187,922,363,969,108,81,9,104,9608,9675,950,311,100,102,123,1472,967,9580,929,8804,919,47,326,76,182,275,85,934,343,110,113,69,70,951,9492,56,124,59,916,9650,423,918,185,917,9488,98,172,9562,8312,39,8260,198,964,8308,8800,9572,918,928,55,9565,59,75,114,172,80,113,9496,74,946,9580,126,9553,110,927,96,9484,63,124,54,8242,951,967,926,8801,248,966,9572,87,8531,182,924,9474,8318,92,9572,67,353,8597,8543,8242,100,8470,66,49,42,118,95,100,123,198,105,188,95,98,248,966,8805,9,917,914,917,77,8313,8253,965,363,230,104,87,62,120,40,8218,8242,8494,9633,9580,67,69,101,83,311,916,333,9559,9484,8747,33,39,45,123,960,8310,968,45,8747,9474,57,102,190,8309,45,333,105,120,63,959,8219,70,8805,8531,68,50,957,44,9618,8260,9668,925,97,9618,114,8312,8531,311,89,187,967,8494,929,45,101,81,187,48,948,89,269,8597,961,52,948,52,126,925,122,9633,919,105,8311,56,8470,969,8310,247,953,125,9618,925,424,63,9492,9553,177,50,103,9565,8318,959,931,100,87,316,967,919,172,92,9565,8312,927,79,968,8318,8308,916,8260,932,920,9484,37,8801,299,80,81,9617,189,93,333,53,97,102,964,9608,43,44,957,57,9660,921,8776,9660,919,92,316,424,9488,8993,119,103,167,106,9,37,46,257,230,9492,8242,53,9562,94,915,8593,8993,935,8747,80,8710,72,8710,8776,8776,926,122,179,8470,9632,8747,177,914,179,8318,947,110,166,9532,121,922,920,8805,59,922,67,166,39,343,96,954,8313,935,423,947,80,100,947,83,109,965,8313,9675,924,9660,115,8494,311,40,78,8312,952,968,113,9632,65,63,9496,9633,60,8304,198,956,8747,74,9660,9633,925,40,68,124,8800,8311,105,914,8540,8318,189,176,87,107,76,161,9556,47,8540,8721,8308,951,353,9675,8540,961,9552,63,9474,9633,113,166,38,9553,968,299,945,177,172,122,178,8218,73,363,101,177,947,32,9572,8218,103,8721,124,59,93,94,77,9484,8721,54,269,9580,925,8309,8734,8594,96,948,935,39,110,76,9492,38,8494,110,122,9492,8540,33,40,932,97,9,353,171,47,919,921,70,8592,920,8308,116,40,926,66,9488,947,8592,9532,32,954,917,68,921,8804,8710,93,8317,9580,917,106,87,61,64,937,8721,248,9472,946,9492,8308,113,9658,61,9552,80,8597,84,112,9484,316,9565,8242,50,40,326,9552,179,41,920,164,189,9556,926,951,257,956,179,98,8593,343,9650,8992,9,38,190,969,92,37,9668,9496,248,9608,32,32,923,9552,43,9573,42,74,936,53,70,924,124,56,187,64,122,959,914,198,81,36,8260,117,51,257,8260,87,42,269,9573,100,190,126,8313,89,125,929,9562,8252,94,954,41,9618,424,8494,107,9608,123,8747,8311,110,934,69,9562,103,46,166,69,8240,9562,102,8592,99,87,956,311,178,161,954,8318,9668,187,954,915,51,64,167,105,75,9619,84,8593,9668,35,178,91,66,112,8730,33,9668,965,177,171,954,9633,8494,382,92,85,917,8540,8311,110,956,57,922,52,49,8310,46,9484,9484,9675,83,8805,8541,8308,968,949,8310,62,43,8531,8309,928,928,78,9556,9617,8592,64,914,36,43,914,915,37,269,81,9633,945,76,956,8993,106,8308,924,56,8240,118,57,125,52,9562,8253,316,423,48,81,353,9565,55,8730,94,187,9660,52,343,73,86,190,177,326,967,102,8253,928,9556,41,960,961,164,166,103,198,275,8317,929,105,937,32,8313,8747,95,36,9492,923,182,949,9660,106,92,113,932,49,81,933,87,9618,8734,936,44,954,9556,39,269,9572,106,257,39,57,51,69,121,423,120,8721,73,8531,8804,9472,960,172,8252,960,9488,8304,8805,8595,117,9572,59,945,965,8710,960,178,9668,55,94,9553,961,951,353,8805,119,424,103,343,62,120,117,189,33,326,97,929,89,117,8734,49,33,178,81,950,39,931,963,109,72,964,353,93,275,171,109,87,177,106,8532,955,103,48,969,40,8539,93,122,50,8593,934,928,96,8240,953,54,108,8594,966,946,36,964,9472,952,291,88,8541,269,9552,953,120,8240,969,291,915,299,247,110,960,9633,102,8532,8219,8317,114,8592,8242,109,9572,8219,969,61,423,176,65,67,9572,1472,923,953,95,78,8470,955,59,8734,87,121,1472,9474,920,124,60,965,9474,269,952,230,931,966,96,107,99,95,126,9573,967,9559,946,86,37,9618,56,32,125,87,32,35,96,9556,105,47,934,8304,95,8308,161,343,187,119,39,104,9565,172,950,950,104,968,8734,166,8801,9565,90,959,952,32,8318,54,248,117,953,934,8240,8594,9618,69,248,71,96,964,935,105,953,9472,8317,8730,9552,931,91,948,8805,75,9565,967,40,9484,9496,99,8242,919,931,38,8313,949,68,41,123,8721,8311,958,9472,182,114,916,111,8260,947,9496,36,8734,88,963,108,114,8801,954,960,9660,109,937,41,90,916,126,79,125,9617,87,945,80,9617,107,8310,67,8721,952,109,8747,948,916,423,73,185,161,924,9552,121,382,8311,964,125,92,9632,8729,8240,109,8219,102,84,950,914,9617,8730,9496,8597,68,47,178,946,45,8260,8992,62,65,955,76,94,112,916,945,74,121,187,114,9633,8318,8470,49,93,172,36,50,120,178,9492,915,51,9492,50,955,104,8776,74,106,423,333,102,955,917,85,965,8595,110,933,950,8312,937,92,111,9562,9,79,73,382,8260,8494,8594,923,106,353,248,937,178,43,8252,113,50,248,230,969,90,120,8729,110,95,8804,99,8304,8730,9496,48,937,963,952,113,8543,79,916,8992,959,8539,9562,74,75,8531,951,316,9496,8721,79,9532,81,9573,956,9496,8804,8539,166,967,916,69,104,86,9484,48,8993,423,957,423,382,963,9496,100,8721,103,248,8317,122,50,58,62,952,230,68,275,89,924,51,920,8804,66,57,78,122,110,106,87,931,934,96,423,8734,8540,9650,164,914,8218,91,8312,963,91,37,113,178,8804,67,8494,8597,9474,8594,9552,111,113,917,917,8543,9556,166,8592,115,103,959,269,8710,933,77,8531,108,61,8252,925,103,8218,363,8318,929,8310,9492,966,79,198,105,9617,9472,198,9608,80,8219,343,8252,114,161,8304,123,423,44,187,9660,9619,45,164,950,48,117,37,9633,8594,920,9650,966,953,112,60,56,947,9632,9632,187,424,48,257,961,959,951,112,62,57,109,9488,8531,77,9608,963,115,950,84,108,9650,269,8597,951,8747,230,931,96,9559,326,37,921,39,188,84,110,8317,164,53,105,382,9632,9660,353,9675,103,8734,954,9632,8260,89,8532,920,167,121,8540,9660,9573,172,91,967,950,952,951,9573,956,423,164,9608,73,44,953,423,311,92,949,40,185,916,9660,8311,952,9619,9,915,8800,69,74,8801,99,8252,43,106,8312,947,112,966,326,8317,9562,8309,8800,66,311,71,945,69,46,927,62,9532,333,90,8253,114,182,915,936,8730,8597,44,61,8596,8540,948,948,8721,8470,947,51,949,32,9474,326,947,8776,79,122,89,94,41,8313,67,933,91,8242,73,8242,9572,190,189,122,179,8592,8240,86,8710,116,8800,967,920,248,8542,47,102,9618,8310,922,42,958,101,957,8252,8260,275,97,9618,928,190,928,123,80,85,934,60,8310,9496,935,8304,291,920,9532,311,40,423,914,424,67,8730,8805,8594,9632,9556,117,8710,70,9532,104,8220,353,953,959,58,124,79,961,247,9,41,8804,105,950,343,111,102,126,71,248,56,59,920,166,9565,9488,64,257,37,71,88,965,77,955,9496,8729,311,111,969,945,917,8805,9650,53,115,8494,189,1472,118,188,9580,230,52,952,57,88,71,8993,921,918,117,926,80,83,955,8311,55,8540,179,918,8721,922,935,188,921,8252,8594,96,8317,80,936,58,948,90,167,8729,9619,171,959,8721,187,951,64,108,9552,291,126,424,116,121,172,56,915,190,46,8311,102,93,108,933,172,108,63,8309,951,8993,48,915,247,124,176,9619,56,9496,93,965,176,39,968,247,363,55,178,299,72,248,32,8318,112,8531,87,945,9632,122,926,185,8594,316,115,230,90,188,934,925,53,46,97,9572,967,113,105,8541,8993,8592,39,92,107,91,951,9552,8252,257,918,75,172,99,167,311,8317,946,8532,9552,316,33,79,51,9650,8312,9668,45,8710,924,104,83,9618,291,103,920,9675,957,8800,79,109,86,39,9553,9617,8747,954,914,172,269,164,76,8541,8218,85,189,8240,92,190,190,9617,8747,917,9573,424,9532,75,931,187,36,73,105,9488,9484,83,119,98,8595,921,40,59,958,957,1472,9619,934,9618,917,121,951,9474,1472,76,9658,164,935,56,176,8470,73,934,98,93,9484,9472,9488,8308,955,118,59,190,9556,43,47,935,44,9488,9532,189,8747,96,57,187,921,8310,8592,60,961,103,9556,920,299,91,63,935,423,969,931,9619,343,40,46,63,926,9573,80,8312,198,382,72,9474,8531,8804,9562,299,9496,8313,117,126,164,178,964,106,9565,8747,94,55,8729,951,48,1472,119,926,100,8595,8313,52,182,950,961,248,9580,49,8804,8532,64,92,71,926,57,343,88,950,190,8776,8308,115,928,111,275,72,316,182,951,161,104,316,326,8730,333,961,113,51,954,84,9496,87,125,39,945,9632,1472,112,299,9658,97,965,177,9618,953,9488,964,933,9618,8541,8318,9496,8309,8993,89,275,98,65,8531,80,8596,8310,84,92,8543,8805,931,9552,424,931,961,45,75,95,41,954,948,8543,8541,74,8313,77,961,59,922,8542,172,75,8313,189,63,248,104,123,120,9496,72,950,926,58,112,122,71,166,956,926,73,76,959,77,123,960,65,9559,49,969,967,9488,8805,9608,102,118,63,9559,9484,8993,189,9565,8596,69,382,8218,9474,126,423,81,185,920,8540,167,111,966,9658,65,424,923,9675,35,343,8730,9484,178,248,9496,8805,8219,1472,35,40,8240,9556,177,935,114,110,75,91,1472,956,164,38,122,8216,111,53,9472,114,8721,34,45,43,60,62,46,8221,123,275,59,343,125,111,34,291,35,291,8312,424,74,917,92,102,9580,45,8308,8597,920,953,80,914,190,71,182,91,125,8542,9632,88,8729,954,917,966,9632,51,85,126,326,353,299,85,9580,8595,59,87,8992,74,105,96,93,164,423,9565,48,188,166,8540,951,111,949,8801,179,966,125,185,8594,171,960,9556,932,248,951,87,98,61,49,56,63,161,9675,922,9488,32,921,8594,100,914,45,107,8993,964,922,41,921,114,113,121,164,9472,959,923,8494,8308,185,36,126,100,257,9492,9,43,90,343,8494,8531,299,9633,90,8311,9484,248,97,937,9484,948,98,9562,959,188,936,42,99,9472,916,8734,172,275,74,90,363,9472,937,113,9496,8253,43,179,8543,182,8543,8253,172,98,109,967,182,9573,9559,9484,189,37,291,73,333,125,8542,124,187,178,934,125,50,957,935,8311,104,9572,46,8539,107,41,968,933,8539,961,80,177,8595,42,72,102,299,8542,947,78,9632,90,382,8310,69,952,99,8542,969,78,113,38,114,179,8540,927,230,188,937,8318,106,100,99,8310,8310,9565,920,423,9668,961,41,58,9618,189,113,50,121,9552,64,112,8993,109,948,185,424,49,8218,43,8540,960,8242,8721,9532,9617,33,48,8805,923,55,110,68,179,326,8304,64,100,311,8992,936,257,116,54,291,9658,9532,80,62,8539,110,954,124,8592,936,311,247,103,50,423,179,51,42,8734,33,100,51,35,75,89,8594,9650,35,8218,8318,117,8993,123,8993,87,952,8805,8539,81,9,9559,9,55,8531,8595,80,176,8730,914,68,9532,8308,9556,8308,917,968,176,9580,959,121,126,958,966,9668,8593,957,190,8596,44,311,39,9658,58,9668,928,8242,60,257,8312,8219,8597,98,937,958,918,40,188,73,88,104,9580,9618,9559,955,187,936,102,46,54,123,53,167,8309,92,8494,8219,423,382,9618,74,968,82,8801,935,915,79,75,961,111,949,9632,8310,178,126,8532,8710,949,8730,928,55,8318,424,311,57,9633,8593,248,161,952,56,115,927,9650,93,47,316,965,60,8260,957,966,87,343,9668,62,116,113,73,8532,42,8776,933,969,919,947,78,178,918,113,927,102,9496,8317,167,947,45,87,9668,949,9532,126,9552,929,47,80,9562,61,951,8543,8730,954,166,77,99,8734,67,8800,76,190,120,8312,363,94,179,8801,8801,167,96,8313,106,8592,964,966,161,947,914,8252,72,9552,969,925,9472,934,8992,64,964,957,65,9572,299,9532,57,9617,93,961,9562,81,62,969,921,9565,97,188,50,915,8597,9532,963,179,41,9675,326,934,275,8801,68,9532,61,68,109,123,291,8734,46,934,124,108,8592,423,932,56,94,89,118,126,9488,9492,77,41,84,8317,8721,316,41,8531,100,126,8311,9668,923,54,94,8541,72,230,105,8734,1472,275,95,936,958,343,9608,9492,9632,922,8260,9552,114,929,49,363,925,933,955,8776,326,46,45,123,106,86,70,121,33,8313,954,57,107,934,948,8308,95,47,114,9556,8543,961,37,247,967,8470,9484,964,949,9580,8594,113,47,423,916,9553,959,60,8721,423,952,36,957,8800,8730,114,176,8532,8710,8805,89,108,230,58,9472,61,950,82,188,247,90,954,98,9572,247,963,36,311,966,112,353,96,48,8597,8730,123,948,42,9553,46,75,73,117,124,98,8721,43,916,8992,123,931,44,959,80,88,52,8470,91,70,91,8531,8531,957,1472,67,179,198,968,40,9608,9617,120,120,182,925,75,49,247,948,116,8592,9532,9472,9488,8596,311,52,967,968,59,71,946,74,9474,8309,945,247,954,948,8539,123,40,171,8242,70,52,8800,952,9668,57,53,9492,40,93,914,9532,125,9472,96,49,171,1472,8310,922,8595,9650,269,38,927,113,935,182,54,9660,56,55,36,925,56,68,66,89,96,965,111,947,123,114,9562,9608,9492,8253,104,968,928,58,97,76,968,919,8993,8804,104,924,8494,9552,93,952,84,8992,73,9472,71,935,343,8532,40,9556,8542,72,9660,93,937,65,107,9675,382,69,929,121,8542,42,120,8218,189,9668,47,9559,8543,914,37,70,43,113,53,311,937,44,9472,8597,105,269,8494,92,99,933,917,38,54,8532,75,121,8531,1472,55,8800,86,8310,119,105,95,88,99,38,9556,120,42,113,57,54,8218,948,9632,299,8747,9488,8595,56,8543,88,326,44,299,9472,8260,8734,955,99,74,959,70,951,9619,247,32,8317,958,164,177,124,8308,112,953,9562,9580,8219,105,8721,8595,74,63,924,61,198,38,326,8747,9488,424,918,93,61,9484,86,1472,123,40,63,99,96,967,8730,9617,51,8721,119,423,166,113,126,8242,167,111,8747,90,8242,72,66,8304,423,8734,110,291,116,8317,8776,928,76,8312,8992,9617,91,64,50,48,8747,8804,82,8595,8993,185,8993,269,9573,960,8311,8216,111}] ``` Permalink makes the post too long, but [here](https://mathics.angusgriffith.com/)'s a pretty good site to try it online. ### **Let's keep things ASCII friendly, yeah?** [Answer] # 9. [Jstx](https://github.com/Quantum64/Jstx), 372 bytes (UTF-8) ``` 욑㐇䐇嬈㐇㐇㐇㑸吗箝셫籲𤭯権엵뀕㙧碈𐤕竝𦔭퍰ꬠ䶛𤛴繒蔟𥋖쨶꧹趇𐞣𦄿싐灟쵎쒨걿䈷掴샬𐢷无㹶誅聉뺄ﱖ瑊깛떘꙱읇䛪팘킁焲륐䠢𦆀峘ꫛ莲뤝轂𑆯灏𦞮襩蛂虥襳뙫ꇵ𤍎𑝨屡撐餼𤶽ךּ窬趋𐥁ꢙ數𐃐晊琣𐵃鿙靻췩阻佘蹷䂦𦖀꨻㛞𐤚𥺀䇎𑛭ꗕ。𥌭쾜赳꾲ꓠ𥂥㥌䴸蠼更䐾䥛𐌐䤓𤶋䡓𥾶餃𤺰稖蹽彻埜𑗄망䡎𑎖闞𥬎䫹轤𥪸𦢟我듋 ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.3/JstxGWT.html?code=7JqR74ON45CH5JCH5ayI45CH45CH45CH45G45ZCX566d7IWr57Gy8KStr%24aoqeyXteuAleOZp%24eiiPCQpJXnq53wppSt7Y2w6qyg5Lab8KSbtOe5kuiUn_Cli5busIDsqLbqp7notofwkJ6j8KaEv%24yLkOeBn%24y1juySqOqxv%24SIt%24aOtOyDrPCQorfuv7Dml6DjubbukoLoqoXogYnruoTvsZbnkYrquZvrlpjqmbHsnYfkm6rtjJjtgoHnhLLrpZDkoKLwpoaA5bOY6qub6I6y66Sd6L2C8JGGr%24eBj_Cmnq7opanom4LomaXopbPvmLPrmavqh7XwpI2O8JGdqOWxoeaSkOmkvPCktr3vrLrnqqzotovwkKWB6qKZ5pW48JCDkOaZiu6nhOeQo_CQtYPpv5npnbvst6npmLvkvZjoubfuhobkgqbwppaA6qi745ue8JCkmvCluoDkh47ulKzwkZut75%24t6peV772h8KWMrey%24nO6Tl%24i1s%24q%24suqToPClgqXjpYzktLjumIjooLzmm7TvnpnkkL7kpZvwkIyQ5KST8KS2i%24Shk_ClvrbppIPwpLqw56iW6Lm95b275Z%24c8JGXhOunneShjvCRjpbpl57wpayO5Ku56L2k7oS28KWquPCmop_miJHrk4s%3D) Enjoy. [Answer] # 11. [Crystal](https://crystal-lang.org), 1000 bytes ``` puts "丟뫉뚑뫸꾍먹겇멉겇멚뢈먹겇먹겇먹겇먹궸멙겗멺몝뫈놫멻궲묊낭뛾늨뚞뢗띞란땞꾙뙾뎢뒏겐뙉뇧뚹맰뙩낭뫘린몪뢠멋늛묊낛띎뎹딮뒔뗿겥뒹닮뜈곬뚋닪뙻뗨띨돰딉몣묊늄럾뢋딎뎁뗾뢵듮뢒뚎뚱럾낈띾늎띎뢃뛏겐똫돮럻곦땺곣랛닮딨껨뚨뇨되뗫램냯뜙닧딘뛪랙럫땩듪떛귬뗘돤떺뛭듉듭됨귧둋껫뙙곤똊껰뙨늀멛꾘몪랛몈몲몺낝몋릂묉궆뛾뎁듿겦뗪뫨뙚뗨떸껨떚뇨뙛꿯떋꿫떚럪둻뇰뙈릎묉궝뚎놱똞늒딎떤럏겤띫맯뛋뛧뚪루띨런딊놁몪꺙멩놸묉것딎늙뒮몧둎뎐똿겐띘꿩럹뗩뗛러띺뗩떋럤럙듨랛돮둨다됪닰뙩늀몪뒻먹랞묉겤떯겥램곤둸뫮땊룰딙랭뫹뮭목뎕뫻릡묊놌뛞뢾뗎몓땾뒵뜾뚾뜮뚓똏겥됪뇣뙘룤띋듮떈듨똋룦떻냯뗩뗤딋뫤뙙런딈뢐멊낓묊낶뒾낡딿겥럫닩뙈꿰뙋뚰멺뒖몋떽멛릻멙뮜묉궗둎랧뗞낡듯겑듩닩땹뫰뙚뢎멊랹몋릤뫨낶묊놪랏겦똩믦뒉귫딸밋" ``` [Try it online!](https://tio.run/##XZPLkptWFEV/JeU/S3maQSp2BpnZ3Sk9uAmSAPEUECMF8VAjWV3ulkQF/UxGd31E51zKo0yoW1D37LPX3rz/5bcPH3/86e3t518/fvjh3b@XnHZOvKK96OFPqqs@T6nn4zOmmH1/87/ny4U60ueA@kaT0s6YtNS9fjlzsHh4IhmwKuKMIiDNyD6xzvQQEQ3YBc5Cn5dEc6Z74iv7E1FtbrUh5YmmofiLWmEl47SE1Ma@4nU4HsFdn//GuaI6NjP9fCBWqIaoJ6hIKxYnvDnN1ty1ficfKBSeTPhMIOdvuB2FQ2wTfzVfH2aksq1tVIpHknG3sGXRkff6uWR9089bssQoepXuxVfFtGIZErRkFY9HNhFqjxeSNGQRecu6xm3wE/16IAhZ7PBvJE@4c9wnlpV@3bNSum@JIv28I7R0LxwqrE/UiR5Cw0FEmxnNmebGQ0qjKB84zPXLxBAWR67QKAka2oooNgT8i9nQj82GUaLvR3yl7615kzeseqaiMqO0xzmp4TD5SphhOYaSvyMXAjvSlv2RRJFIRg3bkW0ubC0mn2U3fYuoayYXM@f8aO5aEU5HI76EtjC8G5JpqO81@ZWgJkjID6Q3c/YVuWhFuJWxKbRXFWrHskGNfRAOQsDppW9k2agiDI8m/awyxFYX2o61xVa2isikP1e6J5oae03bU34xHZj8QSI9HAhsGpf1gPONzUA8sOmIXcKFmSm60y1RyFa8K1MSf2Z2CxXbEr83KRsLOzxFu5PURhoziiW1tNQdu/qCI436gje2VGqgaqGt7@JIEZ/M/@L4Jkf/H0mZspf/iG4zZhEYbtmeIDMTXHG6wq3NhPWV9mTyLWyjlV3HJuxM6KJoPEpVFqYJYc2xxJnr1xbvwkm9e3v7Dw "Crystal – Try It Online") [Answer] ## 14. C++ (1252 bytes) ``` #include <iostream> #include <string> using namespace std::string_literals; int main(){std::cout<<"$><<\"Fb[\"+'泫Aѹ୽Ñ຃Á຃°ʂÑ຃Ñ຃Ñ຃Ñ൒±๳mBय़൘\0੝ЌࡢѬɳάΊ֬ୱҌݨٻ๺ӁणёĚҡ੝2Ś`ɪ¿࡯\0੯μݑלٶԋ๥ّࠜЂพѿࠠҏԢ΢ܚ؁g\0ࢆ̌ɿ׼މԌɕ؜ɸѼљ̌ંΌࡼμʇл๺ӟܜ̏ฤ֐วͯࠜעఢѢढ۲ԟ͢ਛϱࠣײРͱ̟֡ؠկഞԲܦՐНف؝ۢണڿటұฦԀచҢࢊ¯୲`ͯ‚XP੭ƈ඄Ќމ؋๤Ԡ\"ҰԢՒఢհढүଛտଟհ̠ڏचӂż൭Ѽख़Ӭࡸ׼զ'.unpack(a=\"U*\").map{|i|47882-i}*' '+\")=+kCb)Fb[\"+\"񪁬񪮗񪃐񩹌񪅰񪅔񪆑񩽓񪃓񪁋񪌱񪚺񩶑񪦢񩷒񪚃񩴲񪮸񪌭񪖢񪎍񩶔񪏭񪒫񪇼񪮫񪃣񪡒񪁂񪉒񪉠񪁏񪃁񪉒񪊰񪁗񪁢񪍓񪂠񪑍񪏓񪕗񪐑񪕋񪇒񪖻񩶑񪎀񩸂񪂝񩴲񪮗񪊌񪮖񪂓񪭗񪏃񩵍񪋱񩽋񪌢񪂎񩵂񩲎񩶒񪒦񩵀񩺚񩴱񪚯񪅝񩽽񪉭񩶨񪊽񪎆񪃽񪅽񪄍񪆨񪈬񪮖񪐑񪙘񪇣񩽗񪃰񪍍񪊳񪍓񪈰񩽕񪊀񪝌񪉒񪉗񪌰񩵗񪇢񪁋񪌳񩾫񩷱񪞨񩴱񪞅񪍽񪞚񪋼񪮖񪁐񪕒񪇳񪡋񪇰񪆋񩷁񪎥񩶰񪉾񩷠񩺀񩷢񩲟񩴲񪪤񪏭񪂔񪉝񪞚񪍌񪮪񪍒񪕒񪋂񩵋񪇡񩾭񩷱񪂂񩶰񩺗񩵓񪞅񩴱񪚑񪂬񪮕񪈒񩱕񪎲񪩐񪌃񩰰\".unpack(a).map{|i|481339-i}*' '+')=+kCb)+++\"puts \"NkN'\n"s;return 0;} ``` [Answer] # 16. [///](https://esolangs.org/wiki////), 1157 bytes ``` /˜/string//ˇ/unpack("U*").map{|i|4//ˆ/MMMM//√/MLLL//˙/MMML/k='#include <';m=~(1:10)+77;disp([k,'iostream>',10,k,'˜>',10,'using namespace std::˜_literals;',10,'int main(){std::cout<<"$><<\\"Fb["+"泫Aѹ୽Ñ຃Á຃°ʂÑ຃Ñ຃Ñ຃Ñ൒±๳mBय़൘\\0੝ЌࡢѬɳάΊ֬ୱҌݨٻ๺ӁणёĚҡ੝2Ś`ɪ¿࡯\\0੯μݑלٶԋ๥ّࠜЂพѿࠠҏԢ΢ܚ؁g\\0ࢆ̌ɿ׼މԌɕ؜ɸѼљ̌ંΌࡼμʇл๺ӟܜ̏ฤ֐วͯࠜעఢѢढ۲ԟ͢ਛϱࠣײРͱ̟֡ؠկഞԲܦՐНف؝ۢണڿటұฦԀచҢࢊ¯୲`ͯ‚XP੭ƈ඄Ќމ؋๤Ԡ\\"ҰԢՒఢհढүଛտଟհ̠ڏचӂż൭Ѽख़Ӭࡸ׼զ".ˇ7882-i}*'' ''+")=+kCb)Fb["+"',[93+[148,0,0,0]'+reshape([~(1:154),'˙˙ˆLMLMLˆL',~(1:24)+77,'LMLMLˆMMLMLM√√MMLML',m,'MLˆMLˆML˙LML',m,'MLML√LL',m,'LMLL√MLˆL˙$Q&\\(()`&$\/=YIZ=WQ\/91Y25*Q&D$,,$&,-$$0%42838*9Y1[%WQ-Q%P2X.`\/%XUY5X]W=(`,Y-1&('')+Q3<*`&0-0+`-@,,\/X*$\/aZAWA0A.Q$8*D*)Z1Y,Z]ZUWM2%,A0Q08.X*aZ%Y]XAW=%Q+T1L\/SO:3\/S7466.T]4E5&U[PE07PN_NF5%5C2$5S:E6C06:4.5^4#%@U:\/96:&0T.E1%15I#=TR@`PK`)``0KO94;F:S0V6S8#\/5:S:E.VNTKT(`=_935V.S.$HSaC#EBUGP7@=\/M55%.DPT%S:6(T4O858U3&S'],[],4)'](:)','".ˇ81339-i}*'' ''+'')=+kCb)+++"puts "NkN''']) ``` [Try it online!](https://tio.run/##TVJ5bxpHFFe@Qj8BwsDuwrIH7HIZIhMfbWSwoYC5lgZiowTZEMvgv5Iedis7SZFsR6pUCA54fTRJscB2HOGUyhJpKjnYFDD4SJxo1D/6NdwBKqXzZt7MO@b9NPN@0YlA9HYwenlJllNkNDYVitwiyfI8OR2ZDIyOo0KHVIgR4cDk3XuhewyMzJFmOEjy7/tJ0mwymaAr0XKZyHED0hWKjE5MjwUFeqQ7bPgGpXU0hcnU6u6xUHQS9Y7jSOgOxAgGwlcRnKZw6CinOkdkOgqhBZFAOBiFyEFBNDam05VTNyZCseBUYCLa3UkLRWKCcCAUQbG77YzRO9MxvV4ouqrXc5xw4KZXKBP@s/Orsbb3Gdj8/fUSePX96xmoSvm3sx3r/2r3UWkL7O2UFsPXwHq6tAB2f@Y4CjxbrsbBCl/LHuxUspWHJ1mwuVWPf3h6/hvYe3U8A9ZWa0t/JOsrMFHxJuk/eF7aByu59s1cpfhh6TR1/rLxI9hbP18CmVR1FhSe1PZBJlNfaPAV/iJ5NnOrlczPHcYP9k@LHx804gc/naUOCrViLXEYB89nKxC/WCm@na@2IdMXqcMFUFg7WQSFX45ysOgpD/J8jQdr/PvtRvqIB08f/7UFMqun29XM0dZh@mTlLNPMgRdPGtsXG83F6vL5zNnyex68WH23D/Lp@hYobDS@A/lknQf8w1IObG77j3KlWZcFPNv89s/7V8DLH6rxjw/O4DPWGhn4t/V8g28@gqjNPESt50D2cXMfZNPN/GHm3QJYSx7PvileAbubtSJYTxxnwUrhtNjcEBLlebVGo5CHvpYiiABBZELMIBvvvYl1moXgXq1S5qUZDU61xIfIpoLR24HJIOptM4hlMEiTBJQ5kxkK3BC8FVEwLW7hyH9ec2szQ17C2T4jeBhH2pHOSnzymU0wydSxoNGy2oXLCZFVwnEoivklIo40uK97DE4rR2ppt4KVWiV9IhwXSXC5SESJGYVGqZFq3bRX7LTKrWKLwkX4OVLscrhZl89pQP24W05LUATBZFalXuqXUHJK5pf34DhHuqSwfMBjdBopI2EVaaR9UsxDu3GPz@NwmhVi3EhZKQ3hkgY8YrfPZXQaxFaZnTZxpG1Yp4RazahUhN3H9LMSh9fST6ktQzeGBlgx26sQsTZdv6qXUukYgv2K6RL3OHTwCSqdhLIT/bSYZq93Gexf9vgtg37M76cGh7VM94DORo2obJoujmR18D4xMmQftKN@ww2tkh0hbIToC1ugt6v/muNzi7rHwJFmlhUTfRa72KZToXZmWMNqHEqJDfHhXh/OYIgP1WEIjrTar6GVSu2n/sMP6RBAJpMJJ6djUYFwaHwIQRAfdnn5Lw "/// – Try It Online") [Answer] # 19. [CoffeeScript 1](http://coffeescript.org/), 3753 bytes ``` process.stdout.write "“ĊƁ²ḃ7BpṠƊ}œLṣQgƝḳ>ŒCẎu⁾ʋ2Sẓݤ⁷İfṘʋẆ+ẠMċỌẏO[ƬqØẓḄvEḳĊıAĿṫvṀƥƓñðıL»;“FḂÇÐṄ2(ȦwÇọụTŀƑ'¢¬Ụḣġ1ṇ¡agx⁽ẈD,Ṫ⁶O³ḂṾɲ€shƈ'¹\"F$i{S'⁹<Þ¹æ×$×ɼ/^çạȧæƈYĊ?dḳƓʠ)G¢⁵#®-[ṭ[Þċḳṛ\\r6$ƙHṿụñ|ḳÑ(:ỵ©lɱ<ṂȦżḄȥ9ı³+f¤f/GẠK£p~ƁṚ£ḌBʂbṪṙTEµ1æĖ%ƙ¢>ṘœÑɦʠėỌÞ-ȧ*ẹ nṡGḣẊ6ṭs<SĠ3\"¢ṅfḅḊq⁾ṫȧƤAẓe;ƭʂạ1ɲ⁽vĖ¿ɱ⁴ẒṁAẇṘ(Ṫỵḟkƭ0{ḷḥ}(ẈḣzẊ8Ƥḅ,/€ɗḄṪẹ½5ịİṗṗụ Ỵ;⁷ð®⁶Ð¥%ṠɗḲ)|ṢṘÆs⁺ƁȦḋ:Ri⁺)Ḣ⁸Ø÷`ṬẸṆ?ẓ.ụ×ĊḍɠqȧĠŀP{ḣẇ⁴ɲṇ⁴Ṿ]ṗʂİ⁾ṡWẋ1ɗʂẉOþɱ³ṅẉ`fẊṃÑƓ.Ɲ'½ỴṗŒ⁵%ṾƬȷị}Ðḥ_4ọẇụḳƓ€ṭịọ)ẇ⁺Ẇ^OÐhḳⱮċ-¹ṠǃḳọPẹ.Ɱ⁴HṣṾ}ȥ©BƬ⁶y¬tḂƓ¤IÆẏp{ọĖ&€ⱮỌm¤Sỵ¿¦`ẓċ~⁾ḷ f5ؽẠṭȧịṚẋƑ1¢YhÞmụṠẋgẆḂ!M^ƙÇŻȧỴ⁶Ɱ⁵ɱ7bhbṾƑÞÑJḄqḲØ©¶ṭṾ>ẓew,Ḷ@¿Ċ*¤m-<®þð¦ṚṄİėḥmḲKFṪ⁾)ȧµŻß⁼ȤƁụ[µ&@ċỊ_GƊḢþ¹ṡƘ\\Ðtw2r⁹ṗḌḄGŀṘiṠøhɼ⁵9)ØỵṠ^tṢÆ⁹ç4Ị~ḷẉ¹⁴Ė=ṡṛỤ0S]HỌrGɱ€MvØṢẎU`..¿Ñ}⁸QƁCƝñJḲ⁵Ṁœðỵ⁸ḳ}ụọɱṪwḋowÐṡes°ẈDœẏỤ⁷Ṡ@©Æȧ@{ẈLė¹paw:⁾£×ʋŒḟµị¢ị÷X¡fẊ-ȷ[Ẓc¤<*ȧ<YɱzF{ḞȮİ⁾c(ɠḌ9ẉ׌jSṠỊ<PṬZẆHṭṢ®ṖṢḌƁGøZṡƥÇ-ḤḟqFẏfọCfPŻṂʋœ⁽SṖ^ɼṙẋɼịṣḢḶ\"\"¬ṾQẉDʠ⁺⁸LṘ°`BĊıḥX8⁷ ẸḍṚ><ṁ¢ḥ]>rḍKQgṆ67j£¹ỵḟ;¬BĊƬỵNḟ'Ç£¡ċọh¥ṗȮƑYżŻẓ©Ṃ7×ḍṛ{p+`68¶Ọ¦ịịY6⁽6SỌp`Ṿ=½ȦRẉƥḢẎPDBĖg3ḃḄ2l¡⁴8ẹn!Tŀ5İtṙʠgĊð+Hq⁶ḅẒJ⁴ðpÐẉƝµÆƭƲṪƙḷ×p⁾'w-ụṢṭB⁴&Ọḥ9sẆıh\\&%%ƲƬẇḍụḄ¡Ẹṇrʠƭ!$vṭmṘĖ1Çḟ⁵ẊpœẇỌcøḋṄƈĖƇⱮŀO¶ʠeṗ÷ ḍ⁸ṫ¢×⁸⁻Ṡżṿȷẹ©£ƇKẹI÷¥eḍ¥ƊƬ{Yẓṅ)ṣ罿2v@ƙṙ<×ƲẋdƑH\"BʂĖ&ȯḅƓṇġḷỊṠƓs⁾°¥_÷Ṙ⁺ṅ6ụkIkṁŻḟdR¬ƭ⁼÷?¥xƒṁMAị5ḣ+⁺ḂṾ⁸oɦDlȮ2³ƓỌoṬ1ØgḢCQjʋLṀ?}+®³{ßỌ&}kh\\#<(ọs¹J&<ƲŒȥ~ṛt=ṇỴƥh6ẋ/ cạ⁷jỊėSKtÞ]ḅḋİẏȦʂṅƘṂẋẹ⁶⁼mḳṠƊþȷṣxḤżṃ®ėÞS⁶Ɓ¬ṗAṫ{Ç*ẎWCŀUḟɠ½6J⁵5Ị⁶Ṿẹʋf-ʠɗȮ©KỊ°°9çƒẏSḂṂ[¦¶%_lRĊ⁵Ġ#?]VnḊ]HrỌ⁷:ẉ¿wOḃ9ZɗɠuḞŒƁEṚnỴ⁶ƥƙṢk]2çuN½ṙqṁsȤȯḣBỌdIṃ?ƑṀė2ṛƬẏġß%⁷tRmỵI⁴Ẇ6ẏ QİEṁƁẹçȤH8Ṁ©¦ðLɲẈ&ȤkÇṗgḲƈṫŻṀġOṂkƙsẊḅḣḋXƙfQ?Ḳ!Bṫḷ°¹ṫỌʂlƥlȧỌ⁹ȦẒ@ḳ2¦KỌƓṀʠḂọḅ³Ḣ¡ḥ6ʠ$Ṗ\\ṅ/ṿɲ⁺2;Eg'ṣCṛ]ɱṃø5Ẓ[¢iỵỌ1²gḞAçÇɲƊvHþlʂżụ⁴Ċṿ¦ÇRƲpṡÑƤ-ḅAỊ-Ƙe?ȮȦBƁ⁷çŒ ẇṁỊṢɗḤ×£ƙ$ı^[Ị0®ẉĊØ⁴Ƙ)ẎṄs⁵ḣẇⱮcʠS¹9ṢṘĠ¿ÐŀGWHBżµḍƈ¿⁷ẉe⁹ġ>*ʂɼfỤ;Ṗa⁾ʋ¦Ḍ|¿ỵẒ?6⁾N*ṪḶ8Ṫİ⁻ĖvẋȤḂḣAƈṅ³ÞWʠ×Tİ^⁶ɼßḥ'7*½ɗḊ+YḟṘ¬ȥG3µọḳṣĿṇ-ḳʋṡȯẸjṢ5Ẓ+3<Ỵmƒ6Ḳ^€ŀṇẒḶ^8ṇịɦẎṗHMKK²⁺JvƬṢ€Ð&ÑuE⁶¢3ż'Ȧ¹ḋ⁻w€⁸Þ\\m9ÆḍZƇæ⁺\"ȮƘU]ṾWʠ⁸|Ɠṣŀiẹ©uḃẋðƑ$ʂJøḥƭṠrvẊ@ṪḍAƑḂẒÞ'ÞȤEṚ!ẊṆỤpṗȯÐ<_5ṬyZṇẉwÞ¦ĠċE⁷,ɠȧẒ:ƭḊ²ẇaXqȷ!⁵ 8÷Ṫ⁾oẓżʋẸṾ¥Ṭż¬¶ḟ$\\ɦØ⁸¡ɗnṬ’“$ẹGọ`ƬỵUPṡṀȷæŻ#ƥɠ²'⁴_ṀƇ÷ÑḃḤżtṅAḢẊė2ṭƒnṛ|ṡdĖqḌ\"®⁺©ßf⁽|ṡçƓẠḳḲIÇXƘȦ²J€¡aȧ9CÆb{Dr©`QḲ&Ṭo`tṀ7Ḳẓɓị$ÇıMỌɱ¿ƓB½¡ṙgɦʂ!ḄŻ)⁾6ƊȦxẈn7»" ``` [Try it online!](https://tio.run/##JVeLUhPZFv0VQAQRwQGvPJSRlwqKDiLjVSQgirwE5BEEZxArQSGYgJJQRWDmCp2QToqZwCQo0A8IVed0TnXnL05@xLtOTxVVJOnz2Hvttdfa3TvW39/X5@ydHBqf@vFjfHKst8/pLHVOvRx7M1U6Mzk01ZeTl3X9z/AyNzngyofKhnGuSsw7l167x9WdtgH2lSvfbqQDjVz7/CbrTmV85e1cW0vrJJJ1HxuJfq5uZHxcWyzmmnTf8HF9mWtfWjtZfIJuYCFXPk7fwhGG10jWG2dc/Xuaqy4mszWapAkjeY/o1xHAba7MUw9d5erH8gtmdIZ6uL7CdfnXtIv5C0mYxLke4cqOESrjqoeEng@8zbpPubZ08xJX/8q6j1rJNxzB1ZR1kJ2POwfZUiFRHXm384dm2wuzbrWGbhGVRmkwnwatk8vdNMa1kBmjUbbUYXhrXyJEtpaRippIOOs@PEf2Szq5utdJt5CS8o2rfzockxX5bLOZq2eIiybf4Wfqv3CN64dkd8RK1nB13oymT5CwKVcbSfKtuJ9E@i83AZcWsjP@nrm5@gfZ4cpyQ2b@BaLm6uavt8hhGY0a6@fZJgnfAJbpNeq3ohnJCAJJulVixi5yTc15zdVQE/LnmrcCcTlr2g3piiOPhLm60M@VBa54J1AdwGvGWKQewPddZ3uZeSRZBkTcp9PGOjmzkln3d64FuOrGEg@uuyDi0A@5sj3M9n6a5coxV@S5CwAWl/2O26oYYF@4dBmgWkHkJtZrKjm9ynWfkeBqUPzpcg7Xv18HIWiC7KMadJXI50EkseWg6B1XEecGXXRm3Rpzm1Gu@K49HMKXIq4AboVu0OMersa5pnB1sRbRlwqMg4aXKyuWNGHGDCntejBrA@BBDtYBWCByUVNdCCAzbyTs7EOPueYrs4Ii8U@tNGWhDEAIX3r6kQxXP1A/WytlXwvJKSLG1nQA5UaoKRY3j5HTHDioyM/@I@gHhHTZJgayB@p4jJ@L7BA0UL67la4O4nk2uW/4SoiKhKmHBQRf9JUHgKkUTxAlOLODG@ZMmew2sDjw@Y3Ep0BXtkYid@giGmZ8FluM9QJchD0o/SiJtAtqnZFoD/AwfO9FgspxTv9VuoHgNQkBmTERkvoHkmb@MhLuGKRboyJmVcJPAwgRl@Te72ab1JPWxervuNwO6tBKVr4YfCES99Mt6r@L2k6gWDh8lxyJZNXUDUGjmUtcOaojZ4b3IomMltSQfZpClaPiWvWjkQBRFXkUO1tu252YKjJj5DCt0@2s@8SMgPW63EkOC@qENnifNTHUNExTAq0Q23A46OrUTPkkOlQQSVlGGE1pF9gyJNBUBq0TxFpdBC0BS1WpewpcootYTmOokfe9YKz2iaiA2Vj/GWeiVSEVP7V3NQPFySZQfj5@fxr7wUHt86Oe0lJyRv1zYF0bczeyrzSJ1NEhON2F5kvgHjxDDecEkPqKlURaM2Ds2IyQp1CfkySE7qTXUDbcBNIjrjqySxfNWN0sHt0zgkQdfz5zDWCQHRrM@NLgxDY5RLHQsLqPHj8hIcHHEvO4E@3YSyI1F81YTYeV/P02SL5l7tt87r1gSYCkGglSEPVVu6ir7q15gFZ5iuI222UKk32urov0lGXmbqLKU4GsTD0lXEHvbk/cRqD9yKSx/0Fah0ohnjUoAk5b77ZOoELgCv4LJkGdcMyRIw/SAsan2nD1zYwEugMTGMIGSfQ0CClHzZ9UIfUc0bLKCshwAwLoRnqK3HVjEj@1tA2glysqX5Ed1NqWmOskjs0MUn74C74WUg@ehQQvVgYJSBs095m/I32CKLU1sotQK2nQPv3P2fHinooqEFNfBvVEH/o6KpBEBZpkeRzakfqZnJrRh4iXySIJ7fODmw3G@sAVmBo4VT5CQqBIFZrydS5M5aqRAJM2M9KA4aWJ4maI55GQUS1wF8toYhy1xlFfySFdZHsMcvMX2wTXaHAchSmcKbG7DKq214D1BcL1FLnaiaIYyUGHo@D8eXaARKEgyootIh9JyFY3z2RGYnu5@XDBvVEAaqyXweuUbUFAzTsuWAXVWe6lgBUF@ciWjHXmQcumXa3kKCP1ASYK2JUVwVL1bxKmQXzKulFZCe6jnkHGINC7ZId5WvDpDj0mch/WE5kB@9kOYcrqQhGKTWPklJyVT9chNXWzhgaRp@Z7yfzNjjx4FOTI/AegMKz3GCHRabpXTAdrTsHsBJGfUXB/Q4ihulCBNIfvDIMEKJ@y/fIhibM9SAA9riXyWyY85349ynYVIl4stthujdDHrOjNEXO/nEBnkfkYyF1GNwZQxMa2VxkfWOeqnSsm@@TbLN3GgoK5YSB8ruYCaOMk6t2CGnaQDpjye9BkCgoA@L4zebACqVzO6YUBgqavELkRbG@ZoltdtlsK79K@mFEYhbrAIA4wDEwxqpBH98mobfkYg2gKaKo7b9FJAtsPZN8I0q12rMK8hAYJ1qMEs9QDj/78uDHteoTMLYmcVoBFh7BIr6CVmsLBGV9/SQZ@aO6T3RY8AHyJahoDLtqXdhuL@U4SJUfnn408NLDt0JDO1Xb99zWMvat5Emkji2tC6c5mWkHp6qdW0JLeQCvSAea@hf57/a@4Y7JCMcPDXeU09uYXGIW6OQHonWZE1HKnASe9vINMapkfwBrBcqAmiPrFCNHt87hk6iEc5PCOPSgsAsQvOW1GAhe4oeQaVNeMNFdhJwgWpYl7MGJtqcCMDIPEahBFO2BLgETojMsItSKrYbbpFNYrUIe8@J6wzf62WizMbcBCkApIqOKTvpyZH2HyiLApZKtiTNACdahEOYkCsWVBQ1dGEljBm5UFMfCF0VWKXJGR8iFmDgdqeRkdIAYerfz6rYFC1K4RCXYJEf9Alas4sZOEh4Qc6ctl5AABb9XTGPVYB8w73UxTI5l5FFqXhZ2A63Bf6nnIDjAUhzA5RCCpCyCxt4Rt9NWa@2a0gbnF1BNLB3Lsgcptt0hYzD0RGkQPbuYbye5O/PoTZFr7BLVBv3xnG5giPqO9naLv/51qkvu9GamdqNX/TkuGBJ9aTbuaHjc3pE9gHsoKWyJnwm60T33AxwjduJiZt04g7ZHrSP@5PZ1DHZXld@RMpKgFaqGRqV8uiqFNOULZ/hK@ohvr02C7GRFQKjv1omJAk249zkg0@KuR6AaPrBM0myIXVl4kpyIbb3EHuC0cIG7KTVeEma3YXbIjhnrhNd/wGqCGwDJNeYUUBNbFV2rAylEWqEC9u2HEwtk9YgBVjrqr7Fb1WVEbiWDz/ZYWIgp3dxp8VMNYTVcLqP/NLURDwlfSJ4VmFExRfMhgRsxJmBu3HI7RagxQyspT5qFR7HbkwUQ2HmEqTD0WxqW8E7zZSbuGbFV8I@xA89EE8@dn5u8KlZUZTFSaBCTeOhuolXr0BqDRAnSrkG6ZEdFeufb4uAisx4VR/UNXa55dhVT99tTO6NMM3i@ihmT4EO7xJUsCi7XANRytePFipXmeP5kwj3NR7ZwqIZpiUBoT71En4uUJQp4SBhhHoeMwOWU73@GwooIqCglZQUz/8axrE@9J@ciiCdD32C766IE98LjMYxpN6@eYDO05wNvO92fiHctDj6nftj@IF9wOzBXG6LWbfo8FcOqfGM1DL411TH7LsHzMhRoGme1@OKt4An1aE5Mm6qwc3KGeJ2wDNTi4C/TxCmbGqhvp4ovZm5Nkt6cNKwoQ5lgPbnJV4huysyDovnzqMZL30W8Yxs/YWgM8BzFvDuAtZz4XxpjWiwBGBfOa0bcQk9eVRM/78eP/ "CoffeeScript 1 – Try It Online") Back to UTF-8 [Answer] # 24. [Brainfuck](https://github.com/TryItOnline/brainfuck), 44975 bytes ``` +++++++++++++++++++++++++[>++>+++>++++>+++++<<<<-]+++++++++++++++++++++++++>>>>--------.--.<+++++.+++++.-------.<<<+++++++.>>++++++++.>>++++++.------.+.<--.>-------.<<<+++++++++.<----------------------.>>>>++++++++.--.<++++.+++++.-------.<<<++++++++++++++++++++++.>>.>>++++++.------.+.<--.>-------.<<<-------------.>----------------.>>++.---..<.--.>++++++++.<++++++.>-----.-.+++++.<<<.>++++.>----.>-----.<.>++++.<++++.------.<------------.<<----------------------.>>>>+++.--.<++++++.+++++.-------.<<--------------.>>--------------------.>++++++.------.+.---------------.++++++++.<<-------------.>+.>--------.+++++++++++++++++++.----.<<+++++++++++++.<<.>>>>+.--.----------.+++++.-------.<<<.>>-.>++++++++++++++++++.------.+.---------------.++++++++.<<-------------.>-------.>----.+++++.+++.<<+++++++++++++.<<..>>>>---.-------------.++++++++++++.--------.++++++++++++++.---.---------------.++.++.<<<.>>>--.+++++++++++++++.-----------------.++++++++++++++++++.-----------.<++++++++.>---.++++++++++++++.+.<<<<.>>>>+++++++.<<<<.>....>>+++++++++++++++.+++++++++.-----------.>--------..<<<.>>-----------------.>-.---.--------.+++++++++++.<+++++++++++++++++.>-----.<<<<.>....>>>++++++++++++++.<<<<.>........>>>--------.+.<.>.<++++++++.------.<<.>>>++.-------.<++++++.-----.<<.>++++++++++++++++++.>---.>------.+++++.<<<++++++++.>++++++.>>++++++.--.<++++++++.>----.<--.<++++++++.++.<--------.>++++.>>++++.<.>+.<<<+++++++++.<.>---------........>>>++++++++.<<<<.>............>>>--------.+.--.<++.>----.<--.<<.>>--.<<.+++++++++++++++++++++++++++++.<.++++++++++++++++++++++............++.>>>>---.+.<<+.-.>+++.+.-.++.>++.<-.-.+.-.>+.<++.+.+.----.>---.<.+.+.>++.<-.-.+.-.++.>.<<+.-.>-.>.<.++.--.++.-.>.<-.-.+.++.-.>.+.<<+.-.>--.+.-.++.>-.<-.++.--.++.+.----.++.+.+.----.>+.<.++.>-.<-.---.<.>++.>--.<.+.-.++.+.<+.-.>--.-.>.<++.>++.<-.>.<.-.>+.<++.>-.+.<--.>---.<.+.<++.--.>-.++.+.>.<<+.-.>---.>.<++.>++.<-.<+.-.>-.<+.-.>+.-.++.>.<-.<++++.----.>-.+.-.++.>.<++.--.>.+.<--.<++.--.>+.-.+.-.+.+.>-.<<+.-.>-.-.+.+.>.<-.-.>--.-.<+.+.>.+.++.<-.-.++.>.<-.++.--.-.<+.-.>+.+.>.<-.-.>--.<.>.<++.>++.<-.<++.--.>-.>--.<.+.+.>++.<<+.-.>-.++.+.----.+.>.<+.+.+.----.>+.<++.>-.<++.-.+.----.+.+.>.<++.>.<.--.+.+.<+++.---.>----.++.>.<<+.-.>-.++.+.-.>+.<-.>-.<<+.-.>-.-.<+.-.>+.+.>.<<+.-.>-.>.<.-.<+.-.>+.+.>.+.<--.>.<+++.>.<---.++.+.+.----.>---.<.+.+.>++.+.<--.>.<.>.<+++.-.>-.<-.<+.-.>-.++.+.+.-.-.>.<-.-.>--.<++.>++.<<+.-.>-.<++.--.>-.+.>.<+.+.<+++.---.>--.-.++.>.+.<--.>.<+++.>.<---.++.+.+.-.+.--.+.+.-.-.>-.<-.>.<.-.+.+.>.+.<--.++.+.+.<++.--.>----.++.>-.<-.-.>+.<++.+.+.----.++.>-.<++.>.<---.-.++.+.+.<+.-.>----.+.+.+.+.----.+.-.>--.<++.>++.+.<<+.-.>--.>---.<++.+.>+++.<-.>-.<<+.-.>-.-.+.+.>.<-.<+++.---.>-.+.++.--.>.<+.+.>+.<---.+.-.++.>-.<-.++.>+.<---.++.>-.+.<<+.-.>--.+.-.++.>-.<-.++.+.----.+.++.-.+.>+.<.-.>-.<++.>.<.--.+.>+.<---.>---.<++.>++.+.<--.>.<+++.>.<---.++.>-.+.<--.>.<+++.<+.-.>--.+.>-.<<+.-.>-.>.<<+.-.>.++.-.>.<-.++.--.-.<+.-.>+.+.>.<-.<++.--.>-.>--.<++.>++.+.<--.---.<.>++++.-.+.+.>-.<++.>.<--.>.<-.---.<.>++.>--.-.<+.+.>+++.<-.-.++.>.<<+.-.>-.-.>--.<++.>++.<-.>.<.-.+.+.>.<-.---.<.>++.+.-.>--.<.++.>++.<-.++.--.-.+.-.++.+.+.<+.-.>----.+.-.++.+.+.>.<--.>.+.<--.>---.<.+.-.+.>++.<+.>.<++.----.+.+.>.<-.-.>--.-.<+.-.>-.<<+.-.>.>.++++.+.<.---.<.>++++.-.+.+.>-.<++.>.<--.>.+.<--.<++.--.>+.-.>.<++.>-.<-.-.+.-.++.>.<-.++.--.-.>+.<.++.>-.<<+.-.>-.<++.--.>-.+.++.--.+.+.>+.<.--.-.++.>-.<-.-.>--.-.+.<++.>++.<<+.-.>-.>.<.++.+.----.++.>.+.<--.>---.<.<++.--.>+.-.++.+.>.++.<+.--.>.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<-.<+.-.>-.++.>.<-.>.--.++.<+.>.+.<--.>.<<+++.---.>.++.>-.+.<--.>---.-.<<++.--.>+.+.>+++.<++.----.>--.<.+.+.>++.<-.++.--.++.+.--.>.<-.++.--.>.--.<+.>++.+.<--.>.<.>.<+++.-.+.+.----.+.+.>-.<-.---.<.>++.+.<+.-.>-.++.+.<++.--.>--.-.+.+.>.<-.++.>+.<---.++.>-.<<++++.----.>-.++.-.>.<-.-.+.<++.--.>-.+.+.+.+.<++.--.>----.+.+.>.<-.>.<.-.>+.<++.>-.<-.<++.--.>-.+.-.++.>.+.<--.+.++.+.--.>-.+.<--.>.<.>.<+++.-.>-.+.<--.---.<.>++++.-.+.+.+.+.----.+.++.-.+.<++.--.>--.+.>-.<<+.-.>-.-.+.++.--.>.<.+.>.<-.-.+.++.--.>.<+.+.+.-.-.>.<<+.-.>-.++.+.----.+.++.--.+.+.<+.-.>--.-.+.+.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.+.+.<+++.---.>----.++.>.<<+++.---.>-.-.>+.-.<++.>.<<+++.---.>-.-.>--.<.+.-.+.+.>++.<<+.-.>-.<++.--.>-.+.>.<+.>.<-.-.+.-.++.>.<<++.--.>-.++.+.--.>.<<+.-.>-.-.+.+.>.<-.---.<.>++.+.-.+.++.-.>.+.<--.+.++.-.>-.<-.<++++.----.>-.+.-.++.+.+.>.<--.+.+.>.<--.+.+.<+++.---.>----.++.>.+.<--.>---.<.>+++.<.>---.<++.>++.<-.-.+.++.--.-.++.>.<-.++.--.>.<+.>.<-.>.--.++.<+.>.<<+.-.>-.<++.--.>-.+.>.<+.>.<-.<++.--.>-.+.+.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.<<+.-.>-.++.--.-.+.-.+.++.-.>.<-.>.<.++.>+.<-.>-.<-.>.--.++.<+.>.<<+.-.>-.>.<.-.<+.-.>+.+.>.<-.-.>--.<++.>++.<-.---.<.>++.>--.<.+.-.++.>++.<<+.-.>-.<+++.---.>-.>--.<.++.>++.<-.++.--.++.+.--.+.+.----.>--.-.-.+.+.++.<+.++.-.>.<-.---.<.>++.+.>.<.+.+.+.<+.-.>----.>--.<++.>++.+.<--.+.++.+.--.>-.<++.----.+.+.+.>+.<.-.+.>.<-.>-.<<+.-.>-.>.<.>.--.<+.>++.<-.++.>+.<---.++.>-.+.<--.>---.<.+.>-.+.<-.++.>++.<-.-.+.++.--.++.--.+.+.+.----.+.-.+.-.++.>.<<+.-.>-.>.<.-.>+.<.++.>-.+.<<+.-.>--.>---.<++.>++.<<++++.----.>-.++.-.+.<+.-.>--.>.<+.>.<-.---.<.>++.+.++.+.--.+.<+++.---.>--.+.>.<-.-.+.++.>+.<-.>-.<-.-.<+.-.>+.++.-.>.<-.<+.-.>-.+.-.++.>.<<+.-.>-.-.+.-.++.>.<-.++.+.--.>.<<+.-.>-.>.<.++.--.-.+.+.>.+.<--.<+.-.>+.>-.--.<+.+.>.<---.+.-.++.>++.<-.-.+.-.+.+.>.<<+.-.>-.<++.--.>-.+.>.<+.+.+.----.<+.-.>+.+.+.+.----.+.+.+.+.----.+.>.<+.>.<++.----.>--.-.-.++++.+.<+++.--.-.>---.<++.>++.+.<--.<++.--.>+.++.+.--.>-.<++.-.-.>.<<+.-.>-.-.+.<++++.----.>-.++.>.+.<--.<+.-.>+.>-.<.-.++.>.<<+.-.>-.>.<.++.+.----.++.+.+.<+.-.>----.>--.<++.>++.+.<--.<++.--.>+.-.>---.<.++.+.<+++.---.>--.+.>++.+.<<+++.---.>--.++.>-.<<+.-.>-.-.+.-.++.+.<++.--.>--.-.+.+.>.<<+.-.>-.-.+.-.++.>.<<+.-.>-.>.<.-.>+.<.++.>-.+.<--.>---.-.<<+.-.>+.-.>-.++++.<+.++.--.-.>--.<.+.+.+.>.++.<+.--.>.+.<--.>---.<.+.-.+.>-.<.+.>+++.<<+.-.>-.<+++.---.>-.>--.<.++.+.>.<.--.>-.<+.>+++.<<+.-.>-.>.<.++.+.----.++.>.<-.++.--.-.++.>.+.<--.++.>-.+.<--.---.<.>++++.++.-.>-.<-.-.+.++.--.++.--.+.>.+.<--.>.<<++.--.>.+.+.>-.<-.++.--.-.+.++.-.+.>+.<---.+.-.++.>-.<-.<+.-.>-.<+.-.>+.-.++.+.+.<+++.---.>----.++.>.<-.++.--.-.>--.<.+.+.>++.<-.>.--.-.<+.>+++.<<+.-.>-.>.<.++.>+.<-.>-.+.<--.>---.-.<<++.--.>+.+.>+++.<-.>.<.+.>.<-.>.<.-.+.+.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.<-.-.+.+.>.<++.----.>+.<+++.-.>-.+.<--.-.<.>++.+.>-.<-.++.--.-.<+.-.>+.+.>.<++.>.<--.>.<-.---.<.>++.+.-.+.++.-.>.<-.>.<<+.-.>.++.-.+.>+.<---.+.+.>-.<<+.-.>-.<+.-.>-.>--.<.+.-.++.+.<+.-.>--.+.+.<++.--.>--.+.>++.<-.++.+.----.+.++.-.>.+.<+.--.-.+.-.++.+.+.<+.-.>----.+.-.++.+.+.>-.<--.>.<-.---.<.>++.+.-.>--.<.++.>++.<-.<++.--.>-.+.-.++.>.<-.++.--.>.--.<+.+.>.<---.+.-.++.>++.+.<--.>---.<.+.-.+.>-.<.+.>+++.<++.>.<---.-.++.+.+.----.+.-.>--.<++.>++.<-.++.--.+.+.+.>.<--.+.+.>.<--.>.<<+.-.>-.-.+.-.++.>.<-.---.<.>++.+.-.+.++.-.>.<-.<+++.---.>-.+.++.--.>.<+.>.<-.++.+.--.>.<-.---.<.>++.+.-.>+.<++.>-.+.<--.>---.<.+.>-.++++.<+.>-.<-.-.+.-.+.-.+.+.>.+.<<+.-.>--.+.-.++.+.<++.--.>--.-.+.+.>-.<-.>.--.++.<+.+.>+.-.<--.+.>.<<++.--.>-.-.++.>.<-.---.<.>++.+.++.--.-.++.+.<+++.---.>--.+.>.<-.>.<.+.>.<++.----.>--.<.+.+.+.<+++.---.>--.-.++.>++.<++.----.>--.-.-.++++.<+.<+++.---.>-.+.++.--.>.<+.>.+.<--.--.<.>+++.-.++.>-.<-.-.+.++.--.>.<+.>.<-.++.--.-.++.+.>+.<---.+.-.++.>-.<-.---.<.>++.+.-.>--.<.++.>++.<-.++.>+.<---.++.+.>.<.--.+.+.>.<.--.+.+.+.----.>.<++.+.<+.-.>--.++.-.>-.+.<--.<++.--.>+.++.+.--.>-.<<+.-.>-.>.<.-.+.-.+.-.++.>.<-.<++++.----.>-.+.-.++.>.<<+.-.>-.++.+.-.>+.<-.>-.+.<--.<+.-.>+.>-.--.<+.+.>.<---.>.-.-.+.++++.<.++.>-.+.<--.>.<.+.++.--.-.++.>-.<<+.-.>-.>.<.-.>+.<.++.>-.+.<--.<+.-.>+.>-.--.<+.>++.<++.----.>+.<+++.-.>-.<-.<+++.---.>-.+.++.--.>.<+.+.>+.<---.++.>-.+.<--.>.<+++.>.<---.++.+.+.----.>.<.++.>-.<-.++.--.-.>+.<.++.>-.<-.++.--.+.>.<<+.-.>-.-.+.++.--.<+.-.>-.++.+.+.----.+.>.<+.+.>+.-.<--.+.+.<+.-.>--.++.--.+.>.<<+.-.>-.>.<.-.>+.<.++.+.+.----.<+.-.>+.+.>-.+.<--.--.<.>+++.-.++.>-.<++.----.++.>.<<+.-.>-.++.--.-.+.-.+.++.-.>.+.<+.--.-.>---.<++.>++.+.<--.---.<.>++++.-.+.+.>-.<-.>.<.++.>+.<-.>-.+.<--.>.<+++.<+.-.>--.+.+.>.<---.>.<++.>-.+.<--.<+.-.>+.>-.--.<+.>++.<++.----.>--.<.>.<++.>++.+.<--.-.<.>++.+.>-.+.<--.>.<+++.<+.-.>--.+.>-.<<+.-.>-.++.+.----.+.++.--.+.>.<-.-.+.>.<.+.+.>+.-.<--.+.+.<+.-.>--.-.+.+.>.+.<<++.--.>--.+.+.>-.<-.++.--.>.<+.>.+.<--.<++.--.>+.-.+.++.-.>-.+.<--.>---.<.>+++.<.>---.<++.+.>.<---.>.<++.+.<+.-.>--.>-.<.+.>+++.+.<--.>---.<.+.>-.+.<-.++.>++.<<++.--.>-.++.+.--.>.<-.-.>--.-.<+.+.>.<<+.-.>-.-.+.-.>-.+.+.<.>.<.+.+.+.<++.--.>--.-.+.+.>++.+.<--.>.<<++.--.>.+.+.>-.<<+.-.>-.-.>--.<++.>++.<-.<+.-.>-.>--.++.<++.>.<-.---.<.>++.+.++.--.-.++.+.>+.<---.++.>-.<++.-.+.-.-.+.+.<+.-.>----.++.>.+.<+.+.--.>-.<-.>.<<+.-.>.++.-.+.>+.<---.+.+.>-.<<+.-.>-.-.+.-.++.>.<-.++.<+.-.>--.+.>.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<-.++.--.++.--.++.-.+.+.>.<.--.>.+.<--.>---.<.<+++.---.>+.+.>++.+.<--.>---.-.<<+.-.>+.-.>-.++++.+.<<+++.---.>.++.>-.<<+.-.>-.>.<.++.>+.<-.>-.<-.++.--.-.++.>.<-.-.>--.-.<+.-.>-.++++.<+.---.<.>++.+.-.>+.<++.>-.<++.-.+.-.-.>.<<+.-.>-.<+++.---.>-.>--.<.++.+.>.<---.>.-.-.++++.+.<.>.<.+.++.--.-.++.>-.<<+.-.>-.<+++.---.>-.>--.<.++.+.<+.-.>--.-.+.-.++.+.>.<---.>.<.++.>++.<-.---.<.>++.>--.<.+.-.++.+.>.<---.>+++.<.++.+.+.-.--.-.+.+.>-.<<+.-.>-.>.<.-.>+.<.++.>-.<<+.-.>-.-.+.++.--.>.<.+.>.<-.-.>--.<.>.<++.>++.<++.>.<--.>.+.<--.>---.<.+.-.+.>++.<+.>.<-.<+.-.>-.+.-.++.>.<-.>.<.++.>+.<-.>-.<-.---.<.>++.>--.<.+.-.++.+.>+++.<-.>-.+.<--.<++.--.>+.++.--.-.++.+.+.----.+.++.--.+.>-.<<+.-.>-.-.+.<++++.----.>-.++.>.<-.-.++.>.<-.<+.-.>-.>--.++.<++.>.<-.<+.-.>-.<+.-.>+.-.++.+.<+.-.>--.-.+.-.++.+.+.-.+.----.++.>.<-.-.<+.-.>+.-.+.+.>.<-.---.<.>++.+.-.+.-.+.+.>.<-.+.>.<<+.-.>-.>.<.++.--.-.+.+.>.<-.---.<.>++.+.++.+.--.>.<-.-.>--.<.>.<++.>++.<-.++.--.++.--.++.-.>.+.<--.>---.<.+.-.+.>-.<.+.>+++.<-.-.+.>.<.+.>.<-.>.--.++.<+.+.+.>.<---.-.++.+.<+.-.>--.++.-.+.>+.<---.+.+.+.<+.-.>--.-.+.+.>-.<++.----.>+.<+++.-.>-.<++.----.>--.-.-.++++.<+.-.>--.<.>.<++.>++.<-.-.<+.-.>+.++.-.>.+.<--.<++.--.>+.-.+.++.-.>-.+.<--.--.<.>+++.-.++.+.+.----.+.-.>---.<++.>++.<-.-.+.-.+.-.+.+.+.+.>.<---.+.>.<-.>.<<+.-.>.++.-.+.+.--.>.<-.-.>--.<<+++.---.>.+.-.+.-.++.>++.<<+.-.>-.>.<.>.--.<+.>++.+.<--.>---.<.<+++.---.>+.+.>++.<-.---.<.>++.+.>.<.+.>.<<+.-.>-.+.>.+.<--.<+.-.>+.<++.--.>-.++.>-.<<+.-.>-.>.<.-.+.-.+.-.++.+.<+.-.>--.-.>--.<++.>++.<-.++.+.----.+.++.-.>.<-.---.<.>++.+.<+.-.>-.++.>.+.<--.+.++.-.>-.<-.-.+.++.+.----.++.>.<<+.-.>-.>.<.++.--.-.+.+.>.<-.++.--.-.+.-.++.+.>+.<---.+.++.-.>-.<<+.-.>-.++.+.-.+.----.++.+.+.-.--.+.+.>+.<---.++.>-.<++.-.+.----.+.+.+.+.<+++.---.>----.++.>.<-.++.+.----.+.-.+.+.>.<<+++.---.>-.+.>.+.<+.+.--.>-.+.<--.>.<<+++.---.>.++.>-.<<++.--.>-.++.+.--.>.+.<--.--.<.>+++.-.++.>-.<<+.-.>-.++.+.-.+.----.++.>.+.<--.>.<.>.<.+.+.>-.<<+.-.>-.>.<.>.--.<+.+.>.++.<--.++.-.>.+.<--.>.<.++.>-.<-.<++.--.>-.>--.<++.>++.<-.---.<.>++.+.++.+.--.>.<-.>.+.<-.+.+.+.+.>-.<---.-.++.>.+.<<+.-.>--.+.-.++.>-.+.<+.--.-.+.-.++.+.+.-.--.-.+.+.>-.<-.+.>.<-.++.+.----.+.++.-.+.>+.<---.>.<++.>-.<<+.-.>-.++.+.-.+.----.++.+.+.>.<.--.>.+.<--.>---.<.+.<+.-.>-.+.+.+.>+++.<---.>.<++.>-.<-.-.+.<+++.---.>-.++.>.<++.----.>--.<.+.+.>++.+.<--.---.<.>++++.-.+.+.>-.<++.-.-.>.<-.-.+.++.>+.<---.++.+.+.-.--.-.++.>-.<++.>.<.--.>.<-.<+.-.>-.+.-.++.>.<<+.-.>-.<+.-.>-.>--.<.>.<++.>++.<-.-.+.++.+.----.++.>.<-.---.<.>++.+.<+.-.>-.++.>.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<-.>.--.++.<+.>.<-.<+.-.>-.<+.-.>+.-.++.>.<-.>.<+.>.<-.++.+.----.+.-.++.+.<+.-.>--.++.-.>.<-.++.--.-.++.>.<-.++.--.++.+.----.++.>.<-.<++.--.>-.>+.<.++.>-.<++.>.<.--.>.<-.<++.--.>-.>--.<++.+.>.++.<+.--.>.+.<--.>---.<.>+++.<.+.-.++.>-.<++.--.>.<-.++.>+.<---.++.+.>.<.+.--.>-.<<+.-.>-.++.+.----.+.>.<+.>.<<+.-.>-.-.+.++.--.>.<.+.>.<-.-.+.+.>.<<++.--.>-.-.++.+.+.-.--.+.>.<<+.-.>-.>.<.-.>+.<.++.+.+.----.<+.-.>+.+.>-.<-.++.--.-.+.++.-.>.+.<--.>.<.<++.--.>+.+.>-.<-.<++.--.>-.>--.<.+.+.+.<+.-.>--.+.>++.+.<--.<++.--.>+.-.>.<++.+.+.<+.-.>----.+.+.>-.+.<--.-.<.>++.+.+.<++.--.>--.-.+.+.>-.<++.--.+.<+++.---.>--.+.+.+.----.+.++.--.+.+.>+.<.--.-.++.>-.<-.---.<.>++.+.-.>--.<.++.>++.<-.<++.--.>-.>+.<.++.>-.<<+.-.>-.<+.-.>-.>--.<.>.<++.+.>+++.<---.+.-.+.+.>-.+.<--.<+.-.>+.<+.-.>-.+.+.+.+.>-.<--.+.+.>.<--.>.+.<--.<++.--.>+.++.--.-.++.+.+.<+++.---.>----.++.>-.<-.>.<<+.-.>.++.-.+.+.----.>+.<.++.>-.+.<--.>.<<++.--.>.+.+.>-.<<+.-.>-.-.+.+.>.+.<--.>---.<.<++.--.>+.-.++.>++.<-.++.<+.-.>--.+.>.+.<--.>---.<.+.<+.-.>-.+.+.>++.<<+.-.>-.++.+.----.+.++.--.+.>.+.<--.>---.-.<<+.-.>+.-.>-.++++.<+.>.<<+.-.>.++.-.>.+.<--.>.<.>.<+++.-.>-.<-.++.--.-.<+.-.>+.+.>.<<+.-.>-.++.+.----.+.>.<+.+.>+.<.--.+.>-.<-.<+.-.>-.+.-.++.+.>+.<.--.-.++.>-.+.<--.>.<+++.<+.-.>--.+.+.+.-.--.++.-.>-.<<+.-.>-.>.<.-.>+.<.++.>-.+.<<+.-.>--.+.-.++.>-.<-.---.<.>++.+.-.+.-.+.+.>.<<+.-.>-.++.+.----.+.>.<+.>.+.<<+.-.>--.>---.<++.>++.<-.>.<+.>.<-.-.+.<++.--.>-.+.+.>.<-.>.<+.>.<-.<+.-.>-.<+.-.>+.-.++.>.<<+.-.>-.++.+.----.+.>.<+.>.<<+.-.>-.<+++.---.>-.>+.<++.>-.<-.-.+.-.+.-.+.+.>.<-.++.+.-.-.>.+.<--.>.<.+.++.+.--.>-.<<+.-.>-.<+++.---.>-.>+.<++.+.+.>-.<---.-.++.+.+.<+.-.>----.>--.<++.>++.+.<--.>.<+++.>.<---.++.+.+.-.--.-.+.+.+.+.-.+.--.>-.<-.-.++.>.<-.++.+.----.+.-.+.+.+.>+.<.-.>-.+.<--.>---.<.+.>-.++++.<+.>-.+.<--.>---.<.<+++.---.>+.+.>++.+.<--.>---.<.+.<+.-.>-.+.+.>++.<<+.-.>-.>.<.++.+.----.++.>.<<+.-.>-.+.>.<-.++.+.----.+.-.+.+.>.+.<.>-.+.<--.>.<.<+.-.>+.-.++.+.+.----.+.-.+.+.>-.<-.-.<+.-.>+.-.+.+.>.+.<--.>.<.>.<+++.-.>-.<-.>.<.-.>+.<++.>-.<<+.-.>-.<+++.---.>-.>+.<++.>-.<-.++.--.++.--.++.-.>.+.<--.>.<+++.>.<---.++.>-.<++.--.>.+.<--.<++.--.>+.++.+.--.>-.<++.>.<.--.>.+.<.>-.+.<<+++.---.>--.++.+.<+++.---.>--.-.++.>-.<<+.-.>-.>.<.++.--.++.-.>.<-.<++.--.>-.>+.<.++.+.>.-.<-.>.<-.>.--.-.<+.>+++.<-.<+.-.>-.+.-.++.>.<-.>.<.-.+.+.>.+.<--.>.<.>.<+++.-.+.+.----.>---.-.-.+.<<+.-.>+.>.<+.>+++.+.<<+++.---.>--.++.>-.<-.<++.--.>-.>--.<++.>++.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.<-.>.+.<-.+.+.>-.+.<--.>.<.>.<.+.+.+.<+++.---.>--.+.>-.<++.-.+.-.-.+.+.-.+.--.+.+.>.<---.++.-.>.<<+.-.>-.>.<.-.+.-.>--.<++.+.>.<---.>+++.<.++.>-.<<+.-.>-.>.<.>.<.-.++.>.<-.---.<.>++.+.<+.-.>-.++.+.>+.<---.>---.<++.>++.<<+.-.>-.-.+.++.--.>.<.+.>.<-.++.--.+.+.+.-.--.-.++.>.<-.<+.-.>-.++.>.<-.---.<.>++.+.++.+.--.+.<++++.----.>--.+.>.<<+.-.>-.-.>--.<++.>++.<-.-.<+.-.>+.-.+.+.>.<<+.-.>-.>.<.-.+.-.>--.<++.>++.<-.-.+.++.--.>.<+.>.+.<--.<++.--.>+.-.>.<++.+.>.<.--.-.++.>-.<-.-.>--.-.+.<++.>++.+.<--.>.<.>.<+++.-.>-.<-.++.--.-.>--.<.+.+.+.>.<.--.-.+.+.>++.+.<--.>.<.<++.--.>+.+.+.>.<---.>---.<++.<+.-.>--.++.>++.<<+.-.>-.++.+.----.+.>.<+.+.+.>.<---.-.++.>.+.<--.>---.<.<+++.---.>+.+.>++.+.<+.--.-.>---.<++.>++.+.<<+++.---.>--.++.>-.<<+.-.>-.+.>.+.<--.>.<.>.<.+.+.>-.<++.----.+.+.>.+.<--.<++.--.>+.-.+.-.+.+.>-.<-.-.>--.-.<+.+.>.+.<--.>.<.++.>++.<-.>.<.+.>.<-.<++.--.>-.>--.<++.+.>+++.<.--.-.++.+.<+.-.>--.+.>-.+.<.>-.+.<--.--.<.>+++.-.++.>-.<-.++.+.----.+.-.+.+.>.<-.-.+.<++.--.>-.+.+.>.<-.---.<.>++.+.++.--.-.++.>.<<+.-.>-.-.+.++.--.<+.-.>-.++.>.<-.-.+.-.++.>.+.<--.<++.--.>+.-.>---.<.++.+.<+++.---.>--.+.>++.<-.>.+.<-.+.+.>-.+.<--.>.<.++.>-.+.<--.>---.<.>+++.<.+.-.++.>-.<-.>.<.+.>.<<++++.----.>-.++.-.>.<<++.--.>-.++.+.--.+.+.----.+.-.++.+.+.----.+.-.>--.<++.>++.+.<--.>---.-.<<++.--.>+.+.>.+.<--.+.-.+.+.>++.<-.++.+.--.>.<-.-.>--.<.>.<++.>++.<<+.-.>-.>.<.++.--.-.+.+.+.+.----.+.-.+.-.++.>.<-.---.<.>++.+.++.+.--.>.<<+.-.>-.++.+.----.+.>.<+.>.+.<--.++.+.<+.-.>--.++.-.+.<+.-.>--.+.>-.+.<--.>---.<.+.>-.+.<-.++.>++.<-.-.+.-.++.+.<+.-.>--.-.++.+.<+.-.>--.+.+.+.-.--.-.+.+.+.+.<++.--.>----.+.+.>.<-.-.<+.-.>+.++.-.>.<-.---.<.>++.+.>.<.+.>.<-.-.+.++.+.----.++.+.+.-.--.-.++.>.<-.>.<+.+.+.----.+.+.+.<++++.----.>--.+.>.<-.-.+.++.--.-.++.>.<-.<+.-.>-.+.-.++.+.+.-.--.+.>.+.<--.>.<.<+.-.>+.-.++.>-.+.<--.>---.-.<<+.-.>+.-.>-.+.+.++.<+.+.>.<<+.-.>-.>.<.-.+.-.>--.<++.>++.<-.++.--.-.>+.<.++.>-.<-.<++.--.>-.>--.<++.+.>.<---.+.-.>.<++.>++.<-.++.+.-.-.>.<-.++.+.-.-.>.<<+.-.>-.++.+.-.+.----.++.+.>+.<.--.+.>-.<-.>.<.-.+.+.>.+.<+.--.-.+.-.++.>-.<<++.--.>-.++.+.--.>.<-.>.<<+.-.>.++.-.+.>+.<---.>.<++.>-.<-.-.++.>.<-.>.<.++.>+.<-.>-.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.<-.---.<.>++.+.++.--.-.++.>.<<+.-.>-.++.+.-.+.----.++.+.+.----.<+.-.>+.+.>.<-.---.<.>++.+.>.<.+.+.>+.<---.+.-.++.+.+.----.>.<.++.>-.<-.-.>--.-.<+.+.>+++.<<++++.----.>-.++.-.>.+.<--.>---.<.>+++.<.>---.<++.+.<++.--.>--.+.>++.<++.----.>+.<+++.-.+.+.<+.-.>----.+.+.+.>.<---.+.+.>-.<<+.-.>-.>.<.-.+.-.+.-.++.+.<+.-.>--.-.+.-.++.>.<++.>.<.--.>.<-.-.>+.<++.>-.<<+.-.>-.<+++.---.>-.>+.<++.+.+.>-.<.--.>.+.<--.<++.--.>+.++.+.--.>-.<-.++.--.>.<+.>.<-.>.+.<-.+.+.>-.<-.---.<.>++.+.++.--.-.++.+.+.>.<---.+.>.<<+.-.>-.-.+.-.++.>.<-.-.>--.-.+.<++.>++.<-.++.--.-.+.-.++.>.+.<--.>.<.<++.--.>+.+.>-.<-.>.--.++.<+.>.+.<--.>.<<+++.---.>.++.>-.<-.-.+.++.-.>.+.<--.-.<.>++.+.>-.+.<--.+.++.+.--.>-.<-.++.+.----.+.-.++.>.<-.++.--.++.+.----.++.>.+.<--.---.<.>++++.++.-.>-.+.<--.>.<+++.<+.-.>--.+.>-.<-.++.--.+.>.<-.---.<.>++.>--.++.<++.>.<-.---.<.>++.+.++.--.-.++.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.<<+.-.>-.>.<.++.>+.<-.>-.+.<--.>.<.<+.-.>+.-.++.>-.<-.++.+.----.+.++.-.>.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<-.<+.-.>-.<+.-.>+.-.++.>.+.<<+.-.>--.+.-.++.>-.<<+.-.>-.>.<.-.+.-.>--.<++.>++.<++.-.+.-.-.>.+.<--.>---.<.+.>-.++++.<+.>-.+.<--.>---.<.+.<+.-.>-.+.+.+.<+.-.>--.+.>++.<<+.-.>-.-.+.-.++.>.<-.<+.-.>-.++.+.>+.<.--.+.+.+.>-.<---.+.>.<-.-.>--.-.+.<++.>++.<<+.-.>-.++.+.-.+.----.++.>.<++.----.++.>.<-.---.<.>++.+.++.+.--.>.<<+.-.>-.>.<<+.-.>.-.+.+.+.+.--.+.+.>.<---.++.-.+.>+.<---.+.-.+.+.>-.<<+.-.>-.>.<.++.>+.<-.+.+.----.>.<.++.>-.<-.++.-.>.<-.-.+.<++.--.>-.+.+.>.<<+.-.>-.-.+.++.--.<+.-.>-.++.>.+.<--.<+.-.>+.>-.--.<+.+.>.<.>+++.<-.>-.<-.<+.-.>-.++.>.+.<--.<++.--.>+.-.>.<++.>-.<++.----.+.-.++.>.+.<<++.--.>--.+.+.>-.+.<--.>.<.++.>-.<-.-.+.++.>+.<---.++.+.+.----.+.>-.<+.+.<+++.---.>--.-.++.+.>+.<---.+.-.++.>-.<-.-.+.-.+.-.+.+.>.<<+.-.>-.+.>.<<+.-.>-.++.+.----.+.++.--.+.+.<++.--.>--.++.-.+.+.----.+.>.<+.+.+.<++.--.>----.+.+.+.+.>.<--.+.+.>.<--.>.<-.++.-.>.+.<.>-.<++.-.--.+.+.<+++.---.>--.-.++.>.<<+.-.>-.++.+.----.+.>.<+.>.<<+.-.>-.-.>--.<++.>++.<-.-.>+.<++.>-.<-.++.<+.-.>--.+.>.<-.++.--.-.+.-.++.+.<+.-.>--.++.--.+.>.<++.-.--.+.+.+.-.--.-.+.+.>.+.<--.>.<.>.<+++.-.+.>.-.<-.>.<-.>.<.++.>+.<-.>-.<++.----.++.+.+.-.+.--.+.+.<+.-.>----.+.+.>.+.<--.>---.<.<++.--.>+.-.++.>++.<++.--.>.+.<--.+.++.-.+.>.<.+.--.>-.<<+.-.>-.<++.--.>-.+.>.<+.>.<-.-.>--.<++.>++.<<+.-.>-.++.+.----.+.>.<+.>.<-.++.--.-.<+.-.>+.+.>.<-.++.<+.-.>--.+.+.>+.<.--.-.++.>-.+.<+.--.-.+.-.++.>-.<-.>.<+.+.+.<++.--.>----.++.>.<-.<++++.----.>-.+.-.++.>.<-.-.>--.<++.>++.<-.---.<.>++.+.-.+.++.-.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.+.<--.>---.-.<<+.-.>+.-.>-.++++.<+.---.<.>++.+.-.>--.<.++.+.<+.-.>--.>-.<.+.>+++.+.<--.>---.<.<+++.---.>+.+.+.>.<---.<+.-.>+.+.>++.<<+.-.>-.++.+.-.>+.<-.+.+.>-.<.--.+.+.----.>+.<++.>-.+.<--.>.<.>.<.+.+.>-.<-.++.--.-.>+.<.++.>-.<-.-.+.++.-.>.<-.<++.--.>-.+.+.+.+.-.--.-.+.+.>.<-.++.--.++.+.--.>.<-.---.<.>++.>--.++.<++.>.<-.-.+.++.--.++.--.+.>.<-.++.--.>.<+.+.+.-.--.-.++.<+.-.>--.++.>.+.<--.>---.<.>+++.<.>---.<++.>++.<-.>.<.-.>+.<++.>-.+.<--.>.<.>.<.+.+.>-.+.<.+.>.<---.>---.<++.>++.+.<.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.+.+.----.>+.<.++.>-.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<-.---.<.>++.+.-.>--.<.++.>++.+.<--.<++.--.>+.-.+.++.-.>-.<-.++.--.++.+.--.+.+.----.+.+.>.<-.<++.--.>-.+.+.>.<-.++.+.-.-.>.<-.---.<.>++.>--.<.+.-.++.>++.<<+.-.>-.+.>.<-.++.--.-.<+.-.>+.+.>.+.<--.---.<.>++++.++.-.>-.<<+.-.>-.++.+.-.+.----.++.>.+.<--.>.<.+.++.+.--.>-.<-.-.<+.-.>+.-.+.+.>.+.<--.<+.-.>+.>-.--.<+.>++.<-.++.--.-.<+.-.>+.+.>.+.<--.>---.<.+.<+.-.>-.+.+.>++.+.<+.--.-.>---.<++.+.<+++.---.>--.-.++.>++.<-.-.>--.-.<+.-.>-.++++.<+.<+.-.>-.<+.-.>+.-.++.+.+.>.<---.-.++.+.+.<+.-.>----.+.-.++.+.+.>.<--.+.<+.-.>--.++.-.>.<-.++.--.-.>--.<.+.+.<+.-.>--.++.>++.<<+.-.>-.>.<.++.>+.<-.>-.<-.-.+.++.>+.<---.++.>-.+.<+.+.--.+.+.----.+.>-.<+.>.+.<--.<++.--.>+.-.+.-.+.+.>-.<-.++.+.----.+.-.+.+.+.+.-.--.++.-.>.<-.++.--.-.++.+.>+.<.--.-.++.>-.<-.-.>--.<.>.<++.>++.<-.-.>--.-.<+.+.>+++.<-.<++.--.>-.>--.<++.>++.+.<--.-.<.>++.+.+.<+.-.>--.-.>---.<++.>++.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.----.>--.<++.>++.<-.-.>+.<++.>-.<-.-.+.++.--.>.<+.>.<-.++.--.++.+.----.++.>.<-.<++.--.>-.+.+.>.+.<--.>---.<.+.-.+.>-.<.+.>+++.<-.+.>.<-.<++.--.>-.+.+.>.<-.++.--.++.+.--.+.>+.<---.>---.<++.>++.<<+.-.>-.++.--.-.+.-.+.-.+.+.+.>+.<.--.+.>-.<-.++.--.>.--.<+.>++.<<+++.---.>-.+.>.<-.>.<.-.+.+.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.+.<--.+.++.+.--.>-.<<+.-.>-.<+.-.>-.>--.<.>.<++.>++.<-.>.--.++.<+.>.+.<--.---.<.>++++.++.-.>-.<-.---.<.>++.+.-.>+.<++.>-.<-.---.<.>++.+.-.+.++.-.>.+.<+.+.--.>-.<<++.--.>-.-.++.>.<<+.-.>-.<+++.---.>-.>+.<++.>-.<-.---.<.>++.+.-.+.++.-.>.+.<--.>---.<.+.-.+.>-.<.+.>.+.++.<-.++.-.>.<-.++.--.++.+.--.>.+.<--.<++.--.>+.++.+.--.>-.<-.+.>.<-.>.<<+.-.>.++.-.>.<-.-.+.++.--.-.++.+.+.----.+.-.+.+.>.<++.----.>+.<+++.-.>-.<-.-.>--.<<+++.---.>.+.-.+.-.++.>++.<-.++.--.>.--.<+.>++.<-.-.>--.-.<+.-.>-.++++.<+.++.--.++.--.++.-.>.+.<--.<+.-.>+.<++.--.>-.++.>-.+.<--.>---.<.+.>-.++++.<+.>-.<-.++.--.-.+.++.-.+.+.--.>.<<+.-.>-.++.+.----.+.>.<+.>.<<+.-.>-.>.<.>.--.<+.>++.+.<--.<+.-.>+.+.>-.<++.-.-.>.<<+.-.>-.>.<.++.+.----.++.>.<-.---.<.>++.+.>.<.+.>.+.<--.>---.<.>+++.<.>---.<++.>++.<++.>.<.--.+.>+.<.+.--.>-.<-.-.>--.-.<+.-.>-.++++.+.<.<++.--.>+.-.+.++.-.>-.<-.++.--.+.>.<<+.-.>-.<++.--.>-.+.++.--.+.>.<-.++.--.-.++.+.+.<+++.---.>----.++.+.+.<+.-.>----.>--.<++.>++.<-.-.+.++.--.++.--.+.>.<-.>.<<+.-.>.++.-.>.+.<--.++.>-.+.<--.<+.-.>+.>-.--.<+.>++.<<+.-.>-.++.--.-.+.-.+.++.-.>.<<+.-.>-.-.+.+.>.+.<--.>---.<.+.<++.--.>-.++.>++.<<+.-.>-.-.+.<+++.---.>-.+.+.>.+.<--.>---.<.+.-.+.>-.<.+.>+++.<<+.-.>-.>.<.>.--.<+.>++.<-.-.+.++.--.>.<+.>.<-.-.+.++.>+.<---.++.+.<++++.----.>--.+.+.<++++.----.>--.+.+.<+++.---.>--.-.++.+.+.>-.<--.+.+.>.<--.>.<-.++.-.>.<++.-.+.----.+.+.>.<<+.-.>-.>.<.>.<.-.++.>.<<+.-.>-.+.+.+.----.+.-.>--.<++.>++.+.<--.>.<<++.--.>.+.+.>-.<<+.-.>-.++.+.----.+.>.<+.+.<+++.---.>--.-.++.>.<-.---.<.>++.+.<+.-.>-.++.+.+.>.<---.-.++.>.<<+.-.>-.<++.--.>-.+.++.--.+.>.+.<--.--.<.>+++.-.++.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.+.>+.<---.>.<++.>-.<-.++.+.--.+.<++.--.>--.-.+.+.>.<-.---.<.>++.>--.<.+.-.++.>++.<++.-.-.>.+.<+.+.--.>-.+.<--.>.<.+.++.+.--.>-.<-.++.+.----.+.-.+.+.>.<<+.-.>-.<+++.---.>-.>--.<.++.>++.<-.-.+.++.>+.<---.++.>-.<-.-.+.++.--.++.--.+.>.<++.>.<---.-.++.>.<-.-.+.>.<.+.>.<-.++.>+.<.--.+.>-.<<+.-.>-.>.<.++.--.-.+.+.>.<++.----.>--.-.-.++++.--.-.-.++++.<+.>.--.-.<+.>+++.<-.---.<.>++.+.<+.-.>-.++.+.>+.<---.+.-.++.>-.<<+.-.>-.>.<.-.>+.<.++.>-.+.<--.>---.<.+.<+.-.>-.+.+.>++.<-.---.<.>++.+.++.--.-.++.>.<++.----.+.+.+.<+.-.>--.++.-.+.<+.-.>--.++.--.+.>.<-.>.--.-.<+.>+++.<-.-.+.++.+.----.++.>.<++.--.>.<-.>.<<+.-.>.++.-.>.+.<--.<++.--.>+.-.+.-.+.+.>-.<-.<+.-.>-.++.>.<++.-.+.-.-.+.+.----.<+.-.>+.+.>.<++.----.>+.<+++.-.+.+.<+.-.>----.++.+.+.<+.-.>----.>---.<++.>++.<-.-.+.-.++.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.+.+.----.>--.-.-.++++.<+.---.<.>++.+.<+.-.>-.++.>.<<+.-.>-.-.+.+.>.<-.>.<+.+.>+.<.--.-.++.>-.+.<--.>---.<.+.<++.--.>-.++.>++.+.<--.>---.-.<<++.--.>+.+.>.++++.-.<-.+.>.<++.--.>.<-.-.>--.-.<+.-.>-.+.+.++.<+.-.++.+.+.<++.--.>----.++.+.+.----.+.++.-.>.<<+.-.>-.>.<.-.+.-.+.-.++.>.+.<--.>---.<.<++.--.>+.-.++.>++.<-.-.+.<++.--.>-.+.+.>.<<+.-.>-.>.<.++.--.-.+.+.+.+.-.--.-.++.>.+.<<+.-.>--.+.-.++.>-.<-.-.>--.-.<+.+.>.+.<+.>+++.<-.>-.<<+.-.>-.<+.-.>-.>--.<.+.-.++.+.>.<.-.>++.<++.-.-.>.<<+.-.>-.++.+.----.+.>.<+.+.+.>.<---.+.+.+.----.>+.<.++.>-.<-.---.<.>++.>--.-.<+.+.>.+.<--.>+++.<.++.+.+.----.>---.<++.>++.<<+.-.>-.++.+.-.>+.<-.>-.<<+.-.>-.++.+.-.>+.<-.>-.<-.<+.-.>-.+.-.++.>.<<+.-.>-.++.+.----.+.>.<+.>.<-.-.+.++.--.-.++.+.+.----.>--.-.-.+.+.<.>+++.<.++.+.+.-.-.+.<+.-.>--.++.--.+.>-.<++.-.-.>.<-.-.>+.<++.>-.+.<--.<++.--.>+.-.>.<++.>-.+.<--.>---.<.+.-.+.>-.<.+.>+++.+.<+.+.--.+.+.----.>---.<.+.+.>++.+.<--.>.<.<+.-.>+.-.++.>-.<-.>.<.-.+.+.>.<<+.-.>-.>.<.-.<+.-.>+.+.>.<-.>.<.-.>+.<++.>-.<-.>.--.++.<+.+.+.----.>--.<++.>++.<-.++.--.-.>--.<.+.+.>++.+.<+.--.-.+.-.++.>-.+.<--.<++.--.>+.++.+.--.>-.<-.<++.--.>-.+.+.>.<-.++.-.>.<<+.-.>-.++.+.----.+.++.--.+.>.<-.-.+.++.>+.<-.>-.<<+.-.>-.-.+.+.>.<<+++.---.>-.+.>.<++.>.<.--.+.<++.--.>--.-.+.+.>.+.<--.>---.<.>+++.<.>---.<++.+.>.<---.>.<.++.>++.<<+.-.>-.-.+.++.--.>.<.+.>.<-.-.+.++.--.>.<+.>.<-.-.+.++.+.----.++.+.+.>.<---.-.++.>.<-.++.--.>.<+.+.+.----.+.++.--.+.>.+.<--.>---.<.>+++.<.>---.<++.>++.<<+.-.>-.-.+.++.--.>.<.+.>.<-.-.+.-.+.-.+.+.>.<<+++.---.>-.+.>.<++.----.++.+.+.----.>--.<.+.+.+.>.<---.>+++.<.++.>-.+.<--.<+.-.>+.>-.<.-.++.>.<++.--.+.+.-.+.--.+.>+.<.--.+.>-.+.<--.>---.<.+.-.+.>-.<.+.>+++.+.<--.++.+.+.-.+.----.++.+.<+.-.>--.+.>-.+.<--.>.<<++.--.>.+.+.>-.<<++.--.>-.-.++.>.+.<--.>.<.>.<.+.+.+.+.----.+.>-.<+.+.+.-.+.----.++.>.+.<--.<++.--.>+.-.>---.<.++.>++.+.<--.>---.<.+.-.+.>-.<.+.>+++.<<+.-.>-.++.--.-.+.-.+.++.-.+.+.>.<---.++.-.>.<-.---.<.>++.+.++.+.--.+.+.----.>--.-.-.+.++++.<+++.-.>-.+.<--.>.<<++.--.>.+.+.>-.<++.-.+.----.+.+.>.<-.-.+.++.+.----.++.+.+.>.<---.-.++.+.+.-.-.>.<-.++.+.-.-.>.+.<--.<++.--.>+.-.+.++.-.+.>.-.<-.>.<-.---.<.>++.+.-.+.++.-.>.<-.---.<.>++.+.-.>--.<.++.>++.<-.>.<<+.-.>.++.-.+.+.<++.--.>----.++.>.<<+.-.>-.>.<.++.--.-.+.+.+.+.-.+.--.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.<-.++.--.>.<+.+.+.<+.-.>----.+.-.++.+.+.>.<--.+.+.<+.-.>----.+.-.++.+.+.>.<--.>.+.<--.>.<.+.++.--.-.++.>-.+.<--.>---.<.<++.--.>+.-.++.>++.+.<--.-.<.>++.+.>-.<<+.-.>-.++.+.-.>+.<-.>-.<-.<+.-.>-.>--.++.<++.>.<<+.-.>-.>.<.++.>+.<-.>-.+.<--.<++.--.>+.-.+.-.+.+.>-.<-.<+.-.>-.>--.++.<++.+.>+.<---.++.>-.+.<--.<++.--.>+.++.--.-.++.+.+.>-.<---.+.>.<-.---.<.>++.>--.-.<+.+.>+++.+.<--.<+.-.>+.+.>-.<-.>.<.++.>+.<-.>-.+.<--.>.<.<+.-.>+.-.++.>-.<-.>.<.-.>+.<++.+.+.----.+.++.-.>-.<-.-.++.+.+.<+.-.>----.+.+.>.<<+.-.>-.++.+.----.+.++.--.+.>.<-.-.++.>.<<+.-.>-.>.<.-.+.-.>--.<++.+.<++.--.>--.-.++.>++.<++.----.+.+.>.+.<--.>---.<.>+++.<.>---.<++.>++.+.<--.>.<<+++.---.>.++.+.>.<---.>.<++.>-.<++.>.<.--.>.<-.-.+.<++.--.>-.+.+.>.+.<--.---.<.>++++.-.+.+.+.+.----.+.-.++.>-.<-.++.--.-.+.++.-.+.<+.-.>--.-.+.+.>.<-.>.+.<-.+.+.>-.+.<--.>---.<.+.-.+.>++.<+.>.+.<--.--.<.>+++.-.++.>-.+.<--.<++.--.>+.++.--.-.++.>-.<-.++.--.-.+.-.++.>.+.<--.--.<.>+++.-.++.>-.<<+.-.>-.<++.--.>-.+.++.--.+.+.<+.-.>--.++.-.>.<<+.-.>-.>.<.>.<.-.++.+.+.----.+.-.++.>.<<+.-.>-.<++.--.>-.+.>.<+.+.+.----.+.++.-.+.+.----.+.>.<+.>.<<+.-.>-.++.+.-.+.----.++.>.+.<--.---.<.>++++.++.-.+.+.>-.<---.+.>.<++.----.++.>.+.<--.>.<.++.>-.+.<+.+.--.>-.<<+.-.>-.>.<.++.--.-.+.+.+.+.----.+.-.>--.<++.>++.+.<--.>---.<.+.-.+.>++.<+.>.<<++++.----.>-.++.-.+.<++.--.>--.++.-.+.+.--.>.<-.---.<.>++.>--.<.+.-.++.>++.<++.-.+.-.-.>.+.<+.--.-.+.-.++.>-.+.<--.>---.<.>+++.<.+.-.++.>-.<-.-.>+.<++.+.<++.--.>--.-.++.>-.<-.-.>--.<.++.>++.<-.<++.--.>-.>--.<.+.+.+.>.<---.>.<++.+.>.<---.+.>++.<+.>.+.<<+.-.>--.>---.<++.+.<+.-.>--.-.+.-.++.+.>.<---.+.>++.<+.>.<-.<+++.---.>-.++.+.+.--.>.<<+.-.>-.>.<.-.>+.<.++.+.+.-.--.+.>-.+.<--.+.++.+.--.+.>.<---.>.<++.>-.<<+.-.>-.>.<.++.+.----.++.>.<-.-.++.>.<<+.-.>-.-.+.+.+.>+.<.-.>-.<-.++.--.++.+.--.>.<<+.-.>-.++.+.-.>+.<-.>-.<<++.--.>-.-.++.>.<<+.-.>-.++.+.-.>+.<-.>-.<-.-.+.>.<.+.>.+.<--.>---.<.>+++.<.>---.<++.>++.+.<--.>.<.++.>-.<-.>.<.++.>+.<-.>-.+.<+.+.--.>-.<<+++.---.>-.+.>.<-.---.<.>++.>--.<.+.-.++.+.>.<---.+.-.+.-.++.>++.<-.++.+.--.+.>+.<-.>-.<++.-.-.>.<-.-.+.-.+.-.+.+.>.<-.-.>--.-.+.<++.+.>+++.-.<-.>.<<+.-.>-.>.<.++.--.++.-.>.<-.-.>+.<++.+.+.-.--.++.-.>-.+.<<+.-.>--.>---.<++.>++.<++.>.<---.-.++.>.<-.>.<.-.+.+.+.+.-.--.++.-.>.+.<--.---.<.>++++.++.-.>-.<-.---.<.>++.+.++.+.--.>.<<+.-.>-.-.+.<++++.----.>-.++.>.<<+.-.>-.>.<.-.+.-.>--.<++.>++.+.<--.<+.-.>+.+.+.+.<++.--.>----.++.>-.<<+.-.>-.>.<.++.--.++.-.>.<-.++.+.-.-.>.<<+.-.>-.+.>.<-.+.>.+.<--.---.<.>++++.-.+.+.>-.<++.----.>--.-.-.++++.<+.++.+.--.>.<-.-.>--.<++.>++.+.<--.>---.<.+.>-.++++.<+.>-.<-.++.+.--.>.<<+.-.>-.<+++.---.>-.>--.<.++.>++.<-.<++.--.>-.>--.<.+.+.>++.<<+.-.>-.++.+.----.+.++.--.+.>.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<++.-.--.+.>.+.<--.>.<+++.<+.-.>--.+.>-.<-.---.<.>++.+.-.+.++.-.>.<<+.-.>-.-.+.++.--.>.<.+.>.<-.>.--.-.<+.>+++.+.<--.<+.-.>+.+.>-.+.<--.>.<.>.<+++.-.>-.<-.---.<.>++.+.>.<.+.>.+.<--.>.<+++.>.<---.++.+.>.<---.+.-.++.>-.<-.>.--.<-.+.+.>++.<-.++.>+.<.--.+.+.+.<+.-.>----.+.+.>-.<-.>.+.<-.+.+.+.+.-.+.--.>-.<-.---.<.>++.+.-.+.++.-.>.<++.-.--.+.>.<++.----.>--.<.+.+.>++.<-.-.>--.<.>.<++.+.>+++.<---.>---.<.++.+.>+++.<---.>---.<.++.+.>.<.-.+.<++.--.>--.+.>++.<<+.-.>-.>.<.-.+.-.+.-.++.>.+.<--.--.<.>+++.-.++.>-.+.<--.+.++.-.>-.<-.++.--.-.++.+.+.----.>+.<++.>-.<-.<+++.---.>-.+.++.--.>.<+.>.<-.<++.--.>-.>--.<.+.+.+.<+.-.>--.-.+.+.>++.+.<--.++.>-.<<+.-.>-.++.+.----.+.>.<+.+.<+.-.>--.++.-.+.<+.-.>--.+.+.+.>.<---.+.+.>+.<---.+.++.-.>-.<<+.-.>-.-.+.<++++.----.>-.++.>.+.<--.<++.--.>+.-.>.<++.>-.+.<--.---.<.>++++.-.+.+.+.+.-.>.<-.>-.<-.-.>--.-.<+.-.>-.++++.<+.---.<.>++.+.<+.-.>-.++.>.<-.-.+.-.+.-.+.+.>.<<+.-.>-.>.<.++.--.-.+.+.>.+.<--.>.<.+.++.+.--.>-.<++.----.+.-.++.>.<<+.-.>-.++.+.-.+.----.++.+.>+.<<+.-.>---.++.>-.<-.<++.--.>-.>--.<++.>++.<-.---.<.>++.+.-.+.-.+.+.>.<++.>.<---.-.++.>.+.<--.--.<.>+++.-.++.>-.<-.<+.-.>-.++.+.>+.<---.++.>-.+.<--.---.<.>++++.++.-.>-.<<+.-.>-.-.+.++.--.>.<.+.>.+.<--.+.++.-.+.<+.-.>--.-.>---.<++.+.>.<---.+.-.>.<++.>++.<-.---.<.>++.+.>.<.+.>.<-.<+.-.>-.>--.++.<++.>.<-.++.-.>.<-.++.--.-.+.++.-.>.+.<--.---.<.>++++.++.-.>-.<-.-.+.+.>.+.<--.<++.--.>+.-.+.++.-.>-.<++.----.>+.<+++.-.+.<+.-.>--.-.+.+.>-.+.<--.>---.<.+.<++.--.>-.++.>++.+.<--.>---.<.+.-.+.>++.<+.>.+.<--.<++.--.>+.++.+.--.>-.<-.---.<.>++.+.-.+.-.+.+.>.+.<--.++.+.>.<.--.-.++.>-.<-.++.+.--.>.<-.<+.-.>-.++.>.<++.----.>--.-.-.+.+.++.<++.+.+.>.<--.>.<-.++.+.----.+.++.-.>.+.<--.---.<.>++++.-.+.+.>-.<-.-.+.-.+.-.+.+.>.<-.++.+.----.+.-.++.>.+.<--.>---.<.<++.--.>+.-.++.>++.<-.++.--.++.+.----.++.+.<+.-.>--.-.+.+.+.+.----.+.+.>.<<+.-.>-.++.+.-.+.----.++.>.<-.-.+.++.>+.<-.+.+.-.--.++.-.+.<+++.---.>--.-.++.>-.<-.-.+.>.<.+.+.+.-.--.+.>.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<-.>.+.<-.+.+.>-.+.<<+++.---.>--.++.>-.<-.---.<.>++.>--.++.<++.>.<<+.-.>-.-.>--.<++.>++.<-.>.<.-.>+.<++.>-.<-.-.+.>.<.+.>.+.<<+.-.>--.>---.<++.+.<+.-.>--.-.>.<++.>++.<-.---.<.>++.>--.<.+.-.++.>++.<<+.-.>-.<+++.---.>-.>--.<.++.+.<++.--.>--.-.++.+.>+++.<.--.+.>-.+.<--.>.<+++.>.<---.++.>-.<-.++.--.+.>.+.<--.>.<<++.--.>.+.+.>-.<-.-.>--.-.+.<++.>++.<++.-.+.-.-.>.+.<--.<+.-.>+.<++.--.>-.++.>-.+.<--.<++.--.>+.-.>---.<.++.>++.<-.<+.-.>-.+.-.++.>.<-.>.--.-.<+.>+++.<-.++.+.----.+.-.++.>.<-.++.--.-.+.-.++.+.+.----.+.>.<+.+.>+.<---.>.<++.>-.<-.++.--.+.>.<-.<+++.---.>-.++.+.<+.-.>--.-.+.-.++.>.<-.-.+.++.+.----.++.>.<-.-.>--.<.>.<++.+.>.<.--.>-.<+.>+++.+.<--.>.<.+.++.--.-.++.+.<+.-.>--.>-.<+.>.<-.++.+.--.>.<-.+.>.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.-.+.----.++.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.<<+.-.>-.<++.--.>-.+.++.--.+.>.<-.-.+.++.--.-.++.>.<-.>.<.-.+.+.>.+.<--.+.++.-.>-.+.<--.>.<+++.>.<---.++.>-.<++.----.+.+.>.+.<--.>---.<.+.<++.--.>-.++.+.>+++.<---.+.-.++.>-.<++.----.>--.<.+.+.>++.<<+.-.>-.-.+.-.++.>.<-.++.--.-.>--.<.+.+.>++.<<+.-.>-.<+.-.>-.>--.<.+.-.++.+.>.<---.++.>++.<-.++.-.+.+.----.++.+.+.----.>--.<.+.+.>++.<-.<++.--.>-.>--.<.+.+.>++.<-.---.<.>++.+.>.<.+.>.<-.-.>--.<<+++.---.>.+.-.+.-.++.>++.<-.---.<.>++.+.++.--.-.++.>.<<+.-.>-.-.+.++.--.<+.-.>-.++.>.+.<<+.-.>--.>---.<++.>++.<-.>.<.-.>+.<++.>-.<++.>.<.--.>.<-.++.+.----.+.-.+.+.+.>+.<---.++.+.+.----.>.<++.+.+.<+.-.>----.>---.<++.>++.+.<--.>---.-.<<+.-.>+.-.>-.++++.<<+.-.>+.>.<.>.<.-.++.>.<++.--.>.<<+.-.>-.>.<.++.>+.<-.>-.+.<--.---.<.>++++.++.-.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<-.++.--.+.>.<<+.-.>-.-.+.-.++.>.<-.++.-.+.+.----.>--.<++.>++.<<++.--.>-.-.++.+.>+.<.+.--.>-.<-.++.--.-.>--.<.+.+.>++.<<+.-.>-.>.<.++.>+.<-.>-.+.<--.<++.--.>+.-.>---.<.++.>++.<<+.-.>-.++.+.-.>+.<-.>-.+.<<+.-.>--.>---.<++.>++.<<+.-.>-.<++.--.>-.+.++.--.+.>.<<+.-.>-.>.<<+.-.>.++.-.>.<-.-.>--.-.<+.+.>+++.+.<--.+.++.-.+.+.----.<+.-.>+.+.>-.<-.-.++.+.+.>.<---.++.-.>.+.<--.>.<.+.++.+.--.>-.<-.---.<.>++.>--.<.+.-.++.>++.<++.----.+.-.++.>.<-.-.+.++.>+.<-.>-.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.-.-.>.<-.<+.-.>-.+.-.++.>.<-.-.>--.<.>.<++.>++.<<+.-.>-.-.+.++.--.>.<.+.+.+.>.<---.+.>.<-.<+++.---.>-.++.>.<-.++.--.+.>.<<+.-.>-.++.+.----.+.>.<+.>.<-.-.>--.<<+++.---.>.+.-.+.-.++.>++.<-.<+++.---.>-.+.++.--.>.<+.+.<+++.---.>--.-.++.>.<-.-.>--.-.<+.-.>-.++++.<<+.-.>+.++.+.----.+.++.--.+.>.<-.-.>+.<++.>-.<++.-.-.>.<<+.-.>-.>.<.-.+.-.>--.<++.>++.<++.>.<---.-.++.+.>+.<---.>---.<++.>++.<-.<+++.---.>-.++.>.<-.++.--.-.<+.-.>+.+.>.+.<--.>---.-.<<+.-.>+.-.>-.++++.<+.<+.-.>-.++.>.<-.++.--.>.<+.>.<-.-.+.-.+.+.>.<-.---.<.>++.+.++.--.-.++.>.<-.-.+.++.--.>.<+.+.+.>.<---.-.++.>.<-.>.<.-.+.+.>.+.<<++.--.>--.+.+.>-.<++.-.--.+.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.+.<--.-.<.>++.+.+.<+.-.>--.++.-.>-.<-.---.<.>++.+.<+.-.>-.++.>.<-.-.>--.<<+++.---.>.+.-.+.-.++.+.>+++.<---.>---.<.++.>++.<<+.-.>-.++.--.-.+.-.+.-.+.+.+.+.----.+.++.-.>.<<+.-.>-.++.+.----.+.++.--.+.>.+.<--.>.<+++.<+.-.>--.+.>-.<-.++.--.-.>+.<.++.>-.<++.>.<.--.>.+.<--.---.<.>++++.++.-.>-.<-.-.+.-.+.-.+.+.+.>+.<---.>.<++.>-.<-.-.+.++.>+.<-.>-.<-.-.>--.<<+++.---.>.+.-.+.-.++.>++.+.<--.>.<+++.<+.-.>--.+.>-.<-.++.-.>.<++.----.>--.-.-.+.+.<.+.-.+.+.+.>+++.<---.++.>-.<<+.-.>-.>.<.>.<.-.++.>.<-.---.<.>++.+.-.>--.<.++.>++.<<+.-.>-.>.<.>.--.<+.+.<+.-.>--.-.>.<++.>++.<<+.-.>-.++.+.----.+.++.--.+.>.<<+.-.>-.++.+.-.>+.<-.>-.<<+.-.>-.<++.--.>-.+.++.--.+.>.<-.<+++.---.>-.+.++.--.>.<+.>.<-.++.--.-.<+.-.>+.+.>.+.<--.>.<+++.<+.-.>--.+.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<<+.-.>-.>.<.>.--.<+.>++.<<+.-.>-.++.+.----.+.++.--.+.+.>+.<<+.-.>---.++.+.+.----.+.+.>-.+.<--.>.<<++.--.>.+.+.>-.<++.----.>--.-.-.++++.--.-.<+.+.>+++.<<+.-.>-.++.+.-.>+.<-.>-.+.<--.+.++.+.--.>-.<-.-.+.++.--.>.<+.>.<<+.-.>-.<+.-.>-.>--.<.+.-.++.+.<++++.----.>--.+.>++.<-.---.<.>++.+.>.<.+.>.+.<--.>.<.++.>-.+.<--.<++.--.>+.++.+.--.>-.<<+.-.>-.-.+.++.--.<+.-.>-.++.>.<-.-.>--.-.<+.+.>.<<++.--.>-.-.+.+.>+++.<-.++.>+.<.--.+.+.>.<---.>---.<.++.>++.<-.++.--.-.<+.-.>+.+.>.<++.----.>--.<.+.+.>++.+.<--.>.<.<++.--.>+.+.>-.<<+.-.>-.>.<.++.+.----.++.>.<-.-.++.+.+.-.-.>.<<+.-.>-.>.<.++.--.-.+.+.>.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<-.++.<+.-.>--.+.>.<-.<++.--.>-.>--.<.+.+.>++.<-.++.+.----.+.-.++.+.+.----.+.-.+.+.>.<<+.-.>-.>.<.++.--.-.+.+.>.<-.<+.-.>-.<+.-.>+.-.++.>.<<++.--.>-.++.+.--.+.>+.<.+.--.>-.<<+.-.>-.>.<.++.>+.<-.+.>.<---.+.+.>-.+.<--.---.<.>++++.-.+.+.>-.<-.---.<.>++.>--.<.+.-.++.>++.<++.-.+.-.-.>.<-.<+.-.>-.<+.-.>+.-.++.>.+.<--.<++.--.>+.++.+.--.+.<+.-.>--.+.>-.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.<-.---.<.>++.+.<+.-.>-.++.>.+.<--.<+.-.>+.>-.--.<+.>++.<-.<++.--.>-.>+.<.++.>-.<-.---.<.>++.+.<+.-.>-.++.>.<<+.-.>-.>.<.>.--.<+.>++.+.<--.>---.<.<+++.---.>+.+.>++.<-.-.>+.<++.+.+.----.+.++.-.>-.<++.----.>+.<+++.-.>-.<-.-.<+.-.>+.++.-.>.+.<<+.-.>--.>---.<++.>++.<++.----.+.+.>.<<++++.----.>-.++.-.>.+.<--.>---.<.+.-.+.>-.<.+.>+++.<-.-.+.++.+.----.++.>.+.<+.+.--.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.+.>+.<---.>---.<.++.>++.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.-.--.-.+.+.>.+.<--.<+.-.>+.>-.<.-.++.>.<<+.-.>-.++.--.-.+.-.+.++.-.>.<<+.-.>-.<++.--.>-.+.>.<+.+.+.-.-.>.<-.++.--.++.+.--.>.+.<--.+.++.-.>-.<-.---.<.>++.+.-.+.++.-.>.+.<--.>---.<.<++.--.>+.-.++.+.<+.-.>--.-.>.<++.>++.<-.---.<.>++.+.-.>--.<.++.>++.<-.-.+.+.+.+.-.--.-.++.+.+.----.+.-.+.-.++.>.+.<--.>---.<.+.>-.++++.<+.>-.+.<<+.-.>--.+.-.++.>-.<-.>.+.<-.+.+.>-.<-.---.<.>++.+.-.>--.<.++.>++.<<+.-.>-.+.>.<++.>.<---.-.++.>.+.<--.<++.--.>+.-.+.++.-.>-.+.<--.--.<.>+++.-.++.>-.<++.>.<--.+.<+.-.>--.-.>--.<++.>++.+.<--.>.<+++.>.<---.++.>-.<<++.--.>-.++.+.--.>.+.<--.---.<.>++++.++.-.+.<++++.----.>--.+.>-.<-.<++.--.>-.+.+.>.<++.----.>--.-.-.++++.<+.---.<.>++.+.++.--.-.++.>.<-.++.--.-.+.-.++.>.<-.>.--.-.<+.>+++.<-.---.<.>++.+.++.+.--.+.+.----.+.++.--.+.>.<<+.-.>-.-.+.++.--.<+.-.>-.++.+.+.>.<---.++.-.>.<<+.-.>-.-.+.<+++.---.>-.+.+.>.+.<--.<++.--.>+.++.+.--.>-.+.<--.<++.--.>+.++.+.--.>-.<++.-.+.-.-.>.<<+.-.>-.++.+.-.>+.<-.+.+.----.<+.-.>+.+.>-.<-.-.>--.-.<+.+.>+++.<<+.-.>-.++.--.-.+.-.+.-.+.+.>.<<+.-.>-.<+++.---.>-.>--.<.++.>++.+.<--.>---.<.+.<++.--.>-.++.>++.<<++.--.>-.++.+.--.>.<-.<+++.---.>-.+.++.--.>.<+.+.>+.<---.+.-.+.+.+.<+.-.>--.>-.<+.>.+.<--.>---.<.+.<+.-.>-.+.+.>++.<-.-.+.<+++.---.>-.++.+.+.----.>--.-.-.++++.<<+.-.>+.>.<.++.+.----.++.>.<-.-.>--.<.++.>++.+.<--.>---.<.<+++.---.>+.+.>++.<<+.-.>-.>.<.++.--.++.-.+.<++.--.>--.++.-.>.<++.-.--.+.>.+.<--.>.<<++.--.>.+.+.>-.+.<--.>.<.+.++.+.--.>-.<-.-.>+.<++.+.>.<---.+.++.-.>-.<-.-.+.++.--.++.--.+.>.+.<.>-.+.<--.>---.<.>+++.<.>---.<++.>++.<<+.-.>-.-.+.++.--.>.<.+.>.<<+.-.>-.<+++.---.>-.>--.<.++.+.<++.--.>--.>-.<+.>+++.+.<--.<++.--.>+.-.+.++.-.>-.<<+.-.>-.>.<.>.--.<+.+.>.++.<+.--.>.+.<--.>.<.>.<.+.+.>-.<<+.-.>-.>.<.-.>+.<.++.>-.<-.---.<.>++.+.<+.-.>-.++.>.<-.<++.--.>-.>--.<.+.+.>++.<-.-.>--.<.>.<++.>++.<-.-.>--.-.<+.-.>-.++++.<+.++.--.-.++.>.<-.---.<.>++.>--.-.<+.+.>+++.<-.<++.--.>-.>+.<.++.+.>.<.+.--.>-.<<+.-.>-.>.<<+.-.>.-.+.+.>.<-.<+.-.>-.<+.-.>+.-.++.>.<-.-.+.++.--.++.--.+.+.+.----.+.++.--.+.>.<-.+.>.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.>.<.--.>.<-.-.+.<+++.---.>-.++.>.+.<<+.-.>--.>---.<++.>++.<<+.-.>-.<+++.---.>-.>+.<++.>-.<-.---.<.>++.>--.<.+.-.++.>++.<++.----.+.+.>.+.<--.>---.<.+.>-.+.<-.++.>++.+.<--.>---.<.+.<+.-.>-.+.+.>++.<-.-.++.>.+.<--.<+.-.>+.<+.-.>-.+.+.>-.<<++.--.>-.-.++.+.+.<+.-.>----.+.-.++.+.+.>.<--.+.>+.-.<--.+.>.<-.-.<+.-.>+.++.-.+.+.>.<---.+.+.+.----.+.>.<+.>.<<+.-.>-.+.>.<<+.-.>-.<++.--.>-.+.++.--.+.+.+.----.>+.<.++.>-.<<+.-.>-.>.<.++.+.----.++.>.+.<--.>---.<.<+++.---.>+.+.+.<+.-.>--.-.+.+.>++.+.<--.---.<.>++++.-.+.+.>-.<-.-.+.-.++.+.+.>.<---.++.-.>.<<+.-.>-.++.--.-.+.-.+.-.+.+.+.<+.-.>--.-.+.-.++.>.+.<<+.-.>--.>---.<++.+.>+++.<---.>.<++.>-.<<+.-.>-.-.+.-.++.>.<<+.-.>-.++.+.----.+.>.<+.>.<-.-.>--.-.+.<++.>++.<-.>.<<+.-.>.++.-.>.<-.<++++.----.>-.+.-.++.>.<++.----.>--.<.+.+.>++.+.<--.<+.-.>+.+.>-.+.<--.<++.--.>+.-.+.++.-.+.+.-.+.----.++.>-.<<++.--.>-.-.++.>.<-.++.+.----.+.-.+.+.+.<++++.----.>--.+.>.<-.-.>--.-.<+.-.>-.++++.<+.<++.--.>-.+.-.++.+.>+.<.+.--.>-.<-.-.+.>.<.+.+.<+++.---.>--.+.+.+.<+.-.>----.++.>.+.<--.<++.--.>+.-.+.-.+.+.>-.<<+.-.>-.<+++.---.>-.>--.<.++.+.>.<---.++.>++.<-.<+.-.>-.<+.-.>+.-.++.+.+.>.<---.-.++.>.+.<--.>---.<.+.-.+.>++.<+.>.<<+++.---.>-.+.>.+.<--.<++.--.>+.-.>---.<.++.>++.<-.>.+.<-.+.+.>-.<++.----.+.-.++.>.<++.-.-.>.<<+++.---.>-.+.+.>+.<.--.+.>-.<<+.-.>-.>.<<+.-.>.++.-.+.<+.-.>--.-.+.+.+.>+.<---.+.-.+.+.>-.<-.-.++.>.<-.<+++.---.>-.++.>.<-.-.++.+.<+.-.>--.++.--.+.>.<-.++.<+.-.>--.+.>.<++.-.+.----.+.+.+.+.----.+.-.>--.<++.>++.+.<<++.--.>--.+.+.>-.+.<--.>---.<.+.<++.--.>-.++.>++.<-.>.--.++.<+.>.+.<<+.-.>--.+.-.++.>-.+.<--.>.<.<+.-.>+.-.++.+.+.----.+.>-.<+.>.<-.<++.--.>-.>--.<.+.+.>++.<-.>.<+.>.<-.>.<.-.+.+.>.<<+.-.>-.-.+.++.--.>.<.+.+.+.----.+.-.+.-.++.+.<++.--.>--.++.-.>.<++.----.>--.<.+.+.>++.+.<--.>.<+++.<+.-.>--.+.>-.<++.>.<--.>.<-.>.--.<-.+.+.>++.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<<+.-.>-.<+.-.>-.>--.<.>.<++.+.<+.-.>--.>-.<+.>+++.<-.++.+.----.+.-.+.+.+.+.<+++.---.>----.++.+.+.----.>+.<.++.>-.+.<--.++.+.+.>-.<--.+.+.>.<--.>.+.<--.<++.--.>+.-.>.<++.>-.+.<--.>.<+++.<+.-.>--.+.>-.<-.-.+.++.>+.<-.>-.<<+.-.>-.-.+.-.++.+.+.-.--.+.>.<<+.-.>-.<++.--.>-.+.++.--.+.+.+.-.--.+.+.>+.<---.>.<++.>-.<-.++.--.-.+.-.++.+.+.<++.--.>----.+.+.>.<-.---.<.>++.+.>.<.+.>.<<++.--.>-.-.++.+.<+.-.>--.-.+.+.+.<+.-.>--.-.>--.<++.>++.<-.>.<<+.-.>.++.-.>.<-.++.--.-.<+.-.>+.+.>.+.<--.>.<+++.<+.-.>--.+.<+.-.>--.++.+.+.-.--.-.+.+.>-.<-.-.+.++.+.----.++.+.+.----.>--.<++.>++.<-.++.--.++.--.++.-.>.<-.<++.--.>-.+.-.++.>.+.<<+.-.>--.>---.<++.>++.<<+.-.>-.>.<<+.-.>.-.+.+.>.<-.<++.--.>-.>--.<++.+.>+++.<---.++.+.>.<---.+.-.+.+.>-.<-.<+.-.>-.>--.++.<++.>.+.<+.+.--.+.+.<+++.---.>----.++.>-.+.<+.+.--.>-.<-.<++.--.>-.+.-.++.>.<-.-.+.-.+.-.+.+.>.<<+.-.>-.-.+.-.++.+.+.----.+.>.<+.>.<-.---.<.>++.+.-.+.-.+.+.+.<++.--.>--.-.+.+.+.+.>.<---.+.>.<-.-.>+.<++.>-.<-.-.+.+.+.+.<+++.---.>----.++.+.<++.--.>--.-.++.+.+.<+.-.>----.+.-.++.+.+.>.<--.>.<-.-.+.-.+.-.+.+.+.<++.--.>--.-.+.+.>.<-.++.--.++.--.++.-.>.<-.++.-.>.<<+.-.>-.+.>.<-.<+++.---.>-.+.++.--.>.<+.>.<-.<++.--.>-.>+.<.++.>-.<<+.-.>-.<+.-.>-.>--.<.+.-.++.>++.+.<--.>---.-.<<+.-.>+.-.>-.++++.<+.++.<+.-.>--.+.+.+.----.+.-.+.+.>.<-.---.<.>++.+.++.--.-.++.>.<<+.-.>-.<+++.---.>-.>--.<.++.+.<+.-.>--.>++.<+.+.+.<++.--.>----.++.>.<<+.-.>-.>.<.++.--.++.-.>.<-.---.<.>++.>--.-.<+.+.>+++.<-.-.+.++.-.>.<++.--.+.>+.<-.>-.<<+.-.>-.-.+.+.>.+.<--.<+.-.>+.>-.--.<+.+.>+++.<.+.--.>-.<-.-.<+.-.>+.-.+.+.>.+.<--.>---.<.<+++.---.>+.+.>++.<<+.-.>-.-.+.<++++.----.>-.++.>.<-.++.--.>.<+.>.<<++.--.>-.-.++.+.<++.--.>--.-.+.+.>.<-.++.--.-.>--.<.+.+.>++.<++.----.>+.<+++.-.+.+.<+.-.>----.++.>-.<<+.-.>-.-.+.<+++.---.>-.+.+.>.<<+.-.>-.++.+.----.+.++.--.+.>.<++.>.<.--.>.<-.++.+.--.>.+.<<+.-.>--.+.-.++.+.<++.--.>--.++.-.+.>.<.--.-.++.>-.+.<--.<+.-.>+.<++.--.>-.++.>-.<++.----.>--.-.-.++++.--.++.--.<++.>++.+.<--.>---.-.<<+.-.>+.-.>-.+.<<++.--.>+.-.>-.++++.<<+++.---.>+.-.>+.-.<++.+.+.----.+.++.--.+.>.<-.-.+.-.>+.<++.+.>.-.<-.>.<++.-.+.----.+.+.>.<-.>.--.-.<+.>+++.<-.>.--.<-.+.+.>++.<-.++.--.-.<+.-.>+.+.>.<-.-.+.<++.--.>-.+.+.>.+.<--.>.<.>.<+++.-.>-.<-.++.--.-.++.>.<<+.-.>-.<+++.---.>-.>+.<++.>-.<++.----.>--.<.>.<++.+.>.++.<+.--.>.<++.-.+.----.+.+.>.<-.-.+.++.+.----.++.>.+.<--.>.<+++.<+.-.>--.+.+.<+++.---.>--.+.>-.<-.++.--.-.++.>.+.<--.>---.<.+.<++.--.>-.++.>++.<<+.-.>-.>.<.-.<+.-.>+.+.>.+.<--.+.++.-.>-.<++.----.+.+.>.<-.-.+.++.--.>.<+.+.+.-.--.+.+.+.----.+.-.+.+.>.<<+.-.>-.>.<.-.+.-.>--.<++.>++.<<+.-.>-.++.+.----.+.>.<+.>.<-.-.+.++.>+.<-.+.+.----.>.<++.>-.<<+.-.>-.>.<<+.-.>.++.-.+.<+.-.>--.++.--.+.>.<<+.-.>-.>.<.>.<.-.++.>.<-.>.<.++.>+.<-.>-.+.<--.<++.--.>+.-.+.++.-.>-.<-.-.++.>.<++.-.+.-.-.>.<-.---.<.>++.+.++.+.--.>.<-.<+++.---.>-.++.>.<-.>.<.-.>+.<++.>-.<<+.-.>-.>.<.-.<+.-.>+.+.+.+.>.<---.+.+.>+.<.--.-.++.>-.<-.>.<.++.>+.<-.>-.<-.---.<.>++.>--.<.+.-.++.>++.<-.>.<.+.>.<<+.-.>-.>.<.-.+.-.+.-.++.+.+.<+.-.>----.+.+.>.+.<--.>.<.++.+.+.-.+.----.++.>-.+.<--.>.<+++.<+.-.>--.+.>-.<-.++.>+.<.--.+.>-.<++.--.+.+.-.+.--.>.+.<--.-.<.>++.+.+.>.-.<-.>.+.<--.<+.-.>+.+.>-.<++.-.--.+.>.<-.++.--.++.+.----.++.>.+.<--.---.<.>++++.++.-.>-.<++.-.-.+.+.>.<---.-.++.+.+.----.>--.<.+.+.>++.+.<--.>---.-.<<++.--.>+.+.>+++.<-.++.>+.<---.++.>-.<-.>.+.<-.+.+.>-.<-.-.+.++.+.----.++.>.<<+++.---.>-.-.>+.-.<++.+.+.<+.-.>----.+.-.++.+.+.>.<---.++.-.>.<-.+.>.<-.<+.-.>-.++.>.<-.-.+.+.>.+.<--.++.>-.<-.++.+.--.+.>+.<---.>---.<.++.>++.<-.<+.-.>-.++.>.<-.>.<.+.>.<-.-.>--.<++.<+.-.>--.++.>++.<-.<+.-.>-.++.>.<<+.-.>-.+.+.>+.<---.>---.<.++.>++.<<+.-.>-.+.>.<<+.-.>-.+.>.<-.+.+.+.--.>.<-.-.>--.<++.>++.+.<--.++.>-.<++.-.>-.<.-.>+.<++.-.--.++.-.-.>.<.+.+.-.--.<<<.>--.<------------------------..++++++++++++++++++++++............>>>>++++++++.<<.>>----.<<<<.>>>>---.<<<<.>++.<.++..>--.<------------------------.++++++++++++++++++++++............>>>>+++++++.<<.>>----.<<<<.>>>>++++.<<<<.>++.<.>>>++++++.<++++.>>+.<<<<.>+++++++.>++++.------.>>---.<-----.>-----.-.<<--.>>++++.+++++++.<<<--------.>++.>-.<--.>>-------.<<<<++++++++++++.------------.>>>>+.+.--.<+.>----.<--.<<++.>>>+++++++++++++..<<<<+++++++.>>.<<.+++++.------------.++.>-------------.-------.<.>>>>++.<<<++.>>>--.<<<<+++++.>>+.<<.>.<-------.++.>+++++.+++.<.>>>>++.<<<--------.>>>--.<<<<+++++.>>+.<<.>.<-------.++.>+++++.++++.<.>>>>++.<<<---------.>>>--.<<<<+++++.>>+.<<.>.<-------.++.>+++++.+++++.<.>>>>++.<<<<++++++++++.>>>>--.<<<<-----.>>+.<<.+++++.------------.++.>-----.++++++.<.>>>>++.<<<<++++++++++.>>>>--.<<<<-----.>>+.<<.+++++.------------.++.>------.+++++++.<.>>>>++.<<<<++++++++++.>>>>--.<<<<-----.>>>.<<<.+++++.------------.++.>-------.++++++++.<.>>>>++.<<<<++++++++++.>>>>--.<<<<-----.>>>+.<<<.+++++.------------.++.>--------.<--.++.>>>>++.<<<-----.>>>--.<<<<+++++.>>>+.<<<.>.<-------.++.>+++++.>----------.>>-------.<<<<.>>>>+++++++++.<<<-----.>>>--.<<<<+++++.>>>+.<<<.>.<-------.++.>+++++.>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<<<<.>>>+++++++++++++++++++.<<-----.>>--.<<<+++++.>>+++++++++++++++.<<.>.<-------.++.>++++++.<--.++.>>>++.<<------.>>--.<<<+++++.>>+.<<.>.<-------.++.>++++++.>----------------.>-------.<<<.>>>+++++++++.<<------.>>--.<<<+++++.>>>--------------.<<<.>.<-------.++.>++++++.>>>.<<<<.>>>++++++++++++++++.<<------.>>--.<<<+++++.>>>-------------.<<<.>.<-------.++.>+++++++.<--.++.>>>+++++++++++++++.<<-------.>>--.<<<+++++.>>>------------.<<<.>.<-------.++.>+++++++.>.>+++++.<<<.>>>+++++++++..<<++++++++.<------------------------..++++++++++++++++++++++............>>++++++++++.+++++++++.+++.-------------.----.++.+++++.<<.++++++++.>>>-------.<-------.>----.<<<--------.>>++.<<.>>++++++.>----.<<<.>>----.<<+++++++++.-------------------------------.++++++++++++++++++++++............>>>+++++++++++++.<<<----------------------.++++++++++++++++++++++................>>>-----.<----.>----.<<<.>>.<<.>++.<.>>++++++++.>----.++++++.<<<++++++++++++++.>+++++++++++++++++++.>--------.>--.+.<++++.<<------.>>>+++.<----------.++++++++.------.--.<<++++++++.>>++.<<--.>++++.>>-------.<<-.>>+++++.--.---------.+++++.-------.<<<------.+..++++++++++++++++++.-------------------------------------------------.++++++++++++++++++++++................>>>++++++++.<<<.+++++++++++.++++++++++++++++++.-----------------------------.>>>++++.+.--.---------.+++++.-------.<<<++++++++++++++.>----------------.>>++++++++.-.<++++++.--.>++++++.<<<------.>++.>>------.+++++++.--------.<++++.>+++++.<----.+.>------.<+++.<<++++++.>+++++++++++++.>.>++++.<.----.>++++.<<<------.>>>++.<------.++++++++.------.--.<<+++++++++.>>++.<<-----.------------.>>++++.<<+++++++++..++++++++++++++++++.-------------------------------------------------.++++++++++++++++++++++............>>>+++++++.<<<----------------------.++++++++++++++++++++++............>---------------.>++++++++++++++.-.+++++.----.---.-------.<<++++++++++++++.>>--------------.>-----------.---------.+++++++++++.<++++++++++++++.<<------.>>>-----.<<<+.>--------.<-------------------------------.>>>++++++++++++++.<<<.>>>.. ``` [Try it online!](https://tio.run/##vV1ZqmW5EVyQkFZw0EaMP2yDwRj8YfD6y@8eTTlEZOqWGz@qq1/dQUdjDpGRqb/@@y//@Nff//O3f/76VdjPn3opP3/e/8Zf5fn5qX@m3@g/P3X@tJ8/z/tqG3@v13@amB9vvRf76/xYK@35@bv7L5X3HfTTPo/fH1qPp083Pz/fvuiEeSDowvh2a8@nB6c7z3rKnJzZrZ8mx4fGG@vt9eIje6Me3p5kFs78@ylw38AN2cmwHziDs/NSztQ0NNezH/rFz1R8@t7ezaO/L9fv098zs6bVLzuqfml7tlDf2tzdDbcte2kH3dzX3o@0tQE@7TY8GvYo/6H2nK0MuvA@6pFnZL7QWhMHscgt4x5xVnUthN81VY22qVkEp24v6@6K6Yt4b75/2v4cFDHuvUdGK83MTDtvF9yTNcBzOs/bXlCZGX9PqHhNSqp1yOex/pwQLdKELBEjJXPg52E8WHZjrM7n/yX6aex9@ay352Pzv0ejjfF8ntvG1Pw8s739eEf2vjVPeR/y7PNv9bnP91Zb9fNrG3Na3lfW5@a/9lPr@fJnnOc782nqyWNw85NbrL6NPKuZT29nw3XspdXNT5f2cLpUBu@3n/HoPls5Y6mmnTXEOW176FVI99H@eme2PJ@4/lnWxLUxpNXufGXM2BjHM16ZW1A8cTR1@qK@99h@rwF2vYLrwWLW32/qmZ8TX2a3x8fW8PpQj2P6p3xcIlhui7nH@lgQNWg1BLmN9Ftz1cZj@nsgW7A998fXV@rcPqpHn9@rmrpi5kbsjjU3cqBrSaLejVO9H1bPnpQjm5/ez1tzWGfnzGk8qzKfJlpo@/tNfsMMUR7FPoXrmDywSHuHicHPU13XvPQyx23O9X59nT4qAc72GtP2HvwqBjomcjW4e60WXK/AOe/jHfFsOcK99YTYImfMHCf1eGnynQO@OjQ3mpJf64wXfcLPzKtdqTeOamwvrxDkawSF7I796uqeEY11SYojzSqWUnK/vJM4piSfEC8a@xY5WsOc4Uh9gM5p2QdubKDa9FGac@LO@tRd4oTpCVECfJ7dMaNyJOuwttUbL3j6WMnxkEfJj3O@mtNWw9KeXVh75igeo52VRpUT2IeRwcRkUVK@2l2m5OeRVnJTujP/GAWpLAO1ckAGtj1fWo0/etHVgpUz7kpUATuwXgqJQQKFvWb3HAojFreOQer2bFVhvRhdqE5xU9OEFO6Rz3OrPvAdccQzlde9sadMplq1yCLSSRqBZ373SnoL6kgm/RsauDqo/VjiUnaeCbcy5QxTncpkSvTOVR9vyt46xjVe03Mg@pLfSwWzHnkD6QHagtjKdrn3vsAKZC2ytLXaWujRM3GkxZr3KZGU2vFaU51WpWa2CbBWR6tsJcqIsSH12XyloS1xTqKwl7B/ozQQNKP6Rh600BPHXJwsMWNnqpWVqWWL3B1iD@wlOLrHmxNGn9rDe9w3bZ2uh/QJB7ZjYwHX0R0HZ0Mv5GjvX6V1rD/StZpbqNuZpQaNQaEszf5qTmK5xQIjf5i3q33WcK8rS6eu4@aXexno8lWvfQI1jJY82sTKyGi7h23iPU3M8z7VwP7RtuM8diWVN9u67@s8x3aZNG6VDwU1u1A0/sBr42uNReMSxidxXg6EBqiOrmAyt3m/LGo4BfvkZ1ahMkmUzxBZFUfIqCNXvNl0RHylrhJze4DOk76XnGJr4wO1qlw6a6xttaBtut7Wtr3xjSobhNWWwBx1RjeSm9nJAU4@9OgfrcWs6UT1AF8a6u1b/eGmhqFtQqIoF0/qG4sPIAFnTaMybd2lNM5a4HEK6YF17T4/3sGCEJD1xbaSeko0jUtYLatVeapwyk@3oShKEQFhISn8Tvy6hjEhobMeSghg9ap1TDFbjSGlDCfMrI@@7NCFgGuHT9v7NdWA7kF6WYuFEnMszCNQCLuU@DZCOaS2Au6nxTQVlCvOhVnK2gKrANhoQre67VqUdg7dnCN7gc2GASOqAB2oJ3bG88XKGtQcaLkbFBF59lun9q3p0Xoo8SdUmF5/JTR0PEGfTeIIm9mR7ohQOInXBL1/F7MwumY6yY/yCa1Ql4CUs8UoJCrNAqEuubg34NSKbLTqrICytusWb1@YK84MkLsmhQuVkSoMNGBsHzlkZpHa8wUAjdTWtLY2QH6XomNGgJzjfuMKCNm@oORQnpOW1PGqpnWpF2lQcX1665cJ6FUQwHNKJUMKXbCuXELxyMeHC8fHdcI8QJsDU3PLs5o6zipSyU4ncZnQisnI425ffI/BjRKSjkEOgsLwmKo7nbn/K7VAd9arNfG1zaWFjFcblRkpzCKFg3JYUq5njCVgXRMHv2oEe7tC2A90ayBlVqsQzbSoYCIoIWApDRggqYX2Cw1ezUhwfpp1SXmcBSLmAjatnIShozJGEJ4tpQN42ww3XAwZVQP6U6J3HPdQ6KoLTDiFywNj0A6h9ikdWdfxISjUpfNeNtRU1XdBUIqC8UbC9GlfNQk4SGgLBMwhgGH0Um1g2o08OdHWcO2x4aHtli3oqg/iqjUmbvVFGL0aSpHyZc/4i6EMJKi4xpU6CBlZ7cPOqdOMwj1E8aWIVORwlooki6craNzJd17sT2GpuMmymzhCe5d1ZNxBFA1eMrZW6jl1E@riYVYA9AhB9aVr68FeebwVxFoZrUrb@Bj03zweQ9QB4CoBvgoOEcGwMmJAXIKYmGbhj4o89@K8cgdHoKqefELtUKBSKjUbKgpvhE6lYplBvsdR3cCRgxKRsuxc7CGKvDhuEuW2QRg@YPmtzeEoKtJEkLuHoy7r1FlLIoyXBsBlgRELKyN48LUa6oKL1VcVyMdC@EY6Kc@zeO6SMcGWDjMYpROIoFlnG6TBRsJH3MJE0BN3n6mlJul4Iah/j02E5wVF/aRZTszJgXcpyW1ictUIKuhO0jPmaEjpRuC@IiArUs6wCWFLg2wfKx0shmGKGlO1vfQvLw7zVGG@iPgkByKCidSc3Xk@N0C7Gyfxb2php5FNYWdbWhiK60B0ULB5z7pVb2vI2BxAkbyH8bTUviTM19hQUrwWbSFaRiInoghbPaanAlyGz4vj4FB4u595TOmcqXbUDIanYfxZWXxnBdfESwM8J9N369ElApLERyI6CPdkNW83zkUAqQePA0vF7oJ@wtjlCMua5y6MJBGUgKpxAvNngTJLavyanhMIFBD59i5SlWgTosd6fMP7gZzbz@ghG0uqhiwcIp4MWSJsOQp2xLZcJeCn20A5qQ/AyY4r4mwhTDxGFDsIGgK4AEhdzYA7esfKWMxXdSa6cHeJzZPwuw6H80pa4/A0xgu2S9g99ilgC8KQVtNoXRVjYmgsjKGDUfTOIFYspJIYGTkD@EZgYfjVIBaMbGtYIZhkUH3yCRRCSTTZs618GALmJHUcMo0xdJVYJ9GqW3t8PS63sBExXMr6KLys4xqEcuWzUBxCH8NPl@kjD8CzAK8BjF6rGg4pcrplRJmohiCh4pQXUfx@fRQpc8RJSUoVvMrrMeABwTkS@ari5PdetsXXDApJNqFzLQR3sKrQXJA0BQIqhgyUGgNHJkujwvlYRrS1gLXAmVWBKZmYixEVTWVNku@hDLdiDxmk/4AgE4l/1OO2QvefcQYp5HaTt3S6a9LHtqXj7CpCT5VqR4R8KuNc3sYPnMNp8RkF6KJYKeLNyc7p2BsGPTSOYuyKYm1GlxhWrzFqDSGdkB8KvLBkL4asuFmmebKOl@exZG@1VbZpEv5omPukWc2piXYByZMQyg2fTvv7W8KJyQPStSvbQ@diWaa18f6Zxe6I3iYJs0L6AKF8O6UNsiy0TaUdI4WmXOXykaIOevBle2YgWxwymWS8lkeSuDEQxNYiMg1PtQNp5yiccJnrF5zYIGvmijthLUgGqWMibtQnGioAQBml5nPOIs3dCQsruATVICJ/AEeKGiLqnlPxS2jaHTJzplJoD8V0VNwOZhhAwNXRJEAtg7BQgopxS5aUT5jDZ40lwqokVa70eXJFxJiA2xIw/cIzq455jOjj1G@Lhfi0fsep@i4LDPmEF2QZ4JKyLDzGE45yxlVnbHZPHo6NctHhWu6yO/ZwWLoZhRAg5ISgPQR4s6yTnAsJdwQXgDQ@ySiPWUqXy5m8QH8TAqdm6vgUXpwiilDa3LiwpWa0VgNzWKwdDvQ6y4cG9lHAeAki/tzqIvyRPDsmLlYQUmfsprEghOfG3aYPg7R/JMuRg@xQdvqS9ZohX0lIBlAci0V3NVATRW8CuhIIMkL3OAgl26BksjtTYi22oBG6rkLLoHxMZMgWgY2hCi8JjtlKmn6i95ShOpMzVtxkOrJ/sWo74GpD0r4h8HsiRkoaKNdpkJycE@GxxYS0WAxPyyY3DMC4LTR@kxu9OuRr2RwuppLHL5AURnkOVzV8cHLGFb1YhxMJU49K4zBCPAb@CJyrkryvHTykBexAokOQInzBvwyxWxifbhmZHtIecCk8UoNgHaSCjJOIEnJZ5tLyMXQ6WuhA4LqL7o2III9xP2bDyupAj8@cg7LA0fstsgPx88RmAM4yrRIJYkHQYYJ1l0BpMpPchcw1XAQEwaKxm0G8zAy6xxWFnIRxnqQ0j4ECv84/blf0tcC2cxkqlVX2ypjXxBFIOxamMTlI3xaRQKTAoOZQEWVEBXjQCC0GHIYK8ykJvQZan8brRhRKF4XCkCEmWt1UQwm8EsDKZKxGL6tWXetW41kAtv7FlmScF4oK63gRL9ESZ3OA5AgQV4m1p/XeI26LOXQxZHpZjRTkfWdmAqpSdKH5dBgjJhDkFqdoDRcEoakuNvpOK8YicORLxoPSXc5YO3QoGIq8UjAlY0drLWKIROVOWBMGjC8H4rlDhQC8YW3Q6gu2FOfqZNxzmNzPPO1gz9h@GGYO9dlx0VwXyYBQBiAI5fX@CuYI9IsYk0OS3UEpJDBlAieR831DqPXVGEihR8SLuEQ4FMoBjcGAVixOsztZKoQTl4h3tWIOq01sVVRCPKi6YYtYqKxgXI7S5G0ae0fq9M5Smgk6DJ1qVXUchL0Dz4rFJIDGqd8g0oD/A0S8Do/Y6E9W4ATGEGSMCqZgO4a@pImVJXWemt8QIRVQ06XGSIYfAt2Oy2Yjm9fhKFLRGJU5ibl8Vjez6v7RvEBy9KlokmXLI3AJMf2xkENxHW8Lcgj1q3snSH0zkENfEOMdMkwzBhD06wwiCSwsmmAUhJt8ImYHPLwR17CJGZqZ6bPGfQUJndNJZkHOI68iz1O9ZXoMeXWeC88STxFAZv6A0Jq/K0ZmJQTlK5MEfpsTVi5CMDRtxXLeeemVpBgxRcGItXrqZt9V7SIZUi1FWjkXqFBDkeR5nPt3viuqYsPnKOsOJpzhcElWTJiLEUO8RAQXnh5DUotYHS3A3LnTeUE@oC8fJaIhvvbUF7EG4u0waJOtrgCzfEqo0nA@/AML2BcQ2cWJAKxAJU33t/zui/oS/iYsM@mFBJsLKZZWDDW@SSGFcsR1yUpUUiWocGM8XZzEzcijyc03jsQlzlzii/Q/5GYE71TJjNeo3Kvlg0Rlx0HCBUgNiQk6HGKlafs2GBulAaEsVFP9tvsqCMTxg1letPyStUlc6XiCHBp@NipjHQZ7wOm6v/KDsn5Qmie4HwynVYHiEfWGkeOK9nivAVjs5D4m/GEeKq3VCryGL/6z1ih1KYKM3Jwt99sZ5En5GVcCVeKOrMAKqA2dUA7SfAVRWkNRkQq5/cMAx6nxA9UAcej07iGxUVfTy9Lwkp2XI/ZGHgblx@nlLuGpju6VqwTGt@CohfVdemkJKwnlMKOV6zQYjOVg5ZVogwoC1lr2dUB9rUC4mxgpIT/vQd12xqKDnpMoC8CCH7YEcr3IsXfXPWCOeDRRNI2CJTRZtw@F3K9qbsAL0AKcjlU8L8jmTFK2YFIBwWe8nxvsGwxwXDD1KfUpLAYXJkzzso2pu4dUTfc5ERqnTo5T3mXmdz2qN8VeGHhTG8lijrhmK3YBLkFISqCi5lx6Zwo7n@HVAkTPUlZ0nLTrUBZ76WNMf8DkVFVLIrrOw6eK2XlKb/yx5VK4DYir8sR3l0QFg@wlB8JSacpxkrBth7KD35tEK@OiWhAXUS4QRshueoM3Etg86cAeL2GxohRMDKsy@rpI2kAkNQF00ZEEzrkN0YYVIOBOo2f8tmjMTVmCsJrrTQXj3yikHrFIeDaTrznPA34a88rq1dAi/L6CCRECQUJDpZoHWMrBdYpPu7o0JyFXxAlqQe4dToRzNx3nMBpinyEONq4YlpU6waTtsCYPMw6i6MAXVx2oe6xpqf8Aq4nK1zuqi9d4mPpbLlIKcKHwDAoMaZTlq/upSOHMKC8M6uv0lk9WWMwUifGOdg8MmrjsFwmHXyTHwXJlN1eMNZdyoxPCw2weX5ufpKVIEIlDsuVOWRDOg2dNsXi/NUujOgRbK3UXdKX3gaY3aWUE8fsYQvdkAxiLiy6k0EX5g5ss7u2AGGxNigDAm2NLSmelBYixbaeKRiW3KYQXPesk3CwCANijGoa5Qg2zLPUIsiMaU1TBvDr5udEPLleIKd36Ek5n3uHEJ8ACzRJSYdJU4AiFJXgo5SOJ9YbaDANCKM5FIpfoMpXoUucIDzWFBhEqzSorRd4ooEXBTAYTNav4elYUEWGFUVkpF3MBL0rgP2FtcH8GuPwv4Prf3WPng65hqZmek43NbUlZrNeYyR76l9C0sb9YzrLOKnH0BFSpr5p7YBu6M44lCjvwAd06xajbtKQet8d8NRN8CVNyyYAIMwfqVFYZfVpQkFAQMowLRU2nAEkCcKO@s9vxES/RSHxLjDVPMcegRbUvcDmucn2ljM8dZdTRKC8yuGiI6ip7d5qnRpiryGElanxVndHR7jDya@iQIvgGoZZnFV5Ahgti02RYfh1FrC2tU4EsQ1aoHjJyo2SubhKL4cVE9tZYfDc8dSQpuSa46BKk4/rgKiqDRQ@cZzplKXsPMnlQkQ@83s6IugmpfHNj1XdlHsElR/5WgpQ8kt1N20@a@FVuJsr9BJ6U5XrrTA5cvQdVt90ZRlllv9zd5/fF2vCPE2l8Dzl9elPC44vQGgkQYjoPNhVQNlhH9TroJaMs6rbwtXxLyyIfisNwVmv@9RTuHFdZsE2mKMOsaI8i4gwHVD6W52UGV7tc1YJDl74bIOUyybsHF6KBq4RMP68LZvmaEw7WL6SvrtxqHocDjJSrOiC@8na59RowccoE/m/SsG3ScvfBOnoLK3JJ6GVfBBeq/NbF@8u57S07weUIvDq0zJhUrndK2NAun6s60QHZZosBXqyvtt@7Q2D5prCeAvVtUFkjHZk3V0jaOBK8XPnsDyMpA5tIWTfk2i2b1GDLpJGYo2/J817RTVWVRHwvwpvwEr6WZRRKAtyMePYiNsY@nUdMPc8zGqrkp736y/808dN/fvbrnwbHEj1v4733849VgSV55lePRE@cr@9H7k9Ps6j38/Z4vW9z6TPDo8t1c4DnNn/fmsdmPXuPYgqYcTD6evHzFDUINdC3r23F7uYgJhGsiVmd4xeN/bz7GThos8yGziu7L3Nu2rPalx2ckzKPUz2I2hyv@rocwTeN4Fa@b0a3I2Z4brj31dV0yWaqlT@@zXr2yH2r/T2Q8aK28jsNl4uW65YieoXA6sz24Pp0tcHlQVCS4vfbN@fiu5/dEfze6XaTm9F9DnatiAk8rYHmeAPdCUM5g83MH2nfNEKnsqwtByfktn3evJ4P3HjSetR4XzvCzUw75@F/VW3idfVb8zK2HeH0NHkaxfESa2rk6NJkciPMkc1fsRL5bQXqjsVvNzYbFINU3W9CD59pUYJXK0mxyPpFeSg2xiG2aTcL3syMNTWPbZ/Sqf6ltFqqfniSusEmNud6He2mbJ3@l8mWCye/9XU3VmMtGylbDLWH1xPbs599hONZKTHZzfZy2Wji@LajVZ9ziZ7bJksivI7VXtVHb5D23OwNsTmqnJYzTvXh/9fiK7P39w9sd0tn@y6Wvykb0m2DTvSVnje1RR@uaPrZbtouudrDWp692q39@vVf "brainfuck – Try It Online") Went through a few code generators to keep it under the ~65k character limit for answers, [this one](https://marsipulami0815.net/cryptomx/bf.html) did the trick. ]
[Question] [ An **[Abecedarian Word](https://english.stackexchange.com/questions/208852/is-there-a-name-for-a-word-where-all-the-letters-are-in-alphabetical-order#:%7E:text=You%20can%20call%20them%20abecedarian,letters%20of%20the%20Latin%20alphabet.)** is a word whose letters are in alphabetical order. Your goal is to write a program that outputs all abecedarian words from a given lexicon. ## Rules: 1. **[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** are forbidden. 2. If a word contains punctuation, diacritical marks, or any characters other than ASCII alphabet characters (`A-Za-z`), remove the entire word. 3. Words that are abecedarian in ASCII are not necessarily abecedarian for this challenge. For example 'Maddox' shouldn't be considered abecedarian. 4. Your program should work with any lexicon, but for testing purposes, this one can be used. (If my code works properly) It contains ~~588~~ 587 abecedarian words that follow the above rules. The lexicon does not count towards your byte total. <https://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words> 5. As per the request of @Olivier Grégoire, here are the Abecedarian words from the lexicon: ``` A Abbott Abby Abe Abel Ac Acrux Aden Ag Ainu Al Alps Am Amos Amy Ann Apr Ar Art As At Au Av B BMW Be Begin Bell Bellow Ben Benny Benz Berry Bert Bess Best Betty Bi Biko Bill Billy Bk Blu Boru Br Btu C Cd Celt Cf Chi Chimu Chou Ci Cl Cm Co Coors Cory Cox Coy Cr Crux Cruz Cs Cu D Dee Deimos Deity Del Dell Dem Denny Depp Di Dino Dior Dis Dix Dot Dow Dr E Eggo Elmo Eloy Emmy Emory Enos Er Es Eu F Finn Finns Flo Flory Fm Fox Fr Fry G Gil Gill Ginny Gino Ginsu Gipsy Guy H Hill Hiss Ho Hz I Ill In Io Ir It Ivy J Jo Joy Jr K Knox Kory Kr L Ln Lot Lott Lou Lr Lt Lu Luz M Mn Mo Moor Moors Mort Moss Mott Mr Mrs Ms Mt N Nov Np O Oort Orr Os Oz P Pt Pu Q R Ru Rx S St Stu T Ty U V W X Y Z a abbess abbey abbot abet abhor abhors ably abort abuzz accent accept access accost ace aces achoo achy act ad add adder adders adds adept ado adopt ads adz aegis aery affix afoot aft aglow ago ah ahoy ail ails aim aims air airs airy all allot allow alloy ally almost alms am ammo amp amps an annoy ant any apt art arty as ass at ax ay b be bee beef beefs beefy been beep beeps beer beers bees beet befit beg begin begins begot begs bell bellow bells belly below belt bent berry best bet bevy bill billow billowy bills billy bin bins biopsy bit blot blow boo boor boors boos boost boot booty bop bops boss bossy bow box boy brr buy buzz by c cell cello cellos cells cent chi chill chills chilly chimp chimps chin chino chinos chins chintz chip chips chit choosy chop choppy chops chow city clop clops clot cloy coo coop coops coos coot cop cops copy cost cosy cot cow cox coy crux cry cs d deem deems deep deeps deer deers deft defy deity dell dells demo demos den dens dent deny dew dewy dill dills dilly dim dims din dins dint dip dips dirt dirty dis diss ditty divvy do door doors dopy dory dos dot dotty dry e eel eels eery effort egg eggs egis ego egos eh ell ells elm elms em empty ems emu envy err errs es ex f fill fills filly film films filmy fin finny fins fir firs first fist fit fix fizz floor floors flop floppy flops floss flow flu flux fly foot fop fops for fort forty fox foxy fry fuzz g ghost gill gills gilt gimpy gin gins gipsy girt gist glop glory gloss glossy glow gnu go goo goop gory got gs guy h hi hill hills hilly hilt him hims hint hip hippy hips his hiss hit ho hoop hoops hoot hop hops horsy hos host hot how i ill ills imp imps in inn inns ins is it ivy j jot joy k kW knot knotty know ks l lo loop loops loopy loot lop lops lorry loss lost lot low lox ls m moo moor moors moos moot mop mops moss mossy most mow ms mu my n no nor nosy not now nu o oops opt or ow ox p pry psst q r rs s sty t tux u v w x y z ``` 6. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` fØẠŒlÞ$ƑƇ ``` [Try it online!](https://tio.run/##y0rNyan8/z/t8IyHuxYcnZRzeJ7KsYnH2v8/3L3lcHvk//@OTs4urlyJSckpqVyOSc4prly@iSkp@RVcbvlFJZVc/nmpXC75eeolnnnJOaUpqSEZmcVAderOKequXOqJAA "Jelly – Try It Online") -3 bytes thanks to Nick Kennedy ``` fØẠŒlÞ$ƑƇ Main Link Ƈ Keep elements that are Ƒ Invariant when .[][.]$ Last two links combined, but [ØẠ][ŒlÞ] is an LCC, so it takes another f Filtered to keep ØẠ Alphabetical characters Þ And sorted by Œl Lowercase ``` Basically, "keep elements that are invariant when you filter out non-alphabetical characters and sort alphabetically". Jelly's sort is stable. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes *Ties [a stone arachnid's Vyxal answer](https://codegolf.stackexchange.com/a/225537/94066) for #1.* ``` áʒlD{Q ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8MJTk3JcqgP//49WcnRydnFV0lFQSkxKTkkFMRyTnFPAIr6JKSn5FSCWW35RSSWI4Z8HVuKSn6de4pmXnFOakhqSkVkM0abunKIO1qiXCDPw8EqlWAA "05AB1E – Try It Online") ``` áʒlD{Q # full program áʒ # all elements of... # implicit input... á # containing only letters... ʒ # where... # (implicit) current element in filter... l # in lowercase... Q # is equal to... D # (implicit) current element in filter... l # in lowercase... { # sorted # (implicit) exit filter # implicit output ``` [Answer] # [Raku](http://raku.org/), ~~32~~ 36 bytes ``` *.grep:{!/<-[a..z]>/&[le] .comb}o&lc ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy@9KLXAqlpR30Y3OlFPryrWTl8tOic1VkEvOT83qTZfLSf5v7VCcWKlQpqGjW9iSkp@hYJLZl6@gmtObr5CYlJyyuGVdpr/AQ "Perl 6 – Try It Online") `*.grep:` filters the input list on the provided predicate function, which is combined from two other functions using the `o` function composition operator. The right function (the first to be applied) is the built-in lowercasing function `lc`. The left, brace-delimited function contains the main logic for this challenge. That function contains two checks, separated by `&`. `/<-[a..z]>/` is a regex that matches any character other than the lowercase Latin letters "a" through "z". The leading `!` negates that test, matching only words containing no such characters. `.comb` splits the input string into individual characters. `[le]` reduces that list of characters with `le`, which is the less-than-or-equal operator for strings. That's equivalent to `char₁ le char₂ le ... le charₙ`, which is true if the sequence of characters is lexically monotonically nondecreasing. [Answer] # JavaScript (ES6), 68 bytes ``` a=>a.filter(w=>(w=w.toLowerCase())==w.match(/[a-z]/g).sort().join``) ``` [Try it online!](https://tio.run/##NchBCsIwEEDRq0hWGbDpCdKNWz1BKXQ6mdaWmJEkWPVGnsODxSq4@PD4C94wUZyvuQriuIy2oG3QjLPPHPVqm63VZDnKyvGAiTWA3c4FM5113WL17OoJTJKYNZhF5tD3UEhCEs/Gy6RH3aqBY3yo/U7hQI7@eL9@IuKUvjqhc3JXHUD5AA "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 34 32 bytes ``` #~(-:-.&Alpha_j_-.~[/:toupper)&> ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/les0dK109dQccwoyEuOz4nX16qL1rUrySwsKUos01ez@a3KlJmfkK6QpqPsmpqTkV6hbqycmJaekAmlHKK2XqP4fAA "J – Try It Online") -2 thanks to xash * `#~` Filter by... * `(-:]/:toupper)&>` Words that are equal to themselves when sorted by their uppercase values... * `-.` And then removing... * `-.&Alpha_j_` All characters not in `[A-Z][a-z]`. [Answer] # [><>](https://esolangs.org/wiki/Fish), 86 bytes ``` 10i::}:0(?;a=?v:'['(?v::'`{'@)@(*@:@1+(@}**{10. +$0.?v0[>100. >~~31. >' ␕'@ =0l< o^? ``` [Try it online!](https://tio.run/##S8sszvj/39Ag08qq1spAw9460da@zEo9Wl0DSFmpJ1SrO2g6aGg5WDkYams41GppVRsa6HFpqxjo2ZcZRNsZGhjoKdjV1RkbAil1BVF1By4FBVuDHBuF/Dj7//9dc3LzuXwTU1LyK7hcMvPyuRKTklMOr@RySk0t5qqKquICAA "><> – Try It Online") (The `␕` represents the character 0x15.) ## Verification It takes a few minutes, but it works: ``` C:\Users\conorob\Programming\fish λ time python fish.py abc.fish <words.txt >out.txt real 5m18.932s user 0m0.000s sys 0m0.031s C:\Users\conorob\Programming\fish λ wc out.txt 587 587 3209 out.txt ``` ## Process First, I like to get a functional program working, even if it is not golfy. [133 bytes:](https://tio.run/##S8sszvj/39DAwFCPyy7TyqrWykDD3jrR1r7MSj1aXcO@TAEI7Kys1BOq1R00HTS0HKwcDLU1HGq1tKq5FLAAO3UFde04VCm7ujr7MoNoBTuIPZh6cuwV4/L//3fNyc3n8k1MScmv4HLJzMvnSkxKTjm8ksspNbWYqyqqigsA) ``` 1001. >i::}:0(?;a=?v:'['(?v >::'`{'@)@(*@:@1+(@}**{ >' '+^ >~~?v0[ >1001. >l?!^o ``` There's a *lot* of wasted whitespace in this one. So, first, I'll flip line 3 up onto line 1. Then, I'll reorganize the last two lines to occupy more of the trailing spaces, including reversing the last line. [113 bytes:](https://tio.run/##S8sszvj/39DAwFBPARXYqSuoa5dx2WVaWdVaGWjYWyfa2pdZqUera9jHgeWtrNQTqtUdNB00tBysHAy1NRxqtbSqucCaDaLtwGba1dXZl0GEFPLjFO1zIEyb//9dc3LzuXwTU1LyK7hcMvPyuRKTklMOr@RySk0t5qqKquICAA) ``` 1001. >' '+v >i::}:0(?;a=?v:'['(?^ >::'`{'@)@(*@:@1+(@}**{ 0[>1001.>~~?v o^!?l < ``` Now that the last line is more flexible, we can move even more of the last two lines into the leading whitespace. [101 bytes:](https://tio.run/##S8sszvj/39DAwFBPARXYqSuoa5dx2WVaWdVaGWjYWyfa2pdZqUera9jHgeWtrNQTqtUdNB00tBysHAy1NRxqtbSquRTq6uzLDKLtwGbacQFV5tgo5Mcp2v//75qTm8/lm5iSkl/B5ZKZl8@VmJSccngll1NqajFXVVQVFwA) ``` 1001. >' '+v >i::}:0(?;a=?v:'['(?^ >::'`{'@)@(*@:@1+(@}**{ ~~?v0[>1001.> l< o^!? ``` I tried reversing lines 3/4, but that ended up longer because the direction changed. But, now that we made more room on line 3, we can reverse the lowercase procedure back onto line 2. However, to do this, we need to make line 3 jump back to its start before it reaches the lowercase procedure. This is easy to do, since we have a spare leading whitespace. [92 bytes:](https://tio.run/##S8sszvj/39DAwFCPyy7TyqrWykDD3jrR1r7MSj1aXcO@TAEI7Kys1BOq1R00HTS0HKwcDLU1HGq1tKq5FOrq7MsMou3A2u0MjPRAatUV1LXjuICsHBuF/DhF@///XXNy87l8E1NS8iu4XDLz8rkSk5JTDq/kckpNLeaqiqriAgA) ``` 1001. >i::}:0(?;a=?v:'['(?v >::'`{'@)@(*@:@1+(@}**{ ~~?v0[>1001.>02. >' '+^ l< o^!? ``` We can shave that wasted space in the loop using a very questionable technique. [91 bytes:](https://tio.run/##S8sszvj/39DAwFCPyy7TyqrWykDD3jrR1r7MSj1aXQNIWaknVKs7aDpoaDlYORhqazjUamlVcynU1dmXGUTbgXXaGRjpKSgo2KkriKg7aKsAjQLycmwU8uMU7f//d83JzefyTUxJya/gcsnMy@dKTEpOObySyyk1tZirKqqKCwA) ``` 1001. >i::}:0(?;a=?v:'['(?v::'`{'@)@(*@:@1+(@}**{ ~~?v0[>1001.>02. >' ␔'@+$1. l< o^!? ``` I've replaced the unprintable 0x14 here with its unicode equivalent `␔`. This bit works by generating a string `' ␔'`, which gives the values on the stack `[char, 32, 20]`. The original code computed `[char+32]`, then resumed control flow. We want to use a jump instead of arrow directions, and the point we want to jump to is (1, 20) in the codebox. `@` permutes these three values to give us `[20, char, 32]`. We then perform the sum and move it below 20 (`+$`), giving us `[char+32, 20]`. Then, we push 1 and jump to (1, 20) (`1.`). We can shave 1 more byte, by using the last bit of extra space on line 4 to save on the `!` character. [90 bytes:](https://tio.run/##S8sszvj/39DAwFCPyy7TyqrWykDD3jrR1r7MSj1aXQNIWaknVKs7aDpoaDlYORhqazjUamlVcynU1dmXGUTbgXXaGRjpKSgo2KkriKg7aKsAjVKwNcixUciPs///3zUnN5/LNzElJb@CyyUzL58rMSk55fBKLqfU1GKuqqgqLgA) ``` 1001. >i::}:0(?;a=?v:'['(?v::'`{'@)@(*@:@1+(@}**{ ~~?v0[>1001.>02. >' ␔'@+$1. =0l< o^? ``` We can reorganize this once again, to eliminate the first line. This, however, is still, [90 bytes:](https://tio.run/##S8sszvj/39Ag08qq1spAw9460da@zEo9Wl0DSFmpJ1SrO2g6aGg5WDkYams41GppVRsa6HEpKNTV2ZcZRNsZGhjoKdgZGOopKCjYqSuIqjtoq4DlbQ1ybBTy4@z//3fNyc3n8k1MScmv4HLJzMvnSkxKTjm8ksspNbWYqyqqigsA) ``` 10i::}:0(?;a=?v:'['(?v::'`{'@)@(*@:@1+(@}**{10. ~~?v0[>100. >01. >' ␕'@+$0. =0l< o^? ``` However, this gives us a little more whitespace to play with, allowing us to tuck more of our code into the leading whitespace. [86 bytes:](https://tio.run/##S8sszvj/39Ag08qq1spAw9460da@zEo9Wl0DSFmpJ1SrO2g6aGg5WDkYams41GppVRsa6HFpqxjo2ZcZRNsZGhjoKdjV1RkbAil1BVF1By4FBVuDHBuF/Dj7//9dc3LzuXwTU1LyK7hcMvPyuRKTklMOr@RySk0t5qqKquICAA) ``` 10i::}:0(?;a=?v:'['(?v::'`{'@)@(*@:@1+(@}**{10. +$0.?v0[>100. >~~31. >' ␕'@ =0l< o^? ``` This has reduced our Unnecessary Space Count™ to 5. At this point, I'm not quite sure where to go. By my reckoning, either the logic (`'`{'@)@(*@:@1+(@}**{`) must be golfed, or the fundamental structure/approach to the problem must be reworked. [Answer] # [R](https://www.r-project.org/), ~~89~~ 76 bytes ``` function(d,`+`=lapply)d[gsub('[^A-Z]',21,d+toupper)+utf8ToInt+is.unsorted<1] ``` [Try it online!](https://tio.run/##HcyxDoIwFAXQ3c9gKU3RBFwcZKiACYNxYZJgoLxWSUhLaJvIH/kfflilLDcnN@/d2YnUCSt7MygZQtSSNh27aRoXDPVLWxai@kn3jwZFSRwBMcpOE58xsUacKlVKQwZ9sFKr2XA4x40TYR/uEL1keYGiHepYD9yDsgy25tYBqI/XdX1aPO7SnwS5ksiUsh8t8Oo96GDtKEMZoMLTT/2@mzqfcXIMMHbuDw "R – Try It Online") Implemented as function taking a strings vector and filtering non-abecedarians out Steps: 1. make the string uppercase 2. replace any non letter character with `'21'` (i.e. two descending ASCII char) 3. turn strings into ASCII code points 4. take only the strings where the code points are sorted [Answer] # [Ruby](https://www.ruby-lang.org/) -p, 29 + 1 = 30 bytes ``` $_=$_[/^#{[*?a..?z]*?*}*\s/i] ``` [Try it online!](https://tio.run/##KypNqvz/XyXeViU@Wj9OuTpayz5RT8@@KlbLXqtWK6ZYPzP2//@S1OISrpL8RCCZmJScwuWbz@Wfy@WYkpqTmw@krMF0YpIeUMq9ND0nE8z/l19QkpmfV/xftwAA "Ruby – Try It Online") Uses a regex composed by the letters "a" to "z" joined by "\*" to find the words. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `a`, ~~9~~ ~~8~~ 6 bytes *-2 thanks to @Aaron Miller* ``` '⇩:sǍ= ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=a&code=%27%E2%87%A9%3As%C7%8D%3D&inputs=berry%0Aabcdc%0Aabcd%C3%A9%0Aaccess%0AMaddox&header=&footer=) ``` '⇩:sǍ= # Full program # All inputs (implicit) ' # where... ⇩ # the lowercase version... = # is equal to... ⇩:s # the sorted lowercase version... Ǎ # with only alphabetical characters # Implicit output ``` [Answer] # [Zsh](https://www.zsh.org/) `-F`, 28 bytes ``` grep -xi `printf %s* {a..z}` ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwbLi1BIFXbelpSVpuhZ70otSCxR0KzIVEgqKMvNK0hRUi7UUqhP19KpqEyBKFkCpmymJXIWFhVyJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVVzZfvklJZVcSSlpGVk5eQVFJWUVVVx6XInqxVyOSak5QAqX5qpKLt_ElJT8CohlAA) An abecederian word is one which matches the regular expression `^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$` (case insensitively). This regex is constructed by `printf %s* {a..z}`, and then matched using `grep`. The `-x` implicitly adds the `^` `$`; the `-i` option makes matching case-insensitive. [Answer] # BQN, 28 bytes ``` ("a{"⊸⍋⊸/≡∧)∘+⟜(32×'a'⊸>)¨⊸/ ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKCJheyLiirjijYviirgv4omh4oinKeKImCvin5woMzLDlydhJ+KKuD4pwqjiirgvCkYgIk1hZGRveCLigL8iYWJjZGUi4oC/IkFiY2RlIuKAvyIuYSLigL8iYX4i) Thanks to @DLosc for 3+4 bytes saved! ## Explanation BQN doesn't have builtins for string manipulation, so I had to manually recreate lowercasing/filtering non-alphabetical chars. * `...¨⊸/` Filter lexicon of words... * `+⟜(32×'a'⊸>)` Lowercase word * `≡∧` Check if sorted lowercased word matches... * `"a{"⊸⍋⊸/` Remove `[^a-z]` from unsorted lowercased word [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, 14 bytes ``` $LE"az"JLC_FIg ``` [Try it online!](https://tio.run/##K8gs@P9fxcdVKbFKycvHOd7NM/3/f9/ElJT8Ci7HxOSM1DwglZNZmZgBo9WLgayifKB4UlJiMYTMTAHR@SUlUEodLF4JJsDslNIcCAnmpYIwhJUDJtSL/@sW5QAA "Pip – Try It Online") ### Explanation ``` g List of lines read from stdin (due to -r flag) FI Filter on this function: LC_ The string, lowercased "az"J and inserted between "a" and "z" $LE is sorted in ascending ASCII order (fold on string-less-than-or-equal) Output each element of the result list on a separate line (-l flag) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~18~~ 14 bytes -4 bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m)! ``` ⊢⌿⍨(∧≡∩∘⎕A)¨∘⌈ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXokc9@x/1rtB41LH8UefCRx0rH3XMeNQ31VHz0AoQq6fjf9qjtgmPevsedTU/6l3zqHfLofXGj9omAtUEBzkDyRAPz@D/aQrqiUlJyeoK6mXhFZFVQPrwksQUIOWbmJKSXwFk6CWqAwA "APL (Dyalog Extended) – Try It Online") `¨∘⌈` for each uppercased word: `∩∘⎕A` the word intersected with `'AB ... YZ'`, keeping duplicate letters. `∧` the word sorted ascending. `≡` are those strings equal? `⊢⌿⍨` select words from the input where the result is a `1`. [Answer] # [Java (JDK)](http://jdk.java.net/), 74 bytes ``` l->l.filter(s->{int p=65,r=1;for(var c:s)r=p>(p=c&95)?0:r;return p<r*91;}) ``` [Try it online!](https://tio.run/##bVDRatswFH3PV@hpsUtj1ocO6tQZacZYYGVjDgxW@nBjy4lSWRJXcoYp@fZMunLSDPrgc8495@peyTvYw2RXvxxFazQ6tvN1JnR2NR1dOp0TMms6VTmh1buhdcihDVElwVr2CEKx1xFjpltLUTHrwHnaa1Gz1mdJ6VCozdMzA9zYlFoZ@zqsuC9p3H21BXx6nl3/X85Yw4qjnMz8nYR0HBM7mb0K5ZgpPt1eY3EzbTQme0BW5TbFwswSU1Qf7m7Tzx9znCJ3HSpm7vHq7mZ6SI9TWh76pVDcsoIp/vf8Lx66puHI618car8rREtlOhcvNbhlbx1vM6HSlIYxltGs5Fy2YIZH57nTC/@UOSL0aVxOQCcK1mRgjOwTKod8mK87lxk/w0kV4/em@xuetxrOX5K3w3k@nE6zSnfKJSnNP4wOx/loPrajOcEDwWPABcHqW6AlwZcyEIU/vocvqHKxpLSkakXp6mfA37HhD8EqIFRbrjxJ0cP2xBSg9v56DTaiqANr5wYak98TkK47GZEqHr6oJMGgAWtiS9OJY4I15@osBk@B2/ZvilxR70CdODobEGGJkFyFvYpjREoRttCeeHBifa4CWZA62N0OPPbWCiUuFLUOWl3Isf0H "Java (JDK) – Try It Online") ## Credits * -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 bytes ``` lambda x:[y for y in x if y.isalpha()and sorted(f:=y.upper())==[*f]] ``` [Try it online!](https://tio.run/##Dc2xCsMgFEDR3a8QF7VDli4l4JAmKXQoXbolGUyfEsGqqIH49Tb75dxQ8ubd9RZiTYIQ0t37YURy/YJC3drDiF4SwB/o4WMu6O0UGryj@em@dgf12Uw6O9oDHRGVJ9CkYE1mZHaEIy3mauVvBYmPdipY@4gLNg4f2GhcGpOkDZtkXDrA6TwoYLoVpdlDUJFxLsR00ctSQzQuM80S5/UP "Python 3.8 (pre-release) – Try It Online") Yeah! now Python ties with Javascript! -24 thanks to @makonede -5 thanks to @hyper-neutrino [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 68 bytes ``` [ [ >upper dup [ LETTER? ] ∀ swap [ <= ] monotonic? and ] filter ] ``` [Try it online!](https://tio.run/##HY7NasJAGEX3PsUtuvYBqm1MNEih7cLGlUj4MvOpg3FmMj@kIkKXfc6@SDrt8hy4h3sgEYwbth8v7@tHkBdK4cxOc4sLhdM0aiWM5H/A0ZlolT7CcxdZC/boeljHIVytUzpgNhp1/Q1vJKX5RF4sVyWoECuGIIe8afiKh8V4gprqphY1DqptcR922OE5WssOMtoEr2VVlZsMe/x8f8H39CfnT4kvRptg0q0MpGUSKRHSbj8ISq3p8As "Factor – Try It Online") * `[ ... ] filter` Take words from the lexicon for which the quotation returns `t`. * `>upper` Uppercase the word so case doesn't mess with the test for monotonicity later. * `dup [ LETTER? ] ∀` Does it only consist of (uppercase) letters? * `swap [ <= ] monotonic? and` And is it also sorted? [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` ^ $'¶ T`L`l`^.+ ^ $%'¶ O`\G. %)`^(.+¶)(\1|.+¶.+) Gi`^[A-Z]+$ ``` [Try it online!](https://tio.run/##FcpRCoIwAIfx9/85lCmjQUdYOiUofPGpbGy6QYJsYAsKOpcH8GJL3z5@fLMNo9MxSiRkXdCqi5qUZBQbpLs0qqsZ0lzJjNF1ybPu@NuD0RyoRyXv/HB70CRGfipKAd0PxoL3hRG4amP8B5WfwxeNsyi9I@HshultbPscX9tHCkMEiP4D "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ $'¶ ``` Duplicate the word. ``` T`L`l`^.+ ``` Lowercase the duplicate. ``` ^ $%'¶ ``` Duplicate the lowercased word. ``` O`\G. ``` Sort the letters of the lowercase duplicate. ``` ^(.+¶)(\1|.+¶.+) ``` If the sorted lowercase equals the lowercase word, delete the lowercase and sorted lowercase, otherwise delete everything. ``` %)` ``` Run the above stages on each word separately. ``` Gi`^[A-Z]+$ ``` Keep only words containing letters. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ΦA⬤↧ι›№βλ∧μ‹λ↧§ι⊖μ ``` [Try it online!](https://tio.run/##PYxBDsIgEEWvQrqBJngCV0jVNKnRhbumCwqTlISCAar19Ag1Opv/8/PeyEl46YRJ6ea1jeSkTQRPWvtYIqkpYsaQzr3ASxGA6LycPYiCcLdkfqTIFMwqMlPUQQjE5PwbLLZWwUo0RQ1IDzPYCJmtf7dPqe8rduDNsaKoEqNUUAobudqWi1DKraWdnI/vUq52QxpncX4vzaLgPunw1TBXeBOxqIYh7Z7mAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` A Input as an array Φ Filtered where ι Current element ↧ Lowercased ⬤ All characters satisfy № Count of λ Current character in β Predefined variable lowercase alphabet › Is greater than μ Current index ∧ Logical And λ Current character ‹ Is less than ι Current element § Indexed by μ Current index ⊖ Decremented ↧ Lowercased ``` [Answer] ### perl, 59 ``` say if /^[A-Za-z]+$/ and lc($_) eq join "",sort map {lc} @F ``` [Try it online!](https://tio.run/##ncpNTgMxDEDhfU5hVZUGBENh0RUb2MyuF2hVkEk8g2lqhzhpKYirE36OwFt@eolyXLZqBIfl1c31bTM8AY@weNjc92vs37cX8wWgBIj@bP54DvQKL8oCs9mlaS6wxwQf0X/C3dCa1QkzBfhnbiKhjJHNeK@ducCY2Yq5UfORpDg7oj0/Vb@LLJNbsd8xuSqGIfyJVSko5jzmoiq/VGVEzkJmbvWz6ZsboqZ0@tJUWMVaP3Qd9BHlGw "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` lambda x:re.findall(f"^{26*'%c*'}$"%(*range(65,91),),x,10) import re ``` [Try it online!](https://tio.run/##HY3BCoIwHIfv/6cYI9kmElkkFHgwNegQXTpGMN1MQafMBUr0Ll17Dh/MzNPv8v2@r@lNXqvNmPm3seRVIjjq9lous0IJXpY0w/fX2rOJldrkvcAWtTVXD0m9rbNzmcOcznFXDIqqqbVBWo5GtqZFPsIYAwSHMIqBJ6mQECShiOE4YT3AmQtRd3BREqJaEXNSafkU8poX7QSSUJAYCIfhM1//guELHE0LMJsbXShDMzrnGBt/ "Python 3 – Try It Online") Python had already a solution ([here](https://codegolf.stackexchange.com/a/225424/103772)) but it didn't worked on tests with char like (éèàÈ...). ## How it works : * `re.findall` returns all the occurences of a given pattern in a given string. * `f"^{26*'%c*'}$"%(*range(65,91),)` produce the pattern `^A*B*C*...Y*Z*$` which will match any upper abecedarian word. * `10` (`=2|8`) passed in argument to `re.findall` sets the flag `re.IGNORECASE` (`=2`) to disable caseCheck in the string and the flag `re.MULTILINE` (`=8`) which apply the pattern to each line of the string. [Answer] # [Perl 5](https://www.perl.org/) + `-lF -M5.10.0`, 28 bytes ``` /@{[sort map lc,@F]}/xi&&say ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiL0B7W3NvcnQgbWFwIGxjLEBGXX0veGkmJnNheSIsImFyZ3MiOiItbEZcbi1NNS4xMC4wIiwiaW5wdXQiOiJBYmJleVxuQWJob3JcbkFicmlkZ2VkXG5BY2VzXG5BZGRlclxuRm9ydHlcbkhlbGxvXG5NYWRkb3hcbk9uZVxuU3R1In0=) [Answer] # [Red](http://www.red-lang.org), 88 bytes ``` func[b][a: charset[#"a"-#"z"]remove-each w b[any[w <> sort copy w not parse w[any a]]]b] ``` [Try it online!](https://tio.run/##LYsxDsIwDEV3TmG5cy9QIW7Awmp5cBxHXWgqJ1DKjTgHBwuNxPSenv53i@1mkfiUppYei1Jgkgl0Fi9WaUDBccA3sts9P2000Rk2CCTLThucL1CyV9C87kdecoW1P2HrAxBmDtxWz8EgAWEw9x0BJWjUP7@fLqpWyiFXiTG/kKH9AA "Red – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Not entirely sure I've understood the spec correctly. ``` ¶ñv o\l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWY&code=tvF2IG9cbA&input=WwoiYWJjIgoiY2JhIgoiZEVmIgoiROlmIgpd) [Answer] # Java 8, 127 bytes ``` l->l.filter(s->(s=s.toLowerCase()).matches("[a-z]+")&java.util.Arrays.equals(s.chars().toArray(),s.chars().sorted().toArray())) ``` [Full Program (must be run locally)](https://tio.run/##jVJNbxoxEL3zKywOla0WrwLlqwSkNuqhElWkVDlFORjvLJh67a1nNhtS5bdTLxA@CpU6F8szb2bevJmlelKtZfpzbfLCB2LL@JfGyy9llkGA9A5UCmHU@Cv87fbrs4aCjHfnMVeU9IMCqPxStgOS93fTU2dJxsqpQbrgzkqn60by3qmwui0gKPLhAhA3PeWNtxZ0hOC/MVt6o0ajKGfWaKatQmTflXHsd4NF2/mRFMXnyZuU5THKY6Jx84dHpsIcBaNF8BWyIzl2@bWd8L3etrzeFphMWDZe29YkjmcsQeDYmnAcoyQ/9RWEG4XAhZC5Ir0A5M0H1Xp5fN8U7w6zfA5BrVDCr1JZ5Cj1QgXkIpbYRLj4cPBhlAHS46AQ6zeioz3lU5LMwrPRcaYxc1Cx05vg@6Q3qzFnyz@HHcPjIfDmgqjAT0kyj/uXc0OLclYihNiYwJHUPk@qeo65cclg2O53e90kqCpJh/1Bp9fu637nqt0bZLP2sNNV8aN6VwOlBjDs6uxjBFc@pNgU0hfgtty4OKMVxbbGRanFQY76IvdiBMDSUtQik6oo7Irv1BGR4ebi@OHy6jXG3KjykbYrJMilL0kWsSJZx7cl/wcj0bzAvtxr43X9Bw) # Java 16, 124 bytes ``` l->l.filter(s->(s=s.toLowerCase()).matches("[a-z]+")&s.chars().boxed().toList().equals(s.chars().sorted().boxed().toList())) ``` [Java 16 added the `Stream#toList` method.](https://jdk.java.net/16/release-notes#JDK-8180352) [Answer] # [Julia](http://julialang.org/), 55 bytes ``` x->x[@.all(isletter,x)isascii(x)issorted(lowercase(x))] ``` [Try it online!](https://tio.run/##FYhRCgIxDAX/e5IUdMEDKCKihxBZsk0KkeBKU7HbG3kOD1a3PzPz3uOtgrvS4r6V7aHcjgOqgphyzpw2xYuhBRHoZXPKTKDzh1NA4/X090ZiL8UFIiRGUnmygfe@4Smc@eJwCvT7utrdx0Acu0c3rnTX6qKo1j8 "Julia 1.0 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 164 bytes ``` #include<stdio.h> a;main(){for(char*s,w[99];!feof(stdin);!a&&printf("%s\n",w),a=0)for(scanf("%s",s=w);*s;a|=tolower(*s++)>tolower(*s)&&isalpha(*s))a|=!isalpha(*s);} ``` [Try it online!](https://tio.run/##TYtNDoIwGET3vQUYSQtI3JoKC2P0EGrIZ3@kSW0JxTRBPZDn8GBI3ehmXt5khi0ujI3jTBmmb1ysXc@VLZoKAb2CMpjcpe0wa6BLXe4Pq9WJRlJYicPQEBpBkrSdMr3E8dwdTZx7kkO5JOHmGJhvH@eu9ISmjsKj7K22XnQ4dVlGqp@RJFEOdNtAEDItoz@nz3GEDduKHYIz4@8XGgKDFFzIwBrVU6L9gKTSevgA "C (gcc) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), 67 bytes Assumes the Notebook environment. Otherwise an extra `Print` needs to be added around the last part of the code (as is done in the TIO link). ``` f=(a=Characters@ToLowerCase@#;a==AlphabeticSort@a)&/@#&;l~Pick~f[l] ``` This code assumes a lexicon has been defined previously and saved in the variable `l`. It maps the function `f` over each word in the lexicon and keeps only words for which `f` returns `True`. `f` in turn takes in a word, lowercases it, and then puts the letters in the string individually into a list. It returns true if the list does not change when `AlphabeticSort` is run on it. `AlphabeticSort` takes in a list of strings and sorts them in alphabetic order into a new list. The `ToLowerCase` function call is needed because `AlphabeticSort` sorts lowercase letters before their uppercase version, and so `f` fails to find "Oort" because it gets sorted into {"o","O","r","t"}, which doesn't match the original character order. [Try it online!](https://tio.run/##PYtBCoMwFETvEkFaKPQA8iHitguh7sTFJEQSGk2Jv5S26NVj3HQz8xjeTGBrJrDTSJ5@olYqMIvLAZ9crxn@aaHMYfg8QOmcX4g1jXQCNRYRmk1cZBdu4W1ig8XIogJR/b/eQ2SJc3mVRVm10c3c@611@rGNvR@GlHY "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 9 bytes ``` )zz:aa:so ``` [Try it online!](https://tio.run/##LVbLdtw2DP2Vu@0vZDcvxxN7bDdJm7Y7SaQetkgqpOR5rPtr/S73XijHxCUIgiAAAhrXSx59@bn4j7P7@O12@1RVn0r6@LhV@J7y8t@/2GBT12meNV0JXjRi03Dk5YKN8xGbDpshLthwY5wKNoEjaeaRyP0pY6NBM5QSqfuOLbanH9h6jm6IxHE0SGdOWsd4Fd4IOYulga0vRSBunikcON4SQacJFL1hOy7YMgJsM7bzgh12Djs/zti12PWDKFDcJwJXI3YBu8SRciHytl26kDhnDkZKuGHHzQV77L0nDQqSE93YMyl7BbD3gSTP936asB84YiKkTKD6cME@zaQz9hkHHLou4TAGAa87hCCQB4dI8wfqEBfc4W5gLgUFd2MSUeku4I6e3mWOKz7j8zCKBHLisy4nlIU4FQqWK@5xL437gam8T7i/4YgjBceIY8Ix4zjj@H7FF3xJHGQyHvAQec@D7nzIeMRjxCPjeFRxPDKNjxSSI8M8nXCKOCUOhn2ypJ4SX@@UijgeOVEuKceMJzyldzxNeMaz1J5zxnPB8w0veJnxsuB3fMXXBV8v@IZvM8eC7/h@xR/4Ez/wF/7GP6hQ1bXKQ9NVSP@q2gt6@mGo3VGbuqeql9sNVdP4ONs0rZNsNE0qWnmR1n1KQp5tKHccRj6vWDQJzIhLIuMk4yWscXKe6avalkVQtUnutaROJV@xDKqeg/mu@Igk6g9BJCaLjOE@H4uk89YuQpMKgvk96hAPBxZWFSYRBZEjSlXxsjwqeZiNuKCCIueS7l1Rg@1ee6PWoBhehVEwGZg0GxhrMBPaQdiJhrii9rpkYrGMo147XtMqkflfEulFgdq/VtPXZpi1WauCBdK0aZUVQ/FRpGVS3dfyRRmr7QTfslZt1labxBVm4Qo8kiaRdsoKkunwhUSeVVqznayI@HVs0CggQVqx2CRkFA0/OyRp9OaoTVdNfB9Dk0WDtOIqWXG@aTLVVVM26bRMpMlgWnnt0tFGX6Zm1N5oQsXfqFQaxk@aDIrQgLsmM5FsKSON3WB7NMnYGxnQJ7HhqzQFDs7zqycowsnA2GwglnXuVDrOPpdOiXKWG@dZoQKxUWSM1KMUzyIySpyzvDlLm2NrOLWGY8acckTgKSbIKT9uyLOBVLUsgtmW7ywgdqhTBTirAKdwnT5uTo4wWpJ0KfHw/LqTCkHrttXHw3ediEJ1NqtaRKaHgrPY/BhEZDiHifa8LRb4SBdY1iJKOC5o0SrI1oJsLUhiMDBBkCCKonESZpExfKp2MBDR3MCybEfFaFg0TQaMtbWKIBbDM2ER8ZzuVS200jYtmVDIAm1eRGSYjFbF36HrVSqd/O/Mf6LWgVep@a31O/sF6vQwnTzt5E9nP2OdOWJoizM6/kPBnHbJiHqmRreY8Y5d14P9ZO20dtPaTL2uZSuJJItaTaJJm5NkRgLuJQ4a760NekXd29JWmb4wLlhsve2dMUB32pXqW@taBqjfZvtpVqC8gsYHPvErXnnulR3zhrcfeItcCZhGTme8FYzg52KUF6N5IbwKZ4wmNJm@gJajUc6MtnkmXUBHAgLTFPTUwV46qKGDTASaCDIRdDhYfu0XIvA4U8RaZFlF8IMTeTyq2eWknOMLJJhP@iXjLmW8cMJEZ6ZCIz@Rwev4x4BmzCyfBe8444Irbv8D "Burlesque – Try It Online") ``` )zz # Map to lower case :aa # Filter all alpha :so # Filter sorted ``` [Answer] # [brev](/brev) 166 bytes! ``` (import srfi-13(chicken sort))(for-each print(filter(o(fn(equal? x(strse x "^[a-z]+$"(as-list(fn(sort x(bi-each < char->integer))))#f)))string-downcase)(read-lines))) ``` ]
[Question] [ Take the decimal number \$0.70710678\$. As a fraction, it'd be \$\frac{70710678}{100000000}\$, which simplifies to \$\frac{35355339}{50000000}\$. If you were to make the denominator \$1\$, the closest fraction is \$\frac{1}{1}\$. With \$2\$, it'd be \$\frac{1}{2}\$, and with \$3\$ it's \$\frac{2}{3}\$. Because \$0.\bar{6}\$ is closer to \$0.70710678\$ than \$\frac{3}{4}\$ or \$\frac{4}{5}\$, it would still be the closest with a maximum denominator up to (and including) \$6\$. ### Task There are two inputs: a decimal, and a maximum denominator. The first input consists of a number \$n\$ as input, where \$0\le n<1\$, and the fractional part is represented with a decimal (although not necessarily using base 10). This can be represented as a floating point number, an integer representing a multiple of \$10^{-8}\$ (or some other sufficiently smaller number), a string representation of the number, or any other reasonable format. The second input is an integer \$n\ge1\$, also taken in any reasonable format. The output should be a fraction, with a denominator \$d\le n\$, where \$n\$ is the second input. This should be the closest fraction to the inputted decimal that is possible with the restrictions placed on the denominator. If there are multiple which are equally close (or equal to the inputted number), the one with the smallest denominator should be chosen. If there are two with the same denominator which are equidistant, either are acceptable. The outputted fraction can be represented in any reasonable format, as long as it consists of a numerator and denominator, both being natural numbers. ### Test cases ``` 0.7 4 -> 2 / 3 0.25285 15 -> 1 / 4 0.1 10 -> 1 / 10 0.1 5 -> 0 / 1 0.68888889 60 -> 31 / 45 0.68888889 30 -> 20 / 29 0.0 2 -> 0 / 1 0.99999999 99 -> 1 / 1 ``` ### Other This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes per language wins! [Answer] # Scratch 3.0, 45 blocks/254 bytes [![enter image description here](https://i.stack.imgur.com/1CwIR.png)](https://i.stack.imgur.com/1CwIR.png) As SB Syntax: ``` define(n)(d) set[A v]to(0 set[D v]to(d set[i v]to(0 repeat((n)+(1 set[j v]to(0 repeat((n)+(1 set[r v]to((i)/(j if<(D)>([abs v]of((r)-(D)))>then set[A v]to(join(i)(join(/)(j set[D v]to([abs v]of((r)-(D end set[j v]to((j)+(1 end set[i v]to((i)+(1 end say(A ``` [Try it on Scratch!](https://scratch.mit.edu/projects/506339261/) Just wouldn't be right if I didn't do this in Scratch. ## Explained ``` define(n)(d) // Define an empty name function with parameters `n` (the denominator) and `d` (the decimal to fractionify) set[D v]to(d // This will store the current absolute difference between potential fraction and actual decimal set[i v]to(0 // outer-cartesian-loop variable repeat((n)+(1 set[j v]to(0 // inner-cartesian-loop variable repeat((n)+(1 // simulate cartesian product of range(0, n+1) and range(0, n+1) set[r v]to((i)/(j // divide i / j if<(D)>([abs v]of((r)-(D)))>then // if the difference between (i/j) and d is smaller than the current smallest difference set[A v]to(join(i)(join(/)(j // update answer and difference set[D v]to([abs v]of((r)-(D end set[j v]to((j)+(1 end set[i v]to((i)+(1 end say(A // output answer ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes ``` ◄oa-⁰´×/ŀ→ ``` [Try it online!](https://tio.run/##ASIA3f9odXNr///il4RvYS3igbDCtMOXL8WA4oaS////MC4x/zEw "Husk – Try It Online") `≠` is absolute difference, but doesn't seem to work for floats. So `oa-` is used. -2 bytes from Leo. ## Explanation ``` ◄oa-⁰´×/ŀ→ Inputs: decimal → ⁰, max denominator → implicit ŀ→ range 0..denominator ´×/ convert all possible pairs to fractions ◄o min by a-⁰ absolute difference with the decimal ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ÝD¦âΣ`/α}¬ ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//8OdRMKmw6LOo2AvzrF9wqz//zE1CjAuMjUyODU "05AB1E – Try It Online") ## Explanation ``` Ý # [0 .. input] D # Duplicate ¦ # Tail -> [1 .. input] â # Cartesian product Σ } # Sort by α # Absolute difference between # Input 2 `/ # and numerator / denominator ¬ # Head ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` (0{]/:&,|@-)%/~@i.@>: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQyqY/Wt1HRqHHQ1VfXrHDL1HOys/mtypSZn5CsYFRkr2CoY6JkrpCmYVEDEDItMwGJGpkYWpgpACUNTuIyhAVjKECRqABVFCMHUGQONMAWLmlmAgSXIGDOYBiODIiNLDGljVPMMgEJGMHvBIpZQAJSwtKz4DwA "J – Try It Online") Takes float as left input, max denominator as right input. * `%/~@i.@>:` Creates "division table" for all pairs 0 to max denominator. * `|@-` Elementwise differences between those table values and the target float. * `]/:&,` Sort the table `/:` according to those differences after flattening both `&,`. * `0{` Return the first item in the sorted list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Żpḷ÷/ạ¥ÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8///o7oKHO7Yf3q7/cNfCQ0sPz3u4Y9H////NDP4b6JlZgIElAA "Jelly – Try It Online") [Verify all test cases](https://tio.run/##y0rNyan8///o7oKHO7Yf3q7/cNfCQ0sPz3u4Y9H/w8sd9B81rfn/PzraQM9cxyRWhwvIMDI1sjDVMTSF8Ax1DA1gLKiQmQUYWOqYGaAJGEMFDHSMIAxLKNCxtIyNBQA "Jelly – Try It Online") Note that this selects the fraction with the smallest *numerator*, and I'm not completely sure if it's always also the one with the smallest denominator. Takes the maximum denominator as the first argument and the float as the second argument. ## Explanation ``` Żpḷ÷/ạ¥ÞḢ Main dyadic link, taking m and x Ż Range [0..m] p Cartesian product with ḷ m, implicitly converted to the range [1..m] Þ Sort by ¥ ( ÷/ Divide the two numbers ạ Absolute difference with x ¥ ) Ḣ Head ``` [Answer] # JavaScript (ES7), 64 bytes Expects `(value)(max_denominator)`. Returns `[numerator, denominator]`. ``` v=>g=(d,e)=>d?g(d-1,(E=((q=v*d+.5|0)/d-v)**2)>e?e:(r=[q,d],E)):r ``` [Try it online!](https://tio.run/##fc89D4IwEAbg3V/R8Q75aAtVMClOzCauxsHQQjQGFE0n/zvyIQQl8ZKmNzzXe3s5mdMjrc63p1OUSteZrI2McwnK1ihjtc1BOcyGRALcpbHU0hUvip5yDFoWx1hv9QYqebjb6mgniJuqTsviUV61ey1zyIC6a9IXQkAQiec1PSce8Re/kgseik4yMUjWyGAm2fgmo1PJ6B8qxvW0pc292/djYja1CruKEFbDAr@L8o/6A@XtAh7NKB2z8O8sMxl9CqE50w/Wbw "JavaScript (Node.js) – Try It Online") ### Commented ``` v => // outer function taking the float value v g = (d, e) => // inner recursive function taking the maximum denominator d // and the current minimum error e, initially undefined d ? // if d is not equal to 0: g( // do a recursive call: d - 1, ( // decrement d E = ( // compute the new error E = (q / d - v)² (q = v * d // where q is round(v * d) + .5 | 0) // / d - v // ) ** 2 // it's shorter to square than to use Math.abs() ) // > e ? // if E is greater than e (always false if e is still // undefined): e // pass e unchanged : // else: (r = [q, d], E) // save the new result [q, d] in r and pass E ) // end of recursive call : // else: r // return the final result ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~97~~ 90 bytes ``` def f(n,k,a=[1]): while k:p=round(n*k);j=abs(p/k-n);a=[a,(j,p,k)][j<=a[0]];k-=1 return a ``` [Try it online!](https://tio.run/##XY/LDoIwEEX3fsXEVWsGLSDIw/ojpIsaIUDN0FSI8euxCnHhXZ05ucnk2tfYDhTP861uoGGEBrWsQsWLDTzb7l6DKax0w0Q3RjvDy17q64PZgwmIl76qkfVo0XBV9WepK6FUaQIZbsDV4@QI9NwMDgjBQEdQMbE/IRw5gqcoibIEIUyWM/QofrjKNPsmx1T8iXgVAiFaKF@Dec6VX@BjXUcj@7xH2AaXLS4rOZ/f "Python 3 – Try It Online") `round(n*k)` gets the closest numerator for a given denominator `k`. `abs(p/k-n)` calculates the absolute value between this fraction and the input fraction `n`. If this is the best option so far, then update the answer accordingly. Outputs three values: the absolute difference, the numerator and the denominator respectively. *thanks to Noodle9 for -7 bytes* [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 83 bytes ``` param($n,$d)1..$d|%{0..($x=$_)|%{@{n=$_;d=$x}}}|sort{[Math]::Abs($_.n/$_.d-$n)}-t 1 ``` [Try it online!](https://tio.run/##XZBNa4NAEIbP9Vd4mBaXbjZqaxojC5aUQg9tCj2KiMluSIuusrvSgNnfbtWaUDqH4X2fGZiPuvrmUh14UXSwp21X5zIvHRAYGPIIAXa6bl1CHDhSyFBv4lb0KmIUjsaYk6qkbpPXXB/S1epxqxzIiJj3ic1AIDPTttcZCzRXep0rrmjsWLHjkgd8j/Co/MBfBtgLJuthz73IM1wsxwjxwv1P7s7Exf6kwilwGCILWSC5ago9jEZ/Nulvsa5A2tS@gb0dZ4P5bbylyfvHulG6KjfbL77TabKRjEvO0rh9EXWjhw@8NSWXua4kBUlE9MRFVXJxBix6lvlOf1ZiLM8HZCxzWab7AQ "PowerShell – Try It Online") [Answer] # Excel, 72 bytes ``` =LET(a,SEQUENCE(B1),x,ROUND(A1*a,),INDEX(SORTBY(x&"/"&a,ABS(x/a-A1)),1)) ``` [Answer] # [Wolfram Language](https://www.wolfram.com/language/), ~~62~~ 57 bytes -3 bytes thanks to [J42161217](https://codegolf.stackexchange.com/users/67961/j42161217). ``` MinimalBy[Join@@Array[Divide,{#,#}+1,0],a|->Abs[a-#2],1]& ``` [Try it online!](https://tio.run/##XYg9CsIwGEB3r1Fw8dP8aGszCKk4CYK6hgxRUwy0taSxUEou4Q08oUeoaOvim957uXJXnStnzqpLV93OFCZX2boR25spOE@sVY3YmNpcNLQBBH5CAEtQr8czOVVCTQMqgchxt7emcIgnZZk1IpWIH3WtbaURb0ctni1h4eEjNKRxCCTsiwDBPxtWFH9hEOG/MR8GBtoLGwDGvEfocDfadW8 "Wolfram Language (Mathematica) – Try It Online") (uses [\[Function]](http://reference.wolfram.com/language/ref/character/Function.html) rather than `|->`, as TIO doesn't have the most recent version of the language) Does the brute-force method of generating every possible fraction and taking the one closest to the given number. I previously had a solution using [Convergents](http://reference.wolfram.com/language/ref/Convergents.html), but it failed for inputs like `0.1` where, because of the language accounting for inexact numbers, the closest fraction wouldn't appear in the list. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 69 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.625 bytes ``` ʁ:ḢẊµƒ/⁰ε;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyoE64bii4bqKwrXGki/igbDOtTtoIiwiIiwiNVxuMC4xIl0=) A port of the 05AB1E answer updated to 2.6+ and vyncoded. ## Explained ``` ʁ:ḢẊµƒ/⁰ε;h ʁ: # Push two copies of the range [0, input) Ḣ # on one of those copies, remove the first element Ẋ # Take the cartesian product of these two lists µ...; # And sort this by: ƒ/⁰ε # the absolute difference between the second input and the item reduced by division h # output the first item ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 81 bytes ``` n=>k=>eval('for(a=0,b=M=1;b<=k;(m=a/b<n?n-a++/b:a/b++-n)<M&&[R=P,M=m])P=[a,b];R') ``` [Try it online!](https://tio.run/##dcrRCoJAEAXQ9z5EZ1jN1dI0HfsCQXwVH3YlwcxNTPz9TSKIDbpwH@bcuYlVPNu5nxZ3jXVHWlE@UH5dxR3s7jGDIO5IKshPZUZDCiMJT2bqolzBmCfP28WYqzArLKuuqHQKGhssqRaObNLKRj3NvVqgA74/IRwRd18IwiAOEfzQUH8T/ivmSxS/kyBE/M9wMAeOEBiQfIKwFfUL "JavaScript (V8) – Try It Online") Maybe there are edge cases which failed due to floating point errors. But it at least pass all testcases given by OP. [Answer] # JavaScript (ES6), 63 bytes ``` c=>f=(d,M)=>d?f(d-1,M>(N=(.5-d*c%1)**2)?M:(s=d,N)):[c*s+.5|0,s] ``` Like [this](https://codegolf.stackexchange.com/a/221220/83717) answer, expects `(value)(max_denominator)`, and returns `[numerator, denominator]`. Here's how it works: ``` c=> // the decimal - this will not change f=( // the inner recursive function d, // the max denominator. We will decrement this to loop M // the "error" (with a twist) )=> d? // if d is nonzero, we're still recursing f(d-1, // call f with the new denominator we're testing M> // the bigger M is, the closer d*c is to an integer (N= // we'll test the error and save it in N in case we need it (.5-d*c%1)**2 // the error (with the twist); the closer d*c to an integer, the // closer d*c%1 to 0 or 1, the closer .5-d*c%1 to .5, the bigger // (.5-d*c%1)**2 is. This means; bigger "error" is better ) ?M // if M is bigger than the newly checked error, continue with M :( // otherwise, s=d, // save that denominator in s, N // continue with the new error (that we saved in N) ) ) : // if d is zero, we've checked all denominators so we're done [c*s+.5|0, // return the numerator (which is just c*s rounded to the nearest integer) s] // and the denominator, which we saved in s ``` [Answer] # [R](https://www.r-project.org/), 61 bytes ``` function(n,d,a=round(n*1:d))c(a[i<-which.min((a/1:d-n)^2)],i) ``` [Try it online!](https://tio.run/##jc/RCoMgFAbg@57iwG50WKnNlmPtRcY2pIi8mIUstrdvJRHSInaulPP582t71ba2@Twqq4qXbkzeV51xJ2RISVRum86UyOzZqcS4QOqqz@G71kUdPbVBSMXDIjT4zvGNaLyMQzQ6EpjmABhgBxBehguHGJLgl3PBM@GeMOFxNvDDCmdzOqMLzuimF34bOvoVnmZuJIHUi09cG7HpE8/zMZ7LFU/nOvyfOnIaAlIufxv0Xw "R – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` NθFNF⁺²ι⊞υ⟦↔⁻∕κ⊕ιθκ⊕ι⟧I✂⌊υ¹ ``` [Try it online!](https://tio.run/##ZY09C8IwFEX3/oqMLxDFFgpCJ9Glg1JwFIc2jfTRfNgkr38/xk6Cyx3O5dwrp95L1@uUWvumeCMzKA8Lb4qX8wx@IedsY52mAJVgmEFHYQIS7HEagtMUFVzR5vqCK44KZsFaK70yykY1QjYEW77xVzzzY@fRRjj3IcJdo9y20JABykbJeZPSYV/V1bEuyjrtVv0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` FN ``` Input the maximum denominator and loop up to it. (The actual denominator is 1 more than the loop index.) ``` F⁺²ι ``` Loop over the possible numerators. ``` ⊞υ⟦↔⁻∕κ⊕ιθκ⊕ι⟧ ``` Calculate the error and save the numerator and denominator with it. ``` I✂⌊υ¹ ``` Output the numerator and denominator with the smallest error (in the case of a tie, the smallest numerator wins). [Answer] # [JavaScript (V8)](https://v8.dev/), 93 bytes ``` (d,m)=>eval("for(i=1,b=m;i<=m;i++)n=Math.round(d*i),w=Math.abs(d-n/i),w<b?[b=w,x=[n,i]]:0;x") ``` [Try it online!](https://tio.run/##dcpBDoIwFATQvadoWLXywYKCVKiewBMQFq1IrJFCAIHbo6iJqYmzmMWbuYpetKdG1Z3TR1PBJ5xDSfj@3IsbtoqqwYp7IHkZq2Qu2yaaH0V3cZvqrnOcLxWB4S1Ctjh39GqWRB5SyQcYeapBZdmOxqNFprpRusMFpu4W0IaQxRf8wI8CQF5gqPcU@ivmJYxeYYBC@mdYmwMF5BvAPgHEGCHTAw "JavaScript (V8) – Try It Online") **Explanation:** Fairly straighforward approach. Most of the work is done by a `for` loop, wrapped in an `eval` statement. This saves bytes, as it's shorter than wrapping it in `{}` (which requires `return`). During the `for` loop (all iterations are denominators from `1` to `m`), four things happen: * `n` is set to the closest numerator * `w` is set to the distance between the fraction and the `d` (the first number) * `w` is compared with the previous best, `b` (initially `Infinity`) * If `w` is less than `b`, `b` takes `w`'s value and `x` (the output) becomes the outputted fraction [Answer] # [Haskell](https://www.haskell.org/), 100 bytes ``` u=10^8 a#b|b!!0<a!!0=b|1>0=a n!m=tail$foldl1(#)[[min o$u-o,div(n*d+o)u,d]|d<-[1..m],let o=n*d`mod`u] ``` [Try it online!](https://tio.run/##bdBLU4MwEADge3/F9nEAu8WER1uc0l@gJ4@IlhqcdiShY0F74L/jEh5Spzskmdkvu7PhEJ8/kzStqiLg7HU9iqf7cj8es01MW7Av@ZYF8UiNZZDHx3T2kaUi5cbUDEN5VJDNikWG4vhtqDsxz8wCRVSKzSLkliUjTJMcsoBoJzOxK6JKxlQUgIxPT29wKvLn/OtRQQjnQ/YDCuZzmCBM6lNnZHzROQi2g6wBNA6Jqe1FQXI5Je95IuBhcEsVsqm9HyRFotqiyQgoSkMhtUK6jGQmTa7zYKxYEwgugo3gmNiK7dlrTwv3kJP3wvsazmrh7AZ5CPWFXpZrHT7CkqHD0fVukMPQps/vCZpgera6H/Tkt4FAi2uKoopZK@jCpbXY0mbTz3FGzNJP0sS9ljiRS8T7Ks4GxNmVeV1HVhtRNzrQqxpydEfvypzW7LrM9slY39L@37J7F0C9/ib5BQ "Haskell – Try It Online") * input as 8 digits of the decimal part of n. * output a [ numerator, denominator ] list. a#b selects a or b (which are [distance to closest 10^8 multiple, numerator , denominator] ) based on minimum distance. n!m computes every [dist, num, den] from 1 to m , then finds closest fraction folding by # and return only [num,den] [Answer] # [Julia 1.7](https://julialang.org), 37 bytes ``` x|n=argmin(y->(x-y)^2,(0:n).//(1:n)') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZDRCoIwGIXpdk_x30QTUreZpYOCnkMMpFYYNkInKPgm3XTTQ9XTtDY16odx-PftHMa5Pc51kWf3-6NWRzd6TptOrrPydMklbt0NbtzW2bE5Jlw6nu9jqnXm2MevyUyJSlWwhq1sE0S8FQyzsMLA9yHQhIUsCs0V7eVDFprQ0UPJl1Dyg6wHiEGaLCMzMcDSmAIbF_6gwCBmTCzWiIx57C8v7gfgc8ZPoBShQ15di6zFCW-AS-CiuYq9EgfgpajqQgGyJWAjCZ_TFLwOho2lTtr3NZT8Bg) `argmin(f, domain)` needs julia 1.7 or later [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `h`, 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` LDḣṖÞẸ/¹-A ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0UoZS7IKlpSVpuhabfFwe7lj8cOe0w_Me7tqhf2inruOS4qTkYqj0gqWmXAZ6hhAOAA) Port of user100947's 05AB1E answer. #### Explanation ``` LDḣṖÞẸ/¹-A # Implicit input LD # Push [0..input) and duplicate ḣṖ # Cartesian product of [0..input) with [1..input) Þ # Sort by: Ẹ/ # Dump and divide ¹-A # Absolute difference with second input # Implicit output of first item ``` ]
[Question] [ Frequently while I'm code-golfing, I'll want to know what the ASCII value of a certain character is. One of my favorite resources for quickly looking up all of the [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) is [ASCIItable.com](http://www.asciitable.com/). This has a really nice image that not only shows the printable ASCII characters and their values, but also the unprintable and extended characters, and the values in hexadecimal, octal, and HTML: [![enter image description here](https://i.stack.imgur.com/iCOov.gif)](https://i.stack.imgur.com/iCOov.gif) Today's challenge is to recreate that ASCII table as an ASCII table instead of an image. To keep things simpler, we will not use control-characters (characters below 32) and we'll only show the decimal value and the character. In other words, your challenge is to write either a full-program or a function that prints or returns the following text: ``` Dec Chr | Dec Chr | Dec Chr ---------------------------------- 32 Space | 64 @ | 96 ` 33 ! | 65 A | 97 a 34 " | 66 B | 98 b 35 # | 67 C | 99 c 36 $ | 68 D | 100 d 37 % | 69 E | 101 e 38 & | 70 F | 102 f 39 ' | 71 G | 103 g 40 ( | 72 H | 104 h 41 ) | 73 I | 105 i 42 * | 74 J | 106 j 43 + | 75 K | 107 k 44 , | 76 L | 108 l 45 - | 77 M | 109 m 46 . | 78 N | 110 n 47 / | 79 O | 111 o 48 0 | 80 P | 112 p 49 1 | 81 Q | 113 q 50 2 | 82 R | 114 r 51 3 | 83 S | 115 s 52 4 | 84 T | 116 t 53 5 | 85 U | 117 u 54 6 | 86 V | 118 v 55 7 | 87 W | 119 w 56 8 | 88 X | 120 x 57 9 | 89 Y | 121 y 58 : | 90 Z | 122 z 59 ; | 91 [ | 123 { 60 < | 92 \ | 124 | 61 = | 93 ] | 125 } 62 > | 94 ^ | 126 ~ 63 ? | 95 _ | 127 DEL ``` Trailing spaces on each line, and a trailing newline are permitted. Since this is a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, your submission may not take any input, or access any external resources (such as a file or the web), and your goal is to compress the code to output this text as much as possible. Standard loopholes apply, and the shortest answer in bytes wins. Happy golfing! [Answer] ## Python ~~2~~ 3.6, ~~185~~ ~~183~~ ~~175~~ ~~159~~ 156 bytes Saved 8 bytes thanks to FlipTack! Still quite new to golfing in Python. ``` for a in["Dec Chr | "*3,"-"*39]+["".join(f"{l:<5}{('Space',chr(l),'DEL')[(l>32)+(l>126)]:<6}| "for l in(i,32+i,64+i))for i in range(32,64)]:print(a[:-5]) ``` Uses a nested list comprehension to generate the table body. Ungolfed: ``` lines = \ ["Dec Chr | "*3, "-"*39] + # first two lines ["".join( # join 3 parts of each line f"{l:<5}{('Space',chr(l),'DEL')[(l>32)+(l>126)]:<6}| " for l in (i,32+i,64+i) # generate 3 parts of a line ) for i in range(32,64)] for line in lines: print line[:-5] ``` Update: apparently using f-string here is shorter than the `%` operator. --- ### Old attempt, ~~185~~ ~~183~~ 175 bytes ``` print("Dec Chr | "*3)[:-5]+"\n"+"-"*34 a=lambda x:('Space',chr(x),'DEL')[(x>32)+(x>126)] for l in range(32,64):print("%-5d%-6s| "*3%(l,a(l),l+32,a(l+32),l+64,a(l+64)))[:-5] ``` Ungolfed: ``` print ("Dec Chr | "*3)[:-5] + "\n" + "-"*34 def a(x): return "Space" if x==32 else "DEL" if x==127 else chr(x) for line in range(32,64): print ("%-5d%-6s| "*3 % (line, a(line), line+32, a(line+32), line+64, a(line+64))) [:-5] ``` [Answer] # Befunge, ~~176~~ 172 bytes ``` <v"Dec Chr "0 ^>:#,_$1+:2`#v_" |",, \:#->#1_55+,v>55+,"!-":>,#: +2*,:"_"`#@_v>1+:8-#v_$1+:3%!:7g,!29+*5 *84+1%3\/3::<^,gg00:<`"c"p00+5+`"~"\`*84::p62:.:+* Space | DEL ``` [Try it online!](http://befunge.tryitonline.net/#code=PHYiRGVjICBDaHIgICAiMApePjojLF8kMSs6MmAjdl8iIHwiLCwKXDojLT4jMV81NSssdj41NSssIiEtIjo+LCM6CisyKiw6Il8iYCNAX3Y+MSs6OC0jdl8kMSs6MyUhOjdnLCEyOSsqNQoqODQrMSUzXC8zOjo8XixnZzAwOjxgImMicDAwKzUrYCJ+IlxgKjg0OjpwNjI6LjorKgogIFNwYWNlCgp8IERFTA&input=) [Answer] # Pyth, ~~89~~ ~~85~~ ~~79~~ 77 bytes ``` PP*"Dec Chr | "3*\-34V32PPsm++.[`=+N32;5.[?qN32"Space"?qN127"DEL"CN;6"| "3 ``` [Try it online!](http://pyth.herokuapp.com/?code=PP%2a%22Dec++Chr+++%7C+%223%2a%5C-34V32PPsm%2B%2B.%5B%60%3D%2BN32%3B5.%5B%3FqN32%22Space%22%3FqN127%22DEL%22CN%3B6%22%7C+%223&debug=0) [Answer] ## JavaScript (ES6), ~~179~~ 173 bytes ``` f=n=>n?(n>>6?' | ':` `)+n+(99<n?' ':' ')+(126<n?'DEL':String.fromCharCode(n)+' '+f(n>95?n-63:n+32)):`${x='Dec Chr '}| ${x}| ${x} ${'-'.repeat(34)} 32 Space`+f(64) console.log(f()) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~98, 96~~, 94 bytes ``` i32 | 64 | 9631ñÙl.l.ñÍä«/& & ÎéiD@" bsDELF 27kdH5lRSpaceÄÒ-Ä3RDec Chr³ | Î35|D ``` [Try it online!](https://tio.run/nexus/v#@59pbKRQo2BmAiQszaSNDQ9vPDyTMUcvRw/I6D285NBqfTUFBQUxMRCpwHW47/DKTBcHJa6kYhdXH2k3BTEj8@wUD9OcoOCCxORU6cMthyfpHm4xDnJJTVZQcM4oOrQZaLD04T5j0xqX//8B "V – TIO Nexus") Just *barely* squeaking in under a hundred. I'm gonna see if I can beat Pyth, but I won't make any promises. Here is a hexdump: ``` 00000000: 6933 3220 7c20 3634 207c 2039 361b 3331 i32 | 64 | 96.31 00000010: f1d9 016c 2e6c 2ef1 cde4 ab2f 2620 2020 ...l.l...../& 00000020: 1616 2620 2020 200a cee9 6944 4022 0a62 ..& ...iD@".b 00000030: 7344 454c 1b46 2016 3237 6b64 4835 6c52 sDEL.F .27kdH5lR 00000040: 5370 6163 651b c4d2 2dc4 3352 4465 6320 Space...-.3RDec 00000050: 2043 6872 b320 7c20 1bce 3335 7c44 Chr. | ..35|D ``` And here's how it works: ``` i32 | 64 | 96<esc> " Insert some starting text 31ñ ñ " 31 times: Ù " Duplicate this line <C-a> " Increment the first number on this line l. " Increment the next number l. " Increment the next number ``` Here is where it get's interesting. First, let me explain a vim-trick. While in insert mode, certain characters are inserted (all printable ASCII-characters, most unmapped characters above `0x7f`, and a few others), but other characters have a side-effect. For example, `0x1b` (`<esc>`) will escape to normal mode. `0x01` (`<C-a>`) will re-insert the last inserted text, etc. Sometimes, we want to insert these characters literally. So to insert a literal escape character, you must type `<C-v><esc>`. This works for all characters that have a side effect. So essentially, `<C-v>` is the equivalent of a backslash in languages with string literals that allow you to escape certain characters in a string. The other useful trick with `<C-v>` in insert mode, is that it can be used to [insert characters by code-point](http://vimdoc.sourceforge.net/htmldoc/insert.html#i_CTRL-V_digit), in either Decimal, Hexadecimal, Octal, or Hexadecimal Unicode. Since we already have the numbers that correspond to certain ASCII values, we just need to put a `<C-v>` before those characters, and run the corresponding text as vim-keystrokes. This can be achieved with a regex command, and a "Do 'x' on every line" command. So we: ``` Í " Substitute globally: ä« " One or more digits / " With: & " The matched number + some spaces <C-v><C-v>& " A ctrl-v character, then the matched number again " Since ctrl-v is like a backslash, we need two to enter a literal ctrl-v character Î " On every line: éi " Insert an 'i' D " Delete this line @" " Run it as vim keystrokes ``` At this point, the buffer looks like this ``` 32 | 64 @ | 96 ` 33 ! | 65 A | 97 a 34 " | 66 B | 98 b 35 # | 67 C | 99 c 36 $ | 68 D | 100 d 37 % | 69 E | 101 e 38 & | 70 F | 102 f 39 ' | 71 G | 103 g 40 ( | 72 H | 104 h 41 ) | 73 I | 105 i 42 * | 74 J | 106 j 43 + | 75 K | 107 k 44 , | 76 L | 108 l 45 - | 77 M | 109 m 46 . | 78 N | 110 n 47 / | 79 O | 111 o 48 0 | 80 P | 112 p 49 1 | 81 Q | 113 q 50 2 | 82 R | 114 r 51 3 | 83 S | 115 s 52 4 | 84 T | 116 t 53 5 | 85 U | 117 u 54 6 | 86 V | 118 v 55 7 | 87 W | 119 w 56 8 | 88 X | 120 x 57 9 | 89 Y | 121 y 58 : | 90 Z | 122 z 59 ; | 91 [ | 123 { 60 < | 92 \ | 124 | 61 = | 93 ] | 125 } 62 > | 94 ^ | 126 ~ 63 ? | 95 _ | 127 ``` Now we just need some general clean up, which accounts for most of the bytes in this answer ``` bsDEL<esc> " Change the literal 0x7f character to "DEL" F <C-v>27kd " Remove a space from the lines that have too many H5l " Move to the first space character RSpace<esc> " And replace it with "Space" Ä " Duplicate this line Ò- " And replace it with '-'s Ä " Duplicate this line 3R " And replace it with three copies of the following string: Dec Chr³ | <esc> " 'Dec Chr | ' Î35|D " Remove all but the first 35 characters of each line ``` [Answer] ## F#, 222 bytes ``` let c,p=String.concat" | ",printfn"%s" Seq.replicate 3"Dec Chr "|>c|>p p(String.replicate 34"-") for i=32 to 63 do[for j in[i;i+32;i+64]->sprintf"%-5d%-5s"j (match j with 32->"Space"|127->"DEL"|_->string(char j))]|>c|>p ``` [Try it online!](https://repl.it/@AndreSlupik/ProperDemandingOyster-1) [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 167 bytes ``` [[Space]nq]sp[[DEL]nq]sq[[ ]n]sc[Dec Chr]dsen[ | ]dsfnlenlfnlen10P34[[-]n1-d0<a]dsax10P0[[32+dndZ2=c[ ]ndd32=pd127=qP[ ]n]dswx[ | ]nlwx[ | ]nlwx10P95-d32>b]dsbx ``` [Try it online!](https://tio.run/nexus/dc#TY2xCsJAEER/ZXsJJHeKCMbG2FkE7By2SG5PLMKSyxWm8N/jJpXN8JidmV2Ax9iFyJo4j0Bzu2@YAGLlHNDEQHR9Tyw5KojoS4YvHaIOm1Zl6/dAwVoVUp47u3azmSXg3U5Unq4OVmQV8a4epXLHOrXr1PpC8mfGOqrDH1j/dCgsf@kt0c/L8gM "dc – TIO Nexus") How it works: ``` [[Space]nq]sp # p is a macro that prints "Space" and then quits from the call one level up [[DEL]nq]sq # q is a macro that prints "DEL" and then quits from the call one level up [[ ]n]sc # c is a macro that prints a space [Dec Chr]dsen # Save the string "Dec Chr" in register e, and print it. [ | ]dsfn # Save the string " | " in register f, and print it. len # Print "Dec Chr" again. lfn # Print " | " again. len # Print "Dec Chr" again. 10P # Print a newline. 34 # Push 34 on the stack. [[-]n1-d0<a]dsa # a is a macro that repeatedly prints "-" and decrements the top of the stack, while the top of the stack is positive. x10P # Execute macro a, followed by a newline. (This prints the line of hyphens.) 0 # Push 0 on the stack. [ # Starting a large macro (which will be stored in register b) for printing the table row by row. [32+dndZ2=c[ ]ndd32=pd127=qP[ ]n]dsw # w is a macro which: (1) adds 32 to the top of the stack; (2) prints it as a number; (3) uses Z to compute the number of characters the number required to print that number; (4) if it required 2 characters to print the number, calls the macro c to print an extra space (5) prints the string "Space" (for ASCII code 32) or the string "DEL" (for ASCII code 127) or the appropriate character, followed by the right number of spaces x # Execute macro w to print an entry in column 1. [ | ]n # Print a column divider. lwx # Execute macro w to print an entry in column 2 (ASCII code 32 higher than the previous entry). [ | ]n # Print a column divider. lwx # Execute macro w to print an entry in column 3 (ASCII code 32 higher than the previous entry). 10P # Print a newline. 95- # Subtract 95 to adjust to go to the beginning of the next line. d32>b # If the top of stack is <= 32, execute macro b again, effectively looping to print all the rows of the table. ]dsb # End the definition of the large macro, and store it in register b. x # Execute the macro that's in b (with 0 at the top of the stack initially). ``` [Answer] ## Perl, 120 bytes ``` $,="| ";say+("Dec Chr ")x3;say"-"x32;say map{sprintf"%-5s%-6s",$_,$_-32?$_-127?chr:DEL:Space}$_,$_+32,$_+64for 32..63 ``` Run with `-E` flag: ``` perl -E '$,="| ";say+("Dec Chr ")x3;say"-"x32;say map{sprintf"%-5s%-6s",$_,$_-32?$_-127?chr:DEL:Space}$_,$_+32,$_+64for 32..63' ``` *-2 bytes thanks to [@G B](https://codegolf.stackexchange.com/users/18535/g-b).* [Answer] # C, 179 bytes ``` i;f(){for(;i++<37;)printf(i<4?"Dec Chr%s":"-",i<3?" | ":"\n");printf("\n32 Space | ");for(i=64;i<127;i+=i>95?-63:32)printf("%-5d%-6c%s",i,i,i>95?"\n":"| ");puts("127 DEL");} ``` [Try it online!](http://ideone.com/aZ6PdJ) Semi-ungolfed: ``` i; f() { for(;i++<37;) printf(i<4?"Dec Chr%s":"-",i<3?" | ":"\n"); printf("\n32 Space | "); for(i=64;i<127;i+=i>95?-63:32) printf("%-5d%-6c%s",i,i,i>95?"\n":"| "); puts("127 DEL"); } ``` [Answer] ## Ruby, 124 bytes ``` puts [["Dec Chr "]*3*"| ",?-*34,(0..31).map{|d|(1..3).map{|x|"%-5s%-6s"%[y=x*32+d,y<33?"Space":y>126?"DEL":y.chr]}*"| "}] ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~151~~ ~~150~~ ~~148~~ ~~136~~ ~~135~~ ~~130~~ ~~129~~ 125 bytes *12 bytes saved thanks to @nmjcman101 for using `<C-v>g<C-a>` for the numbers instead of `line('.')`* *2 byte saved thanks to @DJMcMayhem for removing lines with leading spaces using `ÇÓ/d` and by using `dê` to remove extra spaces and rearranging stuff* This answer is in competition with @nmjcman101's V [answer](https://codegolf.stackexchange.com/a/106286/41805) (which uses `:set ve=all`). ~~But now, I found a way to remove those `A ^[`s and saved some bytes and we are at an even bytecount~~ ``` iSpace ¬!~Ó./&ò iDELí^/31 HlgGo| 63ÙkGld/Sp $p/` G$d/@ $p/64 G$d/S $pÇÓ/d /d hdê/32 O34é-O!| !| !Ó!/Dec Chr ``` [Try it online!](https://tio.run/nexus/v#@58ZXJCYnKrAJX1ojWLd4cl6@mqHN3Flurj6SB9eG6dvbKigoMAl5pGTzuieX6MgbWZ8eGa2mHtOin5wAZdKgX4Cl5i7Soq@A4htZgLhBAM5h9sPT9ZP4QKijJTDq/SNjbj8pY1NDq/U9VesUQAh6cOTFfVdUpMVFJwzioB2/P8PAA "V – TIO Nexus") Hexdump: ``` 00000000: 6953 7061 6365 200a 1bac 217e d32e 2f26 iSpace ...!~../& 00000010: f20a 6944 454c 1bed 5e2f 3331 2020 200a ..iDEL..^/31 . 00000020: 1648 6c67 0147 6f7c 201b 3633 d96b 1647 .Hlg.Go| .63.k.G 00000030: 6c64 2f53 700a 2470 2f60 0a16 4724 642f ld/Sp.$p/`..G$d/ 00000040: 400a 2470 2f36 340a 1647 2464 2f53 0a24 @.$p/64..G$d/S.$ 00000050: 70c7 d32f 640a 2f64 0a68 64ea 2f33 320a p../d./d.hd./32. 00000060: 4f1b 3334 e92d 4f21 7c20 217c 2021 1bd3 O.34.-O!| !| !.. 00000070: 212f 4465 6320 2043 6872 2020 20 !/Dec Chr ``` ### Explanation (uncomplete and outdated) The strategy here is that I'm using the line numbers to generate the ASCII code points. Note: `^[` is `0x1b`, `^V` is `C-v` First we generate all the characters. ``` iSpace " insert Space ^[¬!~ " insert every character between ! and ~ ``` The current buffer looks like ``` Space !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Now we insert a newline between these characters ``` Ó./&ò " insert a newline before every character (:s/./&\r/g) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~130~~ ~~120~~ 99 bytes Sub 100 club. I'm no longer convinced that `:se ve=all` is the best way of doing this. It's an extra... 11 bytes just for writing the `|`'s! But that's what I have. I'm posting this almost in competition with @KritixiLuthos answer using `:se ve=all` to avoid some `A <esc>`'s. I'm not convinced that either method is better yet, so hopefully this can inspire some golfing on both parties and see which method takes the cake. I'm also half expecting @DJMcMayhem to kick both our pants ``` iSpace ¬!~Ó./&ò iDELí^/31 Hlg:se ve=all 12|êr|2ñ031j$x)PñHd)ÄÒ-Ä3RDec Chr³ | /d hdêÎ35|D ``` [Try it online!](https://tio.run/nexus/v#AXMAjP//aVNwYWNlChvCrCF@w5MuLybDsgppREVMG8OtXi8zMSAgIAoWSGxnATpzZSB2ZT1hbGwKMTJ8FsOqcnwyw7EwFjMxaiR4KVDDsUhkKcOEw5Itw4QzUkRlYyAgQ2hywrMgfCAbL2QKaGTDqsOOMzV8RP// "V – TIO Nexus") Hexdump for the curious (if there's interest I'll just change this to a vim-style hidden character block) ``` 00000000: 6953 7061 6365 0a1b ac21 7ed3 2e2f 26f2 iSpace...!~../&. 00000010: 0a69 4445 4c1b ed5e 2f33 3120 2020 0a16 .iDEL..^/31 .. 00000020: 486c 6701 3a73 6520 7665 3d61 6c6c 0a31 Hlg.:se ve=all.1 00000030: 327c 16ea 727c 32f1 3016 3331 6a24 7829 2|..r|2.0.31j$x) 00000040: 50f1 4864 29c4 d22d c433 5244 6563 2020 P.Hd)..-.3RDec 00000050: 4368 72b3 207c 201b 2f64 0a68 64ea ce33 Chr. | ./d.hd..3 00000060: 357c 44 5|D ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 200 bytes ``` BEGIN{b="-----------";a="Dec Chr ";print a"|",a"|",a"\n-"b b b;for(a=31;a++<63;){printf"%-5d%-6s| %-5d%-6c| %-5d%-5s\n",a,a<33?"Space":sprintf("%c",a),a+32,a+32,a+64,a<63?sprintf("%c",a+64):"DEL"}} ``` Formatted: ``` BEGIN { b="-----------" a="Dec Chr " print a"|",a"|",a"\n-"b b b for(a=31;a++<63;) { printf "%-5d%-6s| %-5d%-6c| %-5d%-5s\n", a, a<33 ? "Space" : sprintf("%c", a), a+32, a+32, a+64, a<63 ? sprintf("%c", a+64) : "DEL" } } ``` [Try it online!](https://tio.run/##VYxBC4JAEIX/yjAgKO4eanMPriKUEkF06epl3JQiMHGDDupv35ZSonnweMx8b@h1t3Zb7A@noUqR/wYVpZjXGmB37QEAVdff2icQjshmK1uOFTip5tH7lIqVojBMpFDB8KEb9Hh08bg0I8xJLykyZeueMEqEyPDcka4xNt@aj552t4BRKNaLyY1jpcj@GbcOYsyLI06TtW8 "AWK – Try It Online") [Answer] ## C 188 Bytes ``` f(){i=31;printf("Dec Chr | Dec Chr | Dec Chr");printf("\n--------------------------");for(;i<63;i++)printf("\n%d%4c | %d%4c | %d%4c",(i+1),(i+1),(i+33),(i+33),(i+65),(i+65));puts("DEL"); ``` Normally looks like this: ``` f() { int i=31; printf("Dec Chr | Dec Chr | Dec Chr"); printf("\n--------------------------"); for(;i<63;i++) printf("\n%d%4c | %d%4c | %d%4c", (i+1),(i+1),(i+33),(i+33), (i+65),(i+65)); puts("DEL"); } ``` [Answer] ## C (249 bytes) Newlines added for clarity. ``` #define L(s,e)for(i=s;i<e;++i) #define P printf main(i){L(0,3)P("Dec Chr %s",i<2?" | ":"\n"); L(0,34)P("-");P("\n");L(32,64){P("%-5d", i); i==32?P("Space"):P("%-5c",i); P(" | %-5d%-5c | %-5d ",i+32,i+32,i+64); i==63?P("DEL"):P("%-5c",i+64);P("\n");}} ``` [Answer] # Java, 434 422 321 bytes ``` class A{public static void main(String[]a){ int k=1,r,s=32; for(;k<4;k++) o("Dec Chr ",k); for(;k<37;k++) o("-",k==36?3:4); for(k=r=s;!(k==64&&r==-63);r=k>95?-63:s,k+=r) o(k+" "+((k>99)?"":" ")+(k==s?"Space":k==127?"DEL ":((char)k+" ")),k/s); } static void o(String s,int j){ System.out.print(s+(j==4?"":j==3?"\n":"|")); } } ``` Java is probably not the best language for this as there is the overhead of classes and main method... You can eliminate main method using a static declaration, reducing the byte count down further: ``` class A{ static{...} ``` but this results in an error (after otherwise successfully running): ``` Exception in thread "main" java.lang.NoSuchMethodException: A.main([Ljava.lang.String;) at java.lang.Class.getMethod(Class.java:1786) ... ``` The byte count does int include newlines or indentation. [Answer] # [Tcl](http://tcl.tk/), 233 bytes ``` lassign {"Dec Chr" " | " 31} h S i set H $h$S$h$S$h\n[string repe - 34] proc p x {format %-5d%c $x $x} time {set H "$H [p [incr i]] $S[p [expr $i+32]] $S[p [expr $i+64]]"} 32 puts [regsub {\ {8}} [regsub \177 $H DEL] " Space"] ``` [Try it online!](https://tio.run/##ZY@9CsIwAIT3PMUR4iQObf3brdDBLWObocbYBrQNSQqFmGePf@Ai3B18Nxycl7eUbq1zuhsQaKkkcOgtBQXweGWRRfTg0MQpjwqsZ/zrZqidt3roYJVRWKFYC2LsKGEwI1xHe289FqvNZSHB5pci8fquEL5LlFWkNqj1IC20EADjb1azsWB6WeT/3XYtBI0ocmIm71Bb1bnpjNAg7GP8cZPtdmAVyuNJfJ5w00pFRUpP "Tcl – Try It Online") [Answer] # PHP, ~~163 149~~ 147 bytes ``` <?=($p=str_pad)(D,31,"ec Chr | D"),$p(" ",32,"-");whhile($i<96)printf("%s%-4d%-6s",$i%3?"| ":" ",$o=$i%3*32+32+$i/3,$i++?$i<96?chr($o):DEL:Space); ``` **breakdown** ``` # print header <?=($p=str_pad)(D,31,"ec Chr | D"),$p("\n",32,"-"); while($i<96) # loop $i from 0 to 96 printf("%s%-4d%-6s", # print formatted: # string, 4 space decimal leftbound, 6 space string leftbound $i%3?"| ":"\n", # linebreak for 1st column, pipe+space else $o=$i%3*32+32+$i/3, # ($i mapped to) ASCII value $i++?$i<96?chr($o):DEL:Space # character ); ``` Using `%-N` is worth the byte that rightbound numbers and character would save. [Answer] # [R](https://www.r-project.org/), ~~235 228 221~~ 212 bytes ``` y=apply(rbind(rep("Dec Chr ",3),1,matrix(sapply(1:96,function(i)paste(i+31,rep(" ",i<69),"if"(i<2,"Space","if"(i>95,"DEL",intToUtf8(c(i+31,rep(32,4))))))),nrow=32)),1,paste,collapse=" | ") y[2]=strrep("-",34) y ``` [Try it online!](https://tio.run/##RY4xT8MwFIT3/grrsTyLx5CkVKSqWShbh0rABAzGOKql4FjPr4JI/e@pSZG48XTf3fE0jcam1I/IHyF@IvuEsPVOqYcDKwXUaKroywqHH8yXZLVuV9Qdo5MwRAw62Swew3VT0YwXKmxWrSYIHWDY1ARPyToPf8Z9e0uwfdyVWJTn4UW6O3T/fFPTUl9EkYdv09T698Q8Q27oe5uyN6BOCvRifK3fTRael2/K32Xxpqs9l24lB6/Y52Mv64WzgiNlnwy8RdDTGQ "R – Try It Online") I tried really hard to get under 200 bytes but these `paste` and `collapse` are killing me. Returns a list of lines. [Answer] # [Stax](https://github.com/tomtheisen/stax), 53 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éV ►Γ┐º╬¼1N_◄╒0└♀α→┴♂┐Y♣╟n»┤3°k⌡{═╥I⌂╜<─W}íè7Y♠Σ▲ÿb#√ ``` [Run and debug it](https://staxlang.xyz/#p=82562010e2bfa7ceac314e5f11d530c00ce01ac10bbf5905c76eafb433f86bf57bcdd2497fbd3cc4577da18a375906e41e986223fb&i=&a=1) [Answer] # JavaScript (ES6), 258 bytes ``` a="Dec Chr | ".repeat(2)+"Dec Chr\n"+"-".repeat(34);for(b=32;64>b;b++)a+="\n"+b+" "+(32==b?"Space ":String.fromCharCode(b)+" ")+"| "+(b+32)+" "+String.fromCharCode(b+32)+" | "+(b+64)+(35<b?" ":" ")+(63==b?"DEL":String.fromCharCode(b+64)) console.log(a) ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 159 bytes ``` ,'Dec Chr'*3-join' | ' '-'*34 32..63|%{($_,($_+32),($_+64)|%{"$_".PadRight(5)+"$(([char]$_,('Space','DEL')[$_-ne32])[$_-in32,127])".padRight(5)})-join' | '} ``` [Try it online!](https://tio.run/nexus/powershell#@6@j7pKarKDgnFGkrmWsm5WfmaeuoKBQo6DOpa4LFDHhMjbS0zMzrlGt1lCJ1wFibWMjTTBtZqIJFFVSiVfSC0hMCcpMzyjRMNXUVlLR0IhOzkgsigWpVw8uSExOVQfa4uqjrhmtEq@bl2psFAtmZeYZG@kYGpnHairpFSBMqNWEOgPoiNr//wE "PowerShell – TIO Nexus") The first two lines are just creating literal strings and leaving them on the pipeline. The first uses the comma operator `,` to create an array, and then `-join`s that array together to create the headers. The second is just a straight string multiplication. The third line loops over `32..63` and each iteration sends three values `$_`, `($_+32)`, and `($_+64)` into an inner loop. The inner loop does a `PadRight` on the value (adds the appropriate spaces to pad to `5` characters). That is then string concatenated `+` with the result of a nested pseudo-ternary `( )[ ]`. The pseudo-ternary selects either the `char` representation of that number, or else `Space` or `DEL` if it's the appropriate value. Again, we `PadRight` the appropriate characters. Those three strings (for example, `32 Space`, `64 @`, `96 ``) are encapsulated in parens and `-join`ed with the column markers into a single string. Each of those 32 strings are then left on the pipeline. At the end of execution, an implicit `Write-Output` inserts a newline between elements on the pipeline, so we get that for free. [Answer] # Perl, ~~165~~ 155 bytes ``` $s='Dec Chr ';$_=join"\n",("$s| $s| $s","-"x34,map{join"| ",map{sprintf'%1$-5d%1$-6c',$_}($_,$_+32,$_+64)}32..63);s/ {8}/ Space/;s/\x7f.*/DEL\n/;print ``` [Answer] # Python 2, ~~1564~~ 218 bytes My first golf, sorry for obvious mistakes ``` print("Dec Chr | "*3)[:-2]+"\n"+"-"*34+"\n32 Space | 64 @ | 96 `" for n in range(33,63):print"| ".join([str(n+x).ljust(5)+chr(n+x).ljust(6)for x in [0,32,64]]) print"63 ? | 95 _ | 127 DEL" ``` [Try it online!](https://tio.run/nexus/python2#VY0xD4IwEIV3fsXlptYC0RZqZNFE3NwckSghKBBTSMGEwf@OB@rg9O69u/ve2NrK9AzjIgfYlxYAXoALxZPIk6nAs0GBHgXBNCtJ@1Ob5QVd6YDMDmB@2WiSKzq3xoKByoDNzL1gSrla8WguQQL7dVMZlnS9ZUYM3H/Uz65nIRd5@ZdoDhNpmEjJ0lXS1UGacucD0orKtr/mkOTyNSu5BogPRxzHNw "Python 2 – TIO Nexus") Incase you're wondering, the first version was a base64 encoded string. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~82~~ 76 bytes ``` žQSDÇƵQ¸«.Bs𔇲”:"DEL"¸«.B)øvyð2×ý})3äøvy… | ©ý}®”†… Chr ÿ”3ר¨'-34×.Á.Á» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L7AYJfD7ce2Bh7acWi1nlPx4Q2PGuY@alh4aBOQtlJycfVRgshoHt5RVnl4g9Hh6Yf31moaH14C4j9qWKZQo3BoJVDo0DqwxgUgIQXnjCIFhcP7gSLGh6cfWnFohbquscnh6XqHG4Ho0O7//wE "05AB1E – Try It Online") Still golfing, this can be improved a lot. --- `žQSDÇƵQ¸«.Bs𔇲”:"DEL"¸«.B)ø` pushes padded numbers with text equivalent: ``` [['32 ', 'Space'], ['33 ', '! '], ['34 ', '" '], ['35 ', '# '], ['36 ', '$ '], ['37 ', '% '], ['38 ', '& '], ['39 ', "' "], ['40 ', '( '], ['41 ', ') '], ['42 ', '* '], ['43 ', '+ '], ['44 ', ', '], ['45 ', '- '], ['46 ', '. '], ['47 ', '/ '], ['48 ', '0 '], ['49 ', '1 '], ['50 ', '2 '], ['51 ', '3 '], ['52 ', '4 '], ['53 ', '5 '], ['54 ', '6 '], ['55 ', '7 '], ['56 ', '8 '], ['57 ', '9 '], ['58 ', ': '], ['59 ', '; '], ['60 ', '< '], ['61 ', '= '], ['62 ', '> '], ['63 ', '? '], ['64 ', '@ '], ['65 ', 'A '], ['66 ', 'B '], ['67 ', 'C '], ['68 ', 'D '], ['69 ', 'E '], ['70 ', 'F '], ['71 ', 'G '], ['72 ', 'H '], ['73 ', 'I '], ['74 ', 'J '], ['75 ', 'K '], ['76 ', 'L '], ['77 ', 'M '], ['78 ', 'N '], ['79 ', 'O '], ['80 ', 'P '], ['81 ', 'Q '], ['82 ', 'R '], ['83 ', 'S '], ['84 ', 'T '], ['85 ', 'U '], ['86 ', 'V '], ['87 ', 'W '], ['88 ', 'X '], ['89 ', 'Y '], ['90 ', 'Z '], ['91 ', '[ '], ['92 ', '\\ '], ['93 ', '] '], ['94 ', '^ '], ['95 ', '_ '], ['96 ', '` '], ['97 ', 'a '], ['98 ', 'b '], ['99 ', 'c '], ['100', 'd '], ['101', 'e '], ['102', 'f '], ['103', 'g '], ['104', 'h '], ['105', 'i '], ['106', 'j '], ['107', 'k '], ['108', 'l '], ['109', 'm '], ['110', 'n '], ['111', 'o '], ['112', 'p '], ['113', 'q '], ['114', 'r '], ['115', 's '], ['116', 't '], ['117', 'u '], ['118', 'v '], ['119', 'w '], ['120', 'x '], ['121', 'y '], ['122', 'z '], ['123', '{ '], ['124', '| '], ['125', '} '], ['126', '~ '], ['127', 'DEL ']] ``` --- `vyð2×ý})3äøvy… | ©ý}` joins 'em together into the table: ``` ['32 Space | 64 @ | 96 ` ', '33 ! | 65 A | 97 a ', '34 " | 66 B | 98 b ', '35 # | 67 C | 99 c ', '36 $ | 68 D | 100 d ', '37 % | 69 E | 101 e ', '38 & | 70 F | 102 f ', "39 ' | 71 G | 103 g ", '40 ( | 72 H | 104 h ', '41 ) | 73 I | 105 i ', '42 * | 74 J | 106 j ', '43 + | 75 K | 107 k ', '44 , | 76 L | 108 l ', '45 - | 77 M | 109 m ', '46 . | 78 N | 110 n ', '47 / | 79 O | 111 o ', '48 0 | 80 P | 112 p ', '49 1 | 81 Q | 113 q ', '50 2 | 82 R | 114 r ', '51 3 | 83 S | 115 s ', '52 4 | 84 T | 116 t ', '53 5 | 85 U | 117 u ', '54 6 | 86 V | 118 v ', '55 7 | 87 W | 119 w ', '56 8 | 88 X | 120 x ', '57 9 | 89 Y | 121 y ', '58 : | 90 Z | 122 z ', '59 ; | 91 [ | 123 { ', '60 < | 92 \\ | 124 | ', '61 = | 93 ] | 125 } ', '62 > | 94 ^ | 126 ~ ', '63 ? | 95 _ | 127 DEL '] ``` --- `®”†… Chr ÿ”3ר¨'-34×.Á.Á»` takes care of the header portion of the table: ``` Dec Chr | Dec Chr | Dec Chr ---------------------------------- 32 Space | 64 @ | 96 ` 33 ! | 65 A | 97 a 34 " | 66 B | 98 b 35 # | 67 C | 99 c 36 $ | 68 D | 100 d 37 % | 69 E | 101 e 38 & | 70 F | 102 f 39 ' | 71 G | 103 g 40 ( | 72 H | 104 h 41 ) | 73 I | 105 i 42 * | 74 J | 106 j 43 + | 75 K | 107 k 44 , | 76 L | 108 l 45 - | 77 M | 109 m 46 . | 78 N | 110 n 47 / | 79 O | 111 o 48 0 | 80 P | 112 p 49 1 | 81 Q | 113 q 50 2 | 82 R | 114 r 51 3 | 83 S | 115 s 52 4 | 84 T | 116 t 53 5 | 85 U | 117 u 54 6 | 86 V | 118 v 55 7 | 87 W | 119 w 56 8 | 88 X | 120 x 57 9 | 89 Y | 121 y 58 : | 90 Z | 122 z 59 ; | 91 [ | 123 { 60 < | 92 \ | 124 | 61 = | 93 ] | 125 } 62 > | 94 ^ | 126 ~ 63 ? | 95 _ | 127 DEL ``` [Answer] # T-SQL, 242 bytes ``` DECLARE @ INT=32PRINT'Dec Chr | Dec Chr | Dec Chr '+REPLICATE('-',34)L:PRINT CONCAT(@,' ',IIF(@=32,'Space | ',CHAR(@)+' | '),@+32,' ',CHAR(@+32),' | ',@+64,SPACE(5-LEN(@+64)),IIF(@=63,'DEL',CHAR(@+64)))SET @+=1IF @<64GOTO L ``` Formatted: ``` DECLARE @ INT=32 PRINT'Dec Chr | Dec Chr | Dec Chr ' + REPLICATE('-',34) L: PRINT CONCAT(@,' ',IIF(@=32,'Space | ',CHAR(@)+' | ') ,@+32,' ',CHAR(@+32),' | ', @+64,SPACE(5-LEN(@+64)),IIF(@=63,'DEL',CHAR(@+64))) SET @+=1 IF @<64 GOTO L ``` Tried a few variations, including replacing various common strings with other variables, but this was the shortest version I found. [Answer] # [Python 3](https://docs.python.org/3/), 154 bytes ``` for l in[['Dec Chr ']*3,['-'*35]]+[[f"{x:<5}{['Space',chr(x),'DEL'][(x>32)+(x>126)]:5}"for x in(c,c+32,c+64)]for c in range(32,64)]:print(' | '.join(l)) ``` [Try it online!](https://tio.run/##FcwxC4MwFATgv/JweYmmhSbVQUqX2q1bx0cGCVoViRIcUqy/PU2WO/jgbv1uw2JVCP3iYIbREmHTGYDH4ABQ50oQnjBXpdYFUZ/tvr6Vx074XlvToTCDY54LbJ4v1MT8XUlexLrIiuu6PLJ07OMxM8IUSsaorlwnNVHBtfbTsehJ69WNdmMIP8DztMTRzHkIfw "Python 3 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 144 bytes ``` (p:=PadRight)["",37,"Dec Chr | "]'(34*"-")'(Join&"| "=>Tr@ChopInto&3<|{p&11<|p&5@Repr@_+(<~32->$Space,127->$DEL~>@_or Char!_)}=>32:127)|Print ``` [Try it online!](https://tio.run/##DYzBCoMgAEB/xckw3epQbgRRItQOGztE7TZGSJPZJUW8zfXrztvjPXjCOTErGQI2VdOL97B8lCNPCFNaprCTMwCtsgAAD@ArwfR0gBkkCb7pZUUwyoY9LG@VNtfVaURr/zUoz2tv0JkP0lg@HXG90SJj@9GIWaZ5UUbuLveN8UnbuBd2N5Ffw2hRxUh8b5fVhfAH "Attache – Try It Online") ]
[Question] [ # Introduction Number theory is full of wonders, in the form of unexpected connections. Here's one of them. Two integers are [co-prime](https://en.wikipedia.org/wiki/Coprime_integers) if they have no factors in common other than 1. Given a number \$N\$, consider all integers from 1 to \$N\$. Draw two such integers *at random* (all integers have the same probability of being selected at each draw; draws are independent and with replacement). Let \$p\$ denote the probability that the two selected integers are co-prime. Then \$p\$ tends to \${6} / {\pi^2} \approx 0.6079...\$ as \$N\$ tends to infinity. # The challenge The purpose of this challenge is to compute \$p\$ as a function of \$N\$. As an example, consider \$N = 4\$. There are 16 possible pairs obtained from the integers 1,2,3,4. 11 of those pairs are co-prime, namely \$(1,1)\$, \$(1,2)\$, \$(1,3)\$, \$(1,4)\$, \$(2,1)\$, \$(3,1)\$, \$(4,1)\$, \$(2,3)\$, \$(3,2)\$, \$(3,4)\$, \$(4,3)\$. Thus \$p = {11} / {16} = 0.6875\$ for \$N = 4\$. The *exact* value of \$p\$ needs to be computed with at least \$4\$ decimals. This implies that the computation has to be deterministic (as opposed to Monte Carlo). But it need not be a direct enumeration of all pairs as above; any method can be used. Function arguments or stdin/stdout may be used. If displaying the output, trailing zeros may be omitted. So for example \$0.6300\$ can be displayed as `0.63`. It should be displayed as a decimal number, not as a fraction (displaying the string `63/100` is not allowed). Winning criterion is fewest bytes. There are no restrictions on the use of built-in functions. # Test cases Input / output (only four decimals are mandatory, as indicated above): ``` 1 / 1.000000000000000 2 / 0.750000000000000 4 / 0.687500000000000 10 / 0.630000000000000 100 / 0.608700000000000 1000 / 0.608383000000000 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~12~~ 8 bytes ``` RÆṪSḤ’÷² ``` [Try it online!](http://jelly.tryitonline.net/#code=UsOG4bmqU-G4pOKAmcO3wrI&input=&args=MTAwMA) The following binary code works with [this version of the Jelly interpreter](https://github.com/DennisMitchell/jelly/tree/0ea6f804d01b9da15070c77e8e7ba3ffa0f9d114). ``` 0000000: 52 91 b0 53 aa b7 9a 8a R..S.... ``` ### Idea Clearly, the number of pairs **(j, k)** such that **j ≤ k** and **j** and **k** are co-prime equals the number of pairs **(k, j)** that satisfy the same conditions. Also, if **j = k**, **j = 1 = k**. Thus, to count the number of co-prime pairs with coordinates between **1** and **n**, it suffices to calculate the amount **m** of pairs **(j, k)** such that **j ≤ k**, then compute **2m - 1**. Finally, since Euler's totient function **φ(k)** yields the number integers between between **1** and **k** that are co-prime to **k**, we can calculate **m** as **φ(1) + … + φ(n)**. ### Code ``` RÆṪSḤ’÷² Input: n R Yield [1, ..., n]. ÆṪ Apply Euler's totient function to each k in [1, ..., n]. S Compute the sum of all results. Ḥ Multiply the result by 2. ’ Subtract 1. ÷² Divide the result by n². ``` [Answer] # Mathematica ~~43~~ 42 bytes I found [Lattice points visible from the origin](https://shreevatsa.wordpress.com/2008/11/07/lattice-points-visible-from-the-origin/), from which the picture below is taken, to be helpful in reframing the problem through the following questions regarding a given square region of the unit lattice: * What fraction of the unit-lattice points have co-prime coordinates? * What fraction of unit-lattice points can be seen from the origin? [![grid](https://i.stack.imgur.com/AUnvH.png)](https://i.stack.imgur.com/AUnvH.png) --- ``` N@Mean[Mean/@Boole@Array[CoprimeQ,{#,#}]]& ``` --- **Examples** Trailing zeros are omitted. ``` N@Mean[Mean/@Boole@Array[CoprimeQ,{#,#}]]&/@Range@10 ``` > > {1., 0.75, 0.777778, 0.6875, 0.76, 0.638889, 0.714286, 0.671875, > 0.679012, 0.63} > > > --- **Timing** The timing, in seconds, precedes the answer. ``` N@Mean[Mean/@Boole@Array[CoprimeQ,{#,#}]]&[1000]// AbsoluteTiming ``` > > {0.605571, 0.608383} > > > [Answer] # Pyth - ~~13~~ 11 bytes ``` .OqR1iM^SQ2 ``` [Test Suite](http://pyth.herokuapp.com/?code=.OqR1iM%5ESQ2&test_suite=1&test_suite_input=1%0A2%0A4%0A10&debug=0). [Answer] ## Mathematica, ~~42~~ 32 bytes ``` Count[GCD~Array~{#,#},1,2]/#^2.& ``` Anonymous function, uses simple brute force. The last case runs in about .37 seconds on my machine. Explanation: ``` & A function taking N and returning Count[ , , ] the number of 1 ones in the 2 second level of ~Array~ a matrix of GCD the greatest common denominators of {#,#} all 2-tuples in [1..N] / divided by # N ^2. squared. ``` [Answer] # Dyalog APL, 15 bytes ``` (+/÷⍴)∘∊1=⍳∘.∨⍳ ``` Pretty straightforward. It's a monadic function train. Iota is the numbers from 1 to input, so we take the outer product by gcd, then count the proportion of ones. [Answer] # Octave, ~~49~~ 47 bytes Just calculating the `gcd` of all pairs and counting. ``` @(n)mean(mean(gcd(c=kron(ones(n,1),1:n),c')<2)) ``` > > The kronecker product is awesome. > > > [Answer] ## Sage, 55 bytes ``` lambda a:n((sum(map(euler_phi,range(1,a+1)))*2-1)/a**2) ``` Thanks to Sage computing everything symbolically, machine epsilon and floating-point issues don't crop up. The tradeoff is, in order to follow the output format rule, an additional call to `n()` (the decimal approximation function) is needed. [Try it online](http://sagecell.sagemath.org/?z=eJwdw0EKgzAQQNF9IHeY5Uw6RSd0JXiSUmTExAZMGtIKHl_p5_04bprnRUGHgvjdM2atGPYttKm-Ezcta0BhvQkROX8X6tQ5T9ZYEz8NDkgFnsKeHyz95X__GqyBq9pS-UHEg06BNByF&lang=sage) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` LÕO·<sn/ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5/BU/0PbbYrz9P//NzQwMAAA "05AB1E – Try It Online") Explanation: ``` L Push inclusive range of (implicit) input (4 -> [1, 2, 3, 4]) Õ Perform Euler's Totient on each element ([1, 2, 3, 4] -> [1, 1, 2, 2]) O Sum list elements ([1, 1, 2, 2] -> 6) ·< Double result and subtract 1 (2*6 - 1 = 11) sn Square input (4 -> 16) / Divide sum by input squared (11 / 16 = 0.6875) (Implicit output) ``` It might be golf-able, I just copied [Dennis' Jelly method](https://codegolf.stackexchange.com/a/67778/89342), and I haven't really bothered trying to make it any smaller. [Answer] # JavaScript (ES6), 88 bytes ``` n=>eval(`p=0;for(i=n;i;i--)for(j=n;j;j--,p+=a)for(a=1,k=j;k>1;k--)a=i%k||j%k?a:0;p/n/n`) ``` ## Explanation ``` n=> eval(` // use eval to enable for loop without {} or return p=0; // p = number of pairs for(i=n;i;i--) // i = 1 to n for(j=n;j;j--,p+=a) // j = i to n, a will equal 1 if i and j are coprime, else 0 for(a=1,k=j;k>1;k--) // for each number from 0 to j a=i%k||j%k?a:0; // if i%k and j%k are both 0, this pair is not coprime p/n/n // return result (equivalent to p/(n*n)) `) ``` ## Test Takes a while for large (`>100`) values of `n`. ``` var solution = n=>eval(`p=0;for(i=n;i;i--)for(j=n;j;j--,p+=a)for(a=1,k=j;k>1;k--)a=i%k||j%k?a:0;p/n/n`) ``` ``` N = <input type="text" id="input" value="100" /> <button onclick="result.textContent=solution(+input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Seriously, 15 bytes ``` ,;ª)u1x`▒`MΣτD/ ``` Hex Dump: ``` 2c3ba62975317860b1604de4e7442f ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=2c3ba62975317860b1604de4e7442f&input=1000) I'm not going to bother explaining it since it literally uses exactly the same algorithm as Dennis's Jelly solution (although I derived it independently). [Answer] # J, ~~19~~ 17 bytes ``` *:%~1-~5+/@p:|@i: ``` Usage: ``` (*:%~1-~5+/@p:|@i:) 4 0.6875 ``` Explanation: ``` *:%~1-~5+/@p:|@i: i: [-n..n] |@ absolute value of each element ([n..1,0,1,..n]) 5+/@p: sum of the totient function for each element 1-~ decreased by one, giving the number of co-prime pairs *:%~ divided by N^2 ``` [Dennis' solution](https://codegolf.stackexchange.com/a/67778/7311) gives a nice explanation how can we use the totient function. [Try it online here.](http://tryj.tk/) [Answer] ## Mathematica, 35 bytes Implements @Dennis's algorithm. ``` (2`4Plus@@EulerPhi@Range[#]-1)/#^2& ``` Compute the sum of the totient (Euler's phi function) over the range from 1 to the input value. Multiply by floating point two (with four digits of precision) and subtract one. (More precision can be retained by using instead "`2`" and "`1`4`".) This is the total number of coprime pairs, so divide by the square of the input to get the desired fraction. Because the two is an approximate number, so is the result. Testing (with timing data in the left column since at least one of us thinks that's interesting), with the function assigned to `f` so that the test line is more easily read.: ``` f=(2`4Plus@@EulerPhi@Range[#]-1)/#^2& RepeatedTiming[f[#]] & /@ {1, 2, 4, 10, 100, 1000} (* {{5.71*10^-6, 1.000}, {5.98*10^-6, 0.750}, {0.000010 , 0.6875}, {0.0000235 , 0.6300}, {0.00028 , 0.6087}, {0.0033 , 0.6084} } *) ``` Edit: Showing extent of the range of inputs (swapping the precision to the one instead of the two because otherwise the results get rather monotonous) and challenging others to do the same... ``` f = (2 Plus @@ EulerPhi@Range[#] - 1`4)/#^2 & {#}~Join~RepeatedTiming[f[#]] & /@ {1, 2, 4, 10, 100, 1000, 10^4, 10^5, 10^6, 10^7} (* Results are {input, wall time, output} {{ 1, 5.3*10^-6, 1.000}, { 2, 6.0*10^-6, 0.7500}, { 4, 0.0000102, 0.68750}, { 10, 0.000023 , 0.63000}, { 100, 0.00028 , 0.6087000}, { 1000, 0.0035 , 0.608383000}, { 10000, 0.040 , 0.60794971000}, { 100000, 0.438 , 0.6079301507000}, { 1000000, 4.811 , 0.607927104783000}, {10000000, 64.0 , 0.60792712854483000}} *) ``` `RepeatedTiming[]` performs the calculation multiple times and takes an average of the times, attempting to ignore cold caches and other effects causing timing outliers. The asymptotic limit is ``` N[6/Pi^2,30] (* 0.607927101854026628663276779258 *) ``` so for arguments >10^4, we can just return "0.6079" and meet the specified precision and accuracy requirements. [Answer] # Julia, 95 bytes ``` n->(c=combinations([1:n;1:n],2);((L=length)(collect(filter(x->gcd(x...)<2,c)))÷2+1)/L(∪(c))) ``` Just the straightforward approach for now; I'll look into shorter/more elegant solutions soon. This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable. Ungolfed: ``` function f(n::Integer) # Get all pairs of the integers from 1 to n c = combinations([1:n; 1:n], 2) # Get the coprime pairs p = filter(x -> gcd(x...) == 1, c) # Compute the probability return (length(collect(p)) ÷ 2 + 1) / length(unique(c)) end ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 25 bytes Making the function anonymous would save a byte, but then I'd have to use `self` making it more expensive overall. ``` f(n)=n^2-sum(j=2,n,f(n\j)) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~20~~ 17 bytes This uses [current version (5.0.0)](https://github.com/lmendo/MATL/releases/tag/5.0.0) of the language. Approach based on [@flawr's answer](https://codegolf.stackexchange.com/a/67818/36398). ``` i:tg!X*t!Zd1=Y)Ym ``` *Edit (April 28, 2015)*: [Try it online!](http://matl.tryitonline.net/#code=aTp0ZyFYKnQhWmQxPVg6WW0&input=MTAw) After this answer was posted, function `Y)` was renamed to `X:`; the link includes that change. ### Example ``` >> matl i:tg!X*t!Zd1=Y)Ym > 100 0.6087 ``` ### Explanation ``` i: % vector 1, 2, ... up to input number tg! % copy, convert into ones, transpose X* % Kronecker product. Produces a matrix t! % copy, transpose Zd % gcd of all pairs 1= % is it equal to 1? Y) % linearize into column array Ym % compute mean ``` --- Old answer: **20 bytes** ``` Oi:t"t@Zd1=sb+w]n2^/ ``` **Explanation** ``` O % produce literal 0. Initiallizes count of co-prime pairs. i % input number, say N : % create vector 1, 2, ... N t % duplicate of vector " % for loop t % duplicate of vector @ % loop variable: each element from vector Zd % gcd of vector and loop variable. Produces a vector 1=s % number of "1" in result. Each "1" indicates co-primality b+w % accumulate into count of co-prime pairs ] % end n2^/ % divide by N^2 ``` [Answer] # [Samau](https://github.com/AlephAlpha/Samau/tree/master/OldSamau), 12 bytes **Disclaimer: Not competing because I updated the language after the question was posted.** ``` ▌;\φΣ2*($2^/ ``` Hex dump (Samau uses CP737 encoding): ``` dd 3b 5c ad 91 32 2a 28 24 32 5e 2f ``` Using the same algorithm as Dennis's answer in Jelly. [Answer] # Python2/Pypy, 178 bytes The `x` file: ``` N={1:set([1])} n=0 c=1.0 e=input() while n<e: n+=1 for d in N[n]: m=n+d try:N[m].add(d) except:N[m]=set([d,m]) for m in range(1,n): if N[m]&N[n]==N[1]:c+=2 print c/n/n ``` Running: ``` $ pypy x <<<1 1.0 $ pypy x <<<10 0.63 $ pypy x <<<100 0.6087 $ pypy x <<<1000 0.608383 ``` The code counts the co-prime pairs `(n,m) for m<n` twice (`c+=2`). This ignores `(i,i) for i=1..n` which is ok except for `(1,1)`, thus being corrected by initialising the counter with `1` (`1.0` to prepare for float division later) to compensate. [Answer] # Factor, ~~120~~ 113 bytes I've spent class golfing this and I can't get it shorter. Translation of: [Julia](https://codegolf.stackexchange.com/a/67876/46231). ``` [ [a,b] dup append 2 <combinations> [ members ] keep [ first2 coprime? ] filter [ length ] bi@ 2 /i 1 + swap /f ] ``` Example runs on the first 5 test cases (a value of 1000 causes it to freeze the editor, and I can't be bothered to compile an executable right now): ``` ! with floating point division IN: scratchpad auto-use { 1 2 4 10 100 } [ [1,b] dup append 2 <combinations> [ members ] keep [ first2 coprime? ] filter [ length ] bi@ 2 /i 1 + swap /f ] map --- Data stack: { 1.0 0.75 0.6875 0.63 0.6087 } ! with rational division IN: scratchpad auto-use { 1 2 4 10 100 } [ [1,b] dup append 2 <combinations> [ members ] keep [ first2 coprime? ] filter [ length ] bi@ 2 /i 1 + swap / ] map --- Data stack: { 1.0 0.75 0.6875 0.63 0.6087 } { 1 3/4 11/16 63/100 6087/10000 } ``` [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 75 bytes ``` > 1 > Input >> φ(L) >> ∑ 1 2 3 >> 4+4 >> ≺5 >> 2² >> 6÷7 >> Output 8 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGQy07BM6@gtITLzk7hfJuGjyaI8ahjooKhgpGCMYhjom0CFuvcZQqijQ5tAlFmh7ebg2j/0hKgbgWL//8NDQwMAA "Whispers v2 – Try It Online") ## How it works Implements [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s [algorithm](https://codegolf.stackexchange.com/a/67778/66833). We calculate \$m = \sum\_{k=1}^n\phi(k)\$. We then double \$m\$ and decrement it to get \$2m-1\$, before squaring \$n\$ and dividing by it, to output \$\frac{2m-1}{n^2}\$ [Answer] # [R](https://www.r-project.org/), 78 bytes ``` mean(mapply(function(x,y)sum(!x%%which(!y%%1:y))<2,1:(N=scan()),rep(1:N,e=N))) ``` [Try it online!](https://tio.run/##DctBCoAgEADAt3gQdsGD21HyC/5BxFBIE03K12/NfTpzib5C8a2dC45Zw52vCq9aOGYB8Ur5pBwSiCUlmYW4b4oMODvC/xBVjw3IOBWtQ0QmrTV/ "R – Try It Online") Uses `which(!y%%1:y)` to calculate divisors of y (including 1), and `!x%%divisors_of_y` to count common divisors of x and y (including 1), so `sum(common_divisors)<2` is `TRUE` for co-prime pairs. The R `mapply` function applies a custom function to two (or more) sets of arguments, here specified as `1:N` and `rep(1:N,each=N)` (which repeats each number in `1:N`, `N` times). Conveniently, R 'recycles' the shorter argument list to the length of the longer one, so `1:N` gets repeated for us automaticaly. ]
[Question] [ # Background Sometimes in calculus you're expected to calculate the sum of an infinite series. Sometimes these series are very friendly, like a geometric series, but add anything else onto it and it can quickly get complicated to solve by hand. Sometimes I like to be lazy - a lot of sums can be found simply by adding the first few terms then making an approximation. Say the sum of the first ten terms is 0.199999983, and the future terms are approaching zero. We can say with a fair degree of certainty that our final answer will be 0.2, or 1/5. # The Challenge Given a decimal number and an integer as inputs, calculate the best (fully simplified) fractional approximation of the decimal number for all fractions up to a denominator of the given integer. The best fractional approximation will be that which is closest to the decimal number in absolute value. You may take these inputs any way you like and you may output the numerator and denominator any way you like. The numerator and denominator must always be integers, and you may assume we will deal with only positive numbers because adding a negative sign is trivial. # Test Cases ``` Input | Output 1.21, 8 | 6/5 3.14159265359, 1000000 | 3126535/995207 19.0, 10000000 | 19/1 3.14159265359, 12 | 22/7 2.7182818, 100 | 193/71 0.8193927511, 22 | 9/11 0.2557463559, 20 | 1/4 0.2557463559, 100 | 11/43 0.0748947977, 225 | 14/187 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins! [Answer] # [Python 3](https://docs.python.org/3/), ~~66~~ 61 bytes ``` lambda x:Fraction(x).limit_denominator from fractions import* ``` [Try it online!](https://tio.run/##ZY3PasQgEIfP9SmGPSVFRMe46sJe@xSFYmtChfgHIyX79GmyW3po5zLMb75vptzaZ05ym66v2@ziu3ewXl6q@2ghp27t2RxiaG9@TDmG5FquZKo5wvSDLBBiybU9b48Oy20hU66wUvAQEkRXuvHLzfTYsKX5kPoLeSo1pNYdEIVp/9P5fifGcj1ROPWbYCgoGCKZGISyeFZSWQqC34sIy/jvxP9RSJBpYdAIc6cIZ0ZYaVErsZ9F3ANUSg9nqQ4B@Z/g4XA9GDtoq/XhqG8 "Python 3 – Try It Online") The above function takes a floating point number and returns a bound function `Fraction.limit_denominator` which, in turn, takes the upper bound for the denominator to return a simplified, approximated fraction as requested. As you can tell, I’m more of an API reader than a golfer. --- * minus 5 bytes [thanks to ovs](/questions/207352/cleaning-up-decimal-numbers/207379#comment491671_207379) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~77~~ 71 bytes *-6 bytes thanks to @ovs !* ``` lambda x,n:min([abs(x-(a:=round(x*b))/b),a,b]for b in range(1,n+1))[1:] ``` [Try it online!](https://tio.run/##ZY/RboMgGIXvfQrSK9iY@KMUMfFJul7gajcSRYJ0sUnf3YFbm2UzXuj5zndQdw0fky1r59dz@7oOeuxOGi3UNqOx@KC7GS8vWDetny72hJenjhDWEappdzxPHnXIWOS1fe8xUPsMhBygOa5mdJMPaL7OWWoNxvapGN/zOZyMbTKEFktRv7j@LfQn1KJROzwHH7k3jm5KPrvBBLy77QhJAkU2FvtPPeDFpuSXfjA24EBQOi6ks@7sPsJ25BiVePt@vgwhOmccfzTtOJ/s75w@ePvYICvkHCiq0Q3tmcjKHCoQiu9FKRRFUGxXhCVsGVNK8EJmoPLigRMHxeCfzSPgnMmM5xJqXkO9OVu9ZBKyIq/jk@JSQPwInvpxJ@VcCFntS5F2@Gaw6k/8sxRBGUkhq1pVUkmZhkQiFYNafgE "Python 3.8 (pre-release) – Try It Online") Simply try all denominators from `1` to `n`, saving all results into a list where each element has the form `[error, numerator, denominator]`. By taking the min of the list, the fraction with the smallest error is selected. [Answer] # [Python 2](https://docs.python.org/2/), ~~168, 135~~, 87 bytes ``` z=i=1 def f(x,y):exec"r=round(x*i);q=abs(r/i-x)\nif q<z:z=q;t=r;u=i\ni+=1;"*y;print t,u ``` [Try it online!](https://tio.run/##jY9BboMwEADPzSus5IJTStkFx3aIf9ILAbu12tgBjAR8nkAq5ZIeuseRZnb3OoYv73CeJ2UVbGptiImGeKRHPehq26rW966Ohr2lRaPKcxe17/ZtoB/OGtKcpuOkmiKotuiVXdirgmK7H4tra10gIe5nE0GCEBNBNzsTZQnkwCQeWMZkTCC9D33ZVf5y0S7omvg@kLOuyr7TxC6N8lt3JHhPfrz7XBsgk/ShLu7/5ef9SBeICQeBAsS9upI0ESAziZzBcjriL0PGeH7I2Gpi@swecspzIXMuOV9lRue/374B "Python 2 – Try It Online") Thank you all for your recommendations on my first golf! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` î*LãΣ`/¹α}н ``` [Try it online](https://tio.run/##ASsA1P9vc2FiaWX//8OuKkzDo86jYC/Cuc6xfdC9//8wLjI1NTc0NjM1NTkKMTAw) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZX/D6/T8jm8@NziBP1D685trL2w97/O/@hoCx1DPSPDWJ1oQyMdYz1DE0NTSyMzU2NTS5CQgYGOkZ65oYWRhaEFkG9kpGOgZ2FoaWxpZG5qCNJkZAAUMTI1NTcxMzaF60ETMjIyBQoZmJtYWJqYW5qbx8YCAA) (except for the two `1000000` test cases, which take too long). **Explanation:** ``` î # Ceil the (implicit) input-decimal * # Multiply it by the (implicit) input-integer L # Pop and push a list in the range [1, ceil(decimal)*int] ã # Create all possible pairs of this list by taking the cartesian product Σ # Sort this list of pairs by: ` # Pop and push both values separated to the stack / # Divide them by one another ¹α # Get the absolute difference with the first input-decimal }н # After the sort: leave only the first pair # (after which it is output implicitly as result) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 169 bytes Maybe the reason why there was no submissions using [Farey sequences](https://en.wikipedia.org/wiki/Farey_sequence) is that the code appears rather lengthy. In short, every proper fraction \$\frac{m}{k}\$ in lowest terms appears in Farey sequence of order \$d\$ if and only if \$k\le d\$. Farey sequences are constructed by taking [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of neighboring terms of lower order: \$\left(\frac ab,\frac cd\right)\to\frac{a+c}{b+d}\$, starting from \$\left(\frac 01,\frac 11\right)\$. And the target number is within one of the intervals \$\left[\frac ab,\frac{a+c}{b+d}\right]\$, \$\left[\frac{a+c}{b+d},\frac cd\right]\$, then we take the interval as a current one. So the algorithm is: 1. Take \$\left(\frac ab,\frac cd\right):=\left(\frac 01,\frac 11\right)\$. 2. Take \$\frac{m}{k}:=\frac{a+c}{b+d}\$ and compare with target. 3. If \$\frac{m}{k}>\$ target, replace \$\frac{a}{b}\$ by \$\frac{m}{k}\$, 4. Else replace \$\frac{c}{d}\$ by \$\frac{m}{k}\$. 5. If the next denominator \$b+d\$ is no more than denominator limit, repeat from 2. 6. Else return nearest from \$\frac ab,\frac cd\$ to the target. ``` def f(e,n,g,j): if n==0:return e,1 x=[(0,1),(1,1)] while True: (a,b),(c,d)=x if b+d>j:break m,k=a+c,b+d x[m*g>n*k]=(m,k) m,k=x[2*n/g-a/b>c/d] return m+e*k,k ``` [Try it online!](https://tio.run/##ZZLNkqMgEMfP4Sm4CYYVQQmaKvIUe8vkgIqJEyUWmppM1b57tjXZPez2Aej/r7tpPsbv@XLzWTGG57NxLW6JY56d2Sfdo03XYm9Mug9uvgePHRNo8zBHkjJBGREwntDm69L1Dv8MdwcZG2JZBaxmDTUP8KFEtW0On/sqOHsFYWBXY7c1AxW8x3GIzwcfX0@GAKFo5Y@jjD0//7C8OtS8gU3eHQxbF1/Z9TmZEEWRSKRguMC/8I4rlCUiF6qUO5WpkmGRrgYwE6vGy1LJVCNRJulfvHBRcvFftgQgJddIJloUshDFmrOGZ1wLlCYFrEqplYAm5BIPdRZdKqXzXaaWOnLN4Pk/8rsSgAxIqvOizHWp9VJILSTnotAIzoi6YbyFGQeHBjvXFxdMcEl9G0a4dYIwGPjTvSIh@mi2EevtUDUWD/sQERBoxP4Euam2oyNTMo19N5Pow0f0mJ7oyt/2cihqbwHDSzJ4R@ZwBzf/2jxpO9/YvicT/I8l1E6Tg/Za0vmZWMqWCT6ASOO4d35ZLkpNqTFrSPMSHKXP3w "Python 3.8 (pre-release) – Try It Online") Eats (entire\_part,proper\_numerator,proper\_denominator,denominator\_limit) and produces (numerator,denominator), like ``` >>> f(3,141592653589793,10**len('141592653589793'),57) (179, 57) ``` P.S. Recursive version is nothing but shorter, even with all whitespace removed: ``` f=(lambda e,n,g,j,a=0,b=1,c=1,d=1: n and( b+d>j and(lambda x,y:(x+e*y,y))(*([(a,b),(c,d)][2*n/g-a/b>c/d])) or((m:=a+c)*g>n*(k:=b+d))and f(e,n,g,j,a,b,m,k)or f(e,n,g,j,m,k,c,d) )or(e,1) ) ``` [Try it online!](https://tio.run/##ZVLRjqQgEHznK3iTdnpVUAY1cX5kdh5QcdZdRYNzyU5y/z4H7uzmckdCaKqqi4Zmvd/eFpuXq3sMDXtMem57TQ1avOI76ibDtuHY@dk3vCaWatszQiltD/3pfd89cz7xXrPPg4nveAdgMTszjS0g67CHy1nENr2@6LQ9dWl/AQgei2Nsrht96CC@nmzMPurG@wJ4WzqwnyqwxRk/YHF/gR7A4Bx8PONxDg8gW@OiKOKJ4EhL@pseU0nyhBdcVuIoc1kh5dk@PJnzHUurSopMEV4l2Q8deF6l/L9s4QkhUkVEongpSl7uObs8TxUnWVL6qBJKcl@ECHrvE3AhpSqOuQw@Ys9Ii3/gp5Mncs9kqiirQlVKBSMZmCLlpSL@jmSc18XdqDNk1rfuzbjGmaRb5nWczN4iTyXbr5a56LU/RPjs01y7iHkAIvwWma3Tq2Fbsq3TeGPRq43gnF32t/0eXxsgg@9CaIh/ezR0tPR5eDKMttfTxDaod6neNuPLG9hob0wDhsV/B57F8WRsCAPSATTNLum/AAPw@AM) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` Nθ⪫…⮌⌊EEN⌊⁺·⁵×θ⊕κ⟦↔⁻θ∕ι⊕κ⊕κι⟧²/ ``` [Try it online!](https://tio.run/##bYzLCsIwFET3fkVwdQOxWrWCdCUVoUJFxJ246OOCF/OoaVPw66NmJeKB2Qxzpr6Vtjal9D7XresPTlVo4cHT0dGS7mFvSEP2rCVmN9PCCQe0HUJBmpRTUJRtyLfMBdtJYywcpetgFiWCnUlhBw/Bcl1bVKh7bODOPwh22VSdka4Pry7MtjRQg0B/hN9KMLqGev7OeDrmPPV@EcXLOFnPV8kiWY/iWcBPBvkC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ Input decimal as a number N Input maximum denominator E Map over implicit range κ Current index (0-indexed) ⊕ Increment (i.e. 1-indexed) × Multiplied by θ Input decimal ⌊⁺·⁵ Round to nearest integer E Map over results ι Current numerator ∕ Divided by ⊕κ Current denominator θ Input decimal ↔⁻ Absolute difference ⊕κ Current denominator ι Current numerator ⟦ ⟧ Make into list ⌊ Take the minimum (absolute difference) ⮌ Reverse the list … ² Take the first two entries ⪫ / Join with literal `/` Implicitly print ``` I'm not 100% sure that the algorithm is correct, so just in case, here's a 34-byte brute-force solution: ``` NθFNF⊕⌈×θ⊕ι⊞υ⟦↔⁻θ∕κ⊕ι⊕ικ⟧I⊟⌊υ/I⊟⌊υ ``` [Try it online!](https://tio.run/##hY5LC4JAFIX3/oqh1R2w0sxAWoVtWhQu2kULH1NenIeOM/79KaNAIugsv/PglHWuS5Vz5w6yteZkRcE0dHTr3ZQmMIWUkjcrNRNMGlZBypCjvMMZBeuh88nURDqKZLavwfrksit6xa1hcERpX@k9DlgxaH70vpFPmuvzVaZRGkjz3kCm2nEJhRVgx8rHnS1n/5LORYtwHcbJahNHceKFQRC4@cAf "Charcoal – Try It Online") Link is to verbose version of code. Very slow, so test case is limited to a denominator of `1000`. Explanation: ``` Nθ ``` Input the decimal. ``` FN ``` Loop over the possible denominators (except 0-indexed, so all of the references to the loop variable have to be incremented). ``` F⊕⌈×θ⊕ι ``` Loop until the nearest numerator above. ``` ⊞υ⟦↔⁻θ∕κ⊕ι⊕ικ⟧ ``` Save the fraction difference and the denominator and numerator. ``` I⊟⌊υ/I⊟⌊υ ``` Print the numerator and denominator of the fraction with the minimum difference. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` mc ×õ ï ñ@ÎaXr÷ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWc&code=bWMg1/Ug7yDxQM5hWHL3&input=WzEuMjEsIDhd) ``` mc ×õ ï ñ@ÎaXr÷ :Implicit input of array U m :Map c : Ceiling × :Reduce by multiplication õ :Range [1,result] ï :Cartesian product with itself ñ :Sort by @ :Passing each pair X through the following function Î : First element of U a : Absolute difference with Xr÷ : X reduced by division :Implicit output of first pair ``` [Answer] # [Zig 0.6.0](https://ziglang.org), 149 bytes ``` fn a(e:f64,m:f64)[2]f64{var n:f64=1;var d=n;var b=d;var c=b;while(d<m){if(n/d>e)d+=1 else n+=1;if(@fabs(n/d-e)<@fabs(b/c-e)){b=n;c=d;}}return.{b,c};} ``` [Try it](https://godbolt.org/z/9MYE8b) Formatted: ``` fn a(e: f64, m: f64) [2]f64 { var n: f64 = 1; var d = n; var b = d; var c = b; while (d < m) { if (n / d > e) d += 1 else n += 1; if (@fabs(n / d - e) < @fabs(b / c - e)) { b = n; c = d; } } return .{ b, c }; } ``` Variable declarations are annoying. [Answer] # [Perl 5](https://www.perl.org/) `-p -MList::Util=min`, ~~65~~, 61 bytes -4 bytes thanks to DomHastings ``` / /;$_=min map abs($`-($-=.5+$_*$`)/$_)." $-/$_",1..$';s;.* ; ``` [Try it online!](https://tio.run/##VY5BasMwEEX3PsWQDthOKlkz9kRShG/QLrszOC60IHASE3lTSq9e1aWr7v6D/@Atb/dZ8kN8r3CoP9P0gUPAoS/Lr9xAE3DsL/EKl2mB6TVVeFYVql7LAcc9nusGx1rvANU2do@kNZYhBb2HkDNpJnBFq6kj8XyUVjwQF6wtOXbkgIwpjHbkW89WiIB5Yxax3bGV7c3mP/8JxnbOd9ZbuwnyfVvWeLumrOYlq@enmNbT6WWN82/4Dw "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~61~~ 60 bytes With a byte saved by Dominic van Essen. ``` function(x,d,n=round(1:d*x))c(m<-order((x-n/1:d)^2)[1],n[m]) ``` [Try it online!](https://tio.run/##dY/BasQgEIbvfQqhFy1GndHJOGX7JMv2smmghzUQdiFvn6qhhUI7p@H/5vvRdZ/VadjnR7neP5eiNzvZ8rYujzJpeJ1eNmOu@nYalnX6WLXehuJrbN7RnOFiy/l2Mfusg0MiTmMkEqswGPWswKenWYNDsCq3YPRUg@ggAQmOFNsthD6NR@ihFyEM3Fxx4efi6BQPf3RgY4i@SegYMmbI3Tyk6LlpweW6CzJBfRN2qxYe6L8P/CbflZXFDgOnLImFuTVSh8lD5v0L "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ċ×⁹p÷/ạ¥Þ⁸Ḣ ``` A dyadic Link accepting the decimal [evaluated as a float] on the left and the denominator limit on the right which yields a pair `[numerator, denominator]` representing the simplified fraction. **[Try it online!](https://tio.run/##ATIAzf9qZWxsef//xIrDl@KBuXDDty/huqHCpcOe4oG44bii////My4xNDE1OTI2NTM1Of8xMg "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ZcuxDcIwEADAPlNkAMvxv/359yyWSxqUgpYylCxAhwQSoqEnUGIWiRcxsZBoaE@69WoYtqW89@mQx8cm3bv5eXpd0jGP0zydS7p2eXcrJQTQCKqV2KhgNTggjz1Z8qoFrIiaQVBAFjCmitEC3npkgmUifg2J2PWW6kTzb79s2Il37JlrptjEDw "Jelly – Try It Online") (big denominator limit cases removed due to inefficiency.) ### How? ``` Ċ×⁹p÷/ạ¥Þ⁸Ḣ - Link: v, d Ċ - ceil (of the decimal value, v) ×⁹ - multiplied by chain's right argument (denominator limit, d) p - Cartesian power (d) -> all pairs [[1,1],...,[1,d],[2,1],...,[Ċ×⁹,d]] (note that any pair representing a non-simplified fraction is to the right of its simplified form) Þ - (stable) sort by: ¥ - last two links as a dyad: / - reduce by: ÷ - division (i.e. evaluate the fraction) ạ ⁸ - absolute difference with the chain's left argument (v) Ḣ - head ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 [bytes](https://github.com/abrudz/SBCS) ``` ⌊.5+(⊃∘⍋1+|⍨⌊⊢-|⍨)∘÷∘⍳×1,⊣ ``` [Try it online!](https://tio.run/##zZCxTsMwEIZ3P0XGhKZx7hzX9swCK@UFKqGyVIKpEqJMSBVKSQUDChMDLGwMFarESN7kXiSc0xZIGWAkiiLn/@67RP/gdNQ9OhuMTo7rc7rOE92h4g2qkvJLKmbjEDqUPzLoRuOqhAnDajmm6U21pGJBxeuF@EXjnK3ntrNSQogpf4qqMvTa1T2b0PHDjFnv@mPEOXseLuq19rdp/l2/vh7yl6mYs/T@omh6S/O7/sEuPw/39vs1JAjBMLAipHIGER8hbS4B7tvLF0UR7mzmRJpYcMqh0eC3IHKCWpusp7T2PqbbyUpLTWZdZpwxjaaFoOLhX93CNxMHNpgEPamFSiAD7bCnlXbxpheGCppMOqcxNdxakn5iz8FJ@GEjA0RpBCYGLFqwjdOMK2mgVWzMo0x4D7TK5LwxZLYVrzcxUK2q/SLtSSbBmg8 "APL (Dyalog Unicode) – Try It Online") A dyadic tacit function that takes the decimal number on its left and the max denominator on its right, and gives a 2-element vector of `[denominator, numerator]`. ### How it works ``` ⌊.5+(⊃∘⍋1+|⍨⌊⊢-|⍨)∘÷∘⍳×1,⊣ ⍝ Left: x, Right: d ∘÷∘⍳ ⍝ v←[1, 1/2, ..., 1/d] ( |⍨) ⍝ Remainder of x divided by each of v |⍨⌊⊢- ⍝ Min distance from x to some integer multiple of v 1+ ⍝ Add 1 to treat close enough numbers as same ⍝ Otherwise it gives something like 5/20 due to FP error ⊃∘⍋ ⍝ D←The index of minimum (the optimal denominator) ×1,⊣ ⍝ Exact fraction (D,Dx) ⌊.5+ ⍝ Round both ``` [Answer] # [Io](http://iolanguage.org/), 78 bytes Port of Surculose Sputum's answer. ``` method(x,y,Range 1to(y)map(a,list((x-(b :=(a*x)round)/a)abs,b,a))min slice(1)) ``` [Try it online!](https://tio.run/##dcxBDoIwEEDRvafocsZU7AyUtiZewrWboqBNoCWACZ4edWM0xvX7@SEtjdjtxXHp6umazjDLuzz4eKkFTQnu2PkevGzDOAHMG6ieMfj1jEO6xTNuPfpqlJX0iF2IYmzDqQZCXBrIMypIOy51rp0UxCj6IcSpjasGODNk2ZJ9glKfojJLLndsNJEUzN/GWpuizPXryOq//UyVKawrjDPmNdVvXB4 "Io – Try It Online") # [Io](http://iolanguage.org/), 93 bytes ``` method(x,y,list(((q :=(r :=Range 0to(y)map(a,(x-(a*x)round/a)abs))indexOf(r min))*x)round,q)) ``` [Try it online!](https://tio.run/##dcy9DoIwFIbh3avoeI6p2B4obU28BhNnlxpAm0D5NYGrRxg0GuPyLU@@19dzwQ5HdpmrfLjXGYx84qXvBwBoF4BumbMLt5yJoYYJK9eA4zDuwG1H7OpHyPYO3bVH9CHLx1OxXCofEF/MW8S5gDiSiVSWUhUry5kkZE3nw1CGTQEUaWnISLOAEJ8iIiNtbEkrKTkj@jZSSidprNYiif/2ExU6MTbRVus1qt44PwE "Io – Try It Online") ## Explanation (ungolfed): ``` method(x, y, // Take two operands r := Range 0 to(y) map(a, // Map in range 0..y (set to r): (x-(a*x)round/a)abs // |x-round(a*x)/a| ) // (Aka find the appropriate numerator) q :=r indexOf(r min) // Set q as the 0-index of the smallest number of r list((q*x)round,q) // Output [numerator,denominator] ) // End function ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes ``` (t=s=1;While[Denominator[s=Rationalize[#,1/t++]]<#2,j=s];j)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PEttjW0Do8IzMnNdolNS8/NzMvsSS/KLrYNgioKD8vMSezKjVaWcdQv0RbOzbWRtlIJ8u2ONY6S1Ptf0BRZl6JQ3q0sZ6hiaGppZGZqbGppY6CoVHs//8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # Julia, 66 bytes ``` r(x,m)=minimum((n=Int(round(x*d));(abs(x-n/d),n//d)) for d=1:m)[2] ``` or ``` (x,m)->minimum((n=Int(round(x*d));(abs(x-n/d),n//d)) for d=1:m)[2] ``` [Answer] # [R](https://www.r-project.org/), 75 bytes ``` function(x,d)c((n=rep(0:1,e=d)+(1:d*x)%/%1)[f<-order((x-n/1:d)^2)[1]],f%%d) ``` [Try it online!](https://tio.run/##fY3RSsQwEEXf/QpBColmk8wk00kW@yXLKtK0sCCtZFfo39e06EMr7Dzee@bcPLef47W73t77/NE2c/89tLfLOIhJJdkKMTS5@xL2CKprknwRcEzPk6xMBfLUvx7GnLosxHQYTGnkG8oTnM@qr6okN2YBGkEF@fhUG3rYNE6DB4pYk6OowK5XQAdrZGIktLz9gajtH7qwEA3ctWKBEM1Og5ohYICwuFaNM7wTWR1KHJEJQOHiKVv/GCRiXzsqW7iajL@D/K4VyO0pyz5Ez5G5jNFCeQOB5x8 "R – Try It Online") Not a competitive answer as it's already beaten by [Kirill](https://codegolf.stackexchange.com/questions/207352/cleaning-up-decimal-numbers/207381#207381), but posting for fun anyway. I didn't think of the `round()` function, so this approach rounds down & then up to generate a double-length list of candidate numerators, and then finds the index of the closest fraction. Since the index might be in the second (rounded-up) part of the list, the denominator is the index *mod* the length of the single-length list. I think it's fair to conclude that the `round()` function indeed serves a useful role... ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. Related to [AoC2015 Day 20](https://adventofcode.com/2015/day/20), Part 1. *[Here's why I'm posting instead of Bubbler](https://chat.stackexchange.com/transcript/240?m=59765196#59765196) [and why not emanresuA](https://chat.stackexchange.com/transcript/message/59777290#59777290)* --- To keep the Elves busy, Santa has them deliver some presents by hand, door-to-door. He sends them down a street with infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on. Each Elf is assigned a number, too, and delivers presents to houses based on that number. Instead of giving out presents at fixed intervals, Santa decides to give them out in longer and longer intervals because apparently he's short of supplies right now. Ignore the fact that [the total number of presents delivered is the same after all](https://en.wikipedia.org/wiki/Aleph_number#Aleph-nought) :P * The first Elf (number 1) delivers presents to the houses numbered 1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5, ... (1, 3, 6, 10, 15, ...) * The second Elf (number 2) delivers presents to the houses numbered 2, 2+3, 2+3+4, 2+3+4+5, 2+3+4+5+6, ... (2, 5, 9, 14, 20, ...) * Elf number 3 delivers presents to houses 3, 3+4, 3+4+5, ... (3, 7, 12, 18, 25, ...) * ... There are infinitely many Elves, numbered starting with 1. Each Elf delivers exactly 1 present at each house. So, the first nine houses on the street end up like this: * House 1 gets 1 present (by Elf 1). * House 2 gets 1 present (by Elf 2). * House 3 gets 2 presents (by Elves 1 and 3). * House 4 gets 1 present (by Elf 4). * House 5 gets 2 presents (by Elves 2 and 5). * House 6 gets 2 presents (by Elves 1 and 6). * House 7 gets 2 presents (by Elves 3 and 7). * House 8 gets 1 present (by Elf 8). * House 9 gets 3 presents (by Elves 2 (2+3+4), 4 (4+5), and 9). So the lowest-numbered house that gets at least 3 presents is House 9. Given a positive number `n`, what is the lowest house number that will get at least `n` presents? Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` n -> answer 1 -> 1 2 -> 3 3 -> 9 4 -> 15 5 -> 45 6 -> 45 7 -> 105 8 -> 105 9 -> 225 10 -> 315 12 -> 315 17 -> 1575 25 -> 10395 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes ``` n->i=1;while(numdiv(i)<n,i+=2);i ``` [Try it online!](https://tio.run/##FcdBDoJADADArzSc2tAldhPjAZePEA4bBG2CtSEo4fWr3mY8rxruXmZIxUKnSdr9ocuE9n7e9INKV2OtU6RWS3ZfDjQIHfiqtv1Y/VPBjEbEML5szBv20jRyGhh6iQxyYYjngah8AQ "Pari/GP – Try It Online") House \$i\$ gets a present from elf \$j\$ \$\iff\$ \$i=\frac{k(j+k-1)}{2}\$ for some \$k \ge 0\$ \$\iff\$ \$k=\frac{\sqrt{(2j-1)^2+8i}-2j+1}{2}\$ for some \$k\$ \$\iff\$ \$(2j-1)^2+8i=l^2\$ for some \$l\$ \$\iff\$ \$8i=(l+2j-1)(l-2j+1)\$ for some \$l\$ \$\iff\$ \$m-8i/m=4j-2\$ for some divisor \$m\$ of \$8i\$. So house \$i\$ gets \$n\$ presents \$\iff\$ \$8i\$ has \$n\$ divisors \$d\$ such that \$d\equiv 2 \pmod{4}\$ \$\iff\$ \$i\$ has \$n\$ odd divisors. But \$i\$ and \$2i\$ has exactly the same number of odd divisors. So we only need to consider the odd numbers, whose divisors are all odd. [Answer] # JavaScript (ES7), 65 bytes ``` f=(n,k)=>(g=n=>n&&!((4*n*--n+8*k+1)**.5%1)+g(n))(k)>=n?k:f(n,-~k) ``` [Try it online!](https://tio.run/##FYxBDoIwEADvvmI9SHbLllgFQU3ryVcYDwQpasnWgPHo1xEPc5rMPOtPPTbD4/XWEm/tNHmLwoGsw86KdZIkS8RcidJa0kqF1JBSWbEylHYoRBjIWTmFg587/Q00HS9gGDYMW4acoWDYMZQMFcOewaxnZmlKuGY@Due6uaOAdQuAJsoY@zbrY4f@P1/Q9AM "JavaScript (Node.js) – Try It Online") ### How? The formula giving the \$x\$-th house visited by Elf number \$n\$ is: $$H\_n(x) = \frac{x(x+2n-1)}{2}$$ We want to know whether Elf number \$n\$ is going to visit some house \$k\$, i.e. if there's some \$x>0\$ such that \$H\_n(x)=k\$. It means that we have to check if the following quadratic equation has a positive integer solution: $$\frac{1}{2}x^2+\left(n-\frac{1}{2}\right)x-k=0$$ The determinant is: $$\Delta = \left(n-\frac{1}{2}\right)^2+2k=n^2-n+2k+\frac{1}{4}$$ Leading to: $$4\Delta = 4n^2-4n+8k+1 = 4n(n-1)+8k+1$$ $$2\sqrt{\Delta} = \sqrt{4n(n-1)+8k+1}$$ Leading to a unique positive value of \$x\$: $$x=\frac{\sqrt{\Delta}+1}{2}-n$$ But the only thing we're interested in is to know whether this \$x\$ is an integer. So we just test whether \$\sqrt{4n(n-1)+8k+1}\$ is an integer (which — if it is — is always odd). Hence the JavaScript test: ``` !((4 * n * --n + 8 * k + 1) ** 0.5 % 1) ``` --- # JavaScript (ES6), 57 bytes This one is a port of [alephalpha's great method](https://codegolf.stackexchange.com/a/238053/58563). ``` f=(n,i=1)=>eval("for(d=n,k=i;k;)d-=i%k--<1")>0?f(n,i+2):i ``` [Try it online!](https://tio.run/##FY1LDoIwGIT3nGJCYmzDX0IRfGHrylMYFw0PrZDWgOH6tS5mFt9MZt5mNUs7289XON/1IQyKObJKcqX71UwsHfzMOuVoVLYZG94JZTejEBeZcl1ch387K/nZhuYOSSgJO0JFqAl7woFwJJwIsoiKoYykrPHI4@7NtC/moHQCtN4tfurzyT8jyrCF0NEyxAfOEx5@ "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Another port of [alephalpha's approach](https://codegolf.stackexchange.com/a/238053). ``` ∞·<.ΔÑg›_ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8Q9tt9M5NOTwx/VHDrvj//40B "05AB1E – Try It Online") A direct brute force approach is a byte longer: ``` ∞.ΔLŒOy¢›_ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTfI5O8q88tOhRw674//@NAQ "05AB1E – Try It Online") ``` ∞ -- infinite list of positive integers ·< -- double and decrement each; this yields the odd integers .Δ -- find the first value that satisfies: Ñg -- the number of divisors ... ›_ -- ... is not less than the input ∞.Δ -- find the first positive integer y that satisfies: L -- range from 1 to y ŒO -- the sums of each contiguous sublist -- these are all of the form sum(a..b) for 1<=a<b<=y y¢ -- count the occurrences of y in the sums ›_ -- is this not less than the input? ``` [Answer] # [R](https://www.r-project.org/), 42 bytes Or **[R](https://www.r-project.org/)>=4.1, 35 bytes** by replacing the word `function` with `\`. ``` function(n){while(sum(!T%%1:T)<n)T=T+2;+T} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7O6PCMzJ1WjuDRXQzFEVdXQKkTTJk8zxDZE28haO6T2f4VtsoahlaGBjqGRjqG5jpGpJldxaolfYm5qsUZOYkFBTqVGhU6apk6F5n8A "R – Try It Online") Another port of [@alephalpha's solution](https://codegolf.stackexchange.com/a/238053/55372). [Answer] # [Husk](https://github.com/barbuz/Husk), ~~10~~ ~~9~~ 8 bytes *Edit: -2 bytes thanks to hint from ovs* ``` ḟȯ≥⁰LḊİ1 ``` [Try it online!](https://tio.run/##ASMA3P9odXNr/23igoHhuKMxMP/huJ/Ir@KJpeKBsEzhuIrEsDH//w "Husk – Try It Online") An alternative [Husk](https://github.com/barbuz/Husk) approach to [rues' answer](https://codegolf.stackexchange.com/a/238066/95126), here porting [alephalpha's method](https://codegolf.stackexchange.com/a/238053/95126). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [N.µxtExNNn-+N·%>½}¾¹@i,q ``` [Try it here!](https://tio.run/##yy9OTMpM/f8/2k/v0NaKEtcKP788XW2/Q9tV7Q7trT2079BOh0ydwv//jUwB) **Decomposition:** ``` func(n) - Number of presents for a given house 'n' xt # s_max = sqrt(2n) E } # for s in 1..s_max xNNn-+N· # n, 2n+s-s^2, 2s %> # if 2n-s^2+s % 2s = 0 ½ # increment present counter ¾ # return present counter main [ # loop n=0..infinity N # push house number to stack .µ # reset present counter to zero xtExNNn-+N·%>½}¾ # func(n) ¹@ # if func(n) >= p: i,q # print N, quit ``` **Explanation:** I wanted to find a mathematical approach rather than a computational one, and I'm decently pleased with what I found. Found through very unscientific means, but works for all numbers I've tested. Making a scatter plot between elf number \$r\$ and house number \$h\$ reveals some nice patterns. Distinct straight lines are formed, which I have named 'series'. Where these series have integer pairs \$(r,h)\$, a house receives one present. An equation was formed to define these series by number: $$ n = sr + \frac{s^2-s}{2} $$ Solving for \$r\$ gives: $$ r = \frac{2n-s^2+s}{2s} $$ Integer solutions for \$r\$ mean that elf \$r\$ visited house \$n\$ on series \$s\$. $$ (2n-s^2+s) \equiv 0 \pmod {2s} $$ means a present was left. All that remains is to iterate over all series for a house to count a number of presents. A maximum series number is defined: $$ s\_{max}= \lfloor \sqrt{2n} \rfloor $$ derived approximately from the h-intercept of each series being $$ r = \frac{s(s+1)}{2} $$ This ensures that \$r \geq 1\$. Iterate over series \$1\$ though \$\sqrt{2n}\$ for each house to determine number of presents. Iterate over houses with this function until finding one with sufficient presents! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` Nθ≔⁰ηW‹№υηθ«≦⊕η≔⟦⟧υFη«≔⁰ζW‹ζη«≦⊕κ≧⁺κζ»⊞υζ»»Iη ``` [Try it online!](https://tio.run/##dY@9DoIwEIDn9ik6tgkmJo5MholECXE1DhUrbSwF@qMJhmevLWBwcbjh7rvvfipOddVS6X2uOmcL11yZxj1J4d4YUSu8TRAP2YsLyRA@MGNw1jplsYsgQT0h6A3BkXaLkKtKs4Ypy26zChZwviTIxfzeaoT5pIF1yxAR@N0zRH9u@zf/MUkrPYmaW1xKZwL7zhxDlM7wePJUGeEISy3CExk1NpxCUu93fvOUHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute force because I'm too tired to work out a formula. ``` Nθ ``` Input `n`. ``` ≔⁰η ``` Start at house `0`. ``` W‹№υηθ« ``` Repeat until `n` visits have been found. ``` ≦⊕η ``` Try the next house. ``` ≔⟦⟧υ ``` Start building up the list of houses visited by the elves. ``` Fη« ``` Loop over enough elves so that the last elf visits the house. (Note that these elves are 0-indexed.) ``` ≔⁰ζ ``` Start at house `0`. ``` W‹ζη« ``` Repeat until the current house has been reached or passed. ``` ≦⊕κ ``` Increase the gap between houses. ``` ≧⁺κζ ``` Visit the next house. ``` »⊞υζ ``` Save the house the elf ended up visiting. ``` »»Iη ``` Output the found house. Porting @alephalpha's method takes 22 bytes: ``` Nθ≔¹ηW‹LΦη¬﹪η⊕κθ≧⁺²ηIη ``` [Try it online!](https://tio.run/##JYxBCsIwEEX3niLLCcSFddmVCELBluINYhsywTRpMxM9fkzpX3x48HgT6jRF7Uvpwpp5yMvbJNhke7oRORvgogRW@qHzRsDTENULlhEeznN1UYkhMvRxzj7u1IUpmcUENjN85D4lNilFr9ej@XIWGUafSYnmyI/JBYa7JgaUsi3lWs5f/wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔¹η ``` Start at house `1`. ``` W‹LΦη¬﹪η⊕κθ ``` While the current house has fewer than `n` divisors (which must all be odd)... ``` ≧⁺²η ``` ... visit the next house but one. ``` Iη ``` Output the found house. [Answer] # [Rust](https://www.rust-lang.org/), 65 64 bytes ``` |n|{let mut i=1;while(1..=i).filter(|j|i%j<1).count()<n{i+=2};i} ``` [Try it online!](https://tio.run/##VZDRboMwDEXf@Qr3YVPSRqgJpR2ifEk1TWxLNlfU1UJQH4BvT4M2suKne@yra9m2a503BJcaiXHok0Y7MFCBH2joJ7h0DrCS5e0bG81kmlbIU4ON05YN5wGfzkfJ049rR47xI/W4qdRY4ujLxFwtMBJQU3vTlgMSPJ8SCMWkAMnFr1YCsllnAopZ74InnyEXsIuwf4RDsG0jvSyoEKBUJLkNm/4jpVriFJQfIqt8isqKufEavgN/9fn@tXq4rIyDum21dW/6Z8UMWxMXsF54xmT0/g4 "Rust – Try It Online") * -1 byte by using `<1` instead of `==0` (thanks @Kevin Cruijssen) [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` f=lambda n,v=1:v*(sum(v%-~u<1for u in range(v))>=n)or f(n,v+2) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU@nzNbQqkxLo7g0V6NMVbeu1MYwLb9IoVQhM0@hKDEvPVWjTFPTzjZPEyiYpgFUrm2k@R@kIhOhwlBHwdBQ04qLs6AoM69EI1MHqDJTU/M/AA "Python 3 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 76 bytes ``` lambda n:next(v for v in range(3**n)if sum(v%u<1for u in range(1,v+1,2))>=n) ``` [Try it online!](https://tio.run/##TckxDoMwDADAmb7CSyUbsrhsCPqSLqkgrSUwKCQRvD6ICW69ZQ//Wevsuk8e7fTtLWijwxYwgZs9JBAFb/U3YF2WSuJgjROmZ2z5/Hg9m1SxeRG9O6V8ptwTmKl5FIsXDSgGHApRPgA "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 32 bytes ``` 1//.i_/;0~DivisorSigma~i<#:>i+2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731BfXy8zXt/aoM4lsyyzOL8oODM9N7Eu00bZyi5T20jtf0BRZl5JdFq0YWwsF4xtgsQ2NIiN/Q8A "Wolfram Language (Mathematica) – Try It Online") *-20 bytes thanks to att! Also thanks to ovs.* Based off [alephaleph's excellent insight](https://codegolf.stackexchange.com/a/238053/15469), and probably not a great Wolfram golf but I couldn't resist those builtins. I'll look forward to att setting me straight. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes Fixed a bug and saved 3 bytes thanks to Dominic Van Essen! ``` ḟo≥⁰S#ȯṁ∫ṫḣN ``` [Try it online!](https://tio.run/##ATkAxv9odXNr/23igoH/4bifb@KJpeKBsFMjyK/huYHiiKvhuavhuKNO////WzEsMiwzLDQsNSw2LDcsOF0 "Husk – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 66 bytes ``` ->n,*r{w=[];1.step.find{|x|w+=r=[0,*r].map{|y|y+x};w.count(x)>=n}} ``` [Try it online!](https://tio.run/##FcpLCoAgFADAq7QKzXrkOp4XCRf9hBaZWKGint1qPWOfORSFpRO6bWx0OMqBw3VvBtSu15h8cgwtjv3HEo7JxBRSYD4PDpbz0TfxVKDOuZiKcADe03@RWtHyAg "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @>Xâ Ê*Xu}f ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QD5Y4iDKKlh1fWY&input=WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDEyLDE3LDI1XS1t) Port of @alephalpha answer. [Answer] # TI-Basic, 32 bytes ``` Input N 1 While N>sum(seq(not(IfPart(Ans/I)),I,1,Ans Ans+2 End Ans ``` Port of [alephalpha's solution](https://codegolf.stackexchange.com/a/238053/58563). Output is stored in `Ans` and displayed. [Answer] # Python3, 162 bytes: ``` r=range q=lambda h,n,l:any(i==h for i in l if i and l.count(i)>=n) f=lambda n,h=1:h if(v:=q(h,n,[sum(r(x,y+1))for x in r(1, h+1)for y in r(1, h+1)]))else f(n,h+1) ``` A basic brute-force approach. [Try it online](https://tio.run/##VY7BCsIwDIbve4ocUyzCEEQG8UXEQ3WrLXRZl22yPn1tBQ/mlHz8@ZKYVjfx6RIlZyEx/BqamYIZH70Bp1mHznBCT@TATgIePEMAb0tnuIdwfE4br@jVlVg19rfK2lHbuRLEd0czVtVt2UYU3HU6tEpV215tgq0GV1Al6Y/clRrCMoDF4itzjuLLseCXFUcT0Wr4vlzzZ1UqfwA). [Answer] # Java, 73 bytes ``` n->{int r=1,c=1,j;for(;c<n;)for(r+=2,c=j=1;j<r;)if(r%j++<1)c++;return r;} ``` Port of [*@alephalpha*'s Pari/GP answer](https://codegolf.stackexchange.com/a/238053/52210). [Try it online.](https://tio.run/##fZDBasMwDIbvfQoRGNh4DbGhFOpkb7Beehw7eG4y7KVOUZzCKHn2TM6ynkYO/rGlT78ke3MzW3/@mmxr@h5ejQv3DYALscbG2BqO6TkHwLKkgWuKjBuSPproLBwhQDWF7cs95bGSz5aO102HTNsyaJ5uKCpFCV9J7UvU3DUMn7wQpeRWCI11HDAA6nHSyfs6fLTkvbS4de4MFxqOnSK68Pn2bvjvYMk6tXXkC66UBakQfM4BnL77WF/yboj5lepiG5gT2QEgEyGnffi8zL9cJovDgslilVMPTq1y@we3X@PU7o9TO7589jj9AA) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=1, // Result-integer `r`, starting at 1 c=1, // Count-integer, starting at 1 j; // Temp integer, uninitialized for(;c<n;) // Loop as long as the count is smaller than the input: for(r+=2, // Increase `r` by 2 c=j=1; // Reset the count to 1, j<r;) // Loop `j` in the range [1,r): if(r%j++<1) // If `r` is divisible by `j`: // (and increase `j` by 1 afterwards with `j++`) c++; // Increase the count by 1 return r;} // After the nested loops: return the result ``` [Answer] # TypeScript Types, 302 bytes ``` //@ts-ignore type a<N,M=[]>=N extends M["length"]?M:a<N,[...M,0]>;type b<N,E,C,M=[]>=M extends N?[...C,0]:M extends[...N,...0[]]?C:b<N,[...E,0],C,[...M,...E]>;type c<N,M=[0],C=[0]>=N extends M?C:c<N,[...M,0],b<N,M,C>>;type d<N,M=[0]>=c<M>extends[...N,...0[]]?M["length"]:d<N,[...M,0]>;type M<X>=d<a<X>> ``` [Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4A5AGgFkBeAbQF0A+W8w9AD3HUQBNIhavQBEAG17xwACxGMA-NQBcZKvQB0m6pQAMLANy4ChAEYVKAUUoBhGgxa1qHbrwGFy8jZtt6lTrjz8kF7qVJrqOkwK1kpmauFWejaUIdoJBkZEAMbmdPRJ1gx6rOwBroLU8jE58Vq6jJRxNDbMzIb4RHy5RQ451MxlQSFhmpGMCsLikjJySl216trF7cbUpAAarF1km8yY2B2EACoAjIS0QqQnbZgghPcAevIHxkcATOeXbzd3j8+ZxwAzJ81oCfsB7oQni8iEcACwg0hw8GQ6EAo4AVkRGJRfxhxwAbIiCbiof9DkcAOyIymktEUgAciIZdOeQA) ## Ungolfed / Explanation ``` type NumToTuple<N,M=[]> = N extends M["length"] ? M : NumToTuple<N,[...M,0]> type CheckElf<HouseNum, NumToAdd, PresentCount, Sum=[]> = Sum extends HouseNum // If Sum == HouseNum, return ElfCount + 1 ? [...PresentCount, 0] : Sum extends [...HouseNum, ...0[]] // Otherwise, if Sum >= HouseNum, return ElfCount ? PresentCount // Othwerise, add NumToAdd to Sum, increase NumToAdd, and recurse : CheckElf<HouseNum, [...NumToAdd, 0], PresentCount, [...Sum, ...NumToAdd]> type CountPresents<HouseNum, ElfNum=[0], PresentCount=[0]> = HouseNum extends ElfNum // If HouseNum == ElfNum, return PresentCount ? PresentCount // Otherwise, check this elf, add one to ElfNum, and recurse : CountPresents<HouseNum, [...ElfNum,0], CheckElf<HouseNum, ElfNum, PresentCount>> type FindHouse<PresentMin, HouseNum=[0]> = CountPresents<HouseNum> extends [...PresentMin,...0[]] // If the number of presents at this house is >= the minumum, return this house number ? HouseNum["length"] // Otherwise, check the next house number : FindHouse<PresentMin,[...HouseNum,0]> type Main<X> = FindHouse<NumToTuple<X>> ``` ]
[Question] [ # Challenge In this challenge, you will be writing the first program, p1, of an infinite sequence of programs, in which running pn outputs/generates program pn+1. When concatenating the first n >= 2 programs, the sequence should output `n`. # Example Let's say the first 4 programs are: ``` p1 p2 p3 p4 ``` If I were to run `p1`, it should output: ``` p2 ``` If I were to run `p1p2`, it should output: ``` 2 ``` If I were to run `p1p2p3p4` it should output: ``` 4 ``` If I were to run `p4`, it should generate the next program in the sequence: ``` p5 ``` ## Scoring Your score is the byte count of the first `10` programs. [Answer] # Pyth, 12 p1: ``` l"1 ``` p2: `1` p3: `1` *etc..* p1p2p3: ``` l"111 ``` Output: `3` **Explanation:** ``` l length "1 string "1" ``` On first run, this outputs the length of a single character string, `1`. This also happens to be a valid Pyth program, outputting `1` again. Therefore, *pn+1* is always `1`. When the programs are chained, `p1` outputs the length of the chained programs, which will be `n`. [Answer] # Lua, ~~950~~ 900 bytes ``` s=io.open(arg[0]):read()if#s<95 then print(s)do return end end print(#s/90) do return end; ``` Ungolfed: ``` s=io.open(arg[0]):read'*a' if #s < 96 then print(s) do return end end print(#s/90) do return end; ``` Explanation: The first line grabs the entire source of the program. Then we compare the length of the entire program to 1 + the length of one single program. If the size of the current program is smaller than this value, than the source is printed, which is the next program, p2, and we exit. Each iteration is just a quine. When several of these are put together, the the conditional fails, and we print the length of the concatenated program divided by the length of one program, which is the number of concatenated programs, n. [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 19 bytes Not dealing with strings here, but using method tricks. ### p1 ``` 1ml1-\+N 1 ``` ### p2 ``` 1 ``` ### p3 ``` 1 ``` So on, so forth. Explanation below: ``` 1ml1-\+N 1m Execute the first index of lines (the bit with the ones) l1- Get the length minus 1. \+ Add them all up. N Output as number. 1 Push one to the stack. ``` [Try it online!](http://vitsy.tryitonline.net/#code=MW1sMS1cK04KMQ&input=&debug=on) [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 14 bytes Similar to the Pyth and Jolf answers, I'm mapping strings. The only difference is that I use the line wrapping features to make sure I always get the right length. p1 ``` 'l3-N ``` p2 ``` 1 ``` Replace 1 with *any* single number. p3 and so on match this pattern, and you can do this until `Integer.MAX_VALUE`, the integer restriction of the language. Explanation: ``` 'l3-N ' Wrap around the line until finding another '. Since no ' is found before the End of the line, it wraps around. l Get the length of the stack. 3- Subtract three. N Output as number. ``` [Try it online!](http://vitsy.tryitonline.net/#code=J2wzLU4&input=&debug=on) [Answer] # Seriously, 15 bytes First program, 6 bytes (contains an unprintable): ``` 5Ql-. ``` Hex Dump: ``` 35516c2d2e7f ``` This program prints `1`: [Try it online](http://seriouslylang.herokuapp.com/link/code=35516c2d2e7f&input=) The rest of the programs are all `1`, a valid program that prints itself just like the Pyth answer. The original program prints the length of its source code minus 5 and terminates immediately. `1`s appended to the end increase the length of the source code by 1 byte each time, but never get executed. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 14 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=YS1scTQ) ``` a-lq4 a print lq the length of the source code - 4 minus 4 ``` When executed, this prints `1`. Thus, `p2 = 1`. Executing `p2` yields `1`. So, for all `N > 1`, `pN = 1`. Observe `p1p2`: `a-1q41`. This transpiles to: ``` alert(sub(length("a-lq41"),4)); 1; ``` Since implicit printing is disabled after the first print, this prints `2`, as the length of the source code minus 4 is 2. And on and on and on. [Answer] # Ruby, 318 bytes ### p1: ``` x=DATA.readlines.size _="_=%p;puts _%%_" puts x>0?x+1:_%_ __END__ ``` Each separate program pi outputs [this](https://stackoverflow.com/a/2475931/1373657) one-line quine: `_="_=%p;puts _%%_";puts _%_`. When you add these quines to the end of p1, they end up as lines in the `DATA` object because they are below the magic `__END__`. Here's a test: ``` $ ruby chain.rb # running p1 _="_=%p;puts _%%_";puts _%_ $ ruby -e '_="_=%p;puts _%%_";puts _%_' # running p2 _="_=%p;puts _%%_";puts _%_ $ ruby -e '_="_=%p;puts _%%_";puts _%_' # running p3 _="_=%p;puts _%%_";puts _%_ $ # Concatenating p2 and p3 to p1: $ ruby -e '_="_=%p;puts _%%_";puts _%_' >> chain.rb $ ruby -e '_="_=%p;puts _%%_";puts _%_' >> chain.rb $ ruby chain.rb # running p1p2p3 3 ``` The ten first programs concatenated looks like this (318 bytes): ``` x=DATA.readlines.size _="_=%p;puts _%%_" puts x>0?x+1:_%_ __END__ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ _="_=%p;puts _%%_";puts _%_ ``` [Answer] # C#, 2099 + 7 = 2106 bytes First program (uses compiler flag `/main:A`): ``` class A{static void Main(){int a=System.Reflection.Assembly.GetEntryAssembly().GetTypes().Length;var b=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a>1?"{2}":b,0,b.Replace("\"","\"\""),a);}} ``` Second program: ``` class A0{static void Main(){var a=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a,0+1,a.Replace("\"","\"\""));}} ``` Third program: ``` class A1{static void Main(){var a=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a,1+1,a.Replace("\"","\"\""));}} ``` You get the idea. [Answer] # Javascript ES6, score ~~483~~ 455 Program 1, 77 bytes: ``` v=1;setTimeout(_=>alert(v>1?v:'a=_=>this.v?v++:alert("a="+a+";a();");a();')); ``` Program 2 and beyond, 42 bytes each: ``` a=_=>this.v?v++:alert("a="+a+";a();");a(); ``` [Answer] # PHP, 1470 bytes Program 1: 219 bytes: ``` class O{public$n=1;function __destruct(){echo($n=$this->n)>1?$n:'if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a));';}}$o=new O(); ``` progam 2 and beyond 139 bytes: ``` if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a)); ``` use like: ``` php -r "class O{public$n=1;function __destruct(){echo($n=$this->n)>1?$n:'if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a));';}}$o=new O();" ``` Uses a slightly golfed version the php quine technique detailed here: <http://10types.co.uk/the-lab/a-minimal-php-quine/> ]
[Question] [ You task here is very simple: Given a positive integer `n` without leading zeroes as input, split it in all possible ways ## Examples **Input->Output** ``` 111 -> {{111}, {1, 11}, {11, 1}, {1, 1, 1}} 123 -> {{123}, {12, 3}, {1, 23}, {1, 2, 3}} 8451 -> {{8451}, {845, 1}, {8, 451}, {84, 51}, {84, 5, 1}, {8, 45, 1}, {8, 4, 51}, {8, 4, 5, 1}} 10002-> {{10002},{1,2},{10,2},{100,2},{1000,2},{1,0,2},{10,0,2},{100,0,2},{1,0,0,2},{10,0,0,2},{1,0,0,0,2}} 42690-> {{42690}, {4269, 0}, {4, 2690}, {426, 90}, {42, 690}, {426, 9, 0}, {4, 269, 0}, {4, 2, 690}, {42, 69, 0}, {42, 6, 90}, {4, 26, 90}, {42, 6, 9, 0}, {4, 26, 9, 0}, {4, 2, 69, 0}, {4, 2, 6, 90}, {4, 2, 6, 9, 0}} ``` ## Rules Leading zeroes, if they occur, should be removed. Duplicate partitions in your final list should also be removed. This is `code-golf`. Shortest answer in bytes, wins! [Sandbox](https://codegolf.meta.stackexchange.com/a/19258/67961) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ṫ{~cịᵐ}ᵘ ``` Convert to string `ṫ` and get all unique `{…}ᵘ` reverse concatenations `~c` mapped to integers `ịᵐ` (to remove leading zeros). [Try it online!](https://tio.run/##ASUA2v9icmFjaHlsb2cy///huat7fmPhu4vhtZB94bWY//8xMDAwMv9a "Brachylog – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` .œïÙ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f7@jkw@sPz/z/39DAwMAIAA "05AB1E – Try It Online") --- ### Explanation ``` .œ - Partitions of implicit input ï - Converted to integers (will remove leading 0s) Ù - Uniquified - Output implicitly ``` [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` f=lambda s:{(int(s),)}|{a+b for i in range(1,len(s))for a in f(s[:i])for b in f(s[i:])} ``` [Try it online!](https://tio.run/##XZDRboMgFIbveYpzV8hoI9gtnUn7IksvbKobiUUiZlnT@ezuHBSL80K/852fA@ju/Vdr83Gsj015u1xL8MWDG9tzL6QYfh/lywXqtgMDxkJX2s@KK9lUFvuCfEm@5v6jMOcgLlGY4iyG0dxc2/Xg754xajfGVpRAsfP91diCAT7GOgnVj4NjSOy8a0zPN9vTRrAYwB6@cVVnHBfBTivwvdigXUc3qPEeTsARA99lwzElxKiUAtie4MGRpJCA1wGlAhBFQzgwpfOY1vmU1hLyOaQXIDeww/5VTWmiEEeYhx4koJychITSfsJLZuL5PFmW6ek8RPP5dfhk8fuESHJRMkkl3bS/0lQMbK/f3rOwbaCwLZGELCD@AdSzlRBRwsqu0kmRxAhjh4plFq1ZDf43b12mY6YyHfRcPfwB "Python 3 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` {sMM./ ``` [Try it online!](https://tio.run/##K6gsyfj/v7rY11dP//9/JUMDAwMjJQA "Pyth – Try It Online") ## Explanation ``` {sMM./ ./ # Partitions of implicit input sMM # Convert to integers (to remove leading 0s) { # Deduplicate ``` [Answer] # [R](https://www.r-project.org/), ~~136~~ 126 bytes *Edit: -10 bytes thanks to Giuseppe* ``` function(s,n=nchar(s))unique(lapply(apply(!combn(rep(1:0,n),n-1),2,which),function(i)as.double(substring(s,c(1,i+1),c(i,n))))) ``` [Try it online!](https://tio.run/##VY5LCgIxEAXP4q4bWzGjK2HOIkkbTUOmJ@aDePoYEQTfonZVvNxLilIv2hbn89xvTbnKqlBIZ@VgMxTEpvJoHqJNKb7gyw2vi1PIPoE5H0iRdGeQJnoG4YD0Kwnasr@uzUUPpblSs@h99BkMyXYoDDL0z/7OgJmOJ@xv "R – Try It Online") Hmm... I suspect that this mayn't be the shortest way... but so far my attempts at recursive solutions have been *even* longer... **Commented code:** ``` split_number= function(s,n=nchar(s)) # s=input number (converted to string), n=digits unique( # output unique values from... lapply( # ...looping over all... apply( # ...combinations of breakpoints by selecting all... !combn(rep(1:0,n),n-1), # ...combinations of TRUE,FALSE at each position... 1,which), # ...and finding indices, function(i) # ...then, for each combination of breakpoints... as.double( # ...get numeric value of... substring(s,c(1,i+1),c(i,n)) # ...the substrings of the input number ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes ``` ŒṖḌQ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0RP4//9/EyMzSwMA "Jelly – Try It Online") [-1 byte](https://codegolf.stackexchange.com/questions/210321/split-a-number-in-every-possible-way/210324?noredirect=1#comment495778_210324) thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) ## How it works ``` ŒṖḌQ - Main link. Takes an integer as argument (e.g. n = 42690) ŒṖ - Get all partitions. Automatically cast to digits [[4, 2, 6, 9, 0], [4, 2, 6, [9, 0]], [4, 2, [6, 9], 0], [4, 2, [6, 9, 0]], [4, [2, 6], 9, 0], [4, [2, 6], [9, 0]], [4, [2, 6, 9], 0], [4, [2, 6, 9, 0]], [[4, 2], 6, 9, 0], [[4, 2], 6, [9, 0]], [[4, 2], [6, 9], 0], [[4, 2], [6, 9, 0]], [[4, 2, 6], 9, 0], [[4, 2, 6], [9, 0]], [[4, 2, 6, 9], 0], [4, 2, 6, 9, 0]] Ḍ - Convert each list back to digits [[4, 2, 6, 9, 0], [4, 2, 6, 90], [4, 2, 69, 0], [4, 2, 690], [4, 26, 9, 0], [4, 26, 90], [4, 269, 0], [4, 2690], [42, 6, 9, 0], [42, 6, 90], [42, 69, 0], [42, 690], [426, 9, 0], [426, 90], [4269, 0], 42690] Q - Remove duplicates [[4, 2, 6, 9, 0], [4, 2, 6, 90], [4, 2, 69, 0], [4, 2, 690], [4, 26, 9, 0], [4, 26, 90], [4, 269, 0], [4, 2690], [42, 6, 9, 0], [42, 6, 90], [42, 69, 0], [42, 690], [426, 9, 0], [426, 90], [4269, 0], 42690] - Implicit output ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq -F`, ~~108~~ ~~96~~ ~~94~~ 90 bytes ``` say uniq map{@b=(sprintf'%b',$_)=~/./g;$_="@F ";s/ /','x pop@b/ge;s/\d+/$&*1/reg}1..2**$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVKhNC@zUCE3saDaIclWo7igKDOvJE1dNUldRyVe07ZOX08/3Vol3lbJwY1LybpYX0FfXUe9QqEgv8AhST89FSgSk6Ktr6KmZahflJpea6inZ6SlpaLs9v@/oYGBgdG//IKSzPy84v@6vqZ6BoYGQNons7jEyiq0JDPHFmT1f103AA "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), ~~139~~...~~104~~ 94 bytes ``` def f(? :String):Set[_]=Set(?)++(for{< <-1 to?.size-1 x<-f(?take<) y<-f(?drop<)}yield x+","+y) ``` [Try it online!](https://tio.run/##PY3BboMwDIbveQor2iEWo0pYW20oFdpxh516rKaJFjOxsoCIDzDGs9OIoV7s77f0@feXvM7n5vxNF4b3vHJAPZMrPLy2LYxzQSWUKoP0yF3lvjA9Ep8@Pw5hqQyjSJVNN1qwsQFuso2vfik2ordxkDi/kkUxLKHomtbiNFRUF9BH8lFGAy7vmTwrn8KbY4QDtKGHa6dK5eWDl7j5uf53KzkGC/4gzEkiCrGYRhtcydwpeVrpebu7H7XWycrbZP@iUUzzDQ "Scala – Try It Online") A recursive method. The input has to be a string. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 59 bytes ``` \G\d $&$'¶$`,$& +%)`^.+¶ m`^,|\b0+\B O` m`^(.+)(¶\1)+$ $1 ``` [Try it online!](https://tio.run/##K0otycxL/K@qoeGe8D/GPSaFS0VNRf3QNpUEHRU1Lm1VzYQ4Pe1D27i4chPidGpikgy0Y5y4uPwTQHwNPW1NjUPbYgw1tVW4VAz//zc0NOQyNDLmsjAxBTIMDAyMuEyMzCwNAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \G\d $&$'¶$`,$& ``` Create copies of the line with all possible proper prefixes of the first number on the line. ``` ^.+¶ ``` If there were any such prefixes, delete the original line. ``` +%)` ``` Repeat until no more prefixes can be generated. ``` m`^,|\b0+\B ``` Remove the leading separator and also leading zeros of any numbers. ``` O` m`^(.+)(¶\1)+$ $1 ``` Sort and deduplicate the results. For the Retina 1 port, the biggest saving comes from deduplication, which is basically a built-in in Retina 1. The newlines aren't included in the deduplication, so another stage is needed to filter out blank lines, but it's still a saving of 14 bytes. Another 3 bytes can be saved by using `$"` which is a shorthand for `$'¶$``. I also tried using an `L` stage to avoid leaving the original line but then a conditional is required to end the loop which means that the byte count ends up unchanged. [Answer] # [Python 3](https://docs.python.org/3/), 81 bytes ``` f=lambda g:{(int(g),)}|{b+(int(g[i:]),)for i in range(1,len(g))for b in f(g[:i])} ``` [Try it online!](https://tio.run/##XZDBboMwDIbveQrfmmhpRUJXdUjti0w9UBW6SDSNAE2rOp6d2QmhYRzg8@8vjoV79F93m49jfWjK2/lSwrV4cmN7fhVSDL/P81uoPk1xwqS@t2DAWGhLe624kk1lUfX5mfIa1cKcxDCam7u3PXSPjjFqN8ZWZGCw6fqLsQUDfIx1EqofBwdvbDrXmJ6v1seVYFHAHr7xVGscFz4NJ/A9pz52LW1b485OwAGF77LhaAkxKqUA1kd4ciQpJOD2oJQHopgQDkzpPNo6D7aWkE@SnoGyge237yrYRF5HmIbuJWAYMgkJpf2EZyfwtE@WZTrsQzTtr/0ni98XRJJzJBMr6ab9RUzFwLZ695H5az35a4kkZB7xD2A8pRIiSlikCzspEo0wdqiYZ9GZxeB/85ZlOiaU6aDX6eEP "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` ⊞υ⟦S⟧≔⟦⟧θFυ«≔⊟ιη¿ηFLη⊞υ⁺ι⟦I…η⊕κ✂η⊕κ⟧¿¬№θι⊞θι»Iθ ``` [Try it online!](https://tio.run/##bY@9CsIwFIVn@xR3vBciVFcn6SSIFDqWDiXGJhiTtkkEEZ893opujofz83Gk7mfpe5tznYLGJKA9uDHFJs7GDUgd7Yp9CGZw2HYCJpYXPwMmgmex@jq1H9GQAM3uylwANcEndVRuiJolwW@@timgYUzVh4jVQ1pVae5rAQcnZ3VTLqozXol4sLFGqj9WRwtJ2aBgwZ08L/nkIk4CDP1oH7ErXkXNXzixACdu5rwpy3Kb13f7Bg "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦S⟧ ``` Start a breadth first search with the input number. ``` ≔⟦⟧θ ``` Start with no results. ``` Fυ« ``` Loop over the candidates. ``` ≔⊟ιη ``` Get the current suffix. ``` ¿ηFLη ``` If the suffix is not empty then loop over all of its proper suffixes... ``` ⊞υ⁺ι⟦I…η⊕κ✂η⊕κ⟧ ``` ... push the next candidate, which is the prefixes so far, the current prefix cast to integer, and the current suffix. ``` ¿¬№θι⊞θι ``` But if it is empty and the resulting split is unique then push it to the results. ``` »Iθ ``` Print all the results. (This uses Charcoal's default output, whereby lists are double-spaced as their entries are printed on separate lines.) [Answer] # [J](http://jsoftware.com/), 36 29 bytes ``` [:~.]<@("./.~+/\)"#.2#:@i.@^# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9GJtHDSU9PT16rT1YzSVlPWMlK0cMvUc4pT/a3JxpSZn5CukKagbGhmrIzgGBgZGCK6JkZmlgfp/AA "J – Try It Online") *-7 bytes thank to xash!* Explanation later. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 38 bytes ``` {unique +<<m:ex/^(.+)+$/>>[0],:as(~*)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujQvs7A0VUHbxibXKrVCP05DT1tTW0Xfzi7aIFbHKrFYo05Ls/Z/cWKlgh5QQ1p@kUJOZl5q8X9DQ0MuQyNjLgsTUyDDwMDAiMvEyMzSAAA "Perl 6 – Try It Online") [Answer] # Mathematica 106 bytes ``` Union@Table[FromDigits/@#~TakeList~i,{i,Join@@Permutations/@IntegerPartitions@Length@#}]&@IntegerDigits@#& ``` [Try it online](https://tio.run/##NYwxC8IwEEZ/TKBTodFduEEEpUOGOoUMp1zTQ3OB9Jyk/euxKK7fe@9LqBMlVL5jHQ/1KpwFBrw9yZ9KTkeOrHMHZh3wQT3PunL75vaSWQAclfTSLc6yOWdRilQcFuXvBD1J1AnMEpo//R2CaaorLOpHv7PW7kOoHw) [Answer] # JavaScript (ES6), 88 bytes Expects a string. Returns a Set of comma-separated strings. ``` f=([c,...a],o='',S=new Set)=>c?f(a,o+c,o?f(a,o+[,c],S):S):S.add(o.replace(/\d+/g,n=>+n)) ``` [Try it online!](https://tio.run/##bcpBCsIwEIXhvaeQbprQMU1qFRVSD9Fl7SJMkqKUTGmLHj8quJLAW/x8vId5mgXn@7TuAlkXo9esQxBCmB5I5zm0OrjXtnUr1w1ePTNABQL9qgPsoeWX74SxlpGY3TQadKy82aIcIOimCJxHpLDQ6MRIA/MsU0plnG/@tdon9FQfkmcpZZXwujqe5cfjGw "JavaScript (Node.js) – Try It Online") ### How? It's important to note that `Set.prototype.add()` returns the set itself. And because the recursion always ends with `S.add(...)`, each call to `f` returns `S`. ### Commented *NB: alternate slash symbols used in the regular expression to prevent the syntax highlighting from being broken* ``` f = ( // f is a recursive function taking: [c, // c = next digit character ...a], // a[] = array of remaining digits o = '', // o = output string S = new Set // S = set of solutions ) => // c ? // if c is defined: f( // do a recursive call: a, // pass a[] o + c, // append c to o o ? // if o is non-empty: f( // do another recursive call a, // pass a[] o + [, c], // append a comma followed by c to o S // pass S ) // end of recursive call (returns S) : // else: S // just pass S as the 3rd argument ) // end of recursive call (returns S) : // else: S.add( // add to the set S: o.replace( // the string o with ... ∕\d+∕g, // ... all numeric strings n => +n // coerced to integers to remove leading zeros // (and coerced back to strings) ) // end of replace() ) // end of add() (returns S) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã cU à f_¬¥NîmnÃâ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4wpjVSDgIGZfrKVOw65tbsPi&input=IjEwMDQiCi1R) * Saved 1 thanks to @Shaggy ! ``` ã - substrings of input cUã) - concatenated to substrings of input(repeated) à - combinations f_¬¥N - take combinatons if == input when joined ®mn - deduplicates ( @Shaggy ® ) Ãâ - implicitly returns unique elements ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~32~~ 25 bytes -4 bytes from not de-listing first result -3 bytes from @ngn's improvements ``` {?.''(&'+1,!1_2&$x)_\:$x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqtpeT11dQ01d21BH0TDeSE2lQjM@xkqlovZ/mrqhoaGCoZGxgoWJKZBhYGBgpGBiZGZp8B8A "K (ngn/k) – Try It Online") * `&'+1,!1_2&$x` returns the subset of the (power set of indices of the input) that begin with 0. The original power set index generation code was taken from [@JohnE's answer on a different question](https://codegolf.stackexchange.com/a/51634/98547), and includes improvements from @ngn's comments on this answer. * `(...)_\:$x` `cut`s the stringified-input on each of the specified indices * `?.''` converts each slice to integers, taking the `distinct` elements [Answer] # [Ruby](https://www.ruby-lang.org/), 127 bytes ``` ->(n,f=->(s){s.size.times.map{|i|([f.(s[0...i])].flatten(i>1?1:0).map{|j|[j.flatten<<s[i..-1]]})}.flatten(2)}){f.(n.to_i.to_s)} ``` [Try it online!](https://tio.run/##PUzbCsIgGL7fU/wMBgruR@1ARa0HEYkVGzmaSdpFTZ99raJuvgPf4XY/Pka3G8uKWNbuJvJ08OjNs8Fg@sZjX7shmkhUi8QrjohGU43tpQ6hscRUYi82nH57XVTdL9puvTKIpdA60fQfSJroMH1ZDNeDeYOnaVRCCJYJOWPZar54S865ZNlcLtecZfnkPjLX2NSnMwwQbQR3D57khYOygsLlUICyDJyyWlNI4ws "Ruby – Try It Online") **Explanation** 1. first lambda takes a number and a function as parameters 2. second parameter defaults to the lambda that computes the partition 3. the second lambda is called with the number stripped of leading zeroes 4. computation starts with a map for each split point in the number 5. recursively call lambda for the substring before the split point 6. append the substring after the split point to each resulting partition array judicious array creation [] and applications of flatten in the code ensure exactly one level of array nesting in the result. [Answer] # [Perl 5](https://www.perl.org/), 87 bytes ``` sub f{$_=pop;/(.)(.+)/?do{my$s=$1;map s/@_\d+/0+$&/ger,map{("$s $_",$s.$_)}f(1,$2)}:$_} ``` [Try it online!](https://tio.run/##nVLLbsIwELzzFaPIbW3hkjhQRIlC8wO99QYoosJUtIREMZUaRfl2ajsvUDk1h93x7MzsHpLJ/PB0Pqvvd@xKEodZmgUuHTE6GjL3ZZuWSUFUSESQbDIoN4pX26HrDcm9@yFzrsmSOkSBxA4nakRiVu2o4MRn1ZzE1flbSbxJdZrPX9Nc4qShChfTYJAUiMwrpANgKYQAwgWWjkYOhyPQdA2atwbrNbdqf9yq/bGd@qg7/LZr4l/q2eRJ1GqDzFj3@oYZOgY9MDNt7D@r6xytErW0vcnzPL@@ySCHmyNM9ZrW9QbA9us9WtzLe13L4Zo0uNk@8afPnt1ukbnPANQIFxxaBMtd77fzC1MHMb2w4YYPXTCudlzG4ZYTbWKD@5jGvF6DBYNdmlP7d7HSBiQFJftjxon8yVgYkThoaNxpJoh0KSMzrEIq2I@Qfi/4SE9BpEu5sxnsr4SYTcdNIkPHKPC4gDP6TPdH@sDxwFWan@iXLJSJYqy27VW8lTI7FHRlaI6VuYT3WVpXnX8B "Perl 5 – Try It Online") Ungolfed: ``` sub f { $_ = pop; # set $_ to input (last arg) if( /(.)(.+)/ ) { # if input two or more digits, split # into start digit and rest my $s = $1; # store start digit return map s/@_\d+/0+$&/ger, # no @_ => 1st recursive level => trim leading 0s # 0+$& means int(digits matched) map { ("$s $_", "$s$_") } # return "start+space+rest" and "start+rest"... f(1, $2) # ...for every result of rest # (1 marks recursive level below first) } else { return $_ # if just one digit, return that } } ``` # [Perl 5](https://www.perl.org/) -MList::Util, 68 bytes ...which is further golfed from the answer from @xcali ``` say uniq map"@F "=~s| |$_/=2;','x($_%2)|reg=~s|\d+|$&*1|reg,1..2**@F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVKhNC@zUCE3sUDJwY1LybauuEahRiVe39bIWl1HvUJDJV7VSLOmKDUdJBOTol2joqZlCOLrGOrpGWlpObj9/29oYGBg9C@/oCQzP6/4v66vqZ6BoQGQ9sksLrGyCi3JzLEFWfJf1w0A "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ummdf(=d¹Σ)ṖQd ``` [Try it online!](https://tio.run/##yygtzv7/vzQ3NyVNwzbl0M5zizUf7pwWmPL//39DA0MA "Husk – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 44 bytes ``` YaUQ({(a|>0)RMx}M({y=aRMs?a^sx}M(PMaJs)))RMx ``` Probably my craziest Pip answer. There's definitely a shorter method, but I decided to roll with this. -p pretty prints the final list for easier verification. Takes a very long time with 5 digit numbers. [Try it online!](https://tio.run/##K8gs@G@tEBqoUV1pmxjkW2wfnVhTUxxbUeurEeCb6FWsCeQFlRdr/o9MBCnSSKyxM9AM8gXJw3QkxhUjlGuCJP///29oZPxftwAA "Pip – Try It Online") ## Explanation ``` YaUQ({(a|>0)RMx}M({y=aRMs?a^sx}M(PMaJs)))RMx a → first command line argument Ya Yank a into variable y PMaJs join each element of a with a space, get permutations {y=aRMs?a^sx}M filter out the permutations that are not in order {(a|>0)RMx}M Strip leading zeros and empty strings in each split RMx remove empty strings from the whole result UQ print the unique splits ``` ]
[Question] [ A prime is weak if the closest other prime is smaller than it. If there is a tie the prime is not weak. For example **73** is a weak prime because **71** is prime but **75** is composite. ## Task Write some computer code that when given a prime greater than **2** as input will determine if it is a weak prime. This is a standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") so you should output two unique values for each of the two cases (e.g. `weak` and `not weak`). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so standard rules for the tag apply. ## OEIS Here are the first 47 weak primes: ``` 3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401, 409, 421, 433, 443, 449, 463, 467, 491, 503, 509, 523, 547, 571, 577, 601, 619, 643, 647 ``` Here is the OEIS for weak primes (should return `weak`) [OEIS A051635](http://oeis.org/A051635) Here is the OEIS for balanced primes (should return `not weak`) [OEIS A006562](http://oeis.org/A006562) Here is the OEIS for strong primes (should return `not weak`) [OEIS A051634](http://oeis.org/A051634) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Æn+Æp>Ḥ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5724bYCu4c7lvz//9/Q0BgA "Jelly – Try It Online") ### Explanation ``` See if Æn the next prime +Æp plus the previous prime >Ḥ is greater than 2n ``` As a bonus, changing `>` to `=` or `<` checks for balanced and strong primes, respectively. [Answer] ## Mathematica, 24 bytes ``` n=NextPrime;2#+n@-#<n@#& ``` The `NextPrime` built-in can be (ab?)used to compute the previous prime by feeding it a negative argument. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤÆRạÞ⁸ḊḢ> ``` Returns `1` for weak and `0` for not weak or balanced (returns `1` for an input of `2`) **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bikw4ZS4bqhw57igbjhuIrhuKI@////NTM "Jelly – Try It Online")** ### How? ``` ḤÆRạÞ⁸ḊḢ> - Link: prime number > 2, p Ḥ - double -> 2*p ÆR - yield primes between 2 and 2*p inclusive ⁸ - chain's left argument, p Þ - sort by: ạ - absolute difference (i.e. distance from p) Ḋ - dequeue (removes p from the list, since it has distance zero) Ḣ - head (gives us the nearest, if two the smallest of the two) > - greater than p? ``` [Answer] # [PHP](https://php.net/), 69 bytes prints one for weak prime and nothing for not weak prime ``` for(;!$t;$t=$d<2)for($n=$d=$argn+$i=-$i+$w^=1;$n%--$d;);echo$n<$argn; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbqxk/T8tv0jDWlGlxFqlxFYlxcZIEySgkgdk24KVaatk2uqqZGqrlMfZGlqr5Knq6qqkWGtapyZn5Kvk2YDVWP//DwA "PHP – Try It Online") [Answer] # Octave, ~~93~~ 84 bytes *Thanks to @LuisMendo and @rahnema1 for saving bytes!* ``` function r=f(x);i=j=x;do--i;until(i<1|isprime(i));do++j;until(isprime(j));r=x-i<j-x; ``` [Try it online!](https://tio.run/##TY1BCsIwFET3OcVHKCS0gdalaW7iRpoEJ9RUaqpZePeYBgVn998M7y9TvDxtzm4LU8QSaNWOJ6GgvU7KLFJCbSFi5hiHNx73FTfLIUTp2tb/ui/3ha86SYxeJpVtMAz6qBh7XTFb2h193wtGJXDE/3yV7SkkRMcPjTlRY87h0BE6cvVnHe3WKtBoB8XKmT8) [Answer] # Maxima, 42 bytes ``` f(n):=is(n-prev_prime(n)<next_prime(n)-n); ``` [Try it online!](https://tio.run/##y02syMxN/P8/TSNP08o2s1gjT7egKLUsvqAoMzcVKGaTl1pRAufp5mla/@cC8vJKNNI0DA01Na0RPGMUnjkKzxLE@w8A "Maxima – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` qZq0)G_Yq+GE> ``` This outputs `1` if weak, `0` otherwise. [Try it online!](https://tio.run/##y00syfn/vzCq0EDTPT6yUNvd1e7/f3NjAA "MATL – Try It Online") ### Explanation ``` q % Implicit input, Subtract 1 Zq % Vector of primes up to that 0) % Get last one G % Push input again _Yq % Next prime + % Add G % Push input E % Multiply by 2 > % Greater than? Implicit display ``` [Answer] # GNU APL 1.2, 78 bytes ``` ∇f N X←(R←(~R∊R∘.×R)/R←1↓⍳N×2)⍳N (|R[X-1]-N)<|R[X+1]-N ∇ ``` `∇f N` declares a function that takes an argument. `(~R∊R∘.×R)/R←1↓⍳N×2` gives a list of all the primes from 2 to twice the argument. I'm assuming that the next prime is less than twice the original. If this is untrue, `N*2` gives N squared and takes the same number of bytes (hopefully that's big enough to exceed the next prime). [(See Wikipedia's explanation for how the prime-finding works)](https://en.wikipedia.org/wiki/APL_(programming_language)#Prime_numbers) `X←(R←(...))⍳N` assigns that list to vector `R` (overwriting its previous contents), finds the index of the original prime `N` in that list, and then assigns that index to `X`. `|R[X-1]-N` computes the difference between the previous prime (because `R` contains the primes, the `X-1`th element is the prime before `N`) and `N` and then takes the absolute value (APL operates right-to-left). `|R[X+1]-N` does the same, but for the next prime. `(|R[X-1]-N)<|R[X+1]-N` prints 1 if the previous prime is closer to the original than the next prime and 0 otherwise. Parentheses are needed for precedence. `∇` ends the function. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Æp;;ÆnI</ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW4G19eG2PE8b/f///5sbAwA "Jelly – Try It Online") [Answer] # Pyth, 15 bytes ``` >-fP_ThQfPT_tQy ``` [Try it here.](http://pyth.herokuapp.com/?code=%3E-fP_ThQfPT_tQy&test_suite=1&test_suite_input=73&debug=0) Uses Pietu1998's algorithm. [Answer] # [Perl 6](http://perl6.org/), 41 bytes ``` {[>] map ->\n{$_+n,*+n...&is-prime},1,-1} ``` [Try it online!](https://tio.run/##NclLCoAgFAXQrdxBSB999IEmUhupEAcWQYrYKMS1GwTNDhxvwjVm@4DtmHJc5g1We4h5dbFQjeN144iInbfw4bQm8Y6LLmWJWz84gvGI@LMsVAXGsH9IHANR37Yyvw "Perl 6 – Try It Online") `$_` is the argument to the function. The mapping function `-> \n { $_ + n, * + n ... &is-prime }` takes a number `n` and returns a sequence of numbers `$_ + n, $_ + 2*n, ...` that ends when it reaches a prime number. Mapping this function over the two numbers `1` and `-1` produces a sequence of two sequences; the first starts with `$_ + 1` and ends with the first prime number greater than `$_`, and the second starts with `$_ - 1` and ends with the first prime number less than `$_`. `[>]` reduces this two-element list with the greater-than operator, returning true if the first sequence is greater (ie, longer) than the second. [Answer] ## Python 2.7 - 120 bytes ``` from math import* i=lambda x:factorial(x-1)%x==x-1 def f(n,c):return 1 if i(n-c)>i(n+c) else 0 if i(n+c)>0 else f(n,c+1) ``` Since python doesn't have a built-in is prime function, we can use Wilson's theorem to get a nice short prime checker. Wilson's theorem states that a number is prime if and only if (n-1)! is congruent to -1 mod(n). Hence the function i will return 1 if the number is prime and 0 if it's not. Following that the f function will determine if the next prime from that number occurs first when incremented down rather than incremented up. If neither of the incremented numbers prime, it's just recursively called again. Some example I/O ``` f(3,1) 1 f(15,1) 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~122~~ ~~108~~ ~~103~~ ~~94~~ 92 bytes ``` def a(n): r=[2];x=2 while r[-1]<=n:x+=1;r+=[x]*all(x%i for i in r) return sum(r[-3:])>3*n ``` [Try it online!](https://tio.run/##jZLNattQEIX3foqBUrATFaw7c/XjVH2CLrsTWhiqYFFHDrJD3Kd355tAKGSThefOj@fcc47u89/L4TSn2@33@Cj79bzZrWTp@jQ8XLu0ktfDdBxl6b@Vw/du3l3vu/Jhue/663C3Px7X16@TPJ4WmWSaZdn46nh5WWY5vzytfUl3w@aH3s2352V6Gs8/x/P512E/V3krnfSpEC0kF1IXUpb@86okbwtJnic/1fvqPfPTvGeeZ7Z8Vnmv8rr2s/Ze7b3Gz8bPFpwtoFtQt1G23EOZKDWujIyBETK9TK/if6CXddBi2jBtI9CLO1rIwj4FZZBTCgGUICe4pxyBKcipYgDxVNMDOTWh2YNCVwFV6CqmaDgBXbUImIMTihUKU4WpwlSBUnxQSBpGGPINby2FmRGwFJIW5gJqkDS8NZgayAaoNWTIN0RnjM2AZvAy8jNSc3wjUDIAGakZqRmpGZTcxifkG0KtQm@F1KqMjAH8KovAwOphtfJnNF@k/@/NfXxYE8942gzyRV7H/Z@3nc9uzqfL@zZ5INz@AQ "Python 2 – Try It Online") Uses Pietu's idea... and then saved 28 bytes by golfing shorter prime list iterators; then 2 more by replacing `-3*n>0` with `>3*n` (d'oh!) [Answer] # Regex (most flavors), 47 bytes ``` ^(?=(x*)(?!(x+)(\2\2x)+$)\1)x+(?!(xx+)\4+$)\1\1 ``` [Try it online!](https://tio.run/##TY3BTsJAFEX37yuAmPAeleK0haHUgZULNix0aTWZwFBGh2kzHaEifjtWEhMXN7k55yb3TR5kvXa68sO60hvl9qV9V58XJ6w6dh5V8dBUiCcxHw0ur7gQ2AwIF11sAsI8yqOGghvKGTXBlbY4T64kZ5fB6EShL5@807ZACmuj1wont8OEKDvutFGIRjglN0ZbhURdYT@Moa9CmLCujPbYH/Yp01tEK4rQKFv4Hc2j81nXK7lCLSrparW0HovnuxeiP6H@CztnCzb71eR3rjz2lvYgjd50nLSFmnV6gcm2pcNM3wuV6SCg9rDX9EKnKiU9agr30q936IjWpa1Lo0JTFi3Pvi8RxDAGDowBi4G1JYUohiiFmEHMIWGQxJBwGLe7FCYMJhw4Ax4DT2EawzSFlEOasjb8Bw) Takes input in unary. Outputs a match for weak primes, no match for non-weak primes. Works in ECMAScript, Perl, PCRE, Python, Ruby. Explanation: Let N be the input, A the closest prime < N, and B the closest prime > N. The main difficulty of a regex approach to this challenge is that we can’t represent numbers greater than the input, like B. Instead, we find the smallest b such that 2b + 1 is prime and 2b + 1 > N, which ensures 2b + 1 = B. ``` (?= (x*) # \1 = N - b, tail = b (?!(x+)(\2\2x)+$) # Assert 2b + 1 is prime \1 # Assert b ≥ \1 (and thus 2b + 1 > N) ) ``` Then, note that we don’t actually need to find A. As long as *any* prime < N is closer to N than B, N is a weak prime. ``` x+ # tail iterates over integers < N (?!(xx+)\4+$) # assert tail is prime \1\1 # assert tail ≥ 2 * \1 (and thus tail + B > 2N) ``` [Answer] # Octave, 53 bytes ``` @(n)diff(list_primes(h=nnz(primes(n))+1)(h-2:h),2)>0 ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMyUzLU0jJ7O4JL6gKDM3tVgjwzYvr0oDysnT1NQ21NTI0DWyytDUMdK0M/ifZpuYV2zNlaZhaKgJIo3BpDmYtNT8DwA "Octave – Try It Online") [Answer] # JavaScript ES6, ~~162~~ 154 bytes 8 bytes save based on *Jörg Hülsermann*'s trick "print nothing in one case". No need to `?"Y":"N"` after `one<two` ``` var isWeak= a=>{p=[2];i=0;f=d=>{j=p[i];l:while(j++){for(x=0;p[x]*p[x]<=j;x++){if(j%p[x]==0){continue l}}return p[++i]=j}};while(p[i]<a+1){f()};return a*2<p[i]+p[i-2]} [43,//true 53,//false 7901,//false 7907,//true 1299853,//true 1299869//false ].forEach(n=>{console.log(n,isWeak(n))}) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` [<Dp#]¹[>Dp#]+¹·› ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2salQDn20M5oOxCtfWjnoe2PGnb9/29uDAA "05AB1E – Try It Online") Uses Pietu1998's algorithm. [Answer] # [Python 3](https://docs.python.org/3/), 149 bytes ``` f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k) def a(n):p=f(n);return p.index(n)in filter(lambda i:p[i]-p[i-1]<p[i+1]-p[i],range(1,len(p)-1)) ``` [Try it online!](https://tio.run/##fZHLboMwEEX3@QoUqZLNI@rYBie0/EP2iIUroLVMJghRqVWUb6eeqstONoA5vneO5fl7/bii3raxmdzlrXcJ5qGB/NxAjWn73Dnsk/NTSNvQZaPAIn7nIYsb0pAGueuHMXECZT03kcqXZVg/F0zmg8d@@Ip/PCajn9ZhEX/9vp5b3xXxUUD3Gl8Z/K66fHH4PgjIpwHFLAuQcpsXj6vY3@717b4/jNfl4lahcieUlHL3L9WRapaWkZYstZFalgJEDMBzGg38bKB6eNB/In5iuaJ@xfcryis@r8lf8/6a/DTvZyhv@LwhP8P7Geo3fH9J@fLB3dH5Sv58FflVvF9F8yt@vqW85fOW/CzvZ8nP8n5Hyh8pv/0A "Python 3 – Try It Online") I'm using a prime generating function (top line) taken from [this old stack exchange answer.](https://codegolf.stackexchange.com/a/70027/70097) [Answer] # JavaScript, 98 bytes ``` let test = _=>(o.innerHTML=f(+prime.value)) let f= n=>{P=n=>{for(i=n,p=1;--i>1;)p=p&&n%i};a=b=n;for(p=0;!p;P(--a));for(p=0;!p;P(++b));return n-a<b-n} ``` ``` Enter Prime: <input id="prime"> <button type="button" onclick="test()">test if weak</button> <pre id="o"></pre> ``` **Less Golphed** ``` n=>{ P= // is a Prime greater than 1, result in p n=>{ for(i=n,p=1;--i>1;) p=p&&n%i }; a=b=n; // initialize lower and upper primes to n for(p=0;!p;P(--a)); // find lower, for(p=0;!p;P(++b)); // find upper, return n-a<b-n // is weak result } ``` Note the test code does *not* check the input "prime" is actually a prime. [Answer] # [braingasm](https://github.com/daniero/braingasm), ~~23~~ 22 bytes Prints `1` for weak primes and `0` for not weak. ``` ;>0$+L[->+>2[>q[#:Q]]] ``` Walkthrough: ``` ; Read a number to cell 0 >0$+ Go to cell 1 and copy the value of cell 0 L Make the tape wrap around after cell 1 [ ] Loop: ->+> Decrease cell 1 and increase cell 0 2[ ] Twice do: > Go to the other cell q[ ] If it's prime: #:Q Print the current cell number and quit ``` [Answer] # Julia 0.6, 64 bytes ``` g(x,i)=0∉x%(2:x-1)?1:1+g(x+i,i);x->g(x,1)&(g(x-1,-1)<g(x+1,1)) ``` [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` n=input() a=b=c=i=2;p=1 while b<n: p*=i;i+=1 if p*p%i:a,b,c=b,c,i print a+c>2*b ``` [Try it online!](https://tio.run/##DchBCoAgEEbhvadwE5S5yRZBNt1FpeiHmIYwotObi7f4nnz5uNiVwgSWJ7edChQpEch5oUG9B85Nx4VnpcUQPPp6NfYqaTAHG22imoWSG5x16NPqTCxlGn8 "Python 2 – Try It Online") Uses Wilson's theorem for the primality test. [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` >D¹Σ§e₁←₁→ ḟṗt¡ ``` [Try it online!](https://tio.run/##yygtzv7/387l0M5ziw8tT33U1PiobQKYnMT1cMf8hzunlxxa@P//f2MA "Husk – Try It Online") ]
[Question] [ # Challenge Given a string and a number, divide the string into *that many* equal-sized parts. For example, if the number is 3, you should divide the string into 3 pieces no matter how long the string is. If the length of the string does not divide evenly into the number provided, you should round down the size of each piece and return a "remainder" string. For example, if the length of the input string is 13, and the number is 4, you should return four strings each of size 3, plus a remainder string of size 1. If there is no remainder, you may simply not return one, or return the empty string. The provided number is guaranteed to be less than or equal to the length of the string. For example, the input `"PPCG", 7` will not occur because `"PPCG"` cannot be divided into 7 strings. (I suppose the proper result would be `(["", "", "", "", "", "", ""], "PPCG")`. It's easier to simply disallow this as input.) As usual, I/O is flexible. You may return a pair of the strings and the remainder string, or one list of strings with the remainder at the end. # Test cases ``` "Hello, world!", 4 -> (["Hel", "lo,", " wo", "rld"], "!") ("!" is the remainder) "Hello, world!", 5 -> (["He", "ll", "o,", " w", "or"], "ld!") "ABCDEFGH", 2 -> (["ABCD", "EFGH"], "") (no remainder; optional "") "123456789", 5 -> (["1", "2", "3", "4", "5"], "6789") "ALABAMA", 3 -> (["AL", "AB", "AM"], "A") "1234567", 4 -> (["1", "2", "3", "4"], "567") ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. Bonus points (not really 😛) for making your solution actually use your language's division operator. [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ 59 bytes ``` s,n=input() b=len(s)/n exec'print s[:b];s=s[b:];'*n print s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v1gnzzYzr6C0REOTK8k2JzVPo1hTP48rtSI1Wb2gKDOvRKE42iop1rrYtjg6ySrWWl0rjwsq/v@/uqGRsYmpmbmFpbqOgikA "Python 2 – Try It Online") [Answer] # PHP>=7.1, 75 bytes ``` [,$s,$d]=$argv;print_r(preg_split('/.{'.(strlen($s)/$d^0).'}\K/',$s,$d+1)); ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/73efe68d002d61949b9d550f86ba52887009babc) # PHP>=7.1, 52 bytes print only the remainder ``` [,$s,$d]=$argv;echo substr($s,(strlen($s)/$d^0)*$d); ``` [Test Cases](http://sandbox.onlinephpfunctions.com/code/1c139a47686ded9bc3dff5ae27c90ec3dfe5045e) [Answer] # [Pip](https://github.com/dloscutoff/pip), 21 bytes 20 bytes of code, +1 for `-n` flag. ``` a~C(#a//b*XX)XbP$$$' ``` Takes inputs as command-line arguments; outputs strings and remainder newline-separated. [Try it online!](https://tio.run/##K8gs@P8/sc5ZQzlRXz9JKyJCMyIpQEVFRf3///@6Bf8NjYxNTM3MLSz/mwIA "Pip – Try It Online") ### Explanation Fun with regex operations! Let's take `abcdefg` as our string and `3` as our number. We construct the regex `(.{2})(.{2})(.{2})`, which matches three runs of two characters and stores them in three capture groups. Then, using Pip's regex match variables, we can print 1) the list of capture groups `["ab";"cd";"ef"]`, and 2) the remainder of the string that wasn't matched `"g"`. ``` a,b are cmdline args; XX is the regex `.` (match any one character) #a//b Len(a) int-divided by b: the length of each chunk *XX Apply regex repetition by that number to `.`, resulting in something that looks like `.{n}` C( ) Wrap that regex in a capturing group Xb Repeat the whole thing b times a~ Match the regex against a P$$ Print $$, the list of all capture groups (newline separated via -n) $' Print $', the portion of the string after the match ``` [Answer] # [Haskell](https://www.haskell.org/), 62 bytes `#` is an operator taking a `String` and an `Int`, and returning a list of `String`s. Use as `"Hello, world!"#4`. ``` s#n|d<-length s`div`n=[take(d+n*0^(n-i))$drop(i*d)s|i<-[0..n]] ``` [Try it online!](https://tio.run/##ZY7LCsIwEEX3fkV9LBJtg9b6RIX6FnTlUioNJthgnEqSWgT/vVYLIribc@6dYSKqL1zK7EoFjAUYrujJ1BKQArgmV3pDOopTksApUeqBqpggxSkbDvdGCTg7E1QM9gYMxph89jJdhScbOZLD2USWDpm4hzA@GHrhiDWg3jwicATGNabiGxJ1hvVTjJxDkxAIgixDlXX@VGxbaawkK1dsy8Olf9l5S386my@Wq3XO7ptbbtvrdHv9wbew9af@zs@x/ZMXN18 "Haskell – Try It Online") # How it works * `s` is the input string and `n` is the number of non-remainder pieces. * `d` is the length of each "normal" piece. `div` is integer division. * The list comprehension constructs `n+1` pieces, with the last being the remainder. + `i` iterates from `0` to `n`, inclusive. + For each piece, first the right amount (`i*d`) of initial characters are `drop`ped from the beginning of `s`, then an initial substring is `take`n from the result. + The substring length taken should be `d`, except for the remainder piece. - The actual remainder must be shorter than `n`, as otherwise the normal pieces would be lengthened instead. - `take` returns the whole string if the length given is too large, so we can use any number `>=n-1` for the remainder piece. - The expression `d+n*0^(n-i)` gives `d` if `i<n` and `d+n` if `i==n`. It uses that `0^x` is `1` when `x==0`, but `0` if `x>0`. [Answer] # [Python 2](https://docs.python.org/2/), ~~68 67~~ 65 bytes * @musicman123 saved 2 bytes:output without enclosing with `[]` * Thanks to @Chas Brown for 1 Byte: `x[p*i:p+p*i]` as `x[p*i][:p]` ``` def f(x,n):p=len(x)/n;print[x[p*i:][:p]for i in range(n)],x[p*n:] ``` [Try it online!](https://tio.run/##FclBCoAgEAXQq0ytNIQgWhntu4O4CNQS5DuIkJ3e6G0fv/XOWHp3PlAQTUFq3pOHaHLGxiWimmZ4itoazTbkQpEiqJy4vIC06l9o24MYD59SVvTkktwwqlX2Dw "Python 2 – Try It Online") [Answer] # C++14, ~~209~~ 180 bytes That's a bit too long, but uses the division operator: ``` #include<bits/stdc++.h> using q=std::string;using z=std::vector<q>;z operator/(q s,int d){int p=s.length()/d,i=0;z a;for(;i<d+1;){a.push_back(s.substr(i++*p,i^d?p:-1));}return a;} ``` Usage: ``` vector<string> result = string("abc")/3; ``` Online version: <http://ideone.com/hbBW9u> [Answer] # Pyth, 9 bytes ``` cz*L/lzQS ``` [Try it online](https://pyth.herokuapp.com/?code=cz%2aL%2FlzQS&input=5%0AHello%2C+world%21) ### How it works First `Q` is autoinitialized to `eval(input())` and `z` is autoinitialized to `input()`. ``` cz*L/lzQSQ lz length of z / Q integer division by Q *L times every element of SQ [1, 2, …, Q] cz chop z at those locations ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Ld⁹x,1$}R⁸ṁ ``` [Try it online!](https://tio.run/##y0rNyan8/98n5VHjzgodQ5XaoEeNOx7ubPx/eLlS5KOmNVmPGuYc2qYLBYe2/f@v5AHUkq@jUJ5flJOiqKSjgCng6OTs4ubq7gFiGxoZm5iamVtYgiV8HJ0cfR2V/pvoKJjqKBiBSWMA "Jelly – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 107 bytes ``` fn f(s:&str,n:usize)->(Vec<&str>,&str){let c=s.len()/n;((0..n).map(|i|&s[i*c..i*c+c]).collect(),&s[c*n..])} ``` [Try it online!](https://tio.run/##jZJdT8IwFIbv@RXdLkiLs8oYfjAlKX5xAbfeLItZapcsKR2uRROB3z7PaUKEKMZdvKc5532fnXRrVta1pSGLojKUkXWHwFNYqxr3ot4CWtJwqrSuI/JRN/o1CCOSsIjQdyWDDEfQCGGMBSxYwBbmUIOQsfQfvOE@z@M8dMf058YT0f87U0zu7h8en6Zgjr9x2MW4nyDgSLofD5LhxeXV9eE2fczGKAOUBGXoOd57ZJOZmIi5AO9gb5EZZsXE69wjxN@7HN7zj02QgK4dY9lUxmkTwPu1Jk5ZZ8kSwHBfaWeLH7ikdtS1ronMaGWrT8VOx/RZyRvsjSNUttbKEXlruVbwL5yZlNJzzg3ji2JJN9Wma7OqJzkHOZE547LWWklHGcQz2TOc52zbtl8 "Rust – Try It Online") Formatted: ``` fn q129259(s: &str, n: usize) -> (Vec<&str>, &str) { let c = s.len() / n; ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) } ``` This simply `map`s indices onto the correct slices of the source `str` (`collect`ing into a `Vec`) and slices out the remainder. Unfortunately, I cannot make this a closure (74 bytes): ``` |s,n|{let c=s.len()/n;((0..n).map(|i|&s[i*c..i*c+c]).collect(),&s[c*n..])} ``` as the compiler fails with ``` error: the type of this value must be known in this context --> src\q129259.rs:5:18 | 5 | let c = s.len() / n; | ^^^^^^^ ``` and if I provide the type of `s:&str`, the lifetimes are wrong: ``` error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements --> src\q129259.rs:6:27 | 6 | ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) | ^^^^^^^^^^^^^^^^^^^ | note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 4:18... --> src\q129259.rs:4:19 | 4 | (|s: &str, n| { | ___________________^ 5 | | let c = s.len() / n; 6 | | ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) 7 | | })(s, n) | |______^ note: ...so that reference does not outlive borrowed content --> src\q129259.rs:6:27 | 6 | ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) | ^ note: but, the lifetime must be valid for the lifetime 'a as defined on the body at 3:58... --> src\q129259.rs:3:59 | 3 | fn q129259<'a>(s: &'a str, n: usize) -> (Vec<&str>, &str) { | ___________________________________________________________^ 4 | | (|s: &str, n| { 5 | | let c = s.len() / n; 6 | | ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) 7 | | })(s, n) 8 | | } | |_^ note: ...so that expression is assignable (expected (std::vec::Vec<&'a str>, &'a str), found (std::vec::Vec<&str>, &str)) --> src\q129259.rs:4:5 | 4 | / (|s: &str, n| { 5 | | let c = s.len() / n; 6 | | ((0..n).map(|i| &s[i * c..i * c + c]).collect(), &s[c * n..]) 7 | | })(s, n) | |_____________^ ``` [Answer] # [Retina](https://github.com/m-ender/retina), 92 bytes ``` (.+)¶(.+) $2$*1¶$.1$*1¶$1 (1+)¶(\1)+ $1¶$#2$*1¶ \G1(?=1*¶(1+)) $1¶ ¶¶1+ O^$`. ¶1+$ O^$`. ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ09b89A2EMmlYqSiZXhom4qeIYQ25NIwBEvGGGpqc6mAhJQhSrhi3A017G0NtYCSQCWaYEmuQ9sObTPU5uLyj1NJ0OPiAnFUYLz//z1Sc3LydRTK84tyUhS5TAE "Retina – Try It Online") Explanation: The first stage converts the number of parts to unary and also takes the length of the string. The second stage then divides the length by the number of parts, leaving any remainder. The third stage multiplies the result by the number of parts again. This gives us the correct number of strings of the correct length, but they don't have the content yet. The number of parts can now be deleted by the fourth stage. The fifth stage reverses all of the characters. This has the effect of switching the original content with the placeholder strings, but although it's now in the right place, it's in reverse order. The placeholders have served their purpose and are deleted by the sixth stage. Finally the seventh stage reverses the characters back into their original order. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 bytes ``` {$^a.comb.rotor($a.comb/$^b xx$b,*)} ``` [Try it online!](https://tio.run/##ZZBtS8MwFIU/r7/iLgRJZm3t21SGSjdf9mH7BdZBa1MstM1IC26M/faaG50W9uXc5J6T50C2QlXTvt7DRQH30B/oJnU@ZJ05SnZSMfpzc@kmg92OZvaEH/tCKmBV2YiWw8Ea1W5CmDN55AlxkpYl@SV3Z9aoTfdQMHptA/W4dezJUlSVtOFLqiofExtCuHoA9oZ7fSPaw6F9HDpD3vUcEw5MK5QtdJ8ClKjTssmF4tYZMPoDGp6hnqDmrAwSw/p1PF88Pb@8LrXj/z7EFQbNGqNY3sj/0hnIbVfKJq3Qs4jnB2E0vbm9G7R7SPBRApQQJTI0E8TmVTyP17E2glPxClPx3OjahOMBf/BZZ3TMYoR/Aw "Perl 6 – Try It Online") Returns a list of lists of strings, where the last element is the remainder (if there is one). ### Explanation: ``` { } # Anonymous code block $^a.comb # Split the string into a list of chars .rotor( ) # And split into xx$b # N lists $a.comb/$^b # With string length/n size ,* # And whatever is left over ``` [Answer] # JavaScript (ES6), 77 bytes ``` (s,d,n=s.length)=>[s.match(eval(`/.{${n/d|0}}/g`)).slice(0,d),s.slice(n-n%d)] ``` Returns an array of two elements: the divided string parts and the remainder part. ## Test Snippet ``` f= (s,d,n=s.length)=>[s.match(eval(`/.{${n/d|0}}/g`)).slice(0,d),s.slice(n-n%d)] ``` ``` <div oninput="O.innerHTML=I.value&&J.value?JSON.stringify(f(I.value,+J.value)):''">String: <input id=I> Number: <input id=J size=3></div> <pre id=O> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` ¯W=Ul fV)òW/V pUsW ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=r1c9VWwgZlYp8lcvViBwVXNX&input=IjEyMzQ1Njc4OSIKNSAtUQ==) (uses `-Q` flag to visualize the output) ### Explanation ``` ¯W=Ul fV)òW/V pUsW : Implicit: U = input string, V = input integer Ul fV : Floor U.length to a multiple of V. W= : Assign this value to variable W. ¯ ) : Take the first W characters of U (everything but the remainder). òW/V : Partition this into runs of length W / V, giving V runs. pUsW : Push the part of U past index W (the remainder) to the resulting array. : Implicit: output result of last expression ``` [Answer] # Python, ~~82~~ ~~76~~ 74 bytes ``` def G(h,n):l=len(h);r=l/n;print[h[i:i+r]for i in range(0,n*r,r)],h[l-l%n:] ``` Well, looks like this qualifies for the bonus points. May I please receive a cookie instead? Oh wait, they aren't real? Darn... [Try It Online!](https://tio.run/##BcFBCsIwEAXQq4wFIdERRVyldF3vELIQmjoDw08ZCsXTx/e23y4Nz96XutIchBGTTVYRJI4@2R3j5oo9S9akVy9rc1JSkH/wreHBuDh7LCzZbnZGKn0Ow7uaNaajuS2ngV@x/wE) [Answer] ## Python, ~~95, 87, 76~~ 73 Bytes ``` def f(s,n): a=[];i=len(s)/n while n:a+=s[:i],;s=s[i:];n-=1 print a+[s] ``` [Try it online!](https://tio.run/##DcbBCoQgEADQu18xdVJyWXahi@K9fxAPQkoDwxhNEH299U5vv8@t8b/3tVSoWiwbpyCHmDwGKqzFfFnBtSEVYJenINFhsl7eoEueP@GnYD@QT8hTlNSrHpdC1Cxc7aB1GC3Mpj8 "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` ²g¹‰`s¹.D)R£ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0Kb0QzsfNWxIKD60U89FM@jQ4v//Tbg8UnNy8nUUyvOLclIUAQ "05AB1E – Try It Online") ### Explanation ``` ²g¹‰`s¹.D)R£ ²g # Push length of string ¹ # Push amount of pieces ‰ # divmod of the two `s # Flatten the resulting array and flip it around ¹.D # Repeat the resulting length of the pieces amount of pieces times(wow that sounds weird) ) # Wrap stack to array R # Reverse (so the remainder is at the end) £ # Split the input string into pieces defined by the array ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` kʰ↙Xḍ₎Ylᵛ&ht↙X;Y ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wP/vUhkdtMyMe7uh91NQXmfNw62y1jBKQiHXk///RCtFKHqk5OfnWCuX5RTkpiko6JrE6GGKmIDFHJ2cXVzd3DyUdIxDX0MjYxNTM3MISJu3j6OTo66ikY4wkCzUupDw1r6RSISe1pCS1qFghJz8vXQ8kpRALAA "Brachylog – Try It Online") Takes input as a list `[string, number]` and outputs as a list `[remainder, parts]`. (Commas were replaced with semicolons in the "Hello, world!" test cases for clarity, since the string fragments don't get printed with quotes.) ``` The input ʰ with its first element k ↙X having the last X elements removed ḍ and being cut into a number of pieces ₎ where that number is the last element of the input Y is Y lᵛ the elements of which all have the same length, & and the input h 's first element t↙X 's last X elements ; paired with Y Y are the output. ``` (I also replaced a comma in the code with a semicolon for a consistent output format. [With the comma](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wP/vUhkdtMyMe7uh91NQXmfNw62y1jBKQiE7k///RCtFKHqk5OfnWCuX5RTkpiko6JrE6GGKmIDFHJ2cXVzd3DyUdIxDX0MjYxNTM3MISJu3j6OTo66ikY4wkCzUupDw1r6RSISe1pCS1qFghJz8vXQ8kpRALAA), cases with no remainder would just output the parts without an empty remainder, and as nice as that is for some purposes, I don't actually know why it works that way...) After this came out to be a whole 16 bytes, I tried to make something based on `+₁ᵗ⟨ġl⟩` work, but as the fixes got longer and longer I decided that I would just stick with my original solution for now. [Answer] ## C(gcc), 72 bytes ``` d;f(s,n)char*s;{for(d=strlen(s)/n;n--;puts(""))s+=write(1,s,d);puts(s);} ``` [Try It Online](https://tio.run/##JYw7DsIwEAX7nMK42gVbKFCu3HMDCkQR@QORjB15jSiinN2Q8MqZ0bP6YW1rjgKwSmifQ9kzzSEXcIZriT4B4zFR0pqmd2WQEpEP5lPG6qFXrBz@BSMt7TWMCbCbO/Hb@iaq53q7CyPkxceYxTWX6Hb9SdLWBFgDJc5I3bKR9gU) [Answer] # Excel Formula, ~~185~~ ~~173~~ ~~165~~ ~~161~~ 149 bytes The following should be entered as an array formula (`Ctrl`+`Shift`+`Enter`): ``` =MID(A1,(ROW(OFFSET(A1,,,B1+1))-1)*INT(LEN(A1)/B1)+1,INT(LEN(A1)/B1)*ROW(OFFSET(A1,,,B1+1))/IF(ROW(OFFSET(A1,,,B1+1))=B1+1,1,ROW(OFFSET(A1,,,B1+1)))) ``` Where `A1` contains your input (e.g. `12345678`) and `B1` contains the divisor. This also uses Excel's division operator for a bonus. After entering the formula as an array formula, highlight it in the formula bar and evaluate it using `F9` to return the result, for example: [![Excel formula evaluation showing split groups](https://i.stack.imgur.com/eVand.png)](https://i.stack.imgur.com/eVand.png) **-12 bytes:** replace each `INDIRECT("1:"&B1+1)` with `OFFSET(A1,,,B1+1)` to save 2 bytes per occurence, plus some tidying removing redundant brackets. **-8 bytes:** remove redundant `INDEX` function. **-4 bytes:** rework "remainder" handling. **-12 bytes:** remove redundant `INT(LEN(A1)/B1)` by offsetting array generated by `ROW(OFFSET(A1,,,B1+1))` by -1. [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 62 bytes ``` YpC<c-r>=strlen('<c-r>"') <esc>jYp<c-x>"aDkk:s:\n:/ C<c-r>=<c-r>" <esc>"bDkkqq@blha <esc>q@a@q ``` [Try it online!](https://tio.run/##K/v/P7LA2SZZt8jOtrikKCc1T0MdzFNS1@SySS1OtsuKLAAKVNgpJbpkZ1sVW8XkWelzQXVAVELUKSUB5QsLHZJyMhIhIoUOiQ6F//97pObk5OsolOcX5aQocpn81y0DAA "V (vim) – Try It Online") takes input as 2 lines, returns the divisions on separate lines. `a` is useful here to append a newline after the current character. [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ 76 bytes *-1 byte thanks to musicman523.* ``` def f(s,n):l=len(s);print[s[i:i+l/n]for i in range(0,l-n+1,l/n)]+[s[l-l%n:]] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo1gnT9MqxzYnNU@jWNO6oCgzryS6ODrTKlM7Rz8vNi2/SCFTITNPoSgxLz1Vw0AnRzdP21AHKKUZqw1Ul6Obo5pnFRv7P01D3SM1JydfR6E8vygnRVFdR8FEkwuLqClY1NHJ2cXVzd0DKGAEFjA0MjYxNTO3sEQo8XF0cvR1BPKNkVWADf4PAA "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 53 bytes ``` ->s,n{a=s.scan(/.{,#{s.size/n}}/);[a[0,n],a[n,n]*'']} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euWCevOtG2WK84OTFPQ1@vWke5GsjJrErVz6ut1de0jk6MNtDJi9VJjM4DUlrq6rG1/wsU0qLTU0uK9ZIz8nMLdBTA7JL8@MzY/4ZGxiamZuYWllymAA "Ruby – Try It Online") [Answer] # Mathematica, 58 bytes ``` {#~Partition~a,#2}&@@TakeDrop[#,(a=Floor[Length@#/#2])#2]& ``` Pure function taking a list of characters and a positive integer as input. For example, the last test case is called by ``` {#~Partition~a,#2}&@@TakeDrop[#,(a=Floor[Length@#/#2])#2]&[{"1","2","3","4","5","6","7"},4] ``` and returns: ``` {{{"1"}, {"2"}, {"3"}, {"4"}}, {"5", "6", "7"}} ``` [Answer] # Haskell, ~~120~~ 88 bytes (thanks to Ørjan Johansen!) Does `div` count as the division operator? I am curious how I could cut this down, I haven't learned all the tricks yet. ``` q=splitAt;x!s|n<-div(length s)x,let g""=[];g s|(f,r)<-q n s=f:g r,(a,b)<-q(n*x)s=(g a,b) ``` [Answer] ## Ohm, 3 bytes (non-competing?) ``` lvσ ``` Non competing because the built-in isn't implemented yet in TIO and i have no PC handy to test whether it works in the latest pull in the repo. ~~Built-in ¯\\\_(ツ)\_/¯. I used the wrong built-in... But hey there is still an other one laying around.~~ Now I used the wrong built-in two times (or one built-in works wrong with remainders). Do I get bonus points because `v` is (floor) division? [Answer] # [CJam](https://sourceforge.net/p/cjam), 16 bytes ``` {_,2$//_2$<@@>s} ``` Anonymous block expecting the arguments on the stack and leaves the result on the stack after. [Try it online!](https://tio.run/##S85KzP1fWPe/Ol7HSEVfP95IxcbBwa649n9dakqs9X9TBSWP1JycfB2F8PyinBRFJQA "CJam – Try It Online") ### Explanation Expects arguments as `number "string"`. ``` _, e# Copy the string and get its length. 2$ e# Copy the number. / e# Integer divide the length by the number. / e# Split the string into slices of that size. _ e# Copy the resulting array. 2$ e# Copy the number. < e# Slice the array, keeping only the first <number> elements. @@ e# Bring the number and original array to the top. > e# Slice away the first <number> elements, s e# and join the remaining elements into a string. ``` [Answer] # [J](http://www.jsoftware.com), 26 bytes ``` (]$~[,(<.@%~#));]{.~0-(|#) ``` Apart from elminating spaces and intermediate steps, this hasn't been golfed. I expect that I've taken the long way somehow, what with my parentheses and argument references (`[` and `]`). See [Jupyter notebook](https://github.com/DaneWeber/JlangLearning/blob/master/Divide%20a%20string%20-%20Programming%20Puzzles%20%26%20Code%20Golf.ipynb) for test cases, such as the following: ``` 5 chunk test2 ┌──┬───┐ │He│ld!│ │ll│ │ │o,│ │ │ w│ │ │or│ │ └──┴───┘ ``` [Answer] # [R](https://www.r-project.org/), ~~79~~ 63 bytes *-16 from Giuseppe fixing the indexing* ``` function(s,n,k=nchar(s),l=k%/%n)substring(s,0:n*l+1,c(1:n*l,k)) ``` [Try it online!](https://tio.run/##JYxNCsIwEEb3nmJclCY6YAOuhCz87wG8QK1JWxImMkkRTx8j/VYfj8fjbHW2M/VpCiQiEjpN/dixiBK9dtWuIhnnZ0w80VCE5kAbv1XYC/V/6KTMVtSt8T4gfAL717pGgL1cFXw8nS/X270tZAEPE1MJQQc@0GAYljDYwPAOMRme0rfYqpG57Ac "R – Try It Online") Built around giving vector inputs to `substring()` [Answer] ## JavaScript, 49 bytes ``` d=(s,n)=>s.match(eval(`/.{1,${0|s.length/n}}/g`)) ``` [Try It Online](https://tio.run/##HcqxCsIwFEDRvV/xLA55EBMFB6HE2T9wEKEhiW3lmUgSstR@e6ze8XKeuuhk4vTOu3Kq1SqWuEd1TuKlsxmZK5pYL8V84Nt5/0mCnB/yKP2yyKFHrEVHiC6DAsvaiyMKHK4hkt20HI7YNY8Qgf0VTP5HsYE1E3wK5ASFga3zFu/Y1S8) ``` d=(s,n)=>s.match(eval(`/.{1,${0|s.length/n}}/g`)) var ret = d("######.######..#####..########..##.##..##.##.....##.....######.######.##.....##..#####.....##.....##.....##...####.....##......####...######", 5); for (var r in ret) console.log(ret[r]); ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` î╩╘30¥♂┴ÿ&╕¡ ``` [Run and debug it](https://staxlang.xyz/#p=8ccad433309d0bc19826b8ad&i=%22Hello,+world%21%22,+4%0A%22Hello,+world%21%22,+5%0A%22ABCDEFGH%22,+2%0A%22123456789%22,+5%0A%22ALABAMA%22,+3%0A%221234567%22,+4%0A&a=1&m=2) ]
[Question] [ [Negadecimal](https://en.wikipedia.org/wiki/Negative_base), also known as base -10, is a non-standard positional numeral system. Take the number \$1337\_{10}\$. In decimal, this has the value one thousand three hundred thirty seven, and can be expanded to: $$1\cdot10^3+3\cdot10^2+3\cdot10^1+7\cdot10^0$$ $$(1000)+(300)+(30)+(7)$$ In negadecimal, instead of \$10^n\$, each digit would be multiplied by \$(-10)^n\$: $$1\cdot(-10)^3+3\cdot(-10)^2+3\cdot(-10)^1+7\cdot(-10)^0$$ $$(-1000)+(300)+(-30)+(7)$$ Thus, \$1337\_{-10}\$ is \$-723\_{10}\$ in decimal. (An interesting consequence of this is that negative signs are unnecessary in negadecimal; any integer can be represented as `/[0-9]+/`.) In this challenge, your score is the sum of the lengths of two programs or functions: * One to convert a number in negadecimal to decimal * One to convert a number in decimal to negadecimal All inputs will be integers. You must be able to handle negative numbers. You can take input and output in any reasonable way. This is code golf, so the shortest answer in bytes per language wins. ## Test cases **Negadecimal to decimal:** ``` 1337 -> -723 0 -> 0 30 -> -30 101 -> 101 12345 -> 8265 ``` **Decimal to negadecimal:** ``` -723 -> 1337 0 -> 0 1 -> 1 21 -> 181 -300 -> 1700 1000 -> 19000 -38493 -> 179507 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ## Nega to Deca ``` T(ö ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/ROPwtv//DY2NzQE "05AB1E – Try It Online") ## Deca to Nega ``` T(в ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/ROPCpv//dc2NjAE "05AB1E – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` f=(p,e=n=>n&&(i=(n%10+10)%10)-p*e((n-i)/p))=>e f(10) f(-10) ``` [Try it online!](https://tio.run/##dc9NDoIwEAXgPafoRjJVK1OqKSzKXQiWH0NKI8br1xKEYIndTJMv8/LmUb7LsXp29sXMcNfO1QrsWSujChPH0CkwB44njtQPyuxRAxjW0cRSqgodNaoGD1HrJ/MfVw1mHHp96YcGGuBCSEIoJUlCmExFFDCZ3sw8tIyvlu5QIq65AjHkHL1/c3HPMr@hXLaza/7bq4Wp6trLnxDw/9otpHxjWahT11VlUMwH44Zz3PlcdlmfjnAf "JavaScript (Node.js) – Try It Online") `f` defines a helper function. `f(10)` returns a function that converts from negadecimal to decimal while `f(-10)` returns a function that converts from decimal to negadecimal. [Answer] # JavaScript (ES6), 25 + 55 = 80 bytes ## Negadecimal to decimal (25 bytes) ``` f=n=>n&&n%10-10*f(n/10|0) ``` [Try it online!](https://tio.run/##XclBCoMwEEDRvafIRkmEmJmMVjf2LmJNUWQitXTl3aMgFcxffXhT9@vW/jMuX83@NYTgWm6fnGWcImiE3Ek2CBuo0Hte/TwUs39LJ5GoFkoJY4SuLSV3BXF0KkREcJGmGBHwj8fGaKmsTmzsowo7 "JavaScript (Node.js) – Try It Online") ### How? This one is pretty straightforward. We recursively compute: $$f(n) = \cases{ 0, n=0\\ (n \bmod 10) - 10\times f\left(\left\lfloor\dfrac{n}{10}\right\rfloor\right), n>0}$$ ## Decimal to negadecimal (55 bytes) ``` f=(n,i=n%10,k=n>0?-n:~n-i+(i+=10))=>n?f(k/10|0)+i%10:'' ``` [Try it online!](https://tio.run/##ZczRDoIgGAXg@56CmyZMiR@pIW7osziTRrqflq2r1qtTbdWMzu13zjl2127uz/504Rj2Q4zOUiy8xbWEYrTYQMuxviP3OfW5lcCYbbB1dBQSbsBy/yzWWRb7gHOYhs0UDtRRrktFCGNECCKV0qtfluSVNydWyoVVqXIF8FUNkB7Dgg38OVfV1qjP3OxAxwc "JavaScript (Node.js) – Try It Online") ### How? In JS, the result of the `%` operator has the same sign as the dividend. For instance, `-17 % 10` is `-7` rather than `3` (like in Python), which is what we'd really like to get here. A possible workaround would be: ``` (n % 10 + 10) % 10 ``` Besides, we also need to compute \$\left\lfloor n/-10\right\rfloor\$ with \$n\$ either positive or negative. This can be done with: ``` Math.floor(n / -10) ``` but this expression is a bit lengthy. Rather than dealing with both issues separately, we explicitly test the sign of \$n\$ and compute the variables `i` and `k` accordingly: * We unconditionally set `i = n % 10`. * If \$n>0\$, we define `k = -n` and leave `i` unchanged. * If \$n\le 0\$, we define `k = ~n + 10` and add \$10\$ to `i`. Both operations are merged into `k = ~n - i + (i += 10)`. We then can use `k / 10 | 0` and `i % 10` in both cases. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes Negadecimal to decimal: ``` ḅ-10 ``` [Try it online!](https://tio.run/##y0rNyan8///hjlZdQ4P/LofbHzWt@f8/movT0NjYXEdBQVlB105B19zIkovTAMhVgIoYcHEaQ/gQBcZAAUMDQx2YAJANFDAyNjHVgQhYGJmZcsUCAA "Jelly – Try It Online") Decimal to negadecimal ``` b-10 ``` [Try it online!](https://tio.run/##y0rNyan8/z9J19Dg/@H2R01rHu7o@f8/motT19zIUkdBQUFZQddOwdDY2JyL0xDEhwtxcRpBBSB8C6CIrrGBAUKTuYEBUJMBspClAUhM19jCxNJYB6bM0tTAnCsWAA "Jelly – Try It Online") Input as an integer, output as a list of digits. +2 total bytes (+1 to each) to I/O as integers [Answer] # [Lisp Flavored Erlang](https://lfe.io/), 33 + 59 + 59 = ~~153~~ 151 bytes ``` (defun m(X Y)(rem(+(rem X Y)Y)Y)) (defun n(N)(if(== N 0)0(-(m N 10)(*(n(floor(/ N 10)))10)))) (defun d(N)(if(== N 0)0(+(m N 10)(*(d(ceil(/ N -10)))10)))) ``` `n` computes the decimal, given a negadecimal. `d` computes the reverse. Both functions take & return a regular integer. Erlang's `rem` function works like JavaScript's instead of like Python's, which is why the `m` function is necessary. I save some total bytes by reusing it — if this were 2 separate challenges, it would be inlined as each function only uses it once. Edit: Rearranged some of the function calls to save a couple bytes without changing logic [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~17~~ 13+35 = 48 bytes From negadecimal: ``` Fold[#2-10#&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyVa2UjX0EBZLfZ/QFFmXkm0sq5dWrRbUX6uS2Z6ZkmxvoNzRmJRYnJJalGxg3JsrFpdcHJiXl01l5KhsbG5kg6XkgGIMAaThgaGYMrI2MRUiav2PwA "Wolfram Language (Mathematica) – Try It Online") Input a list of digits. To negadecimal: ``` f@0=0 f@a_:=f@-⌊a/10⌋||a~Mod~10 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NwcDWgCvNITHeyjbNQfdRT1eivqHBo57umprEOt/8lDpDg/8BRZl5JdHKunZpDsqxanXByYl5ddVcuuZGxjpcBjpchjpcRkCsa2wA4hiASF1jCxNLY67a/wA "Wolfram Language (Mathematica) – Try It Online") Return an `Or` of digits, including a leading zero. +1 byte to output as an integer instead: [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NwcDWgCvNITHeytbQIM1B91FPV6K@ocGjnm7txDrf/JQ6Q4P/AUWZeSXRyrp2aQ7KsWp1wcmJeXXVXLrmRsY6XAY6XIY6XEZArGtsAOIYgEhdYwsTS2Ou2v8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Factor](https://factorcode.org/), 28 + 59 = 87 bytes ### Negadecimal to decimal ``` [ 0 [ swap 10 * - ] reduce ] ``` [Try it online!](https://tio.run/##PY2xCsIwGIT3PMW5CkpjFaE@gHTpIk6lQ4i/tNimMfmDSOmzx1BUbrjv44a7K82ji9dLWZ0LPMgZ6jEobmEdMb@t6wzD0zOQ0eRxEmVVwGunWLdCrMDkGZ2xgb2YBDBBIk85Yl4s@3b@J5lI/nmXlj0OyedYp6WGfykLmWGNDRo4ugVNaOKg7O9uDLz8baF7Ui5@AA "Factor – Try It Online") Takes an array of negadecimal digits and returns an integer. ``` [ 0 [ ... ] reduce ! Reduce over the digits with starting value of 0... swap 10 * - ! ( accum digit -- accum' ) Evaluate accum * -10 + digit ] ``` ### Decimal to negadecimal ``` [ [ dup 0 = not ] [ -10 2dup / ceiling -rot rem ] produce ] ``` [Try it online!](https://tio.run/##NY5Pi8IwFMTv/RTjB0hN2wX/LHtevHhZPJUeQnxqsE2yLy8LIn72bhS8DMz8BmZOxkrg@fCz239vcSX2NGIycnlJfcreigs@ITKJ3CI7L0j0m8lbSvisdvstkmUj9lJVCwglgfMxS6ruUKu2Q4O2geq0RqOLqG79senwmHv0OOYIjS/4IBiKV41G@wyXsORG589QXBjTVHjkcMyWMMyTie@xkOW11pfSH3EquHyPqGFHMjz/Aw "Factor – Try It Online") Takes an integer and returns an array of negadecimal digits in reverse order. Does not produce any leading zeros, which means the input of 0 gives an empty array. ``` [ [ cond ] [ loop ] produce ! Starting with the value of n, loop until cond gives false ! and collect the top values during the loop dup 0 = not ! Cond: stop if top is 0 ! Loop: yield the last digit and keep the higher value -10 2dup / ceiling ! ( n -- n -10 keep ) keep = ceil(n/-10) -rot rem ! ( keep yield ) yield = n%-10 (non-negative mod) ] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ## Negadecimal to decimal, 4 bytes ``` B_10 ``` [Try it online!](https://tio.run/##yygtzv7/3yne0OD////RhjrGQGgeCwA "Husk – Try It Online") input as list of digits, output as integer. ## Decimal to Negadecimal, 4 bytes ``` B_10 ``` [Try it online!](https://tio.run/##yygtzv7/3yne0OD///@65kbGAA "Husk – Try It Online") input as integer, output as list of digits. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 40 bytes ## Negadecimal to decimal, 10 bytes ``` {y+x*-10}/ ``` [Try it online!](https://tio.run/##y9bNz/7/P82qulK7QkvX0KBW/3@auoahgjEQmlsraOgYaFoDmQoG1gqGCgYKhiDKCChgomCq@R8A "K (oK) – Try It Online") ## Decimal to negadecimal, 30 bytes -8 bytes thanks to coltim! ``` {$[~x;0;(10*o@-_-x%-10)+10!x]} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWiW6rsLawFrD0EAr30E3XrdCVdfQQFPb0ECxIrb2f5q6hq65kbGCoYKRoYKusYGBgqEBkNA1tjCxNFYw0FT4DwA "K (oK) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 31 + 34 = 65 bytes ## Negadecimal to decimal, ~~32~~ 31 bytes Saved a byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!! ``` f=lambda n:n and~9*f(n/10)+n%10 ``` [Try it online!](https://tio.run/##TY7dCoJAEIXvfYpBCN0aaX8yU7Cb6CmyC9MVpVpF98JuevVttR8amOF8h@FwuoeuW8WNqdJbfr@UOahEQa7KZ7ysfLVmlKzUglGj5aAHSMF3wI7PhIgQgogLgm@HItCvFhYC8UNGGYI9P@ZiEyLs@Da0FnGKWhZX2U/pbjYeeTbGB7uhi/DPwiVO1fagUUKjYG6UzIlTscrXZIaub5S2T@AFew9hQPjkn2SaDmfzAg "Python 2 – Try It Online") ## Decimal to negadecimal, ~~42~~ ~~35~~ 34 bytes Saved 7 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! Saved another byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!! ``` g=lambda n:n and n%10+10*g(0-n/10) ``` [Try it online!](https://tio.run/##TU7LDoIwELzzFRsSQ6tt3FINYIIX41eIB8SKRi2E9qBfXwv42mSTnZndmW2f9tzo2Lk6v5X3w7EEvdJQ6iPoicCZwGlNkOu5QOqsMtYIyIEE4IvwJJYMhJQJZSMjPPzMyAA/c9wL6VfiEr0qEvwuCByYDH8Ul@ki6/2TbIl9Ag2qs6ququs/CIvHNi4e2cb3MmTwj2VIg1PTgWUKLhrGt1eDq/G3NbF0AG130dZvQcTXEQPD4B2wU3lu9u4F "Python 2 – Try It Online") [Answer] # [Racket](https://racket-lang.org/), 106 bytes ## Negadecimal to decimal, 39 bytes ``` (λ(x)(foldl(λ(a b)(+(* -10 b)a))0 x)) ``` [Try it online!](https://tio.run/##HYtRCsIwGIPfe4qADyaK0DrF8/y6TsRaZexhd/MOXqn@GyHkCyGj3Z55apti9Y5xLYF9Hh41ozb@vpzF4V36srDhKu65wyFFR5MiZqkpBL7sg4otmdC5LgKjuwOWSIhIax59POEsv/0B "Racket – Try It Online") Takes an array of negadecimal digits and returns an integer. ## Decimal to negadecimal, 67 bytes ``` (define(d x)(if(= 0 x)0(+(modulo x 10)(*(d(ceiling(/ x -10)))10)))) ``` [Try it online!](https://tio.run/##JYxbCsIwFES3MuCHc5Vg0gjqh4sJTVqC6YOqUNfmHtxSvdWfYebAnCnUt/RYNiX0Lab/YExN7hMjZmFueIXVZrlnN8RnGTDDWeGOkXXKJfctD8qMQpFfiDryfSzhBXZhBD9vqmsVCrY0p8rDoXIw3lqVaRh/Pl481vfyBQ "Racket – Try It Online") Takes the input as an integer and returns an integer. [Answer] # Scala, 15 + 71 = 86 bytes ### Negadecimal to decimal ``` _.:\(0)(_-10*_) ``` [Try them both online!](https://scastie.scala-lang.org/fUFog85tSwibyflcYkBnpA) Takes input as a reversed list of digits. This is rather straightforward - multiply the first digit by -10, add the second digit to that, multiply that by -10, and so on. ### Decimal to negadecimal ``` Seq.unfold(_){x=>val m=(x%10+10)%10;Option.when(x*x>0)(m->(m-x)/10)}:+0 ``` Returns a reversed list of digits, with a leading zero (at the end). This is not so trivial. Because of the way Scala's `%` works, we can't just use `x%10`, as it maintains the sign of `x` and not `10`. 10 has to be added to `x%10` to ensure it is positive, and then `%10` is done again. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes ``` {×₁₀ʰ↔-}ˡ ``` [Try it online!](https://tio.run/##AU8AsP9icmFjaHlsb2cy/3t3IiAtPiAidz/hurnihrDigoLhuol94bWQ/3vDl@KCgeKCgMqw4oaULX3Lof//WzEzMzcsMCwzMCwxMDEsMTIzNDVd "Brachylog – Try It Online") ``` ≜{×₁₀ʰ↔-}ˡ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/eobcOjpqaHuzprH26d8P9R55zqw9MfNTU@amo4teFR2xTd2tML//@Pjjc3MtYx1DEy1Ik3NjDQMTQAEvHGFiaWxrEA "Brachylog – Try It Online") Negadecimal input and output is as digit lists. The decimal to negadecimal program uses reversed I/O and is also impressively slow, as it uses pure brute force (coming out 6 bytes shorter than [a saner implementation](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w36BG9VFT46OmBl81fQjj4c7WRz2dIHbbBh3f//@j482NjHUMdYwMdeKNDQx0DA2ARLyxhYmlcSwA)). ``` { }ˡ Left fold over input negadecimal digits: × multiply ʰ the accumulator ₁₀ by 10, ↔- subtract it from the next digit. ≜ Try outputting all integers until the output {×₁₀ʰ↔-}ˡ is the negadecimal representation of the input. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 28 + 43 = 71 bytes ## Negadecimal to decimal, 28 bytes ``` f(n){n=n?n%10-10*f(n/10):0;} ``` [Try it online!](https://tio.run/##XZDhToMwFIX/7yluSEiAtVlLnVMR/WF8CiELKWUS9W6hJBIJry7eITCxyb1pT87X9lzND1r3feGh32KMj@hKwaUISNhI4d@JqOs/shI9H9oV0CqxhtrY2u4xzF9SiKGVSu0YCAaKSgpJLVRX2y6aAdOcjK5NPjPQ8l2oBojP1E14PUH6NasC6ka/mer3FSdpnsOkuX2i2joM/p6VM3LFsQLv/GKJuWkIE9G4vQdbfplj4c2f9zejElykCNbrwT/FnRIg3XWJPVjSaOGw5DiPcakaUhfp/6OnimyF57g58Aeg7toEKR4ysGyegIljm45Xd6uu/9bFe3awPf/8AQ "C (gcc) – Try It Online") ## Decimal to negadecimal, ~~48~~ ~~45~~ 43 bytes Saved 3 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!! Saved 2 bytes thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!!! ``` g(n){n=n?n%~9+10*(g(n/~9+(n=n%~9<0))+n):0;} ``` [Try it online!](https://tio.run/##XVDtaoQwEPx/T7EIQvziEtPDs57tj9KnqFIkRittc4cRKhX76LWrVa82kN3NMDNhR3ilEMNQEmV1Klb3yvwKHUZtgsgeR4IgQidqWY6ybmnUD@9ZpYgF3Q7wVKqBRupGP@e@ekohhs4LfO4Cc4G64GPzOMWJ0bF6/HgT8j5atbK9SNHIfJVDxzgPFj07YmfBZBBODiwIDzSYHcRLVttYpXiV9e/vRtI@@kkbPuA9GC78fXNj1hXnGsj4faVy2aKMRvN4Al19ynNB1qWs/YzYVygCx5n4SwzLOgq9rnFMlDTaMDQyxrS3qER0E8V/6aVGWkEMMwfvDrCaOlG4nnJBu2sCMo51Olv3u374FsVbVurB@/gB "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), 71 bytes *Combined negadec\_to\_dec and dec\_to\_negadec code thanks to [user](https://codegolf.stackexchange.com/users/95792/user), and inspired by [Neil's answer](https://codegolf.stackexchange.com/a/215840/95126)* ``` b=function(p)d=function(x)`if`(x,(y=x%%10)-p*d((x-y)/p),0) b(10) b(-10) ``` [Try it online!](https://tio.run/##VY3dCoMwDIXv@x5CMlLWGIfbRZ/Ff4cwtDgH9em7bgrizTkk58vJHEJt@8/YLMM0gsP2GDyWQ1@CJ1itTxI2qN2lBfB6xatDMqhq4L/qaGHsnlXbNcUyFdHslu2LPbMbqtS7cu61QgMskpMhMcSGiVPJbkjnJjxonacSaaaUSYv5HUXRcs8egnT@hSp8AQ "R – Try It Online") --- # [R](https://www.r-project.org/), ~~49~~ ~~47~~ 41 + 47 = 88 bytes *Separate functions* **negadecimal to decimal (~~49~~ ~~47~~ 41 bytes):** *Edit: -2 bytes (and, as a consequence, -6 more bytes) thanks to [att](https://codegolf.stackexchange.com/users/81203/att)* ``` d=function(x)`if`(x,x%%10-10*d(x%/%10),0) ``` [Try it online!](https://tio.run/##VcxBDkAwEEDRvXs0mZERM0qsnKWaFpFICZXU6cvW6r/VP3OYFusnZ@JuvgzZD/MdXFz3AAnHdR4hUVJKuBIuPSRVf0ZizJc9ju0BB6J1T0yaSVhIGt12SP8vFkV@AQ "R – Try It Online") **decimal to negadecimal (47 bytes):** ``` d=function(x)`if`(x,(y=x%%10)+10*d((y-x)/10),0) ``` [Try it online!](https://tio.run/##VY3LCoAgEADv/UewWyutGVQHv6VCK4Kw6AH69ea1yzBzmiva2QzPMbh5nZLqaPXyOvNshwOP47aM4AmC9nkuGUvJhQUIwmOVkhjjPZ3nHsCAaGtFTJJqSUJxMk4Qqmt6hfTfYJbFDw "R – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 + 18 = 23 bytes ## Negadecimal to decimal: ``` I↨S±χ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDM6@gtCS4BCiarqGpo@CXmp5YkqphaKAJBNb//xsaG5v/1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. This is just custom base conversion with a base of `-10`. ## Decimal to negadecimal: ``` NθP0Wθ«←I﹪θχ≔±÷θχθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLtzSnJLOgKDOvREPJQAkoUJ6RmZOqAJRTqObiDABLWPmkppXoKDgnFpdo@OanlObkaxTqKBgaaGoC1XM6Fhdnpudp@KWmJ5akanjmlbhklmWmpMKU6CiArKn9/1/X3Mj4v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the decimal number. ``` P0 ``` Print a `0` in case the input is zero. ``` Wθ« ``` Repeat until the input is zero. ``` ←I﹪θχ ``` Print the next digit in right-to-left order. ``` ≔±÷θχθ ``` Divide the input by `10` and change its sign. (Sadly this is not the same thing as dividing the input by `-10`. [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), ~~69~~ ~~68~~ 66 bytes --- # ~~24~~ 23 bytes *-1 byte thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)* ``` ->x{x.reduce{_2-_1*10}} ``` [Try it online!](https://tio.run/##Tc1BCoNADAXQfU/xoTvJSDKj1U29iLix1bUMKBbHs0@VqJjs/ssnfmx/sX9HU83LnPruO366JXiawmR8IryucUBfoxZy2xYNGgBPwFQwhXUPVdZcR5UPcnTDo@hOFGKSkxWF5UK7vcwo3w8US/vK4x8 "Ruby – Try It Online") TIO uses an older version of Ruby, while in Ruby 2.7, we've numbered parameters, which saves 3 bytes. --- # ~~45~~ 43 bytes ``` f=->x,s=''{x!=0?f[-~~(x/10),"#{x%10}"+s]:s} ``` [Try it online!](https://tio.run/##KypNqvz/P81W165Cp9hWXb26QtHWwD4tWreuTqNC39BAU0dJubpC1dCgVkm7ONaquPZ/gQJQ1tzIOFZBQUFZwdDY2JwLJGQI4kOEwHwjqACQbwER0TU2MIBqMjcwgGgygAtZGkDFdI0tTCyBpoOUWZoamP8HAA "Ruby – Try It Online") ]
[Question] [ Write a program that accepts as input an emoticon and ouputs if the emoticon is happy or sad. The program accepts a string as input or parameter, and should display the string "happy" if the input is in the happy emoticon list, or "sad" if the input is in the sad emoticon list. You can assume the input is always a valid (happy or sad) emoticon, with no space or tabs around. Here is a space separated list of happy emoticons: ``` :-) :) :D :o) :] :3 :c) :> =] 8) =) :} :^) :-D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D (-: (: (o: [: <: [= (8 (= {: (^: ``` Here is a space separated list of sad emoticons: ``` >:[ :-( :( :-c :c :-< :< :-[ :[ :{ 8( 8-( ]:< )-: ): >-: >: ]-: ]: }: )8 )-8 ``` This is code-golf, so the shortest program wins. [Answer] # Python, 86 bytes I should be sent to prison. ``` x=lambda c: ["happy","sad"][c[0]+c[-1:]in open(__file__).read(88)[::-1]]#<][><:>{:}(:) ``` The shortest I could come up with was equivalent to Martin's CJam answer, so I decided I'd hide all the sad emojis (minus the middle character if any) in the reverse of my code and use Python's `__file__` quine cheat. Muahahaha. [Answer] # CJam, ~~33~~ 32 bytes *Thanks to Dennis for saving 1 byte.* ``` q)"[(c<{"&\"])>}"&|"sad""happy"? ``` Looks like it's shorter to do the same thing without a regex... [Test it here.](http://cjam.aditsu.net/#code=qS%2F%7B%3AQ%3B%0A%0AQ)%22%5B(c%3C%7B%22%26%5C%22%5D)%3E%7D%22%26%7C%22sad%22%22happy%22%3F%0A%0A%5DoNo%7D%2F&input=%3A-)%20%3A)%20%3AD%20%3Ao)%20%3A%5D%20%3A3%20%3Ac)%20%3A%3E%20%3D%5D%208)%20%3D)%20%3A%7D%20%3A%5E)%20%3A-D%208-D%208D%20x-D%20xD%20X-D%20XD%20%3D-D%20%3DD%20%3D-3%20%3D3%20B%5ED%20(-%3A%20(%3A%20(o%3A%20%5B%3A%20%3C%3A%20%5B%3D%20(8%20(%3D%20%7B%3A%20(%5E%3A%20%3E%3A%5B%20%3A-(%20%3A(%20%3A-c%20%3Ac%20%3A-%3C%20%3A%3C%20%3A-%5B%20%3A%5B%20%3A%7B%208(%208-(%20%5D%3A%3C%20)-%3A%20)%3A%20%3E-%3A%20%3E%3A%20%5D-%3A%20%5D%3A%20%7D%3A%20)8%20)-8) ## Explanation This based on the same observation as the Retina answer, but this time matching happy faces doesn't have any benefit, so we'll match sad faces instead (because there's one less mouth to take into account). The solution is otherwise exactly the same, except that it's not implemented via regex substitution: ``` q) e# Read input and split off last character. "[(c<{"& e# Set intersection with the sad right-hand mouths. \ e# Pull up remaining emoticon. "])>}"& e# Set intersection with the sad left-hand mouths. | e# Set union, which amounts to a logical OR in this case. "sad""happy"? e# Pick the correct string. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~38~~ 36 bytes ``` .+[])D3>}]|[<[({].+ happy ^...?$ sad ``` We can recognise all emoticons by their mouths, because none of the mouths is used as a hat or eyes in the other set (only in the same set). The happy ones have one more mouth to take into account, but they have the benefit that the mouths don't appear in the other set at all, not even as noses (the opposite is not true: `c` is both a sad mouth and a happy nose). This means we can avoid using anchors but instead just ensure that there are more characters on the other side of the mouth. So the valid mouths for happy faces are `] ) D 3 > }` on the right or `< [ ( {` on the left. We match those with `.+[])D3>}]|[<[({].+` and replace them with `happy`. If we didn't match there will be two or three characters in the string (the emoticon), but if we did there will be five (`happy`). So in a second step we replace two or three characters with `sad`. [Answer] # JavaScript (ES6), 46 Using a regexp to find sad emoticons, that are those beginning with `>)]}` or ending with `<([{c`. Side note: other regexps here may be shorter but I'm not sure to understand them. Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably ~~not~~ newest Chrome but not MSIE. I tested on Firefox, Safari 9 could go) **Big news** It seems arrow functions finally arrived to Chrome land! [Rel 45, august 2015](https://www.chromestatus.com/feature/5047308127305728) ``` F=s=>/^[\])}>]|[[({<c]$/.test(s)?'sad':'happy' //Same length X=s=>/[\])}>].|.[[({<c]/.test(s)?'sad':'happy' Y=s=>s.match`].|[)}>].|.[[({<c]`?'sad':'happy' //TEST out=x=>O.innerHTML+=x+'\n'; sad='>:[ :-( :( :-c :c :-< :< :-[ :[ :{ 8( 8-( ]:< )-: ): >-: >: ]-: ]: }: )8 )-8'.split` ` happy=':-) :) :D :o) :] :3 :c) :> =] 8) =) :} :^) :-D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D (-: (: (o: [: <: [= (8 (= {: (^:'.split` ` out('The sad faces') sad.forEach(x=>out(x + ' is ' + F(x))) out('\nThe happy faces') happy.forEach(x=>out(x + ' is ' + F(x))) ``` ``` <pre id=O></pre> ``` [Answer] # Julia, 87 69 bytes - saved 18 bytes thanks to Alex A. ``` s=readline();print(s[end-1] in")D]3>}"||s[1] in"([<{"?"happy":"sad") ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~77~~ ~~75~~ ~~74~~ ~~72~~ ~~61~~ 55 bytes ``` lambda e:('happy','sad')[e[-1]in'[(c<{'or e[0]in'])>}'] ``` [Try it online!](https://tio.run/##HY/NisMwDITvfYq5BMtQL7vkEkSdw@KHKGQdyOaHBrpJqHtoKXn27KQw8idrkISW5/0yT/k2@J/t2vz9dg16FXNpluVpjiY1nbFVX7mvOE6mkvb0MvMNffW5/6MtVxO3oWn7BA@jzkKpAJ2JCM2hLbMSPqKw8MxXaE24gGKPgAfxCDgT5wBP@B05fI7vOkCcQqhZUSlOfD2kgHi8WK0VpVacJ1DKtdxInKCUo0G9UAi3CSKLluMsm9zeiEhExcpaQaswH2m5jncxMPZwGHhrwjhB3jdaPWC5jRPt7IYsAQYZJB0xSLL2iH7q/Ltz@wc "Python 3 – Try It Online") ## How does it work If a face string starts with `])>}` or ends with `[(c<{`, it is sad, otherwise it is happy. Tuple indexing is used as `if`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 50 bytes ``` (rh{,"[(c<{":Im?};?h{,"])>}":Im?}),"sad".;"happy". ``` ### Explanation ``` ( ),"sad".;"happy". § If what's in the parentheses is true, § output "sad", else output "happy". rhA § Unify A with the last char of the input ,"[(c<{":ImA § True if A is a char of "[(c<{" ; § OR ?hA § Unify A with the first char of the input ,"])>}":ImA § True if A is a char of "])>}" ``` [Answer] # Python, 159 bytes. ``` i,e=raw_input(),0 for c in i:e=(e,i.index(c))[c in":=8xXB"] f,s,h=i[:e],i[e+1:],0 for c in f:h+=c in"[(c<{" for c in s:h+=c in")]}>D" print["Sad","Happy"][h>0] ``` [Answer] # MATLAB, ~~85~~ 83 bytes There must be a way to reduce the size here. ``` e=input('');if any([e(end)=='[(c<{',e(1)=='])>}']),'sad';else 'happy';end,disp(ans) ``` Input is a smiley string. First and last characters will be compared to determine whether it's sad. If not, it's happy. I was able to save 2 bytes by not displaying either, but assigning them to MATLAB's default variable (ans) instead and then displaying ans after the if-statement. But I'm convinced it can be improved somehow. 2 bytes improvement by changing *function s(e),* to *e=input('');*. [Answer] # PowerShell, 92 Bytes ``` param([char[]]$a)if("<[({".IndexOf($a[0])+"})D3]>".IndexOf($a[-1])-eq-2){"sad"}else{"happy"} ``` A little wordy, but as a bonus, it doesn't use regex! This takes advantage of the .NET `<string>.IndexOf()` function that returns `-1` if the character *isn't* found in the string. So, if the first character isn't a "happy" character, the first `IndexOf()` will be -1 -- likewise for the last character. So, if it's a sad face, the `IndexOf()`s will always sum to -2, meaning the `-eq-2` is `$TRUE`, and thus `sad` gets printed. --- ### Bonus variant: PowerShell with Regex, 95 bytes ``` param([char[]]$a)if(($a[0]-match"[<\[\(\{]")-or($a[-1]-match"[\}\)D3\]>]")){"happy"}else{"sad"} ``` [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` lambda y:"sad"if re.match("(.*[[(c<{]$)|(^[\])>}])",y)else"happy" import re ``` [Try it online](https://tio.run/##HY/NioNAEITvPkUhC/aEmIsXaTIeFh8iYEZwjRLBPxwPETfP7lYWauZrqqluet7W5zQmR2vvR18NP48Km4a@eoRdi6W5DNVaPyWUy6kopL7u7sv8SlncncnezoTnzTS9b8JnNc9bGHTDPC0rc0db1Y2HRaSxgVI5dCIcNIHWrDJYh9TAsn5DSyLOkX5ejhfxynEjbjksYT9IYBN8lzkkVgg1KQrFlb@FpBCLnW6pyLTgPIFScc2NxBVKxWxQO1LhNoGjaTjOMBR/gnCEU7zppWyl0cXPfbdKhMgEQTst8OhG/J@oAealG1fxZ7TijQmOPw "Python 3 – Try It Online") The regex import makes it a bit too long, as well as the inability to use `None` as an array index. But I like regex :) [Answer] # Java 8, 52 bytes ``` e->e.matches(".+[\\[(c<{]|[)>\\]}].+")?"sad":"happy" ``` [Try it online.](https://tio.run/##jVE9T8MwEN35FU@ebFXJ0iW6NkFCWenCgpS4knEDTWmTqDGIquS3l9c2CAYGpHd@92Gd35037t1Fm9XryW9d3@Pe1c3xBqibUO2fna@wOIfAQ9jXzQu8Hp3KzJgfaEQfXKg9FmiQ4lRFWRXvXPDrqtcqnhRlWWg/P9rPwmRlaQcbT5S5Vb1bKVFr13UHdZpdO3VvT1t2Ghu@t/UKO0oaXy0snLnqeW7331IuHSBQEhkIkUNakoVMIZ5ehtQiMUjpD5AlKcqRnC3HB@kjxyPpMUdKSs80RTrF3TKHjgSaaAWFYM4zhU6gUxyZXYqK@25bB62gjLlo47YOfah2cfsW4o4aw7bRF5UTVQY1aWJ/Dc1liX9eHyu/xuS6zkNmUlC9hhCR53ykOYSIWCCOSDRn07BMGoo3goyUCSzJCgbmEpaSf0rnyz/CGZjx74fTFw) **Explanation:** ``` e-> // Method with String as both parameter return-type e.matches( ".+[\\[(c<{]|[)>\\]}].+") // Checks if the input matches the regex ?"sad" // If it does: output "sad" :"happy" // Else: output "happy" ``` Java's [`String#matches`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) implicitly adds `^...$` to match the entire String, which is why it is shorter to check for sad faces instead of checking for happy faces like most other answers do with `.+[\\])D3>}]|[<\\[({].+` (because my regex would fail in [*@MartinEnder*'s Retina answer](https://codegolf.stackexchange.com/a/57755/52210) for example, due to the happy test case `:c)`). **Regex explanation:** ``` ^.+[\\[(c<{]|[)>\\]}].+$ ^ Start of the string .+ One or more characters, [\\[(c<{] followed by one of "[(c<{" | Or [)>\\]}] One of ")>]}", .+ followed by one or more characters $ End of the string ``` [Answer] # [AutoHotkey], 78 bytes ``` InputBox,e MsgBox % RegExMatch(e,"(^[\])>}].+$)|(^.+[\[(c<{]$)")?"sad":"happy" ``` ## How does it work Using RegEx and ternary operator. Nothing new, as some answers used this method too. If input string starts with `])>}` or ends with `[(c<{`, it is sad, otherwise it is happy. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 33 bytes ``` $_=/.[[(c<{]$|[\])>}]./?sad:happy ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfLzpaI9mmOlalJjomVtOuNlZP3744McUqI7GgoPL/f6tkzX/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online") ]
[Question] [ Let's consider the sequence \$S\$ consisting of one \$1\$ and one \$0\$, followed by two \$1\$'s and two \$0\$'s, and so on: $$1,0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,...$$ (This is [A118175](https://oeis.org/A118175): *Binary representation of n-th iteration of the Rule 220 elementary cellular automaton starting with a single black cell.*) Given \$n>0\$, your task is to output \$a(n)\$, defined as the number of \$1\$'s among the \$T(n)\$ first terms of \$S\$, where \$T(n)\$ is the \$n\$-th [triangular number](https://oeis.org/A000217). The first few terms are: $$1,2,3,6,9,11,15,21,24,28,36,42,46,55,65,70,78,91,99,105,...$$ One way to think of it is to count the number of \$1\$'s up to the \$n\$-th row of a triangle filled with the values of \$S\$: ``` 1 (1) 01 (2) 100 (3) 1110 (6) 00111 (9) 100001 (11) 1111000 (15) 00111111 (21) 000000111 (24) 1111000000 (28) 01111111100 (36) ... ``` ## Rules You may either: * take \$n\$ as input and return the \$n\$-th term, 1-indexed * take \$n\$ as input and return the \$n\$-th term, 0-indexed * take \$n\$ as input and return the \$n\$ first terms * take no input and print the sequence forever This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` Sum[1-⌈s=√n⌉+Round@s,{n,#(#+1)/2}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0N9pQ91FPR7Hto45ZeY96OrWD8kvzUhyKdarzdJQ1lLUNNfWNamPV/gcUZeaVKOg7pOs7BCXmpadGGxnE/v8PAA "Wolfram Language (Mathematica) – Try It Online") -2 bytes from @ZippyMagician [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤR>)FŒHṪS ``` A monadic Link accepting \$n\$ which yields \$a(n)\$. **[Try it online!](https://tio.run/##y0rNyan8///hjiVBdppuRyd5PNy5Kvj///@mAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AR4A4f9qZWxsef//4bikUj4pRsWSSOG5qlP/MjDDh@KCrP8 "Jelly – Try It Online"). ### How? We can think of \$S\$ as being built in blocks of length \$2i\$ where each block is a string of \$i\$ ones followed by \$i\$ zeros: `10 1100 111000 ...`. If we stop at \$i=x\$ and call the result \$S\_x\$ we know that \$S\_x\$ necessarily contains an equal number of ones and zeros. We also know that the length of \$S\_x\$ will be \$\sum\_{i=1}^{x}2i = 2 \sum\_{i=1}^{x}i = 2T(x)\$. So the value of \$a(x)\$ is the count of ones in the first half of \$S\_x\$. An alternative way to get this same result is to subtract the count of the *zeros* in the first half of \$S\_x\$ from \$T(x)\$, and since \$S\_x\$ contains an equal number of ones and zeros this must also be the count of zeros in the second half of \$S\_x\$. Therefore we can form the complement of \$S\_x\$ and count the ones in its second half: ``` ḤR>)FŒHṪS - Link: integer, n ) - for each (i in [1..n]): e.g. i=3 Ḥ - double 6 R - range [1,2,3,4,5,6] > - greater than i? [0,0,0,1,1,1] F - flatten -> [0,1,0,0,1,1,0,0,0,1,1,1,...] ŒH - split into two equal length parts Ṫ - tail S - sum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Σ↑ṁṘḋ2NΣ ``` [Try it online!](https://tio.run/##AR0A4v9odXNr///Oo@KGkeG5geG5mOG4izJOzqP///8xMg "Husk – Try It Online") or [Verify first 12 values](https://tio.run/##ASQA2/9odXNr/23igoHhuKP/zqPihpHhuYHhuZjhuIsyTs6j////MTI "Husk – Try It Online") Returns the \$n^{th}\$ value of the sequence, 1 indexed. ## Explanation ``` Σ↑ṁṘḋ2NΣ ṁ N map the following across natural numbers and concatenate Ṙḋ2 replicate [1,0] n times ↑ take all values Σ till the triangular number of the input Σ sum them ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` f n=sum$sum[1..n]`take`do z<-[1..];[1,0]<*[1..z] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NFcFiKMN9fTyYhNKErNTE1LyFapsdEEisdbRhjoGsTZaIE5V7P/cxMw824KizLwSldzEAoU0BZC4oUHsfwA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 48 bytes ``` sum.(take.sum.r<*>(([1,0]<*).r=<<).r) r n=[1..n] ``` [Try it online!](https://tio.run/##FcgxDoAgEADB3ldQWIDRi/TgR5DiYkSJQAjo9z2l2Uz2xHrtIZDTK9UnAr/x2qGpqGHh3MhxtmoQULRSf0VXWNJGAiRLEX3Sufh09xEzc6x9OVt6NxfwqDRtOX8 "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` f=lambda n,k=8:k>n*-~n*2or(-k**.5%2<1)+f(n,k+4) ``` [Try it online!](https://tio.run/##DctBDoMgEEbhfU/xb4gMShMmbWKMeheaijW0g0E33fTqlNVbvHz793wl4VLC9Pafx9NDujj1Q5zF2J8YTlnbaMz1rnh01AZdf3ujElKGYBNkL@uiXQd2NFyAPW9yolF8wM6oaaAqQpVE5Q8 "Python 2 – Try It Online") **52 bytes** ``` lambda n:sum(-(k+1)**.5%1<.5for k in range(n*-~n/2)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0V0NXI1vbUFNLS89U1dBGzzQtv0ghWyEzT6EoMS89VSNPS7cuT99IU/M/SCIPIWGoo2BkqGnFpaBQUJSZV6KgrmpUrKBrpwCk1BVUNfJ0FNI08oDaAA "Python 2 – Try It Online") Based on the formula for \$S\$ that [user's noted](https://codegolf.stackexchange.com/a/214621/20260) from the OEIS page of [A118175](https://oeis.org/A118175). We simplify it to the following, one-indexed using Booleans for 0/1: $$ S(k) = \mathrm{frac}(-\sqrt{k}) < \frac{1}{2},$$ where \$\mathrm{frac}\$ takes the fractional part, that is the difference between the number and its floor. For example, \$\mathrm{frac}(-2.3)=0.7\$. This is equivalent to \$\sqrt{k}\$ being at most \$\frac{1}{2}\$ lower than its ceiling. The code simply sums $$\sum\_{k=1}^{n(n+1)/2} S(k),$$ but shifting the argument \$k\$ by one to account for the zero-indexed Python range. --- **57 bytes** ``` def f(n):N=n*-~n/2;a=round(N**.5);print(a+N-abs(a*a-N))/2 ``` [Try it online!](https://tio.run/##HcyxDYMwEAXQnilOVHfGBmEpDRYZwTtcBCY038iQIk1Wd5QM8N7xvp4ZvtZlTZQYMsUZxn0w@KBzyS8sHI3pbxKOsuNi7aLTx8lq1EWRwdeUC4F2UFFsK4@W/ChTQ/QHBNu6e2vDL69f "Python 2 – Try It Online") Outputs floats. A direct arithmetic formula. Thanks to Arnauld for -1 byte [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LxL@˜2äнO ``` -2 bytes by taking inspiration from [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/214616/52210) for generating the `[1,0,1,1,0,0,1,1,1,0,0,0,...]` list. Outputs the \$n^{th}\$ value. (Thanks to *@ovs*.) [Try it online](https://tio.run/##yy9OTMpM/f/fp8LH4fQco8NLLuz1///fEgA) or [verify the first 10 test cases](https://tio.run/##yy9OTMpM/R/i6mevpPCobZKCkr3ff58KH4fTc4wOL7mw1/@/zn8A). **10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) version that outputs the infinite sequence instead:** ``` ∞xL@˜∞£OηO ``` [Try it online.](https://tio.run/##yy9OTMpM/f//Uce8Ch@H03OA9KHF/ue2@///DwA) **Explanation:** ``` L # Push a list in the range [1, (implicit) input] # i.e. input=5 → [1,2,3,4,5] x # Double each value (without popping) # [2,4,6,8,10] L # Convert each value to a [1,n] list as well # [[1,2],[1,2,3,4],[1,2,3,4,5,6],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8,9,10]] @ # Check for each value in the [1,input] list that it's >= the values in the # inner ranged lists # [[1,0],[1,1,0,0],[1,1,1,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,0,0,0,0,0]] ˜ # Flatten it # [1,0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0] 2ä # Split it into 2 equal-sized parts # [[1,0,1,1,0,0,1,1,1,0,0,0,1,1,1],[1,0,0,0,0,1,1,1,1,1,0,0,0,0,0]] н # Only leave the first item # [1,0,1,1,0,0,1,1,1,0,0,0,1,1,1] O # And sum this list # 9 # (after which this sum is output implicitly as result) ∞ # Push an infinite list of positive integers # [1,2,3,...] xL@˜ # Same as above # [1,0,1,1,0,0,1,1,1,0,0,0,...] ∞ # Push an infinite list again £ # Split the list into parts of that size # [[1],[0,1],[1,0,0],[1,1,1,0],...] O # Sum each inner list # [1,1,1,3,...] η # Take the prefixes of that list # [[1],[1,1],[1,1,1],[1,1,1,3],...] O # Sum each inner list # [1,2,3,6,...] # (after which the infinite list is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ⁵DxⱮRFḣRS$S ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4oG1RHjisa5SRuG4o1JTJFP/MTA7w4ck4oKsR/8 "Jelly – Try It Online") Takes \$n\$, outputs \$a(n)\$, 1-indexed ## How it works ``` ⁵DxⱮRFḣRS$S - Main link. Takes n on the left ⁵ - 10 D - [1, 0] R - [1, 2, ..., n] Ɱ - For each i in [1, 2, ..., n]: x - Repeat [1, 0] i times F - Flatten the array $ - Group the previous two commands into a monad T(n): R - [1, 2, ..., n] S - Sum ḣ - Take the first T(n) elements of the sequence S - Take the sum, essentially counting the 1s ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 13 bytes ``` IΣ∕⭆⊕N⭆10×ιλ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8MlsywzJVUjuAQonO6bWKDhmZdclJqbmleSmgJkF5SW@JXmJqUWaWhq6iggVCkZGijpKIRk5qYWa2TqKORogqSNgKSm9f//hgb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input `n` ⭆⊕ Map over inclusive range ⭆10 Map over characters of literal string `10` λ Current character × Repeated by ι Outer index ∕ ² First half of resulting string Σ Digital sum (i.e. count `1`s) I Cast to string Implicitly print ``` Previous 24-byte more Charoal-y solution: ``` NθGLθψ¤⭆θ⭆²⭆⊕ιλ≔№KA0θ⎚Iθ ``` [Try it online!](https://tio.run/##TU5BCoMwELz7iuBpAxZsj/UkQkGwRegLUrvY0HWjMSn4@nQ9tXMYmBmYmeFl/OAMpdTyHMMtTg/0sOgq6x1to2M4d4VaCrWJdbFEcA/e8ng1M4j7E6d/0fLgcUIO@ASrC0VaUGX1utqRoXGRA/SI71r6JM7LXHgfbQiNh31dqgI0Zg1yRlcpHct0@NAX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` GLθψ ``` Draw an empty right triangle of side `n`. ``` ¤⭆θ⭆²⭆⊕ιλ ``` Fill it using the string `010011000111...`. (The string is always twice as long as the triangle.) Charcoal's fill paints the provided string into the area to fill (see for example [Bake a slice of Pi](https://codegolf.stackexchange.com/q/93615/17602)). Note that the `0`s and `1`s are swapped. ``` ≔№KA0θ ``` Get the number of `0`s that were actually printed. ``` ⎚Iθ ``` Clear the canvas and print the result. [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` a=lambda n,k=1:-~n*n>k*k*2and k+a(n,k+1)or max(0,k-~n*n/2-k*k) ``` [Try it online!](https://tio.run/##HYo7DoMwEAX7nOI1CNvYCt4SCe6ykfNZOSzIoiBNru5YqUaamf1zvDalWnl@83pLDPV5jlP4qtMlu@yINSEPbFoYot0KVj7N6PN/uVJok62P5gWiKKzPu4keNNrpAuxF9EDfUUJY0NCjM@LBRqytPw "Python 2 – Try It Online") This is based on $$ \begin{align} a(n) &= f(\frac{n\cdot(n+1)}{2}, 1) \\ \\ f(n, k) &= \begin{cases} k+f(n-2k, k+1), & \text{if $n > k$} \\ \operatorname{max}(0, n), & \text{if $n \le k$} \end{cases} \end{align} $$ but the conditions and the base case are more convoluted to get this into a single recursive function. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~30~~ ~~25~~ 24 bytes -6 bytes thanks to coltim ``` {+/(x+/!x)#,/x{0,x,1}\1} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWltfo0JbX7FCU1lHv6LaQKdCx7A2xrD2f5q6obaikcF/AA "K (oK) – Try It Online") Returns the n-th term 1-indexed. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~100~~ ~~89~~ ~~85~~ ~~84~~ 77 bytes -11: Change `a**2` to `a*a` and simplify `1-Math.ceil(c)+Math.round(c)` to `Math.ceil(c)-c<0.5` ([@xnor](https://codegolf.stackexchange.com/users/20260/xnor)) -4: Move `c=Math.sqrt(b+1)` inside `Math.ceil(c)` and omit the `f=` ([@user](https://codegolf.stackexchange.com/users/95792/user)) -1: Change ...`c<0.5` to ...`c<.5` ([@xnor](https://codegolf.stackexchange.com/users/20260/xnor)) -7: Remove unnecessary `(` and `)`, and change `Math.sqrt(`...`)` to ...`**.5` ([@Samathingamajig](https://codegolf.stackexchange.com/users/98937/samathingamajig)) ``` a=>(x=0,Array((a*a+a)/2).fill().map((a,b)=>x+=Math.ceil(c=(b+1)**.5)-c<.5),x) ``` [Try it online!](https://tio.run/##Dc1BDoIwEEDRvacgrGYoVNCwEUriAVx5gqEWGFMpKY3BGM9e2fzF2/wnvWnVnpdQzO5h4qAgkupgU2V@9Z4@AJSRIDyeUA5sLaB80bJr3qPqNqFuFCapDVvQCnpRYZbJGgvd7s03jNgcDoPzYE1IWJUNt1XdsBD41W5enTXSuhFYpJdUpEkqvVkMBTgXLIO7B8/zuD@tmccwoRiAEX9N/AM "JavaScript (Node.js) – Try It Online") [Answer] # APL+WIN, ~~26~~ 21 bytes. minus 5 bytes thanks to Adam. Prompts for integer: ``` +/(+/m)↑∊(m←⍳⎕)∘.⍴1 0 ``` [Try it online! Thamks to Dyalog Classic](https://tio.run/##FcvNCcJAEMXx@1ThMSHE7Ev87EGLWCIRYYNCTjYQFyGiB8E@tKJpZH1z@M9lfs9fQnm4@nA@lm3ww3Bqkz7e@52Oz0Y03rpUVFlR9bmOL433rOdDpy9NrvEz1@mHmUuEkjqBdFKzhi3Ykq3Ymm3YlsHZMQmjMAvDMA3jMA8bwBa1kz8 "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda n:sum([j for i in range(1,n+1)for j in[1]*i+i*[0]][:n*-~n//2]) ``` [Try it online!](https://tio.run/##TcsxDoMwEAXRq2zpNURg6CzlJI4LI@JkEXyQIQUNVzfQpX2aWfbtO6PN8fnKY5i6PhDs@puUGyjOiYQElAI@b2VKFIZvHC50xmspRLvae2ehHweqqvGc7wD/l2nYLkmwqajAnE8 "Python 3 – Try It Online") [Answer] # Scala, ~~66 58~~ 51 bytes ``` n=>1 to n flatMap(i=>""*i+"\0"*i)take(n*n+n>>1)sum ``` [Try it online](https://scastie.scala-lang.org/PJ6Mt7irSY6rMkzg4dExaQ) There is an unprintable character `0x01` inside the first quote. An anonymous function that takes an integer `n` and returns the nth element of the sequence (1-indexed). [Answer] # [Haskell](https://www.haskell.org/), 46 bytes ``` f n=sum[1|a<-[1..n],b<-[1..a],a*a-b<n*(n+1)/2] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDfasCbRRjfaUE8vL1YnCcJKjNVJ1ErUTbLJ09LI0zbU1DeK/Z@bmJlnW1CUmVeioKKQm1igkKYAUmpiEPsfAA "Haskell – Try It Online") --- **46 bytes** ``` f n=sum[max 0$min a$n*(n+1)/2-a*a+a|a<-[1..n]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDc6N7FCwUAlNzNPIVElT0sjT9tQU99IN1ErUTuxJtFGN9pQTy8vNvZ/bmJmnm1BUWZeiYKKQm5igUKaAkjKxCD2PwA "Haskell – Try It Online") --- **48 bytes** ``` f n=sum[1|k<-[2,4..n*n+n],even$ceiling$sqrt$2*k] ``` [Try it online!](https://tio.run/##BcExDsAQFADQq/zBpColxjqJGKShFfwo2ql31/cu15PPec4AqPtTjPjSvhrJFOdIcUHL/OuRHD7miCfpdxtE0mRncRF1bREHECiuQgAjOFebnT8 "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~82~~ 61 bytes Saved 2 bytes thanks to [ErikF](https://codegolf.stackexchange.com/users/79060/erikf)!!! ``` c;p;f(n){for(c=p=0,n=n*-~n/2;n>2*p;n-=2*p++)c+=p;c+=n<p?n:p;} ``` [Try it online!](https://tio.run/##VVDbbsIwDH3nK6xKSL24ok0v0IWwh2lfMXhAaTqqaSZqeaiGul/vXCgMIsVOjo@PfKzDT62HQUsrK5e8c3VsXK2sipAU@eEvLYSkjfCtpFBxCgJPB8pKDrS2r/RiZT/UdILvfU2uNzvPgM8ImM4afTLlxw4UnGMUmGCOBcYxxhkKBlIUK0xyTAWmOWYZ5hkuI1yusIixYGaU9fKipw/7xtcHo79Mw3qjoLPt3sW2K974Zg7C4z9xpj52A@44TE2l6bgtktNzDW39Y46VexvTW0yAf0ckBMGF7cHV1s0asdJVJoBYPpVaLo2LfEYNo/d9XDp3/wTbMKVynXkJ4QY4ztstsSNCaBFurlulzG6S7Wf98Ac "C (gcc) – Try It Online") Inputs a \$1\$-based number \$n\$ and returns the \$n^{\text{th}}\$ term. [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` r?x|q<-sum[0..x]-r*r,r>q=min q 0|l<-r+1=l+l?x (0?) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8i@oqbQRre4NDfaQE@vIla3SKtIp8iu0DY3M0@hUMGgJsdGt0jb0DZHO8e@4n9uYmaebUFRZl6JSm5igYaBvWa0oZ6ekUHsfwA "Haskell – Try It Online") Slightly longer but complete different approach from the existing Haskell answer. This one is basically all arithmetic whereas the existing one builds the list from scratch. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 8 bytes ``` ƛdɾ<;fIt ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixptkyb48O2ZJdCIsIiIsIjUiXQ==) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes ``` .+ $* 1 $`1$.`$*00 ((.)+?)(?<-2>.)+$ $1 1 ``` [Try it online!](https://tio.run/##DcY7CoAwEEDB/p1jhXwwZOMfxJReIxYWNhbi/aNTzXO@133UxuylBo84FCkqoYiLEWOC9dmavLZp@yuIorUqiY6egZGJmQWNHw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* 1 $`1$.`$*00 ``` Create the string `101100111000`... up to `n` `1`s and `n` `0`s, which is twice as long as the desired triangle. ``` ((.)+?)(?<-2>.)+$ $1 ``` Delete the second half of the string. ``` 1 ``` Count the number of `1`s remaining. [Answer] # [J](http://jsoftware.com/), 25 bytes ``` (1#.2&!$&;1 0<@#"{~i.)@>: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQyV9YzUFFXUrA0VDGwclJWq6zL1NB3srP5rcnGlJmfkK6QpGShoGCpoK2TqKRgaGGj@BwA "J – Try It Online") ``` (1#.2&!$&;1 0<@#"{~i.)@>: ( )@>. increment n by 1 and then i. for every i in 0 … n+1: 1 0 #"{~ take i 1s and i 0s, <@ and box the result (;1 0;1 1 0 0;…) 2&! T(n) by binominal(n+1, 2) $&; raze the boxes to a list (1 0 1 1 0 0…) and take the first T(n) elements 1#. sum the list, i.e. count the 1s ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes ``` :"@:t~]vG:s:)z ``` Input is 1-based. [Try it online!](https://tio.run/##y00syfn/30rJwaqkLrbM3arYSrPq/39TAA) Or [verify the first values](https://tio.run/##y00syflvpeQQ4QUirUrqYsu8rIqtNKv@u/w3NAQA). ### How it works ``` % Implicit input: n : % Range: [1 2 ... n]. " % For each @ % Push iteration index, k (goes from 1 to n) : % Range: gives [1 2 ... k] t % Duplicate ~ % Negate, element-wise: gives [0 0 ... 0] (k zeros) ] % End v % Concatenate everything into a column vector G % Push n again : % Range: [1 2 ... n] s % Sum: gives n-th triangular number, T(n) : % Range ) % Index: keeps the first T(n) values z % Number of nonzeros % Implicit output ``` [Answer] # [R](https://www.r-project.org/), 55 bytes ``` sum(unlist(Map(rep,list(1:0),e=n<-1:scan()))[1:sum(n)]) ``` [Try it online!](https://tio.run/##K/r/v7g0V6M0LyezuETDN7FAoyi1QAfMMbQy0NRJtc2z0TW0Kk5OzNPQ1NSMBjKByvM0YzX/Gxr@BwA "R – Try It Online") Generates A118175 and sums the first \$T(n)\$ terms. [Answer] # Desmos, 85 bytes \$\sum\_{n=1}^{x(x+1)/2}(1-\operatorname{ceil}(\sqrt{n})+\operatorname{round}(\sqrt{n}))\$ ``` \sum_{n=1}^{x(x+1)/2}(1-\operatorname{ceil}(\sqrt{n})+\operatorname{round}(\sqrt{n})) ``` I haven't been able to find a nice formula myself, so I used the \$a(n) = 1 - \operatorname{ceil}(\sqrt{n+1}) + \operatorname{round}(\sqrt{n+1})\$ formula provided on [A118175's page](https://oeis.org/A118175). [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~12~~ ~~11~~ 10 bytes ``` ┅2…&¦_2÷eΣ ``` [Try it online!](https://tio.run/##S0/MTPz//9GUVqNHDcvUDi2LNzq8PfXc4v//DQ0B "Gaia – Try It Online") Uses the observation from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/214616/67312) to save a byte (so go upvote that), namely that constructing the complement sequence and counting the 1s in the *second* half is equivalent to counting the 1s in the first half. ``` # implicit input n ┅ # push [1, 2, ..., n] 2… # push [0,1] &¦ # for each i in [1, 2, ..., n] repeat each element of [0,1] i times _2÷ # flatten and divide into two sublists of equal length eΣ # take the second sublist and sum ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~19~~ 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╒♂░*mzyh½<iΣ ``` Outputs the 1-based \$n^{th}\$ value. [Try it online.](https://tio.run/##y00syUjPz0n7///R1EmPZjY9mjZRK7eqMuPQXpvMc4v//zfkMuIy5jLhMuUy4zLnsuCy5DI04DI05TIy4DIy5TIFsg0MAA) **Original 19 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) answer:** ``` ╒♂░*mzykæî‼<≥]╡imΣΣ ``` Outputs the 1-based \$n^{th}\$ value as well. [Try it online.](https://tio.run/##AVMArP9tYXRoZ29sZv//4pWS4pmC4paRKm16eWvDpsOu4oC8POKJpV3ilaFpbc6jzqP//zEKMgozCjQKNQo2CjcKOAo5CjEwCjE1CjIwCjI1CjUwCjEwMA) **Explanation:** ``` ╒ # Push a list in the range [1, (implicit) input] ♂░ # Push 10, and convert it to a string: "10" * # Repeat the "10" each value amount of times: ["10","1010","101010",...] m # Map over each inner string: z # Revert sort its digits: ["10","1100","111000",...] y # Join it together to a single string: "101100111000..." h # Push its length (without popping the string itself) ½ # Halve it < # Only keep the first length/2 amount of digits in this string i # Convert the string to an integer Σ # And sum its digits # (after which the entire stack joined together is output implicitly) ╒♂░*mzy # Same as above # Get its prefixes (unfortunately there isn't a builtin for this): k # Push the input-integer æ # Loop that many times, # using the following four characters as body: î # Push the 1-based loop index ‼ # Apply the following two commands separated: < # Slice to get the first n items ≥ # Slice to remove the first n items and leave the remainder ] # After the loop, wrap all values on the stack into a list ╡ # Remove the trailing item i # Convert each string of 0s/1s to an integer mΣ # Sum the digits of each inner integer Σ # And sum the entire list together # (after which the entire stack joined together is output implicitly) ``` [Answer] # [Raku](http://raku.org/), 40 bytes ``` {sum flat({1,0 Xxx++$}...*)[^sum 1..$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyEtJ7FEo9pQx0AhoqJCW1ulVk9PT0szOg4kZ6inpxIfW/u/OLFSITexAKhLByRmZPAfAA "Perl 6 – Try It Online") * `{ ... } ... *` is an infinite sequence, where the bracketed expression is a function that generates each successive element. * `++$` increments the anonymous state variable `$` each time the generating function is evaluated. The first time it's called, `++$` is 1, then 2, etc. * `1, 0` is just a two-element list. * `xx` is the replication operator. Prefixed with the cross-product metaoperator `X`, `Xxx` crosses the list `1, 0` with the incrementing value of `++$`, generating the sequence `(((1), (0)), ((1, 1), (0, 0)), ((1, 1, 1), (0, 0, 0)), ...)`. * `flat` lazily flattens that infinite sequence into the given sequence S, ie: `1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, ...`. * `[^sum 1..$_]` takes the first N elements from that sequence, where N is the sum of the numbers from 1 up to `$_`, the argument to the function. * The leading `sum` sums the selected elements. [Answer] # [Arn](https://github.com/ZippyMagician/Arn) `-rlx`, [14 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` &♦r┬f½▀╔î¾rl¥Æ ``` [Try it!](https://zippymagician.github.io/Arn?code=JC4ofHt8YXthPn1cfjorfVw=&input=MQoyCjMKNAo1CjYKNwo4CjkKMTA=&flags=cmx4) # Explained Unpacked: `$.(|{|a{a>}\~:+}\` ``` Mutate STDIN from N → [1, N] $. Partition down middle ( |..\ Fold N with concatenation _ Where N is a variable; implied { After mapping with block, key of `_` |..\ ~:+ Where N is a one-range to _ * 2 a{ Block with key of `a` a > Is greater than _ Implied } End block } End block Last entry, sum ``` Alternate 14 byte solution with the same flags: `$.(a{~:+a@>a}\):_` # [Arn](https://github.com/ZippyMagician/Arn), [23 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` W▀Q$µgˆÎ§Ò"ˆÞC5fbA┐V-7J ``` [Try it!](https://zippymagician.github.io/Arn?code=K3sxLSg6XjovKSs6digwLjUrOi99XH46LSorKw==&input=MQoyCjMKNAo1CjYKNwo4CjkKMTA=&flags=) Thinking of adding a round fix to Arn, that'll help this pretty high byte count. 1-indexed, returns the Nth term. Based off of [@J42161217](https://codegolf.stackexchange.com/users/67961/j42161217)'s answer # Explained Unpacked: `+{1-(:^:/)+:v(0.5+:/}\~:-*++` ``` +...\ Fold with addition after mapping ~ Over the one-range to :-*++ n * (n + 1) / 2 { Begin map, key of `_` 1 - Subtract ( :^ Ceiling _ Implied :/ Square root ) + Add :v(0.5+:/ Round `:/_`, ending implied } End map ``` [Answer] # [Swift](https://swift.org), 80 bytes *Adapted from the [Python 2 answer by @ovs](https://codegolf.stackexchange.com/a/214602/59749)* ``` func a(_ n:Int,_ k:Int=1)->Int{-(~n*n)>k*k*2 ? k+a(n,k+1):max(0,k-(~n)*n/2-k*k)} ``` And the un-golfed form: ``` func a(_ n: Int, _ k: Int = 1) -> Int { -(~n*n) > k*k*2 ? k + a(n, k+1) : max(0, k - ~n*n/2 - k*k) } ``` And here's some sample output. ``` print((1...10).map { a($0) }) // [1, 2, 3, 6, 9, 11, 15, 21, 24, 28] ``` It might actually be better to use a loop instead of recursion. Some limitations with closures (i.e. lambdas) in Swift forced me to use a function decl, which takes up a lot of space. :/ [Answer] # [CJam](https://sourceforge.net/p/cjam), 22 bytes ``` qi),:+{_)mqmo\mqi-}%:+ ``` Uses `round(sqrt(n+1)) - floor(sqrt(n))` to calculate the `n`th position in the bit sequence. (Getting it as a repetition of numbers was smaller to generate, but one byte larger in the end to sum.) [Try it online!](https://tio.run/##S85KzP3/vzBTU8dKuzpeM7cwNz8mtzBTt1bVSvv/fyMDAA "CJam – Try It Online") [Answer] # [Red](http://www.red-lang.org), 109 bytes ``` func[n][b:[[1]]loop n[append/only b head insert next copy[0 1]last b]sum take/part load form b n + 1 * n / 2] ``` [Try it online!](https://tio.run/##DYw7CsMwEER7n2K6QELwp3SRQ6RdtpCtFTGRV0KWIT69stM8GN5MEd/e4om7MKOFU1dSpmUmGpljShlKLmdR3yeNFxZ8xHlsekipUPnVbk35ogEjR3dULHycO6r7Sp@dKTGZHlLZbap4YMTd2GPiViSLsxNMA6iDJZdNK8iq2/OFYOSO2x8 "Red – Try It Online") I know it's very long - I just wanted to see what the [K solution](https://codegolf.stackexchange.com/a/214583/75681) (cortesy @coltim) would look like in Red :) ]
[Question] [ This challenge is simply to return a list of lists of integers, similar to the Python range function, except that each successive number must be that deep in lists. **Rules**: * Create a program or a non-anonymous function * It should return or print the result * The result should be returned in a list (of lists) or array (of arrays) * If the parameter is zero, return an empty list * This should be able to handle an integer parameter 0 <= n < 70. + (recursive solutions blow up pretty fast) * The function should be callable with only the one parameter. * Other behavior is undefined. * This is code golf, so shortest code wins. **Example Call:** ``` rangeList(6) > [0, [1, [2, [3, [4, [5]]]]]] ``` **Test Cases:** ``` 0 => [] 1 => [0] 2 => [0, [1]] 6 => [0, [1, [2, [3, [4, [5]]]]]] 26 => [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]]]]]]]]]]]]]]]]]]]]]]]]]] 69 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ``` **EDIT:** isaacg's [answer](https://codegolf.stackexchange.com/a/47366/34718) is the shortest so far. I'll update the accepted answer if anyone finds a shorter one in a language that existed at the posting of the challenge. Thanks for playing! [Answer] # Pyth, 13 bytes ``` ?hu]+HG_UQYQY ``` [Try it here.](http://pyth.herokuapp.com/) ``` Implicit: Q = eval(input()) Y = [] ? QY If Q = 0, print Y h else, print the first element of u _UQY the reduce, where Y is the initial value, over the list reversed(range(Q)) ]+HG The reduce function: The list containing H prepended onto G. The new number is inserted into the accumulated list, then the resultant list is wrapped in another list. ``` [Answer] # APL (~~13~~ 18) Assuming `⎕IO=0`: ``` f←{×⍵:⊃,∘⊂∘,/⍳⍵⋄⍬} ``` Explanation: * `×⍵:` if `⍵` is positive, + `,∘⊂∘,`: join the left operand to the enclose of the right operand (i.e. `x ,∘⊂∘, y = [x, [y]]`) + `/`: reduce + `⍳⍵`: the numbers `0..⍵-1` + `⊃`: disclose the result * `⋄`: otherwise + `⍬`: return the empty list + (this is necessary because `/` fails on `⍬`, and `⍳0` gives the empty list.) Addendum: This function returns a nested array. However, it is a bit hard to tell this from APL's default output. It separates array items by spaces, so you can only tell nesting by double spaces. Here is a function that will take a nested array, and return a string, formatting the nested array in Python style (i.e. `[a,[b,[c,...]]]`). ``` arrfmt←{0=≡⍵:⍕⍵ ⋄ '[',(1↓∊',',¨∇¨⍵),']'} ``` [Answer] # Haskell, 67 bytes ``` data L=E|I Int|L[L] 1#m=L[I$m-1] n#m=L[I$m-n,(n-1)#m] p 0=E p n=n#n ``` In Haskell all elements of a list have to be of the same type, so I cannot mix integers with list of integers and I have to define a custom list type `L`. The helper function `#` recursively constructs the required list. The main function `p` checks for the empty list and calls `#` otherwise. As new data types cannot be printed by default (the rules allow just to return the list), I add some more code for demonstration purpose: ``` data L=E|I Int|L[L] deriving Show ``` Now: ``` -- mapM_ (print . p) [0..5] E L [I 0] L [I 0,L [I 1]] L [I 0,L [I 1,L [I 2]]] L [I 0,L [I 1,L [I 2,L [I 3]]]] L [I 0,L [I 1,L [I 2,L [I 3,L [I 4]]]]] ``` [Answer] # Python, 48 bytes ``` f=lambda n,i=0:i<n and[i]+[f(n,i+1)]*(i<n-1)or[] ``` Using list multiplication to handle the special case. [Answer] # Mathematica, 33 ``` f@0={};f@1={0};f@n_:={0,f[n-1]+1} ``` [Answer] # CJam, 16 bytes ``` Lri){[}%]~;']*~p ``` This is a full program. It takes input via STDIN and prints the final array on to STDOUT. As with the other CJam entry, `0` input will print `""` as that is the representation of an empty array in CJam. **How it works**: ``` L "Put an empty array on stack. This will be used for the 0 input"; ri) "Read the input, convert it to integer and increment it"; {[}% "Map over the array [0 ... input number] starting another array"; "after each element"; ]~; "Now on stack, we have input number, an empty array and the final"; "opening bracket. Close that array, unwrap it and pop the empty array"; ']*~ "Put a string containing input number of ] characters and eval it"; "This closes all the opened arrays in the map earlier"; p "Print the string representation of the array"; "If the input was 0, the map runs 1 time and the ; pops that 1 array"; "Thus leaving only the initial empty array on stack"; ``` [Try it online here](http://cjam.aditsu.net/#code=Lri%29%7B%5B%7D%25%5D%7E%3B%27%5D*%7Ep&input=0) [Answer] # JavaScript (ES6) 40 Recursive solution, pretty robust, no blows. *Update* Fails near 6500 with 'too much recursion' ``` F=n=>n--?(R=m=>m<n?[m,R(++m)]:[m])(0):[] ``` Iterative solution (45) No limits except memory usage ``` F=n=>{for(s=n?[--n]:[];n;)s=[--n,s];return s} ``` Try F(1000): FireBug console will not show you more than 190 nested arrays, but they are there [Answer] # Java, 88 107 105 104 102 bytes ``` import java.util.*;int o;List f(final int n){return new Stack(){{add(n<1?"":o++);if(o<n)add(f(n));}};} ``` Pretty long compared to the others, though you can't do much better with Java. A check to determine whether to continue recursion is all it takes. [Answer] # Python 2, 56 bytes I suspect this could be golfed more. ``` f=lambda n,i=0:[i,f(n,i+1)]if i<n-1 else[i]if n>0 else[] ``` Tests: ``` # for n in (0,1,2,6,26,69): print n, '=>', f(n) 0 => [] 1 => [0] 2 => [0, [1]] 6 => [0, [1, [2, [3, [4, [5]]]]]] 26 => [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]]]]]]]]]]]]]]]]]]]]]]]]]] 69 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ``` [Answer] # CJam, 17 bytes I know Optimizer has found 16, but here is the best I can do: ``` {:I{[}%;{]}I1e>*} ``` This is a block, the closest thing to a function in CJam, which takes an integer on the stack, and leaves the desired nested array. Use [this program to test it](http://cjam.aditsu.net/#code=5%0A%7B%3AI%7B%5B%7D%25%3B%7B%5D%7DI1e%3E*%7D%0A~ed%3B), which puts the input on the stack, then calls the function and inspects the stack. Note that for `0`, the stack output will contain `""` - this *is* CJam's native representation of an empty array. [Answer] # Ruby 46 ``` f=->n{r=a=[] (0...n).map{|i|a<<a=[i]} r[0]||r} ``` Test it online: <http://ideone.com/uYRVTa> [Answer] # C# - 100 Simple recursion. Check the zero special case and tick up with one variable, down with the other ``` object[]A(int y,int x=0){return y==0?new object[0]:y==1?new object[]{x}:new object[]{x,A(--y,++x)};} ``` # C++ 87 **(Visual C++ 2012)** ``` int*A(int y,int x=0){int*b=new int{x};return!y?new int:--y?(b[1]=(int)A(y,++x))?b:0:b;} ``` This one is great, by which I mean byzantine, but it's the same basic idea as the c# one. It's a C style array implementation, so it doesn't give you an array, it gives a int pointer, in which I was be storing both ints and other pointers. Like this: `[0,*] *->[1,#] #-> [2,&] &-> etc`, where the symbols are pseudo code for the int value of a pointer and the --> is where it pointers to in memory. What an excellent easy to use implementation of c style jagged arrays I've devised (cough), but I maintain it's plausible enough to be within the rules of the question. There's quite a lot of abusing ternary operators here, and also quite a lot of abusing the implicit cast from int to bool. **Example:** If we let `int *bar = (int*)A(3);`, we can see: ``` bar 0x003bded8 {0} ((int*)bar[1])[0] 1 ((int*)(((int*)bar[1])[1]))[0] 2 ``` Which is pointer talk for [0,[1,[2]]]. Okay, fine. It doesn't actually have to be the awful. Here's some test code for running this c++ code: ``` int* GetNext(int* p){ return (int*)p[1]; } int main() { auto x = 10; auto bar = A(x); for (int i = 1; i < x; i++){ bar = GetNext(bar); std::cout << bar[0] << std::endl; } ``` } [Answer] # Pyth, 15 bytes ``` ?u[HG)_UtQ]tQQY ``` Which is really saying, in Python: ``` Q = eval(input()) if Q: print reduce(lambda G,H:[H,G], reverse(range(Q-1)), [Q-1]) else: print [] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~65 59 45~~ 41 bytes These nested lists are the same data-structure as rooted `Tree`s, except that they can also be empty. Hence, we can use a list of them - also called a `Forest` to represent them. ``` (0!) data T=N[T]Int m!n=[N((m+1)!n)m|m<n] ``` [Try it online!](https://tio.run/##JYq9DoIwFIX3@xQXpzZEAw6YGDo5OcgiGxrTQBEivRJ6Exh8dmvVk3w5Pzmddg8zDL5VFy@SSEKjWWOpiqq8HonBRqSqQggbpzIiaV82p6vvybGm2uC5e85Y4tyZyQAGue8gCmSHi0T17wvGMa5wHwjhN7EDsLqncLF6PN1QjFNPjBtsA5PRjQw@9GQcqjzHu@HDk9gQO59AClvIYJvBLnnX7aDvzq/rcfwA "Haskell – Try It Online") ### Explanation First of all we need to implement the `Tree` data type: ``` data Tree = Node [Tree] Int ``` From there it's just recursion using two parameters `m` (counting up) and `n` to keep track when to terminate: ``` m ! n= [ Node ((m+1)!n) m| m<n ] ``` ## Alternative, 61 bytes ``` import Data.Tree f n=unfoldForest(\b->(b,[b+1|b<n-1]))[0|n>0] ``` [Try it online!](https://tio.run/##bVDBTsJAEL3vV7xwoQ1sUzhggtALRj2gF7ghIdt0Sje2u7W7hRDx6g/4h/4IbhGSxniazJs3772ZTJhXyvOTLEpdWbzVIpeppAQPj7Ngken9dXInrAiWFRFLoaa1SnWe3OuKjPVeYh55cX8V9wbHeKL4YO37q/CoonB94hxLjUQaEeeEsiJrD7yspLJSbfuoqNA7gs3IEL4/vzBEdigzUgbMOPdfB4zHaLJAYBrhggnwCAvrpLbg/BYt@vTc4J23NVIHX48KGnwujd1sztRm2ukwYJ9RRa7iAnvPOiHUWK19mKtujV4P5h/WzvxldftdjNvRdua87BLzD8YKIZXjF6J82sAra@vumSsE7Y3AZQvco0Tiu5pLRc5iMsGW7EwrS8qaU8gGbMhGbDhiN@EP "Haskell – Try It Online") ### Explanation The function `unfoldForest` takes a list of initial values and a function `x -> (y,[x])`. For each initial value `x` it *unfolds* a tree using the function, producing a tuple `(y,xs)` where `y` will become the root and the `xs` are used to repeat the procedure: ``` unfoldForest (\b -> (b, [b+1 | b < 2]) [0] ≡ Node 0 [unfoldForest (\b -> (b, [b+1 | b < 2) [1]] ≡ Node 0 [Node 1 [unfoldForest (\b -> (b, [b+1 | b < 2) []]] ≡ Node 0 [Node 1 []] ``` [Answer] ## Perl - 44 ``` sub t{$r=[($t)=@_];$r=[$t,$r]while--$t>0;$r} ``` Will add explanation upon request. You can try it [here](https://ideone.com/boNb5V). [Answer] # JavaScript, 93 bytes This isn't ideal, but I might as well give it a try. I'll try and golf this further later on, though for now I see no obvious way to. ``` function f(n){s='[';i=0;while(i<n-1)s+=i+++',[';s+=i||'';do{s+=']'}while(i--);return eval(s)} ``` [Answer] # Python, 75 bytes This is just for show. It's the program I wrote when creating/designing this challenge. ``` f=lambda x,y=[]:y if x<1 else f(x-1,[x-2]+[y or[x-1]])if x>1 else y or[x-1] ``` [Answer] # Python, 44 ``` f=lambda n,i=0:i<n-1and[i,f(n,i+1)]or[i][:n] ``` Recursively creates the tree. The `[:n]` at the end is to special-case `n==0` into giving the empty list. [Answer] # [Joe](https://github.com/JaniM/Joe), 8 bytes Note: This is a non-competing answer. The first version of Joe was released after this question. ``` F:/+,M]R ``` What do we have here? `F:` defines a function F that is a chain of `/+,`, `M]` and `R`. When you call `Fn`, first `Rn` gets evaluated, returning range from 0 to n, exclusive. `M]` wraps each element to a list. Then the list is applied to `/+,`. `x +, y` returns `x + [y]`. `/` is a right fold. Thus, `/+,a b c d...` returns `[a, [b, [c, [d...]]]`. Example invocations (code is indented by 3, output by 0): ``` F:/+,M]R F10 [0, [1, [2, [3, [4, [5, [6, [7, [8, [9]]]]]]]]]] F2 [0, [1]] F1 [0] F0 [] F_5 [0, [-1, [-2, [-3, [-4]]]]] ``` [Answer] # Ruby - Recursive version - 52 ``` r=->(n,v=nil){(n-=1;n<0 ?v:r[n,(v ?[n,v]:[n])])||[]} ``` # Non-recursive version: ~~66~~ ~~62~~ 57 ``` r=->i{(i-1).downto(0).inject(nil){|a,n|a ?[n,a]:[n]}||[]} ``` Sample output (same for both versions) ``` p r[0] # => [] p r[1] # => [0] p r[2] # => [0, [1]] p r[6] # => [0, [1, [2, [3, [4, [5]]]]]] p r[26] # => [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]]]]]]]]]]]]]]]]]]]]]]]]]] p r[69] # => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ``` The non-recursive version can handle arbitrarily large input. ``` p r[1000] # => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68, [69, [70, [71, [72, [73, [74, [75, [76, [77, [78, [79, [80, [81, [82, [83, [84, [85, [86, [87, [88, [89, [90, [91, [92, [93, [94, [95, [96, [97, [98, [99, [100, [101, [102, [103, [104, [105, [106, [107, [108, [109, [110, [111, [112, [113, [114, [115, [116, [117, [118, [119, [120, [121, [122, [123, [124, [125, [126, [127, [128, [129, [130, [131, [132, [133, [134, [135, [136, [137, [138, [139, [140, [141, [142, [143, [144, [145, [146, [147, [148, [149, [150, [151, [152, [153, [154, [155, [156, [157, [158, [159, [160, [161, [162, [163, [164, [165, [166, [167, [168, [169, [170, [171, [172, [173, [174, [175, [176, [177, [178, [179, [180, [181, [182, [183, [184, [185, [186, [187, [188, [189, [190, [191, [192, [193, [194, [195, [196, [197, [198, [199, [200, [201, [202, [203, [204, [205, [206, [207, [208, [209, [210, [211, [212, [213, [214, [215, [216, [217, [218, [219, [220, [221, [222, [223, [224, [225, [226, [227, [228, [229, [230, [231, [232, [233, [234, [235, [236, [237, [238, [239, [240, [241, [242, [243, [244, [245, [246, [247, [248, [249, [250, [251, [252, [253, [254, [255, [256, [257, [258, [259, [260, [261, [262, [263, [264, [265, [266, [267, [268, [269, [270, [271, [272, [273, [274, [275, [276, [277, [278, [279, [280, [281, [282, [283, [284, [285, [286, [287, [288, [289, [290, [291, [292, [293, [294, [295, [296, [297, [298, [299, [300, [301, [302, [303, [304, [305, [306, [307, [308, [309, [310, [311, [312, [313, [314, [315, [316, [317, [318, [319, [320, [321, [322, [323, [324, [325, [326, [327, [328, [329, [330, [331, [332, [333, [334, [335, [336, [337, [338, [339, [340, [341, [342, [343, [344, [345, [346, [347, [348, [349, [350, [351, [352, [353, [354, [355, [356, [357, [358, [359, [360, [361, [362, [363, [364, [365, [366, [367, [368, [369, [370, [371, [372, [373, [374, [375, [376, [377, [378, [379, [380, [381, [382, [383, [384, [385, [386, [387, [388, [389, [390, [391, [392, [393, [394, [395, [396, [397, [398, [399, [400, [401, [402, [403, [404, [405, [406, [407, [408, [409, [410, [411, [412, [413, [414, [415, [416, [417, [418, [419, [420, [421, [422, [423, [424, [425, [426, [427, [428, [429, [430, [431, [432, [433, [434, [435, [436, [437, [438, [439, [440, [441, [442, [443, [444, [445, [446, [447, [448, [449, [450, [451, [452, [453, [454, [455, [456, [457, [458, [459, [460, [461, [462, [463, [464, [465, [466, [467, [468, [469, [470, [471, [472, [473, [474, [475, [476, [477, [478, [479, [480, [481, [482, [483, [484, [485, [486, [487, [488, [489, [490, [491, [492, [493, [494, [495, [496, [497, [498, [499, [500, [501, [502, [503, [504, [505, [506, [507, [508, [509, [510, [511, [512, [513, [514, [515, [516, [517, [518, [519, [520, [521, [522, [523, [524, [525, [526, [527, [528, [529, [530, [531, [532, [533, [534, [535, [536, [537, [538, [539, [540, [541, [542, [543, [544, [545, [546, [547, [548, [549, [550, [551, [552, [553, [554, [555, [556, [557, [558, [559, [560, [561, [562, [563, [564, [565, [566, [567, [568, [569, [570, [571, [572, [573, [574, [575, [576, [577, [578, [579, [580, [581, [582, [583, [584, [585, [586, [587, [588, [589, [590, [591, [592, [593, [594, [595, [596, [597, [598, [599, [600, [601, [602, [603, [604, [605, [606, [607, [608, [609, [610, [611, [612, [613, [614, [615, [616, [617, [618, [619, [620, [621, [622, [623, [624, [625, [626, [627, [628, [629, [630, [631, [632, [633, [634, [635, [636, [637, [638, [639, [640, [641, [642, [643, [644, [645, [646, [647, [648, [649, [650, [651, [652, [653, [654, [655, [656, [657, [658, [659, [660, [661, [662, [663, [664, [665, [666, [667, [668, [669, [670, [671, [672, [673, [674, [675, [676, [677, [678, [679, [680, [681, [682, [683, [684, [685, [686, [687, [688, [689, [690, [691, [692, [693, [694, [695, [696, [697, [698, [699, [700, [701, [702, [703, [704, [705, [706, [707, [708, [709, [710, [711, [712, [713, [714, [715, [716, [717, [718, [719, [720, [721, [722, [723, [724, [725, [726, [727, [728, [729, [730, [731, [732, [733, [734, [735, [736, [737, [738, [739, [740, [741, [742, [743, [744, [745, [746, [747, [748, [749, [750, [751, [752, [753, [754, [755, [756, [757, [758, [759, [760, [761, [762, [763, [764, [765, [766, [767, [768, [769, [770, [771, [772, [773, [774, [775, [776, [777, [778, [779, [780, [781, [782, [783, [784, [785, [786, [787, [788, [789, [790, [791, [792, [793, [794, [795, [796, [797, [798, [799, [800, [801, [802, [803, [804, [805, [806, [807, [808, [809, [810, [811, [812, [813, [814, [815, [816, [817, [818, [819, [820, [821, [822, [823, [824, [825, [826, [827, [828, [829, [830, [831, [832, [833, [834, [835, [836, [837, [838, [839, [840, [841, [842, [843, [844, [845, [846, [847, [848, [849, [850, [851, [852, [853, [854, [855, [856, [857, [858, [859, [860, [861, [862, [863, [864, [865, [866, [867, [868, [869, [870, [871, [872, [873, [874, [875, [876, [877, [878, [879, [880, [881, [882, [883, [884, [885, [886, [887, [888, [889, [890, [891, [892, [893, [894, [895, [896, [897, [898, [899, [900, [901, [902, [903, [904, [905, [906, [907, [908, [909, [910, [911, [912, [913, [914, [915, [916, [917, [918, [919, [920, [921, [922, [923, [924, [925, [926, [927, [928, [929, [930, [931, [932, [933, [934, [935, [936, [937, [938, [939, [940, [941, [942, [943, [944, [945, [946, [947, [948, [949, [950, [951, [952, [953, [954, [955, [956, [957, [958, [959, [960, [961, [962, [963, [964, [965, [966, [967, [968, [969, [970, [971, [972, [973, [974, [975, [976, [977, [978, [979, [980, [981, [982, [983, [984, [985, [986, [987, [988, [989, [990, [991, [992, [993, [994, [995, [996, [997, [998, [999]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ``` Both versions also gracefully accept negative numbers ``` p r[-5] # => [] ``` [Answer] # PHP 5.4 (67 bytes): I know, I know. It's far from being the shortest answer. But it works! Here it is: ``` function F($n){for($c=$n?[--$n]:[];~$n&&$n--;$c=[$n,$c]);return$c;} ``` You can test it right here: <https://ideone.com/42L35E> (ignore the error) --- # Javascript (57 bytes): This is the **same** **exact** **code** except that Javascript is picky about the return and I've reduced the variable names: ``` function F(n){for(c=n?[--n]:[];~n&&n--;c=[n,c]);return c} ``` See? Same code! --- # ES6 (49 bytes): Basically the same exact code, but reduced for ES6: ``` F=n=>{for(c=n?[--n]:[];~n&&n--;c=[n,c]);return c} ``` [Answer] # Javascript (114 bytes): Everybody else was doing recursive, so I wanted to try an iterative solution. I have too many special cases, though. I hold a master list, and then loop and append new lists with new numbers. ``` function q(n){a=[];if(n==1)a=[0];else if(n!=0){a=[0,b=[]];for(i=1;i<n;){c=[];b.push(c);b.push(i++);b=c}}return a} ``` [Answer] # Common Lisp (95 bytes): ``` (defun f(n &optional(i 0))(cond((< i(1- n))(cons i(list(f n(1+ i)))))((> n 0)(list i))(t nil))) ``` [Answer] # JavaScript, ~~35~~ 37 bytes Recursive solution ``` f=(n,x=[])=>n?f(--n,x[0]?[n,x]:[n]):x ``` [Try it online!](https://tio.run/##DcexCsMgEADQX3H04AxpBqEBm71DO3QUh5B6IUXugkpJv95merzP/J3Lkre9GpZ3bI2cZjycD@BuPJE25qzvw@RPw@g5wHg0kqx0ilWxElK@xwsOaHGwaK8B1CJcJMUuyarvr@ejKzVvvG7006QZANof) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` _i¯ëFNI<α)R ``` [Try it online](https://tio.run/##yy9OTMpM/f/fzc/T5txGzaD//80A) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCS6i9ksKjtkkKSvb/4zMPrT@82s0vwubcRs2g/7W1OjH/ow10FAx1FIx0FMyAJBCbWcYCAA). 11-bytes alternative: ``` _i¯ëݨRvy)R ``` [Try it online](https://tio.run/##yy9OTMpM/f8/PvPQ@sOrD889tCKorFIz6P9/MwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCS6i9ksKjtkkKSvb/4zMPrT@8@vDcQyuCyio1g/7X1urE/I820FEw1FEw0lEwA5JAbGYZCwA). **Explanation:** 05AB1E has no loops that go downwards, so to loop in the range `(input, 0]` I either have to: * Create that range first (`ݨR`; create range `[0, input]`, remove last item, reverse), and then loop over it (`vy`); * Or loop in the range `[0, input)` instead (`F`), and take the absolute difference between the loop-index and the input-1 (`NI<α`). ``` _i # If the (implicit) input is 0: ¯ # Push the global array (empty by default) ë # Else: F # Loop `N` in the range [0, (implicit) input): N # Push index `N` I< # Push input-1 α # Take the absolute difference between the two ) # Wrap everything on the stack into a list R # Reverse the list # (output the result implicitly after the if/loop) ``` ]
[Question] [ **Final results available** # Introduction After my previous KOTH with heavy themes ([fantasy war](https://codegolf.stackexchange.com/questions/44978/koth-warring-towns), [worldwide pandemic](https://codegolf.stackexchange.com/questions/70135/koth-a-world-wide-pandemic)...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot! # Glossary > > *Coins*: Tokens that can either be flipped or unflipped. > > *Unflipped*: Coins placed on the table with their value pointing down. This is the default state of the coins. > > *Flipped*: Coins placed on the table with their value pointing up. > > *Local*: Refers to your pile of coins. > > *Global*: Refers to the pile of coins at the center. > > > # Principle **At the start** of the game, each player starts with **0 points** and **0 coins** (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players. Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side. The game lasts for **50 rounds** or until there are **0 coins at the center** at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula: ``` (2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))` ``` Each action will get you points (or make you lose some) and **at the end** of the game, **each coin** you have will be added to your points (**-1 for unflipped, +2 for flipped**). The player with the highest score wins. The controller provides you with input via command arguments, and your program has to output via stdout. # Syntax **Input** Each time your program is called, it will receive arguments in this format: `Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...` Rounds are 1-indexed. **Example input** `6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0` Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative. **Output** You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used. `N`: Do Nothing `1`: Take 1 coin from the central pile *[Effects: +1 local unflipped / -1 point / -1 global unflipped]* `2`: Take 2 coins from the central pile *[Effects: +2 local unflipped / -2 points / -2 global unflipped]* `3`: Take 3 coins from the central pile *[Effects: +3 local unflipped / -3 points / -3 global unflipped]* `A`: Put back 1 coin from your pile *[Effects: -1 local unflipped / +1 point / +1 global unflipped]* `B`: Put back 2 coins from your pile *[Effects: -2 local unflipped / +2 points / +2 global unflipped]* `C`: Put back 3 coins from your pile *[Effects: -3 local unflipped / +3 points / +3 global unflipped]* `X`: Remove 1 coin from your pile *[Effects: -1 local unflipped / 0 point]* `Y`: Remove 2 coins from your pile *[Effects: -2 local unflipped / 0 point]* `Z`: Remove 3 coins from your pile *[Effects: -3 local unflipped / 0 point]* `R`: Rotate coins to previous player *[Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]* `T`: Rotate coins to next player *[Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]* `F`: Flip 1 coin *[Effects: -1 local unflipped / +1 local flipped / +2 point]* `U`: Unflip 1 coin *[Effects: +1 local unflipped / -1 local flipped / -2 point]* **Example output** `2FF` : Takes two coins and flips two coin, scoring `-2 + 2 + 2 = 2 points` If your output is incorrect, controller will assume `NNN`. # Controller You can find the controller on [GitHub](https://github.com/Thrax37/was-master). It also contains two samplebots, written in Java. To make it run, check out the project and open it in your Java IDE. The entry point in the `main` method of the class `Game`. Java 8 required. To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the `players` package (you can take example on the already existing bots). This class must implement `Player` to override the method `String getCmd()`. The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : `return "C:\Ruby\bin\ruby.exe MyBot.rb";`. Finally, add the bot in the players array at the top of the `Game` class. # Rules * Bots should not be written to beat or support specific other bots. * Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has 1 second to respond. * Provide commands to compile and run your submissions. # Supported Languages I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language. As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11. # Final results These are the results of 100 games (points are added up) : ``` 1. BirdInTheHand: 1017790 2. Balance: 851428 3. SecondBest: 802316 4. Crook: 739080 5. Jim: 723440 6. Flipper: 613290 7. Wheeler: 585516 8. Oracle: 574916 9. SimpleBot: 543665 10. TraderBot: 538160 11. EgoisticalBot: 529567 12. RememberMe: 497513 13. PassiveBot: 494441 14. TheJanitor: 474069 15. GreedyRotation: 447057 16. Devil: 79212 17. Saboteur: 62240 ``` Individual results of the games are available here : <http://pasted.co/63f1e924> (with starting coins and number of rounds per game). A bounty of 50 reputations is awarded to the winner : **Bird In The Hand** by [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner). Thank you all for your participation, see you next KOTH~ [Answer] # Oracle, Python 3 Update: changed the order of the various tries to favor low pile of coins over rotations. ``` import sys import itertools from copy import deepcopy MOVES_REQUIRED = 3 FLIPPED = 0 UNFLIPPED = 1 def filter_neighbors(neighbors, me, size): limit = size - MOVES_REQUIRED for data in neighbors: i, _, flipped, unflipped = map(int, data.split('_')) if MOVES_REQUIRED < (me - i) % size < limit: continue # Skip neighbors that are too far away yield i, [flipped, unflipped] class Player: def __init__(self, raw_data): _, me, coins, *data = raw_data.split(';') self.num_players = len(data) self._me = int(me) self._coins = int(coins) self._state = dict(filter_neighbors(data, self._me, self.num_players)) def reset(self): self.me = self._me self.coins = self._coins self.state = deepcopy(self._state) self.my_state = self.state[self.me] def invalid_move(self, move): if move in 'NRT': return False if move in '123'[:self.coins]: return False flipped, unflipped = self.my_state if flipped and move == 'U': return False if unflipped and move == 'F': return False if move in 'AXBYCZ'[:2 * unflipped]: return False return True def N(self): return 0 def one(self): self.coins -= 1 self.my_state[UNFLIPPED] += 1 return -1 def two(self): self.coins -= 2 self.my_state[UNFLIPPED] += 2 return -2 def three(self): self.coins -= 3 self.my_state[UNFLIPPED] += 3 return -3 def A(self): self.coins += 1 self.my_state[UNFLIPPED] -= 1 return 1 def B(self): self.coins += 2 self.my_state[UNFLIPPED] -= 2 return 2 def C(self): self.coins += 3 self.my_state[UNFLIPPED] -= 3 return 3 def X(self): self.my_state[UNFLIPPED] -= 1 return 0 def Y(self): self.my_state[UNFLIPPED] -= 2 return 0 def Z(self): self.my_state[UNFLIPPED] -= 3 return 0 def R(self): self.me = (self.me + 1) % self.num_players flipped, unflipped = self.my_state = self.state[self.me] return 2 * flipped - unflipped def T(self): self.me = (self.me - 1) % self.num_players flipped, unflipped = self.my_state = self.state[self.me] return 2 * flipped - unflipped def F(self): self.my_state[FLIPPED] += 1 self.my_state[UNFLIPPED] -= 1 return 2 def U(self): self.my_state[FLIPPED] -= 1 self.my_state[UNFLIPPED] += 1 return -2 setattr(Player, '1', Player.one) setattr(Player, '2', Player.two) setattr(Player, '3', Player.three) def scenarii(player): for tries in itertools.product('FUABCXYZ123NRT', repeat=MOVES_REQUIRED): player.reset() points = 0 for try_ in tries: if player.invalid_move(try_): break points += getattr(player, try_)() else: yield points, ''.join(tries) if __name__ == '__main__': player = Player(sys.argv[1]) print(max(scenarii(player))[1]) ``` Tries every single possible output and keep the one that yield the maximum amount of points for this turn. [Answer] ## Bird in the Hand, Ruby ``` def deep_copy(o) Marshal.load(Marshal.dump(o)) end ID = 0 PTS = 1 FLP = 2 UFL = 3 round, id, global, *players = ARGV[0].split(';') round = round.to_i id = id.to_i global = global.to_i players.map!{ |s| s.split('_').map(&:to_i) } nplayers = players.size my_pos = players.find_index { |i, p, f, u| i == id } state = { round: round, id: id, global: global, players: players, my_pos: my_pos, me: players[my_pos], prev_p: players[my_pos-1], next_p: players[(my_pos+1)%nplayers], ends_game: round == 50 && my_pos == nplayers-1, score: 0 } moves = { 'N' => ->s{deep_copy(s)}, '1' => ->s{t = deep_copy(s); coins = [1, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t}, '2' => ->s{t = deep_copy(s); coins = [2, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t}, '3' => ->s{t = deep_copy(s); coins = [3, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t}, 'A' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t}, 'B' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t}, 'C' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t}, 'X' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t}, 'Y' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:me][UFL] -= coins; t}, 'Z' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:me][UFL] -= coins; t}, 'F' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t[:me][FLP] += coins; t[:score] += 2*coins; t}, 'U' => ->s{t = deep_copy(s); coins = [1, t[:me][FLP]].min; t[:me][FLP] -= coins; t[:me][UFL] += coins; t[:score] -= 2*coins; t}, 'R' => ->s{ t = deep_copy(s) (-1...t[:players].size-1).each do |i| t[:players][i][FLP] = s[:players][i+1][FLP] t[:players][i][UFL] = s[:players][i+1][UFL] end t[:score] += 2*t[:me][FLP] - t[:me][UFL]; t }, 'T' => ->s{ t = deep_copy(s) (0...t[:players].size).each do |i| t[:players][i][FLP] = s[:players][i-1][FLP] t[:players][i][UFL] = s[:players][i-1][UFL] end t[:score] += 2*t[:me][FLP] - t[:me][UFL]; t } } results = {} 'N123ABCXYZFURT'.each_char { |c1| s1 = moves[c1][state] 'N123ABCXYZFURT'.each_char { |c2| s2 = moves[c2][s1] 'N123ABCXYZFURT'.each_char { |c3| s3 = moves[c3][s2] s3[:ends_game] ||= s3[:global] == 0 results[c1+c2+c3] = s3 } } } endingMoves = results.keys.select{|k| results[k][:ends_game]} endingMoves.each{|k| results[k][:score] += 2*results[k][:me][FLP] - results[k][:me][UFL]} $> << results.keys.shuffle.max_by {|k| results[k][:score]} ``` If neither of us has a bug in their programs, the main algorithm of this is likely very similar to Mathias's Oracle. Based on the assumption that prior to the final round we can't know which coins we'll end up with, we evaluate the current set of moves purely based on the points received immediately, ignoring completely what sort of coins we'll end up with. Since there are only **143 = 2744** possible move sets we can easily simulate all of them to figure out how many points they'll bring. However, if a move set ends the game (either because it reduces the global pot to zero, or because this is round 50 and we're the last one to move), then it also takes into account the coins owned at the end of the move set to determine the move set's value. I first considered terminating the game whenever possible, but this would result in the horrible move `333` when there are only 9 coins left in the pot. If there are multiple move sets giving the same result, we choose a random one. (I might change this to bias it in favour of game-terminating move sets.) [Answer] ## Greedy Rotation, Ruby ``` round, id, global, *players = ARGV[0].split(';') round = round.to_i id = id.to_i global = global.to_i players.map!{ |s| s.split('_').map(&:to_i) } nplayers = players.size my_pos = players.find_index { |i, p, f, u| i == id } prev_p = players[my_pos-1] next_p = players[(my_pos+1)%nplayers] prev_score = 2*prev_p[2] - prev_p[3] next_score = 2*next_p[2] - next_p[3] take_from = prev_p $><< '3' if prev_score > next_score || prev_score == next_score && prev_p[3] > next_p[3] $><< 'T' else $><< 'R' take_from = next_p end if take_from[3] >= 3 $><< 'C' elsif take_from[3] >= 1 $><< 'F' else $><< 'N' end ``` This is quite similar to ArtOfCode's approach, except that this checks from which neighbour we can get more points, and it chooses `C` instead of `F` if we end up with 3 or more coins after the rotation. After writing this up, I'm pretty sure that a better approach would be just to greedily pick the best out of all moves every time, preceding rotation by taking if possible (instead of sticking to a fixed "get unflipped, rotate, get rid of unflipped" pattern). This also doesn't take into account the implicit points represented by the coins actually owned (based on the assumption that the game is going to last enough rounds that I likely won't end up keeping my coins anyway). [Answer] ## Flipper, Python 2 Flipper gathers coins and tries to turn unflipped to flipped. Flipper is not a smart player but tries to be a positive force in the game. ``` import sys, random # process input data (not used here): args = sys.argv[1].split(';') rounds, myid, coins = map(int, args[:3]) players = [map(int, data.split('_')) for data in args[3:]] # implement strategy using multiples of 'N123ABCXYZRTFU': options = '12333FFFFFFFFFFF' print ''.join(random.choice(options) for i in range(3)) ``` Flipper just needs the `python flipper.py <arg>` to run. [Answer] ## SimpleBot, Python 3 SimpleBot is, well, simple. He's worked out one strategy and he's going to stick with it. To run: ``` python3 main.py ``` where the contents of the `main.py` file is: ``` def main(): print("3RF") if __name__ == "__main__": main() ``` [Answer] ## Balance, Lua Balance will try to keep the balance in its token, minimizing the loss in case someone uses the `R` and `T` actions against him. He thinks this style of life is the true one and should be enforced to anyone that doesn't keep a good balance of flipped/unflipped coins, so everyone close to him will be punished as soon as it could make them lose points. He needs the following command to run: ``` lua balance.lua ``` Where the file balance.lua contains the following piece of code: ``` local datas={} local arg=arg[1]..";" -- parse the arguments -- add some meta datas for debuging purpose/usefulness arg:gsub("(.-);",function(c) if not datas.round then datas.round=c+0 elseif not datas.myID then datas.myID=c+0 elseif not datas.coins then datas.coins=c+0 else datas[#datas+1]={} datas[#datas].repr=c c=c.."_" tmp={} c:gsub("(.-)_",function(d) tmp[#tmp+1]=d end) datas[#datas].id=tmp[1]+0 datas[#datas].points=tmp[2]+0 datas[#datas].flip=tmp[3]+0 datas[#datas].unflip=tmp[4]+0 if datas[#datas].id==datas.myID then datas.myOrder=#datas datas.myDatas=datas[#datas] end end end) local actions="" -- construct actions for i=1,3 do -- if we aren't in balance and can grab more coins -- we do it if #actions==0 and datas.myDatas.unflip<=datas.myDatas.flip/2 and datas.coins>=3 then actions=actions.."3" datas.myDatas.unflip=datas.myDatas.unflip+3 datas.coins=datas.coins-3 -- if we couldn't grab coins, but aren't in balance, we flip some coins elseif datas.myDatas.unflip>datas.myDatas.flip/2 then actions=actions.."F" datas.myDatas.unflip=datas.myDatas.unflip-1 datas.myDatas.flip=datas.myDatas.flip+1 -- if we didn't have anything to do on our pile, let's punish -- the fools who doesn't follow the great Balance principle else previous=datas.myOrder<2 and #datas or datas.myOrder-1 following=datas.myOrder>=#datas and 1 or datas.myOrder+1 lossPrev=-datas[previous].flip + 2*datas[previous].unflip lossFoll=-datas[following].flip+ 2*datas[following].unflip if lossFoll>0 and lossPrev>0 then actions =actions.."N" elseif lossFoll>=lossPrev then actions=actions.."T" datas[following].unflip,datas[following].flip=datas[following].flip,datas[following].unflip else actions=actions.."R" datas[previous].unflip,datas[previous].flip=datas[previous].flip,datas[previous].unflip end end end print(actions) ``` [Answer] # The Janitor, Python 3 He tries to clean the mess the other players make with all these coins and put them back into pool. ``` import sys; def Parse(S): T = S.split(';'); me = eval(T[1]); N = len(T)-3; A = list(map(lambda x: list(map(lambda y:int(y),T[3+((2*N+x+me)%N)].split('_'))),range(-3,4))); Dic = {} for a in A: Dic[a[0]] = a[1:]; Dic[-1] = [me]; return Dic; def Recursive(Dic,me,D): if D==3: return ''; V = Dic[me]; N = max(Dic.keys()); Next = (me+1)%N; Prev = (N+1+me)%N; for i in range(3,0,-1): if V[2]>=i: Dic[me][2] = Dic[me][2]-i; return chr((i-1)+ord('A'))+Recursive(Dic,me,D+1); if V[1]>0: Dic[me][1] = Dic[me][1]-1; Dic[me][2] = Dic[me][2]+1; return 'U'+Recursive(Dic,me,D+1); if Dic[Next][2]>Dic[Prev][2]: return 'T'+Recursive(Dic,Next,D+1); return 'R'+Recursive(Dic,Prev,D+1); Dic = Parse(sys.argv[1]); me = Dic[-1][0]; print(Recursive(Dic,me,0)); ``` He tries to give back all his unflipped coins, if he has some stuck flipped coins he will unflip them and if he gets rid of all his coins he will get somebody's else. [Answer] # Crook, R ``` args <- strsplit(commandArgs(TRUE),";")[[1]] state <- as.data.frame(do.call(rbind,strsplit(args[-(1:3)],"_")), stringsAsFactors=FALSE) colnames(state) <- c("id","pts","flipped","unflipped") state$flipped <- as.integer(state$flipped) state$unflipped <- as.integer(state$unflipped) nb <- nrow(state) score <- function(place) 2*state$flipped[place]-state$unflipped[place] my_place <- which(state$id==args[2]) next_1 <- ifelse(my_place!=nb,my_place+1,1) next_2 <- ifelse(next_1!=nb,next_1+1,1) next_3 <- ifelse(next_2!=nb,next_2+1,1) previous_1 <- ifelse(my_place!=1,my_place-1,nb) previous_2 <- ifelse(previous_1!=1,previous_1-1,nb) previous_3 <- ifelse(previous_2!=1,previous_2-1,nb) n <- 3 out <- c() while(n){ M <- N <- score(my_place) R <- switch(n,"1"=score(next_1), "2"=cumsum(c(score(next_1),score(next_2))), "3"=cumsum(c(score(next_1),score(next_2),score(next_3)))) P <- switch(n,"1"=score(previous_1), "2"=cumsum(c(score(previous_1),score(previous_2))), "3"=cumsum(c(score(previous_1),score(previous_2),score(previous_3)))) M <- c(M,M+R[-n]) N <- c(N,N+P[-n]) if(any(R>M & R>0)){ action <- c("R","RR","RRR")[which.max(R-M)] out <- c(out, action) state[,3:4] <- state[c((nchar(action)+1):nb,seq_len(nchar(action))),3:4] n <- n-nchar(action) }else if(any(P>N & P>0)){ action <- c("T","TT","TTT")[which.max(P-N)] out <- c(out, action) state[,3:4] <- state[c((nb+1-seq_len(nchar(action))),1:(nb-seq_len(nchar(action)))),3:4] n <- n-nchar(action) }else if(n>1 & all(R[1]+M[1]>c(0,P[1]+M[1],R[1]+R[2]))){ out <- c(out,"RT") n <- n-2 }else if(n>1 & all(P[1]+M[1]>c(0,R[1]+M[1],P[1]+P[2]))){ out <- c(out,"TR") n <- n-2 }else{ out <- c(out, switch(n,"1"="A","2"="1F","3"="2FF")) n <- 0 } } cat(paste(out,collapse="")) ``` To run: `Rscript Crook.R` Basically it exchanges its coins with its neighbours only if the exchange is uneven in its favour. If no beneficial exchange is possible, then it exchanges coins with the global pile in a way that keeps its ratio intact but generate some points. **Edit:** I added a little bit of depth to this bot by making it check the next and previous 2 and 3 player stacks instead of just the next one and check if, overall, it is beneficial to rotate that many times. **2nd Edit**: Following @MartinBüttner's idea, the bot now performs a "RT", or "TR", if it would be beneficial for him more than for its neighbours (if I didn't mess up in implementing it :) ). [Answer] # Jim, Ruby based on Martin Büttner's *Greedy Rotation*. ``` PlayerId = 0 Points = 1 Flipped = 2 Unflipped = 3 round, id, global, *players = ARGV[0].split(';') round = round.to_i id = id.to_i global = global.to_i if(round == 1) print '3FF' exit end players.map!{ |s| s.split('_').map(&:to_i) } nplayers = players.size my_pos = players.find_index { |a| a[PlayerId] == id } coin_vals = players.map{|a| a[Flipped]*2 - a[Unflipped]} move = [-1,1].max_by{|s| swap_gain = coin_vals.rotate(s) scores = (0...nplayers).map{|i| swap_gain[i]+players[i][Points] } scores.delete_at(my_pos)-scores.max } if move == 1 print 'R' else print 'T' end print ['1F', 'FF'][rand 2] ``` will rotate one way or the other, depending on what will give him the most points compared to the best other player. Then, he flips for quick cash. [Answer] ## TraderBot This bot tries to rotate whenever it is the one that takes the most points in that action. If it cannot rotate then tries to get rid of the unfliped coins or take a few more to change them in the following actions. ``` import java.util.ArrayList; ``` import java.util.List; public class TraderBot { ``` class Player{ private int id; private int points; private int flip; private int unflip; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public int getFlip() { return flip; } public void setFlip(int flip) { this.flip = flip; } public int getUnflip() { return unflip; } public void setUnflip(int unflip) { this.unflip = unflip; } } int round; int coins; int otherMaxPoints = 0; Player myself = new Player(); List<Player> players = new ArrayList<>(); public static void main (String[] s){ new TraderBot().play(s); } private void play(String[] s){ parse(s[0]); System.out.println(action() + action() + action()); } private int simRotateNext(){ int flip, unflip; int maxP = Integer.MIN_VALUE; int myP = 0; for (int i = 0; i < players.size(); i++){ flip = players.get(i).getFlip(); unflip = players.get(i).getUnflip(); int next = i + 1 <= players.size() - 1 ? i + 1 : 0; int p = 2 * flip - unflip; if (p > maxP && players.get(next).getId() != myself.getId()){ maxP = p; } else if (players.get(next).getId() == myself.getId()){ myP = p; } } return myP - maxP; } private int simRotatePrev(){ int flip, unflip; int maxP = Integer.MIN_VALUE; int myP = 0; for (int i = players.size() -1; i > 0; i--){ flip = players.get(i).getFlip(); unflip = players.get(i).getUnflip(); int prev = i - 1 >= 0 ? i - 1 : players.size() - 1; int p = 2 * flip - unflip; if (p > maxP && players.get(prev).getId() != myself.getId()){ maxP = p; } else if (players.get(prev).getId() == myself.getId()){ myP = p; } } return myP - maxP; } private int rotateNext(){ int flip, unflip, nflip, nunflip; flip = players.get(0).getFlip(); unflip = players.get(0).getUnflip(); for (int i = 0; i < players.size(); i++){ int next = i + 1 <= players.size() - 1 ? i + 1 : 0; nflip = players.get(next).getFlip(); nunflip = players.get(next).getUnflip(); players.get(next).setFlip(flip); players.get(next).setUnflip(unflip); players.get(next).setPoints(players.get(next).getPoints() + 2 * flip - unflip); flip = nflip; unflip = nunflip; } return myself.getPoints(); } private int rotatePrev(){ int flip, unflip, nflip, nunflip; flip = players.get(players.size() -1).getFlip(); unflip = players.get(players.size() -1).getUnflip(); for (int i = players.size() -1; i > 0; i--){ int prev = i - 1 >= 0 ? i - 1 : players.size() - 1; nflip = players.get(prev).getFlip(); nunflip = players.get(prev).getUnflip(); players.get(prev).setFlip(flip); players.get(prev).setUnflip(unflip); players.get(prev).setPoints(players.get(prev).getPoints() + 2 * flip - unflip); flip = nflip; unflip = nunflip; } return myself.getPoints(); } private String action() { int next = simRotateNext(); int prev = simRotatePrev(); if (next > 0 || prev > 0){ if (next > prev){ rotateNext(); return "T"; } else { rotatePrev(); return "R"; } } if (myself.getUnflip() > 3){ myself.unflip -= 3; myself.points += 3; return "C"; } if (myself.getUnflip() > 0){ myself.unflip -= 1; myself.points += 2; return "F"; } if (myself.getPoints() > otherMaxPoints){ return "N"; } else { myself.unflip += 3; myself.points -= 3; return "3"; } } private void parse(String s){ String[] ps = s.split(";"); round = Integer.parseInt(ps[0]); myself.setId(Integer.parseInt(ps[1])); coins = round = Integer.parseInt(ps[2]); for (int i = 3; i < ps.length; i++){ String[] sp2 = ps[i].split("_"); if (Integer.parseInt(sp2[0]) == myself.getId()){ myself.setPoints(Integer.parseInt(sp2[1])); myself.setFlip(Integer.parseInt(sp2[2])); myself.setUnflip(Integer.parseInt(sp2[3])); players.add(myself); } else { Player p = new Player(); p.setId(Integer.parseInt(sp2[0])); p.setPoints(Integer.parseInt(sp2[1])); p.setFlip(Integer.parseInt(sp2[2])); p.setUnflip(Integer.parseInt(sp2[3])); players.add(p); if (p.getPoints() > otherMaxPoints){ otherMaxPoints = p.getPoints(); } } } } } ``` To run: Just add it to the same folder as the default bots and then create the following class ``` package players; import controller.Player; public class TraderBot extends Player { @Override public String getCmd() { return "java TraderBot"; } } ``` Then add that class to the `Player[] players` array. [Answer] ## Wheeler Wheeler calculated the best possible move for it when rotating the coins. ``` import java.util.ArrayList; import java.util.List; public class Wheeler { String[] actions = {"TTT", "TTR", "TRR", "TRT", "RRR", "RRT", "RTR", "RTT"}; String paramString; class Player{ private int id; private int points; private int flip; private int unflip; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public int getFlip() { return flip; } public void setFlip(int flip) { this.flip = flip; } public int getUnflip() { return unflip; } public void setUnflip(int unflip) { this.unflip = unflip; } @Override public String toString() { return "Player [id=" + id + ", points=" + points + ", flip=" + flip + ", unflip=" + unflip + "]"; } } int round; int coins; int otherMaxPoints = 0; Player myself = new Player(); List<Player> players = new ArrayList<>(); public static void main (String[] s){ new Wheeler().play(s); } private void play(String[] s){ paramString = s[0]; reset(); System.out.println(action()); } private int rotateNext(){ int flip, unflip, nflip, nunflip; flip = players.get(0).getFlip(); unflip = players.get(0).getUnflip(); for (int i = 0; i < players.size(); i++){ int next = i + 1 <= players.size() - 1 ? i + 1 : 0; nflip = players.get(next).getFlip(); nunflip = players.get(next).getUnflip(); players.get(next).setFlip(flip); players.get(next).setUnflip(unflip); players.get(next).setPoints(players.get(next).getPoints() + 2 * flip - unflip); flip = nflip; unflip = nunflip; } return myself.getPoints(); } private int rotatePrev(){ int flip, unflip, nflip, nunflip; flip = players.get(players.size() -1).getFlip(); unflip = players.get(players.size() -1).getUnflip(); for (int i = players.size() -1; i > 0; i--){ int prev = i - 1 >= 0 ? i - 1 : players.size() - 1; nflip = players.get(prev).getFlip(); nunflip = players.get(prev).getUnflip(); players.get(prev).setFlip(flip); players.get(prev).setUnflip(unflip); players.get(prev).setPoints(players.get(prev).getPoints() + 2 * flip - unflip); flip = nflip; unflip = nunflip; } return myself.getPoints(); } private String action() { int maxPoints = myself.getPoints(); String action = "1F2"; for (String s : actions){ int cPoints = 0; for (char c : s.toCharArray()){ if (c == 'T'){ cPoints += rotateNext(); } else { cPoints += rotatePrev(); } } if (cPoints > maxPoints){ action = s; } reset(); } return action; } private void reset(){ players = new ArrayList<>(); String[] ps = paramString.split(";"); round = Integer.parseInt(ps[0]); myself.setId(Integer.parseInt(ps[1])); coins = round = Integer.parseInt(ps[2]); for (int i = 3; i < ps.length; i++){ String[] sp2 = ps[i].split("_"); if (Integer.parseInt(sp2[0]) == myself.getId()){ myself.setPoints(Integer.parseInt(sp2[1])); myself.setFlip(Integer.parseInt(sp2[2])); myself.setUnflip(Integer.parseInt(sp2[3])); players.add(myself); } else { Player p = new Player(); p.setId(Integer.parseInt(sp2[0])); p.setPoints(Integer.parseInt(sp2[1])); p.setFlip(Integer.parseInt(sp2[2])); p.setUnflip(Integer.parseInt(sp2[3])); players.add(p); if (p.getPoints() > otherMaxPoints){ otherMaxPoints = p.getPoints(); } } } } } ``` [Answer] # Saboteur, Python 2 ``` import random moves = '3R' print '33' + ''.join(random.choice(moves)) ``` The randomness means it probably won't sabotage very well, but later I think I'll have it wait til the 'end' (how many turns/coins are left) and THEN rotate, after looking at the nearby reachable players to steal from... actually only doing one rotation seems really poor, considering other people are also likely to use rotations. I don't think this'll work very well... [Answer] ## SecondBest, Python 3 This program will go through all possible 3 move combinations and choose the second-best one. Because if you have the perfect move, it's probably a trap. Edit: removed commented-out input ``` import sys from copy import deepcopy from random import randint In=str(sys.argv[1]) def V(n,f=10,t=14): n=str(n);z=0;s='';d='0123456789';d1='N123ABCXYZRTFU' for i in n:z=z*f+d.index(i) while z:z,m=divmod(z,t);s=d1[m]+s while len(s)<3:s='N'+s return s In=In.split(';') number=In[0:3] players=In[3:] for x in range(0,len(players)):players[x]=players[x].split('_') for x in players: if number[1] in x[0]:self=x for x in range(0,len(players)): for y in range(0,len(players[x])): players[x][y]=int(players[x][y]) for x in range(0,len(number)):number[x]=int(number[x]) Pos=list(map(V,range(0,14**3))) B=[] C=[] P1=deepcopy(players) N1=deepcopy(number) for x in range(len(Pos)): P=True y=Pos[x] if '1A'in y or '2B'in y or '3C'in y or 'FU'in y or 'A1'in y or 'B2'in y or 'C3'in y or 'UF'in y: P=False#stupid check if P:#legality check z=0 players=deepcopy(P1) number=deepcopy(N1) for x in players: if str(number[1]) in str(x[0]):self=x for w in range(0,3): if y[w] in '3': if int(number[2])<3:P=False;break else:z-=3;self[3]+=3;number[2]-=3 if y[w] in '2': if int(number[2])<2:P=False;break else:z-=2;self[3]+=2;number[2]-=2 if y[w] in '1': if int(number[2])<1:P=False;break else:z-=1;self[3]+=1;number[2]-=1 if y[w] in 'A': if int(self[3])<1:P=False;break else:z+=1;self[3]-=3;number[2]+=3 if y[w] in 'B': if int(self[3])<2:P=False;break else:z+=2;self[3]-=2;number[2]+=2 if y[w] in 'C': if int(self[3])<3:P=False;break else:z+=3;self[3]-=1;number[2]+=1 if y[w] in 'X': if int(self[3])<1:P=False;break else:self[3]-=1 if y[w] in 'Y': if int(self[3])<2:P=False;break else:self[3]-=2 if y[w] in 'Z': if int(self[3])<3:P=False;break else:self[3]-=3 if y[w] in 'F': if int(self[3])<1:P=False;break else:z+=2;self[3]-=1;self[2]+=1 if y[w] in 'U': if int(self[3])<1:P=False;break else:z-=2;self[3]+=1;self[2]-=1 if y[w] in 'R': self[2:4]=players[(players.index(self)+1)%len(players)][2:4] z+=int(self[3])*-1 z+=int(self[2])*2 if y[w] in 'T': self[2:4]=players[(players.index(self)-1)%len(players)][2:4] z+=int(self[3])*-1 z+=int(self[2])*2 if P: C.append(z);B.append((z,y)) c=list(set(C)) c.sort() c=c[::-1][1];D=[] for x in B: if c in x:D.append(x) print(D[randint(0,len(D)-1)][1]) ``` Edit: The code was printing a random legal move. It should now be returning the second best result. [Answer] # Devil's Bot Although its output is only half the devil's number, the results should be quite disastrous. Taking 9 coins each turn, it eventually exhausts the pile of coins. Since this bot never flips any of the coins it takes, it is extremely bad for anyone else sitting next to it when there is a rotation (-9 points for each turn taken by this bot). ``` print("333") ``` Command: `python3 devil.py` I hope to make some real bots later on. [Answer] ## Remember Me, Python 3 This program contains a significant amount of inbuilt data from a test against the fixed SecondBest bot. It *should* learn about what moves are the best to use, but it does not use other players' input. Edit: removed unnecessary point calculation Edit: uncommented player input ``` import sys file=sys.argv[0].split('\\')[::-1][0] from copy import deepcopy from random import randint In=str(sys.argv[1]) def V(n,f=10,t=14): n=str(n);z=0;s='';d='0123456789';d1='N123ABCXYZRTFU' for i in n:z=z*f+d.index(i) while z:z,m=divmod(z,t);s=d1[m]+s while len(s)<3:s='N'+s return s In=In.split(';') number=In[0:3] players=In[3:] for x in range(0,len(players)):players[x]=players[x].split('_') for x in players: if number[1] in x[0]:self=x for x in range(0,len(players)): for y in range(0,len(players[x])): players[x][y]=int(players[x][y]) for x in range(0,len(number)):number[x]=int(number[x]) Pos=list(map(V,range(0,14**3))) B=[] P1=deepcopy(players) N1=deepcopy(number) for x in range(len(Pos)): P=True y=Pos[x] if '1A'in y or '2B'in y or '3C'in y or 'FU'in y or 'A1'in y or 'B2'in y or 'C3'in y or 'UF'in y: P=False if P: players=deepcopy(P1) number=deepcopy(N1) for x in players: if str(number[1]) in str(x[0]):self=x for w in range(0,3): if y[w] in '3': if int(number[2])<3:P=False;break else:self[3]+=3;number[2]-=3 if y[w] in '2': if int(number[2])<2:P=False;break else:self[3]+=2;number[2]-=2 if y[w] in '1': if int(number[2])<1:P=False;break else:self[3]+=1;number[2]-=1 if y[w] in 'A': if int(self[3])<1:P=False;break else:self[3]-=3;number[2]+=3 if y[w] in 'B': if int(self[3])<2:P=False;break else:self[3]-=2;number[2]+=2 if y[w] in 'C': if int(self[3])<3:P=False;break else:self[3]-=1;number[2]+=1 if y[w] in 'X': if int(self[3])<1:P=False;break else:self[3]-=1 if y[w] in 'Y': if int(self[3])<2:P=False;break else:self[3]-=2 if y[w] in 'Z': if int(self[3])<3:P=False;break else:self[3]-=3 if y[w] in 'F': if int(self[3])<1:P=False;break else:self[3]-=1;self[2]+=1 if y[w] in 'U': if int(self[3])<1:P=False;break else:self[3]+=1;self[2]-=1 if y[w] in 'R': self[2:4]=players[(players.index(self)+1)%len(players)][2:4] if y[w] in 'T': self[2:4]=players[(players.index(self)-1)%len(players)][2:4] if P: B.append(y) Pos=list(B) B=[] # C=[['NNN',0],['NN1',-1],['NN2',-2],['NN3',-3],['NNR',-6],['NNT',-1],['N1N',-1],['N11',-2],['N12',-3],['N13',-4],['N1X',-1],['N1R',-7],['N1T',-2],['N1F',1],['N1U',-3],['N2N',-2],['N21',-3],['N22',-4],['N23',-5],['N2A',-1],['N2X',-2],['N2Y',-2],['N2R',-8],['N2T',-3],['N2F',0],['N2U',-4],['N3N',-3],['N31',-4],['N32',-5],['N33',-6],['N3A',-2],['N3B',-1],['N3X',-3],['N3Y',-3],['N3Z',-3],['N3R',-9],['N3T',-4],['N3F',-1],['N3U',-5],['NRN',-6],['NR1',-7],['NR2',-8],['NR3',-9],['NRA',-5],['NRB',-4],['NRC',-3],['NRX',-6],['NRY',-6],['NRZ',-6],['NRR',-12],['NRT',-7],['NRF',-4],['NRU',-8],['NTN',-1],['NT1',-2],['NT2',-3],['NT3',-4],['NTA',0],['NTX',-1],['NTR',-7],['NTT',-2],['NTF',1],['NTU',-3],['1NN',-1],['1N1',-2],['1N2',-3],['1N3',-4],['1NA',0],['1NX',-1],['1NR',-7],['1NT',-2],['1NF',1],['1NU',-3],['11N',-2],['111',-3],['112',-4],['113',-5],['11B',0],['11X',-2],['11Y',-2],['11R',-8],['11T',-3],['11F',0],['11U',-4],['12N',-3],['121',-4],['122',-5],['123',-6],['12A',-2],['12C',0],['12X',-3],['12Y',-3],['12Z',-3],['12R',-9],['12T',-4],['12F',-1],['12U',-5],['13N',-4],['131',-5],['132',-6],['133',-7],['13A',-3],['13B',-2],['13X',-4],['13Y',-4],['13Z',-4],['13R',-10],['13T',-5],['13F',-2],['13U',-6],['1XN',-1],['1X1',-2],['1X2',-3],['1X3',-4],['1XR',-7],['1XT',-2],['1RN',-7],['1R1',-8],['1R2',-9],['1R3',-10],['1RA',-6],['1RB',-5],['1RC',-4],['1RX',-7],['1RY',-7],['1RZ',-7],['1RR',-13],['1RT',-8],['1RF',-5],['1RU',-9],['1TN',-2],['1T1',-3],['1T2',-4],['1T3',-5],['1TA',-1],['1TX',-2],['1TR',-8],['1TT',-3],['1TF',0],['1TU',-4],['1FN',1],['1F1',0],['1F2',-1],['1F3',-2],['1FR',-5],['1FT',0],['1UN',-3],['1U1',-4],['1U2',-5],['1U3',-6],['1UA',-2],['1UB',-1],['1UX',-3],['1UY',-3],['1UR',-9],['1UT',-4],['1UU',-5],['2NN',-2],['2N1',-3],['2N2',-4],['2N3',-5],['2NA',-1],['2NB',0],['2NX',-2],['2NY',-2],['2NR',-8],['2NT',-3],['2NF',0],['2NU',-4],['21N',-3],['211',-4],['212',-5],['213',-6],['21B',-1],['21C',0],['21X',-3],['21Y',-3],['21Z',-3],['21R',-9],['21T',-4],['21F',-1],['21U',-5],['22N',-4],['221',-5],['222',-6],['223',-7],['22A',-3],['22C',-1],['22X',-4],['22Y',-4],['22Z',-4],['22R',-10],['22T',-5],['22F',-2],['22U',-6],['23N',-5],['231',-6],['232',-7],['233',-8],['23A',-4],['23B',-3],['23X',-5],['23Y',-5],['23Z',-5],['23R',-11],['23T',-6],['23F',-3],['23U',-7],['2AN',-1],['2A2',-3],['2A3',-4],['2AR',-7],['2AT',-2],['2XN',-2],['2X1',-3],['2X2',-4],['2X3',-5],['2XA',-1],['2XX',-2],['2XR',-8],['2XT',-3],['2XF',0],['2XU',-4],['2YN',-2],['2Y1',-3],['2Y2',-4],['2Y3',-5],['2YR',-8],['2YT',-3],['2RN',-8],['2R1',-9],['2R2',-10],['2R3',-11],['2RA',-7],['2RB',-6],['2RC',-5],['2RX',-8],['2RY',-8],['2RZ',-8],['2RR',-14],['2RT',-9],['2RF',-6],['2RU',-10],['2TN',-3],['2T1',-4],['2T2',-5],['2T3',-6],['2TA',-2],['2TX',-3],['2TR',-9],['2TT',-4],['2TF',-1],['2TU',-5],['2FN',0],['2F1',-1],['2F2',-2],['2F3',-3],['2FA',1],['2FX',0],['2FR',-6],['2FT',-1],['2FF',2],['2UN',-4],['2U1',-5],['2U2',-6],['2U3',-7],['2UA',-3],['2UB',-2],['2UC',-1],['2UX',-4],['2UY',-4],['2UZ',-4],['2UR',-10],['2UT',-5],['2UU',-6],['3NN',-3],['3N1',-4],['3N2',-5],['3N3',-6],['3NA',-2],['3NB',-1],['3NC',0],['3NX',-3],['3NY',-3],['3NZ',-3],['3NR',-9],['3NT',-4],['3NF',-1],['3NU',-5],['31N',-4],['311',-5],['312',-6],['313',-7],['31B',-2],['31C',-1],['31X',-4],['31Y',-4],['31Z',-4],['31R',-10],['31T',-5],['31F',-2],['31U',-6],['32N',-5],['321',-6],['322',-7],['323',-8],['32A',-4],['32C',-2],['32X',-5],['32Y',-5],['32Z',-5],['32R',-11],['32T',-6],['32F',-3],['32U',-7],['33N',-6],['331',-7],['332',-8],['333',-9],['33A',-5],['33B',-4],['33X',-6],['33Y',-6],['33Z',-6],['33R',-12],['33T',-7],['33F',-4],['33U',-8],['3AN',-2],['3A2',-4],['3A3',-5],['3AR',-8],['3AT',-3],['3BN',-1],['3B1',-2],['3B3',-4],['3BA',0],['3BX',-1],['3BR',-7],['3BT',-2],['3BF',1],['3BU',-3],['3XN',-3],['3X1',-4],['3X2',-5],['3X3',-6],['3XA',-2],['3XB',-1],['3XX',-3],['3XY',-3],['3XR',-9],['3XT',-4],['3XF',-1],['3XU',-5],['3YN',-3],['3Y1',-4],['3Y2',-5],['3Y3',-6],['3YA',-2],['3YX',-3],['3YR',-9],['3YT',-4],['3YF',-1],['3YU',-5],['3ZN',-3],['3Z1',-4],['3Z2',-5],['3Z3',-6],['3ZR',-9],['3ZT',-4],['3RN',-9],['3R1',-10],['3R2',-11],['3R3',-12],['3RA',-8],['3RB',-7],['3RC',-6],['3RX',-9],['3RY',-9],['3RZ',-9],['3RR',-15],['3RT',-10],['3RF',-7],['3RU',-11],['3TN',-4],['3T1',-5],['3T2',-6],['3T3',-7],['3TA',-3],['3TX',-4],['3TR',-10],['3TT',-5],['3TF',-2],['3TU',-6],['3FN',-1],['3F1',-2],['3F2',-3],['3F3',-4],['3FA',0],['3FB',1],['3FX',-1],['3FY',-1],['3FR',-7],['3FT',-2],['3FF',1],['3UN',-5],['3U1',-6],['3U2',-7],['3U3',-8],['3UA',-4],['3UB',-3],['3UC',-2],['3UX',-5],['3UY',-5],['3UZ',-5],['3UR',-11],['3UT',-6],['3UU',-7],['RNN',-6],['RN1',-7],['RN2',-8],['RN3',-9],['RNA',-5],['RNB',-4],['RNC',-3],['RNX',-6],['RNY',-6],['RNZ',-6],['RNR',-12],['RNT',-7],['RNF',-4],['RNU',-8],['R1N',-7],['R11',-8],['R12',-9],['R13',-10],['R1B',-5],['R1C',-4],['R1X',-7],['R1Y',-7],['R1Z',-7],['R1R',-13],['R1T',-8],['R1F',-5],['R1U',-9],['R2N',-8],['R21',-9],['R22',-10],['R23',-11],['R2A',-7],['R2C',-5],['R2X',-8],['R2Y',-8],['R2Z',-8],['R2R',-14],['R2T',-9],['R2F',-6],['R2U',-10],['R3N',-9],['R31',-10],['R32',-11],['R33',-12],['R3A',-8],['R3B',-7],['R3X',-9],['R3Y',-9],['R3Z',-9],['R3R',-15],['R3T',-10],['R3F',-7],['R3U',-11],['RAN',-5],['RA2',-7],['RA3',-8],['RAA',-4],['RAB',-3],['RAC',-2],['RAX',-5],['RAY',-5],['RAZ',-5],['RAR',-11],['RAT',-6],['RAF',-3],['RAU',-7],['RBN',-4],['RB1',-5],['RB3',-7],['RBA',-3],['RBB',-2],['RBC',-1],['RBX',-4],['RBY',-4],['RBZ',-4],['RBR',-10],['RBT',-5],['RBF',-2],['RBU',-6],['RCN',-3],['RC1',-4],['RC2',-5],['RCA',-2],['RCB',-1],['RCC',0],['RCX',-3],['RCY',-3],['RCZ',-3],['RCR',-9],['RCT',-4],['RCF',-1],['RCU',-5],['RXN',-6],['RX1',-7],['RX2',-8],['RX3',-9],['RXA',-5],['RXB',-4],['RXC',-3],['RXX',-6],['RXY',-6],['RXZ',-6],['RXR',-12],['RXT',-7],['RXF',-4],['RXU',-8],['RYN',-6],['RY1',-7],['RY2',-8],['RY3',-9],['RYA',-5],['RYB',-4],['RYC',-3],['RYX',-6],['RYY',-6],['RYZ',-6],['RYR',-12],['RYT',-7],['RYF',-4],['RYU',-8],['RZN',-6],['RZ1',-7],['RZ2',-8],['RZ3',-9],['RZA',-5],['RZB',-4],['RZC',-3],['RZX',-6],['RZY',-6],['RZZ',-6],['RZR',-12],['RZT',-7],['RZF',-4],['RZU',-8],['RRN',-12],['RR1',-13],['RR2',-14],['RR3',-15],['RRA',-11],['RRB',-10],['RRC',-9],['RRX',-12],['RRY',-12],['RRZ',-12],['RRR',-18],['RRT',-13],['RRF',-10],['RRU',-14],['RTN',-7],['RT1',-8],['RT2',-9],['RT3',-10],['RTA',-6],['RTX',-7],['RTR',-13],['RTT',-8],['RTF',-5],['RTU',-9],['RFN',-4],['RF1',-5],['RF2',-6],['RF3',-7],['RFA',-3],['RFB',-2],['RFC',-1],['RFX',-4],['RFY',-4],['RFZ',-4],['RFR',-10],['RFT',-5],['RFF',-2],['RUN',-8],['RU1',-9],['RU2',-10],['RU3',-11],['RUA',-7],['RUB',-6],['RUC',-5],['RUX',-8],['RUY',-8],['RUZ',-8],['RUR',-14],['RUT',-9],['RUU',-10],['TNN',-1],['TN1',-2],['TN2',-3],['TN3',-4],['TNA',0],['TNX',-1],['TNR',-7],['TNT',-2],['TNF',1],['TNU',-3],['T1N',-2],['T11',-3],['T12',-4],['T13',-5],['T1B',0],['T1X',-2],['T1Y',-2],['T1R',-8],['T1T',-3],['T1F',0],['T1U',-4],['T2N',-3],['T21',-4],['T22',-5],['T23',-6],['T2A',-2],['T2C',0],['T2X',-3],['T2Y',-3],['T2Z',-3],['T2R',-9],['T2T',-4],['T2F',-1],['T2U',-5],['T3N',-4],['T31',-5],['T32',-6],['T33',-7],['T3A',-3],['T3B',-2],['T3X',-4],['T3Y',-4],['T3Z',-4],['T3R',-10],['T3T',-5],['T3F',-2],['T3U',-6],['TAN',0],['TA2',-2],['TA3',-3],['TAR',-6],['TAT',-1],['TXN',-1],['TX1',-2],['TX2',-3],['TX3',-4],['TXR',-7],['TXT',-2],['TRN',-7],['TR1',-8],['TR2',-9],['TR3',-10],['TRA',-6],['TRB',-5],['TRC',-4],['TRX',-7],['TRY',-7],['TRZ',-7],['TRR',-13],['TRT',-8],['TRF',-5],['TRU',-9],['TTN',-2],['TT1',-3],['TT2',-4],['TT3',-5],['TTA',-1],['TTX',-2],['TTR',-8],['TTT',-3],['TTF',0],['TTU',-4],['TFN',1],['TF1',0],['TF2',-1],['TF3',-2],['TFR',-5],['TFT',0],['TUN',-3],['TU1',-4],['TU2',-5],['TU3',-6],['TUA',-2],['TUB',-1],['TUX',-3],['TUY',-3],['TUR',-9],['TUT',-4],['TUU',-5]] # points=0 # dpoints=self[1]-points z=0 for x in range(len(Pos)): y=Pos[x] z=0 for x in C: if x[0]==y:z=x[1] B.append((z,y)) B.sort() B=B[::-1] G=open(file,'r') H=G.read().split('#')[::-1] G.close() G=open(file,'w') H[3]=H[3].replace(H[3][8:-1],str(self[1])) J=eval(H[4][3:-1]) A=[B[0][1],dpoints] P=1 for x in range(0,len(J)): if J[x][0]==A[0]:J[x][1]+=A[1];P=0 if P:J.append(A) H[4]='\nC='+str(J)+'\n' s='' for x in H[::-1]:s+=x;s+='#' G.write(s[:-1]) G.close() print(B[0][1]) ``` ]
[Question] [ Write two programs, each taking a string `s` and a number `n` ≥ 0, such that: * The first program prints `s` `n` times, separated by newlines. * The second program prints each character of `s` `n` times, with repeated characters separated by newlines. * Every character at column `x`, line `y` in one program equals the character at column `y`, line `x` in the other program. Both programs must contain at least two lines. You may take input in any reasonable order or format that works for both programs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the less bytes, the better. Count bytes from your longer program (that is, the one with more lines than columns). --- Here's an example in a hypothetical programming language, with `s` = `"Hello, world!"` and `n` = `3`: ### Program A ``` a(b*c defg h.ij) ``` ### Output ``` Hello, world! Hello, world! Hello, world! ``` ### Program B ``` adh (e. bfi *gj c ) ``` ### Output ``` HHH eee lll lll ooo ,,, www ooo rrr lll ddd !!! ``` [Answer] # C, 196 bytes **Regular version: 190 bytes** ``` p;f(char *s,n) { ; while( p++< n) puts(s);p; } /* f*******u*0**;* / (///////t/)//}+* c*)dfppnc(;p(w+/ hs{oo=+;h* u"hs} a, {r0+)a /t"i)/ rn (;< r *s l;* /////// / / e/ ******* * * (*/ ``` **Mirrored version: 196 bytes** ``` p;pf(char/* ; u*/*s,n/* fwt*/){ /* (hs*/do{ /* ci(*/for(/* hls*/p=0;/* ae)*/p++</* r(;*/n;) putchar/* *p;+*/(* s+ 0); /* ,+}*/puts/* n< */("" ) ;}while( *++s);/* {n/ */}/* / )*/ ``` **Readable regular version:** ``` p; f(char* s, n) { ; while (p++ < n) puts(s); p; } ``` **Readable mirrored version:** ``` p; pf(char* s, n) { do { for (p = 0; p++ < n; ) putchar (*s + 0); puts(""); } while (*++s); } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes Inputs are `s`, then `n`. **Normal version** (10 bytes): ``` 1!X" XDD " ``` [Try it online!](https://tio.run/##y00syfn/31AxQokrwsWFS@n/f3WP1JycfB2F8vyinBRFdS5jAA) **Mirrored version** (11 bytes): ``` 1X" !D XD " ``` [Try it online!](https://tio.run/##y00syfn/3zBCiUvRhSvChUvp/391j9ScnHwdhfL8opwURXUuYwA) ### Explanation The **normal version** is parsed as ``` 1 % Push 1 ! % Transpose: does nothing to the 1 X" % Implicit inputs: n, s. Repeat s n times vertcally and 1 time horizontally XD % Display the full stack contents. This prints the output D % Display. Triggers implicit input, which is not present, and so errors " % For each. This statement is not reached ``` The **mirrored version** is parsed as ``` 1 % Push 1 X" % Implicit inputs: n, s. Repeat s n times vertcally and 1 time horizontally ! % Transpose. This transforms the above into the desired output D % Display. This prints the output XD % Display all stack contents. The stack is empty, so this does nothing " % For each. Triggers implicit input, which is not present, and so errors ``` [Answer] # perl, 102 bytes ``` $_=<>;$n=<>;print$_ x$n __END__ =E <N >D ;_ $_ ; = < > ; s / . / $ & x $ ; . " \ n " / g e ; p r i n t ``` [Try it online!](https://tio.run/##FYi7CoNAFAX7@QqRS8rYaLWPSlu/QLhEMEEI67Ja@Pebm@LMYSZv5TvUKhp8dJL@zGVPl2hzS0J1mkdVwoSfiSNOEcUR8ET7k46nTXhwG51Zy0IydnzYrGQKu5Wr1vdxNOur0P8A "Perl 5 – Try It Online") ``` $_=<>;$;=<>;s/./$&x$;."\n"/ge;print __END__ =E <N >D ;_ $_ n = < > ; p r i n t $ _ x $ n ``` [Try it online!](https://tio.run/##FcexCoMwFEDR/X6FyMPRLHZ6SSZd/QLh0YIVocSQOvj3qV3u4ea1fB61igUfVfTfr@uddJdo3y6pdduquezpxGyaRzPChJ@JI2qIkQh4IkqmsN9/IhgN122q9X0czetZGH4 "Perl 5 – Try It Online") The programs are fairly trivial, they just do what is required without any trickery. The only trickery is the `__END__`; this tells perl to ignore anything what is following. That way, hardly anything is shared between the two programs, only the first two bytes are: `$_`, where the `_` is either the name of the variable, or the first character of the `__END__` token. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ENη¿⁰« N η ‖ ↙ ¿ ⁰ « ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nqXv96w7t/3Q/keNGw6t5gJyuM5t53rUMI3rUdtMrkP7uYDiXIdW//9vzOWRmpOTr6NQnl@Uk6L4XzcRAA "Charcoal – Try It Online") Explanation: ``` ENη ``` Convert the input number to an implicit range, map each entry to the input string, and print the result. ``` ¿⁰ ``` Execute the rest of the program only if `0` is true (which it isn't). ``` « ``` Wrap the rest of the program in a block, so it doesn't matter what its meaning is, since it never gets executed. Reflected: ``` ENη‖↙¿⁰« N η ¿ ⁰ « ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nqXv96w7t/1Rw7RHbTMP7X/UuOHQai6gENe57VyH9nMB@VyHVv//b8zlkZqTk6@jUJ5flJOi@F83EQA "Charcoal – Try It Online") Explanation: Much like the other program, except that the `‖↙` reflects the output as desired. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 6 bytes -1 byte thanks to @dingledooper. ``` иø » q ``` [Try it online!](https://tio.run/##MzBNTDJM/f//wo5Duwu5Du/4/9@YyyM1JydfR6E8vygnRREA "05AB1E (legacy) – Try It Online") ## Explanation (Horizontal) ``` и Sequence product. ø Transpose this product. » Join the product by newlines. q Exit the program. ``` ## Explanation (transposed) ``` и Sequence product. » Join the product by newlines. q Exit the program. A garbage dump the interpreter ignores: ø ``` ``` [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes **First program: 94 bytes** ``` sfp,n=input();"\ ,or";s=sfp+"\n" print s*n; """ = n ict n pic un* t p (s; ):" #"" """ 1; #\ ``` [Try it online!](https://tio.run/##FcoxDoMwEATAfl9xWhogbohS5eSfuENBWELnEzZFXu@QdjT@bXuxZ@9182Axm19tnJQJoZzUGm9/MBnhZ7YmdTYVIYkohrw2mAg8r7hsRhPHWBXTmxju83@LYki9c/8cR2GQ1w8 "Python 2 – Try It Online") **Second program: 95 bytes** ``` s,p=input()#"1# for c in s:"";\ print c*p;""" ,"n n;t =s i=s ns* pfn up; t+ (" )\" ;n" """ \ ``` [Try it online!](https://tio.run/##FcoxDoMwEATAfl9xWhogbkCpYvkn7lAQltD5hI8ir3fE1GM/P6quvbdgqajdPk4DlwF7vWSTotI@ZMywq6jLNlskiUCFRkdqgpIatM2wXXFbhL8EIwVTJqISz8@98/ieZ2WQ9x8 "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-pF`, 51 bytes I feel I can condense this more so I'll likely tinker with it to try and make it more square... ``` $_=$_ x<>;' ; f =xo <$r >;@ ;.F $$; \/} .|{ =| $$' ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYlXqHCxs5anctaIY3LtiKfy0aliMvO2oHLWs@NS0XFmitGv5ZLr6aay7ZGAchX///fIzUnJ19HITy/KCdFkcv4X35BSWZ@XvF/3QI3AA "Perl 5 – Try It Online") ### Explanation Basically this just runs `$_=$_ x <>` which, since `-p` flag is used, will just print out the string triplicated. The rest of the string is avoid by being inside a single quote. ``` $;=<>;$\.=$ _ x$;.$/||$ =for@F;}{' $ _ x < > ; ' ``` [Try it online!](https://tio.run/##K0gtyjH9/1/F2tbGzlolRs9WhSteoULFWk9Fv6ZGhcs2Lb/Iwc26tlqdCyjBpcBVwWXDZcdlzaX@/79Hak5Ovo5CeH5RTooil/G//IKSzPy84v@6BW4A "Perl 5 – Try It Online") ### Explanation This takes `n` from STDIN (`<>`) and stores in `$;`, next the magic variable `$\` (which is automatically output as the final argument to any call to `print`) is appended to with `$;` copies of `$_`. `$_` is set to each letter of the input during the `for@F`. We need to also close the implicit `while (<STDIN>)` loop (that is added via `-p`) with `}{` so that the global `$_` is empty and when `print` is called, only `$\` is output. [Answer] # Mathematica, 114 bytes Mathematica, with it's long, unsplittable names means that no matter how short I make this, it'll still have obtuse names, the alternative of using <> and #&/@ would be shorter for either individual program, but dealing with them in the transposition makes the program longer overall. ``` StringRiffle[ t;Table[##],1* rT;"\n"]&(* ) ia nb gl Re i[ f# f# l] e] [ C, h" a\ rn a" c, t" e" r] s& [( 1* *) ``` **Normal** ``` StringRiffle[Characters[1* t;Table[##]],"\n",""]&(*) rT; ia" nb\ gln Re" i[] f#& f#( l]* e, [1 *) ``` **Transposed** ### Base programs: Normal: StringRiffle[Table[##],"\n"]& Transposed: StringRiffle[Characters[Table[##]],"\n",""]& [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Unfortunately, for this challenge, the execution of a Jelly program starts with the bottom line of code, so there's quite a bit of work required to get a solution under about 25 bytes! ``` W ñ ẋY Z ñ ``` **[Try it online!](https://tio.run/##y0rNyan8/z9c4fBGroe7uiO5orgOb/z//78HUDxfR6E8vygnRfG/MQA "Jelly – Try It Online")** ``` WẋZñ Y ñ ``` **[Transposed](https://tio.run/##y0rNyan8/z/84a7uqMMbuRQiuQ5v/P//vwdQOF9HoTy/KCdF8b8xAA "Jelly – Try It Online")** ### How? Normal: ``` W ñ - Link 1: s, n W - wrap (s) in a list ñ - call the next Link (2) as a dyad - f(that, n) ẋY - Link 2: wrapped s, n ẋ - repeat (s) (n) times Y - join with newlines Z - Link 3 (unused) ñ - Main Link: s, n ñ - call the next Link (1) as a dyad - f(s, n) - implicit (smashing) print ``` Transposed: ``` WẋZñ - Link 1: s, n W - wrap (s) in a list ẋ - repeat (that) (n) times Z - transpose ñ - call the next Link (2) as a dyad - f(that, n) Y - Link 2: transposed, repeated [s] Y - join with newlines ñ - Main Link: s, n ñ - call the next Link (1) as a dyad - f(s, n) - implicit (smashing) print ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 bytes ``` ] *M m ``` [Run and debug it](https://staxlang.xyz/#c=]%0A*M%0Am&i=8+%22hello%22&a=1&m=2) **Mirrored:** ``` ]*m M ``` [Run and debug it](https://staxlang.xyz/#c=]*m%0A+M&i=8+%22hello%22&a=1&m=2) ]
[Question] [ The [infinite Fibonacci word](https://en.wikipedia.org/wiki/Fibonacci_word) is a specific, infinite sequence of binary digits, which are calculated by repeated concatenation of finite binary words. Let us define that a *Fibonacci-type word sequence* (or *FTW sequence*) is any sequence **⟨Wn⟩** that is formed as follows. * Commence with two arbitrary arrays of binary digits. Let us call these arrays **W-1** and **W0**. * For each **n > 0**, let **Wn ≔ Wn-1 ∥ Wn-2**, where **∥** denotes concatenation. A consequence of the recursive definition is that **Wn** is always a prefix of **Wn+1** and, therefore, of all **Wk** such that **k > n**. In a sense, this means the sequence **⟨Wn⟩** converges to an infinite word. Formally, let **W∞** be the only infinite array such that **Wn** is a prefix of **W∞** for all **n ≥ 0**. We'll call any infinite word formed by the above process an *infinite FTW*. ### Task Write a program or function that accepts two binary words **W-1** and **W0** as input and prints **W∞**, abiding by the following, additional, rules: * You may accept the words in any order; as two arrays, an array of arrays, two strings, an array of strings, or a single string with a delimiter of your choice. * You may print the digits of the infinite word either without a delimiter or with a consistent delimiter between each pair of adjacent digits. * For all purposes, assume that your code will never run out of memory, and that its data types do not overflow. In particular, this means that any output to STDOUT or STDERR that is the result of a crash will be ignored. * If I run your code on my machine (Intel i7-3770, 16 GiB RAM, Fedora 21) for one minute and pipe its output to `wc -c`, it must print at least one million digits of **W∞** for **(W-1, W0) = (1, 0)**. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ### Example Let **W-1 = 1** and **W0 = 0**. Then **W1 = 01**, **W2 = 010**, **W3 = 01001**, **W4 = 01001010** … and **W∞ = 010010100100101001010…**. This is *the* infinite Fibonacci word. ### Test cases All test cases contain the first 1,000 digits of the infinite FTW. ``` Input: 1 0 Output: 0100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001 Input: 0 01 Output: 0100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001 Input: 11 000 Output: 0001100000011000110000001100000011000110000001100011000000110000001100011000000110000001100011000000110001100000011000000110001100000011000110000001100000011000110000001100000011000110000001100011000000110000001100011000000110000001100011000000110001100000011000000110001100000011000110000001100000011000110000001100000011000110000001100011000000110000001100011000000110001100000011000000110001100000011000000110001100000011000110000001100000011000110000001100000011000110000001100011000000110000001100011000000110001100000011000000110001100000011000000110001100000011000110000001100000011000110000001100000011000110000001100011000000110000001100011000000110001100000011000000110001100000011000000110001100000011000110000001100000011000110000001100011000000110000001100011000000110000001100011000000110001100000011000000110001100000011000000110001100000011000110000001100000011000110000001100011000000110000001100011000000110000001100011000000110001100000011000000110001100000011000110000001100000011 Input: 10 010 Output: 0101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010 Input: 101 110 Output: 1101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101 ``` [Answer] ## Haskell, 15 bytes ``` v%w=w++w%(v++w) ``` The infix function `%` produces an infinite string, which Haskell prints forever because Haskell is cool like that. ``` >> "1"%"0" "010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101 ``` The recursive idea is similar to [Zgarb's solution](https://codegolf.stackexchange.com/a/63131/20260). Writing `f` for the function `%`, and `+` for string concatenation, it implements: ``` f(v,w) = w + f(w,v+w) ``` The infinite output string starts with `w`, and the remainder of it is the result for the Fibonacci-shifted strings `w` and `v+w`. This has no problem generating a million characters in a minute. [Answer] # Pyth, 8 bytes ``` u,peGsGQ ``` Input in the form `"W-1", "W0"`. Proof of completion: ``` $ time pyth -cd 'u,peGsGQ' <<< '"1", "0"' 2>/dev/null | head -c1000000 > /dev/null real 0m0.177s user 0m0.140s sys 0m0.038s ``` --- Proof of correctness: Here is the series as internally generated. It is printed in concatenation by the program. ``` [0, 10, 010, 10010, 01010010, 1001001010010,...] ``` Compare to the following, printed in concatenation, which is simply the string added to the previous string on each step: ``` [0, 1, 0, 01, 010, 01001, 01001010, 0100101001001, ...] ``` We want to prove these are equivalent. Clearly, they are the same through the first few steps. Let's compare them after a bit: ``` 010 010 10010 01001 01010010 01001010 1001001010010 0100101001001 ``` We see that the pairs of strings are alternately of the forms: ``` 01a 10b a10 b01 ``` Where a and b are arbitrary sequences on 0s and 1s. Let's continue the sequence for a bit, to prove is continues forever by induction: ``` 01a 10b 10b01a 10b01a10b a10 b01 a10b01 b01a10b01 ``` 2 steps later, it is of the correct form. ``` 10b 01a 01a10b 01a10b01a b01 a10 b01a10 a10b01a10 ``` 2 steps later, it is of the correct form. So by induction, the strings always match once concatenated. [Answer] ## Haskell, 31 bytes ``` w#v=v++drop(length v)(v#(v++w)) ``` This defines an infix function `#` that takes two strings and returns an infinite string. Usage: ``` > let w#v=v++drop(length v)(v#(v++w)) in "11"#"000" "000110000001100011000000110000... ``` If I query the millionth element of the sequence defined by "1" and "0", even the [online interpreter](http://tryhaskell.org/) prints the result in less than a second: ``` > let w#v=v++drop(length v)(v#(v++w)) in ("1"#"0") !! 1000000 '0' ``` ## Explanation ``` w#v= -- The result of w#v is v++ -- v concatenated to v#(v++w) -- the infinite word v#(v++w), drop(length v) -- with the first v characters dropped. ``` Basically, we know that `w#v == v#(v++w)` and `w#v` begins with `v`, and use these facts to define the result. Since Haskell is lazy, this "magically" just works. [Answer] ## CJam, ~~12~~ 11 bytes ``` llL{@_o+_}h ``` This takes the two words on separate lines, in the opposite order, e.g. ``` 0 1 ``` gives ``` 0100101001001010010100100101001... ``` ### Explanation The idea is to build up the word naively (by remembering the current word and appending the previous one to it) and while we're doing that, we print whatever we just appended (in order not to repeat the prefix that was already printed). To avoid having to handle the starting point separately, we start from an empty word, such that W0 is the first thing we append (and print). ``` ll e# Read the two lines separately. L e# Push an empty string. { e# Infinite loop... @ e# Pull up the previous FTW. _o e# Print it. +_ e# Append it to the current FTW and duplicate it. }h ``` [Answer] # Pip, 8 bytes Hey, tied with Pyth! ``` (fOba.b) ``` Straightforward recursive definition borrowed from [xnor's Haskell answer](https://codegolf.stackexchange.com/a/63169/16766). With spaces added for clarity: ``` (f Ob a.b) ``` Every program in Pip is an implicit function that takes the command-line args as its arguments (assigned to variables `a` through `e`) and prints its return value. `O` is an operator that outputs and then returns its operand, so the first thing that happens here is the second argument is displayed (sans trailing newline). Now, the Lisp-inspired syntax `(f x y)` in Pip is a function call, equivalent to `f(x,y)` in C-like languages. The `f` variable refers to the current function--in this case, the top-level program. Thus, the program recursively calls itself with `b` and `a.b` as the new arguments. I was pleasantly surprised to find that this approach is plenty fast: ``` dlosc@dlosc:~$ time pip -e '(fOba.b)' 1 0 2>/dev/null | head -c1000000 > /dev/null real 0m0.217s user 0m0.189s sys 0m0.028s ``` It takes about 30 seconds on my Ubuntu machine for the program to hit the max recursion depth, at which point it has printed out somewhere over a billion digits. This iterative solution is slightly faster and hogs less memory, at the cost of one byte: ``` W1Sba.:Ob ``` [Answer] # APL, ~~24~~ 18 ``` {(,/⌽⍵),⊂⍞←↑⍵}⍣≡⍞⍞ ``` Using [xnor's formulation](https://codegolf.stackexchange.com/a/63169/46915) allowed to shave off few characters. ``` ⍞ ⍝ Read W₋₁ as a character string. ⍞ ⍝ Read W₀. { }⍣≡ ⍝ Apply the following function repeatedly until fixpoint: ⍝ It takes a pair of strings (A B), ⍞←↑⍵ ⍝ prints A (,/⌽⍵),⊂ ↑⍵ ⍝ and returns (BA A). ``` On an infinite machine in infinite time it would actually print W∞ thrice—first incrementally while running the loop, and then twice as a result of the whole expression when the `⍣≡` fixpoint operator finally returns. It's not very fast but fast enough. In GNU APL: ``` $ printf '%s\n' '{(,/⌽⍵),⊂⍞←↑⍵}⍣≡⍞⍞' 1 0 | apl -s | head -c 100 0100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010$ $ time printf '%s\n' '{(,/⌽⍵),⊂⍞←↑⍵}⍣≡⍞⍞' 1 0 | apl -s | head -c 1000000 >/dev/null 0m3.37s real 0m2.29s user 0m1.98s system ``` [Answer] ## PowerShell, ~~97~~ 76 Bytes ``` param($a,$b)write-host -n $b;while(1){write-host -n $a;$e=$b+$a;$a=$b;$b=$e} ``` Edit - Umm, writing out `$e.substring($b.length)` after we just concatenated `$a` and `$b` together is equivalent to writing out just `$a` ... derp. Wow, verbose. PowerShell will, by default, spit out a newline every time you output something. Really the only way to get around that is with `write-host -n` (short for `-NoNewLine`), and that absolutely kills the length here. Essentially, this iterates through the sequence, building `$e` as the "current" Wn as we go. However, since we're wanting to build the infinite word instead of the sequence, we leverage our previous variables to print out the suffix `$a` that was populated in our previous loop. Then we setup our variables for the next go-round and repeat the loop. Do note that this expects the input to be explicitly delimited as strings, else the `+` operator gets used for arithmetic instead of concatenation. ### Example: ``` PS C:\Tools\Scripts\golfing> .\infinite-ftw.ps1 "111" "000" 0001110000001110001110000001110000001110001110000001110001110000001110000001110001110000001110000001110001110000001110001110000001110000001110001110000001110001110000001110000001110001110000001110000001110001110000001110001110000001110000001110001110000001110000 ... ``` [Answer] # Pure bash, 58 ``` a=$1 b=$2 printf $b for((;;)){ printf $a t=$b b+=$a a=$t } ``` I run out of memory before 1 minute, but have plenty of digits by then - after 10 seconds I have 100 million digits: ``` $ ./ftw.sh 1 0 | head -c100 0100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010ubuntu@ubuntu:~$ $ { ./ftw.sh 1 0 & sleep 10 ; kill $! ; } | wc -c 102334155 $ ``` [Answer] # Mathematica, 56 bytes ``` $IterationLimit=∞;#0[$Output~WriteString~#2;#2,#<>#2]& ``` [Answer] # Dyalog APL, 9 ``` {⍵∇⍺,⍞←⍵} ``` This one uses `∇` to define a recursive function. It's a direct translation of [this xnor's Python 3 answer](https://codegolf.stackexchange.com/questions/63127/an-infinite-ftw/63171#63171). It takes W0 as right, and W−1 as its left argument, both should be character vectors. [Answer] # C, 76 (gcc) ``` main(c,v)char**v;{int p(n){n>2?p(n-1),p(n-2):puts(v[n]);}for(p(4);;p(c++));} ``` This is a fairly straightforward recursive printer, implemented as a nested function (a GNU C extension not supported by clang) to avoid having to pass `v` around. `p(n)` prints **Wn-2**, where **W-1** and **W0** must be provided in `v[1]` and `v[2]`. This initially calls `p(4)` to print **W2**. It then loops: it calls `p(3)` to print **W1**, making the complete output **W2W1**, which is **W3**. It then calls `p(4)` to print **W2**, making the complete output **W4**, etc. Performance is slightly better than my earlier answer: I'm seeing 1875034112 values in a minute. --- # C, 81 (clang) This is a completely different approach from the above that I feel is worth keeping up, even though it scores worse. ``` s[],*p=s;main(c,v)char**v;{for(++v;;)for(puts(v[*++p=*++p!=1]);*p+1==*--p;++*p);} ``` This has all kinds of undefined behaviour, mainly for fun. It works with clang 3.6.2 on Linux and with clang 3.5.2 on Cygwin for the test cases in the question, with or without special command-line options. It doesn't break when optimisations are enabled. It doesn't work with other compilers. > > You may accept the words in any order; as two arrays, an array of arrays, two strings, an array of strings, or a single string with a delimiter of your choice. > > > I accept the words as command-line arguments in string format. > > You may print the digits of the infinite word either without a delimiter or with a consistent delimiter between each pair of adjacent digits. > > > I use newline as the consistent delimiter. > > For all purposes, assume that your code will never run out of memory, and that its data types do not overflow. > > > In particular, this means that any output to STDOUT or STDERR that is the result of a crash will be ignored. > > > I access `s` out of bounds. This must surely end with a segfault or an access violation at some point. `s` happens to get placed at the end of the data segment, so it shouldn't clobber other variables and give wrong output before that segfault. Hopefully. > > If I run your code on my machine (Intel i7-3770, 16 GiB RAM, Fedora 21) for one minute and pipe its output to `wc -c`, it must print at least one million digits of **W∞** for **(W-1, W0) = (1, 0)**. > > > Testing using `{ ./program 1 0 | tr -d '\n' & sleep 60; kill $!; } | wc -c`, I get 1816784896 digits in one minute on my machine when the program was compiled with `-O3`, and 1596678144 when it was compiled with optimisations diabled. --- [Answer] # Javascript (53 bytes) ``` (a,c)=>{for(;;process.stdout.write(a))b=a,a=c,c=b+a;} ``` Input should be string and not number (`'0'` and not just `0`). [Answer] ## Perl 5, ~~45~~ ~~55~~ 49 bytes 44 bytes, plus 1 for `-E` instead of `-e` ``` sub{$i=1;{say$_[++$i]=$_[$i].$_[$i-1];redo}} ``` Use as e.g. ``` perl -E'sub{$i=1;{say$_[++$i]=$_[$i].$_[$i-1];redo}}->(1,0)' ``` This prints successive approximations to W∞ and thus, if you wait long enough, prints, on its last line of output, W∞ to any desired length, as required. The digits of the word are concatenated without a delimiter. Since I'm on Windows, I tested it for the "at least one million digits of W∞" requirement by running it with output redirected to a file and killing it after about 59 seconds, then running GnuWin32's `wc -L`, which printed 701408733. --- ## Update: The OP clarified in a comment on this answer (and probably I should have realized anyway) that the extra output preceding W∞ disqualifies the above. So instead here's a 55-byte solution that prints *only* W∞: ``` sub{print$_[0];{print$_[1];unshift@_,$_[0].$_[1];redo}} ``` Used the same way, but *with the arguments in reverse order*, and doesn't require `-E`: ``` perl -e'sub{print$_[0];{print$_[1];unshift@_,$_[0].$_[1];redo}}->(0,1)' ``` Doubtless it can be golfed further, but I don't see how to do so right now. --- ## Further update: [Dennis](/u/12012) shaved five bytes by using `-a` (thus reading `<>` to remove `sub`) and reassigning the parameter passed to `print` at the end of the `redo` block: With `-ane` and reading from `<>` (both inputs on one line, space-separated, in reverse order); 48 + 2 bytes: ``` $_=$F[0];{print;unshift@F,$F[0].($_=$F[1]);redo} ``` And, based on that, I shaved one more byte (same as above, but now the inputs are in the correct order); 47+2 bytes: ``` $_=$F[1];{print;push@F,$F[-1].($_=$F[-2]);redo} ``` [Answer] ## [REXX](https://en.wikipedia.org/wiki/Rexx), 48 ``` arg a b do forever b=a||b say b a=b||a say a end ``` *ftw.rex* exec ftw.rex 0 1 Currently can't test performance because I used an online compiler to write it. The "forever" can be replaced with any number where as the printed ftw numbers are (number + 2). I also wrote a small (messy) solution in Prolog. Didn't figure how to test performance with this one but its probably atrocious anyway. ``` f(A,B,C):-atom_concat(B,A,D),(C=D;f(B,D,C)). :- C='0';C='1';(f(1,0,C)). ``` [Answer] ## Python 2, 67 bytes ``` a,b=input() print'\n'.join(b+a) while 1:a,b=b,b+a;print'\n'.join(a) ``` Accepts input as a comma-separated pair of strings: `"1","0"`, for the example in the question. No online interpreter because infinite loops are bad. ~~Buffered output made me gain a lot of bytes. :(~~ Thanks Dennis for pointing out that 1 digit per line is valid. Timing on my (significantly-weaker) machine: ``` $ time python golf.py <<< '"1","0"' 2>/dev/null | head -c2000000 > /dev/null real 0m1.348s user 0m0.031s sys 0m0.108s ``` [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 62 bytes ``` (od" "=,6&xI0G2@dO$I)I1-0G($d2[I2:g]Xx0c2*1c-0g0g-d[icO]0G0G1) ``` [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=%28od%22+%22%3D%2C6%26xI0G2%40dO%24I%29I1-0G%28%24d2%5BI2%3Ag%5DXx0c2%2A1c-0g0g-d%5BicO%5D0G0G1%29&input=110+101) Expects input in the order **W0**, **W-1** with a space in between. ### Explanation ``` ( Open while loop (for input-reading) od Read in character from input and duplicate " "=, 0 if equal to " ", 1 otherwise 6& Jump 6 characters if this is non-zero xI0G2@ Dump, push length of stack, move to front, and jump next two dO Duplicate and output as character if 1 $I) Close while loop when input is empty I1-0G Push length of stack - 1 and move it to the front ``` Meta-explanation for the following is that at this point in time, we have two numbers followed by a string of "0"s and "1"s with no separation. If the lengths of **W0** and **W-1** are `a` and `b`, respectively, then the two numbers at the front of the stack are `<a+b>` and `<a>`, in that order. The word formed by concatenating **Wi+1** and **Wi**, i.e. **Wi+1** + **Wi**, is equal to 2 \* **Wi+1** - **Wi**. So the following code duplicates the stack (2 \* **Wi+1**), pops off the top `<a>` elements (- **Wi**), and then replaces `<a+b>` and `<a>` with their successors, `<a+2b>` and `<b>`. ``` ( Open while loop (for calculation and output) $d Duplicate the whole stack 2[I2:g] Pull <a+b> and <a> from the middle of the stack Xx Dump the top <a> elements (and <a+b>) 0c2*1c- Get <a+b> and <a>, then calculate 2*<a+b> - <a> = <a+2b> = <a+b> + <b> 0g0g- Get <a+b> and <a>, then subtract d[icO] Output as character the first <b> elements 0G0G Move both to front 1) Infinite loop (basically, "while 1:") ``` [Answer] ## Python 3, 32 ``` def f(a,b):print(end=b);f(b,a+b) ``` The same recursive idea as my [Haskell answer](https://codegolf.stackexchange.com/a/63169/20260), except the prefix is printed because Python can't handle infinite strings. Used a trick from Sp3000 to print without spaces by putting the string as the `end` argument in Python 3 [Answer] # Perl, 32 bytes ``` #!perl -pa $#F=3}for(@F){push@F,$F[-1].$_ ``` Counting the shebang as two, input is taken from stdin, space separated as *W0*, *W-1*. Output for 1MB times at ~15ms, most of which can be attributed to interpreter launch. --- **Sample Usage** ``` $ echo 0 1 | perl inf-ftw.pl 0100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001001010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001001010010100100101001001010010100100101001010010010100100101001010010010100100101001010010010100101001001010010010100101001001010010100100101001001... $ echo 110 101 | perl inf-ftw.pl 1101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101101011101011101101011101101011101011101101011101011101101011101... ``` [Answer] # Prolog, 69 bytes ``` q(A,B):-atom_concat(B,A,S),write(A),q(B,S). p(A,B):-write(B),q(A,B). ``` **Example input:** p('1','0') Haven't found a way to remove the extra write. Should be able to improve on this if I figure out how to do that. [Answer] # [J](http://jsoftware.com/), 22 bytes including 6 for input chars similar to Dyalog APL solution ``` '1'((]stdout@])$:,)'0' ``` [Try it online!](https://tio.run/##y/rv56Sn4JaZlJ@XmJycqRCeX5SikFFSUlBspa@fnJ@Smp6fk6ZXXJKYnJ1akZyRmJeeqpecn6tfWJpaXJKZn1esb2ZsaGSun5inm5mXlpmXWZKqm1ZS/l/dUF1DI7a4JCW/tMQhVlPFSkdT3UAdbJkCGKHQhAWROVwgUwwMDYAITMBoFA6GoJ6e3n8A "J – Try It Online") ]
[Question] [ This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will give you an integer `n`, and ask you to count the number of positive integer sequences \$S = (a\_1, a\_2, \dots, a\_t)\$ such that 1. \$a\_1 + a\_2 + \cdots + a\_t = n\$, and 2. \$\displaystyle \sqrt{a\_1+\sqrt{a\_2 + \cdots + \stackrel{\vdots}{\sqrt{a\_t}}}} \$ is an integer. ### Example If `n = 14`, then there are 8 such sequences: * \$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{3+\sqrt{1}}}}}}} = 2\$ * \$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{4}}}}}} = 2\$ * \$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{3+\sqrt{1}}}}} = 2\$ * \$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{3+\sqrt{1}}}}} = 2\$ * \$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{8+\sqrt{1}}}}} = 2\$ * \$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{4}}}} = 2\$ * \$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{4}}}} = 2\$ * \$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{9}}}} = 2\$ (In this example, all of the nested square root expressions are equal to 2, but in general, this may not be the case.) Pairs \$(n,(a(n))\$ for \$n \leq 25\$: ``` (1,1),(2,0),(3,0),(4,2),(5,0),(6,2),(7,0),(8,2),(9,2),(10,4),(11,2),(12,6),(13,2),(14,8),(15,4),(16,14),(17,6),(18,20),(19,8),(20,28),(21,14),(22,44),(23,20),(24,66),(25,30) ``` --- Your code must be robust against floating-point errors, that is it must work for arbitrarily large inputs, in principle. Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the shortest code wins. --- (This is now on the On-Line Encyclopedia of Integer Sequences as [A338271](https://oeis.org/A338271). Sequence [A338268](https://oeis.org/A338268) has been added too, based on [Bubbler's \$f\$ function](https://codegolf.stackexchange.com/a/213851/53884).) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 [bytes](https://github.com/abrudz/SBCS) ``` +/⊢{∨/⍺⍵<⍵0:0⋄⍺=0:1⋄+/∊∇¨/⍺(⍵*2)-⊂⍳⍺}¨⍳ ``` [Try it online!](https://tio.run/##JYy/DgFBEIf7e5I7RuzO7p0/odLQ4gUkchoJrYgG4XJyQuEFVDqFaJT3KPMiZ3a22N/vm803M1svG/PNbLlaVFW9SflzS9mrScWPim@Pn@oquhx57quuZmInyyk7lyKFbNQwalC@p@LDH7vyxVCldLpRcaX8UL4Nne50fUzGA87pcDSpUpEwDoJolaZBqEFHECIoTiNpATlj4US4JdwW7khqBdaV9hNC4sr4yULbVeyVBLR0yzt8xR3THZFQAUprbyGClTZeQwuJW8MYjIr@ "APL (Dyalog Unicode) – Try It Online") A tacit function containing an inner dfn to use recursion. Does not use floating point numbers at all. ### How it works First of all, observe that $$ \displaystyle \sqrt{a\_1+\sqrt{a\_2 + \cdots + \stackrel{\vdots}{\sqrt{a\_t}}}} \le \cdots \le \sqrt{a\_1+a\_2 + \cdots + a\_t} \le a\_1+a\_2 + \cdots + a\_t = n $$ and this holds for all suffixes of any given sequence of positive integers. Let's define a function \$f(x,y)\$ as the number of sequences where the sum is \$x\$ and the "root sum" is \$y\$. Then the following holds: $$ \begin{align} f(0, 0) &= 1 \\ f(0, y) &= 0, \qquad 0 < y \\ f(x, y) &= 0, \qquad x < y \text{ or } y < 0 \\ f(x, y) &= \sum\_{i=1}^{x}{f(x-i, y^2-i)} \end{align} $$ Then the desired result is the sum \$\sum\_{i=1}^{n}{f(n,i)}\$. [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes This builds all sequences that sum to \$n\$ and slightly higher and counts those that exactly sum to \$n\$. ``` f=lambda n,k=0:(n==0)+sum(f(n-d*d+k,d)for d in range(n-~k)if d*d>k) ``` [Try it online!](https://tio.run/##RcnBCsIwDADQu1@R2xLXwZzgodD9SyVGQ1026jzI0F@v9eTtwVte6222YykS7nE6cwRzKfQeLYSe2sdzQkHreM9tckwyZ2BQgxzteqnxSaQCtcdE5bf634OD4UR@B7BktRWl2dQPb@hG2ASVqhsqXw "Python 3 – Try It Online") This approach is based on the observation that \$\sqrt x\$ can only be an integer if \$x\$ is an integer. This means, when building a sequence right to left, we always have to make sure to complete to a perfect square. At every step \$\sqrt{a\_i+k}\$, \$a\_i+k = d^2\$ for some positive \$d\$ with \$0 \lt d^2-k \le n'\$, where \$n'\$ is the remaining integer at the current step. To check every possible square, \$d\$ needs to be tested up to \$\lfloor\sqrt{n'+k}\rfloor\ \le n+k\$. In the code we count the number of times \$n'=0\$ is exactly reached, by summing all results and adding `n==0`. If `n` gets negative, `range(n-~k)` will eventually be empty, which will cause the recursion to stop. This seems to be currently the fastest approach, and with some added *memoization* this gets really fast: [First 1000 values](https://tio.run/##RY1BDoIwEEX3nGJ2dAQS0B1JOYJXMJV2pIFOSYFEJXr1WhfGv3rJS96fH@vg@RQjyUm5q1bA5SjrVrCUNRbL5gQJrvRBF2OpkXwADZYhKL6ZJN4jWoKkuxEjBe@ANu5X76cFrJt9WGEK26VX/WCy9PFj4dR9sU8jz54NCsIs@7btv92U0NR1g20GaXOwvArKd9seX1B1sJOwmDjH@AE "Python 3 – Try It Online") With a small modification the sequences can be printed: ``` f=lambda n,k=0,*a:(n==0!=print(a))+sum(f(n-d*d+k,d,d*d-k,*a)for d in range(n-~k)if d*d>k) ``` [Try it online!](https://tio.run/##JYwxDsIwDAC/Yja7TaUimJDMX4yMITJ1q9AOLHw9jdTphjvd8lvfc1xqNf7I9FCBSM5j6uSGwTyeeCk5VhSi/rtNaBiDdtp70tQ4eCvJ5gIKOaBIvJ6t@Dtlg@bvTvUYGJ6vRHUH "Python 3 – Try It Online") [Answer] # [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, 31 DECLEs1 ≈ 39 bytes2 *1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.* *2. As per the exception described [in this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the exact score is **38.75 bytes** (310 bits)* --- This is an implementation with only integer additions, subtractions and comparisons. A routine taking the input in **R1** and returning the result in **R3**. ``` **1DB** | CLRR R3 **1C0** | CLRR R0 **275** | @@rec PSHR R5 **089** | TSTR R1 **20C 001** | BNEQ @@notZ **00B** | INCR R3 **272** | @@notZ PSHR R2 **1D2** | CLRR R2 **110** | @@loop SUBR R2, R0 **012** | DECR R2 **110** | SUBR R2, R0 **148** | CMPR R1, R0 **20E 00E** | BGT @@done **080** | TSTR R0 **226 008** | BLE @@loop **270** | PSHR R0 **271** | PSHR R1 **101** | SUBR R0, R1 **090** | MOVR R2, R0 **004 148 040** | CALL @@rec **2B1** | PULR R1 **2B0** | PULR R0 **220 013** | B @@loop **2B2** | @@done PULR R2 **2B7** | PULR R7 ``` ### Full commented test code ``` ROMW 10 ; use 10-bit ROM width ORG $4800 ; map this program at $4800 PNUM QEQU $18C5 ; EXEC routine: print a number ;; ------------------------------------------------------------- ;; ;; main code ;; ;; ------------------------------------------------------------- ;; main PROC SDBD ; set up an interrupt service routine MVII #isr, R0 ; to do some minimal STIC initialization MVO R0, $100 SWAP R0 MVO R0, $101 EIS ; enable interrupts MVII #$200, R3 ; R3 = backtab pointer CLRR R1 ; R1 = number to test @@loop INCR R1 ; increment R1 PSHR R1 ; save R1 & R3 on the stack PSHR R3 CALL func ; invoke our routine MOVR R3, R1 ; save the result in R1 PULR R3 ; restore R3 CALL print ; print R1 PULR R1 ; restore R1 CMPI #28, R1 ; go on as long as R1 is less than 28 BLT @@loop DECR R7 ; done: loop forever ENDP ;; ------------------------------------------------------------- ;; ;; prints the result of a test case ;; ;; ------------------------------------------------------------- ;; print PROC PSHR R5 ; save the return address on the stack MOVR R1, R0 ; R0 = number to print MVII #4, R1 ; R1 = number of digits MOVR R3, R4 ; R4 = backtab pointer ADDI #5, R3 ; advance by 5 characters for the next one PSHR R3 ; save R3 CLRR R3 ; R3 = attributes (black) CALL PNUM ; invoke the EXEC routine PULR R3 ; restore R3 PULR R7 ; return ENDP ;; ------------------------------------------------------------- ;; ;; ISR ;; ;; ------------------------------------------------------------- ;; isr PROC MVO R0, $0020 ; enable display MVI $0021, R0 ; colorstack mode CLRR R0 MVO R0, $0030 ; no horizontal delay MVO R0, $0031 ; no vertical delay MVO R0, $0032 ; no border extension MVII #$D, R0 MVO R0, $0028 ; light-blue background MVO R0, $002C ; light-blue border JR R5 ; return from ISR ENDP ;; ------------------------------------------------------------- ;; ;; our routine ;; ;; ------------------------------------------------------------- ;; func PROC CLRR R3 ; R3 = counter for the final result CLRR R0 ; start with R0 = 0 @@rec PSHR R5 ; this is the recursive entry point TSTR R1 ; if R1 is equal to 0 ... BNEQ @@notZ INCR R3 ; ... increment R3 @@notZ PSHR R2 ; save R2 on the stack CLRR R2 ; start with R2 = 0 @@loop SUBR R2, R0 ; subtract R2 from R0 DECR R2 ; decrement R2 SUBR R2, R0 ; subtract R2 from R0 CMPR R1, R0 ; abort if R0 is greater than R1 BGT @@done TSTR R0 ; skip the recursive call if R0 <= 0 BLE @@loop PSHR R0 ; save R0 and R1 on the stack PSHR R1 SUBR R0, R1 ; subtract R0 from R1 MOVR R2, R0 ; move R2 to R0 CALL @@rec ; recursive call PULR R1 ; restore R0 and R1 PULR R0 B @@loop ; keep going @@done PULR R2 ; this is either the end of a recursive PULR R7 ; call or the end of the routine ENDP ``` ### Output Below are **a(1)** to **a(28)**. [![output](https://i.stack.imgur.com/KmMut.png)](https://i.stack.imgur.com/KmMut.png) *screenshot from [jzIntv](http://spatula-city.org/%7Eim14u2c/intv/)* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~56~~ 50 bytes ``` If[a=##-i i;0<a<#,a~#0~i,1-Sign@a]~Sum~{i,√+##}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtOtFWWVk3UyHT2sAm0UZZJ7FO2aAuU8dQNzgzPc8hMbYuuDS3rjpT51HHLG1l5Vq1/wFFmXkl0cq6dmkOyrFqdY5FRYmVdUam/wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Åœ€œ€`ÙʒÅ«t+}н§Å²}g ``` Brute-force approach, so very slow. Times out for \$\geq10\$. [Try it online](https://tio.run/##yy9OTMpM/f//cOvRyY@a1oCJhMMzT0063HpodYl27YW9h5YDmZtq0///NwMA) or [verify the first 9 test cases](https://tio.run/##yy9OTMpM/W/p6mevpPCobZKCkr3f/8OtRyc/aloDJhIOzzw16XDrodUl2rUX9h5aDmRuqk3/r/MfAA). **Explanation:** ``` Åœ # Get all combinations of positive integers that sum to the (implicit) # input-integer € # Map over each inner list: œ # And get all its permutations €` # Flatten the list of lists of lists one level down Ù # Uniquify the list of lists ʒ # Filter it by: Å« # Cumulative left-reduce the list by: t # Taking the square of the current integer + # And adding it to the previous } # After the cumulative left-reduce, which keeps all intermediate steps: н # Pop and push its first item § # Cast this decimal to a string (bug work-around) Ų # And check that it's a perfect square }g # After the filter: pop and push the length # (which is output implicitly as result) ``` The `§` shouldn't have been necessary, but unfortunately there is [an 05AB1E bug with decimal values for the `Ų` builtin](https://github.com/Adriandmen/05AB1E/issues/172). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 65 bytes ``` .+ *_; +%L$w`^((^_|\2__)*)(;|(?=(_+);(?!\1))) $#4*$#2*_$4;$#2*_ ; ``` [Try it online!](https://tio.run/##HcgxCoAwDADAPb8QU0haKLTUKaiji08oTR0cXBxEcPHvFZwO7trv49xC8w4srFgV0E8VDC31PxVwZsWnFqKib46qbJnkpXkkdSw0dzkwM2CfLPbRKib5BWktDh8 "Retina – Try It Online") Link includes test suite that tests all `n` up to and including the input. Explanation: ``` .+ *_; ``` Convert the input to unary and append a working area for the previous square root. ``` +` ``` Repeat until no new solutions can be found. ``` %` ``` Check all lines separately for new solutions. ``` L$w`^((^_|\2__)*)(;|(?=(_+);(?!\1))) ``` Match all square prefixes of the current value. This (`$.1`) represents the amount being square rooted on this pass. `$#2` is its square root. `$.4` is the residue after subtracting the terms so far; `$#4` is a flag for whether the residue is non-zero, in which case the square must be greater than the previous square root. This check is not performed if the residue is zero, as the previous residue must have been non-zero anyway, thus allowing completed sequences to remain undisturbed. ``` $#4*$#2*_$4;$#2*_ ``` For each square prefix, add its square root to the residue, and record the new value along with the square root. However, if the current value turned out to be square, then the square root is skipped and all that remains is the `;`. This indicates a completed sequence. ``` ; ``` Count the number of complete sequences found. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ 34 [bytes](https://github.com/abrudz/SBCS) Thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for -1 byte! Another port of my Python answer. ``` 0∘{⍵≤⍺:⍵=⍺⋄(⊢+.∇⊢+⍵-×⍨)(⌊⍺*÷2)↓⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@BRx4zqR71bH3UuedS7ywrIsgXSj7pbNB51LdLWe9TRDqKBwrqHpz/qXaGp8ainC6hA6/B2I81HbZMf9W4GytX@T3vUNuFRb9@jruZHvWse9W45tN74UdvER31Tg4OcgWSIh2fw/7RDKxSA6k0NAA "APL (Dyalog Unicode) – Try It Online") The main function is the *dfn* `{ ... }` which takes \$k\$ as the left argument and \$n+k\$ as the right argument. `0∘` supplies the initial \$k=0\$. `⍵≤⍺:⍵=⍺` is the stopping condition, if \$n+k \le k \Leftrightarrow n \le 0\$, this returns a value of \$1\$ if \$n=0\$ and \$0\$ otherwise. `⍳⍵` is the inclusive range from \$1\$ to \$n+k\$. `⌊⍺*÷2` is the floor of the aqure root of \$k\$. `↓` drops this many items from the range. This results in a new range from \$\left\lceil\sqrt{k}\right\rceil\$ to \$n+k\$. These are the values for \$d\$ that satisfy \$d^2>k\$. `⊢∇¨⊢+⍵-×⍨` is a train applied to this range. `×⍨` squares every value. => \$d^2\$ `⍵-` subtracts each square from \$n+k\$. => \$n+k-d^2\$ `⊢+` adds the range again. This is needed beacuse we actually call the function with \$n+k\$ and not just \$n\$. => \$n+k-d^2 + d\$ `⊢` is the right argument, in this this case the potential \$d\$'s. `+.∇` is the inner product of the functions `+` and `∇`. First `∇` (recurse) is called on every pair of \$d\$ and \$n+k-d^2 + d\$, then the resulting vector is reduced by addition (`+`). [Answer] # [Haskell](https://www.haskell.org/), 53 bytes A port of my Python answer. ``` (#0) n#k|n==0=1|w<-n+k=sum[(w-d*d)#d|d<-[1..w],d*d>k] ``` [Try it online!](https://tio.run/##PY0xa8MwGER3/YojbiFJKxEHsgTLS6cOgQ6BDo4HEdmNsPVZyCpOin97VTstnQ7uveMuqm@qto3Gus4HHKtrEG/eUKjZX/XSUfBdKw4dKc1YbQP2e/w6x5ur4CFzvFIA/w9/1664QcLdTSwet3pGU5xoMTNmlaFJ@DLu3YTLAfMmW@ewyqHGA4oUQmC7K6dXeYrLZLNilDQjSbmR6ThknJ4a2X/aYjlwvdarRI8640UqxFA@T0XelDF@n@tWffSRn537AQ "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (`-MList::Utils+sum`), 64 bytes ``` sub f{my($n,$k)=@_;sum!$n,map f($n+$k-$_*$_,$_),$k**.5+1..$n+$k} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrTq3UkMlT0clW9PWId66uDRXEcjLTSxQSAMKa6tk66rEa6nE66jEawLVaGnpmWob6umBZWr/FydWgpTFa6blFykAhY3MrLkgYmammtb//@UXlGTm5xX/1/X1ySwusbIKLcnM0QZaARQw1TMwBAA "Perl 5 – Try It Online") Using @ovs formula [Answer] # [Jelly (fork)](https://github.com/DennisMitchell/jelly), 15 bytes ``` ŒṗŒ!€ẎQ½+¥/€Æ²S ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7px@dpPioac3DXX2Bh/ZqH1qqD@Qcbju0Kfj///9mAA "Jelly – Try It Online") This will work for some inputs on TIO, but will fail for others due to floating point errors. However, my fork has [symbolic math support](https://github.com/cairdcoinheringaahing/jellylanguage/commit/40cc217ec50272370867fc5ea4fbd5c6126f1c11), meaning that it basically never uses floats. ## How it works This is a brute force attempt. Times out on TIO for \$n \ge 10\$. Uses a similar approach to [Kevin's answer](https://codegolf.stackexchange.com/a/213868/66833), but found independently. ``` ŒṗŒ!€ẎQ½+¥/€Æ²S - Main link. Takes n on the left Œṗ - Integer partitions of n € - Over each: Œ! - Calculate the permutations Ẏ - Merge into a list of lists Q - Deduplicate € - Over each list: ¥/ - Reduce by: ½ - Square root of left + - Plus right Ʋ - Is a square? S - Sum ``` ]
[Question] [ Why is the number 6174 so interesting? As [defined](http://en.wikipedia.org/wiki/Kaprekar%27s_constant) by Wikipedia > > 1. Take any four-digit number, using at > least two different digits. (Leading > zeros are allowed.) > 2. Arrange the digits in ascending and > then in descending order to get two > four-digit numbers, adding leading > zeros if necessary. > 3. Subtract the smaller number from the > bigger number. > 4. Go back to step 2. > > > The above process, known as Kaprekar's > routine, will always reach 6174 in at > most 7 iterations. Once 6174 is > reached, the process will continue > yielding it. > > > Write a program which runs the Kaprekar's routine against a given four-digit number (see definition above) printing out each step of the routine. Rules: * Submissions must be complete programs. * Input must be read from standard input. Piping from *echo* is OK. * Input should be in numeric form. * Printing out leading zeros is required. (See examples below.) * Last line should say how many iterations were needed. Punctuation is required. Examples: ``` > 2607 7620 - 0267 = 7353 7533 - 3357 = 4176 7641 - 1467 = 6174 Iterations: 3. > 1211 2111 - 1112 = 0999 9990 - 0999 = 8991 9981 - 1899 = 8082 8820 - 0288 = 8532 8532 - 2358 = 6174 Iterations: 5. > 6174 7641 - 1467 = 6174 Iterations: 1. ``` Any programming language is welcome. Extra points for esoteric ones + a small bounty. **Update 1**: There is already a [similar question](https://codegolf.stackexchange.com/questions/1255/hitting-495-kaprekar). **Update 2**: Added example for 6174 as input. Thanks to Peter Taylor for the notice. [Answer] ## Ruby 1.9, 122 characters ``` puts"Iterations: #{(1..7).find{s=$_.chars.sort*"";puts [r=s.reverse,?-,s,?=,$_="%04d"%(r.to_i-s.to_i)]*" ";~/6174/}}." ``` Example invocation: ``` $ echo 1211 | ruby -ln kaprekar.rb ``` I've counted the `-ln` flag as 4 characters (difference between the normal invocation `ruby kaprekar.rb` and `ruby -ln kaprekar.rb`). [Answer] # Perl - 147 143 134 130 129 126 129 128 126 ``` for($_=<>;$_-6174+!$c;$c++){$_=reverse$d=join'',sort split//,"$_" |$|x4;printf"$_ - $d = %04d\n",$_-=$d}die"Iterations: $c.\n" ``` EDIT: Now complies with 6174 case, at the cost of a few chars... run with `echo -n <number> | perl kaprekar.pl` EDIT: Finally back to where I was before :D [Answer] # Python, 141 chars ``` n=input() i=0 while n-6174:a=''.join(sorted("%04d"%n));b=a[::-1];n=int(b)-int(a);print"%s - %s = %04d"%(b,a,n);i+=1 print"Iterations: %d."%i ``` [Answer] ## Golfscript, 74 characters ``` );:|;{0):0;|$:§-1%" - "§" = ""0"4$~§~-+-4>:|n|6174`=!}do"Iterations: "0"." ``` [Answer] # ><> - 268 308 ``` </&4pff1 v>i86*-:n&1-:&?! >ao& v <v&0pff+1gff >&1+:4= ?v&:a%:}-a, v&8[4r::0}~< >&1-:?!v&:@@:@(?$}&:&3%1=?} v >~:}}:}@:}$:} \:n}:n}:n}:n}' - 'ooo:n}:n}:n}:n}' = 'ooo \a*+a*+a*+}a*+a*+a*+-:0&\ v? =4&:+1&,a-}:%a:< /\&~~rnnnnao:29777****= ?v voooooooooooo"Iterations: "/ \ffgna'.'oo; ``` Not much of a contender for golf, but it was fun to write. :) Run with `./fish.py kaprekar.fish -v <number>` EDIT: Now takes input from STDIN. [Answer] # Haskell, ~~197~~ ~~192~~ ~~182~~ 181 characters ``` import List p=putStrLn.unwords "6174"%k|k>0=p["Iterations:",shows k"."] n%k=p[b,"-",a,"=",c]>>c%(k+1)where a=sort n;b=reverse a;c=take 4$shows(read b-read a)"0" main=getLine>>=(%0) ``` [Answer] ## JavaScript, ~~189~~ ~~182~~ 165 chars Credit to DocMax: ``` for(n=prompt(i=o=e='');!i--|n-6174;o+=n+' - '+a+' = '+(n=(p=n-a+e)[3]?p:0+p)+'\n') b=n.split(e).sort(),n=b.reverse(a=b.join(e)).join(e); alert(o+"Iterations: "+~i+'.') ``` Original: ``` for(n=prompt(i=o=e='');n-6174;o+=(i++?n+"\n":e)+(n=(a=n.split(e).sort().join(e)).split(e).reverse().join(e))+' - '+a+' = ',n=n-a+e)while(!n[3])n=0+n alert(o+n+"\nIterations: "+i+'.') ``` Ungolfed: ``` var i = 0; var n = prompt(); var out = ''; while (n != 6174) { while ((n=''+n).length<4) n='0'+n // pad number if(i)out+=n+"\n" a = n.split('').sort().join(''); n = a.split('').reverse().join(''); out += n + ' - ' + a + ' = ' n-=a i++; } console.log(out + "6174\nIterations: " + i + '.'); ``` [Answer] ### PowerShell, 125 ~~128~~ ~~130~~ ~~131~~ ``` for($a,$OFS=$input+'';$b-6174;++$i){$a=$b=+($c=''+($x="$a 000"[0..4]|sort)[4..0])-"$x" "$c-$x = {0:d4}"-f$a}"Iterations: $i." ``` Passes all test cases from the question. [Answer] ## JavaScript, 260 bytes ``` function z(c){for(u=c+y;u.length<4;)u=0+u;return u}for(p=prompt(i=0,r=y="");;) if(s=(p+y).split(y).sort(),t=s.concat().reverse(),a=s.join(y),b=t.join(y),q=a<b?b:a, w=a<b?a:b,p=z(q-w),i++,r+=z(q)+" - "+z(w)+" = "+p+"\n",p==6174)break;alert(r+ "Iterations: "+i+".") ``` [Answer] # Clojure, 256 characters ``` (let[i #(Integer/parseInt%)f #(format"%04d"%)a #(->>% f sort(apply str)i)d #(->>% f sort reverse(apply str)i)k #(let[u(d %)l(a %)n(- u l)](println(f u)"-"(f l)"="(f n))n)](while true(println"Iterations:"(count(take-while #(not=% 6174)(iterate k(read))))))) ``` [Answer] ## Scala 2.9, 194 characters ``` object K extends App{var(c,s)=(0,args(0));do{var d=s.sorted;var e=d.reverse.toInt-d.toInt;s="%04d".format(e);println(d.reverse+" - "+d+" = "+s);c+=1}while(s!="6174");print("Iterations: "+c+".")} ``` Makes use of the App trait from Scala 2.9. **Edit:** gives correct output for initial input of 6174. [Answer] # PHP, 215 ~~259~~ ~~276~~ characters ``` <?php echo">";$n=str_split(str_pad(trim(fgets(STDIN)),4,0,0));for($k=0,$z=0;$k-6174;$z++){sort($n);$a=implode($n);$b=strrev($a);$k=str_pad($b-$a,4,0,0);echo"$b - $a = $k\n";$n=str_split($k);}echo"Iterations: $z\n"; ``` Ungolfed: ``` <?php echo ">"; $n = str_split(str_pad(trim(fgets(STDIN)),4,0,0)); for($k=0, $z=0; $k-6174; $z++) { sort($n); $a = implode($n); $b = strrev($a); $k = str_pad($b-$a,4,0,0); echo "$b - $a = $k\n"; $n = str_split($k); } echo "Iterations: $z\n"; ``` [Answer] ## CoffeeScript, 233 225 characters ``` o=e='';i=0;n=prompt() while n!=6174 n=e+n;q=(n='0'+n if !n[3]) for x in [0..2];n?=q;o+=n+"\n" if i;a=n.split(e).sort().join(e);n=a.split(e).reverse().join(e);o+=n+' - '+a+' = ';n-=a;i++ alert(o+"6174\nIterations: "+i+'.') ``` Try it [here](http://alicebobandmallory.com/kaprekars_constant_golf.html) or with instructions [here](http://alicebobandmallory.com/kaprekars_constant.html). [Answer] **Scala 276** ``` object o{var i=0;def a(v:String){val c=v.toList.sortWith(_>_).mkString;val b=c.reverse;val d=c.toInt-b.toInt;val e="0"*(4-(d+"").length)+d;val p=c+" - "+b+" = "+e;if(d!=6174){println(p);i=i+1;a(e)}else{println(p+"\nIterations: "+(i+1)+".")}};def main(s:Array[String])=a(s(0))} ``` **Scala 283** ``` object o{var i=0;def a(v:String){val c=v.toList.sortWith(_>_).mkString;val b=c.reverse;val d=c.toInt-b.toInt;val e="0"*(4-(d+"").length)+d;val p=c+" - "+b+" = "+e;if(d!=6174){println(p);i=i+1;a(e)}else{println(p);println("Iterations: "+(i+1)+".")}};def main(s:Array[String])=a(s(0))} ``` diff: ``` else{println(p);println("Iterations: "+(i+1)+".")}}; // to else{println(p+"\nIterations: "+(i+1)+".")}}; ``` [Answer] ## GAWK - 152 chars This is a GNU awk version. It may not work with other non-gnu versions. ``` {for(z=$1;z-6174+!c;++k){split(z,a,"");asort(a);for(b=c=i=0;i<4;z=c-b){c+=a[i+1]*10^i;b=b*10+a[++i]}printf c" - %.4d = "z"\n",b}print"Iterations: "k"."} $ awk -f k.awk <<< 9992 2999 - 9992 = 6993 3699 - 9963 = 6264 2466 - 6642 = 4176 1467 - 7641 = 6174 Iterations: 4 ``` [Answer] ## Ruby, 179 chars but posting anyway ``` s=gets.chomp n=0 begin s=s.to_s.chars.sort.reduce{|s,c|s+c}.rjust(4,'0') a=s.reverse puts"#{a} - #{s} = #{'%04d'%(s=a.to_i-s.to_i)}" n+=1 end while s!=6174 puts"Iterations: #{n}." ``` [Answer] # K, 104 ``` {b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];} ``` Test cases ``` k){b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];}'2607 1211 6174; 7620 - 0267 = 7353 7533 - 3357 = 4176 7641 - 1467 = 6174 Iterations: 3 2111 - 1112 = 0999 9990 - 0999 = 8991 9981 - 1899 = 8082 8820 - 0288 = 8532 8532 - 2358 = 6174 Iterations: 5 7641 - 1467 = 6174 Iterations: 1 ``` [Answer] **PERL** ``` chomp($n=<STDIN>); do{ $t++; $desc=join('',reverse sort split(//,$n)); $asc=join('', sort split(//,$n)); $n=($desc - $asc); for($i=4;$i>length $n;$i--){ $n="0".$n; } print $desc." - ".$asc." = ".$n."\n"; $n="6174" if $n eq "0000"; }while($n ne "6174"); print "Iterations: $t.\n"; ``` [Answer] # Mathematica, ~~314~~ 291 characters This is the program, kaprekar.m :- ``` SetOptions[$Output,FormatType->OutputForm]; x=$ScriptCommandLine[[2]]; f[x_]:=(a=Characters@x; b=Sort@ToExpression@a; c=Sort[FromDigits/@{#,Reverse@#}&@b]; {c,{b,a}}=IntegerString[{#2-#&@@c,c},10,4]; Print[a," - ",b," = ",c];c) x=f@x; e=NestWhileList[f,x,#!="6174"&]; Print["Iterations: ",N@Length@e] ``` Setting the path prior to running :- ``` $ PATH=${PATH}:/Applications/Mathematica.app/Contents/MacOS ; export PATH ``` Running the program :- ``` $ MathematicaScript -script kaprekar.m 2607 7620 - 0267 = 7353 7533 - 3357 = 4176 7641 - 1467 = 6174 Iterations: 3. $ MathematicaScript -script kaprekar.m 1211 2111 - 1112 = 0999 9990 - 0999 = 8991 9981 - 1899 = 8082 8820 - 0288 = 8532 8532 - 2358 = 6174 Iterations: 5. $ MathematicaScript -script kaprekar.m 6174 7641 - 1467 = 6174 Iterations: 1. ``` [Answer] # [PHP](https://php.net/), 160 bytes ``` function k($n,$d=1){$o=str_split($n);sort($o);echo$q=strrev($r=join($o))," - $r = ",$n=str_pad($q-$r,4,0,0)," ",$n==6174?"Iterations: $d.":k($n,++$d);}k($argn); ``` [Try it online!](https://tio.run/##HY49D8IgEIZ3fwUhN0CkpjVNmxRJF5cuLrqbpvRLDVBAF@Nvr9DtzT3v3T1mMuupNpNB0NpRIYGGsfeOXG/n5kL5OrxV52et0JOAYiBFRr@ghfP27sxr9mFKudM2BE15300alkht/yFgxUPPKhLKMEoQ2HAfM1DbvmklgSUBy3KWsjRUdhsTRVbmNW58b9v42lUI5AFXm8F@D5LyX8hRNwiuxyIt/w "PHP – Try It Online") Complete program, input is `STDIN`, run with `php -nF`. **Output** ``` > echo 2607|php -nF kap.php 7620 - 0267 = 7353 7533 - 3357 = 4176 7641 - 1467 = 6174 Iterations: 3. > echo 1211|php -nF kap.php 2111 - 1112 = 0999 9990 - 0999 = 8991 9981 - 1899 = 8082 8820 - 0288 = 8532 8532 - 2358 = 6174 Iterations: 5. > echo 6174|php -nF kap.php 7641 - 1467 = 6174 Iterations: 1. ``` [Answer] # Rust - 375 bytes ``` use std::io::{self,BufRead};fn main() {let mut x=io::stdin().lock().lines().next().unwrap().unwrap().parse::<i16>().unwrap();let mut n=0;println!("Iterations: {}.",loop {let mut v=[x/1000%10,x/100%10,x/10%10,x%10];v.sort();let j=v.iter().fold(0,|a,i|a*10+i);let k=v.iter().rev().fold(0,|a,i|a*10+i);x=k-j;n+=1;println!("{:04} - {:04} = {:04}",k,j,x);if x==6174{break n};});} ``` I present this as a possible "upper bound", I challenge anyone to find a language where a reasonable implementation of this is longer - as in there is nothing superfluous, but also nothing even remotely obvious that would shrink it significantly. The thing about Rust is that it takes about 120 characters just to read from stdin and parse into an integer. "Oh but then just use the string representation"... but im 99% confident that would be even longer [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) -n flag, 105 bytes ``` say "Iterations: "~+.&{{{say $!=.flip~" - $_"," = ",($/=$!.EVAL.fmt("%04d"));$/}([~] .comb.sort)}...6174} ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVJBybMktSixJDM/r9hKQalOW0@turoaJKGiaKuXlpNZUKekoKugEq@ko6Rgq6Cko6Gib6uiqOca5uijl5ZboqGkamCSoqSpaa2iX6sRXReroJecn5ukV5xfVKJZq6enZ2ZoblL7/7@RmYE5l6GRoSEXSOBffgHYxv@6eQA "Perl 6 – Try It Online") I finally got to use my `{}...*` trick, since we need to have at least one iteration for 6174. I'm not sure why I need the extra wrapping `.&{ }` around the sequence though, which kinda sucks. ### Explanation: ``` .&{ } # Call a function on the input { }...6174 # Create a sequence that goes until 6174 { }([~] .comb.sort) # Get the sorted digits of the number say $!=.flip~" - $_"," = "~($/=$!.EVAL.fmt("%04d")) # Print the iteration ;$/ # Return the result say "Iterations: "~+.&{ } # Print the number of iterations ``` ]
[Question] [ ### Snaking Number Challenge I wonder how many snaking numbers there are between 1 and 50,000? [![Snake on a Nokia](https://i.stack.imgur.com/oOche.gif)](https://i.stack.imgur.com/oOche.gif) Snaking Numbers, in this game, are numbers which can be typed out on a traditional numberpad (format below) by moving one key up, down, left, or right. ``` 7 8 9 4 5 6 1 2 3 0 ``` For example, if you start with the number 5, you could select 4, 6, 8, or 2 as your next valid move - however 7, 3, 9, and 1 are off-limits as they are positioned diagonally to the current key. So, if you have 5, then 2, your next viable key choices are 0, 1, 3, or 5 again. In this Code Golf exercise, you are to output a list of all the positive snaking numbers between 1 and 50k, along with a final count of all the numbers that meet the criterion. ### Rules 1. Numbers cannot start with a Zero. 2. Numbers must be whole positive integers. 3. Each consecutive number, read from left to right, must "snake" around the numberpad. 4. The snake cannot travel diagonally across keys 5. The number 0 can be accessed from both numbers 1 and 2 6. Numbers cannot be paired (eg: 22) ### Examples of valid Snaking Numbers: ``` 12369 45201 1254 10102 1 12 987 ``` ### Examples of invalid numbers ``` 1238 - 8 is not connected 0001 - multiple leading 0s 0101 - leading 0 159 - snake cannot travel diagonally 4556 - duplicate 5 ``` As per normal Code Golfs, the aim is fewest bytes! According to my maths and rules, you should have 670 valid snaking numbers in your list, plus 670 itself printed as the last number. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~60 57~~ 60 bytes ``` (x;#x:({*/1=3!5&+/x*x:+1_-':(+0 1,'2*!3 3)@10\x}')#1+!50000) ``` [Try it online!](https://ngn.bitbucket.io/k#eJzTqLBWrrDSqNbSN7Q1VjRV09av0Kqw0jaM11W30tA2UDDUUTfSUjRWMNZ0MDSIqahV11Q21FY0NQACTQCiOg0U) `!50000` list of `0` .. `49999` `1+` add 1 to all `({` `}')#` filter with the function in `{` `}` `10\x` decimal digits of the argument `(` `)@` use as indices in ... * `!3 3` a pair of lists: `(0 0 0 1 1 1 2 2 2;0 1 2 0 1 2 0 1 2)` * `2*` multiply all by 2 * `0 1,'` prepend `0` to the first list and `1` to the second * `+` transpose (pair of lists -> list of pairs). this gives us the approx button coords. `-':` subtract from each pair the previous pair. use `0 0` as an imaginary element before the first. `1_` drop the first `+` transpose `x*x:` square (assign to `x` and multiply by `x`). here `x` is a pair of lists - ∆x-s and ∆y-s `+/` sum the two lists (element by element) `5&` min with 5 `3!` mod 3 `1=` boolean list of where it's equal to 1 `*/` product (boolean "and") `(x;#x:` `)` make a pair of the result and the length (`#`) of the result [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 5ȷ4µDo1.’d3ZIASĊ’ẸµÐḟṄL ``` A full program which prints a list of all the results and then the number of results. **[Try it online!](https://tio.run/##ASsA1P9qZWxsef//Nci3NMK1RG8xLuKAmWQzWklBU28y4buK4bqgwrXGhyxMJP// "Jelly – Try It Online")** ### How? ``` 5ȷ4µDo1.’d3ZIASĊ’ẸµÐḟṄL - Main Link: no arguments 5ȷ4 - 5*10^4 = 50000 µ µÐḟ - filter discard those for which this is truthy: - e.g.: 8520 ... or 4559 D - decimal digits [8,5,2,0] [4,5,5,9] 1. - literal 1.5 o - logical OR [8,5,2,1.5] [4,5,5,9] ’ - decrement [7,4,1,0.5] [3,4,4,8] d3 - div-mod by 3 [[2,1],[1,1],[0,1],[0,0.5]] [[1,0],[1,1],[1,1],[2,2]] Z - transpose [[2,1,0,0],[1,1,1,0.5]] [[1,1,1,2],[0,1,1,2]] I - deltas [[-1,-1,0],[0,0,-0.5]] [[0,0,1],[1,0,1]] A - absolute value [[1,1,0],[0,0,0.5]] [[0,0,1],[1,0,1]] S - sum (vectorises) [1,1,0.5] [1,0,2] Ċ - ceiling [1,1,1] [1,0,2] ’ - decrement [0,0,0] [0,-1,1] Ẹ - any? 0 (i.e. keep) 1 (i.e. discard) Ṅ - print and yield L - length - implicit print ``` [Answer] # [Python 3](https://docs.python.org/3/), 140 bytes ``` f=lambda s:''==s[1:]or s[1]in'10021234562216565878 43 749 9 5 8'[int(s[0])::10]and f(s[1:]) print(*filter(f,map(str,range(1,50000))),670) ``` [Try it online!](https://tio.run/##HYy9DoMgGAD3PsW3AQ0DoPxI4pMQBhqlNVEkwOLTU9tbbrjk8tU@Zxp6j/MejtcSoFqE5rk6bv1Z4LbfEuKMCS6GUSohuJJKGm1gHECPE0wAIAEMcltquDrmibWc@ZAWiPg/Io9cfvEZt72tBUd6hIxrK7SE9F4xp5LdEEKo0oz0/gU "Python 3 – Try It Online") I'm positive someone will be able to do this with an expression instead of a lookup string. [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` print[n for n in range(1,50000)if all(`n`[i:i+2]in`0x20b33ec8bc49a10589e76b15`for i in range(4))],670 ``` [Try it online!](https://tio.run/##RcxLCoAgEADQq8wyycVo2u8qEahhNRBTSIs6vdWqd4B33Oe6s875SMTnwDDvCRiIIXleYqGkxZegGfy2FY7dQD2VeiR2eGkMVRWnNkym8wpt28WmDsq6b6F/MUKMsm4w5wc "Python 2 – Try It Online") The hex number is decimal `10120214525632365878969854741`, which encodes every ordered pair of digits that can appear adjacent to one another. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~112 106~~ 104 bytes *Saved 2 bytes thanks to @NahuelFouilleul* A full program. ``` for(n=0;++n<5e4;)[...n+''].every(x=>'6589632145201478'.match(x+p+'|'+p+(p=x)),p='')&&print(n) print(670) ``` [Try it online!](https://tio.run/##JcbRCsIgFADQ9z5k914scUudY9mPRA8yjBZk4kQM@ncLejmchytuW9Ia86GY1m6vhMGKmbFwUl7OdOGcBwZw5b749MZqz6CVmfRx6KUaRC9HA/zp8nLHyiKDD/zEaCvRPloA6rqY1pAx0O4fPQpq7Qs "JavaScript (V8) – Try It Online") Or **96 bytes** if we can output the numbers in reverse order: ``` for(n=5e4;n--;)[...n+''].every(x=>'6589632145201478'.match(x+p+'|'+p+(p=x)),p='')&&print(n||670) ``` [Try it online!](https://tio.run/##DcTRCsIgFADQv9m9Ysq21BnDfiR6kGG0oDsxEQP/3ToP5@WL/2xpj1kU2/vjSEhOB7WSECu7SSmJA9xlKCF9sborGG0v5jxPSs/jpBYL8u3z9sTKI4cG/zG6ytgpOgA2DDHtlJFaM8vIev8B "JavaScript (V8) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~37~~ 35 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╞╡~▄ⁿ♪eµïê◙ü╔ï▼ΔJr¥æ≤PH╟♀I♣Δz8─¶Γ╞Ç▓ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=8ce15d53873821b51db83a5b66ecdf904d1a54eb4d9948a4bc6d431f27cfcdfb10ffa9&i=) It was so nice and short, until it wasn't. ### Unpacked (42 bytes) and explanation ``` 49999{E2B{{om"#qYY>!(AFI"%A|E2B{{om-C_Qf%p 49999{ f Filter range [1..49999]: E2B All adjacent pairs of digits {{om Each sorted "#qYY>!(AFI"%A| Literal 2012365478963258741 E2B{{om Pairs of digits, each sorted - Set difference C Cancel block execution if any remain _Q Print current value %p Print length ``` 2012365478963258741 encodes the keypad. Look at pairs of adjacent digits. Perhaps if I could get a decently short alternative that goes in both directions for each pair, I could cut the eight bytes of `{{om`. Without that trailing 670, a simple filter would suffice: `f..!` instead of `{..C_Qf%p`. There might be a better way to go about handling this irregularity. In either case, this filter-range behavior is undocumented. [Answer] # [PHP](https://php.net/), 145 bytes ``` for(;$i++<5e4;$f&&print$i._)for($f=1,$l=b;''<$d=("$i")[$$i++];$l=$d)$f&=$l>a||strstr([12,240,1053,26,157,2468,359,48,579,68][$l],$d)>'';echo 670; ``` [Try it online!](https://tio.run/##FYvhCoMgFEZfZcQljS5DLc0w24NEjG0VCbHE9bN3dwYfBz4Ox68@dg@fuOyBGnBl2cm5NrDkuQ/ue4C7P4vLwWI5wmbfhpAOJkszcFkxwJWMJgmYilRZ2PrXef6OkEYHLlDUDDmTFQqFXDbpK42VbLHWKJsWlR4H2EZMfU@ImT/rflMNMzH@AQ "PHP – Try It Online") For every number from 1 to 50,000, checks every digit of that number from left to right. If all digits are in the list of valid digits of the previous digit, that number is printed. At the end prints a hard coded 670 since it takes less bytes than actually counting it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` ŽÅKLʒSÌYX;:3‰üαï€OP}=g= ``` [Try it online!](https://tio.run/##ATYAyf9vc2FiaWX//8W9w4VLTMqSU8OMWVg7OjPigLDDvM6xw6/igqxPUH09Zz3///8tLW5vLWxhenk "05AB1E – Try It Online") Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/191022/6484). [Answer] # Perl 5 (`-M5.01`), ~~96~~, 92 bytes -4 bytes thanks to @Xcali ``` $r=join"|",map$t++."[^$_]",12,240,1350,26,157,2648,359,48,579,68;map/$r/||say,1..5e4;say 670 ``` [TIO](https://tio.run/##K0gtyjH9/1@lyDYrPzNPqUZJJzexQKVEW1tPScPeNjpOJT5WU0nH0EjHyMRAx9DY1EDHyEzH0NQcSJlY6BibWuoAKVNzSx0zC2ugTn2VIv2amuLESh1DPT3TVBNrIFPBzNzg//9/@QUlmfl5xf91fU31DAwB) [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~179~~ ~~173~~ ~~151~~ 129 bytes ``` [12,240,1350,26,157,2468,359,48,579,68].map((_,i,l)=>i&&(f=(v,t)=>print(v)|v<5e3&&[...l[t]+''].map(k=>f(v+k,k)))(i,i)),print(670) ``` [Try it online!](https://tio.run/##JctLCoMwEADQ28QZnAZ/iQrVi4gUaRWmURtiCBR691Rw@RbvPYXpeDq2/nZYfs1u@@xm/sY45AUVVUZ5qTIqNOWqPq0bKlVLVUOqbkk3o9wmC/AgphW7noWApYNA/oR1vHsI@At3NZdCDFLKdfBjmiRXM12/QEgNGUQEJkakK@k6wxjjHw "JavaScript (SpiderMonkey) – Try It Online") -22 bytes thank to Arnauld -22 bytes thank to dana # explanation: ``` [12,240,1350,26,157,2468,359,48,579,68] // an array where keys are current position and values, the possible destinations .map((_,i,l)=> // loop over it i&&( // if key is not 0 f=(v,t)=> // create a function print(v)| // which print the value v<5e3&& // and if the limit is not attained [...l[t]+''].map(k=>f(v+k,k)) // recurcively call itself with for each destinations )(i,i)), // make the first call with each digit print(670) // finally print 670 ``` --- @dana also gave a 123 bytes solution if we can print 670 first ``` [21,420,5310,62,751,8642,953,84,975,86].map((_,i,a)=>(f=(v,t)=>print(i?v:640)|i&v<5e3&&[...a[t]+''].map(k=>f(v+k,k)))(i,i)) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 99 bytes ``` 1.upto(5e4){|n|w,*x=n.digits;x.all?{|d|[6,21,43,68,162,340,552,272,672,320][w][w=d]>0}&&p(n)} p 670 ``` [Try it online!](https://tio.run/##KypNqvz/31CvtKAkX8M01USzuiavplxHq8I2Ty8lMz2zpNi6Qi8xJ8e@uialJtpMx8hQx8RYx8xCx9DMSMfYxEDH1NRIx8jcSMcMiI2NDGKjy4HINiXWzqBWTa1AI0@zlqtAwczc4P9/AA "Ruby – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~28~~ 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Δh┤♣É╦&·é╝n$K»à¶▲v═NÆ;↨m≥8 ``` [Run and debug it](https://staxlang.xyz/#p=ff68b40590cb26fa82bc6e244baf85141e76cd4e923b176df238&i=&a=1) Unpacked, ungolfed, and commented, it looks like this. ``` G Call to unbalanced trailing '}', then resume here 670P Print 670 } Call target 219J 219 squared (47961) f Filter 1-based range by the rest of the program; implicitly output $2B Convert to string and get adjacent pairs; e.g. 213 -> ["21", "13"] O Push 1 under list of pairs F Iterate over pairs, using the rest of the program o Order each pair; e.g. "21" -> "12" "{<f:[/T8Z" string literal with code points [123 60 102 58 91 47 84 56 90] $ concate as string i.e. "12360102589147845690" s# How many times does the current pair appear in the constant string? * Multiply this by running total. Any zero will cause the result to be zero. ``` [Run this one](https://staxlang.xyz/#c=G++++++++++++++%09Call+to+unbalanced+trailing+%27%7D%27,+then+resume+here%0A670P+++++++++++%09Print+670%0A%7D++++++++++++++%09Call+target%0A219J+++++++++++%09219+squared+%2847961%29%0Af++++++++++++++%09Filter+1-based+range+by+the+rest+of+the+program%3B+implicitly+output%0A++%242B++++++++++%09Convert+to+string+and+get+adjacent+pairs%3B+e.g.+213+-%3E+[%2221%22,+%2213%22]%0A++O++++++++++++%09Push+1+under+list+of+pairs%0A++F++++++++++++%09Iterate+over+pairs,+using+the+rest+of+the+program%0A++++o++++++++++%09Order+each+pair%3B+e.g.+%2221%22+-%3E+%2212%22%0A++++%22%7B%3Cf%3A[%2FT8Z%22%09string+literal+with+code+points+[123+60+102+58+91+47+84+56+90]%0A++++%24++++++++++%09concate+as+string+i.e.+%2212360102589147845690%22%0A++++s%23+++++++++%09How+many+times+does+the+current+pair+appear+in+the+constant+string%3F%0A++++*++++++++++%09Multiply+this+by+running+total.++Any+zero+will+cause+the+result+to+be+zero.&i=) The secret sauce is in the string literal `"{<f:[/T8Z"`. After jamming all the codepoints together, you get `12360102589147845690`. The ascending pairs in this string are the valid snake moves. [Answer] # [Haskell](https://www.haskell.org/), 118 bytes ``` (filter(and.(zipWith elem.tail<*>map f).show)[1..50000],670) f c=words"12 024 0135 26 157 2468 359 48 579 68"!!read[c] ``` [Try it online!](https://tio.run/##DcHdCoMgAAbQ@z3FV1c1hqilFay9xi6iCylFmf2gQrCXdzvHqvjR3uccx8o4n3So1L6S6uvOt0sW2uuNJOX88/7a1AlTk2iPq54YIYL@zQ/Z0fpmsIzXEdZYMg7KW1DWCHAJJjrwVvZoxIC2h@gGyL4siqDVOi1z3pTbMeIMbk@I@Qc "Haskell – Try It Online") A first pass; I'm not good at compression. The `s=` doesn't count, since we don't actually need to bind the result. [Ungolfed code](https://tio.run/##TZA/b8IwEMV3f4oTQgIGUP45AaR0aLt0aYcOHVAGixhi4ThRbJWqXz49@0IVL/bvvTv7nhthb1LrcTTyx72qq3IWjkd4acQA2yc4@UPFZuYZSjgLK/HQXRjAKlr5wkWcLDzFRFGSBUwmjFMeOCVO8kDZ1MqLgHwys3wfOCdO@SFgQZiRuSfiBZkHQt/JlP004iZ9jjfjvP7cdfpfNphAmBqW8Kv6L@UakFq2sHZCabBueN/At9CqpsB4@b2Rg8QdgovdtunuYIIyq0SjFT3M/sqXM2b9q@FXTzhO9eASLko7OcBjrlO82/EIV8VYK5QJ83/AekNUQt3hk/2gMNMS6JaZoKW5YhbSx/EP). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔ΦI…·¹×⁵⁰φ⬤ι№”)¶∧XRτ_ΠGêR⁵m⎇λ”✂ιμ⁺²μ¹θθILθ ``` [Try it online!](https://tio.run/##Rc7dCoMgHAXw@z2FdPUXHKhlH3QVwWCwi9j2AiKuBDNK6/Wd62Z3h8Phx1GT3NQibYyd92Z0cDM26A166QPcnbK7N4d@SjdqYAS9zaw9CErQB2NMUGctGIL6ZXcBMsqKqm7KnFPOuChELUrB87Kpq4LRjKCXNUr/9jNBQ5KBp5gUhk9sxe1l2EyS/un88dBuDFNqcRtjvB72Cw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔ΦI…·¹×⁵⁰φ ``` Process the inclusive range from `1` to `50,000` cast to string. ``` ⬤ι№”)¶∧XRτ_ΠGêR⁵m⎇λ”✂ιμ⁺²μ¹θ ``` Filter out those that have pairs of digits not contained in the compressed string `01478963202125458565236987410`. ``` θILθ ``` Output the remaining array and its length. [Answer] # [Japt](https://github.com/ETHproductions/japt), 34 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 5e4õs f_ä@"-Pì[/Z8"mc øZñÃe pUl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NWU09XMgZl/kQCItUAHsWy8IWgI4Im1jIPha8cNlCnBVbA&input=Ii1QAexbLwhaAjgi) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 64 bytes ``` {670,grep {[+&](:36<12HGX91H8VCL3MG0FDVQ>X+>m:ov/../)%2},1..5e4} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2szcQCe9KLVAoTpaWy1Ww8rYzMbQyMM9wtLQwyLM2cfY193AzSUs0C5C2y7XKr9MX09PX1PVqFbHUE/PNNWk9n9BaYlCmobmfwA "Perl 6 – Try It Online") ### Explanation ``` {670,grep {...},1..5e4} # Meet questionable output requirements # Actual decision problem :36<12HGX91H8VCL3MG0FDVQ> # Bit field of allowed transitions # encoded in base 36 m:ov/../ # All 2-digit substrings X+> # Right shift by each substring # (implicitly converted to an integer) [+&]( ) # Binary and %2 # Modulo 2 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~68~~ ~~65~~ 45 bytes ``` l f.Am}dCtB+J`65874589632012541_PJCtB`TS50000 ``` [Try it online!](https://tio.run/##K6gsyfj/P4crTc8xtzbFucRJ2yvBzNTC3MTUwtLM2MjA0MjUxDA@wAsokxASbGoABP//AwA "Pyth – Try It Online") Inspiration for the revised lookup process came from [Khuldraeseth na'Barya's Stax answer](https://codegolf.stackexchange.com/a/191029/41020), go give them an upvote! --- Edit 2: Rewrote to save a bunch of bytes, previous version: ``` l f.Am}ed@c"12 024 0135 26 157 2468 359 48 579 68";shdCtB`TS50000 ``` --- Edit: Golfed 3 bytes by using string lookups, previous version: ``` l f.Am}ed@sMMc"12 024 0135 26 157 2468 359 48 579 68";hdCtBjT;S50000 ``` ]
[Question] [ ### Task Given (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the [interquartile mean](https://en.wikipedia.org/wiki/Interquartile_mean). ### One possible algorithm 1. Discard the lowest and highest quarters of the data points. 2. Calculate the average (sum divided by count) of the remaining data points. **Note:** If the dataset size is not evenly split-able in four, you will have to [weigh the datapoints](https://en.wikipedia.org/wiki/Weighted_arithmetic_mean) that are shared by sub-sets. See *Example evaluation 2* below. ### Example evaluation 1 Given {1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38} 1. Data count is 12, so we remove lowest and highest 3 datapoints: {~~1, 3, 4,~~ 5, 6, 6, 7, 7, 8, ~~8, 9, 38~~} 2. Average of the remaining 6 datapoints: (5 + 6 + 6 + 7 + 7 + 8) / 6 = **6.5** ### Example evaluation 2 Given {1, 3, 5, 7, 9, 11, 13, 15, 17} 1. Count is 9, so each quarter has 2¼ datapoints: {~~1, 2, (0.25×5),~~ (0.75×5), 7, 9, 11, (0.75×13), ~~(0.25×13), 15, 17~~} 2. Average of the remaining 4.5 datapoints: (0.75×5 + 7 + 9 + 11 + 0.75×13) / 4.5 = **9** [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~11~~ 10 bytes ``` ~~.O><lQS\*4Ql~~ .OsPtc4S*4 ``` [Test suite.](http://pyth.herokuapp.com/?code=.OsPtc4S%2a4&test_suite=1&test_suite_input=1%2C3%2C4%2C5%2C6%2C6%2C7%2C7%2C8%2C8%2C9%2C38%0A1%2C3%2C5%2C7%2C9%2C11%2C13%2C15%2C17&debug=0) ### How it works It quadruplicates the input list to ensure that the data count is divisible by 4. It still needs sorting, because `*4` applies to the whole list instead of to each individual element. Then, it splits the list into four equal parts, then takes away the first and the last part. The remaining list is flattened and the average is taken. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` 4Y"G"6L)]Ym ``` Input is a horizontal vector, with the format ``` [1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38] ``` or ``` [1 3 4 5 6 6 7 7 8 8 9 38] ``` [**Try it online!**](http://matl.tryitonline.net/#code=NFkiRyI2TCldWW0&input=WzEsIDMsIDUsIDcsIDksIDExLCAxMywgMTUsIDE3XQ) ### Explanation ``` 4Y" % Input horizontal vector implicitly. Repeat each element 4 times (run-length % decoding). The resulting array is still sorted. G" % Push input, for each: repeat as many times as the input size 6L) % Remove first and last elements, by applying the index "2:end-1" ] % End for each Ym % Compute mean. Display implicitly ``` [Answer] # Python 3, 50 bytes ``` lambda n:sum(sorted(n*4)[len(n):-len(n)])/len(n)/2 ``` [Ideone it!](http://ideone.com/dlII0Q) ### How it works It is a translation of my [answer in Pyth](https://codegolf.stackexchange.com/a/86464/48934). [Answer] ## [Snowman](https://github.com/KeyboardFire/snowman-lang), 66 bytes ``` }vg","aS:10sB;aM4aRAsOal`,4nD,`aG0AaGal`NdE`AaL1AfL:nA;alaF,nDtSsP ``` [Try it online!](http://snowman.tryitonline.net/#code=fXZnIiwiYVM6MTBzQjthTTRhUkFzT2FsYCw0bkQsYGFHMEFhR2FsYE5kRWBBYUwxQWZMOm5BO2FsYUYsbkR0U3NQ&input=MSwzLDQsNSw2LDYsNyw3LDgsOCw5LDM4) Uses the same algorithm as [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s answers. ``` } enable variables b, e, and g vg read a line of input into b ","aS split on commas (in-place) :10sB;aM convert each element in resulting array to number ("frombase(10)-map") 4aR repeat the array 4 times AsO sort the array al take the length and put it in e without consuming b (the array) `, swap b and e, then move e to g; now b=length g=array 4nD divide b by 4 (4 was stored in e, which is why the array was moved) ,` move the array and length/4 back to their original positions aG split the array into groups of length (length/4) 0AaG take all elements with index >0 (i.e. remove the first element) al store the length of the new array in e again `NdE` bring it up to b, decrement, and put it back AaL take all elements with index <length-1 (i.e. remove last) 1AfL flatten the array 1 level deep :nA; push a block that adds two numbers (to e) al store the length of this new array in g aF fold b over e (sum the numbers) , move g (the length) into e nD divide the sum by the length, resulting in the average tSsP to-string and print ``` [Answer] # Scilab, 8 bytes ``` trimmean ``` See [the documentation](https://help.scilab.org/docs/6.0.0/en_US/trimmean.html). By default, `discard=50`, so the IQM is computed. EDIT: You know, this is a trivial built-in answer, so I’m [marking it as CW](http://chat.stackexchange.com/transcript/message/30801907#30801907). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ~~x4ṫL‘$ḣLN$S÷LH~~ ~~x4ṫLḊḣLN$S÷LH~~ x4œs4ḊṖFS÷LH ``` [Try it online!](http://jelly.tryitonline.net/#code=eDTFk3M04biK4bmWRlPDt0xI&input=&args=WzEsMyw1LDcsOSwxMSwxMywxNSwxN10) [Test suite.](http://jelly.tryitonline.net/#code=eDTFk3M04biK4bmWRlPDt0xICsOH4oKs&input=&args=WzEsMyw0LDUsNiw2LDcsNyw4LDgsOSwzOF0sWzEsMyw1LDcsOSwxMSwxMywxNSwxN10) ### How it works It is a translation of my [answer in Pyth](https://codegolf.stackexchange.com/a/86464/48934). [Answer] ## Pyke, ~~16~~ 13 bytes ``` 4*S4ftOsDsRl/ ``` [Try it here!](http://pyke.catbus.co.uk/?code=4%2aS4ftOsDsRl%2F&input=%5B1%2C+3%2C+4%2C+5%2C+6%2C+6%2C+7%2C+7%2C+8%2C+8%2C+9%2C+38%5D) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` :3jo@4brbcLl/N,L+:N*. ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjNqb0A0YnJiY0xsL04sTCs6Tiou&input=WzE6Mzo1Ojc6OToxMToxMzoxNToxN10&args=Wg) or [verify multiple test cases](http://brachylog.tryitonline.net/#code=Ons6MiZ3QE53fWEKOjNqb0A0YnJiY0xsL04sTCs6Tiou&input=W1sxOjM6NDo1OjY6Njo3Ojc6ODo4Ojk6MzhdOlsxOjM6NTo3Ojk6MTE6MTM6MTU6MTddXQ) ### Explanation This is basically @LeakyNun's Pyth answer algorithm. ``` :3j Append 3 copies of the input to itself o@4 Sort and split in 4 lists of equal length brb Remove the head and the tail of the list of lists cL Concatenate the 2 sublists into a list L l/N, N is the inverse of the length of L L+:N*. Output is the product of N and the sum of the elements of L ``` The only small trick there is in multiplying by the inverse of the length instead of dividing by the length, because division between 2 integers is integer division. [Answer] # [Octave](https://www.gnu.org/software/octave/), 44 bytes ``` @(x)mean(reshape(~~(1:4)'*x,[],4)(:,2:3)(:)) ``` This defines an anonymous function. The input is a horizontal vector. [**Try it on ideone**](http://ideone.com/wNEdX1). ### Explanation The input horizontal vector is first matrix-multiplied (`*`) by a column vector of four ones (built with `~~(1:4)'`). The result is a four-column matrix where each row is a copy of the input vector. This is then reshaped, while maintaining the linear order of the elements, into a 4-column matrix (`reshape(...,[],4)`). The center two columns are kept (`(:,2:3)`) and linearized into a single column (`(:)`), of which the mean is computed (`mean(...)`). [Answer] # [J](http://www.jsoftware.com/), ~~20~~ 18 bytes **2 bytes thanks to @miles** ``` ~~#-:@%~-@#+/@}.#}.4#]~~ -@#(+/%#)@}.#}.4#] ``` [Try it online!](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28-%40%23%28%2B%2F%25%23%29%40%7D.%23%7D.4%23%5D%29%201%203%205%207%209%2011%2013%2015%2017%0A9) ([Online interpreter](http://tryj.tk)) ### Usage ``` >> f =: -@#(+/%#)@}.#}.4#] >> f 1 3 5 7 9 11 13 15 17 << 9 ``` ### How it works It is a translation of my [answer in Pyth](https://codegolf.stackexchange.com/a/86464/48934). [Answer] # [Actually](https://github.com/Mego/Seriously), ~~20~~ ~~15~~ 13 [bytes](https://en.wikipedia.org/wiki/Code_page_437) ``` ~~;l╗;+;+S╜@t╜τ@HΣ╜τ@/~~ ~~;l;τ;a;+;+StHΣ/~~ ;l;τ;aττStHΣ/ ``` [Try it online!](http://actually.tryitonline.net/#code=O2w7z4Q7Yc-Ez4RTdEjOoy8&input=WzEsMyw1LDcsOSwxMSwxMywxNSwxN10) ### How it works It is a translation of my [answer in Pyth](https://codegolf.stackexchange.com/a/86464/48934). [Answer] ## JavaScript (ES6), 75 bytes ``` a=>a.concat(a,a,a).sort(g=(x,y)=>x-y).slice(l=a.length,-l).reduce(g,0)/l/-2 ``` Uses the obvious quadruplicate-and-sort approach, and I get to use `reduce`, which is nice. The only trickery here is to save 4 bytes by reusing the sort comparator to subtract all the array elements from zero, which gives me `-2l` times the answer I want. [Answer] ## Octave, 42bytes Another anonymous function for Octave. ``` @(x)mean([x;x;x;x](:)((b=numel(x))+1:3*b)) ``` You can [try it online](http://octave-online.net). Simply enter that command, and then do `ans([1 2 4 5 6 9])` or whatever numbers are required. This one starts by creating from the input array one with 4 of each input element by first concatenating four copies vertically, and then flattening it vertically. This maintains the sort order. Then is extracts the range of elements from the length of the input array plus 1 up to three times the length of the input array. Because the new array is four times longer, this chops off the upper and lower quartiles. Finally the mean of the new array is returned. [Answer] ## 05AB1E, 15 bytes ``` €D€D¹gô¦¨˜DOsg/ ``` **Explanation** ``` €D€D # quadruple each element in list ¹gô # split into pieces the size of input ¦¨˜ # remove the first and last and flatten the middle 2 DOsg/ # sum and divide by length ``` [Try it online](http://05ab1e.tryitonline.net/#code=4oKsROKCrETCuWfDtMKmwqjLnERPc2cv&input=WzEsIDMsIDUsIDcsIDksIDExLCAxMywgMTUsIDE3XQ) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 15 bytes ``` IQM←(+/÷≢)≢↓-∘≢↓4∘/ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@8Z6PuobYKGtv7h7Y86F2kC8aO2ybqPOmZAWCZAlv7//0BVCoY6CsY6CiY6CqY6CmZgZA5GFmBkCZS14EKoMwXLAUUNgXxDoIAhUMTQHAA "APL (Dyalog Unicode) – TIO Nexus") `4∘/` quadruplicate each element `-∘≢↓` drop as many trailing elements as there are elements in the arguments `≢↓` drop as many leading elements as there are element in the argument `(`…`)` apply the following tacit function:  `+/` the sum  `÷` divided by  `≢` the tally [Answer] # Golfscript, ~~28~~ 29 bytes ``` ~~~.4\*$\,.@/1>2<{+}\*{+}\*'/'@2\*~~ ~.4*$\,.@/1>2<{+}*{+}*\2*-1?* ``` [Try it online!](http://golfscript.tryitonline.net/#code=fi40KiRcLC5ALzE-Mjx7K30qeyt9KlwyKi0xPyo&input=WzEgMyA1IDcgOSAxMSAxMyAxNSAxN10) [Answer] ## Actually, 12 bytes ``` 4α;l¼≈;±(Htæ ``` [Try it online!](http://actually.tryitonline.net/#code=NM6xO2zCvOKJiDvCsShIdMOm&input=WzEsIDMsIDQsIDUsIDYsIDYsIDcsIDcsIDgsIDgsIDksIDM4XQ) (currently doesn't work because TIO is a few versions behind) Explanation: ``` 4α;l¼≈;±(Htæ 4α repeat each element 4 times ;l¼≈ length divided by 4, as integer ;± copy, unary negate (Ht remove first and last quartiles æ mean ``` [Answer] ## Mathematica, 51 bytes ``` Mean@#[[(l=1+Length@#/4);;-l]]&@Sort@Join[#,#,#,#]& ``` Sorts four copies of the list (to prevent issues with list length not multiples of four), takes part `"1 quarter the length of resulting list plus 1"` through to the `"1/4 length list + 1 from the end"`, takes their `Mean`. [Answer] # Java ~~146~~ 126 Bytes Such java much verbose! ``` float m(float[]n){float r=0;int l=n.length,i=l/4;r-=(n[i])*(l%4)/4;r+=n[i*3]*(4-(l%4))/4;for(;i<l*3/4;r+=n[i],i++);return r/l*2;} ``` ## Older Ungolfed partially readable with test cases ``` /** * * @author rohan */ public Golf{ float m(float[]n){ //declarations float r=0; int x,i=0,l=n.length; //sum the array for(float m:n){r+=m;} //remove the excess for(;i<l/4;r-=n[i]+n[l-i-1],i++); //weight the quartiles r-=(n[l/4]+n[l*3/4])*(l%4)/4; //return the sum/length but multiply by two since only half of the set is averaged return r/l*2; } static void interQuartileMean(float... set){ System.out.println(new Golf().m(set)); } /** * @param args the command line arguments */ public static void main(String[] args) { //test cases pass with flying colours interQuartileMean(1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38); interQuartileMean(1, 3, 5, 7, 9, 11, 13, 15, 17); } } ``` [Answer] ## Clojure, ~~82~~ 81 bytes Edit: 1 byte less by re-writing "didvide by 2 n" part. ``` #(let[n(count %)](*(/ n)0.5(apply +(subvec(vec(for[i % j(range 4)]i))n(* 3 n))))) ``` Previous: ``` #(let[n(count %)](/(apply +(subvec(vec(for[i % j(range 4)]i))n(* 3 n)))(* 2.0 n))) ``` Uses `for` to generate 4 repeated values, using float `2.0` not to have fractional results, the rest is just standard. [Answer] ## R, ~~17~~ 11 bytes ``` mean(n,0.25) ``` Assuming `n` is the input vector in the standard R form `n=c(1, 2, 3, ...)`. This is in no way surprising since R can be considered “THE language for statistical computing” and has many statistical built-ins. *UPDATE.* Saved 6 bytes thanks to rturnbull because `trim` is the first optional argument by default! Test cases: ``` a <- c(1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38) b <- c(1, 3, 5, 7, 9, 11, 13, 15, 17) mean(a,trim=0.25) # Returns 6.5 mean(b,trim=0.25) # Returns 9 ``` [Answer] # Excel, 17 bytes ``` =TRIMMEAN(A:A,.5) ``` Relaxed input format make this easy. Input one per row in Column A. [Answer] # [Perl 5](https://www.perl.org/), 80 + 2 `-pa` = 82 bytes ``` map{shift@F;pop@F}1..($b=@F/4);map$_*=1-($b-=0|$b),@F[0,-1];$_=sum(@F)/(@F-2*$b) ``` [Try it online!](https://tio.run/##JY2xCsIwEIZ3nyJDhrYkbU4bW1sCmTLp6CQiLSgGWhtMndRXN54RPu74v//g3Pk@yBDGzj391V5mbVo3OW3ekOcJ7ZU2RZm2WNNTpoCj4kq8aJ8ybQ6CcTi29KT8Y0y0SQscfJlhGwIwsmKkZEQyso5UkTqywbZe/G9k9GgAM6AANFB9Jjfb6eYD38lcgMC9tX5umv1sh9/HwF03fAE "Perl 5 – Try It Online") [Answer] # [Awk](https://www.gnu.org/software/gawk/manual/gawk.html), 68 bytes ``` {while(++i%5)p[++a]=$0}END{for(l=a/4;l<3*a/4;)s+=p[++l];print 2*s/a} ``` [Try it online!](https://tio.run/##SyzP/v@/ujwjMydVQ1s7U9VUsyBaWzsx1lbFoNbVz6U6Lb9II8c2Ud/EOsfGWAtEaxZr24LU5MRaFxRl5pUoGGkV6yfW/v9vyGXMZcplzmXJZWjIZWjMZWjKZWgOAA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` a=>eval(a.flatMap(x=>[x,x,x,x]).slice(n=a.length,-n).join`+`)/2/n ``` [Try it online!](https://tio.run/##bYtBDoMgEEX3PQVLSBFDW6td4A16AmPihILFkMEUY7w9paybeZv//5sFdoj649atwvAyyaoEqjc7eArCetiesNJD9cPBy41MRO@0oahAeIPz9uYVMrEEh9N5YvWlxqQDxuCN8GGmlg6SkysnN04aTu6FttAVHnntRsZOf7@aYmZH5ixzIXMj25@fvg "JavaScript (Node.js) – Try It Online") ]
[Question] [ # Introduction I want to build a ladder. For this, I have scavenged from the junkyard two long boards with holes in them, and I want to place the steps into these holes. However, the holes are not evenly placed, so the steps will be a little wonky, and I find it hard to estimate the amount of rod I need for them. Your job is to do the calculations for me. # Input Your input is two bit vectors, given as arrays of integers, which represent the two boards. A `0` represents a segment of one aud (*arbitrary unit of distance*) without a hole, and a `1` represents a segment of one aud with a single hole. The arrays may be of different lengths and contain a different number of `1`s, but they will not be empty. I will construct my ladder as follows. First, I place the two boards exactly one aud apart, and align their left ends. For each index `i`, I measure the distance between the `i`th hole of the first board with the `i`th hole of the second board, cut a piece of rod, and attach it between the two holes. I stop once I run out of holes in one of the boards. # Output Your output is the total amount of rod I'll need for the steps, measured in auds. The output should be correct to at least six significant digits. # Example Consider the inputs `[0,1,1,0,1,1,1,1,0,0]` and `[1,0,0,1,1,1,0,0,1]`. The resulting ladder looks like this: ![A really funky ladder.](https://i.stack.imgur.com/d2brl.png) The total length of the rod in this ladder is `7.06449510224598` auds. # Rules You can write either a function or a full program. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases ``` [0] [0] -> 0.0 [0] [1,0] -> 0.0 [1,0,0] [1,1,1,1,1] -> 1.0 [0,1,0,1] [1,0,0,1] -> 2.414213562373095 [0,1,1,0,1,1,1,1,0,0] [1,0,0,1,1,1,0,0,1] -> 7.06449510224598 [1,1,1,1,1] [0,0,1,1,0,1,0,0,1] -> 12.733433128760744 [0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,0] [0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1] -> 20.38177416534678 ``` [Answer] ## J, 22 characters Not inspired by the answer of randomra. The `I.` part is equal as that is the immediately obvious way of finding the holes. ``` (4+/@:o.<.&#$-/@,:)&I. ``` * `I. y` – all the indices of `y` repeated as often as the corresponding item of `y`. Incidentally, if `y` is a vector of booleans, `I. y` contains the indices at which `y` is `1`. For instance, `I. 1 0 0 1 1 1 0 0 1` yields `0 3 4 5 8`. * `x u&v y` – the same as `(v x) u (v y)`. Applied as `x u&I. y`, we get `(I. x) u (I. y)`. Let's continue with the transformed input. * `x <.&# y` – the lesser of the lengths of `x` and `y`. * `x -/@,: y` – the difference of the items of `x` and `y`. If one vector is longer, it is padded with zeroes. * `x $ y` – `y` reshaped to the shape specified by `x`. Specifically, if `x` is a scalar, `x` elements are taken from `y`. In this usage, `x (<.&# $ -/@,:) y` makes sure that trailing holes are ignored. * `4 o. y` – the function `%: 1 + *: y`, that is, sqrt(1 + *y*²). Incidentally, this function maps from hole distance to length of rods. * `+/ y` – the sum of the elements of `y`. [Answer] # Python, 85 ``` lambda*A:sum(abs(x-y+1j)for x,y in zip(*[[i for i,x in enumerate(l)if x]for l in A])) ``` This turned out similar to [Mac's solution](https://codegolf.stackexchange.com/a/47281/20260). Convert the lists of 0's and 1's to ordered lists of the one-indices, and then sum the distance between respective elements. [Answer] # J, ~~32~~ 28 bytes The verb `I.` returns the positions of `1`s in a binary string which is a huge help. ``` +/@,@(=/&(#\)*[:>:&.*:-/)&I. 0 1 0 1 (+/@,@(=/&(#\)*[:>:&.*:-/)&I.) 1 0 0 1 2.41421 ``` For a better J solution check [FUZxxl's answer](https://codegolf.stackexchange.com/a/47282/7311). [Answer] # R, 67 Uses outer to do a difference for indexed holes. Diag returns required differences. Then sum the calculated distances ``` function(a,b)sum((diag(outer(which(a==1),which(b==1),"-"))^2+1)^.5) ``` [Test run](http://www.r-fiddle.org/#/fiddle?id=KEeVlJ6h) in R Fiddle. I have wrapped it in a print to show the return complies with spec. ``` > print((function(a,b)sum((diag(outer(which(a==1),which(b==1),"-"))^2+1)^.5))(c(0,1,1,0,1,1,1,1,0,0),c(1,0,0,1,1,1,0,0,1)),digits=10) [1] 7.064495102 > print((function(a,b)sum((diag(outer(which(a==1),which(b==1),"-"))^2+1)^.5))(c(1,1,1,1,1),c(0,0,1,1,0,1,0,0,1)),digits=10) [1] 12.73343313 > ``` [Answer] # Haskell, 77 73 bytes ``` r x=[a|(a,1)<-zip[1..]x] i#j=sum$zipWith(\n m->sqrt((n-m)**2+1))(r i)$r j ``` Usage: `[0,1,0,1] # [1,0,0,1]` which outputs `2.414213562373095` How it works: the function `r` returns a list of the positions of the holes of a board, e.g. `r [0,1,0,1]` -> `[2,4]`. `#` zips two of those lists and turns it into a list of distances between corresponding holes and finally sums it. [Answer] # CJam, ~~36~~ 33 bytes ``` l~]{:L,{L=},}%z{,(},0\{~-_*)mq+}/ ``` Very naive approach... it expects the input as CJam-style arrays on STDIN ``` [0 1 1 0 1 1 1 1 0 0] [1 0 0 1 1 1 0 0 1] ``` [Here is a test harness](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3D'%2CSer~%0A%0A%5D%7B%3AL%2C%7BL%3D%7D%2C%7D%25z%7B%2C(%7D%2C0%5C%7B~-_*)mq%2B%7D%2F%0A%0Ap%7D%2F&input=%5B0%5D%20%5B0%5D%20-%3E%200.0%0A%5B0%5D%20%5B1%2C0%5D%20-%3E%200.0%0A%5B1%2C0%2C0%5D%20%5B1%2C1%2C1%2C1%2C1%5D%20-%3E%201.0%0A%5B0%2C1%2C0%2C1%5D%20%5B1%2C0%2C0%2C1%5D%20-%3E%202.414213562373095%0A%5B0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C0%2C0%5D%20%5B1%2C0%2C0%2C1%2C1%2C1%2C0%2C0%2C1%5D%20-%3E%207.06449510224598%0A%5B1%2C1%2C1%2C1%2C1%5D%20%5B0%2C0%2C1%2C1%2C0%2C1%2C0%2C0%2C1%5D%20-%3E%2012.733433128760744%0A%5B0%2C0%2C0%2C1%2C0%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C0%2C0%2C1%2C0%2C1%2C1%2C0%2C0%2C0%2C1%2C0%5D%20%5B0%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C0%2C1%2C1%2C0%2C0%2C0%2C1%5D%20-%3E%2020.38177416534678) for all the example inputs. The results in the input field are used before the actual code is called. You can remove them if you don't trust me. ;) ## Explanation ``` l~] "Read and eval input, wrap in an array."; { }% "Map this block onto both input arrays."; :L, "Store array in L, get its length N."; {L=}, "In the range [0 .. N-1] get all elements where L is 1."; "At this point we've converted each array into a list of its non-zero indices."; z "Transpose the array, pairing up indices at the same position."; {,(}, "Filter the extraneous elements of the longer input."; 0\ "Put a 0 before the array."; { }/ "For each pair of holes..."; ~- "Unwrap the pair, take the difference."; _*)mq "Square, increment, square root."; + "Add to the running total."; ``` [Answer] # Python, 86 ``` f=lambda a,b,i=1j:a>[]<b and a[0]*b[0]*abs(i)+f(a[a[:1]<=b:],b[b[:1]<=a:],i+a[0]-b[0]) ``` A low-level and naive recursive solution without any list searching. The input lists are `a` and `b`. If either is empty, return `0`. Otherwise, let `x` and `y` be their first elements (the code doesn't actually assign these because you can't do assignments in a `lambda`, but it will make explaining easier). If both are 1, i.e. their product is 1, then they contribute rod distance. We keep track of distance in the complex number `i`, so that distance is the absolute value. Actually, we compute it regardless, then multiply it by `x*y`. Then, we recurse. The idea is to shift both lists one step, unless one list starts with a 0 and the other with a one, in which case we shift only the 0 list. That way, 1's are always consumed in pairs. We could check these conditions with `x<y` and `y<x`, but it's shorter to take advantage of list comparison as `a[:1]<=b`. Finally, we adjust the complex displacement between the current elements by `x-y`. [Answer] # Python, 105 102 100 bytes ``` i=lambda l:(i for i,h in enumerate(l)if h) l=lambda*a:sum(((a-b)**2+1)**.5for a,b in zip(*map(i,a))) ``` Pretty basic, just converts the input lists to lists of hole indices, then computes distance between each pair of such indices. Test case: ``` >>> print l([0,1,1,0,1,1,1,1,0,0], [1,0,0,1,1,1,0,0,1]) 7.06449510225 ``` Credit to @FryAmTheEggman for a couple of byte-saving suggestions. Turns out this can be golfed further, as demonstrated in [xnor's answer](https://codegolf.stackexchange.com/a/47285/38252). [Answer] # J, 20 bytes ``` 4+/@:o.(<0 1)|:-/&I. ``` It uses the trick in [MickyT's answer in R](https://codegolf.stackexchange.com/a/47280/9288). `(<0 1)|:` gives the diagonal of a matrix. For the explanations of the other parts, see [FUZxxl's answer](https://codegolf.stackexchange.com/a/47282/9288). [Answer] # Pyth, 30 bytes ``` s+0m^h^-hded2 .5CmfTm*hb@kblkQ ``` Try it [online](https://pyth.herokuapp.com/) with the input `[0,1,1,0,1,1,1,1,0,0], [1,0,0,1,1,1,0,0,1]`. ### Explanation: I convert the lists into lists of indices `[2, 3, 5, 6, 7, 8]` and `[1, 4, 5, 6, 9]` and zip them together `[(2,1), (3,4), (5,5), (6,6), (7,9)]`. Then I subtract the values, square them, add 1 and sum over all square roots. ``` CmfTm*hb@kblkQ m Q map each list k in input() to the following list: m lk map each value b of [0, 1, 2, ..., len(k)-1] to the value: *hb@kb (b + 1) * k[b] fT filter the list for positive values C zip these two resulting lists s+0m^h^-hded2 .5... m ... map each pair of values d to: ^h^-hded2 .5 ((d[0] - d[1])^2 + 1)^0.5 +0 insert 0 at the front of the list s sum ``` Shame that `sum` doesn't work for empty lists. [Answer] # Python, ~~116~~ 115 bytes This is a recursive solution. It became pretty annoying when I found that `index()` just throws an error when no value is found, but I made it work. Unfortunately, I cannot use a lambda. It also annoyed me that `list.remove()` doesn't return the list, but instead returns `None`. ``` def f(x,y,r=0): try:i,j=x.index(1),y.index(1) except:return r x.pop(i);y.pop(j);return f(x,y,r+((i-j)**2+1)**.5) ``` Run online here: <http://repl.it/c5L/2> [Answer] # [Clip 3](http://esolangs.org/wiki/Clip), ~~55 47~~ 38 ``` [cr+`j[v[w#)#mvw2B}}(c)c]sl`{%ky1%kx1` ``` For the list with the fewer holes, the program iterates through it, and connects each hole with the corresponding hole of the other list. The sizes are calculated and summed. ``` >java -jar Clip3.jar ladder.clip {0,1,1,0,1,1,1,1,0,0} {1,0,0,1,1,1,0,0,1} 7.064495102245980096000721459859050810337066650390625 ``` ## Explanation ``` [c .- Assign c to the lists, in order of size -. r+` .- The sum of... -. j[v[w .- Join the lists with a function on v, w -. # .- Square root -. ) .- 1 plus -. # .- The square of -. mvw .- The distance between v and w -. 2 B .- (one-half, so #...B means square root) -. }}(c)c .- Apply joining function to the lists -. ]sl`{ .- c is the (sorted by size) list of... -. %ky1 .- Indices of y (the second input) which are 1-. %kx1 .- Indices of x (the first input) which are 1 -. ` ``` If we are very liberal about the input format, we can reduce this to 36 bytes by removing each `k`. This requires the input to be a string of the control characters characters `\0` and `\1`. [Answer] # ECMAScript 6, 86 bytes This originally started out using reduce (I wanted to see if it could be done in one loop as opposed to @edc65 answer). ``` f=(c,b,a=[0,...c],j)=>a.reduce((c,v,i)=>c+=v&&(j=b.indexOf(1,j)+1,v=i-j,j)?Math.sqrt(1+v*v):0) ``` But using @edc65 for `map` and `&&t` to return the value I was able to shorten it quite a bit. ``` f=(a,b,j,c=0)=>a.map((v,i)=>c+=v&&(j=b.indexOf(1,j)+1,v=i+1-j,j)&&Math.sqrt(1+v*v))&&c f=(a,b,j,c=0) //variables note the j can be undefined =>a.map((v,i)=> //loop through the first array c+= //add v&& //test to see if we have a hole (j=b.indexOf(1,j)+1, //if so see if there is a whole on the other board v=i+1-j, //calculate index difference j) //the last var gets evaluated so check to see if indexOf returned -1 &&Math.sqrt(1+v*v)) //calculate &&c //return sum ``` [Answer] # Java, 151 This just walks along `a` looking for ones, then walks along `b` when it finds one. If `float` accuracy is acceptable I could save a couple bytes, but I went with `double` to match the test output. ``` double d(int[]a,int[]b){double z=0;for(int x=-1,y=0,d=b.length;x++<a.length&y<d;z+=a[x]>0?Math.sqrt((y-x)*(y++-x)+1):0)for(;y<d&&b[y]<1;y++);return z;} ``` With whitespace: ``` double d(int[]a,int[]b){ double z=0; for(int x=-1,y=0,d=b.length; x++<a.length&y<d; z+=a[x]>0?Math.sqrt((y-x)*(y++-x)+1):0) for(;y<d&&b[y]<1;y++); return z; } ``` [Answer] # JavaScript (ES6) 108 The main point is the f function that maps the input 0..1 arrays in arrays of holes positions. Then the arrays are scanned computing a total rods length using the pythagorean theorem. The `|0` near the end is needed to convert NaNs that can result when the driver array (the first) is longer than the second. ``` F=(a,b,f=a=>a.map(v=>++u*v,u=0).filter(x=>x))=> f(a,b=f(b)).map((v,i)=>t+=Math.sqrt((w=b[i]-v)*w+1|0),t=0)&&t ``` **Test** In Firefox / FireBug console ``` ;[[[0],[0]] ,[[0],[1,0]] ,[[1,0,0],[1,1,1,1,1]] ,[[0,1,0,1],[1,0,0,1]] ,[[0,1,1,0,1,1,1,1,0,0],[1,0,0,1,1,1,0,0,1]] ,[[1,1,1,1,1],[0,0,1,1,0,1,0,0,1]] ,[[0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,0],[0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1]]] .forEach(v=>console.log('['+v[0]+']','['+v[1]+']',F(...v))) ``` > > [0] [0] 0 > > [0] [1,0] 0 > > [1,0,0] [1,1,1,1,1] 1 > > [0,1,0,1] [1,0,0,1] 2.414213562373095 > > [0,1,1,0,1,1,1,1,0,0] [1,0,0,1,1,1,0,0,1] 7.06449510224598 > > [1,1,1,1,1] [0,0,1,1,0,1,0,0,1] 12.733433128760744 > > [0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,0] [0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1] 20.38177416534678 > > > [Answer] # Octave, ~~60~~ ~~59~~ 42 ``` @(a,b)trace(sqrt((find(a)'-find(b)).^2+1)) ``` [Answer] # Perl 98 ``` sub l{$r=0;@a=grep$a->[$_],0..$#$a;@b=grep$b->[$_],0..$#$b;$r+=sqrt 1+(shift(@a)-shift@b)**2 while@a&&@b;$r} ``` ## Readable: ``` sub l { $r = 0; @a = grep $a->[$_], 0 .. $#$a; @b = grep $b->[$_], 0 .. $#$b; $r += sqrt 1 + (shift(@a) - shift @b) ** 2 while @a && @b; $r } ``` ## Testing: ``` use Test::More; for (<DATA>) { my ($A, $B, $r) = /\[ ([0-9,]+) \] \s \[ ([0-9,]+) \] \s -> \s ([0-9.]+) /x; $a = [split /,/, $A]; $b = [split /,/, $B]; cmp_ok l(), '==', $r, "test $_"; } done_testing($.); __DATA__ [0] [0] -> 0.0 [0] [1,0] -> 0.0 [1,0,0] [1,1,1,1,1] -> 1.0 [0,1,0,1] [1,0,0,1] -> 2.414213562373095 [0,1,1,0,1,1,1,1,0,0] [1,0,0,1,1,1,0,0,1] -> 7.06449510224598 [1,1,1,1,1] [0,0,1,1,0,1,0,0,1] -> 12.733433128760744 [0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,0] [0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1] -> 20.38177416534678 ``` [Answer] ## APL, ~~35~~ 28 bytes Uses a similar algorithm to the J solution, but APL has fewer builtins. ``` {+/4○⊃-/{⍵⍴¨⍨⌊/⍴¨⍵}⍵/¨⍳¨⍴¨⍵} ``` Example input: ``` {+/4○⊃-/{⍵⍴¨⍨⌊/⍴¨⍵}⍵/¨⍳¨⍴¨⍵}(1 0 0 1)(0 1 0 1) 2.414213562 ``` ]
[Question] [ \* and don't have a word processor with top-left align support :D Take several lines of input, with at least four unique characters of your choice including newline and space. The input can also be taken as a space-padded matrix of characters. Squash it upwards, then squash it left. Output this, with any amount of trailing newlines and spaces. ## To squash upwards For any non-space character "below" a space, swap their places, until there are no more non-space characters below spaces. ## To squash left For each line, remove all spaces. ## Example (with `abcdefghjkl \n`): With the input (STDIN, function arguments, [etc](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).): ``` a b c d e ff ggg h i jj kk lll ``` Squash upwards: ``` afbgcgdhle fjj gk l i k l ``` Squash left: ``` afbgcgdhle fjjgkli kl ``` Output this text. (STDOUT, function return value, [etc](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).) ## More examples ``` input => output ------- a b c => abc ------- a c => a c ------- => ------- ^ note that trailing spaces are allowed so a single line with a space is valid here a => a ------- a => a ------- ab c => ab c ------- abc d e f g => abc de fg ------- abc d f g => abc dg f ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes per language wins. --- Finding out which academic journal requires submissions to be top-left aligned is left as an excercise for the reader. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS) ``` ~∘' '⍤1∘⍉⍣2 ``` [Try it online!](https://tio.run/##bc6xCsIwEAbgvU/xb5k61OITuOhqfYE0NdE2oKuLi1BUSNFBcNdRcPEJfJR7kXilhUrpEi7ff3ec3Now20m7Md7v6XgXEOSeEVfkTuQeI6@pvJCr6Hwg9yL3@b5jKq9U3ZL5hN/FdJZ4DSYhkUIhA5a8RWsYY7DCmj/IcxQFrLUiEGEYikAjwhi8Ds1Y5zEnrav/7lYxYLKz@g7UXeihTBlV3xRj1twLMxi20Q8 "APL (Dyalog Unicode) – Try It Online") A train taking and returning a character matrix. ``` ⍣2 ⍝ repeat 2 times: ⍉ ⍝ transpose the character matrix ~∘' ' ⍝ remove spaces ⍤1 ⍝ in each row ⍝ each row is padded with spaces to keep the matrix shape ``` --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 [bytes](https://github.com/abrudz/SBCS) -2 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)! In the extended variant `⌂` provides easy access to the [*dfns* namespace](http://dfns.dyalog.com/n_contents.htm), which has a function to **d**rop **a**ll **b**lanks. ``` ⌂dab∘⍉⍣2 ``` [Try it online!](https://tio.run/##bc49CsJAEAXgPqd43VZbqHgCG22NF9hkfzRZ1MJCW4Wg4gYtBHtbwcYTeJS5SNyQQCSkGZjvzQwj1pbLnbArw9V2o5ZSyaKgy16KiI4Pcidyz36hKbuSy@l8IPci9/m@B5TdKL@H05Gvs/EkLDQ8MYEIMSSgGJjWMMZgjoVvkCRIU1hrWcA45yzQ6GEIfw7VWuMDn9Qe/0/Xig4TjZV/oJxCC0XkMW5b7FFW/8J0hnX0Aw "APL (Dyalog Extended) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Zḟ€⁶Z ``` [Try it online!](https://tio.run/##ATsAxP9qZWxsef//WuG4n@KCrOKBtlr/4bu0w4dZ//9hIGIgYyBkICBlCmZmIGdnZyBoIGkKIGpqIGtrIGxsbA "Jelly – Try It Online") ``` Zḟ€⁶Z Main Link Z Transpose the matrix ḟ Filter out € From each row ⁶ Spaces Z Transpose the matrix ``` [Answer] # [J](http://jsoftware.com/), 14 bytes ``` -.&' '"1@|:^:2 ``` [Try it online!](https://tio.run/##Vc29CsIwGIXh/buKQwdDwYTaMVIQBCcn9yppfpsEdKjg4L3HqDg4nO19OLE0gjkMEgxrdJB1XGB/Oh4KFysG1mx2T3mWfWlJ6eWu8iDgMG7Fpcf4Fh0pTNAwgCXn4L1HwEyIESkh50wt2cfN6sWaiv@pm7z2JuRKY/Qpz5Q@vQ5XfP/AJX68vAA "J – Try It Online") Not surprising, but what I came up with is almost identical to ovs's APL approach. ## how Transpose `|:` and remove spaces `-.&' '` on each line `"1` two times `^:2`. [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` lambda x,g=lambda x:[sorted(r,key=' '.find)for r in zip(*x)]:g(g(x)) ``` [Try it online!](https://tio.run/##NYw7DoMwFAR7n2JFw3OEaNIhcZIkhYk/POzYlnEBuTyBIt1IM7t5r3OK98OOzyOoz6QVts6NfxweayrVaCqdN/vYou0tRy1tKijgiC9num3yNThytEl5XIYvY6lpGoUJb2jACGvhnMMMFlgWeI8Qwpn0aw5cA0ezkpSDQC4c6znul8SR@Pz8AQ "Python 3 – Try It Online") -15 bytes thanks to dingledooper [Answer] # [Red](http://www.red-lang.org), 108 bytes ``` func[x][loop 2[x: collect[while[x/1/1][keep pad trim/all form collect[forall x[keep take x/1]]length? x]]]x] ``` [Try it online!](https://tio.run/##dY4xbsQgEEV7n@KL3rI25UpJ7pAWTYFhwKxnbcshCrd3sPGutEVE8/@bh2ZWdtsXO02Nv27@Z7I6k5Z5XvCm8xV2FmGb9O8QhXXuLt2F9Mi8YDEOaY33zojAz@v96Zays1y9ZEZG@UgkPIU0fCITUaataGzsgMTfCbrRyqCHhQNYQXmPEAIGxFJwu2EcISKKHmJN@7C82nCyIx@Dmk2/K@e0t6W4ugPhheHJCn2cJ3Hi88ZljVM6AKFm9f6hmhfT/@@2bato@wM "Red – Try It Online") Takes input and returns output as a series of strings space-padded to equal length. [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` ,c!Z{Xz ``` [Try it online!](https://tio.run/##y00syfn/XydZMao6our//2j1RIUkhWSFFAWFVHVrBfW0NIX09HSFDIVMEE8hK0shO1shJydHPRYA) Or [verify all test cases](https://tio.run/##y00syfmf8F8nWTGqOqLqf6y6LgSoR7iE/FdPVEhSSFbnilZPVLdWUFcAEcnqsVzq6lxAES51hUSwXBJYXAEoAeIkqysAuSkKqWA6TSEdTVwBIQ4A). Input is a char matrix (rectangular char array). ### Explanation ``` , % Do twice c % Convert to char. The first time this takes the input (implicit), % and does nothing because the input is already a char matrix. The second % time this transforms the cell array of char vectors at the top of the % stack into a char matrix, right-padding each line with space ! % Transpose Z{ % Convert char matrix into cell array of its rows Xz % Remove space from each char vector contained in that cell array % End (implicit) % Display (implicit) ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 14 bytes ``` 2{{x@<^x}'+x}/ ``` [Try it online!](https://tio.run/##y9bNS8/7/z/Nyqi6usLBJq6iVl27olb/f5qChlKiQpJCskKKgkKqkrVSWppCenq6QoZCJpCjkJWlkJ2tkJOTo6T5HwA "K (ngn/k) – Try It Online") * `2{...}/` set up a do-reduce, running the code in `{...}` twice + `{...}'+x` call the nested `{...}` with each item of the transposed input - `{x@<^x}` shuffle spaces to the end [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Õ¸¬Õ¸¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1bis1bis&input=ImEgYiBjIGQgIGUKZmYgZ2dnIGggaQogamoga2sgbGxsIg) ``` Õ¸¬Õ¸¬ :Implicit input of string Õ :Transpose ¸ :Split on spaces ¬ :Join Õ¸¬ :Repeat ``` # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 2Æ=Õ¸¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=MsY91bis&input=ImEgYiBjIGQgIGUKZmYgZ2dnIGggaQogamoga2sgbGxsIg) ``` 2Æ=Õ¸¬ :Implicit input of string U 2Æ :Map the range [0,2) = : Reassign to U Õ : Transpose ¸ : Split U on spaces ¬ : Join :Implicit output of last element ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes Input and output is a list of lists of characters. ``` 2FζðδK ``` [Try it online!](https://tio.run/##yy9OTMpM/V/zqGlN8H8jt3PbDm84t8X7f6zXod3/ExWSFJIVUhQUUrnS0hTS09MVMhQyuRSyshSysxVycnIA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##yy9OTMpM/X9o2aEVSlzWXEqHFpZVHtp2aOGjpjXB/43czm07vOHcFu//sZpeQJFDu8FqDu/9r6SkxJWokKSQrJCioJDKlZamkJ6erpChkMmlkJWlkJ2tkJOTA1QKVgKiuRS4QLQCmA2kFbgUQHRiElg4MSmZKwVkjEI6jAdmA20BAA) `2F` iterate two times: `ζ` tranpose the list of lists, padding shorter lists with spaces `ðδK` remove all spaces [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `aj`, 7 bytes ``` 2(ÞTȧvṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=aj&code=2%28%C3%9ET%C8%A7v%E1%B9%85&inputs=a%20b%20c%20d%20%20e%0Aff%20ggg%20h%20i%0A%20jj%20kk%20lll&header=&footer=) ([Test cases!](http://lyxal.pythonanywhere.com?flags=aj&code=2%28%C3%9ET%C8%A7v%E1%B9%85&inputs=a%20b%20c%20d%20%20e%0Aff%20ggg%20h%20i%0A%20jj%20kk%20lll&header=%40f%3A1%7C%E2%86%B5&footer=%29%E2%81%8B%2C%60-----%60%2C%3B%0A%23%20Test%20cases%0A%60a%20b%20c%20d%20%20e%0Aff%20ggg%20h%20i%0A%20jj%20kk%20lll%60%20%40f%3B%0A%0A%60a%20b%20c%60%20%40f%3B%0A%0A%60a%5Cn%20%5Cnc%60%20%40f%3B%0A%0A%60%20%60%20%40f%3B%0A%0A%60a%60%20%40f%3B%0A%0A%60%20%20%0A%20a%60%20%40f%3B%0A%0A%60ab%0Ac%60%20%40f%3B%0A%0A%60abc%0Ad%20e%0Af%20g%60%20%40f%3B%0A%0A%60abc%0Ad%0Af%20g%60%20%40f%3B)) ``` 2(ÞTȧvṅ 2( Repeat twice: ÞT Transpose ȧ Remove whitespace vṅ Join sublists on empty string ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~197~~ \$\cdots\$ ~~181~~ 180 bytes Saved a byte thanks to [a stone arachnid](https://codegolf.stackexchange.com/users/80050/a-stone-arachnid)!!! Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #define F for(i=0;i<l;)for(j=0,p=t[i++];*p;++p,++j)if(*p<33)for(k i;j;k;f(t,l,p,q)char**t,*p,*q;{F=i;q=t[k]+j,k<l;)k+=*q-32?*p=*q,*q=32,l:1;F=0,q=p;!k**++q;)*q-32?*p=*q,k=*q=32:0;} ``` [Try it online!](https://tio.run/##nZVtk5owEMff@ym2dHrDQ5wqiNrL0b7o1C9xOh2NAQM5DoVObW/86rUhBIwptp1jRrPh/8vuZrNRMkwIOZ/fbmnMcgoLiJ8PNotGmD1w7NSTNBqhIqoemeetsFtgzyuQ56UOi223eAgCCWUDhlOc4diuEEcF2jtktz64boXcArl7/LKIGN4LL9nKS1FW@868yN0PA/@TWwhDQFHgI34/xgsRcB8V@E3mup63x46OZZEE70f4dGZ5BU9rltvO4GUA4pExoaJl9XX8uIIIXqw1bIDAFoBayIpjSJIEdsDEBNIUsgw459YJm8t9fXmPHrS6hcCC@quPmnTUn1qoNOgTp@3CjXQNPcisQ0jNbOsNgiU22MPOTRb62AYuG7YpIlLVUGOgxokaQzVO1ThT41y5rQ9IvuCN05L9pM@iRaRv572aumqOQNd9Q/cNPTD0wNAnhj4x9NDQQ0OfGvrU0GeGPjP0uaHPnatzoceCkopuL40abxKSbHe8Occ0TTLOoDmpjIN6rH4n/uWAbzJXLUuavu0nb7Rtp4fd5bgB/L19O8xsYdq0ZXKLN9s4UW0MRhu3Cxr8UmmkFUyzA82eaHao2VPNnmn2/CpTsqMkowcRF2Siy@MXf3n88Fl8wjpVbR60OYtfT7Dri8LyLT2KZSOszIe2n9pol47q3mDwPEk70PwE6rdZOGtutCRWuAPqcFyp4m6acrOZzbc4fuTa6y5TYCpNkSKXGejR60euZXX5n9acPxO7rA6c5rb4F1k54MHYwVe8kEnxw1bLkMSuieIgIse2tbTelUtrmYtyKloDTwMTh@FHwWpILIMg4A4260VFul3r9JWsWJelYMavKolaLIe7O6grQp6KbstUViYSTl6zcZnLgVL7v2oiHOXRvx4ZqW3oOuvW6WlwOv8iMV8n5Xn4/Tc "C (gcc) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `combinators.extras`, 62 bytes ``` [ [ flip [ [ 32 = ] partition prepend ] map ] twice "\n"join ] ``` [Try it online!](https://tio.run/##HY0xDsIwEAT7vGLlB1BAB6JGNDSIClI4zjlc4pyNbQQI8XaTpFntTLFrtck@lsv5eDpsYfzYsOjJpBW9c9QJiR5PEkMJA0UhB/YIkXL@hMiSsauqbwUojQYGLUBqRmvRdR3u4AXR9xgGOOdU9StXXGEdB8xls8YeNYKOmTN7mdcDSTu5UYcp84sNQd1E9Z4FdTHaOSzv5Q8 "Factor – Try It Online") It's a quotation that accepts a matrix of characters/list of strings from the data stack as input and leaves a string on the data stack as output. * `[ ... ] twice` Call a quotation twice. * `flip` Transpose a matrix. * `[ ... ] map` Do something to every row in the matrix. * `[ 32 = ] partition prepend` Separate the spaces from the other characters, then stick 'em on one end. * `"\n"join` Convert a matrix of code points (e.g. `{ { 91 91 32 } { 91 32 32 } { 32 32 32 } }`) to a string. [Answer] # [Vim](https://www.vim.org), 55 bytes ``` YP:s/./\\_./g Dddqq:%s/\v (<C-r>-)(\S)/\2\1 @qq@q:%s/ //g ``` Requires input to be padded to a rectangle. [Try it online!](https://tio.run/##HcrNCkBAFAbQ/TzFt1Esxo2lJMUDKCt1SxjGz2yGmte/ZH1OEBm64qGUmMeUrGqN8b6IHuKAuGz0Xekk5j4hzjmDqr2vfwZ9WWTCjAUGWNW2wVqLHYfCeeK64JwTHV4 "V (vim) – Try It Online") ### Strategy We're going to handle the vertical swaps by constructing a regex that will match any \$n\$ characters--including newline--where \$n\$ is the length of each line. Then we look for a space followed by \$n\$ characters followed by a non-space and swap the space for the non-space. Since the potential matches of this regex are overlapping, we'll use a macro to keep on doing the replacement until there are no more matches. Then the horizontal squashing is easy: just remove all spaces. ### Explanation ``` YP ``` Copy the top line upward. We're going to turn this copy into the regex we need. ``` :s/./\\_./g<cr> ``` Replace each character on the line with `\_.`. In Vim regex, this is a construct that [matches any single character including newline](https://vi.stackexchange.com/a/13991) (TIL). Line 1 now contains a regex that matches \$n\$ characters. ``` Ddd ``` Delete to the end of the line (putting the regex in register `-`) and then delete the now-blank line (doesn't overwrite `-` because it's a multiline deletion). ``` qq ``` Begin recording macro `q`: ``` :%s/\v (<C-r>-)(\S)/\2\1 <cr> ``` Do a substitution on all lines: space, followed by the regex we stored in register `-` (group 1), followed by a non-space character (group 2) => group 2, followed by group 1, followed by space. (The `\v` sequence [means](https://vim.fandom.com/wiki/Simplifying_regular_expressions_using_magic_and_no-magic) we don't have to backslash the parentheses, saving a net 2 bytes.) ``` @qq ``` After the substitution, call the macro recursively. Stop recording... ``` @q ``` ... and call the macro. This recursive macro will run until no more substitutions can be made. ``` :%s/ //g<cr> ``` Replace all spaces on all lines with empty string. [Answer] # Scala 2.12, 71 bytes Fixed a mistake thanks to @ophact ``` 1.to(2)./:(_){_.transpose.map{r=>val(x,s)=r.partition(32<);x++s}->_ _1} ``` [Try it in Scastie!](https://scastie.scala-lang.org/pVSdd4b0TbuWsQlDFajO2w) Takes a matrix of characters as input. The non-space characters have to be greater than 32 (ASCII). ``` 1.to(2) //Make the range[1..2]. This is just to repeat the function twice ./:(_){ //Fold over it with the input as the initial value for the accumulator _.transpose //Transpose the matrix first so we can work on the columns .map{r=> //For every row, val(x,s)=r.partition(32<); //x is non-space characters, s is spaces x++s //Join those together, with all the spaces at the end }->_ //Make a 2-tuple with the current number (either 1 or 2) _1} //Get the first element of that tuple (the matrix), discarding the number ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, ~~11~~ 9 bytes ``` ZD J*||Zg ``` Takes input as lines of stdin, padded to a full rectangle. [Try it online!](https://tio.run/##K8gs@P8/ykXBS6umJir9//9EhSSFZIUUBYVUrrQ0hfT0dIUMhUwuhawshexshZycnP@6RTkA "Pip – Try It Online") ### Explanation ``` g is list of lines of stdin (-r flag) Zg Zip g (transposing into a list of lists of characters) || Strip whitespace from each character (replacing spaces with empty string) J* Join each sublist into a single string ZD Zip again, padding shorter sublists with nil Autoprint with each sublist on a separate line (-l flag) ``` Changing the flags to `-rP` shows the actual structure of the list that gets output (`()` is nil): ``` ["a";"f";"b";"g";"c";"g";"d";"h";"l";"e"] ["f";"j";"j";();"g";"k";();"l";();"i"] [();();();();"k";();();();();"l"] ``` Since the `-l` flag joins each sublist together without a separator, and since nil normally produces no output, `-rl` gives us exactly the output we want: ``` afbgcgdhle fjjgkli kl ``` [Answer] # JavaScript (ES10), 82 bytes Expects a space-padded matrix of characters. Returns a list of lists of characters. ``` m=>m.map(r=>r.flatMap((_,x)=>m.some((r,y)=>1/(c=r[x])||m[y+=[,x]]?0:m[y]=1)?c:[])) ``` [Try it online!](https://tio.run/##RY9Pb8IwDMXv@RRWL9gay@AKCpy2204cSzWFkJSU/GFJN4HGPnuXdpN2en5@P1t2Jz9lVsle@scQj3owYvBi47mXF0xik7hxsn8tBt/mVxqTHL1GTPNbccsnVCLV14bud1/fHkQ9vzbNdrEqphFL2qpV3RANSb9/2KRxZvKMeNLy@GKd3t2CwgXxPu76ZEOLxPPF2R6rfdiHiriJ6VmqE2YQG/hiAB4E5H@oIOOdU1xzznND60IlXTpg0E9OxZCj09zFFkvy@9k4kXgXbcCqIvqrxo3wAJOu2TcNEg6g4AigmTHQti2cwDLoOjifwTnH2EQUOShWMFagHw "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 46 bytes ``` +`(?<=(.)*) (.*¶(?<-1>.)*(?(1)$))(\S) $3$2 ``` [Try it online!](https://tio.run/##Dce5DYAwEATA/KrYwMGdEUhAylMEKQG/8SMCRG0UQGPGk829P/aaY8wm7puWC9ECLvT3puZll849l6JEeByEVK0qECjGGQtWbMBOxwFjDE5YgnPwHiGEHw "Retina 0.8.2 – Try It Online") Takes space-padded input. Note: Lines 2 and 3 end in a space. Explanation: ``` (?<=(.)*) (.*¶(?<-1>.)*(?(1)$))(\S) $3$2 ``` Find a space above non-whitespace and exchange the two. ``` +` ``` Repeat until no more exchanges can be made. ``` ``` Delete the remaining spaces. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` WS⊞υιF²≔E§υ⁰◨Φ⭆υ§μλ›μ Lυυυ ``` [Try it online!](https://tio.run/##Nc1BCsIwFATQfU4xuPqBCuK2q26UgkLRE8Q2TdLGtKSJevuYIC7n8@ZPr4XvF2FTemtjJah1awz34I1TxDm6uGmKFQyv2bh40JGj2TajHF3FSk1o3SA/RRx4hU4MN6N0oJOxQXr6/Skwg799VrA847OXoqCcd9iVy0U6FfIcLyHmxS7XQ851SgIP9BgAycYRSiloGIZpwjzDWsvS/mW/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as newline-terminated space-padded list of strings. Explanation: ``` WS⊞υι ``` Input the strings. ``` F² ``` Repeat twice. ``` ≔E§υ⁰◨Φ⭆υ§μλ›μ Lυυ ``` Transpose the array, filter out the spaces, then right-pad back to the original length. ``` υ ``` Output the final result. [Answer] # JavaScript (ES10[note](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sort_stability)), 76 bytes ``` a=>(g=a=>a[0].map((c,i)=>a.map(l=>l[i]).sort((x,y)=>(y>' ')-(x>' '))))(g(a)) ``` [Try it online!](https://tio.run/##TY7PbsMgDMbvPIVvGK1Fu0fktqdII5WmgZIQggiqiKY9e@aklTYf/PnPz/I36KdeuuRiPi/R3fs0zWHs182oTasaraKsm89WTjoidicnqD8ar2rfuFbIZU4ZsZxWWuFac@DijOVQCrSohdgquDINN@jgDtAzY8BaCw9wDIYBxhG89@xFkNw6RhgjiF1lTm5CehO9y8gv4RK4kGZOX7p7YAZVwzcDiMmFjAbzH0jYbrTsSCOlLK34NylymF1ATi7f1X7xceSK/Yhq@wU "JavaScript (SpiderMonkey) – Try It Online") Just noticed that [this Python answer](https://codegolf.stackexchange.com/a/226795) by [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) used the same algorithm. You may upvote that one. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` TmfIT ``` [Try it online!](https://tio.run/##yygtzv7/qKnx0Lb/IblpniH///9PVEhSSFZIUVBI5UpLU0hPT1fIUMjkUsjKUsjOVsjJyQEA "Husk – Try It Online") same as jelly [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes ``` a=PadRight[#/." "->Nothing]/. 0->" "&;a@a@#& ``` [Try it online!](https://tio.run/##TYyxTsMwFEX3fsWVI0Ug0ZY9amWpohILqghbnOHFSWy3iV2F1wkxM/KpfEIwzsJ23r33nZHYdiOx0zT32OFupt2J2ldnLFfZz/fXdiMg1vuXwNZ5U283eFzvY5QXJElm@XxfrEx8fAslT3FRZQ949tcbH8M01siLVanJV6fYsTSyl0/ahuPNa3bBV6aWB0sTae6md7kYyuvg@E8jlBfRUMsPQWig0QKd8n0PYwwsnPI4n3G5YBgGEfdplSA2yidEuhPFCImoieVSNFr5Nllh/gVYgs9i/gU "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a space-padded matrix of characters and returns the squashed matrix. This function uses the relatively straightforward algorithm: transpose, remove spaces, pad with spaces, and repeat once more. The Unicode character is U+F3C7 for `\[Transpose]`. Note that without the space, the `ReplaceAll` expression would be parsed as `/ .0 -> " "`. ]
[Question] [ Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input. ## Input A string of printable standard ascii characters. Input should not be assumed to be all lowercase. Input will always be at least one character. ## Output Every permutation of uppercase and lowercase for the inputted string (no duplicates). This should only change characters with a small and large version (numbers will stay the same). Each permutation must be output as a string or a list of characters; lists of singleton strings are not allowed. ## Examples ``` a1a ['a1a', 'a1A', 'A1a', 'A1A'] abc ['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC'] Hi! ['hi!', 'hI!', 'Hi!', 'HI!'] ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. As a fun extra see how much additional effort it will take to handle the extended ascii characters, here is an extra test case: ``` ž1a -> ['ž1a', 'ž1A', 'Ž1a', 'Ž1A'] ``` (your program does not need to support this) [Answer] # Pyth, ~~13~~ ~~12~~ 11 ``` {msrVQd^U2l ``` 1 byte thanks to Leaky Nun! Another byte thanks to Jakube! [Try it here](http://pyth.herokuapp.com/?code=%7BmsrVQd%5EU2l&input=%22ab1c%22&debug=0) or run a [Test Suite](http://pyth.herokuapp.com/?code=%7Bms.nd%2aFrRR2&input=%22ab1c%22&test_suite=1&test_suite_input=%22a1a%22%0A%22abc%22%0A%22Hi%21%22%0A%22%C5%BE1a%22&debug=0) We create a list of lists True/False values by taking the cartesian product of the list `[0, 1]` with itself a number of times equal to the length of the input string. So each of the sublists has the same length as the input string. Then we apply the `r` function as a vector operation over the input and the list, so we get `r letter value` for each sub element. `r` with second argument zero is to lowercase and with one it is to upper case. This creates duplicates on non-letters, which means we need to remove duplicates from the result. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` żŒsŒpQ ``` This is a monadic link (function) that expects a string as left argument and returns a list of strings. Handles non-ASCII characters. [Try it online!](http://jelly.tryitonline.net/#code=xbzFknPFknBRCsOH4oKsRw&input=&args=ImExYSIsICJhYmMiLCAiSGkhIiwgIsW-MWEi) ### How it works ``` żŒsŒpQ Monadic link. Argument: s (string) Œs Swapcase; change the case of all letters in s. ż Zipwith; pair each character with itself with changed case. Œp Take the Cartesian product of all pairs. Q Unique; deduplicate the Cartesian product. ``` [Answer] # Python, ~~74~~ 71 bytes ``` f=lambda s:s and{r[0]+t for r in{s,s.swapcase()}for t in f(s[1:])}or{s} ``` Handles non-ASCII characters. Test it on [Ideone](http://ideone.com/buAQWf). [Answer] # Oracle SQL 11.2, 276 bytes ``` WITH v AS(SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))SELECT w FROM(SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w FROM(SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v)START WITH p=1CONNECT BY PRIOR p=p-1)WHERE LENGTH(:1)=LENGTH(w); ``` Un-golfed ``` WITH v AS ( -- Split input into an array of characters SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1) ) SELECT w FROM ( -- Build every string combination SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w FROM ( -- Merge upper and lower arrays, keep same position for each character, it allows to mix cases SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v ) START WITH p=1 -- Start with first character (either lowercase or uppercase) CONNECT BY PRIOR p=p-1 -- Add the next character (either lowercase or uppercase) ) WHERE LENGTH(:1)=LENGTH(w); -- Keep only full strings ``` Ugly as hell, must be more golfable. [Answer] ## 05AB1E, 17 bytes **Code:** ``` vyDš‚N0Êiâvy˜J})Ù ``` **Explained:** ``` vy # for each character in input Dš‚ # create a pair of different case, eg: ['ž', 'Ž'] N0Êiâ # for all pairs but the first, take cartesian product result will be a list of layered lists eg: [['ž', '1'], 'a'] vy # for each such list ˜J} # deep flatten and join as a string eg: ž1a )Ù # wrap in array and remove duplicates ``` [Try it online](http://05ab1e.tryitonline.net/#code=dnlExaHigJpOMMOKacOidnnLnEp9KcOZ&input=xb4xYQ) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~25~~ 22 bytes ``` :ef:1fd. :2ac. @u.|@l. ``` This works as well as the lowercase/uppercase predicates of Prolog, therefore it works on non-ASCII letters too: ``` ?- run("ž1a",Z). Z = ["Ž1A", "Ž1a", "ž1A", "ž1a"] . ``` ### Explanation Unlike all other answers as of the moment I'm posting this, this does not use the cartesian product approach at all. * Main Predicate ``` :ef Split the Input string into a list of 1-char strings :1f Find all valid outputs of predicate 1 with the previous list of outputs as input d. Unify the Output with that list excluding all duplicates ``` * Predicate 1 This is used to apply uppercasing or lowercasing on each char of the input, thus computing one possible permutation. Using findall on this predicate in the main predicate allows to compute all possible permutations (with some duplicates). ``` :2a Apply predicate 2 on the each element of the Input c. Unify the Output with the concatenation of the elements of the previous list ``` * Predicate 2 This is used to turn a character of the string into either its uppercase or its lowercase version. ``` @u. Unify the Output with the uppercase version of the Input | Or @l. Unify the Output with the lowercase version of the input ``` [Answer] ## Haskell, ~~69~~ 58 bytes ``` import Data.Char mapM(\x->toLower x:[toUpper x|isAlpha x]) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzzkjsYgrzTY3scBXI6ZC164k3ye/PLVIocIquiQ/tKAAxKzJLHbMKchIVKiI1fyfm5iZp2CrANIQr6BRUJSZV6KXpqkQrZSYpKSjlGgIJpyMlGL/AwA "Haskell – Try It Online") Edit: @Angs saved 11 bytes. Thanks! [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` tYov!Z}N$Z*Xu ``` [**Try it online!**](http://matl.tryitonline.net/#code=dFlvdiFafU4kWipYdQ&input=J2ExYSc) ### Explanation ``` t % Implicit input string. Duplicate Yo % Change case of string v % Concatenate as a 2xN char array, where N is input length ! % Transpose: Nx2 char array. Each row has different case, if letter Z} % Split into rows: gives N strings of 2 chars. Each char has different % case if it's a letter, or is repeated otherwise N$ % Specify N inputs for next function Z* % Cartesian product of the N strings. Each combination is a row. % Repeated chars (i.e. non-letters) give rise to duplicate rows. Xu % Remove duplicate rows. Implicit display ``` [Answer] ## JavaScript (Firefox 30-57), ~~92~~ 90 bytes ``` f=([c,...s])=>c?[for(t of f(s))for(d of new Set(c.toUpperCase()+c.toLowerCase()))d+t]:[''] ``` Edit: Saved 2 bytes because `new Set` will happily extract the unique characters from a string. [Answer] # [Perl 6](http://perl6.org), 37 bytes ``` {[X~] '',|.comb.map:{unique .lc,.uc}} ``` [Try it](https://tio.run/##XVDLTsMwELznKyYiIolIXfXSQ0sj3F7aOwckhJBjDLXIi9iuqEr4s3Lrd4Vt03Lg4p3Z2fGsXasmH3dXPobONMNMl0NVblAfu57njMJmzOT0hO6VsVPPK7a4lsKoAQ0VzgqrqxKzbvf48P2EMEy@mKyKjBWinuxcqT@cAstlwpxs247Md5buMZgh8oBQjESIWYpbAhAjDk6Vj3ianNRMntVMQmQLiDnV@QKcOCfOifP5op9ear@fXmsf65UPamC58nv18HOJOiLQwXHYH9H@FBfT2@pclLjpNyT6WjWXdQcpgmdEk3e1jQJd1s7GyWQjcqeiQH3WSlr1EsfYUZI2@P8/FwszVWMT/DnOnL1pY722@wU "Perl 6 – Try It Online") ### Explanation: ``` { [X[~]] # cross combine using &infix:<~> operator '', # empty string so that 1 character strings work | # flatten the following into outer list .comb # get every character from input string .map: # and map it with: { unique .lc, .uc } } ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my &case-permutation = {[X~] '',|.comb.map: {unique .lc,.uc}} my @tests = ( 'a1a' => <a1a a1A A1a A1A>, 'abc' => <abc abC aBc aBC Abc AbC ABc ABC>, 'Hi!' => <hi! hI! Hi! HI!>, 'ž1a' => <ž1a ž1A Ž1a Ž1A>, ); plan +@tests; for @tests -> $_ (:key($input),:value($expected)) { is case-permutation($input).sort, $expected.sort, .gist } ``` ``` 1..4 ok 1 - a1a => (a1a a1A A1a A1A) ok 2 - abc => (abc abC aBc aBC Abc AbC ABc ABC) ok 3 - Hi! => (hi! hI! Hi! HI!) ok 4 - ž1a => (ž1a ž1A Ž1a Ž1A) ``` [Answer] # Julia, ~~66~~ 60 bytes ``` !s=s>""?[~s[1:1]t for~=(ucfirst,lcfirst),t=!s[2:end]]∪[]:[s] ``` [Try it online!](http://julia.tryitonline.net/#code=IShzKT1zPiIiP1t-c1sxOjFddCBmb3J-PSh1Y2ZpcnN0LGxjZmlyc3QpLHQ9IXNbMjplbmRdXeKIqltdOltzXQoKZm9yIHMgaW4gKCJhMWEiLCAiYWJjIiwgIkhpISIpCiAgICBkaXNwbGF5KCFzKQogICAgcHJpbnRsbigpCmVuZA&input=) [Answer] # Python, 69 bytes ``` import itertools as i;f=lambda s:set(i.product(*zip(s,s.swapcase()))) ``` [Answer] ## Actually, 28 bytes ``` ;╗l2r∙`"'Ö*£"£M╜@Z"iƒ"£MΣ`M╔ ``` [Try it online!](http://actually.tryitonline.net/#code=O-KVl2wycuKImWAiJ8OWKsKjIsKjTeKVnEBaImnGkiLCo03Oo2BN4pWU&input=ImExYyI) This program can handle non-ASCII characters, thanks to the magic of Python 3. Explanation: ``` ;╗l2r∙`"'Ö*£"£M╜@Z"iƒ"£MΣ`M╔ ;╗ save a copy of input to reg0 l length of input 2r [0,1] ∙ Cartesian product with self (length of input) times ` `M map: "'Ö*£"£M push `Ö` (swapcase) if 1 else `` for each value in list ╜@Z zip with input "iƒ"£M swap the case of those values Σ join string ╔ unique elements ``` [Answer] ## C ~~229~~ 252 bytes ``` i,n,j,k,l;f(char *s){l=strlen(s);for(i=0;i<l;i++)s[i]=tolower(s[i]);int v[l];for(i=0;i<l;i++)v[i]=0;for(i=0;i<pow(2,l);i++){n=i,k=0;for(;n;k++){v[k]=n;n/=2;}for(j=0;j<l;j++){v[j]%=2;if(v[j])s[j]=toupper(s[j]);else s[j]=tolower(s[j]);}printf("%s ",s);}} ``` Ungolfed version: ``` void f(char *s) { int i,num,k,l=strlen(s); for(i=0;i<l;i++) s[i]=tolower(s[i]); int v[l]; for(i=0;i<l;i++) v[i]=0; for(i=0;i<pow(2,l);i++) { num=i,k=0; for(;num;k++) { v[k]=num; num/=2; } for(int j=0;j<l;j++) { v[j]%=2; if(v[j]) s[j]=toupper(s[j]); else s[j]=tolower(s[j]); } printf("%s \n",s); } } ``` Explanation: * Accept the character string, convert the string to lowercase. * Declare integer array of length equal to that of the string. Fill it with zeroes. * Store the numbers from 0 to `2^strlen(s)`in binary form in an `int` array.( For a 3 byte string: 000,001,010...111) * Depending on if a bit at a position is set or, toggle the case. * Output the string for every possible combination. [Try it online!](https://tio.run/nexus/bash#ZZDNboMwEITvPMWKNIppnN@rQ14EcUCOgQXHtmyHqIp4dmqTVGnV2@w3o9XsCt5qWCULVFzeLuLk/AX1tj3DG10r3wbyBtx/GfGHOG9RNRFNSBXtaE8lqwlvKwufLnvIPCSkUMRlrNaWYL5neJIM1@vMFVjmXkt9F5bEIWOoPAyFLP9lh5jd/8JG38mRymx2HypH2r98plgf2VD0Za6Y2uVHNkajC4Eu7Oueblcug4M1iTKU6WKZmzFzmUCYkE7Ai/@UjHw04WZfk3TpIKXhsHGcYvFrhYpEUdmGU3j@IOihKLMH1GSWh7AAwAp/swr2bGTJCs5grG62PGk4h42epxeCjbwm291M0o9DOk3KVc6gcN8 "Bash – TIO Nexus") [Answer] ## [Hoon](https://github.com/urbit/urbit), 242 bytes ``` |= t/tape =+ l=(reap (pow 2 (lent t)) t) %+ roll (gulf 0 (dec (lent l))) |= {a/@ b/(set tape)} =+ %+ turn (gulf 0 (dec (lent t))) |= n/@ =+ t=(snag n t) =+ k=(trip t) ?: =(0 (cut 0 n^1 a)) ?: =((cuss k) t) (cass k) (cuss k) t (~(put in b) -) ``` Ungolfed: ``` |= t/tape =+ l=(reap (pow 2 (lent t)) t) %+ roll (gulf 0 (dec (lent l))) |= {a/@ b/(set tape)} =+ %+ turn (gulf 0 (dec (lent t))) |= n/@ =+ t=(snag n t) =+ k=(trip t) ?: =(0 (cut 0 n^1 a)) ?: =((cuss k) t) (cass k) (cuss k) t (~(put in b) -) ``` I'm not sure how much smaller this could be, unfortunately. First, we set `l` equal to a list with 2^(length t) repetitions of `t`. Hoon doesn't have a `fac` function in the stdlib, but 2^n is always bigger than n!, so we simply map over the bigger list and use a `set` (hashmap) to de-duplicate entries. We then fold over the list [0..(length l)], accumulating into a `(set tape)`. We need to do this instead of mapping over `l` directly because we also need to know what number repetition it is (`a`), but can't simply increment an accumulator due to Hoon being a pure language. We map over [0..(length t)] (again so we have the current index), setting `t` to the nth character in the string, checking if the nth bye of `a` and inverting the case (cuss or cass, depending if it changes or not). The return type of this map is a `tape`. We then put the string into our hashmap, and return the hashmap of all the strings. [Answer] # C, 216 bytes ``` k,i,j,p,n,m;z(char *c){n=-1;m=0;while(c[++n])if(c[n]>64&c[n]<90)c[n]+=32;else if(c[n]<'a'|c[n]>'z')m++;k=1<<(n-m);for(j=0;j<k;j++){for(i=0;i<n;i++){p=1<<i;putc((j&p)==p?toupper(c[i]):c[i],stdout);}putc(0xa,stdout);}} ``` This is ~~a different approach~~, the **same** approach as the other C answer. Should I delete this, and put it under the other answer as a comment? Let me explain with the **Ungolfed version** ``` k,i,j,p,n,m; z(char * c) { int n=-1; // We start at -1 because of forward incrementation int m=0; // this will count the characters we don't have to manipulate while(c[++n]) // go until we reach '\0' { if(c[n]>='a'&c[n]<='z')c[n]-=32; // If we are lower case, then convert else if(c[n]<'A'|c[n]>'Z')m++; // If we are neigther lower case // nor upper, then make a note } // get 2 ^ ("length" - "number of invonvertibles") k=1<<(n-m); for(j=0;j<k;j++) { // go through the combinations for(i=0;i<n;i++) { // for each combination go though the characters p=1<<i; // for each character get it's bit position putc( // if the bit position is set (==1) (j&p)==p ? tolower(c[i]) // convert : c[i], // else: don't stdout); } putc(0xa, stdout); // print a newline } } ``` [Answer] # Python3, 96 bytes ``` i=input().lower() for l in{*__import__('itertools').product(*zip(i,i.upper()))}:print(*l,sep='') ``` Late to the party but still had a go. Thanks to DLosc for reminding me of the stuff I missed, giving me golfing tips and saving me a bunch of bytes. :) [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` ""<>#&/@Union@Tuples[{#,ToUpperCase@#}]&@*Characters ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KCloPFfScnGTllN3yE0LzM/zyGktCAntTi6WlknJD@0oCC1yDmxONVBufZ9f3usmoOWc0ZiUWJySWpR8X9NBX0HhWqlRMNEJR0FpcSkZBCVkamoVPsfAA "Wolfram Language (Mathematica) – Try It Online") `` is the transpose operator (and displays as a superscript **T** in Mathematica). [Answer] # [Perl 5](https://www.perl.org/), 52 + 1 (`-n`) = 53 bytes ``` @k{glob s/./lc("{$&,").uc"$&}"/ger}++;say for keys%k ``` [Try it online!](https://tio.run/##K0gtyjH9/98huzo9Jz9JoVhfTz8nWUOpWkVNR0lTrzRZSUWtVkk/PbWoVlvbujixUiEtv0ghO7WyWDX7///EpOR/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online") [Answer] # Tcl, 165 ~~181~~ bytes ``` set n -1 while {[incr n]<1<<[llength [set s [split $argv {}]]]} {puts [join [lmap c $s b [split [format %0[llength $s]b $n] {}] {string to[expr $b?{u}:{l}] $c}] ""]} ``` Improvements thanks to **sergiol**. Previous answer: ``` set s [split $argv {}] set n -1 while {[incr n]<1<<[llength $s]} {set r "" foreach c $s b [split [format %0[llength $s]b $n] {}] {set r $r[string [expr $b?{tou}:{tol}] $c]} puts $r} ``` Uses a binary number to choose between upper/lower case when creating the output text. [Answer] ## [Perl 5](https://www.perl.org/), 30 bytes ``` s/\pl/{\l$&,\u$&}/g;say<"$_ "> ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP6YgR786JkdFTSemVEWtVj/dujix0kZJJV5Bye7//0TDRK7EpGSujEzFf/kFJZn5ecX/dfNy/uv6muoZGBoAAA "Perl 5 – Try It Online") Outputs an additional space at the end of the output. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 39 bytes ``` &Cross[Sum@V]##Unique@V#SwapCase=>Chars ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX7X825KL@4ODq4NNchLFZZOTQvs7A01SFMObg8scA5sTjV1s45I7Go@L9fampKcbRKQUFyeixXQFFmXklIanEJSEVxdJqOQjSXAhAoJRomKukAqaRkEOWRqQiiju4DinLFxv4HAA "Attache – Try It Online") Similar to the perl answer. (I've lost my more interesting alternative, I should be posting those in the next few hours.) [Answer] # JavaScript (ES6), 103 Handles non-ASCII characters ``` (a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a] ``` **Test** ``` f=(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a] function test() { O.textContent = f(I.value).join('\n') } test() ``` ``` <input id=I oninput='test()' value='ž1a'> <pre id=O></pre> ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->s{a,*b=s.map{[_1,_1.swapcase]} a.product(*b).uniq} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3TXTtiqsTdbSSbIv1chMLqqPjDXXiDfWKyxMLkhOLU2NruRL1CoryU0qTSzS0kjT1SvMyC2shejcVKLhFRyslKukoGQJxolJsLERiwQIIDQA) ]
[Question] [ [Laguerre polynomials](https://en.wikipedia.org/wiki/Laguerre_polynomials) are nontrivial solutions to Laguerre's equation, a second-order linear differential equation: \$xy''+(1-x)y'+ny=0\$. For a given value of \$n\$, the solution, \$y\$, is named \$L\_n(x)\$. To avoid trivial solutions, the polynomials are non-constant except for \$n=0\$. The polynomials can be found without calculus using recursion: \$L\_0(x)=1\$ \$L\_1(x)=1-x\$ \$L\_{k+1}(x)=\frac{(2k+1-x)L\_k(x)-kL\_{k-1}(x)}{k+1}\$ Summation can be used to the same end: \$L\_n(x)=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k\$ \$L\_n(x)=\sum\limits\_{i=0}^n\prod\limits\_{k=1}^i\frac{-(n-k+1)x}{k^2}\$ The first Laguerre polynomials are as follows: [![polynomials](https://i.stack.imgur.com/LR4kc.png)](https://i.stack.imgur.com/LR4kc.png) Coefficients can be found [here](https://oeis.org/A021010). # The Challenge Given a nonnegative integer \$n\$ and a real number \$x\$, find \$L\_n(x)\$. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. * Assume only valid input will be given. * Error should be under one ten-thousandth (±0.0001) for the test cases. # Test Cases Here, \$n\$ is the first number and \$x\$ is the second. ``` In: 1 2 Out: -1 In: 3 1.416 Out: -0.71360922 In: 4 8.6 Out: −7.63726667 In: 6 -2.1 Out: 91.86123261 ``` [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` f=lambda n,x:n<1or((2*n-1-x)*f(n-1,x)-~-n*f(n-2,x))/n ``` [Try it online!](https://tio.run/##TchBCoNADEDRvafIciLJ1EQRKe1hFBkUNIq4GDdefSoFaXf//fXYh8U0pfCe2rnrWzCKT3vJsjmnubFwxDy4Kygin2xf6AV8WFq30XYITgjUF5jdLgnEV1L/TkXQ@D/XBKxeMH0A "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes ``` LaguerreL ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773ycxvTS1qCjV539AUWZeiYJDerSZjq6RnmHs//8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŻṚṀc÷!ƲḅN} ``` A dyadic Link accepting \$n\$ on the left and \$x\$ on the right which yields \$L\_n(x)\$. **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//xbvhuZrhuYBjw7chxrLhuIVOff///zb/LTIuMQ "Jelly – Try It Online")** ### How? This makes the observation that \$L\_n(x)=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k=\sum\limits\_{k=0}^{n}{(-x)^k}\frac{n\choose k}{k!}\$ which is the evaluation of a base \$-x\$ number with n+1 digits of the form \$\frac{n\choose k}{k!}\$. ``` ŻṚṀc÷!ƲḅN} - Link: n, x Ż - zero-range (n) -> [0, 1, 2, ..., n] Ṛ - reverse -> [n, ..., 2, 1, 0] Ʋ - last four links as a monad - f(I=that): Ṁ - maximum -> n c - {that} binomial (I) -> [nCn, ..., nC2, nC1, nC0] ! - {I} factorial -> [n!, ..., 2!, 1!, 0!] ÷ - division -> [nCn÷n!, ..., nC2÷2!, nC0÷0!] N} - negate right argument -> -x ḅ - convert from base (-x) -> -xⁿnCn÷n!+...+-x²nC2÷2!+-x¹nC1÷1!+-x°nC0÷0! ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` _1iZh ``` Inputs are \$n\$, then \$x\$. [Try it online!](https://tio.run/##y00syfn/P94wMyrj/39jLkM9E0MzAA) Or [verify all test cases](https://tio.run/##y00syfmf8D/eMDMq479LyH9DLiMuYy5DPRNDMy4TLgs9My4zLl0jPUMA). ### How it works This uses the [equivalence](https://en.wikipedia.org/wiki/Laguerre_polynomials#Relation_to_hypergeometric_functions) of Laguerre polynomials and the (confluent) hypergeometric function: \$ L\_n(x) = {} \_1F\_1(-n,1,x) \$ ``` _ % Implicit input: n. Negate 1 % Push 1 i % Input: x Zh % Hypergeometric function. Implicit output ``` [Answer] # JavaScript (ES6), ~~48 42~~ 41 bytes Expects `(x)(n)`. May output [**true** instead of **1**](https://codegolf.meta.stackexchange.com/a/9067/58563). ``` x=>g=k=>k<1||((x-k---k)*g(k)+k*g(k-1))/~k ``` [Try it online!](https://tio.run/##ZclLCoNAEEXReVZST6mWUpEM0u5F/DRaYouG4EDcemuG4ujCuUP1q9Z66ecvT75pQ2fDZktn1Zb6kX0n2liZWRE5UsT6DwuQHBpqP61@bM3oHXWUgi5/3VFMLgUoe4y3uTh/MKdGQAUQTg "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes ``` L=lambda n,x:((2*n-1-x)*L(d:=n-1,x)-d*L(n-2,x))/n if n>1else 1-n*x ``` [Try it online!](https://tio.run/##TchBCoMwEEDRfU@R5UyYSZkoIoKeIJewxFLBToN1kZ4@ZlNw999Pv@P10aZPeylh3Ob3I85GKQ8A3ioLZ7QB4jDWpowcq5R9TbyrWZ9GJ1m272KE1eaS9lUPCCDkEW9/NSSule5yWurd1R2xd4JYTg "Python 3.8 (pre-release) – Try It Online") Direct implementation of the recursive algorithm, with one interesting part: `L(1,x)` and `L(0,x)` can be combined as `L(n,x)=1-n*x`. Could save 2 bytes using `L=lambda n,x:n>1and((2*n-1-x)*L(d:=n-1,x)-d*L(n-2,x))/n or 1-n*x`, but `L(n)` is not necessarily zero. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS) ``` 1⊥⍨0,⎕×(-÷⌽×⌽)⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b/ho66lj3pXGOg86pt6eLqG7uHtj3r2Hp4OJDQf9W4GCoKU/edM4zLkMuICUsZchnomhmYgpgmXhR6YYcZ1aL2RniEA "APL (Dyalog Unicode) – Try It Online") A full program that takes `n` and `x` from two separate lines of stdin. ### How it works ``` 1⊥⍨0,⎕×(-÷⌽×⌽)⍳⎕ ⍳⎕ ⍝ Take n and generate 1..n (-÷⌽×⌽) ⍝ Compute i÷(n+1-i)^2 for i←1..n 0,⎕× ⍝ Multiply x to each and prepend 0, call it B 1⊥⍨ ⍝ Convert all ones from base B to single number ``` The mixed base conversion looks like this: ``` 1..n: ... n-3 n-2 n-1 1 B: 0 ... (n-3)x/4^2 (n-2)x/3^2 (n-1)x/2^2 nx digits: 1 ... 1 1 1 1 digit values: x^n/n! ... (nC3 x^3/3!) (nC2 x^2/2!) (nC1 x^1/1!) (nC0 x^0/0!) ``` It is essentially a fancy way to write the sum of product scan over `1, nx, (n-1)x/2^2, (n-2)x/3^2, ...`. This happens to be shorter than a more straightforward `-x`-base conversion (evaluating a polynomial at `-x`): # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://github.com/abrudz/SBCS) ``` (-⎕)⊥⌽1,(!÷⍨⊢!≢)⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@G7qO@qZqPupY@6tlrqKOheHj7o94Vj7oWKT7qXKT5qHczUBak8D9nGpchlxEXkDLmMtQzMTQDMU24LPTADDOuQ@uN9AwB "APL (Dyalog Unicode) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 61 bytes ``` L=lambda k,x:k<1or[1-x,L(w:=k-1,x)*(k+w-x)-L(k-2,x)*w][k>1]/k ``` [Try it online!](https://tio.run/##HYxBCsIwEADvvmKPiW4im5ZSgvUF@UHpoSJiWZuEUEh8fWy9DQMz8bu9g2/6mGp1w2deH88ZGIvlG4U0kiroRLYDK8Iiz4IvWRWpnGBlDpGnke80Xbm@QtpDKLB4EIRgJIJoEEi31B3cIvT6Tx2CMpqkPQHEtPhN7L89lbL@AA "Python 3.8 (pre-release) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` x=>(i=0,g=n=>n?1-x*n/++i/i*g(n-1):1) ``` [Try it online!](https://tio.run/##ZclNCoMwEAbQvSeZT5voWBERxp5F/AkRmZQq4u2j2@L2vaU/@m34@e9uNIxTnCWe0pGX4uVEpdMPmzPVPMt87lNHahgtIw5Bt7BOdg2OZipBDCT/yLbiGvR@RGNvrh5sSsugGogX "JavaScript (Node.js) – Try It Online") Just convert the formula to this, and use recursive: $$ L\_n(x) = \sum\_{i=0}^n\prod\_{k=1}^i\frac{-(n-k+1)x}{k^2} $$ [Answer] # [J](http://jsoftware.com/), 37 20 bytes *-5 thanks to @Bubbler* Calculates the polynomial adapted from the summation formula and uses J's `p.` operator to calculate that polynomial with a given x. ``` (p.-)~i.((!]/)%!)@,] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQr0dDXrMvU0NBRj9TVVFTUddGL/K/g56SlwFejBxbXiDdXiIJJcqJI2Vg7K2KUxJDP1HOysuDT/KwCBkYKGjnWapoIhl6GeiaEZlGfMpaBgoQfjmXApxBvpGUJ5ZgA "J – Try It Online") # [J](http://jsoftware.com/), 45 byte Alternative Recursive function. ``` 1:`-@.[~ ::((>:@]%~($:*[-~1+2*])-]*($:<:))<:) ``` [Try it online!](https://tio.run/##Nce9CoMwFIbhPVfxIS3mpObgSUXK6Q@C4OTkKkEnh15Ebj3NYF94h@ebK64PvBU1GrTQsmeMyzxl0d0PvCaoWvvRIV6TvahbfZJbcJF8dMUvJSpnyigF2OZ5EMQId9KfuhvgwX91BltgOdX/AA "J – Try It Online") ### How it works We define a hook `(fg)`, which is `x f (g n)`. `f` is `(p.-)~` so it will be evaluated as `((i.((!]/)%!)@,]) n) p. (- x)`. ``` (p.-)~i.((!]/)%!)@,] i. @,] enumerate 3 -> 0 1 2, append 3 -> 0 1 2 3, … (!]/) 3 over i % divided by ! !i - negate x p. apply -x to the polynomial expressed in J as 1 3 1.5 0.166667, so 1-3(-x)+1.5(-x)^2+0.16(-x)^3 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes Using the formula \$L\_n(x)=\sum\_{k=0}^n \binom{n}{k}\frac{(-1)^k}{k!} x^k\$. ``` l(n,x)=sum(k=0,n,n!*(-x)^k/(n-k)!/k!^2) ``` [Try it online!](https://tio.run/##HcfBCoMwDADQX0k9JSOpayeyi/6IVAg7DGlXitvAfX2n3t4rui7yLLUmzLzR8P6@MA5XzpzNBWWjObaYJZJpo5k9VS0l/VBBRijrkj87myMNPDQlTAxKxDBNjsGHHTcGZzvXH@4Y7vZUzyDeuhCo/gE "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes Using the generating function \$\sum\_{n=0}^\infty x^n L\_n(t)= \frac{1}{1-x} e^{-xt/(1-x)}\$. ``` l(n,t)=Vec(exp(-x*t/(1-x)+O(x^n++))/(1-x))[n] ``` [Try it online!](https://tio.run/##JcfBCsIwDADQXwk7JTatZI7hxf3Cbl5KhTKGDEoJo4f69XXT23sa982@tbWEmQs9nuuCa1W09VKuKLaSmbG@sjFE/5PPoUXV9MEIdgLdt1wOdmc6WGJKmBgiEYP3wtCHAzcGcYOMpweGu/tpZLC9kxCofQE "Pari/GP – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ⊞υ¹FN⊞υ×⌈υLυI↨Eυ∕⌈υ×ιX§⮌υκ²±N ``` [Try it online!](https://tio.run/##XY7NDoIwEITvPkWP2wRM4ODFkz8XEiWN8QUqrNBAW9If5O3rEuNBD5s9zHwz0/TSNVaOKYnoe4gZK/h@87SOQWWmGOqoH@iAc/bV70qjh6tclI4aIs/YBU0XSOOcUOGUCXCSPsBReiTjtFJnNasWf7BPkMqYsC@qOITKtLjADWd0BK6Wga6kWHo1djLg36i1MaUdy8ttkfJ5fAM "Charcoal – Try It Online") Link is to verbose version of code. Uses a slightly modified version of the summation given in the question. Explanation: ``` ⊞υ¹FN⊞υ×⌈υLυ ``` Calculate the factorials from \$0!\$ to \$n!\$. ``` I↨Eυ∕⌈υ×ιX§⮌υκ²±N ``` For each index \$i\$ from \$0\$ to \$n\$ calculate \$\frac{n!}{i!(n-i)!^2}\$ and then perform base conversion from base \$-x\$ which multiplies each term by \$(-1)^{n-i}x^{n-i}\$ and takes the sum. If we set \$k=n-i\$ we see that we calculate \$\sum\limits\_{k=0}^{n}{\frac{n!(-1)^k}{(n-k)!k!^2}x^k}=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k\$ as required. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~28~~ ~~27~~ 26 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò@l *VpX /Xl ²*JpX /(U-X l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8kBsICpWcFggL1hsILIqSnBYIC8oVS1YIGw&input=NgotMi4x) # [Japt](https://github.com/ETHproductions/japt), ~~30~~ ~~29~~ 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò x@l *VpX /Xl ²*JpX /(U-X l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8iB4QGwgKlZwWCAvWGwgsipKcFggLyhVLVggbA&input=NgotMi4x) ## Explanation ``` ò x@l *VpX /Xl ²*JpX /(U-X l ò // Create a array [0, 1, ..., U] x // sum the array after mapping through @ // Function(X) l // U! *VpX // times V ** X /Xl ² // divided by X! ** 2 *JpX // times (-1) ** X /(U-X l // divided by (U - X)! ``` * `U` is the first input * `V` is the second input * `**` represents exponentiation * `!` represents factorial [Answer] # [C (gcc)](https://gcc.gnu.org/), 91 bytes ``` i;k;float f(n,x)float x;{float p,s=0;for(i=++n;k=i--;s+=p)for(p=1;--k;)p*=(k-n)*x/k/k;x=s;} ``` [Try it online!](https://tio.run/##dclBCoMwEEDRfU8hQiFjMmqsSGGYm3QjQkpIG4O6CIhnTytudff5b8D3MKRkyZH5jP2SGeFVhKMjrUcENXNNZpyEZSk9ObaINEsOsM/AmhAdQShYOPRQxMpVjiLPtKVvb72A9ZZlYbJ@MSK/m5fPlRG1akoAOhF9KY3SF/L4S6u7c2zVs7ygTmFT6t229AM "C (gcc) – Try It Online") Straighforward implementation of polynomial expansion. Slightly golfed less ``` i;k; float f(n,x)float x;{ float p,s=0; for(i=++n;k=i--;s+=p) for(p=1;--k;) p*=(k-n)*x/k/k; x=s; } ``` [Answer] ## [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~69~~ 68 bytes ``` read*,n,a print*,sum([(product([((j-n-1)*a/j/j,j=1,i)]),i=0,n)]) end ``` *-1 byte thanks to @ceilingcat* The program reads in an implicit integer n and real a. Summation and product operations are performed using arrays (initialized using implicit loops) with the intrinsics sum() and product(). [Try it online!](https://tio.run/##JcaxCoAgEADQva9oVDkzG9r8kmiQ1FDolEu/34Te9EKmShblHf70Tt46AQh2KhSxCnjbww5WKLt21TGWJErNhVVJJUhGQ@Qnh2hWwJHJo@t9n@W26A8 "Fortran (GFortran) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` DÝR©c®!/I(β ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/207067/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f/f5fDcoEMrkw@tU9T31Di36f9/Yy5DPRNDMwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@Xw3ODDq1MPrROUT9C49ym/zr/o6MNdYxidaKNdQz1TAzNgCwTHQs9EG2mo2ukZxgbCwA). **Original 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` 1λèN·<I-₁*N<₂*-N/ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f8Nzuwyv8Dm238dTV8rN51NSkpeun//@/MZehnomhGQA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKSfUxC6H/Dc7sPr/A7tN0mQvdRU6OWn82jpiYtXT/9/7U6XCDFXOUZmTmpCkWpiSkKmXlcKflcCgr6@QUl@hAzoRSaNTYKKmC1ean/ow11jGK5oo11DPVMDM2ALBMdCz0Qbaaja6RnGMsFAA). **Explanation:** ``` D # Duplicate the first (implicit) input-integer `n` Ý # Pop one, and push a list in the range [0,n] R # Reverse it to range [n,0] © # Store this list in variable `®` (without popping) c # Get the binomial coefficient of `n` and each value in this list ®! # Push list `®` again, and get the factorial of each / # Divide the values at the same positions of the two lists I( # Push the second input `x`, and negate it β # Convert the list from base-(-x) to a single decimal value # (which is output implicitly as result) ``` --- Uses the recursive formula: $$a(n)=\frac{a(n-1)\times(2n-1-x)-(n-1)\times a(n-2)}{n}$$ ``` λ # Create a recursive environment è # to get the 0-based n'th value afterwards # (where `n` is the first implicit input) # (which will be output implicitly as result at the end) 1 # Starting with a(-1)=0 and a(0)=1, # and for every other a(N), we'll: # (implicitly push a(N-1)) N· # Push `N` doubled < # Decrease it by 1 I- # Decrease it by the second input `x` * # Multiply it by the implicit a(N-1) N< # Push `N`-1 ₂* # Multiply it by a(N-2) - # Decrease the a(N-1)*(2N-1-x) by this (N-1)*a(N-2) N/ # And divide it by `N`: (a(N-1)*(2N-1-x)-(N-1)*a(N-2))/N ``` [Answer] # [Scala](https://www.scala-lang.org/), 81 bytes Use the recursive formula of Laguerre Polynomials. --- Golfed version. [Try it online!](https://tio.run/##ZYyxDoIwFEV3vuKNfaStFgkxjQwmLg5Oxsk4FCykBouBmmAI345FneQuJ/fc5La5qtRYZzedOzgoY6Efr7qAgli5t452clc/s0rjj2lv/LQRKEBXrSYkCi0TrMPQayZoh2zit0a@4sIOI8D0eff3RDVlK2HbNOp1PrrG2PKCEk7WOEihD8Dn4a2rLCmIoBDxJeKfXlEQPBbJbIgprPlcJxRYxMXHD8EwvgE) ``` def f(n:Int,x:Double):Double={if(n<1)1 else((2*n-1-x)*f(n-1,x)-(n-1)*f(n-2,x))/n} ``` Ungolfed version. [Try it online!](https://tio.run/##ZY5PC4JAFMTvfoo57sq6tSYSUoegS4dO0Sk6rLaKYWvoBkb42W21f5CHB29@b5g3dSIL2XVlfFaJwVbmGg8HOKkUKdERNtowNBHW5S0uFP0sWA42ILcuLCAoxKBVUSsQ4rsaHoSdhsLto3rJeuXhJX7c7znFBNpGtM77/cV2IbLK6girqpL3w85Uuc6OtsNe5@bb4GqpKTRJic33@ZTSPzxjEDwQ4egQMMz5GIcMns/FwFun7bon) ``` object Main { def f(n: Int, x: Double): Double = { if(n < 1) 1 else ((2*n - 1 - x) * f(n - 1, x) - (n - 1) * f(n - 2, x)) / n } def main(args: Array[String]): Unit = { println(f(1, 2.0)) println(f(3, 1.416)) println(f(4, 8.6)) println(f(6, -2.1)) } } ``` [Answer] # HTML, 1 Byte, Invalidated by newest edit. ``` 0 ``` \$y=0\$ is a solution to the equation stated in the question for all \$x\$ and \$n\$. [Answer] # Jelly, 0 Bytes, invalidated by newest edit [Try it online!](https://tio.run/##y0rNyan8DwQA) Note that \$y=0\$ is a solution for all \$x\$ and \$n\$. Port of [my HTML answer](https://codegolf.stackexchange.com/a/261536/117478). [Thanks to Jonathan Allen for pointing out this port, and also that this might be a polyglot](https://codegolf.stackexchange.com/questions/207034/laguerre-polynomials#comment574720_261536). ]
[Question] [ ## Challenge: **Input:** A positive integer \$n\$ **Output:** Create a list in the range \$[1,n]\$, and join it together to a string (i.e. \$n=13\$ would be the string `12345678910111213`). Now we output a triangle using the prefixes or suffixes of this string, in one of the following four orientations based on the input integer: * If \$n\equiv 0\pmod 4\$, output it in the triangle shape ◣ * If \$n\equiv 1\pmod 4\$, output it in the triangle shape ◤ * If \$n\equiv 2\pmod 4\$, output it in the triangle shape ◥ * If \$n\equiv 3\pmod 4\$, output it in the triangle shape ◢ **Example:** Input: \$n=13\$ Because \$13\equiv 1\pmod 4\$, the shape will be ◤. Here three possible valid outputs: ``` 12345678910111213 11111111111111111 12345678910111213 1234567891011121 2222222222222222 2345678910111213 123456789101112 333333333333333 345678910111213 12345678910111 44444444444444 45678910111213 1234567891011 5555555555555 5678910111213 123456789101 666666666666 678910111213 12345678910 77777777777 78910111213 1234567891 8888888888 8910111213 123456789 999999999 910111213 12345678 11111111 10111213 1234567 0000000 0111213 123456 111111 111213 12345 11111 11213 1234 1111 1213 123 222 213 12 11 13 1 3 3 ``` ## Challenge rules: * As you can see at the three valid outputs above, only the correct shape and using all the digits in the **correct order** is important. Apart from that you're free to use prefixes or suffixes; reverses/reflects; diagonal printing; etc. etc. Any of the six possible outputs for each shape is allowed (see the test case below to see *all* valid outputs based on the shape). This allows languages with rotation builtins to use it, but those without can also use an alternative approach of using the prefixes in the correct size from top-to-bottom, or using the prefixes for two of the shapes but suffixes for the other two shapes. Choosing the most appropriate output options for your language is part of the golfing process. :) * Input is guaranteed to be a positive integer. For \$n=1\$ we simply output `1`. * Any amount of leading/trailing newlines/spaces are allowed, as long as it prints the correct triangle (without vertical nor horizontal delimiters!) somewhere on the screen. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: Input: \$n=5\$ All possible valid outputs: ``` 12345 54321 12345 54321 11111 55555 1234 5432 2345 4321 2222 4444 123 543 345 321 333 333 12 54 45 21 44 22 1 5 5 1 5 1 ``` Input: \$n=6\$ All possible outputs: ``` 123456 654321 123456 654321 111111 666666 12345 65432 23456 54321 22222 55555 1234 6543 3456 4321 3333 4444 123 654 456 321 444 333 12 65 56 21 55 22 1 6 6 1 6 1 ``` Input: \$n=7\$ All possible outputs: ``` 1 1 7 7 7 1 12 21 67 76 66 22 123 321 567 765 555 333 1234 4321 4567 7654 4444 4444 12345 54321 34567 76543 33333 55555 123456 654321 234567 765432 222222 666666 1234567 7654321 1234567 7654321 1111111 7777777 ``` Input: \$n=8\$ All possible outputs: ``` 1 1 8 8 8 1 12 21 78 87 77 22 123 321 678 876 666 333 1234 4321 5678 8765 5555 4444 12345 54321 45678 87654 44444 55555 123456 654321 345678 876543 333333 666666 1234567 7654321 2345678 8765432 2222222 7777777 12345678 87654321 12345678 87654321 11111111 88888888 ``` Input: \$n=1\$ Only possible output: ``` 1 ``` Input: \$n=2\$ All possible outputs: ``` 12 21 12 21 11 22 1 2 2 1 2 1 ``` [Answer] # JavaScript (ES6), ~~93~~ 89 bytes Returns a matrix of characters. ``` n=>[...(g=n=>n?g(n-1)+n:'')(n)].map((d,y,a)=>a.map(_=>y-(n&2)*y--<0?' ':d)).sort(_=>-n%2) ``` [Try it online!](https://tio.run/##LY7NCsIwEITvPsUe1OxqEmzFH6qpJ6@@gBUNra2WupFUhCI@e63i7Rtm4JvSPm2d@uv9odhl5zY3LZt4r7XGwnTEmwJZBTTmSAhCpoO@2TtiJhtpycT2F48mbhTyMKRRo9R6shEgooxI184/vq3iQUjtah9ICCXMJMwlLCQsJQTTQ0/nzm9tekEGE0PquHbVWVeuwNPO9F/8jhJOuP/KO//P5787r0t3Zexu0Z8SFvRO@ETUfgA "JavaScript (Node.js) – Try It Online") Alternate pattern (same size): ``` n=>[...(g=n=>n?g(n-1)+n:'')(n)].map((_,y,a)=>a.map(d=>y-(n&2)*y--<0?' ':d)).sort(_=>-n%2) ``` [Try it online!](https://tio.run/##LY7LCsIwEEX3fsUs1MxoEmzFB9XElVt/wIqG1lZFJ5KKUMRvr1XcnQMXzr24p6uycL4/FPv82BSmYWO3WmssTUu8KpFVRENOhCBk2umbuyPuZS0dGet@mhtbK@R@TINaqeVoJUAkOZGufHjg3ljFvZiaxTaSEEuYSJhKmEmYS4jGu44ufFi77IQMxkLmufLXo776Eg8b033xO0k55e6raPu/Xvjugr74M2N7i/6UsqB3ygei5gM "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = input [... // split the result of ... ( g = n => // ... a call to the recursive function g, taking n n ? // if n is not equal to 0: g(n - 1) // append the result of a recursive call with n - 1 + n // append n : // else: '' // stop recursion and return an empty string )(n) // initial call to g ].map((d, y, a) => // for each digit d at position y in this array a[]: a.map(_ => // for each character in a[]: y - // we test either y < 0 if (n AND 2) is not set (n & 2) // or -y < 0 (i.e. y > 0) if (n AND 2) is set * y-- < 0 // and we decrement y afterwards ? // if the above condition is met: ' ' // append a space : // else: d // append d ) // end of inner map() ) // end of outer map() .sort(_ => -n % 2) // reverse the rows if n is odd ``` ### Shape summary Below is a summary of the base shape (generated by the nested `map` loops) and the final shape (after the `sort`) for each \$n\bmod 4\$: ``` n mod 4 | 0 | 1 | 2 | 3 ----------+-------+-------+-------+------- n & 2 | 0 | 0 | 2 | 2 ----------+-------+-------+-------+------- test | y < 0 | y < 0 | y > 0 | y > 0 ----------+-------+-------+-------+------- base | #.... | #.... | ##### | ##### shape | ##... | ##... | .#### | .#### | ###.. | ###.. | ..### | ..### | ####. | ####. | ...## | ...## | ##### | ##### | ....# | ....# ----------+-------+-------+-------+------- n % 2 | 0 | 1 | 0 | 1 ----------+-------+-------+-------+------- reverse? | no | yes | no | yes ----------+-------+-------+-------+------- final | #.... | ##### | ##### | ....# shape | ##... | ####. | .#### | ...## | ###.. | ###.. | ..### | ..### | ####. | ##... | ...## | .#### | ##### | #.... | ....# | ##### ``` [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes ``` n=0;s='' exec"n+=1;s+=`n`;"*input() K=k=len(s) while k:k-=1;print s[k^n/-2%-2:].rjust(n%4/2*K) ``` [Try it online!](https://tio.run/##Lc1bCoMwEEDR/1mFBMQXqSa1L2VW4BJKi2AD2sgoSaTt6lOl/b@XM39cP5H03fRQaBhjnrCoLUYRqLfqGGUoapthS23N0oHmxcUJNKhxVBTbBF79MKpAV5qv4WwGcoG96jvlXIZcVredeS7WxRSWuUybxK/E/xHVJgSb/Bu9AAl7KOEARzjBGS4gii8 "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes Returns an array of lines. ``` õ ¬å+ zU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI=&code=9SCs5SsgelU=&input=MTM=) Saved 2 bytes thanks to [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). ``` õ ¬å+ zU :Implicit input of integer U õ :Range [1,U] ¬ :Join to a string å+ :Cumulatively reduce by concatenation zU :Rotate clockwise by 90 degrees U times ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ŗ]∑[]⁸[↷ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUwMTU3JXVGRjNEJXUyMjExJXVGRjNCJXVGRjNEJXUyMDc4JXVGRjNCJXUyMUI3,i=MTM_,v=8) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 94 bytes ``` {[o](|(&reverse xx$_/2+.5),|(*>>.flip xx$_/2+1))([\~](my@a=[~](1..$_).comb)>>.fmt("%{+@a}s"))} ``` [Try it online!](https://tio.run/##NYrRCoIwFEDf/YoxTO7NuGFkBKH4H0vEYoPAMdkilLl@fRnRw4HD4YzSDqeoZ5YpVkUvTAsLZFa@pHWSTVPa7Q85lbhbYFvXpIbH@K8FIojruwU9N30lVimI0g7pbvQNv7N@At/4vOmD44ghKmNZSXRmPqFMrYfr58sK4zwJiYLiiL8YPw "Perl 6 – Try It Online") Anonymous code block that takes a number and returns a list of lines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` Nθ≔⭆θ⊕ιηGLLηη⟲⊗θ‖ ``` [Try it online!](https://tio.run/##LYu9CsIwEIB3nyLjBeIgbnYSXAq1iD5BGs8kcL006UXw6WMF1@/HBVtcstRaz0uVsc4TFsi6253XNXqGh5TI/moXyEb17ArOyIJPiFobFbbwlujjE8NpMGpA9hIg/NU9iRWES6oTbUvWP4YvQiegu9YOx7Z/0xc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔⭆θ⊕ιη ``` Create a string by concatenating the numbers `1` to `n`. ``` GLLηη ``` Fill a triangle of that length with the string. ``` ⟲⊗θ ``` Rotate the triangle anticlockwise by `n*90` degrees. ``` ‖ ``` Reflect everything, thus ending up with a triangle that is rotated clockwise by `n*90` degrees. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 128 bytes ``` n=>{var s="";int i=0,j,p;for(;i<n;s+=++i);for(p=j=s.Length;;)Write("{0,"+(n%4>1?p:0)+"}\n",new string(s[--j],-~n%4>1?j+1:p-j));} ``` [Try it online!](https://tio.run/##TY/LasJAGIX3/1OEAWGGXMiv8ZYx6cqC4KK0hS6si2kcdYIdQya2lJC@Rva9vFheJI266fbjcL5zEuMmRrW3J53MlC6cxVyfXmUuXg5yZopc6V0cb6NWR3H5JnLLRITwLmepyHdSJ@PbY065mmlu7Mi2FbuALEoj4y2l3hV7ztlTrgpJSek7xKa6F8R4k4U@s0n1rImj5bt1NVGzct107bif11BqY5i5KWO8ajl0xVIke3qeISylrYX27qXYPB7nekOZ95AdVEFJV8lYWeQf5UW7VFqeYelXVolVeDYKhzT1d1P/NPVvU3@RVXfIuxO5kVSwXrDuTtD/qPMnokj2ZVW1CH0YQABDGMEYJjAF9AERsA84AAwAh4AjwDHgBHAKff8P "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~95~~ ~~82~~ 79 bytes ``` ->n{r=(0...z=/$/=~s=[*1..n]*'').map{|i|" "*n[1]*i+s[0,z-i]};-n&2>0?r:r.reverse} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vushWw0BPT6/KVl9F37au2DZay1BPLy9WS11dUy83saC6JrNGSUFJKy/aMFYrU7s42kCnSjczttZaN0/NyM7AvsiqSK8otSy1qDi19j9Yr4WOoXGsXmpicgZIb1p0JoyTVVNQWlKskFVrDaJr/wMA "Ruby – Try It Online") 3 bytes saved by G B. [Answer] # [R](https://www.r-project.org/), ~~152~~ ~~139~~ ~~137~~ 134 bytes ``` function(n,N=nchar(s<-Reduce(paste0,1:n,'')),A=!n%%4%%3)for(i in 1:N)cat(rep('',(M=c(N-i+1,i))[1+!A]*(n%%4>1)),substr(s,1,M[1+A]),' ') ``` Unrolled code : ``` function(n){ s = Reduce(paste0,1:n,'') # concat the digits from 1 to n into a string s N = nchar(s) # store the length of s A = !n%%4%%3 # A = TRUE if n MOD 4 == 1 or 2 for(i in 1:N){ # for 1 to N (length of s) M = c(N-i+1,i) # store N-i+1 and i into a vector nSpaces = M[1+!A]*(n%%4>1) # if n MOD 4 == 1 or 2 then nSpaces = i else nSpaces = N-i+1, # but if n MOD 4 == 0 or 1, then force nSpaces = 0 nDigits = M[1+A] # if n MOD 4 == 1 or 2 then nDigits = N-i+1 else nDigits = i prfx = rep('',) # create a character vector repeating '' nSpaces times sufx = substr(s,1,M[1+A]) # substring s by taking the first nDigits characters cat(pr,su,'\n') # print prfx and sufx using space as separator for the values # contatenation (cat function default) and append a newline } ``` [Try it online!](https://tio.run/##bY29DoIwFIV3nqIM5N4rl8QGJyImPAAMrsqAtY1dCqEwGZ@9FhMTB894fr4zB1MHszq12NGh46526jHM6I/FWd9XpXEa/KL3LCvHAETc1KnLskOWlWTGGa2wTsiqIzUsOOsJARjbWmFX2FyyJbrIPG36HW6rk4wEv978Ei9YchvDpieGBCj84GRJz0SIjQldBWwZrg4oWgYtfZPijz61V3gD "R – Try It Online") [Answer] # APL+WIN, 45 bytes Prompts for integer ``` m←⊃(⍳⍴s)↑¨⊂s←(⍕⍳n←⎕)~' '⋄⍎(' ⊖⍉⌽'[1+4|n]),'m' ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/7nApmPupo1HvVuftS7pVjzUdvEQysedTUVA8WBglOB4nkgJX1TNevUFdQfdbc86u3TUFd41DXtUW/no5696tGG2iY1ebGaOuq56v@BZv5P4zI0BgA "APL (Dyalog Classic) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 108 bytes ``` param($n)0..($y=($x=-join(1..$n)).length-1)|%{' '*(0,0,$_,($z=$y-$_))[$n%4]+-join$x[0..($_,$z,$z,$_)[$n%4]]} ``` [Try it online!](https://tio.run/##LYzdCoIwAIXv9xRjHHOrOVzYTbAnERlCmsWcYkH@5LMvkeBcnfOdr@8@1fBqKucCarOEvhzKlsOLVCmOyXCMJnl2D8@1UlstlKv8/d0kWnyjJabxkacylbCSYzaYElghcvgoK077D2O@q6zEvMf@52INKyH6rJS@bCoGS3nb3WhGDcXGR5kQV0YOqCksYYys4Qc "PowerShell – Try It Online") A bit rough around the edges but works. Joins the digits 1 to `n` into a string then iterates from 0 to the length of that string-1. Each time, it uses list indexing to swap to the correct spacing method and number range used to slice our new string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` D€Ẏ;\z⁶U$⁸¡Y ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//ROKCrOG6jjtceuKBtlUk4oG4wqFZ////OA "Jelly – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~14~~ ~~12~~ 10 bytes Using the legacy verion as the rewrite is extremely slow on this for some reason. Saved 2 bytes thanks to *Kevin Cruijssen* ``` LSηsFRζ}J» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJ/jc9mK3oHPbar0O7f7/39AUAA "05AB1E (legacy) – Try It Online") **Explanation** ``` L # push range [1 ... input] S # split to list of individual digits η # calculate prefixes sF } # input times do: R # reverse list ζ # and transpose it J # join to list of strings » # and join on newlines ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç√çZ╟84Γó║ ``` [Run and debug it](https://staxlang.xyz/#p=80fb875ac73834e2a2ba&i=1%0A2%0A5%0A6%0A7%0A8%0A13&a=1&m=2) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~105~~ ~~101~~ 95 bytes *-4 bytes thanks Arnauld for the [trick with Sort](https://codegolf.stackexchange.com/a/181889/80745).* ``` param($n)($x=1..$n-join'')|% t*y|%{($s+="$_")}|sort -d:($n%4-in1,2)|% *ft($x.Length*($n%4-ge2)) ``` [Try it online!](https://tio.run/##JY5NCoMwFIT3OUUILzXP1kCC3QjeoHcQwfhTNBENtEU9e5rW2c58MzO7l1nW3oxjgJaWdAtzvdSTAIsC3qWSEmz2dINNEtw59eln55uA9VoyqBge@@oWT7OmiATPs8Gqm/4F09ZHXj6M7XyfnmZnNGI4CFFaSnWPRYRGxSIqJtfQPO6DgIrniAX7e5d4CqozxsgRvg "PowerShell – Try It Online") Less golfed: ``` param($n) $x=1..$n-join'' $x|% toCharArray |% { ($s+="$_") } | sort -Descending:($n%4-in1,2) |% PadLeft ($x.Length*($n%4-ge2)) ``` [Answer] # [R](https://www.r-project.org/), ~~175~~ ~~172~~ 154 bytes ``` function(n)write(c(" ",0:9)[1+(x=utf8ToInt(Reduce(paste0,1:n,""))-47)*!upper.tri(diag(y<-sum(x|1)))["if"(n%%4>1,1:y,y:1),"if"(!n%%4%%3,y:1,1:y)]],1,y,,"") ``` [Try it online!](https://tio.run/##VYyxDoIwFEV3vwKaEN7TYmhEQUR3V@OmDARa08FCShsh8d@rOMl4zs252gmviJywqjayVaDwpaXhUAPxCI3zPd7YCoajNSK7tmdl4MIbW3Poqt7wmLJcUUIQoyTFpW@7juu10RIaWT1gLKLePmF4M0S8ESkIqCBITuybjXTMGdKf9CcbBJtJTROWJWV0pNOzE7DFQ10ZCO8qxIWA3RzTOWb/6D4 "R – Try It Online") A horrible in-line mess! *-3 bytes by changing the rotation condition* *-17 bytes thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall)'s suggestion, and another byte after golfing that further* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 137 bytes ``` (t=Table[Table[" ",If[(m=#~Mod~4)>1,Tr[1^s]-k,0]]<>ToString/@s[[;;k]],{k,Length[s=Join@@IntegerDigits/@Range@#]}];If[0<m<3,Reverse@t,t])& ``` [Try it online!](https://tio.run/##JcxBC4IwFADgvyIKobBQsZtOduhiFIR5Gy9Y9ZrDnOAeXSL/@hK6fMdvVNTjqMjcldfcx8Q7dXuh/BsGIWueMh55tJymx7JL6px1s8yvDrYDywCqupsuNBurU@GkLMsBgH0GdkSrqZeOHyZjhWgsocZ5b7Qhl4pWWY0igi@Ua59VY1WwFt84OxTECJKNP68nBakItMwL8P4H "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` n=input() s=''.join(map(str,range(1,n+1)));L=len(s) p=-~n/2%2;i=~-L*p+1 exec'print s[:i].rjust(n/2%2*L);i+=1-2*p;'*L ``` [Try it online!](https://tio.run/##HU6xjsIwFJt5X9HllKSlnBIEh6gywlTpltsQQylPNMC9Ri@pDhZ@vZeyWLZl2fbP2PVkxrY/oxVCjGQd@SFKBSHpxbV3JH8bL0PkOTd0QannVGilVFXbO5IMCrwtX/RpPkzl7Kusc19owAe2wrOjmIXD1h0XfB1ClO9YXqvKFVaXJveVyOsxDcNf5@6Y/fCAW5hFfiacTSXZdC3xdxckq0Ufs933fsfc85Q6MTa3US9hBWv4gg1oMP8 "Python 2 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 155 bytes ``` func[n][b: copy""repeat i n[append b i]repeat i l: length? b[t:[l - i + 1]set[k m]pick[i t[l t][l i]]n % 4 + 1 print pad/left copy/part b do do m do do k]] ``` [Try it online!](https://tio.run/##PY3NCsMgEITvPsUS6KmUkP7jpe/Qq@zBxLWVGCN2e@jTW9MfYdj5mB2YRCZfySgUVmb7DIMKqHoJwxxfTZMokmZwEJSOkYKBHhzW1EvhKdz4foFesVQeNiVdQ4cPYjXChNENo3LA5cVYjkMMsIL9UhIxucAQtWk9Wf5MtlEnLiNmXjT9fETM37KFbif@eKh0rHSqdK7UVdrmNw "Red – Try It Online") [Answer] # perl 5, 117 bytes ``` $p=$_++&2?'/ ':'$/';$s='(.*\d.\n)';$r=$_--&2?$s.'\K$':"^(?=$s)";$_=(join"",1..$_).$/;1while s,$r,'$1=~s/\d'."$p/r",ee ``` [TIO](https://tio.run/##DcrRCoIwFAbge59Cxk9Hc55hZIFj@AC9wsgbBymiYwu669Fbu/zg8y5sfUrwBlPTnC4jqZIGgiKNaKjis53Z7nVmyKVtc0Fksg/QIJ7VaBBroTGZaj2WXQjZMWOqGUp3n9eyuTJKBEnozDcqOxMLeBWEdC6la9EXt@L@O/x7OfaYWr/9AQ) [Answer] # [PHP](https://php.net/), ~~116~~ ~~111~~ 109 bytes ``` for($m=$l=strlen($s=join(range(1,$n=$argn)));$l--;)printf('%'.($n&2?$m:-$l).'.'.($n-1&2?$m-$l:$l+1)."s ",$s); ``` [Try it online!](https://tio.run/##NY5Pa8IwGMbv@RQP5Z1N2NtCHNvELHgSPAh6lzGKRKvENCS9jX32rlS9/p6/sY3D1yq2UQjqXe4zLA7Qb4x3xgfjk7FgaMYc30aIU5dcc2wh8XA3GdSkc4DCrwDcse1QhLGk4LvA2G/2P@vd1gxjWNLNkre5T94FSdleu0uQqQlnJzVTsFNGKWXIV5VRMV1Cf5LlS1lLCrP5im7Liryqy3oilZ7YiJbkX7WqiywKpqzM8DjzXBd/wz8 "PHP – Try It Online") Run with `php -nF` input from `STDIN`. `$ echo 6|php -nF t.php` ``` 123456 12345 1234 123 12 1 ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~247~~ ~~209~~ ~~188~~ ~~186~~ ~~160~~ 148 bytes ``` i->{String s="";int l=0,w;for(;l<i;s+=++l);for(w=s.length(),l=0;l<w;)System.out.printf("%"+(1>i%4/2?1:w)+"s\n",s.substring(0,1>~-i%4/2?w-l++:++l));} ``` [Try it online!](https://tio.run/##XZBNT8IwGMfvfIqlCUmbdpXha1aHMcaDB08ckUMtHRS7DtpnLGSZX31WiJp4/ef3f3merTzIdLv6GIwD7UupdPIqjetGASQYlUR5sUxAB1Ay6FB01@yG3bI7lrEpyy578QMearNKqmjFc/DGrRdLT7ptTOcNGMvLxikwteMvDp5qF5pK@2RfDCaddWdDEgqEROxLbDFhrShrj4W9NyLQglJLTkJbBG61W8MGExa5CLSCzI8BdMXrBvguRkGJ0RhRnM3M@Opi@pDlLaEovDnEAg/Nezj14QnLZp/pGWlTS2n@XUNEP4jR3/BH7@Ux2sBrWeHfRxAe5zxLtcGnC/4NsA6jWEcNRTkiYs@lUnoH2MR0IkZ9P3wB "Java (JDK) – Try It Online") `-38 bytes` thanks to @KevinCruijssen `-21 bytes` by letting `printf` handle the padding. `-2 bytes` by doing substring before replace, allowing us to increment `l` in one location rather than two. `-26 bytes` - with `printf` doing the padding, the string full of spaces was no longer necessary, and the digit strings could be generated in a shorter way apparently. `-12 bytes` by not messing about with single digits instead of printing substrings of the perfectly servicable digit string we already have. # Ungolfed ``` input->{ // Lambda expression with target type of IntConsumer String allDigits = ""; int lineLength, line = 0; // Collect a list of all digits in order. for (;line < input; allDigits += ++line) {} // Save the max length of a line, and create a string of that many spaces. for (lineLength=allDigits.length(), line=0; line < lineLength;) { System.out.printf( "%" // construct a format string to handle the padding + ( 1 > input%4/2 ? 1 // No padding : w // Yes padding ) + "s\n" , allDigits.substring( 0 , 1 > (i-1)%4/2 ? w - l++ : ++l ) // A string containing only the digit we want. ); } } ``` ]
[Question] [ Your task is to take in one integer input and print a zigzag pattern using slashes and backslashes. * The integer input determines the length of each zig and zag, as well as the number of zigs and zags * The pattern always starts from right to left # Test Cases ``` 4-> / / / / \ \ \ \ / / / / \ \ \ \ 2-> / / \ \ 0-> 1-> / 8-> / / / / / / / / \ \ \ \ \ \ \ \ / / / / / / / / \ \ \ \ \ \ \ \ / / / / / / / / \ \ \ \ \ \ \ \ / / / / / / / / \ \ \ \ \ \ \ \ ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~108~~ ~~102~~ ~~101~~ ~~98~~ ~~80~~ ~~76~~ 72 bytes * Saved six bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen); removing parentheses and golfing `N-n-1` to `N+~n` * Saved a byte by moving `Z`'s incrementation into the loop condition * Saved three bytes by using `printf("%c\n",...)` instead of `putchar(...)` and `,puts("")` * Saved eighteen (!) bytes thanks to [HatsuPointerKun](https://codegolf.stackexchange.com/users/72535/hatsupointerkun); using `printf("%*s",n,"");` to print `n` spaces instead of using a loop `j;for(j=n;j--;)putchar(32);` and combining both `printf(...);` calls * Saved four bytes by using `printf("%*c",-~n,...);` instead of `printf("%*s%c",n,"",...);` * Saved four bytes thanks to [nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof); moving everything inside one loop instead of two ``` j;f(k){for(j=0;j<k*k;j++)printf("%*c\n",j/k%2?j%k+1:k-j%k,j/k%2?92:47);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/LOk0jW7M6Lb9II8vWwDrLJlsr2zpLW1uzoCgzryRNQ0lVKzkmT0knSz9b1cg@SzVb29AqWxdIQ0UsjaxMzDWta/97WecmZuZpQIzysq0zsPbS1rYxNLDWTNPw0tQpKC0p1lBSAqkEAA "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ ~~10~~ 9 bytes ``` FN«↖Iθ→‖T ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NToZqLM6AoM69Ewyq0wCc1rURHwTmxuESjUFPTmovTN78sVcMqKDM9owTEDUpNy0lNLgkpSswrBpqVqwEUrP3/3@S/btl/3eIcAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` :"GXy@o?P47}92]*c ``` [**Try it online!**](https://tio.run/##y00syfn/30rJPaLSId8@wMS81tIoViv5/38TAA "MATL – Try It Online") ### Explanation ``` : % Implicit input, n. Push range [1 2 ... n] " % For each k in that range G % Push n again Xy % Identity matrix of that size @ % Push k o? % If it's odd P % Flip the matrix upside down 47 % Push 47 (ASCII for '/') } % Else 92 % Push 92 (ASCII for '\') ] % End * % Multiply each entry of the matrix by that number c % Convert to char. Char 0 is shown as space % Implicit end. Implicit display ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~117~~ ~~103~~ 101 bytes ``` a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));} ``` [Try it online!](https://tio.run/##RY7BCsIwEETv/YpQEBJjWxVPtqmK1woFD168rOkWAjWRJgq29Ntj0YJzmeHNLoy0kTQt@sfz1ihJZAPWkjLog4CMmqh14EZ7GVWREyhN2bedjsj5bR3e44N0yuhMaZeTmggPIu9r09IRkE4AXy1QLFPMYA4pm36ORlvTYHxplcNCaaTIeQKzdbbahUkYl1AVWDsaRR3b7sPrn3ScM5YOPv1tqOmGTXEIBv8B "C# (.NET Core) – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~13~~ ~~12~~ 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ╝F{±↔}P}ø ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTVERiU3QiVCMSV1MjE5NCU3RFAlN0QlRjg_,inputs=NA__) could be 8 bytes `╝F{±↔}P}` if the 0 test-case wasn't required Explanation: ``` } implicitly started loop repeated input times ╝ create a down-right diagonal of the input F get the current looping index, 1-indexed { } that many times ±↔ reverse the diagonal horizontally P print that ø push an empty string - something to implicitly print if the loop wasn't executed ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~68~~ 62 bytes -1 byte thanks to Jonathan Frech ``` lambda n:[[~i,i][i/n%2]%n*' '+'/\\'[i/n%2]for i in range(n*n)] ``` [Try it online!](https://tio.run/##LcixDkAwFAXQX3mLvBYhEZPEl7QdKpQn3Epjsfj1WpzxXM@9RXQ5jDYf/pxmTxiMeaUWZ6RF0bkCJRNX3FrLf4WYSEhAyWNdFEpol68kuIktuNmjQAXVa50/ "Python 2 – Try It Online") [Answer] # Mathematica, 84 ~~90~~ bytes ``` (n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"‌​/","\\"],""]&,{n^2,n‌​}])& ``` * *Thank Jenny\_mathy for -6 bytes.* I have no idea why `\` is obviously darker than `/`. [![enter image description here](https://i.stack.imgur.com/X2o2nl.png)](https://i.stack.imgur.com/X2o2nl.png) [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), ~~94~~ 89 bytes ``` ["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add ``` Explanation ``` ["/","\\"][range($n)%2] as $s # for $s= / \ / \ $n times | range($n) # for .=0 to $n-1 | [(range(if $s=="/" then $n-.-1 else . end)|" "), $s] # form list of spaces ending with $s | add # concatenate ``` Sample Run ``` $ jq -Mnr --argjson n 5 '["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add' / / / / / \ \ \ \ \ / / / / / \ \ \ \ \ / / / / / ``` [Try it online!](https://tio.run/##PYtBCsMgEAC/IssWImRTWnrNS4wHQdtaZE2zhlx8e61Q6G1mYF7vdlNOFHJtBs4wwrKANZvjRxiQ9elqnaDUf6hm@HG8o8xzX8ozMDJNdFEhSZhUYK8rKNAjiq3O@9Y@eS0xszQi3lOiyOteumzuoLyXLl8 "jq – Try It Online") [Answer] # Java 8, ~~140~~ ~~134~~ 116 bytes ``` n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;} ``` -24 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##hZDBasMwEETv/YpFULBQ5Lqhh1JF7hc0lx7rHlaKUpQ6ayPLgZL6213Z8bUYJMTOm4UZnfCCsmkdnQ7fo62x6@ANPV3vADxFF45oHeynEeA9Bk9fYLNEgLhK4pBuOl3E6C3sgUDDSLK8Lt6gGVPHJswrqIuN2ViFQuxI8Uk2mpSRsixUEBrvt2Xxyh4qYi@sqtIze6w2koT5lYkrIezOTGYGjKvgYh8IghpGdUvS9qZOSZZAl8Yf4Jz6ZLc8H5@AfCnz00V3zps@5m1CsaaMcpsVfO71L39c4dsV/rTCn/nyr8P4Bw) ``` n->{ // Method with integer parameter and String return-type String r=""; // Result-String for(int a=0,b,c; // Index integers a++<n;) // Loop (1) from 0 to the input (exclusive) for(b=n; // Reset `b` to the input b-->0; // Inner loop (2) from the input to 0 (exclusive) // After every iteration: r+=a%2>0?"/\n":"\\\n") // Append either of the slashes + a new-line for(c=b-n+b|-a%2;++c<b;r+=" "); // Append the correct amount of spaces // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] # Javascript ES8, 83 79 78 76 75 74 71 bytes \*reduced 1 byte with ES8 thanks to Shaggy ``` A=(m,i=0)=>i<m*m?`/\\`[x=i/m&1].padStart(x?i%m+1:m-i%m)+` `+A(m,++i):"" ``` [Test here](https://tio.run/##y0osSyxOLsosKNHNy09J/f/f0VYjVyfT1kDT1i7TJlcr115JQUmvKLUgNbFEI1M/V83QPlM11ypXF0jqGmpqK@nHxChFZ2prg6RitZVi8pS0HUEmaFopKf1Pzs8rzs9J1cvJT9dw1DDU1LTmQhUywhQyxhQyAQr9BwA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` Lm+*;dbQjs<*,_y\/y\\ ``` [Try it online!](http://pyth.herokuapp.com/?code=Lm%2B%2a%3BdbQjs%3C%2a%2C_y%5C%2Fy%5C%5C&input=3&debug=0) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 81 bytes ``` param($a)if($a){1..$a|%{((1..$a|%{" "*--$_+'\'}),($a..1|%{" "*--$_+'/'}))[$_%2]}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRMzMNRFYb6umpJNaoVmtowFhKCkpauroq8drqMeq1mjpAVXp6hiji@kBxzWiVeFWj2Nra////GwMA "PowerShell – Try It Online") Ugh, this is ugly. So much repeated code, plus 7 bytes required to account for `0` special case. *Golfing suggestions welcome.* [Answer] # Pyth, 17 bytes ``` js<*_+RV"\/"_B*L; ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=js%3C%2A_%2BRV%22%5C%2F%22_B%2AL%3B&input=3&debug=0) ### Explanation: ``` js<*_+RV"\/"_B*L;QQQ implicit Qs at the end *L;Q list with ["", " ", " ", ..., " "*(input-1)] _B bifurcate with reverse: [["" to " "], [" " to ""]] +RV"\/" append to each one either "\" or "/": [["\", to " \"], [" /" to "/"]] _ reverse * Q repeat input times < Q but only take the first input many s flatten the list of lists j print on each line ``` [Answer] # Python 3: ~~90 Bytes~~ 82 Bytes ``` lambda n:"\n".join(" "*(abs(i%(n*2)-n+i//n%2)-1)+"/\\"[i//n%2]for i in range(n*n)) ``` Thanks to @Jonathan Frech for pointing out that print wasn't needed and that the first zig was the wrong way [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes ``` F<„/\Nèú.sNƒR}», ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fzeZRwzz9GL/DKw7v0iv2OzYpqPbQbp3//00A "05AB1E – Try It Online") **Explanation** ``` F # for N in [0 ... input-1] do „/\ # push the string "/\" Nè # cyclically index into this string with N < ú # prepend input-1 spaces to this string .s # get suffixes NƒR} # reverse the list of suffixes input+1 times », # join on newline and print ``` **Current best attempt using canvas:** ``` F„/\Nè©53NèΛ2®ð«4Λ ``` [Answer] ## C++, ~~92~~ 91 bytes -1 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` void m(int n){for(int i=0,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);} ``` Thanks to the power of the magic `printf` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~131~~ ~~106~~ ~~98~~ ~~96~~ ~~94~~ 91 bytes ``` i->{for(int j=0;j<i*i;System.out.printf("%"+(j/i%2<1?i-j%i:j%i+1)+"c\n",47+45*(j++/i%2)));} ``` [Try it online!](https://tio.run/##TY7BSsQwFEX3/YpQKCSNjY5UBNMZEVeuZ6kuYiYtL7ZJSV4GZOi311Rm4YW3OfdxOVadVeNn4@zpe4Vp9gGJzUwgTEbUsvjPEsIo@uQ0gndbWehRxUheyKUgOREVgibk1buYJhO6N4dmMOFAEtmv0BwuvQ8UXJ7b30nbQQ3y@BPRTMInFHPIVU/LquTU3kJ13@2eobEVPOXjO8ZL/eHKm/aRtw81tZxvP4wxuaxZZROY09eYBa4eZw8nMilw9Ih5enj/JCoMkV1ttyShtDYz0pbJP7gUy/oL "Java (OpenJDK 8) – Try It Online") [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~39~~ ~~36~~ ~~35~~ 34 bytes ``` {↑((,⍵ ⍵⍴(⌽,⊢)⍳⍵)/¨' '),¨⍵/⍵⍴'/\'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLjSgGT1o7aJGho6j3q3KgDxo94tGo969uo86lqk@ah3M1BEU//QCnUFdU2dQyuAPH2IGnX9GPVaLqBBQAPSFEz//wcA "APL (Dyalog Unicode) – Try It Online") 1 byte saved thanks to [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%c3%bd) [Answer] # [Perl 5](https://www.perl.org/), 70 + 1 (`-n`) = 71 bytes ``` $n=$_**2;$_=$"x--$_.'/';say&&s% /%/ %||s%\\ % \\%||y%\\/%/\\%while$n-- ``` [Try it online!](https://tio.run/##DchBCoAgEADAr0jsGgSrFnUKn9APBOkgJIRFBhX09jZvw@zhWAdmSBZ803QjeAvVTQRe1boe8/xImVFo1ALfN6NzAoVzxU9x6eJriWuARMTcf9t@xi1lpmlQpjVM6Qc "Perl 5 – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 102 bytes ``` (0..q-1).map{r->if(r%2<1)q-1 downTo 0 else{0..q-1}.map{(1..it).map{print(' ')};println('/'+45*(r%2))}} ``` [Try it online!](https://tio.run/##NY3BDoIwEETvfMWGxLCraQXFCyKJR8/6A00E0ggFSo0R0m9HLDqnyezbmUdjKqmm4qlgwC65KENwgglDzjsWEa9FO2qWyQL1apdGNIdwb17q1kAIedXn40JaR2LEuTTLV6ulMhhAQPbofKUw2Aab@LD@dhFZ62ZrIRUKXfYJnLUW7/RqZrrMCEYPZg0YkzP/Ep8x5tPvtifPTh8 "Kotlin – Try It Online") [Answer] # Excel VBA, ~~84~~ 83 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window ``` For i=1To[A1]:For j=1To[A1]:?IIf(i mod 2,Space([A1]-j)&"/",Space(j-1)&"\"):Next j,i ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ḶṚ⁶ẋm0ż⁾/\x$ṁ²Y ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//4bi24bma4oG24bqLbTDFvOKBvi9ceCThuYHCsln///84 "Jelly – Try It Online") Full program. [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ 85 bytes ``` f n=take(n*n)$cycle$[(' '<$[x..n-1])++"/"|x<-[1..n]]++[(' '<$[2..x])++"\\"|x<-[1..n]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7YkMTtVI08rT1MluTI5J1UlWkNdQd1GJbpCTy9P1zBWU1tbSV@ppsJGN9oQKBIbq60NU2Gkp1cBlo@JQVbwPzcxM0/BViElX4FLAQhyEwt8FQpKS4JLinzyFFQU0hRM/wMA "Haskell – Try It Online") *Saved one byte thanks to Laikoni* Repeat a zig ++ a zag, and take the first `n*n` lines. [Answer] # [J](http://jsoftware.com/), ~~39 35 33 32~~ 25 bytes ``` ' /\'{~[,/@$(|.,:+:)@=@i. ``` [Try it online!](https://tio.run/##y/r/P9FWT0FdQT9GvbouWkffQUWjRk/HSttK08HWIVPvf2pyRr5CooIJF5RhCGMY/wcA "J – Try It Online") [Answer] # Dyalog APL, ~~41~~ 40 bytes `⎕IO` must be `0`. ``` {⍪/((⌽⍵ ⍵⍴S↑'/')(⍵ ⍵⍴'\'↑⍨S←⍵+1))[2|⍳⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLiALCBd/ah3lb6GxqOevY96tyoA8aPeLcGP2iaq66traiCE1GPUgYKPelcA5SYAhbQNNTWjjWoe9W4GcmJrTf//BwA) [Answer] # [D](https://dlang.org/), 105 bytes ``` import std.stdio;void m(T)(T n){for(T i,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);} ``` [Try it online!](https://tio.run/##S/n/PzO3IL@oRKG4JEUPiDPzrcvyM1MUcjVCNDVCFPI0q9Pyi4CMTJ0s60ybPGtt7UxNkEiWrYF1FpifpVlQlJlXkqahpKqVHJOnpJOpamSfpW1olaebBWZbGlmZmGta1/6HGJyYmaehWc3FmathomnNVfsfAA "D – Try It Online") Lifted from HatsuPointerKun's C++ answer. ]
[Question] [ In cryptography, [PKCS#7 padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7) is a padding scheme which adds a number of bytes N ≥ 1, where the value of each added byte is equal to N. For example, `Hello, World!`, which has 13 bytes, is the following in hex: ``` 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 ``` If we choose to PKCS#7 pad to length 16, then the result is: ``` 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 03 03 03 ``` And if we choose to pad to length 20, then the result is: ``` 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 07 07 07 07 07 07 ``` Note that in the first example we add three `03` bytes, and in the second we add seven `07` bytes. Your task will be to *validate* whether a string (or integer array) has correct PKCS#7 padding. That is, if the last byte of the input string is N, then your program should check that the last N bytes of the string are equal to N. ## Input A single nonempty ASCII string containing characters between code points 1 and 127 inclusive. If you wish, you may take input as an array of integers instead. ## Output A [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if the input string has valid PKCS#7 padding, otherwise a falsy value. Both functions and full programs are acceptable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the aim is to minimise the number of bytes in your code. ## Test cases The integer array version of inputs is presented here — the string version would have unprintable characters for many of the following test cases: **Truthy:** ``` [1] [1, 1] [2, 1] [2, 2] [5, 6, 5, 3, 3, 3] [1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2] [95, 115, 80, 32, 71, 7, 122, 49, 13, 7, 7, 7, 7, 7, 7, 7, 7] [27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15] ``` **Falsy:** ``` [2] [1, 2] [5, 5, 5, 5] [5, 6, 5, 4, 4, 4] [3, 3, 3, 94, 3, 3] [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 127] [50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7] [26, 27, 59, 25, 122, 110, 20, 30, 114, 6, 9, 62, 121, 42, 22, 60, 33, 12] ``` [Answer] # Python, ~~47~~ ~~34~~ 33 bytes ``` lambda s:s[-1:]*s[-1]==s[-s[-1]:] ``` `s[-1]` is the last member of the list `s`. Checks that the last `s[-1]` members of the input array `s` are the same as an array of `s[-1]` repeated that many times. Takes input as an array of integers. This is a lambda expression; to use it, assign it by prefixing `lambda` with `f=`. [Try it on Ideone!](http://ideone.com/ZzcGBF) To test: ``` >>> f=lambda s:s[-1:]*s[-1]==s[-s[-1]:] >>> f([27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) True >>> f([50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7]) False ``` *Saved 13 bytes thanks to Leaky Nun!* *Saved a byte thanks to Dennis!* [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes ``` ~c[A:B]t#=h~lB ``` [Try it online!](http://brachylog.tryitonline.net/#code=fmNbQTpCXXQjPWh-bEI&input=WzI3OjMzOjU0OjY1Ojk3OjMzOjUyOjU1OjYwOjE6MTA6MTA6MTA6MTA6MTA6MTA6MTA6MTA6MTA6MTBd) ``` ~c[A:B]t#=h~lB ~c[A:B] input is concatenation of A and B t B #= has all equal elements h~lB the first item of B is the length of B ``` [Answer] # Pyth, 5 bytes ``` gFer8 ``` RLE on input, take the last pair and check if the number of repeats is greater or equal than the value. Try it online: [Demonstration](http://pyth.herokuapp.com/?code=gFer8&input=%5B95%2C%20115%2C%2080%2C%2032%2C%2071%2C%207%2C%20122%2C%2049%2C%2013%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D&test_suite_input=%5B1%5D%0A%5B1%2C%201%5D%0A%5B2%2C%201%5D%0A%5B2%2C%202%5D%0A%5B5%2C%206%2C%205%2C%203%2C%203%2C%203%5D%0A%5B1%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%5D%0A%5B95%2C%20115%2C%2080%2C%2032%2C%2071%2C%207%2C%20122%2C%2049%2C%2013%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D%0A%5B27%2C%2033%2C%2054%2C%2065%2C%2097%2C%2033%2C%2052%2C%2055%2C%2060%2C%201%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%5D%0A%5B15%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%5D%0A%5B2%5D%0A%5B1%2C%202%5D%0A%5B5%2C%205%2C%205%2C%205%5D%0A%5B5%2C%206%2C%205%2C%204%2C%204%2C%204%5D%0A%5B3%2C%203%2C%203%2C%2094%2C%203%2C%203%5D%0A%5B1%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%5D%0A%5B1%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%20127%5D%0A%5B50%2C%2039%2C%2094%2C%20105%2C%2049%2C%2029%2C%2074%2C%20102%2C%202%2C%20106%2C%2044%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D%0A%5B26%2C%2027%2C%2059%2C%2025%2C%20122%2C%20110%2C%2020%2C%2030%2C%20114%2C%206%2C%209%2C%2062%2C%20121%2C%2042%2C%2022%2C%2060%2C%2033%2C%2012%5D&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=gFer8&input=%5B95%2C%20115%2C%2080%2C%2032%2C%2071%2C%207%2C%20122%2C%2049%2C%2013%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D&test_suite=1&test_suite_input=%5B1%5D%0A%5B1%2C%201%5D%0A%5B2%2C%201%5D%0A%5B2%2C%202%5D%0A%5B5%2C%206%2C%205%2C%203%2C%203%2C%203%5D%0A%5B1%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%5D%0A%5B95%2C%20115%2C%2080%2C%2032%2C%2071%2C%207%2C%20122%2C%2049%2C%2013%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D%0A%5B27%2C%2033%2C%2054%2C%2065%2C%2097%2C%2033%2C%2052%2C%2055%2C%2060%2C%201%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%5D%0A%5B15%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%5D%0A%5B2%5D%0A%5B1%2C%202%5D%0A%5B5%2C%205%2C%205%2C%205%5D%0A%5B5%2C%206%2C%205%2C%204%2C%204%2C%204%5D%0A%5B3%2C%203%2C%203%2C%2094%2C%203%2C%203%5D%0A%5B1%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%5D%0A%5B1%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%20127%5D%0A%5B50%2C%2039%2C%2094%2C%20105%2C%2049%2C%2029%2C%2074%2C%20102%2C%202%2C%20106%2C%2044%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%5D%0A%5B26%2C%2027%2C%2059%2C%2025%2C%20122%2C%20110%2C%2020%2C%2030%2C%20114%2C%206%2C%209%2C%2062%2C%20121%2C%2042%2C%2022%2C%2060%2C%2033%2C%2012%5D&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒgṪṫṪ ``` Input is an array of code points, output is a non-empty array (truthy) or an empty array (falsy). [Try it online!](http://jelly.tryitonline.net/#code=xZJn4bmq4bmr4bmq&input=&args=WzE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNV0) or [verify all test cases](http://jelly.tryitonline.net/#code=xZJn4bmq4bmr4bmqCjEgMMOHP8K14oKs4oKsRw&input=&args=W1sKIFsxXSwKIFsxLCAxXSwKIFsyLCAxXSwKIFsyLCAyXSwKIFs1LCA2LCA1LCAzLCAzLCAzXSwKIFsxLCAxLCAyLCAyLCAxLCAxLCAyLCAyLCAxLCAxLCAyLCAyXSwKIFs5NSwgMTE1LCA4MCwgMzIsIDcxLCA3LCAxMjIsIDQ5LCAxMywgNywgNywgNywgNywgNywgNywgNywgN10sCiBbMjcsIDMzLCA1NCwgNjUsIDk3LCAzMywgNTIsIDU1LCA2MCwgMSwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTBdLAogWzE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNV0KXSxbCiBbMl0sCiBbMSwgMl0sCiBbNSwgNSwgNSwgNV0sCiBbNSwgNiwgNSwgNCwgNCwgNF0sCiBbMywgMywgMywgOTQsIDMsIDNdLAogWzEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDJdLAogWzEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDEyN10sCiBbNTAsIDM5LCA5NCwgMTA1LCA0OSwgMjksIDc0LCAxMDIsIDIsIDEwNiwgNDQsIDcsIDcsIDcsIDcsIDcsIDddLAogWzI2LCAyNywgNTksIDI1LCAxMjIsIDExMCwgMjAsIDMwLCAxMTQsIDYsIDksIDYyLCAxMjEsIDQyLCAyMiwgNjAsIDMzLCAxMl0KXV0). ### How it works ``` ŒgṪṫṪ Main link. Argument: A (array) Œg Group all runs of consecutive, equal integers. Ṫ Tail; yield the last run. It should consist of n or more occurrences of n. Ṫ Tail; yield n, the last element of A. ṫ Dyadic tail; discard everything after the n-th element of the last run. If the last run was long enough, this will yield a non-empty array (truthy); if not, the result will be an empty array (falsy). ``` [Answer] ## CJam, ~~9~~ 8 bytes *Thanks to Sp3000 for saving 1 byte.* ``` {e`W=:/} ``` Takes an integer list as input and returns `0` (falsy) or a positive integer (truthy). [Test suite.](http://cjam.tryitonline.net/#code=cX5dewoKe2VgVz06L30KCn5dbn0v&input=WzFdClsxIDFdClsyIDFdClsyIDJdCls1IDYgNSAzIDMgM10KWzEgMSAyIDIgMSAxIDIgMiAxIDEgMiAyXQpbOTUgMTE1IDgwIDMyIDcxIDcgMTIyIDQ5IDEzIDcgNyA3IDcgNyA3IDcgN10KWzI3IDMzIDU0IDY1IDk3IDMzIDUyIDU1IDYwIDEgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTBdClsxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNSAxNV0KWzJdClsxIDJdCls1IDUgNSA1XQpbNSA2IDUgNCA0IDRdClsxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMl0KWzEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMTI3XQpbNTAgMzkgOTQgMTA1IDQ5IDI5IDc0IDEwMiAyIDEwNiA0NCA3IDcgNyA3IDcgN10KWzI2IDI3IDU5IDI1IDEyMiAxMTAgMjAgMzAgMTE0IDYgOSA2MiAxMjEgNDIgMjIgNjAgMzMgMTJd) ### Explanation ``` e` e# Run-length encoding, yielding pairs of run-length R and value V. W= e# Get the last pair. :/ e# Compute R/V, which is positive iff R ≥ V. Works, because V is guaranteed e# to be non-zero. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes No run-length encodings for osabie :( ``` ¤sR¬£¬QOQ ``` Explanation: ``` ¤ # Get the last element of the array s # Swap the two top elements R # Reverse the array ¬ # Get the first element £ # Substring [0:first element] ¬ # Get the first element Q # Check if they are equal OQ # Sum up and check if equal ``` With an example: ``` ¤ # [5, 6, 5, 3, 3, 3] 3 s # 3 [5, 6, 5, 3, 3, 3] R # 3 [3, 3, 3, 5, 6, 5] ¬ # 3 [3, 3, 3, 5, 6, 5] 3 £ # 3 [3, 3, 3] ¬ # 3 [3, 3, 3] 3 Q # 3 [1, 1, 1] OQ # 3==3 which results into 1 ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wqRzUsKswqPCrFFPUQ&input=Wzk1LCAxMTUsIDgwLCAzMiwgNzEsIDcsIDEyMiwgNDksIDEzLCA3LCA3LCA3LCA3LCA3LCA3LCA3LCA3XQ) [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes *Thanks to @Adnan for noticing a problem with an earlier version of the code* ``` P0hG0):)&= ``` When the input has correct padding, the output is an array containing only ones, which is [truthy](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScKfSAgICAgICAgICUgZWxzZQonZmFsc3kn&input=WzEgMSAxOyAxIDEgMTsgMSAxIDFd). When it has incorrect padding, the output is an array containing at least a zero, and so is [falsy](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScKfSAgICAgICAgICUgZWxzZQonZmFsc3kn&input=WzEgMSAxOyAxIDEgMTsgMSAxIDBd). [Try it online!](http://matl.tryitonline.net/#code=UDBoRzApOikmPQ&input=Wzk1LCAxMTUsIDgwLCAzMiwgNzEsIDcsIDEyMiwgNDksIDEzLCA3LCA3LCA3LCA3LCA3LCA3LCA3LCA3XQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLClAwaEswKTopJj0KRFQ&input=WzFdClsxLCAxXQpbMiwgMV0KWzIsIDJdCls1LCA2LCA1LCAzLCAzLCAzXQpbMSwgMSwgMiwgMiwgMSwgMSwgMiwgMiwgMSwgMSwgMiwgMl0KWzk1LCAxMTUsIDgwLCAzMiwgNzEsIDcsIDEyMiwgNDksIDEzLCA3LCA3LCA3LCA3LCA3LCA3LCA3LCA3XQpbMjcsIDMzLCA1NCwgNjUsIDk3LCAzMywgNTIsIDU1LCA2MCwgMSwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTBdClsxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTUsIDE1LCAxNSwgMTVdClsyXQpbMSwgMl0KWzUsIDUsIDUsIDVdCls1LCA2LCA1LCA0LCA0LCA0XQpbMywgMywgMywgOTQsIDMsIDNdClsxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyXQpbMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMSwgMTI3XQpbNTAsIDM5LCA5NCwgMTA1LCA0OSwgMjksIDc0LCAxMDIsIDIsIDEwNiwgNDQsIDcsIDcsIDcsIDcsIDcsIDddClsyNiwgMjcsIDU5LCAyNSwgMTIyLCAxMTAsIDIwLCAzMCwgMTE0LCA2LCA5LCA2MiwgMTIxLCA0MiwgMjIsIDYwLCAzMywgMTJd). ### Explanation ``` P % Implicitly take numeric array as input. Reverse the array 0h % Append a 0. This ensures falsy output if input array is too short G0) % Push input again. Get its last element : % Range from 1 to that ) % Apply as index into the array &= % 2D array of all pairwise equality comparisons. Implicitly display ``` [Answer] ## Mathematica, 29 bytes ``` #&@@#<=Length@#&@*Last@*Split ``` Split the input into runs of equal elements, extract the last, and check that its first element is less than or equal to the length of that run. [Answer] ## Haskell, 50 bytes ``` import Data.List ((>=)<$>head<*>length).last.group ``` Takes an array of integers as input. [Answer] # J, 13 bytes ``` #~@{:-:{:{.|. ``` Takes the list as a single argument and outputs `1` if it is truthy and `0` if falsey. ## Usage ``` f =: #~@{:-:{:{.|. f 5 6 5 3 3 3 1 f 5 6 5 4 4 4 0 ``` ## Explanation ``` #~@{:-:{:{.|. Input: array A |. Reverse A {: Get the last value in A {. Take that many values from the reverse of A {: Get the last value in A #~@ Make a list with that many copies of the last value -: Test if the list of copies matches the sublist of A and return ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak/tree/752fab329eec303ea9878c9faaf74a380708f93b), 54 bytes ``` (({})[()]){({}[()]<({}[({})]){<>}{}>)}{}{<>(<(())>)}{} ``` Input is a list of integers, output is 1 for truthy and empty for falsey. ## Explanation ``` (({})[()]){ Loop a number of times equal to the last integer in the input - 1 ({}[()] Handle loop counter < Silently... ({}[({})]) Replace the last code point in the string with its difference with the code point before it {<>} If the difference is not zero then switch stacks {} Discard the difference > End silently ) Handle loop counter } End loop {} Discard the loop counter {<>(<(())>)} If the top of the current stack is not 0 (which means we have not switched stacks push 0 then 1 {} Discard the top of the stack (either nothing if falsey or 0 if truthy) ``` The loop does not immediately end when a value that would result in a falsey return is encountered. It is instead switched to the other stack which is empty and spends the rest of its iterations comparing 0 and 0. [Answer] ## Batch, 101 bytes ``` @for %%a in (%*)do @set/an=%%a,c=0 @for %%a in (%*)do @set/ac+=1,c*=!(n-%%a) @if %c% geq %n% echo 1 ``` Takes input as command-line parameters, loops over them all so that it can get the last one into `n`, loops over them all again to count the run of trailing `n`s, finally printing `1` if the count is at least equal to `n`. Alternatively if printing `0` or a non-zero value is acceptable, then for 93 bytes, change the last line to `@cmd/cset/ac/n`. [Answer] # Haskell, 49 bytes ``` f s|x<-(==last s)=x.length.fst.span x.reverse$s ``` [Try it on Ideone.](https://ideone.com/Gw3I8f) Shorter version which returns `True` for truthy and `False` or an exception for falsy: ``` ((==).head>>=all).(head>>=take).reverse ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` (⊃∧.=⊃↑⊢)⌽ ``` `⊃` Is the first `∧.=` all-equal to `⊃` the first `↑` *n* taken from `⊢` the `⌽` reversed argument? [TryAPL online!](http://tryapl.org/?a=f%u2190%28%u2283%u2227.%3D%u2283%u2191%u22A2%29%u233D%20%u22C4%20f%A8%28%2C1%29%281%2C%201%29%282%2C%201%29%282%2C%202%29%285%2C%206%2C%205%2C%203%2C%203%2C%203%29%281%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%202%29%2895%2C%20115%2C%2080%2C%2032%2C%2071%2C%207%2C%20122%2C%2049%2C%2013%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%29%2827%2C%2033%2C%2054%2C%2065%2C%2097%2C%2033%2C%2052%2C%2055%2C%2060%2C%201%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%2C%2010%29%2815%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%2C%2015%29%20%u22C4%20f%A8%28%2C2%29%281%2C%202%29%285%2C%205%2C%205%2C%205%29%285%2C%206%2C%205%2C%204%2C%204%2C%204%29%283%2C%203%2C%203%2C%2094%2C%203%2C%203%29%281%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%29%281%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%20127%29%2850%2C%2039%2C%2094%2C%20105%2C%2049%2C%2029%2C%2074%2C%20102%2C%202%2C%20106%2C%2044%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%29%2826%2C%2027%2C%2059%2C%2025%2C%20122%2C%20110%2C%2020%2C%2030%2C%20114%2C%206%2C%209%2C%2062%2C%20121%2C%2042%2C%2022%2C%2060%2C%2033%2C%2012%29&run) [Answer] ## Javascript (ES6), ~~51~~ ~~47~~ 41 bytes ``` a=>(r=k=>a.pop()^n?k<2:r(k-1))(n=a.pop()) ``` Examples: ``` let f = a=>(r=k=>a.pop()^n?k<2:r(k-1))(n=a.pop()) console.log(f([5, 6, 5, 3, 3, 3])) console.log(f([5, 6, 5, 4, 4, 4])) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 84 bytes *100000000 beat me [here](https://codegolf.stackexchange.com/a/91478/56656)* [Try It Online!](http://brain-flak.tryitonline.net/#code=KCgoe30pKSl7KHt9WygpXTwoKHt9KTwoW3t9XXt9PD4pPD4-KT4pfTw-KFtdKSh7PHt9Pnt9PChbXSk-fXt9PCgoKSk-KXsoKDx7fXt9PikpfXt9&input=) ``` ((({}))){({}[()]<(({})<([{}]{}<>)<>>)>)}<>([])({<{}>{}<([])>}{}<(())>){((<{}{}>))}{} ``` Takes input as array of integers. Explanation to come. Here is a 64 byte version that outputs the not of the answer: ``` ((({}))){({}[()]<(({})<([{}]{}<>)<>>)>)}<>([])({<{}>{}<([])>}{}) ``` [Answer] # C 91 Bytes ``` int f(int*l){int n;for(n=0;l[++n];);l+=n-1;for(int i=*l;i;)if(l[-i--+1]^*l||n<*l)return 0;} ``` Input: a pointer to a null-terminated array. Output: returns `0` for invalid padding and non-zero for valid (the last element in the array) Examples: ``` int a[] = {5, 6, 5, 3, 3, 3, 0}; printf("%d\n", f(&a[5], 6)); int b[] = {1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0}; printf("%d\n", f(&b[11],12 )); int m[] = {5, 6, 5, 4, 4, 4, 0}; printf("%d\n", f(&m[5], 6)); int n[] = {3, 3, 3, 94, 3, 3, 0}; printf("%d\n", f(&n[5], 6)); ``` Gives: ``` 3 2 0 0 ``` This does rely on undefined behavior. If the padding is valid there is no return statement, but using `gcc -std=c99` this returns the last element of the array that was passed in (at least on my machine). [Answer] # [Perl 5](https://www.perl.org/), 30 bytes Includes `+1` for `-p` ``` #!/usr/bin/perl -p $_=/(.)\1*\z/s+length$&>ord$1 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfQ08zxlArpkq/WDsnNS@9JENFzS6/KEXF8P9/U4WSzNzUYoUYUysFVhD4l19QkpmfV/xftwAA "Perl 5 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` a₁=.l∈ ``` [Try it online!](https://tio.run/##nU/LSgQxEPyVIQdP5ZLuPMYc9EeGOYyy6mFAWJVB1j24gow3/8KrFy/@zeZHxu7sIriIiFQeVUknXXW66M4u7/qrC56Wg6kOTyozHCzz01teP@bx1dwsbufmXtl511/PzWows8psPp5Xm/eXqcvrh@NZn8dxmpqGWjQsk0BlVc6FBxQUzUVH0V7xpZxCVNmR/E7KZ5BH2Nu3DfDDlJsUQBRwZOEYNaEGMcMnkBP@DbsOfwBrLddwDsEjBqQtZwQJYLXE/jI0p/hJmoxsUDecUKsosWyE9/vOJMc/h3qNELtB@oSSn8QHiwVxQxIACVEOmeDFAGsEiUPctp8 "Brachylog – Try It Online") Outputs through predicate success or failure, as Leaky Nun's Brachylog v1 answer does. Takes a similar approach, as well, but comes out a lot shorter. ``` a₁ There exists a suffix of the input = the elements of which are all equal . which is the output variable l the length of which ∈ is an element of the output variable. ``` # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḅt.l≥∈ ``` [Try it online!](https://tio.run/##nU/LSgMxFP2VIQtXx5J7J8mYjT8yzKJK1cWAUCuDtN1UlOnOnxC3bgTxbyY/Mt6bFsEiInLyOCe5yT3nbD49v7prry95XHamOD4tTHe0TI@vaXOf@hezmN/OzErZxbS9mZl1ZyaFGT626@HtaRzeHxaTNm2fU9@PY11Tg5plEiivyjlzj4ysOesg2im@VKkQlXdEt5fyGeQRDvZdA/ww5SZ6EHmcWJSMilCBmOEiqBT@DfsOfwBrLVcoS3iH4BF3nOElgNUS@8vQnOInajKyXt1wRKUix7IBzh06kxz/HOo1QOx66eNzfhIfLBbEDUkARAQ5ZIITA6wRJA5x03wC "Brachylog – Try It Online") An alternate version that comes out to the same length which takes some inspiration from Dennis' Jelly answer. ``` t The last ḅ block of consecutive equal elements of the input . is the output variable l the length of which ≥ is greater than or equal to ∈ an element of the output variable. ``` [Answer] # [Retina](http://github.com/mbuettner/retina), 34 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* \b(1(1)*)(?<-2>¶\1)*$(?(2)!) ``` Input is a linefeed-separated list of integers. Prints `0` or `1`. [Try it online!](http://retina.tryitonline.net/#code=JShTYFxzCi4rCiQqClxiKDEoMSkqKSg_PC0yPsK2XDEpKiQoPygyKSEp&input=MQoxIDEKMiAxCjIgMgo1IDYgNSAzIDMgMwoxIDEgMiAyIDEgMSAyIDIgMSAxIDIgMgo5NSAxMTUgODAgMzIgNzEgNyAxMjIgNDkgMTMgNyA3IDcgNyA3IDcgNyA3CjI3IDMzIDU0IDY1IDk3IDMzIDUyIDU1IDYwIDEgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTAgMTAKMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUgMTUKMgoxIDIKNSA1IDUgNQo1IDYgNSA0IDQgNAozIDMgMyA5NCAzIDMKMSAyIDEgMiAxIDIgMSAyIDEgMiAxIDIKMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxMjcKNTAgMzkgOTQgMTA1IDQ5IDI5IDc0IDEwMiAyIDEwNiA0NCA3IDcgNyA3IDcgNwoyNiAyNyA1OSAyNSAxMjIgMTEwIDIwIDMwIDExNCA2IDkgNjIgMTIxIDQyIDIyIDYwIDMzIDEy) (The first line enables a test suite, where there is one space-separated test case per line.) An alternative idea that ends up at 35 bytes and prints `0` or a positive integer: ``` .+ $* \b(?=(1+)(¶\1)*$)(?<-2>1)*1\b ``` [Answer] ## Pyke, 7 bytes ``` eQ>}lt! ``` [Try it here!](http://pyke.catbus.co.uk/?code=eQ%3E%7Dlt%21&input=%5B95%2C+115%2C+80%2C+32%2C+71%2C+7%2C+122%2C+49%2C+13%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%5D&warnings=0) [Answer] # Javascript (ES5), 89 bytes ``` function(b){for(var d=b[b.length-1],c=0;c<d;c++)if(b[b.length-c-1]!=d)return!1;return!0}; ``` Ungolfed: ``` function a(arr){ var b=arr[arr.length-1]; for(var i=0;i<b;i++){ if(arr[arr.length-i-1]!=b)return false; } return true; } ``` ]
[Question] [ Write the shortest possible assembly-language [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29). Use any ISA you want, unless it has a `print-quine` instruction or equivalent. Examples include x86, MIPS, SPARC, MMIX, IBM BAL, MIX, VAX, JVM, ARM, etc. You may link against the C standard library's `_printf` function (or the Java equivalent for JVM bytecode) for I/O. Length will be judged both on instruction count and size of the data segment. Solutions must contain at least two instructions. The quine should print the *assembly* code, not the assembled machine code. [Answer] ## x86 Linux, AT&T syntax: 244 ``` push $10 push $34 push $s push $34 push $37 push $37 push $s call printf mov $0,%ebx mov $1,%eax int $128 s:.ascii "push $10 push $34 push $s push $34 push $37 push $37 push $s call printf mov $0,%cebx mov $1,%ceax int $128 s:.ascii %c%s%c%c" ``` (I compiled it with this: `gcc -nostartfiles -lc quine.S -o quine`) [Answer] # gas for x86 Linux (~~89~~ 88 bytes, seven instructions) Technically, this is cheating. ``` mov $4,%al mov $1,%bl mov $b,%ecx mov $89,%dl int $128 mov $1,%al int $128 b:.incbin"a" ``` Save in a file named `a` and assemble with the following commands to create the executable named `a.out`. ``` as -o a.o <a ; ld a.o ``` The directive `.incbin` includes a file verbatim at the current location. If you use this to include the source code itself, you get a nice quine. [Answer] ### JVM Bytecode Assembly (via [Jasmin](http://jasmin.sourceforge.net)) – 952 ~~960~~ ~~990~~ ``` .class public Q .super java/io/File .method public static main([Ljava/lang/String;)V .limit stack 9 getstatic java/lang/System/out Ljava/io/PrintStream; ldc ".class public Q%n.super java/io/File%n.method public static main([Ljava/lang/String;)V%n.limit stack 9%ngetstatic java/lang/System/out Ljava/io/PrintStream;%nldc %c%s%c%nldc 3%nanewarray java/lang/Object%ndup%ndup%nldc 0%nldc 34%ninvokestatic java/lang/Integer/valueOf(I)Ljava/lang/Integer;%ndup_x2%naastore%nldc 2%nswap%naastore%ndup2%nswap%nldc 1%nswap%naastore%ninvokevirtual java/io/PrintStream/printf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;%npop%nreturn%n.end method" ldc 3 anewarray java/lang/Object dup dup ldc 0 ldc 34 invokestatic java/lang/Integer/valueOf(I)Ljava/lang/Integer; dup_x2 aastore ldc 2 swap aastore dup2 swap ldc 1 swap aastore invokevirtual java/io/PrintStream/printf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream; pop return .end method ``` Sadly, Jasmin doesn't allow as many nice tricks as Microsoft's `ilasm` allows. But the JVM has a total of *six* different `dup` instructions that do all kinds of fun things. Reordering items on the stack is something .NET doesn't seem to support. In any case, I guess none of my two entries are serious contenders for shortest code but I guess it's hard to make them much shorter. Therefore just for completeness :-) Commented version with info about what's on the stack: ``` .class public Q .super java/io/File .method public static main([Ljava/lang/String;)V .limit stack 9 getstatic java/lang/System/out Ljava/io/PrintStream; ldc ".class public Q%n.super java/io/File%n.method public static main([Ljava/lang/String;)V%n.limit stack 9%ngetstatic java/lang/System/out Ljava/io/PrintStream;%nldc %c%s%c%nldc 3%nanewarray java/lang/Object%ndup%ndup%nldc 0%nldc 34%ninvokestatic java/lang/Integer/valueOf(I)Ljava/lang/Integer;%ndup_x2%naastore%nldc 2%nswap%naastore%ndup2%nswap%nldc 1%nswap%naastore%ninvokevirtual java/io/PrintStream/printf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;%npop%nreturn%n.end method" ldc 3 ; stack; System.out, string, 3 anewarray java/lang/Object ; stack: System.out, string, Object[3] dup dup ; stack: System.out, string, array, array, array ldc 0 ; stack: System.out, string, array, array, array, 0 ldc 34 ; stack: System.out, string, array, array, array, 0, 34 invokestatic java/lang/Integer/valueOf(I)Ljava/lang/Integer; dup_x2 ; stack: System.out, string, array, array, 34, array, 0, 34 aastore ; stack: System.out, string, array, array, 34 ldc 2 ; stack: System.out, string, array, array, 34, 2 swap ; stack: System.out, string, array, array, 2, 34 aastore ; stack: System.out, string, array dup2 ; stack: System.out, string, array, string, array swap ; stack: System.out, string, array, array, string ldc 1 ; stack: System.out, string, array, array, string, 1 swap ; stack: System.out, string, array, array, 1, string aastore ; stack: System.out, string, array invokevirtual java/io/PrintStream/printf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream; pop return .end method ``` **History:** * 2011-02-07 02:09 (990) – First working version. * 2011-02-07 02:11 (960) – `ldc` is shorter than `bipush` or `iconst_*`. * 2011-02-07 02:30 (952) – Who says I need to inherit from java.lang.Object? Other class names are so much shorter :-) [Answer] # GAS x86-64 for Linux (verified on GCC 10.1): ## ~~13 12~~ 5 instructions ## ~~148 136 129~~ 0 byte data section ### ~~298 274 260 51~~ 49 byte source code Self-imposed rules/assumptions: 1. No standard library (including `printf` and `main`) allowed. 2. No `.incbin` allowed. This is commonly considered input in quine challenges. 3. In a similar vein, I disallowed using the `-D` flag as this would likely trivialize the problem as well as any file-content accessing flags. All other flags are fair game. 4. If it's loaded in program memory, it's fair game. As long as no files are accessed. ``` lea .+174,%rsi;inc %di;lea 49,%dx;inc %ax;syscall ``` ### Annotated version: ``` // We rely on Linux initializing all GP registers to 0. // The filename is loaded into memory at this location: lea .+174,%rsi inc %di // Length lea 49,%dx inc %ax // Write string syscall // Since there are no valid instructions after this, it crashes. // Since Segfault info is not program output, we're good. ``` The ELF has no ".data" section. The program reads from the ".debug\_line" section as if it were one, so that's why it's 0 bytes. This requires some setup. ### The ~~Hacks~~ ~~Voodoo Magic~~ Setup Save the file as `lea .+174,%rsi;inc %di;lea 49,%dx;inc %ax;syscall.sx` (ie, source + `.sx`) and compile with: ``` % qFile='lea .+174,%rsi;inc %di;lea 49,%dx;inc %ax;syscall.sx' % gcc -g1 -nostdlib -no-pie $qFile -o quine ``` Explanation: * `-g1` adds debugging info to ELF, which handily injects the filename too! This also means it gets loaded into memory at runtime! * `-no-pie` is required for two reasons: 1. We want to load a non-RIP-relative address 2. The debugging info doesn't get ASLR'ed away. * `-nostdlib` means we don't have to use `main`. Verify with diff: ``` % ./quine > quineresult.sx; diff $qFile quineresult.sx [1] 52466 segmentation fault (core dumped) ./quine > quineresult.sx ``` The filename is not part of the true source code, as it is not part of the file's contents, which is why I only output this source one time. I originally penalized my source code because the filename is vital to the quine, but I realized that this was moot because the rules aren't scoring on source code size anyway. I guess this means I beat the accepted answer without `printf`! [Answer] ## Windows .COM Format: 307 characters Assembles, using A86, to 51 bytes. Requires no external libraries other than the DOS Int21 AH=9 function (write string to stdout). ``` db 185 db 51 db 0 db 190 db 0 db 1 db 191 db 47 db 1 db 172 db 178 db 10 db 199 db 6 db 45 db 1 db 32 db 32 db 180 db 0 db 246 db 242 db 128 db 196 db 48 db 136 db 37 db 79 db 10 db 192 db 117 db 242 db 180 db 9 db 186 db 42 db 1 db 205 db 33 db 226 db 221 db 195 db 100 db 98 db 32 db 32 db 51 db 49 db 10 db 13 db 36 ``` [Answer] # NASM, 223 bytes ``` %define a "%define " %define b "db " %define c "%deftok " %define d "a, 97, 32, 34, a, 34, 10, a, 98, 32, 34, b, 34, 10, a, 99, 32, 34, c, 34, 10, a, 100, 32, 34, d, 34, 10, c, 101, 32, 100, 10, b, 101, 10" %deftok e d db e ``` Beating the accepted answer! [Answer] ### .NET CIL – 623 ~~669~~ ~~691~~ ~~723~~ ~~727~~ ``` .assembly H{}.method void M(){.entrypoint.locals init(string)ldstr".assembly H{0}{1}.method void M(){0}.entrypoint.locals init(string)ldstr{2}{3}{2}stloc 0ldloc 0ldc.i4 4newarr object dup dup dup dup ldc.i4 0ldstr{2}{0}{2}stelem.ref ldc.i4 1ldstr{2}{1}{2}stelem.ref ldc.i4 2ldc.i4 34box char stelem.ref ldc.i4 3ldloc 0stelem.ref call void[mscorlib]System.Console::Write(string,object[])ret{1}"stloc 0ldloc 0ldc.i4 4newarr object dup dup dup dup ldc.i4 0ldstr"{"stelem.ref ldc.i4 1ldstr"}"stelem.ref ldc.i4 2ldc.i4 34box char stelem.ref ldc.i4 3ldloc 0stelem.ref call void[mscorlib]System.Console::Write(string,object[])ret} ``` A single line, no line break at the end. Formatted and commented first version (even though it isn't a quine anymore) – it's unlikely that I deviate much from the general concept: ``` .assembly H{} .method void M() { .entrypoint .locals init ( string, object[] ) // the string ldstr".assembly H{0}{1}.method void M(){0}.entrypoint.locals init(string,object[])ldstr{2}{3}{2}stloc.0 ldloc.0 ldc.i4.4 newarr object stloc.1 ldloc.1 ldc.i4.0 ldstr{2}{0}{2} stelem.ref ldloc.1 ldc.i4.1 ldstr{2}{1}{2} stelem.ref ldloc.1 ldc.i4.2 ldc.i4 34 box char stelem.ref ldloc.1 ldc.i4.3 ldloc.0 stelem.ref ldloc.1 call void[mscorlib]System.Console::Write(string,object[])ret{1}" stloc.0 // store in first local var ldloc.0 // load again. Going to be the first argument to Console::Write ldc.i4.4 newarr object stloc.1 // create new array and store in local var ldloc.1 ldc.i4.0 ldstr"{" stelem.ref // we need a literal brace ldloc.1 ldc.i4.1 ldstr"}" stelem.ref // closing, too ldloc.1 ldc.i4.2 ldc.i4 34 box char stelem.ref // double quote ldloc.1 ldc.i4.3 ldloc.0 stelem.ref // our format string from before ldloc.1 // load array call void[mscorlib]System.Console::Write(string,object[]) // output ret } ``` **History**: * 2011-02-06 16:48 (727) – First working version. * 2011-02-06 17:14 (723) – I don't need a space after a string literal. * 2011-02-06 17:21 (691) – `dup` is shorter than writing `ldloc.1` every time. * 2011-02-06 17:24 (669) – I don't need spaces after *any* literal and things like `ldloc.1` can be written as `ldloc 1` to make the last token a literal. The resulting bytecode is likely larger, but it's about the assembler code so I couldn't care less :-) * 2011-02-06 17:34 (623) – I don't need the `object[]` as a local variable; I can do all that on the stack directly. Nice. [Answer] # gas for x86 Linux, ~~184~~ 176 bytes ``` .globl main main:movw $34,B+87 push $B call printf call printf pop B ret .data B:.ascii".globl main main:movw $34,B+87 push $B call printf call printf pop B ret .data B:.ascii" ``` Build with `gcc -m32 -o a.out quine.S`. (The `-m32` is optional if your OS is already 32-bit.) **Edited to add:** If we modify the rules to allow `puts` to be called instead of `printf` then it can be done in ~~182~~ 174 bytes: ``` .globl main main:movw $34,B+86 push $B+1 call puts call puts pop B ret .data B:.ascii" .globl main main:movw $34,B+86 push $B+1 call puts call puts pop B ret .data B:.ascii" ``` (Note that this one, unlike the previous one, has a terminating newline.) [Answer] # Bootable ASM, 660 bytes ``` [bits 16] mov ax,07C0h mov ds,ax mov ah,0 mov al,03h int 10h mov si,code call p jmp $ p:mov ah,0Eh r:lodsb cmp al,0 je d cmp bx,0x42 jne s c:int 10h jmp r s: cmp al,94 je re cmp al,63 je q jmp c q:mov al,34 jmp c re:push si mov bx,0x42 mov si,code call p mov bx,0 pop si jmp p d:ret code:db "[bits 16]\mov ax,07C0h\mov ds,ax\mov ah,0\mov al,03h\int 10h\mov si,code\call p\jmp $\p:mov ah,0Eh\r:lodsb\cmp al,0\je d\cmp bx,0x42\jne s\c:int 10h\jmp r\s:cmp al,94\je re\cmp al,63\je q\jmp c\q:mov al,34\jmp c\re:push si\mov bx,0x42\mov si,code\call p\mov bx,0\pop si\jmp p\\d:ret\\code:db ?^?\times 510-($-$$) db 0\dw 0xAA55" times 510-($-$$) db 0 dw 0xAA55 ``` Originally by [jdiez17](https://github.com/jdiez17/quines/tree/master/bootable_quine), golfed by yours truly. [Answer] ## x86-64, System V AMD64 ABI, GASM: 432 ``` .att_syntax noprefix .globl main main: pushq rbp movq rsp, rbp mov $.Cs, rdi mov $0xa, rsi mov $0x22, edx mov $.Cs, ecx mov $0x22, r8d mov $0xa, r9d xor eax, eax call printf xor eax, eax leave ret .Cs: .string ".att_syntax noprefix .globl main main: pushq rbp movq rsp, rbp mov $.Cs, rdi mov $0xa, rsi mov $0x22, edx mov $.Cs, ecx mov $0x22, r8d mov $0xa, r9d xor eax, eax call printf xor eax, eax leave ret%c.Cs: .string %c%s%c%c" ``` [Answer] # 80x86 TASM, 561 bytes ``` MODEL TINY .CODE .STARTUP DB 177 DB 076 DB 186 DB 044 DB 001 DB 172 DB 180 DB 036 DB 179 DB 004 DB 191 DB 080 DB 001 DB 079 DB 136 DB 037 DB 212 DB 010 DB 004 DB 048 DB 134 DB 196 DB 075 DB 117 DB 244 DB 180 DB 009 DB 205 DB 033 DB 178 DB 071 DB 226 DB 228 DB 178 DB 038 DB 205 DB 033 DB 195 DB 013 DB 010 DB 069 DB 078 DB 068 DB 036 DB 077 DB 079 DB 068 DB 069 DB 076 DB 032 DB 084 DB 073 DB 078 DB 089 DB 013 DB 010 DB 046 DB 067 DB 079 DB 068 DB 069 DB 013 DB 010 DB 046 DB 083 DB 084 DB 065 DB 082 DB 084 DB 085 DB 080 DB 013 DB 010 DB 068 DB 066 DB 032 END ``` [Answer] I wrote this in assembly on paper and assembled it into machine code by hand with an opcode chart. I then entered the machine code into the program editor on the TI-84 Plus CE and executed it with asm(. It starts at it's own load address, copies that byte into the accumulator, then makes a system call that prints the contents of the accumulator in ascii on the display and repeats for every byte of the program, essentially printing it's own machine code.... Is it technically a quine because I didn't use a computer to assemble it and because the exact code I entered into the calculator is printed by the program itself? This is ez80 machine language on a TI-84 Plus CE: 34 bytes. First byte loads @ D1A881, whitespace ignored: ``` 181F 50 7E 23 0602 4F 07070707 E60F C630 FE3A 3802 C607 CDB80702 79 10EF 42 10E2 C9 C9 ``` [Answer] ## [TAL](http://wiki.tcl.tk/2561) ``` push puts push \100 push {push puts push \100 push {@} dup strmap invokeStk 2} dup strmap invokeStk 2 ``` To execute it, call `::tcl::unsuppoted::assemble` with the code as argument. Tcl 8.6 only. ]
[Question] [ *[Sandbox post (deleted)](https://codegolf.meta.stackexchange.com/a/16701/78039)* The old roman army formations are very famous around the world. In these formations roman legionaries grouped in a geometric shape (usually a rectangle) protecting the flanks and the superior part of it using their shields. The legionaries at interior positions covered the superior part placing their shield above their heads, the legionaries at the flanks carried 2 or more shields: one for protecting the superior part, and one or more shields for protecting the flanks (if someone was in the corner he had 3 shields, if someone was alone in a formation he had 5 shields *Yes, I know it is impossible for a human to carry 5 shields, but somehow they did it*). Using this formation all roman legionaries protected themselves and were the hardest opponent at the time. The history tells there was a roman general who stated that the best formation shape was the square (same number of legionaries in rows and columns). The problem was figuring out how many formations (and the size) he should split his army in order to: * Do not left any legionary out of a formation (although he admitted single legionary formation) * Reduce the amount of required shields The general, after doing some math and calculations, he figured out that the best way to accomplish this 2 conditions is to **start with the biggest square possible, and then repeat until no legionaries left**. --- **Example:** If 35 legionaries in his army, the formation consisted in * A 5x5 legionaries square (This is the biggest square possible). With the remaining legionaries (10) * A 3x3 square With the remaining legionaries (1) * A 1x1 square. At the end it will look something like this: ``` 5x5 * * * * * 3x3 * * * * * * * * 1x1 * * * * * * * * * * * * * * * * * * * * * * ``` *The legionaries at interior positions covered the superior part placing their shield above their heads*. They only needed 1 shield. ``` * * * * * * 1 1 1 * * * * * 1 1 1 * * 1 * * * 1 1 1 * * * * * * * * * ``` *The legionaries at the flanks carried 2* ``` * 2 2 2 * 2 1 1 1 2 * 2 * 2 1 1 1 2 2 1 2 * 2 1 1 1 2 * 2 * * 2 2 2 * ``` *If someone was in the corner he had 3 shields* ``` 3 2 2 2 3 2 1 1 1 2 3 2 3 2 1 1 1 2 2 1 2 * 2 1 1 1 2 3 2 3 3 2 2 2 3 ``` *If someone was alone in a formation he had 5 shields* ``` 3 2 2 2 3 2 1 1 1 2 3 2 3 2 1 1 1 2 2 1 2 5 2 1 1 1 2 3 2 3 3 2 2 2 3 ``` This formation required a total of 71 shields. --- **Challenge** * Calculate the amount of shields that are needed for a X amount of legionaries **Input** * Amount of legionaries in the army **Output** * Amount of shields needed. **Test Cases** ``` 35 => 71 20 => 44 10 => 26 32 => 72 ``` --- * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ ~~50~~ 48 bytes ``` def f(s):n=s**.5//1;return s and(n+4)*n+f(s-n*n) ``` [Try it online!](https://tio.run/##TctNCoAgEEDhfaeYZRr9OFlB4WGCjFZTOLbo9CYJ1fbjvePy204YwmJXWHMWIxmWsurqWk3O@tMRMMy05FRoIamITUmSRJiZrfPxgUaAMQBN9lLbPTSojzBVWn@kEmH/GzGNGG4 "Python 2 – Try It Online") New to code golf, but giving it my best swing! **Method:** Sum `n^2 + 4n` where `n` is each of the largest square numbers that sum to the input. **Edit 1** Reduced to 50 bytes thanks to @Jonathan Frech! **Edit 2** Switched `int(s**.5)` to `s**.5//1` to save 2 bytes thanks to @ovs [Answer] # [R](https://www.r-project.org/), ~~51~~ 50 bytes ``` f=function(x,y=x^.5%/%1)"if"(x,y^2+4*y+f(x-y^2),0) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQqfStiJOz1RVX9VQUykzTQkkEmekbaJVqZ2mUaELZGvqGGj@L04sKMip1DC0MjLVSdP8DwA "R – Try It Online") A square of side length \$y\$ must have exactly \$y^2+4y\$ shields. We reduce by the largest square less than or equal to \$x\$ until \$x\$ is zero, accumulating the number of shields as we go. Proof: Given a perfect square of side length \$y\$, we need precisely 1 shield for each member of the square. Next, for each member on the edge, we need an additional shield. There are \$(y-2)^2\$ members *not* on the edges, so there are \$y^2-(y-2)^2\$ members on the edges. Finally, for each corner, we need an additional shield. Apart from the case where \$y=1\$, we can thus add 4. This simplifies to \$y^2+4y\$ which fortunately also yields the correct value of \$5\$ when \$y=1\$, allowing us to use it for all \$y\$. [Answer] # JavaScript (ES7), 34 bytes ``` f=n=>n&&(w=n**.5|0)*w+w*4+f(n-w*w) ``` [Try it online!](https://tio.run/##XcyxDkAwEADQ3VeYpD2hVMtU/yKlQuQqiFv8ew0szC95c3d2u92m9cjQ90MIzqBpMUkYGQTI9VVwoJRApY5hRkA8WI@7X4Z88SNzrNKcx0LETRl9QRYPKPWD8gVZ/6CSbyXDDQ "JavaScript (Node.js) – Try It Online") ### How? At each iteration, we compute the width \$w = \lfloor\sqrt{n}\rfloor\$ of the largest possible square. The number of shields \$s\_w\$ for this square is given by: $$s\_w = w^2+4w$$ For instance, for \$w=3\$: $$\begin{align}&\pmatrix{3 & 2 & 3\\2 & 1 & 2\\3 & 2 & 3}=&(s\_3=21)\\&\pmatrix{1 & 1 & 1\\1 & 1 & 1\\1 & 1 & 1}+&(3^²=9)\\&\pmatrix{1 & 1 & 1\\0 & 0 & 0\\0 & 0 & 0}+\pmatrix{0 & 0 & 1\\0 & 0 & 1\\0 & 0 & 1}+\pmatrix{0 & 0 & 0\\0 & 0 & 0\\1 & 1 & 1}+\pmatrix{1 & 0 & 0\\1 & 0 & 0\\1 & 0 & 0}&(4\times3=12)\end{align}$$ The formula holds for \$w=1\$, as \$s\_1=5\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ƽ²ạƊƬ_Ɲ½ẋ4S+ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//w4bCvcKy4bqhxorGrF/GncK94bqLNFMr////MzU "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # [Julia 0.6](http://julialang.org/), 36 bytes ``` !n=(s=isqrt(n))*s+4s+(n>0&&!(n-s*s)) ``` [Try it online!](https://tio.run/##DcVNCoAgEEDhvacYNzKTBWU/u7pLUIERUzkG3t6E9/HO7/LrlLPmGWX28oaITFSJHcQiL60xGrmRSojycQdI4BmwraErlbmid8VICuAJnuPFqBOpnbf8Aw "Julia 0.6 – Try It Online") Uses the same \$ n^2 + 4n \$ method as @Giuseppe's R answer, though my method to arrive there involved less meaningful thinking and more just visual inspection: the inner square of 1s has dimensions \$ (n - 2) \$ by \$ (n - 2) \$, so that has \$ (n - 2)^2 \$ shields. Surrounding that, there are 4 walls of \$ n - 2 \$ soldiers each, each with 2 shields - so that adds \$ 4\*(n - 2)\*2 \$ shields. Finally, there are four 3s in the four corners, so that adds 12 shields. $$ (n-2)^2 + 4\*(n-2)\*2 + 4\*3 = n^2 + 4 - 4n + 8n - 16 + 12 = n^2 + 4n $$ ### Ungolfed: ``` !n = begin # Assign to ! operator to save bytes on function parantheses s = isqrt(n) # Integer square root: the largest integer m such that m*m <= n s * s + 4 * s + (n > 0 && # evaluates to false = 0 when n = 0, otherwise recurses !(n - s * s)) end ``` (This can also be done it in 35 bytes with `n>0?(s=isqrt(n))*s+4s+f(n-s*s):0`, but I wrote this for Julia 0.7 wanted to avoid the new deprecation warnings (requiring spaces are `?` and `:`).) [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ëñ|^○╖?║<l╛P╝z√ ``` [Run and debug it](https://staxlang.xyz/#p=89a47c5e09b73fba3c6cbe50bc7afb&i=35%0A20%0A10%0A32%0A482&a=1&m=2) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes ``` 0|⟧^₂ᵐ∋N&;N-ℕ↰R∧N√ȧ×₄;N,R+ ``` [Try it online!](https://tio.run/##AUAAv/9icmFjaHlsb2cy//8wfOKfp17igoLhtZDiiItOJjtOLeKEleKGsFLiiKdO4oiayKfDl@KChDtOLFIr//8zNf9a "Brachylog – Try It Online") ``` 0 % The output is 0 if input is 0 | % Otherwise, ⟧ % Form decreasing range from input I to 0 ^₂ᵐ % Get the squares of each of those numbers ∋N % There is a number N in that list &;N-ℕ % With I - N being a natural number >= 0 i.e. N <= I % Since we formed a decreasing range, this will find the largest such number ↰ % Call this predicate recursively with that difference I - N as the input R % Let the result of that be R ∧N√ȧ % Get the positive square root of N ×₄ % Multiply by 4 ;N,R+ % Add N and R to that % The result is the (implicit) output ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes ``` .+ $* (\G1|11\1)+ $&11$1$1 . ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSyPG3bDG0DDGUBPIVTM0VAFCLr3//41NuYwMuAwNuIyNAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to decimal. ``` (\G1|11\1)+ ``` Match odd numbers. The first pass through the group, `\1` doesn't exist yet, so only `\G1` can match, which matches 1. Subsequent matches can't match `\G1` since `\G` only matches at the beginning of the match, so instead we have to match the `11\1` which is 2 more than the previous match. We match as many odd numbers as we can, and the total match is therefore a square number, while the last capture is one less than twice its side. ``` $&11$1$1 ``` Add the side shields to each match. `$&` is \$n^2\$ and `$1` is \$2n-1\$ while we need \$n^2+4n=n^2+2+2(2n-1)\$. ``` . ``` Sum and convert to decimal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [Ð_#tïÐns4*+Šn-}O ``` [Try it online](https://tio.run/##MzBNTDJM/f8/@vCEeOWSw@sPT8grNtHSProgT7fW//9/Y1MA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/@jDE@KVSw6vPzwhr9hES/vogjzdWv//Ov@NTbmMDLgMDbiMjQA). Work-around because `ΔDtïÐns4*+Šn-}O` (**15 bytes**) doesn't seem to work.. [Try it online in debug-mode to see what I mean.](https://tio.run/##MzBNTDJM/f//3BSXksPrD0/IKzbR0j66IE@31v//f2PT/7opAA) I would expect it to go from `[45,'35',25]` to `[45,10]` after the `-` and next iteration of `Δ`, but apparently it clears the stack except for the last value and becomes `[10]`, resulting in 0 at the very end.. Not sure if this is intended behavior or a bug.. (EDIT: It's intended, see bottom.) **Explanation:** Also uses \$w^2+4w\$ where \$w\$ is the width in a loop like most other answers. ``` [ } # Start an infinite loop: Ð # Triplicate the value at the top of the stack _# # If the top is 0: break the infinite loop t # Take the square-root of the value # i.e. 35 → 5.916... ï # Remove any digits by casting it to an integer, so we have our width # i.e. 5.916... → 5 Ð # Triplicate that width n # Take the square of it # i.e. 5 → 25 s # Swap so the width is at the top again 4* # Multiply the width by 4 # i.e. 5 → 20 + # And sum them together # i.e. 25 + 20 → 45 Š # Triple-swap so the calculated value for the current width # is now at the back of the stack # i.e. [35,5,45] → [45,35,5] n # Take the square of the width again # 5 → 25 - # Subtract the square of the width from the value for the next iteration # i.e. 35 - 25 → 10 O # Take the sum of the stack # i.e. [45,21,5,0,0] → 71 ``` --- EDIT: Apparently the behavior I described above for `Δ` is intended. Here two 17-bytes alternatives provided by *@Mr.Xcoder* that do use `Δ` by putting values in the global\_array (with `^`) and retrieving them again afterwards (with `¯`): ``` ΔЈtïnα}¯¥ÄDt··+O ``` [Try it online](https://tio.run/##AScA2P8wNWFiMWX//86Uw5DLhnTDr27OsX3Cr8Klw4REdMK3wrcrT///MzU) or [verify all test cases](https://tio.run/##AUQAu/8wNWFiMWX/fHZ5PyIg4oaSICI/eSL/zpTDkMuGdMOvbs6xfcKvwqXDhER0wrfCtytP/yIuVizCtP8zNQoyMAoxMAozMg). ``` ΔЈtïnα}¯¥ÄtD4+*O ``` [Try it online](https://tio.run/##ASUA2v8wNWFiMWX//86Uw5DLhnTDr27OsX3Cr8Klw4R0RDQrKk///zM1) or [verify all test cases](https://tio.run/##AUIAvf8wNWFiMWX/fHZ5PyIg4oaSICI/eSL/zpTDkMuGdMOvbs6xfcKvwqXDhHRENCsqT/8iLlYswrT/MzUKMjAKMTAKMzI). [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 25 bytes ``` d[dvddSa*-d0<MLa+]dsMx4*+ ``` [Try it online!](https://tio.run/##S0n@b2z0PyU6pSwlJThRSzfFwMbXJ1E7NqXYt8JES/t/wX8A "dc – Try It Online") Calculates the shields as `sum(n^2)` (the original number) plus `4*sum(n)` by pushing a copy of each square side length into stack register `a` as it goes, then adding all the values from register `a` as the recursion "unrolls". [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` ṁS+o*4√Ẋ≠U¡S≠(□⌊√ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxmDtfC2TRx2zHu7qetS5IPTQwmAgpfFo2sJHPV1A4f///xsbAQA "Husk – Try It Online") ### Alternative ``` ṁS*+4m√Ẋ≠U¡S≠(□⌊√ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxmAtbZPcRx2zHu7qetS5IPTQwmAgpfFo2sJHPV1A4f///xsbAQA "Husk – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ 30 bytes ``` {⍵<2:⍵×5⋄(S×S+4)+∇⍵-×⍨S←⌊⍵*.5} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71YbIysgeXi66aPuFo3gw9ODtU00tR91tAMFdQ9Pf9S7IvhR24RHPV1Avpaeae3/R31TgQJk6Dy0wthUwchAwdBAwdjoPwA "APL (Dyalog Unicode) – Try It Online") -1 byte thanks to @jslip [Answer] # [Ruby](https://www.ruby-lang.org/), 45 bytes ``` ->n{n+(1..n).sum{n-=(z=(n**0.5).to_i)*z;z*4}} ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr3hU08WyTmEfEYk6BB3cohJM8@02c4X1rZupcsKMDW0BkMEdfEZpaDIUOVcwMHiOeWc8jYn3pVSrB9Ep0SqhOwd@OfMXP3KG5yabja7UHw "Ruby – Try It Online") [Answer] # [PHP](http://www.php.net/), 67 bytes ``` <?for($n=$argv[1];$w=(int)sqrt($n);$n-=$w**2)$a+=$w**2+$w*4;echo$a; ``` To run it: ``` php -n <filename> <n> ``` Example: ``` php -n roman_army_shields.php 35 ``` Or [Try it online!](https://tio.run/##K8go@P/fxj4tv0hDJc9WJbEovSzaMNZapdxWIzOvRLO4sKgEKKFprZKna6tSrqVlpKmSqA1haQNJE@vU5Ix8lUTr////G5v@yy8oyczPK/6vmwcA "PHP – Try It Online") --- Using `-R` option, this version is **60 bytes**: ``` for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a; ``` Example: ``` echo 35 | php -nR "for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a;" ``` *(on Linux, replace `"` with `'`)* --- **Note:** This is using [Arnauld's answer](https://codegolf.stackexchange.com/a/169872/81663) great formula, I was not able to find anything shorter than that. [Answer] # [Pyth](https://pyth.readthedocs.io), 19 bytes A recursive function, which should be called using `y` (see the link). ``` L&b+*Ks@b2+4Ky-b^K2 ``` [Try it here!](https://pyth.herokuapp.com/?code=L%26b%2B%2aKs%40b2%2B4Ky-b%5EK2%3By&input=32&debug=0) # [Pyth](https://pyth.readthedocs.io), 21 bytes The revision history is quite funny, but make sure to visit it if you want a much faster version :) ``` sm*d+4deeDsI#I#@RL2./ ``` [Try it here!](https://pyth.herokuapp.com/?code=sm%2ad%2B4deeDsI%23I%23%40RL2.%2F&input=32&debug=0) ### Explanation ``` sm*d+4deeDsI#I#@RL2./ Full program, let's call the input Q. ./ Integer partitions of Q. Yields all combinations of positive integers that add up to Q. @RL2 Take the square root of all integers of each partition. I# Keep only those partitions that are invariant under: sI# Discarding all non-integers. This basically only keeps the partitions that are formed fully of perfect squares, but instead of having the squares themselves, we have their roots. eeD Get the partition (say P) with the highest maximum. m For each d in P ... *d+4d ... Yield d*(d+4)=d^2+4d, the formula used in all answers. s Sum the results of this mapping and implicitly output. ``` [Answer] # [Swift 4](https://developer.apple.com/swift/), ~~111 99 84~~ 78 bytes ``` func f(_ x:Int)->Int{var y=x;while y*y>x{y-=1};return x>0 ?(y+4)*y+f(x-y*y):0} ``` [Try it online!](https://tio.run/##DcpLCoUwDADAq2SZKAV/K8W@tacQEYMFKVLrM0E8e3Uzqzkux7FJiU8/A@MI0g4@krGf938KoL101@q2BTRTK7eavny6sMQzeBBbwA81byjTnFHMd6gtnrQH5yMy1hVRegE "Swift 4 – Try It Online") That feel when implementing integer square root manually is *far* shorter than the built-in... ## Ungolfed and Explained ``` // Define a function f that takes an integer, x, and returns another integer // "_" is used here to make the parameter anonymous (f(x:...) -> f(...)) func f(_ x: Int) -> Int { // Assign a variable y to the value of x var y = x // While y squared is higher than x, decrement y. while y * y > x { y -= 1 } // If x > 0, return (y + 4) * y + f(x - y * y), else 0. return x > 0 ? (y + 4) * y + f(x - y * y) : 0 } ``` ]
[Question] [ # Satan-Primes who are they? they are `Primes` containing `666` these are Satan-Primes:`[46663,266677,666599,666683,616669]` these are **NOT** :`[462667,665669,36363631,555]` # Plot *Every number bigger than 6661 has Satan-Primes behind him* # The Challenge Given an integer `n>6661` find the Satan-Prime **behind (or equal) and closest** to itself. # Examples Integer `n=30000` has 3 Satan-Primes(SP) behind it:`[6661, 16661, 26669]`. Your code must return `26669` which is the closest behind it # Test Cases Input->Output ``` 6662->6661 10000->6661 66697->66697 (a SP returns himself) 328765->326663 678987->676661 969696->966677 ``` # Rules Yor code should work for any `n` in the range of your language. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Neim](https://github.com/okx-code/Neim), 9 bytes ``` >ͻ:D+6S𝕚÷ ``` Explanation: ``` > Increment input ͻ Start infinite loop : Previous prime D Duplicate +6 Push 666 S Swap 𝕚 See if 666 is a substring of the top of the stack ÷ If true, break ``` [Try it online!](https://tio.run/##y0vNzP3/3@7sbisXbbPgD3Onzjq8/f9/MzMzS3MA "Neim – Try It Online") [Answer] # Mathematica, 82 bytes ``` Last@Select[Prime@Range@PrimePi@#,!FreeQ[Subsequences[IntegerDigits@#],{6,6,6}]&]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes Saved 10% thanks to @Dennis! ``` ÆRwÐf666Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW1D54QlpZmZmD3eu@m99uF3lUdMabyCO/P8/GihqpGNoAAQ6QKaluY6xkYW5mamOmbmFpYW5jqUZCMYCAA "Jelly – Try It Online") ### Explanation ``` ÆR # All primes in range [2, input] Ðf # Keep those which satisfy w # truthy if y is in x 666 # ^ (this is y) Ṫ # Tail (take the last element) ``` [Answer] # [Pyth](https://pyth.readthedocs.io), ~~15~~ 14 bytes *Saved 1 byte with help from Dave*. Memory errors for `969696` and anything higher on my machine, but it is fine if it is given enough memory. ``` ef&/`T*3\6P_TS ``` **[Try it here](https://pyth.herokuapp.com/?code=ef%26%2F%60T%2a3%5C6P_TS&input=10000&test_suite_input=6662%0A10000%0A66697%0A76667%0A328765&debug=0) or check out the [Test Suite.](https://pyth.herokuapp.com/?code=ef%26%2F%60T%2a3%5C6P_TS&input=6662-%3E6661++++%0A10000-%3E6661++++%0A66697-%3E66697+%28a+SP+returns+himself%29++%0A328765-%3E326663++%0A678987-%3E676661%0A969696-%3E966677&test_suite=1&test_suite_input=6662%0A10000%0A66697%0A328765&debug=0)** --- # How? ``` ef&/`T*3\6P_TSQ - Full program, with implicit input (Q) at the end SQ - Range [1,Q] f - Filter. P_T - Is prime? & - And /`T*3\6 - It contains 666. e - Last element. - Implicitly output the result. ``` # [Pyth](https://pyth.readthedocs.io), 14 bytes ``` ef/`T*\63fP_TS ``` **[Try it here!](http://pyth.herokuapp.com/?code=ef%2F%60T%2a%5C63fP_TS&input=10000&debug=0)** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ƒNpN666å*iN ``` [Try it online!](https://tio.run/##MzBNTDJM/f//2CS/Aj8zM7PDS7Uy/f7/NzYAAgA "05AB1E – Try It Online") [Answer] # Bash + Core Utils, 51 49 Bytes ``` seq $1|tac|factor|awk 'NF==2&&/666/&&!a--&&$0=$2' ``` Takes command line argument. Can be quite slow with larger numbers. [Answer] # Mathematica, ~~64~~ ~~62~~ ~~61~~ 53 bytes ``` #//.i_/;!PrimeQ@i||ToString@i~StringFreeQ~"666":>i-1& ``` *-1 byte thanks to @KellyLowder* *-8 bytes (wow) thanks to @Notatree* ## Explanation Take an input. We decrement it under these conditions: * the input is not prime, OR * the digits of the inputs does not contain three 6s in a row. We repeat that until a Satan prime is reached. [Answer] # [Perl 5](https://www.perl.org/), 47 bytes 46 bytes of code + 1 for `-p` ``` {$f=0|sqrt;1while$_%$f--;/666/*!$f||$_--*redo} ``` [Try it online!](https://tio.run/##K0gtyjH9/79aJc3WoKa4sKjE2rA8IzMnVSVeVSVNV9da38zMTF9LUSWtpkYlXldXqyg1Jb/2/38joLDlv/yCksz8vOL/ur6megaGBv91CwA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), 14 bytes ``` õ fj w æ_sø666 ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SBmaiB3IOZfc/g2NjY=&input=OTY5Njk2) Seeing as there *was* a 50% time-based bonus: Completes test case `969696` in under half a second. --- ## Explanation Implicit input of integer `U`. ``` õ ``` Generate an array of integers from `1` to `U`. ``` fj ``` Filter (`f`) primes. ``` w ``` Reverse. ``` æ_ ``` Return the first element that returns a truthy value (in this case `1`) when passed through a function that checks if ... ``` sø666 ``` The integer converted to a string (`s`) contains (`ø`) 666. --- ## Faster Alternative, 15 bytes Again, seeing as there was originally a time-based bonus, here's an alternative, and much faster, solution which I can't seem to golf any further. ``` U-@j *U´sø666}a ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=VS1AaiAqVbRz+DY2Nn1h&input=OTY5Njk2) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 128 bytes ``` param($n)function f($a){for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}for(){if($n-match666-and($n-eq(f $n))){$n;exit}$n--} ``` [Try it online!](https://tio.run/##HY1RCsIwEESvUmGFhBJEPyJSepilJnYhTWqbohD27HHj55uZx6zp47Z9diHUuuKGi4Ko/RGnTCl2XgHq4tOmgMbbAGhe@aoLeXWS5gykdQGS/DICsQu7E@x7Zm7OfwjRLJin2VprMD4bu7fyndw0OQ7uS5klNVxrldXj/gM "PowerShell – Try It Online") PowerShell doesn't have any prime factorization built-ins, so this borrows code from my answer on [Prime Factors Buddies](https://codegolf.stackexchange.com/a/94323/42963). We take input `$n`, then declare a new `function f` that calculates out the factors of input `$a`. If the input `$a` is prime, then this will return just `$a`. The main part of the program is the infinite `for()` loop. Inside the loop, we check if `$n` `-match`es against `666` and whether `$n` is prime (i.e., `$n` matches all of the factors of `$n`). If it is, we place `$n` on the pipeline and `exit`, with implicit output. Otherwise, we decrement `$n--` and continue the loop. [Answer] # [Python 2](https://docs.python.org/2/), 77 76 bytes **Edit:** -1 byte thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) Slow running time, runs in `O(n^2)` ``` lambda x:max(q for q in range(x+1)if"666"in`q`*all(q%t for t in range(2,q))) ``` [Try it online!](https://tio.run/##RYzLDsIgEEXX9ismTUxAWViMPJr0S9SkqEVJKC0tC/x6hG68s7mT3HPmb/hMjibd3ZJV4@OlILajisiDnhbwYBwsyr0HFI8NNrpmjNXG9b4/KGuR34dtF/47SjzGOD3VOqzQwTUDlDSnHJKr5ORMBWcXwriQghPJyt2rYilMEW1sW@3mxbiANCp/Vv4A) ## Another 76 bytes solution ``` lambda x:max(q*("666"in`q`*all(q%t for t in range(2,q)))for q in range(x+1)) ``` [Try it online!](https://tio.run/##RYzRDoIgGIWv8yn@ubWBcRG0QNx8EnOTSopNUZALe3qCbjrn5uzbzrd@wnuxLOr2Fic1358K9mZWO3IVKjnnpbGDGyo1TcgdA@jFQwBjwSv7GhEjDmOcofvD/UQxjg@1jRu00CUJJfScQtKUglxYLfiVcFHLWhDJc/siS/Ine37frmF9UxxWb2xAGmWWtF8) # With [SymPy](http://www.sympy.org/en/index.html) 73 bytes ``` lambda x:max(q for q in primerange(0,x+1)if"666"in`q`) from sympy import* ``` [Try it online!](https://tio.run/##HY1NDsIgFITXcoqXrkBZtDU@2iY9iZoUtSiJ/JR2UU6P4MxmJpnJ5@P2cbZNarylrzSPl4R9MHKnCygXYAFtwQdt5iDte6Y1308N06pCxErbaZkYUcEZWKPxEbTxLmzH9JTrvMII1zxreVNn8Rx7wc9tJ/DCUXR9J3iPxXdSUOVTaP/vQA6ZajeqaOmMpR8) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 69 64 bytes ``` param($s)for(;$s-notmatch666-or(2..($s/2)|?{!($s%$_)});$s--){}$s ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VYMy2/SMNapVg3L78kN7EkOcPMzEwXKGSkpweU1TfSrLGvVgSyVFXiNWs1QQp1NatrVYr///9vaAAEAA "PowerShell – Try It Online") * 328765 takes ~30 seconds on my machine, but times out the 60 second limit on Tio.run. * 678987 takes ~1.5 minutes. * 969696 takes ~4.5 minutes. [Answer] # C++ 389 bytes ``` #include <iostream> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> using namespace boost::random;typedef boost::multiprecision::cpp_int Z;int main(int,char**v){mt19937 m(clock());independent_bits_engine<mt11213b,256,Z>g(m);Z n{v[1]},p;while(p++<=n)if(miller_rabin_test(p,25,g)&&p.convert_to<std::string>().find( "666" )!=-1)std::cout<<p<<" ";} ``` This is a full program! You'll need Boost to compile it. (Or copy and paste into your favorite online C++ shell.) Run it from the command-line giving ***n*** as argument. Ungolfed: ``` #include <iostream> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> using namespace boost::random; typedef boost::multiprecision::cpp_int integer; int main( int argc, char** argv ) { mt19937 mt( clock() ); independent_bits_engine <mt11213b, 256, integer> rng( mt ); integer input {argv[ 1 ]}; integer possible; while (possible++ <= input) if ( // is_prime( possible ) miller_rabin_test( possible, 25, rng ) && // possible has "666" in it (possible.convert_to <std::string> ().find( "666" ) != std::string::npos)) std::cout << possible << " "; } ``` Shortcuts were made in terms of random number testing. The original code started testing possible primes at 6661 and incremented by two. You'll also get a compiler warning because of that (-1) there instead of npos. Still, this runs pretty quickly. It only took about 40 seconds to find all 214 satan primes under 1,000,000 on my old AMD Sempron 130. :^D [Answer] # Bash + bsd-games package, 33 * 2 bytes saved thanks to @FedericoPoloni. ``` primes 2 $[$1+1]|grep 666|tail -1 ``` [Try it online](https://tio.run/##NYyxDsIgFEV3v@IObIakYHxA/JSmA9qnktjS8Bj777QMnrOc6TyjfNs7F1SW@orCSCuIyMIMJz2Dw816R3eQ88E7BOo@MOcLToQrtIb6H9pW0sICCzUqczXT/im89dNeY/pBmzbnldsB). [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü>:Ñb/VP6─ ``` [Run and debug it](https://staxlang.xyz/#p=813e3aa5622f565036c4&i=6662%0A10000%0A66697%0A328765%0A678987%0A969696&a=1&m=2) Explanation (unpacked): ``` ^w:pc$666$#! Full program, implicit input-parsing ^ Increment input w do-while: :p Previous prime c$ Copy and stringify 666$ Push "666" # Number of occurences ! Logical not Implicit output ``` [Answer] # [R](https://www.r-project.org/), 57 bytes ``` (a=conf.design::primes(scan():1))[which(grepl(666,a))[1]] ``` -42 bytes from Dominic Van Essen's enormous golf. uses `grepl` to coerce values to string(since 666 cannot be considered a regex) and check for truthy values. Runs through the array in reverse to save 2 bytes. # [R](https://www.r-project.org/) + `conf.design`, ~~81 78~~ 99 bytes ``` library(conf.design);function(n){a=primes(1:n) a[max(which(grepl("666",as.character(a),fixed=T)))]} ``` [Try it on rdrr.io!](https://rdrr.io/snippets/embed/?code=library(conf.design)%0Ax%3Dfunction(n)%7B%0Aa%3Dprimes(1%3An)%0Aa%5Bmax(which(grepl(%22666%22%2Cas.character(a)%2C%20fixed%3DT)))%5D%7D%0Ax(6666)) My first R solution. +21 bytes after including library name. A simple filter. grepl returns true at indices with 666, which returns the truthy indices, and max gets the required index of the prime. [Answer] # MATL, 16 bytes ``` ZqP"@V'666'Xf?@. ``` Try it at [MATL Online](https://matl.io/?code=ZqP%22%40V%27666%27Xf%3F%40.&inputs=30000&version=20.4.0) **Explanation** ``` Implicitly grab input (n) Zq Compute the primes up to n (output is in increasing order) P Flip the array (so larger primes come first) " For each prime @V Convert it to a string '666' Push the string literal '666' to the stack Xf Find the location of '666' in the prime ? If it was present... @. Push it to the stack and break Implicitly display the stack contents ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~85 83~~ 80 bytes [Halvard's](https://codegolf.stackexchange.com/a/140505/59487) is 4 bytes shorter because it's done in Python 2. ``` lambda k:max(x for x in range(k+1)if"666"in str(x)*all(x%i for i in range(2,x))) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbKjexQqNCIS2/SKFCITNPoSgxLz1VI1vbUDMzTcnMzEwJKFZcUqRRoamVmJOjUaGaCVabiVBrpFOhqan5v6AoM69EI03D0AAIgHwA "Python 3 – Try It Online") Give it some time, it's extremely slow because of its `O(n^2)` complexity. [Answer] # JavaScript (ES6), ~~55~~ 54 bytes *-1 byte thanks to @ThePirateBay.* ``` f=n=>/666/.test(d=n)&eval("while(n%--d);d<2")?n:f(n-1) ``` **Very** slow with large inputs. Primality test adapted from [this code golf answer](https://codegolf.stackexchange.com/a/91309/69583). ## Timings * Input `10000` took 10 seconds * Input `328765` took 3 minutes * Input `678987` took 9 minutes * Input `969696` took 16 minutes ## Tests Some of these will hang your browser for several minutes. ``` f=n=>/666/.test(d=n)&eval("while(n%--d);d<2")?n:f(n-1) function test(n) { O.value="Working..." setTimeout(_=>{ let t = Date.now() O.value=`f(${n}) = ${f(n)} in ${(Date.now()-t)/1000}s` }, 10) } ``` ``` Tests<br> <button onclick="test(6662)">6662</button> <button onclick="test(10000)">10000</button> <button onclick="test(328765)">328765</button> <button onclick="test(678987)">678987</button> <button onclick="test(969696)">6662</button><br> Result<br> <input id=O type=text size=25 readonly> ``` ## Faster Version, 56 bytes Completes each test case in under a second. ``` f=n=>/666/.test(n)&&eval("for(d=2;n%d++;);d>n")?n:f(n-1) ;[6662, 10000, 328765, 678987, 969696].forEach(n=>console.log(`f(${n}) -> ${f(n)}`)) ``` [Answer] # Ruby, ~~67~~, ~~66~~, ~~58~~, 56 bytes Includes `+7` bytes for `-rprime` ``` ->z{z.downto(1).find{|x|/666/=~x.to_s&&x.prime?}} ``` It's pretty fast, computing values up to `~2^52` in about a second and `2^64` in under 5 minutes (2011 MBP, Ruby 2.3.1). [Answer] # [PHP](https://php.net/), 148 bytes ``` <?php $p=[2];$s=[];for($i=3;$i<=$argv[1];$i++){foreach($p as $q)if($i%$q===0)continue 2;$p[]=$i;if(strpos($i,'666')!==false)$s[]=$i;}echo end($s);?> ``` [Try it online!](https://tio.run/##JcpBCsIwEEDRq0QYaUJd1Ba6ScceJHQRamIC0kwz1Y149hjwb9@nQKVMMwUSQGj6RQOjWbRPWULEQUOcEGx@vM21Wmxb9anm7BokkLAsYFfR1/cMOyJ2ak3bEbeXE70GMgtC1NX5yJS4bpdmHMdGnRC9fbJTwP/n69aQhNvuEljp@VZKGbraDw "PHP – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 35 bytes ``` my&f={/666/&&.is-prime??$_!!f $_-1} ``` [Try it online!](https://tio.run/##FYtLCoAgFEW3chNx1s/oqfRbijRQCIrERhGt3eyeyeHADS7ulNJxCz89NRHVQlTbVYa4HW5ZuC0KD27L9k0DrvUG4xbTjOevL4M/I8Z8k2ibPGQ1Cp3UinqQ0kYrGPqZh/QB "Perl 6 – Try It Online") Straightforward recursive solution. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 117 115 112 bytes ``` f=>{for(int i=f;i>1;i--){int p=1,j=2;while(j<i)if(i%j++<1)p=0;if(p>0&$"{i}".Contains("666"))return i;}return 0;} ``` [Try it online!](https://tio.run/##NY5BS8QwEEbPza8YikrCbku7YhXS9CJ4Uljcg@eQTXRKTUqSrkjpb6@p6G2@x4N5KhTKeb1OAe07nL5D1J@cqEGGAEcykyxEGVHBxeEZXiRaykiWcHaRHiwIQBvLo/RB00dngxt0@arl@RmtpozxJD5NVrXJ2m9qByZNEKsR3Wycp4kBCsOxqzkWBZs3MIp634sD//rAQdO@RYaG4nW/27U1G0XF0xy76uYqn3HJy/Q4prJA86Zpcsa8jpO3gHz5uyq@rFvKf@Gbx6jpVkLtb@RClvX28HDf3P0A "C# (.NET Core) – Try It Online") * 2 bytes saved by removing unnecessary braces. * 3 bytes saved by combining `int` declarations. I'm sure this could be made shorter; maybe by recursively calling `func f` and removing the outer `for`-loop. ### Recursive Approach, 85 bytes ``` i=>{int p=1,j=2;while(j<i)if(i%j++<1)p=0;return p>0&$"{i}".Contains("666")?i:f(--i);} ``` [Try it online!](https://tio.run/##NY7BSsQwEIbPzVMMRSVht6XdQw@mqQfBk8KiB88hm@qUOC1JuiKlz15TwTkN838z85lQmNHbbQ5IH/D2E6L9ksw4HQKc2cKyEHVEA9cRL/CikbhgWRpnV@2BQAFSLM/aB8sfRwqjs@Wr1ZdnJMuFkAl8msm0iTruaAd92qHZuT1K/YaqW1IAk6qPgzrJ7090lg8tCuw53g6HQ1uLSVXS2zh7gqmr7m7yBde8TA9jMgo8b5omFw943/OiQCHXbb/@7/PuMVrec/rzWdm61VWqXw "C# (.NET Core) – Try It Online") I'm unsure how well this approach fits within the bounds of code-golf due to having to set the `Func<int,int> f = null` first, and that `f` is called again, but not counted towards the bytes. Any clarification would be appreciated. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅPR.Δ666å ``` [Try it online.](https://tio.run/##yy9OTMpM/f//cGtAkN65KWZmZoeX/v9vaAAEAA) (No test suite with all test cases, because it's a bit too slow.) **Explanation:** ``` ÅP # Push a list of primes below or equal to the (implicit) input-integer R # Reverse this list .Δ # Find the first value which is truthy for: 666å # Check whether it contains "666" as substring # (after which the found result is output implicitly) ``` The `666` can alternatively be `Ž2ć` (compressed 666) or `Ƶé·` (compressed 333 and then doubled). [Answer] # Java 8, 77 bytes ``` n->{for(int i=++n;i>1|!(n+"").contains("666");)for(i=--n;n%--i>0;);return n;} ``` [Try it online.](https://tio.run/##PZDBbsIwDIbvPIUXaVKjNhUwLW2J2svO48KRcchCmMKKixqXaWJ99i7tYLZk2b@s77d81BctjvvPwdTae3jVDq8zAIdk24M2FtbjOAlgorEiV0HpZ6F40uQMrAGhHFBU10PTTjuujGNUrlr8PEQYM8ZT0yAFto@YlJJxxafVUghU@CiEq@aKq9ZS1yKg6gc18s/dex34N5tL4/ZwCpBoQ63Dj@0ONP@77u5L1tOL9hZWgPZrPHq7uwbDZbKYh0hCW2TJ0zLP5HMis7zIs6SQY/Z8AgFsvj3ZU9p0lJ6DC9UY3akxW70RizE1/xK/PaMffgE) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type for(int i=++n; // Increase the input by 1 // Set `i` to this input+1 (setting `i` to anything above 1 is fine) i>1 // Continue looping as long as `i` is not 0 nor 1 |!(n+"").contains("666");) // or if `n` as String does not contain "666" as substring: for(i=--n; // Decrease `n` by 1 first // And then set `i` to this new `n` n%--i // Decrease `i` by 1 before every iteration >0;); // And continue looping as long as `n` does NOT evenly divide `i` return n;} // After both loops, return the modified `n` as result ``` If `for(i=n;n%--i>0;);` results in \$i<2\$, it means \$n\$ is a prime number (note: [this prime checker](https://codegolf.stackexchange.com/a/100149/52210) only works for \$n\geq2\$, which is fine in this case). [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ḟo`€d666dfṗṫ ``` [Try it online!](https://tio.run/##yygtzv7//@GO@fkJj5rWpJiZmaWkPdw5/eHO1f///zc0AAIA "Husk – Try It Online") ]
[Question] [ ## The Sequence Everyone knows the only even prime number is `2`. Ho-hum. But, there are certain even numbers `n` where, when concatenated with `n-1`, they *become* a prime number. For starters, `1` isn't in the list, because `10` isn't prime. Similarly with `2` (`21`), and `3` (`32`). However, `4` works because `43` is prime, so it's the first number in the sequence `a(1) = 4`. The next number that works (neither `6` (`65`) nor `8` (`87`) work) is `10`, because `109` is prime, so `a(2) = 10`. Then we skip a bunch more until `22`, because `2221` is prime, so `a(3) = 22`. And so on. Obviously all terms in this sequence are even, because any odd number `n` when concatenated with `n-1` becomes even (like `3` turns into `32`), which will never be prime. This is sequence [A054211](http://oeis.org/A054211) on OEIS. ## The Challenge Given an input number `n` that fits somewhere into this sequence (i.e., `n` concatenated with `n-1` is prime), output its position in this sequence. You can choose either 0- or 1-indexed, but please state which in your submission. ## Rules * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * 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. ## Examples The below examples are 1-indexed. ``` n = 4 1 n = 100 11 n = 420 51 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḊżṖVÆPS ``` A monadic link taking a sequence member and returning its index in the sequence. **[Try it online!](https://tio.run/##y0rNyan8///hjq6jex7unBZ2uC0g@P///4YGBgA "Jelly – Try It Online")** ### How? ``` ḊżṖVÆPS - Link: number, n Ḋ - dequeue (implicit range) = [ 2 , 3 , 4 ,... , n ] Ṗ - pop (implicit range) = [ 1 , 2 , 3 ,... , n-1 ] ż - zip = [[2,1],[3,2],[4,3],... , [n , n-1] ] V - evaluate as Jelly code = [ 21 , 32 , 43 ,... , int("n"+"n-1") ] ÆP - is prime? (vectorises) = [ 0 , 0 , 1 ,... , isPrime(int("n"+"n-1"))] S - sum ``` [Answer] # [Haskell](https://www.haskell.org/), ~~80~~ ~~75~~ 70 bytes *5 bytes save thanks to Laikoni* ``` p x=all((>0).mod x)[2..x-1] g n=sum[1|x<-[4..n],p$read$show=<<[x,x-1]] ``` [Try it online!](https://tio.run/##FcqxCsMgFEDRvV/xBocEzCNaCx00PyIOQkISqkZiS97Qf7d2uHCGu/nyWkKoNQMZH0LXTWOP8ZiBeisRaRDutkIy5ROt@JIerEJMjmd2Ln5mZTsuo7Ul/j9djX5PJp97erPoM6xWcRAjBylbzfeWan48Xf0B "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12, 10~~, 8 bytes ``` ;’VÆPµ€S ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UcPMsMNtAYe2PmpaE/z//39DAwMA "Jelly – Try It Online") 1-2 bytes saved thanks to @nmjmcman101, and 2 bytes saved thanks to @Dennis! Explanation: ``` µ€ # For N in range(input()): ; # Concatenate N with... ’ # N-1 V # And convert that back into an integer ÆP # Is this number prime? S # Sum that list ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 7 bytes ### Code ``` ƒNN<«pO ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//2CQ/P5tDqwv8//83NDAAAA "05AB1E – Try It Online") ### Explanation ``` ƒ # For N in [0 .. input].. NN<« # Push n and n-1 concatenated p # Check for primality O # Sum the entire stack (which is the number of successes) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ ~~11~~ 10 bytes `1`-indexed solution: ``` #ȯṗdS¤+d←ḣ ``` [Try it online!](https://tio.run/##AR4A4f9odXNr//8jyK/huZdkU8KkK2TihpDhuKP///80MjA "Husk – Try It Online") ### Ungolfed/Explanation ``` ḣ -- in the range [1..N] # -- count the number where the following predicate is true ← -- decrement number, S d -- create lists of digits of number and decremented ¤+ -- concatenate, d -- interpret it as number and ȯṗ -- check if it's a prime number ``` Thanks @Zgarb for `-3` bytes! [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~15~~ ~~14~~ ~~12~~ ~~11~~ ~~9~~ 8 bytes 1-indexed. ``` ÇsiZÄÃèj ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=x3NpWsTD6Go=&input=NDIw) ``` Ç :Map each Z in the range [0,input) s : Convert to string i : Prepend ZÄ : Z+1 à :End map è :Count j : Primes ``` [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes *-2 bytes thanks to [@officialaimm](https://codegolf.stackexchange.com/users/59523/officialaimm)*. 1-indexed. ``` lambda n:sum(all(z%v for v in range(2,z))for i in range(4,n+1)for z in[int(`i`+`i-1`)]) ``` **[Test Suite.](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0VyMxJ0ejSrVMIS2/SKFMITNPoSgxLz1Vw0inSlMTJJaJEDPRydM2BAtWAQWjM/NKNBIyE7QTMnUNEzRjNf8XFIGE0jRMNDW5YGxDAwMknokRkPcfAA "Python 2 – Try It Online")** [Answer] # [Pyth](http://pyth.readthedocs.io), 12 bytes ``` smP_s+`d`tdS ``` **[Try it online!](https://pyth.herokuapp.com/?code=smP_s%2B%60d%60tdS&input=420&debug=0) or [Verify all Test Cases.](http://pyth.herokuapp.com/?code=smP_s%2B%60d%60tdS&input=4&test_suite=1&test_suite_input=420%0A100%0A4&debug=0)** --- # How? ``` smP_s+`d`tdSQ -> Full Program. Takes input from Standard Input. Q means evaluated input and is implicit at the end. m SQ -> Map over the Inclusive Range: [1...Q], with the current value d. s+`d`td -> Concatenate: d, the current item and: td, the current item decremented. Convert to int. P_ -> Prime? s -> Sum, counts the occurrences of True. ``` [Answer] # [Röda](https://github.com/fergusq/roda), 73 bytes ``` {seq 3,_|slide 2|parseInteger`$_2$_1`|{|i|[1]if seq 2,i-1|[i%_!=0]}_|sum} ``` [Try it online!](https://tio.run/##TYxBCsIwEEXX5hQjVFCo0ERXQg/gGWKYFprogK01aVeZnD2mOxf/8Rf/P/8Z@hzFzsGthUeOwX7hUiOHNw0WFM@9D/Y@LfZpfVehqlB2HJlYS0MOtrmq6SxZ0wH3bWNS@a5jykmIsacJivvfAQgMel7D64inUp0pmD1NC6BI@SpkI9TGpkT9AA "Röda – Try It Online") 1-indexed. It uses the stream to do input and output. Explanation: ``` { seq 3,_| /* Create a stream of numbers from 3 to input */ slide 2| /* Duplicate every number except the first and the last to create (n-1,n) pairs */ parseInteger`$_2$_1`| /* Concatenate n and n-1 and convert to integer */ {|i| /* For every i in the stream: */ [1]if seq 2,i-1|[i%_!=0] /* Push 1 if i is a prime (not divisible by smaller numbers) */ }_| sum /* Return the sum of numbers in the stream */ } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` lfP_Tms+`d`tdS ``` [Try it online!](https://pyth.herokuapp.com/?code=lfP_Tms%2B%60d%60tdS&input=420&debug=0) **Explanation** ``` Q # Implicit input S # 1-indexed range m # For d in range [1, Q]... s+`d`td # Concatenate d and d - 1 fP_T # Filter on primes l # Return the length of the list ``` [Answer] # [Perl 6](http://perl6.org/), 45 bytes ``` {first :k,$_,grep {is-prime $_~.pred},1..∞} ``` [Try it online!](https://tio.run/##DcpLDsIgFAXQrdw0pCMkFNES@9kKMREM0abk4aQhOHYVLs6NYMfnREfPc102tB5TzT5QeuHy4MzyO7mIHNIhUlgcmH2LSO5WeCfE7/MtdUC6bmiYxTQj@32UBn4ljBqdhFJQGkcNrXAy6CV6A2N2kvNQ/w "Perl 6 – Try It Online") The `grep` produces the sequence of qualifying numbers, then we look for the key (`:k`) (ie, the index) of the `first` number in the list that equals the input parameter `$_`. [Answer] # C, ~~99~~ 94 bytes 1 indexed. It pains me to write primality tests that are so computationally wasteful, but bytes are bytes after all. If we allow some really brittle stuff, compiling on my machine without optimizations with GCC 7.1.1 the following 94 bytes works (thanks [@Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien)) ``` i,c,m,k;f(n){c=i=1;for(;++i<n;c+=m==k){for(k=m=1;m*=10,m<i;);for(m=i*m+i-1;++k<m&&m%k;);}n=c;} ``` otherwise these much more robust 99 bytes does the job ``` i,c,m,k;f(n){c=i=1;for(;++i<n;c+=m==k){for(k=m=1;m*=10,m<i;);for(m=i*m+i-1;++k<m&&m%k;);}return c;} ``` --- Full program, a bit more readable: ``` i,c,m,k; f(n){ c=i=1; for(;++i<n;c+=m==k){ for(k=m=1;m*=10,m<i;); for(m=i*m+i-1;++k<m&&m%k;); } return c; } int main(int argc, char *argv[]) { printf("%d\n", f(atoi(argv[1]))); return 0; } ``` [Answer] ## JavaScript (ES6), ~~ 49 48 ~~ 47 bytes 1-indexed. Limited by the call stack size of your engine. ``` f=n=>n&&f(n-2)+(p=n=>n%--x?p(n):x<2)(x=n+[--n]) ``` [Try it online!](https://tio.run/##HY7LDoIwEEX3fMVshJlACVYMRC2u/ArCokHqI2RKwBj@vg4uTu4jd3Hf9muXfn5NH8X@PoTgDJuG49ghK00pTv@8U2q9Tsh0Wi@acDWctkpxR@Hclhnsiwy0FsQfhFL8sc6gkr4SrettU3RR7vx8s/0TGUwTAfSeFz8O@egfmFhMIAUWEgIDW5AXRBGFHw "JavaScript (Node.js) – Try It Online") [Answer] # [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 33 bytes ``` index({n:prime(n.n-1|int)}from N) ``` [Try it online!](https://tio.run/##DcpBCsIwEAXQvaf4dDUDSUmlq4AewTuUNIEBM5YwoKX27NG3fibr3gvirYuu@UOHxq1JzaSj@ukranyW9qp4cLf0f0g0O0whOMzXwJe6bHRAEfFuYvmppA4DvL9jcCikzDgdLHH/AQ "Tidy – Try It Online") ## Explanation The basic idea is to create a sequence of the valid numbers then return a curried index function. ``` index({n:prime(n.n-1|int)}from N) {n: }from select all numbers `n` from... N the set of natural numbers, such that: n.n-1 `n` concatenated with `n-1` |int ...converted to an integer prime( ) ...is prime index( ) function that returns index of input in that sequence ``` [Answer] # Mathematica, 77 bytes ``` Position[Select[Range@#,PrimeQ@FromDigits[Join@@IntegerDigits/@{#,#-1}]&],#]& ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `L`, 6 bytes ``` Ωv&“⌊Ṅ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyJMIiwiIiwizql2JuKAnOKMiuG5hCIsIiIsIjQyMCIsIjMuNC4xIl0=) 1-indexed ``` Ωv&“⌊Ṅ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‏​⁢⁠⁡‌­ Ω # ‎⁡filter from the range [0... input] v&“⌊ # ‎⁢concatenate n+1 and convert to integer Ṅ # ‎⁣prime? # ‎⁤L flag gets the length of the top of the stack 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 6 bytes ``` '‹Jæ;L ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIn4oC5SsOmO0wiLCIiLCI0MjAiXQ==) ``` L # Number of values ' ; # Between (implicit) 1 and n ‹J # Where n ++ (n-1) æ # Is prime ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 25 bytes ``` [:|p=p-µa*z^_l!a$|+a-1}?p ``` ## Explanation ``` [:| FOR a = 1 to <n> p=p- Decrement p (the counter) by µ -1 if the following is prime, or 0 if not For the concatenating, we multiply 'a' by 10^LENGTH(a), then add a-1$┘p Example 8, len(8) = 1, 8*10^1 = 80, add 8-1=7, isPrime(87) = 0 a*z^_l!a$|+a-1 } Close the FOR loop - this also terminates the prime-test ?p Print p, the 0-based index in the sequence. ``` This uses some pretty involved math-thing with a cast-to-string slapped on for good measure. Making a version hat does solely string-based concatenation is one byte longer: ``` [:|A=!a$+!a-1$┘p=p-µ!A!}?p ``` [Answer] # [PHP](https://php.net/), 203 bytes ``` <?php $n=($a=$argv[1]).($a-1);$p=[2];$r=0;for($b=2;$b<=$n;$b++){$x=0;if(!in_array($b,$p)){foreach($p as $v)if(!($x=$b%$v))break;if($x)$p[]=$b;}}for($b=1;$b<=$a;$b++)if(in_array($b.($b-1),$p))$r++;die $r; ``` [Try it online!](https://tio.run/##TY7BCoMwEETP5issTCEhbTG9xtAPESmJaJWChhTEUvz2dI0Uelp2Znbf@N7HWN587xlGw2ENbHjMlarFhbazEprBm@pa0wym0KybAoczVw1XGow0pBQflmHZ3Gzo@GEY7zYE@6bcCV5sbkZnrW16Dp/bV45ZkJbCnA7hjqQIR5En/dh0LCkBX9Vkk7iy9cdWO9vu7MT8Q1JvR70TmV4gSKlZ2/RTjqBjjKoovg "PHP – Try It Online") Uses a 1-based index for output. TIO link has the readable version of the code. [Answer] # [Ruby](https://www.ruby-lang.org/), 42+9 = 51 bytes Uses the `-rprime -n` flags. 1-indexed. Works by counting all numbers equal to or below the input that fulfill the condition (or more technically, all numbers that fulfill the `n-1` condition). Since the input is guaranteed to be in the sequence, there's no risk of error from a random input like `7` that doesn't "become prime". ``` p (?3..$_).count{|i|eval(i.next+i).prime?} ``` [Try it online!](https://tio.run/##KypNqvz/v0BBw95YT08lXlMvOb80r6S6JrMmtSwxRyNTLy@1okQ7U1OvoCgzN9W@9v9/EyODf/kFJZn5ecX/dYvAwv918wA "Ruby – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->g{(1..g).count{|r|(2...x=eval([r,r-1]*'')).none?{|w|x%w<1}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y69WsNQTy9dUy85vzSvpLqmqEbDSE9Pr8I2tSwxRyO6SKdI1zBWS11dU1MvLz8v1b66prymQrXcxrC2tvZ/gUJatImRQex/AA "Ruby – Try It Online") 1-indexed [Answer] ## [Python 2](https://docs.python.org/2.7/)**, 85 bytes** 1-indexed ``` lambda n:sum(all(z%v for v in range(2,z))for i in range(3,n)for z in[int(`i+1`+`i`)]) ``` [Test](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0VyMxJ0ejSrVMIS2/SKFMITNPoSgxLz1Vw0inSlMTJJaJEDPWyQMLVQGFojPzSjQSMrUNE7QTMhM0YzX/FxSBhNI0TDQ1uWBsQwMDJJ6JEZD3HwA) Improvement to Mr. Xcoder's [answer](https://codegolf.stackexchange.com/questions/137387/can-even-numbers-become-prime/137396#137396) [Answer] # Java 8, 108 bytes ``` n->{for(long r=0,q=1,z,i;;){for(z=new Long(q+""+~-q++),i=2;i<z;z=z%i++<1?0:z);if(z>1)r++;if(q==n)return r;}} ``` 0-indexed **Explanation:** [Try it online.](https://tio.run/##hY/BbsIwEETvfMUKqZItJ1GCONWY/gBw4Vj14BoHGcI6cRyqGrm/nprAtaq0K@3OzOHNSV5lbluNp8N5VI3se9hKg7cZgEGvXS2Vht39BWgsHkGRpANSnqSYNk3vpTcKdoAgYMR8fautI1PaiTLrRJWFzHBOJz0I1F@wSS7p2HzOfvKOMZoZseBmFXgQ4cUwtqreytdAualJWFfUMXY/OyGQOu0Hh@B4jCN/ELTDZ5MIniBXaw5wSS3I3juDx/cPSR8N9t@915fCDr5ok@MbJFgosqRTnT/9qiz/SSwXz0ScxfEX) ``` n->{ // Method with integer parameter and long return-type for(long r=0, // Result-long, starting at 0 q=1, // Loop integer, starting at 1 z,i; // Temp integers ;){ // Loop indefinitely for(z=new Long(q+""+~-q++), // Set z to `q` concatted with `q-1` i=2;i<z;z=z%i++<1?0:z); // Determine if `z` is a prime, if(z>1) // and if it indeed is: r++; // Increase the result-long by 1 if(q==n) // If `q` is now equal to the input integer return r;}} // Return the result ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) 1- Indexed ``` Äm▬á┌╕|°φ♦ ``` [Run and debug it](https://staxlang.xyz/#p=8e6d16a0dab87cf8ed04&i=4%0A100%0A420&m=2) **Explanation** ``` Rxr\{$e|pm|+ #Full program, unpacked, implicit input (Example (4)) R #Create [1 to input] range (ex [1,2,3,4] ) x #Copy value from x register (ex (4) ) r #Create [0 to input-1] range (ex [0,1,2,3) \ #Create array pair using the range arrays (ex [[1,0],[2,1],[3,2],[4,3]]) { m #Map block $e|p #To string, eval string (toNum), isPrime (ex [1,0] => "10" => 10 => 0) |+ #Sum the array to calculate number of truths (ex [0,0,0,1] => 1) ``` ]
[Question] [ You know those stackable shelves that are basically just [wooden boxes](http://bangsboutique.com.au/mock/wp-content/uploads/bangs-shelves-storage-cube-01.jpg) that can be stacked together? We're going to simulate building some bookshelves out of those with some ASCII art. Our books are all *conveniently* uniform in size, and all look like the following: ``` |X| |X| |X| ``` The bookshelves are individual boxes, always three characters high on the inside (enough to fit a book standing upright), composed of `|` characters on the left and right, `-` characters for the top and bottom, and wide enough to fit `X` books (where `X` is an input integer). For example, here's a bookshelf of size `3`: ``` |---------| | | | | | | |---------| ``` because you can fit `3` books into it like so ``` |---------| ||X||X||X|| ||X||X||X|| ||X||X||X|| |---------| ``` The input is going to be two strictly positive integers, `X` and `Y`, where `X` is the width of the shelves we have (measured in books), and `Y` is how many books we have to stack. If we have more books than fit on a single shelf, we need to add more shelves to the top. For example, here is input `4 wide / 6 books`: ``` |------------| ||X||X| | ||X||X| | ||X||X| | |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| ``` If `Y % X > 0`, meaning the number of books is not an integer multiple of the shelf size, the remainder books should go on the top-most left-most position (as in the case with `4 6`, above) and the remaining part of that shelf filled in with spaces. ### Input * Two strictly positive integers [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), each `>0`. * You can take the input in either order (e.g., size of shelves first, then number of books, or vice versa). Please state in your submission the input order. * You can safely assume that neither input will be larger than your language's default `[int]` size (or equivalent). ### Output The resulting ASCII art representation of the books and bookshelves. ### Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * 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. ### Further Examples ``` 6 wide / 2 books |------------------| ||X||X| | ||X||X| | ||X||X| | |------------------| 2 wide / 6 books |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| 4 wide / 9 books |------------| ||X| | ||X| | ||X| | |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| ``` [Answer] ## JavaScript (ES6), ~~100~~ ~~99~~ 98 bytes Takes the width `w` and the number of books `b` in currying syntax `(w)(b)`. ``` w=>g=(b,s=`|${'-'.repeat(w*3)}| `,r=s.replace(/---/g,_=>b&&b--?'|X|':' '))=>(b?g(b)+s:s)+r+r+r+s ``` ### Formatted and commented ``` w => // main function: takes width 'w' as input, returns 'g' g = ( // g = recursive function with: b, // - b = number of books s = `|${'-'.repeat(w * 3)}|\n`, // - s = top/bottom of shell, filled with '-' r = s.replace( // - r = pattern of the current row of books, RegExp('---', 'g'), // using 's' as a template and updating _ => b && b-- ? '|X|' : ' ' // 'b' while building it ) // NB: 'r' must be defined in the scope of 'g', ) => // otherwise it would be overwritten by ( // subsequent calls b ? // if there are remaining books: g(b) + s // do a recursive call and append shell top : // else: s // just append shell top ) + r + r + r + s // append book rows and shell bottom ``` ### Test cases ``` let f = w=>g=(b,s=`|${'-'.repeat(w*3)}| `,r=s.replace(/---/g,_=>b&&b--?'|X|':' '))=>(b?g(b)+s:s)+r+r+r+s console.log(f(6)(2)) console.log(f(2)(6)) console.log(f(4)(9)) ``` [Answer] # Bash (+utilities), ~~130~~, ~~108~~, 106 bytes A single, continuous, shell pipeline to render your bookshelves. Changelog: * Optimized first sed expression a bit, -12 bytes (Thx @Riley !) * Replaced `printf + seq` with a raw `printf`, -10 bytes * Refactored the second sed expression, -2 bytes **Golfed** ``` printf %$2s\\n|fold -$1|sed "s/ /|X|/g;:;/.\{$[$1*3]\}/!s/$/ /;t;h;s/./-/gp;x;p;p;p;x"|sed 's/.*/|&|/'|tac ``` --- ``` $./shelf 6 8 |------------------| ||X||X| | ||X||X| | ||X||X| | |------------------| |------------------| ||X||X||X||X||X||X|| ||X||X||X||X||X||X|| ||X||X||X||X||X||X|| |------------------| ``` [Try It Online !](https://tio.run/nexus/bash#HcvLCsIwEEbhV4lltFBIf6pudF5EMC5KehMkDU4WBcfHdh1LOcuPk@P7GdJg9nQU54IO86szlhqVvjOFwEBvipGvjNp96E5NdXq4L3YCWpETTyyoYTFGXjhuLcW2lytU0IOi1NT6nPM5X35htr71U/8H) **How It Works** `$./shelf 2 3` `printf %$2s\\n` - generate n whitespace characters, one per book (shown as `_`) `___` `fold -$1` - fold them by the shelf length ``` __ _ ``` `sed "s/ /|X|/g;"` - replace `_` with `X`, add book covers ``` |X||X| |X| ``` `:;/.\{$[$1*3]\}/!s/$/ /;t` - right pad with spaces (shown as `_`) ``` |X||X| |X|___ ``` `h;s/./-/gp;x;p;p;p;x` - triplicate each line, and add `---` before and after it. ``` ------ |X||X| |X||X| |X||X| ------ ------ |X| |X| |X| ------ ``` `sed 's/.*/|&|/'|tac` - wrap lines in `| |`, reverse with tac ``` |------| ||X| | ||X| | ||X| | |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| ``` [Answer] # Python 2, ~~133~~ ~~113~~ 105 bytes I'm sure there's a better way... ``` X,Y=input() k='|'+'---'*X+'|' while Y:g=Y%X or X;print k+'\n'+('|'+'|X|'*g+' '*(X-g)+'|'+'\n')*3+k;Y-=g ``` Input is taken `width, books` -20 bytes thanks to @ovs for noticing an unnecessary lambda function! -8 bytes thanks to @ovs for shortening the input. [Answer] ## Batch, 261 bytes ``` @set/an=~-%1%%%2+1,b=%1-n @set s= @set t= @for /l %%i in (1,1,%2)do @call set t=---%%t%%&if %%i gtr %n% (call set s=%%s%% )else call set s=%%s%%X @for %%s in ("|%t%|" "|%s:X=|X|%|" "|%s:X=|X|%|" "|%s:X=|X|%|" "|%t%|")do @echo %%~s @if %b% gtr 0 %0 %b% %2 ``` Uses my trick from my Batch answer to [Let's play tennis](https://codegolf.stackexchange.com/questions/103605) to easily print lots of `|` characters. [Answer] # [Haskell](https://www.haskell.org/), 100 bytes `x#y` returns the string for width `x` and `y` books. ``` s?n=[1..n]>>s x#y|x<y=x#(y-x)++x#x|w<-"---"?x,b<-"|X|"?y++" "?(x-y)=[w,b,b,b,w]>>=('|':).(++"|\n") ``` [Try it online!](https://tio.run/nexus/haskell#NYyxCsIwFAD3fsXjRWhimoIgDpKX/ICbi1AdWnRwMEhbyQvk32MQ5JYbjnuNzwAE7896Xmcga0EKBXbjYH6M91MAu/1rWXygYdf34ebc0rBImW0iFjIZVlqz4BytQWMMeu6mqvmS0SetEQDQSzZJ0RC76UesG5Jtbo@ql7XJ14CqlH1z@AI "Haskell – TIO Nexus") The main function/operator is `#`. When `x<y` it splits the books into `y-x` and `x`, then recurses. When `x>=y`, `w` and `b` are the two line types, minus the outer `|`s and the newline. The helper operator `s?n` concatenates `n` copies of the string `s`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~149~~ 134 bytes ``` param($w,$b)$s="|$('-'*$w*3)|" if($a=$b%$w){,$s+,"|$('|X|'*$a)$(' '*3*($w-$a))|"*3+$s} if($b-=$a){(,$s+,"|$('|X|'*$w)|"*3+$s)*($b/$w)} ``` [Try it online!](https://tio.run/nexus/powershell#XYyxCoQwEET7@wqRkWTXhOMIx1X5D9ukECwEuRQpjN@@LoKN3czw3siW/mm1qA6ZUGLfYI03jMqBWv9aZosUkQdU2h3K6C6iTU2ZRBo7w4H1wGtVg8OIclxe9lG33T61emOkXn5rP0TkK5/fCQ "PowerShell – TIO Nexus") Takes input `$w`idth and `$b`ooks. Sets string `$s` to be one of the horizontal shelves. Then we have two `if` statements. The first checks whether we have "remainder" books. If so, we output the shelf, the (number of books plus number of spaces)`*3`, and another shelf. Next, we see if we still have books remaining after removing the remainders (`$a`). Same sort of setup, except we're using `$w` number of books. Since at this point, `$b` is guaranteed to be a multiple of `$w` (because we removed the remainder, `$a`), we don't need to worry about rounding. *Removed the `[math]::Floor()` call, saving 15 bytes* All of these strings are left on the pipeline, and implicit `Write-Output` happens at program completion. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~62~~ 61 bytes ``` q~1a*W$/W$f{0e]}{{"|X|"S3*?}%s__'-3*W$*_}%1m>W%"| |"*"||"\*o; ``` Takes input as `width books` [Try it online!](https://tio.run/nexus/cjam#@19YZ5ioFa6iH66SVm2QGltbXa1UE1GjFGysZV@rWhwfr65rDJTWiq9VNcy1C1dVquGqUdJSqqlRitHKt/7/30TBEgA "CJam – TIO Nexus") **Explanation** ``` q~ Read and eval input (pushes width W and books B to the stack) 1a* Push an array containing the number 1 B times W$/ Split it into chunks of size W W$f{0e]} Pad each chunk to width W by adding 0's to the right (the last chunk might be shorter than W) { Apply the following to each chunk: { Apply the following to each number in the chunk: "|X|"S3*? Push "|X|" if the number is 1, or " " if it's 0 }% (end of block) s Stringify (joins with no separator) __ Duplicate twice (each shelf is 3 identical lines) '-3*W$*_ Push a string containing '-' repeated 3×W times, then duplicate it }% (end of block) At this point we have an array containing sequences of 3 identical lines each followed by two lines of -'s 1m> Rotate the array 1 to the right; brings the final line of -'s to the start W% Reverse the array, so that the top shelf is the partially empty one "|\n|"* Join the array with the string "|\n|", to build the sides of the shelves "||"\* Join the string "||" with the shelf string (adds the first and last | chars) o Print the result ; Pop and discard W ``` [Answer] # Python 3, 142 bytes Still working on it. `b` is for 'number of books' and `w` is for shelf width. ``` def s(b,w): R=b%w B='|\n' I='|' X='|X|' d=I+3*w*'-'+B f=I+X*w+B p=I+R*X+3*(w-R)*' '+B print(R and d+3*p+d or" ")+b//w*(d+3*f+d)) ``` [Answer] # AHK, 208 bytes ``` AutoTrim,Off w=%1% b=%2% f:=Mod(b,w) Loop,%w% s=%s%--- s=|%s%|`n If (f>0) { Loop,%f% t=%t%|X| Loop,% w-f t=%t% ` ` ` t=|%t%|`n t:=s t t t s } Loop,%w% r=%r%|X| r=|%r%|`n Loop,% (b-f)/w t:=t s r r r s Send,%t% ``` There are a few things frustating me from golfing further: * AutoHotkey doesn't have a built-in repeat function * You can't directly use the passed in arguments (`%1%` & `%2%`) in math functions because those expect variable or number input and it will assume the unescaped `1` to be the number one rather than the variable name * I am not very good at golfing An easier to read version of the above looks like this: ``` AutoTrim,Off w=%1% b=%2% f:=Mod(b,w) Loop,%w% s=%s%--- s=|%s%|`n If (f>0) { Loop,%f% t=%t%|X| Loop,% w-f t=%t% ` ` ` t=|%t%|`n t:=s t t t s } Loop,%w% r=%r%|X| r=|%r%|`n Loop,% (b-f)/w t:=t s r r r s Send,%t% ``` If a `Loop` doesn't use brackets `{}`, then only the next line is part of the loop. If setting a variable's value using `:=` instead of `=`, you can drop the percent sign escape characters. Tilde n is the newline character. [Answer] # Java 7, ~~230~~ ~~224~~ 222 bytes ``` String c(int w,int b){String r="",n="|\n",z="|";int i=0,j,k,t=b%w<1?w:b%w,x=b/w+(t!=w?1:0);for(;i++<w;z+="---");z+=n;for(i=0;i<x;i++){r+=z;for(j=0;j++<3;r+=n){r+="|";for(k=0;k<w;r+=i<1&k++>=t?" ":"|X|");}r+=z;}return r;} ``` **Explanation:** ``` String c(int w, int b){ // Method with two integer parameters and String return-type String r = "", // The return-String n = "|\n", // Part that's used multiple times in the code z = "|"; // Shelf part of the book-boxes int i = 0, j, k, // Indexes used in the for-loops t = b%w < 1 ? w : b%w, // Books on top shelf x = b/w + (t != w ? 1 : 0); // Amount of shelves for(; i++ < w; z += "---"); z += n; // Create the shelf-part ("|---|"; with w times "---") for(i = 0; i < x; i++){ // Loop over the rows r += z; // Append the result with the shelf-part for(j = 0; j++ < 3; ){ // Loop three times (the height of the books & boxes) r += "|"; // Append the result-String with "|" for(k = 0; k < w; // Loop over the columns r += // And append the result-String with: i < 1 // If this is the first row: & k++ >= t ? // And the current column is larger or equal to the amount of books in the top shelf " " // Use an empty space : // Else: "|X|" // Use the book-part ); // End of columns loop r += n; // Append the result-String with a "|" and a new-line } // End of the loop of three r += z; // Append the result-String with the shelf-part } // End of rows loop return r; // Return the result-String } // End of method ``` **Test code:** [Try it here.](https://ideone.com/sFoljG) ``` class M{ static String c(int w,int b){String r="",n="|\n",z="|";int i=0,j,k,t=b%w<1?w:b%w,x=b/w+(t!=w?1:0);for(;i++<w;z+="---");z+=n;for(i=0;i<x;i++){r+=z;for(j=0;j++<3;r+=n){r+="|";for(k=0;k<w;r+=i<1&k++>=t?" ":"|X|");}r+=z;}return r;} public static void main(String[] a){ System.out.println(c(6, 2)); System.out.println(c(2, 6)); System.out.println(c(4, 9)); } } ``` **Output:** ``` |------------------| ||X||X| | ||X||X| | ||X||X| | |------------------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------------| ||X| | ||X| | ||X| | |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| ``` [Answer] # PowerShell, 109 bytes ``` param($w,$b)for(;$b;$b-=$c){if(!($c=$b%$w)){$c=$w}($l="|$('-'*$w*3)|") ,"|$('|X|'*$c)$(' '*($w-$c)*3)|"*3 $l} ``` Less golfed test script: ``` $f = { param($w,$b) for(;$b;$b-=$c){ if(!($c=$b%$w)){$c=$w} ($l="|$('-'*$w*3)|") ,"|$('|X|'*$c)$(' '*($w-$c)*3)|"*3 $l } } @( ,(6, 2, "|------------------|", "||X||X| |", "||X||X| |", "||X||X| |", "|------------------|") ,(2, 6, "|------|", "||X||X||", "||X||X||", "||X||X||", "|------|", "|------|", "||X||X||", "||X||X||", "||X||X||", "|------|", "|------|", "||X||X||", "||X||X||", "||X||X||", "|------|") ,(4, 9, "|------------|", "||X| |", "||X| |", "||X| |", "|------------|", "|------------|", "||X||X||X||X||", "||X||X||X||X||", "||X||X||X||X||", "|------------|", "|------------|", "||X||X||X||X||", "||X||X||X||X||", "||X||X||X||X||", "|------------|") ) | % { $w,$b,$expected = $_ $result = &$f $w $b "$result"-eq"$expected" $result } ``` Output: ``` True |------------------| ||X||X| | ||X||X| | ||X||X| | |------------------| True |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| True |------------| ||X| | ||X| | ||X| | |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| ``` ## PowerShell, 109 bytes, alternative ``` param($w,$b)for(;$b;$b-=$c){($l="|$('---'*$w)|") ,"|$('|X|'*($c=(($b%$w),$w-ne0)[0]))$(' '*($w-$c))|"*3 $l} ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ 118 bytes ``` i,j=input() a=j%i n='|\n' x='|'+'---'*i+n print(x+('|'+'|x|'*a+' '*(i-a)*3+n)*3,'')[a<1]+(x+('|'+'|x|'*i+n)*3)*(j/i)+x ``` [Try it online!](https://tio.run/nexus/python2#VYo7CsMwEAV7ncJNePuRiE1SRidJUqhcFYsxDqjQ3WXjLs0bmHnDYs3m628nDiXXmwXP6B9HaCehSClBTD2sm/lOTenSvXVIUUwQslRYHurnRIDf5bV89f9pV2WhejfWNsYzLvMB "Python 2 – TIO Nexus") Have been meaning to have a go at this one for the last few days. Now that I have finally got time to do it there's already a shorter Python answer. Oh well, just posted as an alternative. Input taken as width,books [Answer] # [SOGL](https://github.com/dzaima/SOGL), 64 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` be%→M"Q└ƨS‘*ač;┼→S%‘A |e3* -* |++M?tMSeM-9*@*a+┼Ot}be÷:?{teSa┼Ot ``` Explanation: First function: ``` →M define function M which pushes b the book amount % mod e the bookshelf width ``` second function: ``` →S create function S (example input: 3) [3] "Q└ƨS‘ push the string "|||XXX|||" (the book) [3, "|||XXX|||"] * multiply by the number on stack (book count) ["|||XXX||||||XXX||||||XXX|||"] a push variable A (later defined "|||") ["|||XXX||||||XXX||||||XXX|||", "|||"] č chop into char array ["|||XXX||||||XXX||||||XXX|||", ["|", "|", "|"]] ; swap top 2 on stack [["|", "|", "|"], "|||XXX||||||XXX||||||XXX|||"] ┼ horizontally append [["||X||X||X|", "||X||X||X|", "||X||X||X|"]] ``` this function expects a number (book count) on stack and outputs the bookshelfs books ``` ["||X||X||X|", "||X||X||X|", "||X||X||X|"] ``` Further down example given is e=3 (bookshelf width) and b=8 (book amount) ``` %‘A var A = "|||" | push "|" ["|"] e3* push E * 3 ["|", 9] -* push that many "-"es ["|", "---------"] |+ append "|" ["|", "---------|"] + prepend the "|" ["|---------|"] ``` this is the bookshelf top/bottom line and always stays on the stack first part (half-empty bookshelf) First main part ``` M? } if the modulo != 0 tM output the bookshelf top/bottom line S execute the S function width the modulo eM- push bookshelf width - modulo (empty space count) 9* multiply by 9 (books are 3x3 so 3x3 spaces) @* get that many spaces a+ append to that "|||" ┼ horizontally append O output t output the bookshelf top/bottom line ``` And the last part ``` be÷ floor divide book amout by width (full shelves) :? if not 0 (a bug makes all loops execute once) { repeat t output the bookshelf top/bottom line eS execute S with shelf width (full shelf) a┼ horizontally append "|||" O output t output the bookshelf top/bottom line ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 124 bytes ``` s->b->{for(int i=0;i++<(b-~s)/s*5;)System.out.printf("|%-"+s*3+"s|%n",i%5<2?"-".repeat(s*3):"|X|".repeat(i<5&b%s>0?b%s:s));} ``` [Try it online!](https://tio.run/##XY9Pb4JAEMXvfooJCc2uwNbaalJBPDRp0kNPXkwMhwXBrIWFMIOJEfrV6arUND3sn/fe5Jc3B3mU3mH31auiKmuCg9GiIZWLrNEJqVKLsT@qmjhXCSS5RIRPqTScRwCDiyTJPMdS7aAwGVtTrfR@G4Gs98ivowAfmt4HYmD@b6XGpkjrEDJY9uiFsRees7JmShOo5cRXjhOw2PtG/ojjmc/XJ6S0EGVDojJ4ypjV2p7l4PjZsbC1teUqexZMV5ZniTqtUknMZHxhtZv27qhg9hDbGE5W5l4g537X@9d@BrmNTGdKkRCWQ2uAM8xdmELn3vXUhflf/eLC66/ubrBhkQG3uEH5nZkJWVX5iV3s7STiQiZJWtFNP0XcH@b@75xrNmTd6HK6/gc "Java (JDK) – Try It Online") ## Credits * -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) [Answer] # PHP>=7.1, 138 Bytes ``` for([,$w,$b]=$argv;$i<ceil($b/$w)*5;)echo str_pad("|".str_repeat(["","|X|"][$t=($i+1)%5>1],$i++<5&&$b%$w?$b%$w:$w),$w*3+1,"- "[$t])."|\n"; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/e08ab44e74ca3839fa77163601db3dd27dcb7955) [Answer] # [Canvas](https://github.com/dzaima/Canvas), 33 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` |X|3*×⁷3×⇵-×|3*×╫│;22╋P %?%⁸}÷[⁷⁸ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JTdDWCU3QyV1RkYxMyV1RkYwQSVENyV1MjA3NyV1RkYxMyVENyV1MjFGNS0lRDclN0MldUZGMTMldUZGMEElRDcldTI1NkIldTI1MDIldUZGMUIldUZGMTIldUZGMTIldTI1NEIldUZGMzAlMEEldUZGMDUldUZGMUYldUZGMDUldTIwNzgldUZGNUQlRjcldUZGM0IldTIwNzcldTIwNzg_,i=NSUwQTM_,v=1) Explanation (some characters have been replaced to look more monospace): ``` |X|3*×⁷3×⇵-×|3*×╫│;22╋P helper function. Prints a shelf with X books |X| push "|X|" 3* repeat it 3 times vertically × repeat that horizontally by the item (X) below on the stack ⁷3× push width * 3 ⇵ ceiling divide that by 2 -× repeat "-" that many times |3* repeat "|" vertically 3 times (aka "|¶|¶|") × prepend that to the dashes (aka ¼ of a bookshelf) ╫│ quad-palindromize with horizontal overlap of the remainder taken before and vertical overlap of 1 ; get the books on top 22╋ and at coordinates (2;2) in the shelf, place them in P print that whole thing %?%⁸}÷[⁷⁸ %? } if width%amount (!= 0) %⁸ execute the helper function with width%amount on the stack ÷[ repeat floor(width/amount) times ⁷ push width ⁸ execute the helper function ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-n`, 45 bytes ``` Wb-:yPPZ['-X3Xa"|X|"X(Yb%a|a).sX3Xa-yRL3]WR'| ``` Takes the width and book count, respectively, as command-line arguments. [Try it online!](https://tio.run/##K8gs@P8/PEnXqjIgICpaXTfCOCJRqSaiRilCIzJJNbEmUVOvGCSmWxnkYxwbHqRe8///f928/6b/DY0A "Pip – Try It Online") ### Explanation We run a loop to print the shelves one by one from top to bottom. At each iteration, we update `b` (the number of books to print) by subtracting `y` (the number of books printed on that iteration). When `b` reaches 0, the loop exits. ``` Wb-:yPPZ['-X3Xa"|X|"X(Yb%a|a).sX3Xa-yRL3]WR'| a is 1st cmdline arg (shelf width); b is 2nd cmdline arg (# books); s is space; y is "" Note that "" becomes zero in numeric contexts Wb-:y While b decremented by y is nonzero: b%a|a b mod a, or a if that quantity is zero Y Yank that value into y ( ) This is the number of books on the current shelf "|X|" Book-spine string X Repeated y times a-y Number of empty slots on the current shelf sX3X Three spaces for each slot . Concatenate to the book-spines string RL3 Make a list of 3 copies of that string '-X3Xa 3*a hyphens [ ] Put that string and the above list in a list WR'| Wrap all strings in the nested list in | PZ Palindromize the outer list (adding a copy of the hyphens to the end of it) P Print, joining all sublists on newlines (-n flag) ``` Because that's a little involved, here's an example of the first iteration when `a = 3, b = 8`: ``` Yb%a|a 2 "|X|"X ^ "|X||X|" ^ .sX3Xa-y "|X||X| " ^ RL3 ["|X||X| ";"|X||X| ";"|X||X| "] ['-X3Xa ^ ] ["---------";["|X||X| ";"|X||X| ";"|X||X| "]] ^ WR'| ["|---------|";["||X||X| |";"||X||X| |";"||X||X| |"]] PZ ^ ["|---------|";["||X||X| |";"||X||X| |";"||X||X| |"];"|---------|"] ``` which then prints as ``` |---------| ||X||X| | ||X||X| | ||X||X| | |---------| ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 56 bytes ``` M++GHGV_fTs*V,]Q1.DEQjCg*5\|smgL\-*L3?d"|X|"" ".[*]1N0 ``` Accepts shelf width, book count as separate arguments in that order. Try it online [here](https://pyth.herokuapp.com/?code=M%2B%2BGHGV_fTs%2AV%2C%5DQ1.DEQjCg%2A5%5C%7CsmgL%5C-%2AL3%3Fd%22%7CX%7C%22%22%20%20%20%22.%5B%2A%5D1N0&input=7%0A12&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=M%2B%2BGHGV_fTs%2AV%2C%5DQ1.DEQjCg%2A5%5C%7CsmgL%5C-%2AL3%3Fd%22%7CX%7C%22%22%20%20%20%22.%5B%2A%5D1N0&test_suite=1&test_suite_input=6%0A2%0A2%0A6%0A4%0A9&debug=0&input_size=2). ``` M++GHGV_fTs*V,]Q1.DEQjCg*5\|smgL\-*L3?d"|X|"" ".[*]1N0Q Implicit: Q=1st arg, E=2nd arg Trailing Q inferred M Define a function, g(G,H): ++GHG Return G + H + G .DEQ Divmod E by Q, yields [E//Q, E%Q] ,]Q1 [[Q], 1] *V Vectorised multiply the two previous results This yields Q repeated E//Q times, then E%Q s Flatten fT Filter out falsey values (i.e. trailing 0 if present) _ Reverse (to put partially filled shelf on top) V For N in the above: ]1 [1] * N Repeat the above N times .[ 0Q Pad the above on the right with 0, to length Q m Map the above, as d, using: ?d"|X|"" " If d != 0, yield "|X|", else " " *L3 Multiply each char by 3 Yields ['|||','XXX','|||'] or [' ',' ',' '] gL\- Use g to wrap each element in '-' s Flatten g*5\| Use g to add '|||||' to start and end of the above C Transpose j Join on newlines, implicit print ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 622 bytes (minimized (remove comments, indentation, 1-char word names) to 303 bytes) My first play with Forth :) ``` : bar 124 EMIT ; : delimline ( width -- ) bar 3 * 0 DO 45 EMIT LOOP bar CR ; : bookline ( width books -- ) bar DUP 0 DO bar 88 EMIT bar LOOP 2DUP = IF DROP DROP ELSE - 0 do 3 SPACES LOOP THEN bar CR ; : shelf ( width books -- ) DUP 0 = IF DROP DROP ELSE OVER delimline 3 0 DO OVER OVER bookline LOOP DROP delimline THEN ; : stack ( width books -- ) CR OVER OVER OVER MOD shelf OVER / DUP 0 = IF DROP DROP ELSE 0 DO DUP DUP shelf LOOP THEN ; 6 2 stack 2 6 stack 3 5 stack 4 4 stack ``` [Try it online!](https://tio.run/##jZBvi4JAEMbf76d4Xl4HcqUW0dGLyD0uqFa07n2lnpJ3Qgl9fNudqRWJIGFnx/nz7G8mq0517vxm5mqaCfa7EwauD7labPApxARJWhZ/ZfGf4g2XIqlzOA56AvrTxXR7eEcfgYI/5MalUuG9AvNIkNC@qo4dHRM4P6oF25DVTPN4zIrGt6quKZli8UV/1BOpkAxF5DKWNuVosaTSjHE4m8u4Vdl8y/UD5DlPy@wZIZO9@rD6kVG7PRv2eDjKkrF7sWRWuNtNwExZ7w7HZ5R6FPt8a1Yq4OHa5MfrQ8HmCN70mMPb6m5UA47gMqJwMbp5HoY3z4fPXtNcAQ "Forth (gforth) – Try It Online") # Output ``` |------------------| ||X||X| | ||X||X| | ||X||X| | |------------------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |------| ||X||X|| ||X||X|| ||X||X|| |------| |---------| ||X||X| | ||X||X| | ||X||X| | |---------| |---------| ||X||X||X|| ||X||X||X|| ||X||X||X|| |---------| |------------| ||X||X||X||X|| ||X||X||X||X|| ||X||X||X||X|| |------------| ``` ]
[Question] [ While ><> is not a popular language, it can be good for golfing and has been used on this website. It was inspired by [Befunge](https://codegolf.stackexchange.com/questions/634/interpret-befunge-93) and has some similarities in its instructions. **Required Commands:** > > `> < ^ v` > > Changes the direction of the instruction pointer (right, left, up, down) > > `/ \ | _ #` > > Mirrors; the pointer will change direction depending on what direction it already has. > > `x` > > Random direction. > > `+ - * , %` > > Addition, subtraction, multiplication, divison and modulo, respectively. Pops A and B off the stack, and pushes B operator A. Division by 0 raises an error. > > `0-9 a-f` > > Pushes the corresponding value onto the stack. a = 10, ..., f = 15 > > `=` > > Pops A and B off the stack, and pushes 1 if B = A, and 0 otherwise. > > `)` > > Greater than. Pops A and B off the stack, and pushes 1 if B < A > > `(` > > Less than. Pops A and B off the stack, and pushes 1 if B > A > > `' "` > > Enables string parsing. String parsing pushes every character found to the stack until it finds a closing quote. > > `!` > > Skips the following instruction. > > `?` > > Skips the following instruction if top of stack is zero, or stack is empty. (note: this does not pop anything off the stack!) > > `:` > > Duplicates the top value on the stack. > > `~` > > Removes the top value from the stack. > > `$` > > Rotates the top 2 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,2,4,3) > > `@` > > Rotates the top 3 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,4,2,3) > > `&` > > Pops the top value off the stack and puts it in the registry. Calling & again will take the value in the registry and put it back on the stack. > > `r` > > Reverses the stack. > > `}` > > Shifts the stack to the right / rotates entire stack clockwise (e.g. 1,2,3,4 becomes 4,1,2,3 > > `{` > > Shifts the stack to the left / rotates entire stack counter-clockwise (e.g. 1,2,3,4 becomes 2,3,4,1 > > `g` > > Pops A and B off the stack, and pushes the value at B,A in the codebox. > > `p` > > Pops A, B, and C off the stack, and changes the value at C,B to A. > > `o` > > Pops and outputs as a character > > `n` > > Pops and outputs the value > > `i` > > Takes one character as user input and pushes its ASCII value to the stack > > `;` > > Ends execution > > > Threading is not required to be implemented, though you can if you want to. *The shortest answer wins, in the event of a tie, the first answer wins.* You may use any language, and eval is allowed. The file will be provided through command line arguments and will have a `.fish` extension. You can use the [official Python interpreter](https://gist.github.com/anonymous/6392418) as a reference if needed. The [Esolangs Wiki article](http://esolangs.org/wiki/Fish) has more information on how the language works, along with a few more examples. ## Test cases: **Hello World!** Code: ``` "Hello World!"r>?o?<; ``` Output: ``` Hello World! ``` **Factorials** Code: ``` 01::nv :@*:n>84*o$1+ ``` Output (Up to 5): ``` 1 2 6 24 120 ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 443 bytes ``` e1r>i::1)$a-*?v{2v xys^p}+1$}:{:{< v0{^?)1p}1}+1:{0-< /rp130p120p210p110p100p00-f{p2 >01g1+11ge+g:0=' '$?$~:21g?v:'"'=$"'"=+?v :'.'=?v::'p'=$'g'=+?/79p02g1+12g8+. >03 v20~v?-g12 <1p12 <0p10p11~< ?! .!p20p21\1p v g 7a^ v<~< < 69. >001-^.98 1<78v//o!^10^~ 3^ 1.!0< ^^ 0-1//~$0$p$ >11g12g+:00g$0(?$~:00g)0$?$~:11pe+0$g:02g:01g+@ @$:0(?!$~$0)@:@(@@*0$?$~01p 0p131<<^$?(@:@@:g$0@:$@:-(1:+1@@:~p00$?)@:g00::+*e-1*2)-10:pbe \ ``` [Try it online!](https://tio.run/##NVDRauswDH33VyjB4KbGieTCbSvcOB8yDBtkvnuaWYfZCM2vd0rZDMLSkXQ4R69v1//3@0wf4xszdfrZ7WNdfFVf39dUbpb0jRdegqq4pNhRuZGAvKALavgodMBCHosn@bdALIjudSlejUiZLFGebWa8GDA66pU95VjZtOaiW9NebKwAbHpzEZRNEdhkI/BwPBf0G4PPJ9sL3QH@XvW41ugy@UcZqPxmW7GpEDFrULEB6Jvy0PdEBarKcHxOUMMaABQE@HfuYUQkl/rzSVE4nuowvDeJMK3qkID6BoNKCdDRMKwaddEAo5gSVZYRs8bd5kqyDh/@iMpsUYtlL0HZTjBplqlGy3438bSbpv1jFqkokXqgEJKOO2lNLIQT64ndjtiSAKscVEfZy4jMdj872vvOEXJ5meHpfm8/5@tnO76HHw "><> – Try It Online") This *should* (as in, I hope it does) work identically to the [reference interpreter](https://gist.github.com/anonymous/6392418) with a couple of exceptions; This doesn't strip trailing newlines, and it doesn't throw an error when `.` receives a negative argument (which wasn't part of the spec anyway). This isn't quite as golfed as I would like, especially regarding the sixth line (with all those chunks of whitespace), but I reached my goal of under 450 bytes, so I thought I'd post it. This takes the program in through STDIN, and should be separated from the input with a NUL byte if there is any. Otherwise you can input stuff through the `-v` or `-s` flags. This works by storing everything within the codebox itself, letting the simulated stack and register be the same as the actual one. We store the program below our interpreter at coordinates `(1,14)`, with the length of each line at that line's zero. The other seven variables we need (number of lines, current x and y positions, current x and y deltas, whether stringmode is toggled, and whether we are skipping the next instruction) are stored in the top left. Because of this, we can simulate most instructions by just placing them in the codebox and running them. Some extra care is needed when simulating movement and skipping ones, but this saves a lot of logic. The only special cases are for the jump instruction (`.`), the stringmode instructions (`"` and `'`), and the get and put instructions (`g`/`p`). These are mostly taken care of on the sixth line, with the get and put logic on thee last line instead, since that is very involved. A more detailed explanation is coming... [Answer] ## APL (Dyalog) (750) Because APL does not really have a command line, load this into a workspace (i.e. with `)ed F`) and then run it from the APL line like so: ``` F'quine.fish' "ar00g!;oooooooooo| F'hello.fish' Hello World! F'stack.fish' 12543 ``` It does not handle any errors. The behaviour of wrong code is not specified. It can't do threads either. Where the Esolang page and the question conflict, it follows the question. Edit: a slightly more readable version with comments can be found here: <https://gist.github.com/anonymous/6428866> ``` F f ⎕IO←0 S←⍬ i←'' s←,0 D←4 2⍴D,⌽D←0 1 0 ¯1 p←0 0 v←0 r←⍬ d←0 1 M←d↓↑M⊂⍨10=M←13~⍨10,83 ¯1⎕MAP f W←{p+←d⋄p|⍨←⍴M⋄p} R←{⌽{v←⊃⌽S⋄S↓⍨←¯1⋄v}¨⍳⍵} U←⎕UCS →v/43 {L←(⍴S)-⊃⌽s ⍵∊G←'><^v':d∘←D[G⍳⍵;] ⍵∊G←'\/':d∘←⌽d×1-2×G⍳⍵ ⍵∊G←'|_#':d×←⊃(1 ¯1)(¯1 1)(¯1 ¯1)[G⍳⍵] ⍵∊'x':d∘←D[?4;] (((~×⊃⌽S)∨L≤0)∧⍵∊'?')∨⍵∊'!':{}W⍬ ⍵∊'.':p∘←R 2 ⍵∊G←⎕D,'abcdef':S,←G⍳⍵ ⍵∊G←'+-=*,)(':S,←⊃(⍎'+-=×,><'[G⍳⍵])/R 2 ⍵∊'%':S,←⊃|⍨/R 2 ⍵∊'"''':v V∘←1,U⍵ ⍵∊':':S,←2/R 1 ⍵∊'~':{}R 1 ⍵∊'$@':S,←¯1⌽R 2+⍵='@' ⍵∊G←'{}':S,←(1-2×G⍳⍵)⌽R L ⍵∊'r':S,←⌽R L ⍵∊'l':S,←L ⍵∊'[':s,←1-⍨L-R 1 ⍵∊']':s↓⍨←¯1 ⍵∊G←'no':⍞←(U⍣(G⍳⍵))R 1 ⍵∊'&':{⍴r:r∘←⍬⊣S,←r⋄r,←R 1}⍬ ⍵∊'i':i↓⍨←1⊣S,←⊃{i∘←10,⍨U⍞}⍣(⊃~×⍴i)⍨i ⍵∊'g':S,←M⌷⍨⌽R 2 ⍵∊'p':((⌽1↓G)⌷M)∘←⊃G←R 3 ⍵∊';':S∘←0 s≡⍬:s∘←,0⊣S∘←⍬ }U p⌷M →45 {}{+S,←p⌷M}⍣{V=M⌷⍨W⍬}⍬ v←0 {}W⍬ →14/⍨S≢0 ``` [Answer] # Haskell 1428 Almost all lowercase characters are used as function names. *P.S.* Are there any game about these kind (2d pointer) esolangs ? They must be very amusing ! ``` import qualified Data.Map as M import System.Environment import Data.Char import System.Random type I=Integer data S=S{p::(I,I),d,e::Int,s::[I],r::S->S,m::M.Map(I,I)Char} a=zip">v<^\\/_|x+-*,%()=:~!?$@&r{}gponi"[q 0,q 1,q 2,q 3, i[1,0,3,2],i[3,2,1,0],i[0,3,2,1],i[2,1,0,3],\s->do x<-randomRIO(0,3);t$s{d=x}, h(+),h(-),h(*),h div,h mod,h$j(<),h$j(>),h$j(==), o(\(x:y)->x:x:y),o tail,t.g.g,\q->t$if s q==[]||head(s q)==0 then g q else q, o(\(x:y:z)->(y:x:z)),o(\(x:y:z:w)->(y:z:x:w)),\q->t$(r q)q, o reverse,o(\s->last s:init s),o(\s->tail s++[head s]), \q->let(i:j:x)=s q in t$q{s=l(b(i,j)q):x}, \q->let(i:j:k:x)=s q in t$q{s=x,m=M.insert(i,j)(n k)(m q)}, y$putChar.n,y$putStr.show,\q->do c<-getChar;t(q{s=l c:(s q)}) ]++[(x,t.c i)|(x,i)<-zip['0'..'9'][0..9]++zip['a'..'f'][10..15]] b p q=maybe ' 'id$M.lookup p(m q) c x q=q{s=x:s q} f(i,j)0=(i,j+1) f(i,j)1=(i+1,j) f(i,j)2=(i,j-1) f(i,j)3=(i-1,j) g q=q{p=f(p q)(d q)} h f=o(\(b:a:k)->f b a:k) i a s=t$s{d=a!!(d s)} j f a b|f a b=1|1<2=0 k=zip[0,1..] l=toInteger.ord n=chr.fromInteger o f q=t$q{s=f(s q)} q x=i[x,x..] t=return u s=M.fromList.foldr1(++)$[map(\(j,x)->((i,j),x))l|(i,l)<-k$map k$lines s] v q=let(x:y)=s q in q{r=w x,s=y} w x q=q{s=x:(s q),r=v} y o q=let(i:x)=s q in o i>>t(q{s=x}) z q=[[[y=<<(maybe t id$lookup x a)q,t()]!!j(==)x ';',y$c(l x)q]!!k,w]!!j elem x"'\"" where k=e q;x=b(p q)q;w=y$q{e=1-k};y=z.g main=z.S(0,0)0 0[]v.u=<<readFile.head=<<getArgs ``` ## An Example Fish Program ``` mm v > v ~>1f+00p v ;v?)+afg00 < #<-- Condition of loop 1 p>>~ 410p v 0vv?)+cfg01 < < #<-- Condition of loop 2 00>~10g00gg'.'=?v~ v #<-- Go this route when +0 vp01+1g01~< # we find a digit. 1g > ^ ^< v < > >~ ; 0 >10g0cg"0"$-+00gg:" "=?^~:"."=?^v ^ pc0+1gc0 n-$"0" ~< ....................... ....................... ......112233........... This program prints ....................... the number on this field. ....................... <------------ ....................... ....................... ....................... ....................... ``` [Answer] # ><>, 1242 bytes ``` 0[0v v&0< >ff+$>i:a=?v:0(?vv ^< v :$+1~< ~ & &^p$}+1:$}:@ < ~ : v]{{00+ff<$ &~ & >~ $^: ^^?(< >}}v&>~&$^& vg$}:$}:}<^^?(&:< >:"'"=?!v>{${${${${$} v v < .-2*4c6}}}}}< >:'"'= ?^0c. >:'.'=?!v$l8(?v}$:0(?vff v v='g': <" "}} ~~{{{~ $++< >?vv ,00< < < > l8(?^}$:0(?!v4fv v: < {$++ff<-*< >'p'=?vv ,00< >ff+-v v{~{<> l9(?^}$:0(?^ff++>$:v v <v(}:$}:]&{{{{{{&[l < v~{{^? < >}}}}}}$:@{${${${${v v}}}}+1<~{{v?)}:$}:$< ^{~{<,00< >50p60p70v >:'&'=?!v~&l4=?^" " 755*. v='[': < >?!v~l5=?v5+{${${$vpv08]p08p< v <" "}} }}}[${${<0>g70g60gv ,00<>93*3a*. 4v}g04g05< >:']'= ?!^~{{{{{!.^>}}}}" "v v{{{p}:+1*66}:4 } $!}}@}:{{{< >:1=?v:0=?v:2=?vv ^[-5<>$}$}v v-1$~< >~1-l 5-[$.l} + $ .$[-5l+1~<>~$1+$^^:{{<f l >>]{${$-{~3}}}v 5 21 -v1<>^ [v2^ v2>]{+{{~0}}}v $ v<>1^ . 12>{+{~1}}}v ^$<>2}}} > >{{{{:}$v{- >>]{^~vff-${v?)}:$@:}$}<{f >]{$-{{^>++}0 >~{:}ff+(?!v^- v~{v!?(}:$}$}$}:{{{{{< <}< >0}>{:0(?v{88. v{~< v:{{{<>{{:}$}$88. >}:0=?v:1=?v3=?vv v$+1$~<{$-2 $} < v +1< -2< > {{:}$}$}$:})v>}$}$}$~v v~{v!?(}<vf~{v?<^:{{{{< } >0}>{:0v:>f+}>{:}ff+(?^v< v{~v!?(<^$}$}$}:{{{{{< < { > v >{:}$}$}>:}$v v{${${:<g$}:< >${${${:}=?!v{~}}}}}~" "7a. .-2*c46}}}}}< ``` # Notes Reads a ><> program from stdin. This implements a more recent spec of ><> than the one in the OP for convenience (which includes all of the "Required Commands"). Since threading was dropped in favour of multiple stacks, this implements the multi stack version. The implementation used is the one at [fishlanguage.com](https://fishlanguage.com/), which also makes multi-line input convenient. It's probably not bug free. Known bugs: * Jumping with `!` while wrapping vertically is off by one. # Method Due to the ability of fish for self-modifying code, it's tempting to write a "self-erasing" interpreter, which just prints the input into its own source doe and then removes itself, before executing the code as-is. Sadly, this isn't quite possible. You have to pick one of: * Solving the halting problem * Adding a size limitation to programs * Have the commands `.`, `g` and `p` fail in some cases. So I did not do that # Instead This interpreter prints the program at an offset of 30 characters. And never executes the program directly. It "pokes" into the code with the `g` command, carefully executing it in a sandboxed environment. That means: * The instruction pointer is "virtual", represented by two coordinates and a direction on the stack, in addition to the current width and height of the program. Wrapping and movement is done through arithmetic. * Most "simple" instructions are performed inside a "direction detection box": ``` 21 1<>^ 2^ v2 v<>1 12 ``` Which allows arrows, mirrors and simple math and stack operations. * The register `&` needs extra code, as it must be executed on the current stack. * The `[` and `]` stack commands need their own implementation. * String parsing must be done through arithmetic. * The `.`, `p` and `g` commands must have a virtual implementation, and their coordinates corrected. [Answer] # Python, 978 ~~980~~ ~~981~~ ``` import sys,random f=open(sys.argv[1]).read().split('\n') s=t=[] d=p=x=y=k=0 r='n' h='0123456789abcdef' while h: c=f[y][x] if k:k=0 elif p: if c==p:p=0 else:s+=[ord(c)] else: for l in (h+'''0123456789abcdef`s+=[h.find(c)] ><^v`d='><^v'.find(c) x`d=random.randint(0,3) /`d=(d+2)%4 \`d=3-d |#`if d<2:d=1-d _#`if d>1:d=5-d +-*,%=)($gp`a,b=s[-2:];s=s[:-2] +-*%`s+=[eval('a%sb'%c)] ,`s+=[a/b] =`s+=[a==b] (`s+=[a<b] )`s+=[a>b] '"`p=c !?`if(not s)or'!'==c or s[-1]==0:k=1 :`s+=s[-1:] ~`s.pop() $`s+=[b,a] @`s=s[:-3]+s[-1:]+s[-3:-1] &`s,r=(s[:-1],s[-1])if r=='n'else (s+[r],'n') .`s,t=t,s r`s.reverse() }`s=[:-1]+s[-1:] {`s=s[1:]+s[:1] m`s,t=[],s+t g`s+=[f[b][a]] p`f[s.pop()][b]=a on`z=chr if c=='o'else str;sys.stdout.write(z(s.pop()));sys.stdout.flush() i`s+=[int(sys.stdin.read(1))] ;`h=0''').split('\n'): l=l.split('`') if c in l[0]: try:exec(l[1]) except:0 if d<2:x=(x-d*2+1)%len(f[y]) else: while 1: try:y=(y+d*2-5)%len(f);f[y][x];break except:0 ``` Doesn't support threading. Versions:  1. 981  2. 980: Fixed `p` instruction; small improvement.  3. 978: Fixed `?` instruction. [Answer] ## Delphi, 1144 All but the theading instructions are implemented. ``` var f:TextFile;c,k,s:String;i,m,b,v,w,x,y,A,l:Int16;procedure U(v:Int16);begin s:=s+Chr(v)end;function O:Int32;begin if l=0then Exit(0);O:=Ord(s[l]);Delete(s,l,1);Dec(l)end;procedure T(a,b:Int16);begin x:=a;y:=b;end;procedure E;begin v:=(v+x+80)mod 80;w:=(w+y+25)mod 25;i:=Ord(c[1+v+80*w])end;begin Assign(f,ParamStr(1));Reset(f);for A:=1to 25do begin ReadLn(f,k);c:=c+k+StringOfChar(' ',80-Length(k))end;x:=1;v:=-1;repeat E;k:=s;l:=Length(k);A:=i;case i-32of 2,7:repeat E;U(i);Inc(l)until i=A;4,5,8,9,12,13,26,32,71,80,93:A:=O;6:b:=1-b;88:i:=Ord('<>^v'[1+Random(4)]);91:l:=1;73:Read(PChar(@A)^)end;case i-32of 4:l:=l+1;80:l:=O;91:A:=O;93:l:=2;26:U(A)end;case i-32of 0:;1:E;2,7,94:O;3:T(-x,-y);4,32,93:Insert(Chr(A),s,l-1);5:U(O mod A);6:if b=0then U(m)else m:=O;8:U(Ord(O>A));9:U(Ord(O<A));10:U(O*O);11:U(O+O);12:U(O div A);13:U(O-A);15:T(-y,-x);16..25:U(i-48);26,73,91:U(A);28:T(-1,0);29:U(Ord(O=O));30:T(1,0);31:if(l=0)or(k[l]=#0)then E;60:T(y,x);62:T(0,-1);63:T(x,-y);65..70:U(i-87);71:U(Ord(c[1+O+80*A]));78:Write(O);79:Write(Chr(O));80:c[1+O+80*l]:=Chr(A);82:for A:=1to(l)do s[A]:=k[l-A+1];86:T(0,1);92:T(-x,y)else Exit;end;until 0=1;end. ``` The indented and commented code reads : ``` {debug}uses Windows;{} var // f is the source file f:TextFile; // c is the entire codebox (a 2-dimensional program) c, // k is a temporary stack copy, needed for reversal k, // s is the stack (kept as a string) s:String; // i is the current instruction read from the program i, // m is the registry memory value (read/written by the '&' instruction) m, // b indicates if the registry should be written (b=0) or read (b>0) by the '&' instruction b, // v,w are x,y positions into the program v,w, // x,y are steps in the respective direction (values -1,0 or 1) : x,y, // A is a temporary variable (only uppercase var, to coincide with comments) A, // l is the length of the stack (may be abused as a temporary) l :Int16; procedure U(v:Int16); // PUSH begin // Push value onto the stack: s:=s+Chr(v) end; function O:Int32; // POP begin // Pop value from the stack : if l=0then Exit(0); O:=Ord(s[l]); Delete(s,l,1); Dec(l) end; procedure T(a,b:Int16); // TURN begin // Turn in a new direction : x:=a; y:=b; end; procedure E; // STEP begin {debug}Sleep(10);{} // Note : x-step needs to stay on same line, y-step needs to stay on same column v:=(v+x+80)mod 80; w:=(w+y+25)mod 25; i:=Ord(c[1+v+80*w]) end; begin // Open file given at the command-line, and read & expand it's lines into our program buffer : Assign(f,ParamStr(1)); Reset(f); for A:=1to 25do begin ReadLn(f,k); c:=c+k+StringOfChar(' ',80-Length(k)) {debug};SetLength(c,A*80) end; x:=1; v:=-1; repeat // Take a step (which gives a new 'i'nstruction) and make a copy of the stack : E; k:=s; // Note : 'l' is used to get an element from the stack. So this gives pops from the top. l:=Length(k); // Shorten '''' and '"' (case 2 and 7) string-collecting, by remembering the quote character in A : A:=i; // Prevent begin+end pairs by handling instructions in 3 consecutive case blocks; This is applied to // all situations where this saves 1 or more characters, justifying the cost for another case-block. // Shorten a few cases by preparing variables so they can be shared with eachother and the 3rd case-block below : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! // Shorten string-collecting, by pushing the entire string here (the opening quote was remembered in A) : 2,7:repeat E;U(i);Inc(l)until i=A; // Note : We stop at the closing character, so the next block will still handle 'i'! // These instructions all need to Pop A, so write it just once here : 4,5,8,9,12,13,26,32,71,80,93:A:=O; // Prevent begin+end for register access, by switching the read/write flag here : 6:b:=1-b; // Shorten 'x' (case 120>88): Choose a random direction instruction and let the 3rd case-block handle it : 88:i:=Ord('<>^v'[1+Random(4)]); // Shorten '{' (case 123-32=91): Share 3rd case-block with ':' (>26) and 'i' (>73) by setting l to 1 here : 91:l:=1; // Prevent begin+end for input retrieval, by reading the input into A here : 73:Read(PChar(@A)^) // Note : This case is last, because it ends on ')', which avoids a closing ';' end; // Shorten a few more cases by preparing variables so they can be shared with eachother and the 3rd case-block below : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! // Shorten '$' (case 38-32=4): Set 'l' to l+1 so that the 3rd case-block can insert just like '@' and '}' : 4:l:=l+1; // Shorten 'p' (case 112-32=80): Set 'l' to O() so that the 3rd case-block doesn't need a begin+end pair : 80:l:=O; // Shorten '{' (case 123-32=91): Share 3rd case-block with ':' (>26) and 'i' (>73) by popping A from position 1, as tricked above!: 91:A:=O; // Note : This is NOT the same as doing this in the 1st case-block, as 'l' needs to be 1 first! // Shorten '}' (case 125-32=93): Prepare 'l' so that the implementation can be shared with '@' (>32): 93:l:=2; // Shorten ':' (case 58-32=26): Share implementation with 'i' (>73) by pushing first copy of A (read above) here 26:U(A) // Note : This case is last, because it ends on ')', which avoids a closing ';' end; // This 3rd case-block contains the final code for all statements (is there's no case here, it's an error) : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! //' ': Ignore spaces 0:; //'!': Skips the following instruction. 1:E; //'"','''': Enables string parsing. String parsing pushes every character found to the stack until it finds a closing quote. //'~': Removes the top value from the stack. 2,7,94:O; //'#': Mirror both axes 3:T(-x,-y); //'$': Rotates the top 2 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,2,4,3) //'@': Rotates the top 3 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,4,2,3) //'}': Shifts the stack to the right / rotates entire stack clockwise (e.g. 1,2,3,4 becomes 4,1,2,3) 4, 32, 93:Insert(Chr(A),s,l-1); // Note : A was Popped in 1st case block //'%': Pops A and B off the stack, and pushes B mod A. 5:U(O mod A); //'&': Pops the top value off the stack and puts it in the registry. Calling & again will take the value in the registry and put it back on the stack. 6:if b=0then U(m)else m:=O; //'(': Less than. Pops A and B off the stack, and pushes 1 if B > A 8:U(Ord(O>A)); //')': Greater than. Pops A and B off the stack, and pushes 1 if B < A 9:U(Ord(O<A)); //'*': Pops A and B off the stack, and pushes B * A. 10:U(O*O); // Note : A and B are inverted, but order is irrelevant here //'+': Pops A and B off the stack, and pushes B + A. 11:U(O+O); // Note : A and B are inverted, but order is irrelevant here //',': Pops A and B off the stack, and pushes B / A. Division by 0 raises an error. 12:U(O div A); //'-': Pops A and B off the stack, and pushes B - A. 13:U(O-A); //'/': Mirror 15:T(-y,-x); //'0'..'9': Push value 0-9 onto the stack. 16..25:U(i-48); //':': Duplicates the top value on the stack. //'i': Takes one character as user input and pushes it's ASCII value to the stack //'{': Shifts the stack to the left / rotates entire stack counter-clockwise (e.g. 1,2,3,4 becomes 2,3,4,1) 26, // Note for ':' : First A was already pushed once above 73, // Note for 'i' : Read() into A was done in 1st case block 91:U(A); // Note for '{' : l=1 was done in 1st case block, A:=O was done in 2nd block //'<': Turn west 28:T(-1,0); //'=': Pops A and B off the stack, and pushes 1 if B = A, and 0 otherwise. 29:U(Ord(O=O)); // Note : A and B are inverted, but order is irrelevant here //'>': Turn east 30:T(1,0); //'?': Skips the following instruction if top of stack is zero, or stack is empty. (note: this does not pop anything off the stack!) 31:if(l=0)or(k[l]=#0)then E; //'\': Mirror 60:T(y,x); //'^': Turn north 62:T(0,-1); //'_': Mirror y 63:T(x,-y); //'a'..'f': Push value 10-15 onto the stack. 65..70:U(i-87); //'g': Pops A and B off the stack, and pushes the value at B,A in the codebox. 71:U(Ord(c[1+O+80*A])); // Note : A was Popped in 1st case block //'n': Pops and outputs the value 78:Write(O); //'o': Pops and outputs as a character 79:Write(Chr(O)); //'p': Pops A, B, and C off the stack, and changes the value at C,B to A. 80:c[1+O+80*l]:=Chr(A); // Note : A was Popped in 1st case block, l was set to 1 in 2nd case block //'r': Reverses the stack. 82:for A:=1to(l)do s[A]:=k[l-A+1]; // Note: This reads from the stack-copy //'v': Turn south 86:T(0,1); //'|': Mirror x 92:T(-x,y) // Note : This case is last, because it ends on ')', which avoids a closing ';' else // ';' (27) and unrecognized instructions end execution. Exit; end; until 0=1; end. ``` Edit history : (1306+18=1324) : Fixed bugs in a few operation orders (Delphi evaluates arguments in reverse). Also fixed stack pop (couldn't pop more than once per instruction). (1324-33=1291) : Removed safeguard when writing contents from an empty stack (1291-56=1235) : Added Turn function, renamed variables, decreased instruction digits (1235-7=1228) : Reordered variables, fixed bug in '@' (1228-37=1191) : Shared more implementation-code by spreading it out over 3 consecutive case-blocks (1191-12=1179) : Shared the stack-cycling implementation between all 3 instructions now. (1179-20=1159) : Split up string-parsing over 3 case-blocks, removed j variable, shared another implementation (1159-15=1144) : Simplified 'x' by changing it into one of the 4 direction-instructions [Answer] ## Lua 1640 (1558 non threading) chars Threading version, golfed (1640 characters): ``` L=loadstring L(([[z=table p=z.insert P=z.remove W=io.write t="><^v/\\|_#x+-*,%=)(!?:~$@&r}{gponi;[].m"C=t.char B=t.byte F=t.match M=setmetatable Q=getfenv R=setfenv I=io.read w="@h1,0@h-1,0@h0,-1@h0,1@h-Y,-X@hY,X|X=-X|Y=-Y@h-X,-Y|z=math.random(1,4)R(f[('><^v'):sub(z,z)],Q())()|@c@a+@a)|@c-@a+@a)|@c@a*@a)|z=@a@pz~=0 @b@c@a/z)@rerror'Div by 0'@d|y=@az=@a@cz%y)|@c@a==@a@n1@g0)|@c@a>@a@n1@g0)|@c@a<@a@n1@g0)|@i|@p#s==0@gs[#s]==0 @b@i@d|@cs[#s])|@a|z=#s s[z@k-1]=s[z-1@k]|z=#s s[z@k-1@k-2]=s[z-1@k-2@k]|@pr @b@cr)r=N @rr=@a@d|z={}@o=1,#s@qz[#s-k+1]=s[k]@ds=z|@c1,@a)|@cP(s,1))|z=@a@cc[@a][z])|z,w=@a,@ac[@a][w]=z|W(C(@a))|W(@a)|z=I(1)while F(z,'%s')@qz=I(1)@d@cB(z))|os.exit()|T.N=1|P(T,I)@o=I,#T@qT[k].I=k@d|s=s==S@nl@gS|z=s==S@nl@gS @o=#s,1,-1@qp(z,P(s,1))@d|"z=1 f={}@o in t:gmatch"."@q_,z,s=w:find("|(.-)|",z)f[k]=L(s)@dT={m@j)@i @py>#c @by=0 @fy<0 @by=#c@d@px>#c[y]@nX==1 @bx=0 @fx<0 @bx=#c[y]@d@d,n@jx,y,X,Y)z=M({I=#T+1,l={},X=X@g1,Y=Y@g0,x=x@g0,y=y@g0},{__index=_G})z.s=z.l T[z.I]=z@d}c={}S={}T.n(-1)fh=arg[1]@nio.open(arg[1])@gio.stdin y=0 for l in fh:lines()@qc[y]=M({},{__index@j)return 32@d})@o=1,#l@qz=l:sub(k,k) @pnot i @b@pF(z@l@bi=z@d@pF(z,"[^\n\r]")@b@m@d@r@pz==i @bi=N@d@m@d@dy=y+1@dwhile #T>0@qfor I=1,#T@qt=T[I]R(1,t)R(T.m,t)()n,o=X,Y q=C(c[y][x])@pi @b@pF(q@l@bi=N @r@cc[y][x])@d@fF(q@l @bi=q @fF(q,"%x")@b@ctonumber(q,16))@fF(q,"[^ ]")@bsetfenv(f[q],t)()@d@[[email protected]](/cdn-cgi/l/email-protection)@n(n~=X@go~=Y)@bT.n(x,y,X,Y)T.N=N X,Y=n,o@d@d]]):gsub("@(.)",{a="P(s)",b="then ",c="p(s,",d=" end ",f="elseif ",g=" or ",h="|X,Y=",i="x,y=x+X,y+Y",j="=function(",k="],s[z",l=[[,"['\"]")]],m="c[y][k-1]=B(z)",n=" and ",o="for k",p="if ",q=" do ",r="else "}))() ``` The threading version does some nasty hacks with setfenv and getfenv to eliminate the need for indexing for the different threads. Threading version readable: ``` -- http://codegolf.stackexchange.com/questions/1595/interpret-fish z=table p=z.insert -- push P=z.remove -- pop W=io.write t="><^v/\\|_#x+-*,%=)(!?:~$@&r}{gponi;[].m" -- all tokens C=t.char B=t.byte F=t.match M=setmetatable Q=getfenv R=setfenv I=io.read --w=("@d1,0@d-1,0@d0,-1@d0,1@d-Y,-X@dY,X|X=-X|Y=-Y@d-X,-Y|z=math.random(1,4)R(f[('><^v'):sub(z,z)],Q())()|@b@a+@a)|@b-@a+@a)|@b@a*@a)|z=@aif z~=0@i@b@a/z)else error'Div by 0'end|y=@az=@a@bz%y)|@b@a==@a @c@b@a>@a@c@b@a<@a@c@h|if #s==0 or s[#s]==0@i@h end|@bs[#s])|@a@gs[z-1]=@e]@g@e-2]=@e-2],s[z]|if r@i@br)r=N else r=@aend|z={}for k=1,#s do z[#s-k+1]=s[k]end s=z|@b1,@a)|@bP(s,1))|z=@a@bc[@a][z])|z,w=@a,@ac[@a][w]=z|W(C(@a))|W(@a)|z=I(1)while F(z,'%s')do z=I(1)end @bB(z))|os.exit()|T.N=1|P(T,I)for k=I,#T do T[k].I=k end|s@f|z@f for k=#s,1,-1 do p(z,P(s,1))end|"):gsub("@(.)",{a="P(s)",b="p(s,",c="and 1 or 0)|",d="|X,Y=",e="s[z-1],s[z",f="=s==S and l or S",g="|z=#s s[z],",h="x,y=x+X,y+Y",i=" then "}) w="|X,Y=1,0|X,Y=-1,0|X,Y=0,-1|X,Y=0,1|X,Y=-Y,-X|X,Y=Y,X|X=-X|Y=-Y|X,Y=-X,-Y|z=math.random(1,4)R(f[('><^v'):sub(z,z)],Q())()|p(s,P(s)+P(s))|p(s,-P(s)+P(s))|p(s,P(s)*P(s))|z=P(s)if z~=0 then p(s,P(s)/z)else error'Div by 0'end|y=P(s)z=P(s)p(s,z%y)|p(s,P(s)==P(s) and 1 or 0)|p(s,P(s)>P(s)and 1 or 0)|p(s,P(s)<P(s)and 1 or 0)|x,y=x+X,y+Y|if #s==0 or s[#s]==0 then x,y=x+X,y+Y end|p(s,s[#s])|P(s)|z=#s s[z],s[z-1]=s[z-1],s[z]|z=#s s[z],s[z-1],s[z-2]=s[z-1],s[z-2],s[z]|if r then p(s,r)r=N else r=P(s)end|z={}for k=1,#s do z[#s-k+1]=s[k]end s=z|p(s,1,P(s))|p(s,P(s,1))|z=P(s)p(s,c[P(s)][z])|z,w=P(s),P(s)c[P(s)][w]=z|W(C(P(s)))|W(P(s))|z=I(1)while F(z,'%s')do z=I(1)end p(s,B(z))|os.exit()|T.N=1|P(T,I)for k=I,#T do T[k].I=k end|s=s==S and l or S|z=s==S and l or S for k=#s,1,-1 do p(z,P(s,1))end|" z=1 f={} for k in t:gmatch"." do -- will contain the tokens _,z,s=w:find("|(.-)|",z) f[k]=loadstring(s) end T={ -- table of threads --N = new thread to be created. m=function() x,y=x+X,y+Y if y > #c then y=0 elseif y<0 then y=#c end if x>#c[y] and X==1 then x=0 elseif x<0 then x=#c[y] end end, n=function(x,y,X,Y) z=M({ I=#T+1, -- keep number id l={}, -- local stack X=X or 1, -- 1 for +x, -1 for -x, 0 for y/-y Y=Y or 0, -- 1 for +y, -1 for -y, 0 for x/-x x=x or 0, -- X of IP y=y or 0, -- Y of IP -- i, -- will contain type of quote when reading in a string --TODO keep local -- r, -- registry --TODO make global },{__index=_G}) -- Enable lookup of functions in global table. z.s=z.l -- current stack is local stack T[z.I]=z -- add at next index end } c={} -- codebox IP wraps around -- TODO make codebox global in code S={} -- global stack -- codebox layout -- -----> +x -- @ |line of text -- wrap around to second line -- |second line of text. -- negative indices can be used for variables -- | -- V +Y -- y first coord, x second -- wrap around rows if nil row -- wrap around cols if nil char. T.n(-1) -- compile to codebox fh= arg[1] and io.open(arg[1]) or io.stdin -- use file or stdin y=0 for l in fh:lines() do c[y]=M({},{__index=function()return 32 end})--default to space for k=1,#l do z=l:sub(k,k) if not i then -- normal mode if F(z,"['\"]") then i=z end if F(z,"[^\n\r]")then --filter out only newlines c[y][k-1]=B(z) end -- any spacing allowed. else if z==i then i=N end-- verbatim string mode c[y][k-1]=B(z) end end y=y+1 end io.stdout:setvbuf("no") -- direct output while #T>0 do for I=1,#T do t=T[I] R(1,t) R(T.m,t)() n,o=X,Y -- keep old directions for new thread detection q=C(c[y][x]) if i then -- stringparsing mode if F(q,"['\"]") then -- end-quote i=N else p(s,c[y][x]) -- push contents of box, then advance end elseif F(q,"['\"]") then -- start-quote i=q elseif F(q,"%x") then -- parsing a number p(s,tonumber(q,16)) elseif F(q,"[^ ]") then assert(setfenv(f[q],t)) f[q]() -- call, feed with state/thread end end if T.N and (n~=X or o~=Y) then -- create new thread T.n(x,y,X,Y) T.N=N X,Y=n,o -- restore directions of parent end end ``` Nonthreading version, golfed (1558 chars, but can be shrunk a bit more if the non-threading version is going to be the criterion): ``` T=table p=T.insert P=T.remove I=io.read W=io.write A=assert t="><^v/\\|_#x+-*,%=)(!?:~$@&r}{gponi;"M=t.match B=t.byte C=t.char f={"X,Y=1,0","X,Y=-1,0","X,Y=0,-1","X,Y=0,1","X,Y=-Y,-X","X,Y=Y,X","X=-X","Y=-Y","X,Y=-X,-Y","z=math.random(1,4)f[('><^v'):sub(z,z)]()","p(s,P(s)+P(s))","p(s,-P(s)+P(s))","p(s,P(s)*P(s))","p(s,(1/P(s) or error'Div by 0')*P(s))","y=P(s)z=P(s)p(s,z%y)","p(s,P(s)==P(s) and 1 or 0)","p(s,P(s)>P(s) and 1 or 0)","p(s,P(s)<P(s) and 1 or 0)","x,y=x+X,y+Y","if #s==0 or s[#s]==0 then f['!']()end","p(s,s[#s])","P(s)","z=#s s[z],s[z-1]=s[z-1],s[z]","z=#s s[z],s[z-1],s[z-2]=s[z-1],s[z-2],s[z]","if r then p(s,r)r=N else r=P(s)end","z={}for k=1,#s do z[#s-k+1]=s[k]end s=z","p(s,1,P(s))","p(s,P(s,1))","z=P(s) p(c[P(s)][z])","z,w=P(s),P(s) c[P(s)][w]=z","W(C(P(s)))","W(P(s))","z=I(1) while M(z,'%s')do z=I(1)end p(s,B(z))","os.exit()"}z=1 for k in t:gmatch"."do f[k]=A(loadstring(f[z]))z=z+1 end c={}s={}X=1 Y=0 x=0 y=0 m=function(s)x,y=x+X,y+Y if y>#c then y=0 elseif y<0 then y=#c end if x>#c[y]and X==1 then x=0 elseif x<0 then x=#c[y]end end F=arg[1]and io.open(arg[1])or io.stdin l=0 for line in F:lines()do c[l]=setmetatable({},{__index=function()return 0 end})for k=1,#line do z=line:sub(k,k)if not i then if M(z,"['\"]")then i=z end if M(z,"[^\n\r]")then c[l][k-1]=B(z)end else if z==i then i=N end c[l][k-1]=B(z)end end l=l+1 end while 1 do q=C(c[y][x])if i then if M(q,"['\"]")then i=N else p(s,c[y][x])end else if M(q,"['\"]")then i=q elseif M(q,"%x")then p(s,tonumber(q,16)) elseif M(q,"[^ %z]")then A(f[q])f[q]()end end m()end ``` Readable version: ``` -- http://codegolf.stackexchange.com/questions/1595/interpret-fish -- -- TODO's -- threading instructions: -- * [ start thread at next change in direction. -- * ] end thread -- * . switch between global and local stack -- * m copy global to local stack -- p=table.insert -- push P=table.remove -- pop t=table.concat{ "><^v", -- Direction DONE "/\\|_#", -- Mirror DONE "x", -- random direction DONE "+-*,%", -- arithm. DONE "=)(", -- pops A and B of the stack if A==B then push 1 else push 0,same for greater than, lesser than. (result on stack) -- DONE "!", -- skip next DONE "?", -- if s[#s]==0 then skip next, else continue DONE ":", -- duplicate top DONE "~", -- remove top DONE "$", -- rotate top 2 values DONE "@", -- rotate top 3 values DONE "&", -- poptop to registry or read from registry DONE "r", -- reverse stack DONE "}{", -- shift stack right, (or up)/ shift stack left (or down) DONE "g", -- pops A,B push values at B,A in the codebox on the stack DONE "p", -- pops A,B,C from stack, and change value at C,B to A DONE "o", -- pops from stack and output character DONE "n", -- pops from stack, outputs number DONE "i", -- take 1 char of input, and push the ASCII value on stack DONE ";", -- os.exit() DONE --[["[", -- start new thread at next direction change "]", -- end thread ".", -- switch between global and local stack "m", -- Copy global stack to local one --]] } f={ "s.dx,s.dy=1,0","s.dx,s.dy=-1,0","s.dx,s.dy=0,-1","s.dx,s.dy=0,1", "s.dx,s.dy=-s.dy,-s.dx","s.dx,s.dy=s.dy,s.dx","s.dx=-s.dx","s.dy=-s.dy","s.dx,s.dy=-s.dx,-s.dy", "z=math.random(1,4)f[('><^v'):sub(z,z)]()", "p(s.s,P(s.s)+P(s.s))","p(s.s,-P(s.s)+P(s.s))","p(s.s,P(s.s)*P(s.s))","p(s.s,(1/P(s.s) or error'Div by 0')*P(s.s))","y=P(s.s)z=P(s.s)p(s.s,z%y)", "p(s.s,P(s.s)==P(s.s) and 1 or 0)", "p(s.s,P(s.s)>P(s.s) and 1 or 0)", "p(s.s,P(s.s)<P(s.s) and 1 or 0)", "s.x,s.y=s.x+s.dx,s.y+s.dy", "if #s.s==0 or s.s[#s.s]==0 then f['!']()end", "p(s.s,s.s[#s.s])", "P(s.s)", "z=#s.s s.s[z],s.s[z-1]=s.s[z-1],s.s[z]", "z=#s.s s.s[z],s.s[z-1],s.s[z-2]=s.s[z-1],s.s[z-2],s.s[z]", "if s.r then p(s.s,s.r)s.r=nil else s.r=P(s.s)end", "z={}for k=1,#s.s do z[#s.s-k+1]=s.s[k]end s.s=z", "p(s.s,1,P(s.s))", "p(s.s,P(s.s,1))", "z=P(s.s) p(s.s,s.c[P(s.s)][z])", "z,w=P(s.s),P(s.s) s.c[P()][w]=z", "io.write(string.char(P(s.s)))", "io.write(P(s.s))", "z=io.read(1) while z:match'%s'do z=io.read(1)end p(s.s,z:byte())", "os.exit()" } z=1 for k in t:gmatch"." do -- will contain the tokens f[k]=assert(loadstring(f[z])) z=z+1 end s={ -- state c={}, -- codebox IP wraps around s={}, -- stack dx=1, -- 1 for +x, -1 for -x, 0 for y/-y dy=0, -- 1 for +y, -1 for -y, 0 for x/-x x=0, -- X of IP y=0, -- Y of IP -- i, -- will contain type of quote when reading in a string -- r, -- registry -- codebox implementation -- codebox layout -- -- -- -----> +x -- @ |line of text -- wrap around to second line -- |second line of text. -- negative indices can be used for variables -- | -- V +Y -- y first coord, x second -- wrap around rows if nil row -- wrap around cols if nil char. move=function(s) s.x,s.y=s.x+s.dx,s.y+s.dy if s.y > #s.c then s.y=0 elseif s.y<0 then s.y=#s.c end if s.x>#s.c[s.y] and s.dx==1 then s.x=0 elseif s.x<0 then s.x=#s.c[s.y] end end } -- compile to codebox fh= arg[1] and io.open(arg[1]) or io.stdin -- use file or stdin y=0 for line in fh:lines() do s.c[y]=setmetatable({},{__index=function() return 0 end}) for k=1,#line do z=line:sub(k,k) --print(y,k,"|"..z.."|") if not s.i then -- normal mode if z:match"['\"]" then s.i=z end if z:match"[^\n\r]"then --filter out only newlines s.c[y][k-1]=string.byte(z) end -- any spacing allowed. else -- verbatim string mode if z==s.i then s.i=nil end s.c[y][k-1]=string.byte(z) end end y=y+1 end io.stdout:setvbuf("no") -- direct output function dbg() print("\nIP",s.y,s.x) print("command",string.char(s.c[s.y][s.x])) print("codebox:",#s.c) for y=0,#s.c do print("\tline",y) io.write"\t" for x=0,#s.c[y] do --io.write(string.char(s.c[y][x]),",\t") io.write(tostring(s.c[y][x]),",\t") end io.write"\n" end print("stack:") for k,v in pairs(s.s) do print("",k,v) end end function run() while 1 do r,e = pcall(string.char,s.c[s.y][s.x]) -- look up command in codebox if not r then print("Error happened reading command",s.c[s.y][s.x]) dbg() end q=string.char(s.c[s.y][s.x]) --print(s.y,s.x,q) if s.i then -- stringparsing mode if q:match"['\"]" then -- end-quote s.i=nil else p(s.s,s.c[s.y][s.x]) -- push contents of box, then advance end else -- not in string parsing mode if q:match"['\"]" then -- start-quote s.i=q elseif q:match"%x" then -- parsing a number p(s.s,tonumber(q,16)) elseif q:match"[^ %z]" then assert(f[q]) r,e= pcall(f[q]) -- call if not r then print("Error calling function for "..q..": \n",e) -- error happened, clarify end end end s:move() -- move the IP end end r,e=pcall(run) if not r then print("Error occured:",e) dbg() end ``` Not putting the next as result, as using compression directly isn't the goal I guess ;). Using murgaLua (or any Lua version with lzlib and luaSocket(for base64 decoding)), at the magic count of 1333: ``` L=loadstring L(zlib.decompress(mime.unb64("eJxtVW1z4jYQ/iuqaYp0yD587fQDzaadS+c6zPQyd4lnjgw4DC8ieACZyE6wDeS3d1fCB6H3AbTa12ff5Ary0Xip2BqqINGZMjn7gqRRq/RFsW+QpMHGJLliOXhXlw8v7weD3bBRtPx38gIE/+nPzuvPf/1i9tvHdaqTP/pxsPKuIQ8m85FhH5EYl2j8CYnVKJ/M2WfIVL5S+ciF/QqPKp8p/cJuSWCpLgU1ajRlG/B2PXkPoWzb06+JtvTDA+FO/176PUvdSzwBL8R0sp5EqgIEMA/MSE/TFQ/lb+KWz/q8SUk1RSd7HvNKViKWX7kQXOzWPJNfeCZa9Oeu/tmdqHfuWgGdyYxVr9Bm+VxpVmu8r4RaZoopY1LT/Dt5YeOStZtKT3eltXK2pF5dlEfPYNkM8bKQpYa1j6Ir+vuR4PJcUMgSilZPlq37HaJrZIDwUJT1G1kMNdQTLUa4yJ3VEDtyiNk1MjSpYuRWfhiDO+gW/09ojw+nOnhzqojAHItjhIEbZmtjbK4UuoLtfoYAF9h09DtNWYVA/EXLRl3EqMMyqCzEUL7phQy/N4I4kz5RMcZFrtxYvjWoBZsY/Xzj19x6EUjWvezyUGzmCc7nJxyK5kXWFATE8gkAuf/IK9RNs0AVSY7zEgU3EGK5ItkVLoGubESUQISwgy4sbGkzwBbc2a4uqRF3GO6Mw5x5gxL0Q/KwRhSHBMmHV0HIZnWhWKJZ3nm06+UFHqoPZSUz2HRmiZ5yb8cDX+w8nO0ZAoF/XaFZBNsVzJ71JE9SzcXpCGCbyqvGxHWqxCGhHhHzsl3zUEpOkFmgZr+MCX4PEJcbqKNRURsVYBXJjJGx1MfwGF3iquIqfObbLjSiViiXmKDsQY9qEtJi25GWBRSOKKG0xF5uh0PMVBUw/GcvqgDHI1hi1augix2mUPsJ+rrDXxRo7odiNoeReeyHFjU+Nulaae44Al0iJ8unicudarykGs/mnWWiVcZpFigTwnoS/FhLo/Jno9mvH2xs8X2cl3acYWkfm4VcCKqfTnOWuArhjebN6zcHXuwJx3MZHGUPAz0wtZRg9Be0kTSOpGfXid4hgNorLRlKfqCLP6xiK7SUG/hGdNUmmAS6S6DtCOcQ9bvxLT6bOT6bUbDCkwstU8CusSe45tZ7EdMTeJrN03k2h4V3C+pMathnBjX6pzfCi+LgijzkqX5ejZVBQfi7EG+cPLA66OG7gq/9U2xx17mjLm4tbR7Xr27Q0le4d1Y0KvVY0m7fMPqWYMrsYP4fCvRCgw==")))() ``` [Answer] ## Delphi, 1855 1701 This version has thread-support at quite a cost : The version without thread-support is 1144 characters right now, so thread-support adds 557 characters (about 50%)! ``` type R=^_;_=record n:R;d:R;s:String;i,m,b,p,v,w,x,y,A,l:Int16;procedure U(v:Int16);function O:Int16;procedure T(a,b:Int16);procedure E;end;var f:TextFile;c,g,k:String;h:R;procedure _.U;begin if p>0then g:=g+Chr(v)else s:=s+Chr(v)end;function _.O;begin if l=0then Exit(0);if p>0then O:=Ord(g[l])else O:=Ord(s[l]);if p>0then Delete(g,l,1)else Delete(s,l,1);Dec(l)end;procedure _.T;begin if(d<>nil)then begin d.n:=n;n:=d;d.v:=v;d.w:=w;d:=nil;n.T(a,b);Exit;end;x:=a;y:=b;end;procedure _.E;begin v:=(v+x+80)mod 80;w:=(w+y+25)mod 25;i:=Ord(c[1+v+80*w])end;var j:byte;begin h:=AllocMem(32);h.n:=h;h.x:=1;h.v:=-1;Assign(f,ParamStr(1));Reset(f);for j:=1to 25do begin ReadLn(f,k);c:=c+k+StringOfChar(' ',80-Length(k))end;repeat h:=h.n;h.E;with h^ do begin k:=s;if p>0then k:=g;l:=Length(k);A:=i;case i-32of 2,7:repeat E;U(i);Inc(l)until i=A;4,5,8,9,12,13,26,32,71,80,93:A:=O;6:b:=1-b;88:i:=Ord('<>^v'[1+Random(4)]);91:l:=1;73:Read(PChar(@A)^)end;case i-32of 4:l:=l+1;80:l:=O;91:A:=O;93:l:=2;26:U(A)end;case i-32of 0,88:;1:E;2,7,94:O;3:T(-x,-y);4,32,93:if p>0then Insert(Chr(A),g,l-1)else Insert(Chr(A),s,l-1);5:U(O mod A);6:if b=0then U(m)else m:=O;8:U(Ord(O>A));9:U(Ord(O<A));10:U(O*O);11:U(O+O);12:U(O div A);13:U(O-A);14:p:=1-p;15:T(-y,-x);16..25:U(i-48);26,73,91:U(A);28,30:T(i-61,0);29:U(Ord(O=O));31:if(l=0)or(k[l]=#0)then E;59:d:=AllocMem(32);60:T(y,x);61:begin if(h=n)then Exit;d:=n;while(d.n<>h)do d:=d.n;d.n:=h.n;d:=h;h:=n;d:=nil;end;62:T(0,-1);63:T(x,-y);65..70:U(i-87);71:U(Ord(c[1+O+80*A]));77:begin if p>0then s:=s+g else g:=g+s;if p>0then g:=''else s:=''end;78:Write(O);79:Write(Chr(O));80:c[1+O+80*l]:=Chr(A);82:for j:=1to(l)do s[j]:=k[l-j+1];86:T(0,1);92:T(-x,y)else Exit;end;end;until 0=1;end. ``` Note that this implementation contains a few ideas that will reduce my other submission by a few dozen characters (I'll apply them later). This code runs the 'multithreaded hello, world' sample flawlessly, and most of the other samples. (My interpreter does give me an division by zero exception when running the 'e' sample - can anyone confirm this with another ><> interpreter?) Here the indented and commented code : ``` {debug}uses Windows;{} // Note : Lowercase identifiers are variables, Uppercase identifiers are types and functions. type R=^_;_=record // n is the next thread (self if round robin) n:R; // d is an extra thread (will start running at next turn) d:R; // s is the thread-local stack (kept as a string) s:String; // i is the current instruction read from the program i, // m is the registry memory value (read/written by the '&' instruction) m, // b indicates if the registry should be written (b=0) or read (b>0) by the '&' instruction b, // p is the stack selector (p=0 : Use thread local stack, p>0 : Use global stack) p, // v,w are x,y positions into the program v,w, // x,y are steps in the respective direction (values -1,0 or 1) : x,y, // A is a temporary variable (only uppercase var, to coincide with comments) A, // l is the length of the stack (may be abused as a temporary) l :Int16; procedure U(v:Int16); function O:Int16; procedure T(a,b:Int16); procedure E; end; var // f is the source file f:TextFile; // c is the entire codebox (a 2-dimensional program) c, // g is the global stack g, // k is a temporary stack copy, needed for reversal k:String; // h is the current thread h:R; procedure _.U; // PUSH begin // Push value onto the stack: if p>0then g:=g+Chr(v)else s:=s+Chr(v) end; function _.O; // POP begin // Pop value from the stack : if l=0then Exit(0); if p>0then O:=Ord(g[l])else O:=Ord(s[l]); if p>0then Delete(g,l,1)else Delete(s,l,1); Dec(l) end; procedure _.T; // TURN begin // Split off a new thread when requested : if(d<>nil)then begin // Insert the new thread in the chain : d.n:=n; n:=d; // Split off the thread : d.v:=v; d.w:=w; d:=nil; n.T(a,b); Exit; end; // Turn in a new direction : x:=a; y:=b; end; procedure _.E; // STEP begin //{debug}Sleep(10);{} // Note : x-step needs to stay on same line, y-step needs to stay on same column v:=(v+x+80)mod 80; w:=(w+y+25)mod 25; i:=Ord(c[1+v+80*w]) end; var j:byte; begin {debug}Assert(SizeOf(_)=32); // Initialize first thread : h:=AllocMem(32); h.n:=h; h.x:=1; h.v:=-1; // Open file given at the command-line, and read & expand it's lines into our program buffer : Assign(f,ParamStr(1)); Reset(f); for j:=1to 25do begin ReadLn(f,k); c:=c+k+StringOfChar(' ',80-Length(k)) {debug};SetLength(c,j*80) end; // Cycle over all threads, executing one instruction per thread : repeat h:=h.n; // Take a step (which gives a new 'i'nstruction) h.E; with h^ do begin // Make a copy of the active stack, and determine it's length : k:=s; if p>0then k:=g; l:=Length(k); // Shorten '''' and '"' (case 2 and 7) string-collecting, by remembering the quote character in A : A:=i; // Prevent begin+end pair for instructions that need only 2 statements, by handling the 1st here : case i-32of // Note : The instruction is decreased by 32, resulting in less digits // Shorten string-collecting, by pushing the entire string here (the opening quote was remembered in A) : 2,7:repeat E;U(i);Inc(l)until i=A; // Note : We stop at the closing character, so the next block will still handle 'i'! // These instructions all need to Pop A, so write it just once here : 4,5,8,9,12,13,26,32,71,80,93:A:=O; // Prevent begin+end for register access, by switching the read/write flag here : 6:b:=1-b; // 'x' (case 120>88): Turn random direction; Choose a random direction instruction and let the 3rd case-block handle it : 88:i:=Ord('<>^v'[1+Random(4)]); // Shorten '{' (case 123-32=91): Share 3rd case-block with ':' (>26) and 'i' (>73) by setting l to 1 here : 91:l:=1; // Prevent begin+end for input retrieval, by reading the input into A here : 73:Read(PChar(@A)^) // Note : This case is last, because it ends on ')', which avoids a closing ';' end; // Shorten a few more cases by preparing variables so they can be shared with eachother and the 3rd case-block below : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! // Shorten '$' (case 38-32=4): Set 'l' to l+1 so that the 3rd case-block can insert just like '@' and '}' : 4:l:=l+1; // Shorten 'p' (case 112-32=80): Set 'l' to O() so that the 3rd case-block doesn't need a begin+end pair : 80:l:=O; // Shorten '{' (case 123-32=91): Share 3rd case-block with ':' (>26) and 'i' (>73) by popping A from position 1, as tricked above!: 91:A:=O; // Note : This is NOT the same as doing this in the 1st case-block, as 'l' needs to be 1 first! // Shorten '}' (case 125-32=93): Prepare 'l' so that the implementation can be shared with '@' (>32): 93:l:=2; // Shorten ':' (case 58-32=26): Share implementation with 'i' (>73) by pushing first copy of A (read above) here 26:U(A) // Note : This case is last, because it ends on ')', which avoids a closing ';' end; // All statements (1 statement, or 2nd statement, or begin+end pair with 2 or more statements) : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! //' ': Ignore spaces 0,88:; //'!': Skips the following instruction. 1:E; //'"','''': Enables string parsing. String parsing pushes every character found to the stack until it finds a closing quote. //'~': Removes the top value from the stack. 2,7,94:O; //'#': Mirror both axes 3:T(-x,-y); //'$': Rotates the top 2 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,2,4,3) //'@': Rotates the top 3 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,4,2,3) //'}': Shifts the stack to the right / rotates entire stack clockwise (e.g. 1,2,3,4 becomes 4,1,2,3) 4, 32, 93:if p>0then Insert(Chr(A),g,l-1)else Insert(Chr(A),s,l-1); // Note : A was Popped in 1st case block //'%': Pops A and B off the stack, and pushes B mod A. 5:U(O mod A); //'&': Pops the top value off the stack and puts it in the registry. Calling & again will take the value in the registry and put it back on the stack. 6:if b=0then U(m)else m:=O; //'(': Less than. Pops A and B off the stack, and pushes 1 if B > A 8:U(Ord(O>A)); //')': Greater than. Pops A and B off the stack, and pushes 1 if B < A 9:U(Ord(O<A)); //'*': Pops A and B off the stack, and pushes B * A. 10:U(O*O); // Note : A and B are inverted, but order is irrelevant here //'+': Pops A and B off the stack, and pushes B + A. 11:U(O+O); // Note : A and B are inverted, but order is irrelevant here //',': Pops A and B off the stack, and pushes B / A. Division by 0 raises an error. 12:U(O div A); //'-': Pops A and B off the stack, and pushes B - A. 13:U(O-A); //'.': Switch between thread-local and global stack 14:p:=1-p; //'/': Mirror 15:T(-y,-x); //'0'..'9': Push value 0-9 onto the stack. 16..25:U(i-48); //':': Duplicates the top value on the stack. //'i': Takes one character as user input and pushes it's ASCII value to the stack //'{': Shifts the stack to the left / rotates entire stack counter-clockwise (e.g. 1,2,3,4 becomes 2,3,4,1) 26, // Note for ':' : First A was already pushed once above 73, // Note for 'i' : Read() into A was done in 1st case block 91:U(A); // Note for '{' : l=1 was done in 1st case block, A:=O was done in 2nd block //'<': Turn west //'>': Turn east 28,30:T(i-61,0); //'=': Pops A and B off the stack, and pushes 1 if B = A, and 0 otherwise. 29:U(Ord(O=O)); // Note : A and B are inverted, but order is irrelevant here //'?': Skips the following instruction if top of stack is zero, or stack is empty. (note: this does not pop anything off the stack!) 31:if(l=0)or(k[l]=#0)then E; //'[': Creates a new thread at the next direction-changing instruction. 59:d:=AllocMem(32); // Note : Double execution gives memleaks, could be fixed with prefix 'if(d=nil)then ' //'\': Mirror 60:T(y,x); //']': Ends the current thread. 61:begin if(h=n)then Exit;d:=n;while(d.n<>h)do d:=d.n;d.n:=h.n;d:=h;h:=n;d:=nil;end; // Note : Memleak on d could be fixed with FreeMem(d) //'^': Turn north 62:T(0,-1); //'_': Mirror y 63:T(x,-y); //'a'..'f': Push value 10-15 onto the stack. 65..70:U(i-87); //'g': Pops A and B off the stack, and pushes the value at B,A in the codebox. 71:U(Ord(c[1+O+80*A])); // Note : A was Popped in 1st case block //'m': Takes all data from the current stack and moves it to the end of the other stack. 77:begin if p>0then s:=s+g else g:=g+s;if p>0then g:=''else s:=''end; //'n': Pops and outputs the value 78:Write(O); //'o': Pops and outputs as a character 79:Write(Chr(O)); //'p': Pops A, B, and C off the stack, and changes the value at C,B to A. 80:c[1+O+80*l]:=Chr(A); // Note : A was Popped in 1st case block, l was set to 1 in 2nd case block //'r': Reverses the stack. 82:for j:=1to(l)do s[j]:=k[l-j+1]; // Note: This reads from the stack-copy //'v': Turn south 86:T(0,1); //'|': Mirror x 92:T(-x,y) // Note : This case is last, because it ends on ')', which avoids a closing ';' else // ';' (27) and unrecognized instructions end execution. Exit; end; end; until 0=1; end. ``` Edit history : (1855-154=1701) : Applied all ideas from the non-threaded version [Answer] # PHP, 2493 bytes ``` <?php if($argc<=1||$argv[1]=='-h'){echo 'e.g.: fish.php program.fish';}else{$f=$argv[1];if(file_exists($f)){$x=file_get_contents($f);$x=str_replace(a("\r\n","\r"),"\n",$x);f($x);}}function f($f){$g=explode("\n",$f);foreach($g as &$u){$a=a();$i=0;while($i++<=strlen($u)){$a[]=substr($u,$i,1);}$u=$a;}$p=a(0,0);$d=a(1,0);$s=a();$q=false;$r=null;while(1){$c=g($g,$p);if($c!==null){if($q&&$c!='"'&&$c!='\''){$s[]=ord($c);}else if(h($c)){$s[]=hexdec($c);}else {if($c=='x'){$a=a('<','>','^','v');$c=$a[mt_rand(0,3)];}switch($c){case '>':$d=a(1,0);break;case '<':$d=a(-1,0);break;case '^':$d=a(0,-1);break;case 'v':$d=a(0,1);break;case '/':$d=a(-$d[1],-$d[0]);break;case '\\':$d=a($d[1],$d[0]);break;case '|':$d[0]=-$d[0];break;case '_':$d[1]=-$d[1];break;case '#':$d=a(-$d[0],-$d[1]);break;case 'o':case 'n':case '~':$a=p($s);if($c=='o'){echo chr($a);}else if($c=='n'){echo (int)$a;}break;case ')':case '(':case '=':$a=p($s);$b=p($s);$s[]=($b<$a&&$c=='(')||($b>$a&&$c==')')||($a==$b&$c=='=')?1:0;break;case ',':case '*':case '%':case '-':case '+':$a=p($s);$b=p($s);switch($c){case '+':$s[]=$b+$a;break;case '-':$s[]=$b-$a;break;case '*':$s[]=$b*$a;break;case ',':$s[]=$b/$a;break;case '%':$s[]=$a%$b;break;}break;case ':':$a=p($s);array_push($s,$a,$a);break;case '!':case '?':if((c($s)==0)||$c=='!'){m($g,$d,$p);}break;case 'g':$a=p($s);$b=p($s);$o=ord(gc($g,a($b,$a)));$s[]=$o;break;case 'p':$j=p($s);$k=p($s);$h=p($s);$g[$k][$h]=chr($j);break;case '$':$a=p($s);$b=p($s);array_push($s,$a,$b);break;case '@':$a=p($s);$b=p($s);$j=p($s);array_push($s,$a,$j,$b);break;case 'r':$s=array_reverse($s);break;case '}':$a=p($s);array_unshift($s,$a);break;case '{':$a=array_shift($s);$s[]=$a;break;case '&':if($r==null){$r=p($s);}else {array_push($s,$r);$r=null;}break;case '\'':case '"':$q=!$q;break;case ';':return;break;case ' ':case "\n":break;default:echo 'E: Unknown syntax "'.$c.'" at ('.$p[0].', '.$p[1].')';return;break;}}}m($g,$d,$p);}}function p(&$s){return array_pop($s);}function h($c){$d=-1;if(is_numeric($c)){$d=(int)$c;}return ($d>=0&&$d<=9)||($c>='a'&&$c<='f');}function m($g,&$d,&$p){$p[1]+=$d[1];$p[0]+=$d[0];if($d[1]!=0){if($p[1]<0){$p[1]=c($g)-1;}if($p[1]>=c($g)){$p[1]=0;}}else{if($p[0]>=c($g[$p[1]])){$p[0]=0;}if($p[0]<0){$p[0]=c($g[$p[1]])-1;}}}function g($g,$p){if(kc($p[1],$g)){if(is_array($g[$p[1]])&&kc($p[0],$g[$p[1]])){return $g[$p[1]][$p[0]];}}return null;}function kc($k,$a){return array_key_exists($k,$a);}function a(){return func_get_args();}function c($a){return count($a);} ``` I know that it has been implemented with smaller compiler size with other languages, but nevertheless with the spirit of a never-say-die programmer, I've came up with a PHP CLI interpreter for `><> Fish`. The entire source code is below. 2 main feature of the Fish programming language was not implemented, namely: 1. Multi-threading. PHP scripts are single-threaded top-down execution only. 2. Input `i` of a character. PHP CLI requires the user to press the `<Enter>` key in order to enter input into the input buffer. Note that I've written and optimized much of the native functions including the creation of array by using: ``` function a(){ return func_get_args(); } $a = a(1,3,4,5); ``` instead of ``` $a = array(1,3,4,5); ``` The program can be accessed through command line interface (CLI) using the following command: > > php fish.php program.fish > > > I spent a total of 6 hours to complete this with reference to the original python interpreter. Original Source: ``` <?php if($argc <= 1 || $argv[1] == '-h'){ echo 'e.g.: fish.php program.fish'; }else{ $f = $argv[1]; if(file_exists($f)){ $x = file_get_contents($f); $x = str_replace(a("\r\n", "\r"), "\n", $x); f($x); } } function f($f) { $g = explode("\n", $f); foreach($g as &$u){ $a = a(); $i = 0; while($i++ <= strlen($u)){ $a[] = substr($u, $i, 1); } $u = $a; } $p = a(0, 0); // position $d = a(1, 0); // direction $s = a(); // stack $q = false; // string lateral $r = null; // registry while (1) { $c = g($g, $p); if ($c !== null) { if ($q && $c != '"' && $c != '\'') { $s[] = ord($c); } else if (h($c)) { $s[] = hexdec($c); } else { if($c == 'x'){ $a = a('<', '>', '^', 'v'); $c = $a[mt_rand(0, 3)]; } switch ($c) { case '>': $d = a(1, 0); break; case '<': $d = a(-1, 0); break; case '^': $d = a(0, -1); break; case 'v': $d = a(0, 1); break; case '/': $d = a(-$d[1], -$d[0]); break; case '\\': $d = a($d[1], $d[0]); break; case '|': $d[0] = -$d[0]; break; case '_': $d[1] = -$d[1]; break; case '#': $d = a(-$d[0], -$d[1]); break; case 'o': case 'n': case '~': $a = p($s); if ($c == 'o') { echo chr($a); } else if ($c == 'n') { echo (int)$a; } break; case ')': case '(': case '=': $a = p($s); $b = p($s); $s[] = ($b < $a && $c == '(') || ($b > $a && $c == ')') || ($a == $b & $c == '=') ? 1 : 0; break; case ',': case '*': case '%': case '-': case '+': $a = p($s); $b = p($s); switch ($c) { case '+': $s[] = $b + $a; break; case '-': $s[] = $b - $a; break; case '*': $s[] = $b * $a; break; case ',': $s[] = $b / $a; break; case '%': $s[] = $a % $b; break; } break; case ':': $a = p($s); array_push($s, $a, $a); break; case '!': case '?': if ((c($s) == 0) || $c == '!') { m($g, $d, $p); } break; case 'g': $a = p($s); $b = p($s); $o = ord(gc($g, a($b, $a))); $s[] = $o; break; case 'p': $j = p($s); $k = p($s); $h = p($s); $g[$k][$h] = chr($j); break; case '$': $a = p($s); $b = p($s); array_push($s, $a, $b); break; case '@': $a = p($s); $b = p($s); $j = p($s); array_push($s, $a, $j, $b); break; case 'r': $s = array_reverse($s); break; case '}': $a = p($s); array_unshift($s, $a); break; case '{': $a = array_shift($s); $s[] = $a; break; case '&': if ($r == null) { $r = p($s); } else { array_push($s, $r); $r = null; } break; case '\'': case '"': $q = !$q; break; case ';': return; break; case ' ': case "\n": break; default: echo 'E: Unknown syntax "' . $c . '" at (' . $p[0] . ', ' . $p[1] . ')'; return; break; } } } m($g, $d, $p); } } function p(&$s) { return array_pop($s); } function h($c) { $d = -1; if (is_numeric($c)) { $d = (int) $c; } return ($d >= 0 && $d <= 9) || ($c >= 'a' && $c <= 'f'); } function m($g, &$d, &$p) { $p[1] += $d[1]; $p[0] += $d[0]; if($d[1] != 0){ if($p[1] < 0){ $p[1] = c($g) - 1; } if($p[1] >= c($g)){ $p[1] = 0; } }else{ if($p[0] >= c($g[$p[1]])){ $p[0] = 0; } if($p[0] < 0){ $p[0] = c($g[$p[1]]) - 1; } } } function g($g, $p){ if(kc($p[1], $g)){ if(is_array($g[$p[1]]) && kc($p[0], $g[$p[1]])){ return $g[$p[1]][$p[0]]; } } return null; } function kc($k, $a){ return array_key_exists($k, $a); } function a(){ return func_get_args(); } function c($a){ return count($a); } ``` ### Edit History 1. Changed the `x` syntax to select one of the direction instead of selecting on its own. 2. Fixed the `p` command where `chr()` should be used before pushing value into code box. ]
[Question] [ in my country we have a children's song which goes like this: ``` Priletela muha na zid, muha na zid, muha na zid. Priletela muha na zid, muha na zid. Pralatala maha na zad, maha na zad, maha na zad. Pralatala maha na zad, maha na zad. Preletele mehe ne zed, mehe ne zed, mehe ne zed. Preletele mehe ne zed, mehe ne zed. Prilitili mihi ni zid, mihi ni zid, mihi ni zid. Prilitili mihi ni zid, mihi ni zid. Prolotolo moho no zod, moho no zod, moho no zod. Prolotolo moho no zod, moho no zod. Prulutulu muhu nu zud, muhu nu zud, muhu nu zud. Prulutulu muhu nu zud, muhu nu zud. ``` As you can see, it contains a bit of redundant information. So I was wondering if it could be compressed a bit. This is code golf — shortest code wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~54~~ 52 bytes Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -2 bytes! ``` T"ÿ, 0, 0. ÿ, 0. "T.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}? ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/ROnwfh0FAyDS4wKyuICUUojeo4ZFh/c@ath5aMW5xYdWHZ5/ui3k3JbassMzlIEyeodWqVccWvioYeHRfb5ltkCi8vA8IK/W/v9/AA "05AB1E – Try It Online") **Commented**: ``` T # push 10 "ÿ, 0, 0.\nÿ,\n0.\n" # push string literal "10, 0, 0.\n10,\n0.\n" T # push 10 again .•ý‹¨ΣªßˆTδ}vØ#• # push compressed string "priletela xmuha na zid" .ª # sentence case => "Priletela xmuha na zid" ‛x¡ # split on 'x' => ["Priletela ", "muha na zid"] ‡ # replace every digit of 10 with the corresponding list entry in the string literal # this is the first verse žM # push the vowels "aeiou" v } # for y in vowels: = # print the last verse without removing it from the stack žM # push the vowels yÞ # the infinite list of the vowel y ‡ # replace every vowel with y ? # print the last verse without a trailing newline ``` --- more obfuscated and a lot slower 52-byter: ``` •nöðrb•ØTz… , «ÅвJT.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}? ``` [Don’t try it online!](https://tio.run/##yy9OTMpM/f//UcOivMPbDm8oSgKyDs8IqXrUsExBh@vQ6sOtFzZ5heiBRPc@ath5aMW5xYdWHZ5/ui3k3JbassMzlIEyeodWqVccWvioYeHRfb5ltkCi8vA8IK/W/v9/AA "05AB1E – Try It Online") ``` •nöðrb• # push compressed integer 211262272027 Ø # push the 211262272028th prime 5996494318979 (slow) Tz # push 1/10 … ,\n # push string " ,\n" « # concatenate to "0.1 ,\n" Åв # convert the prime into that custom base J # join from list of chars into a string # this generates the same string as T"ÿ, 0, 0.\nÿ,\n0.\n" above ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), ~~110~~ ~~105~~ 104 bytes *Saved five bytes, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!* *Saved a byte using [Arnauld's finding](https://codegolf.stackexchange.com/a/216416/83605).* ``` puts z="#{y="Priletela #{$x='muha na zid'},"} #$x, #$x. #{y} #$x.","aeiou".chars.map{z.gsub /[aeiu]/,_1} ``` [Try it online!](https://tio.run/##FYpNCoYgFAD3neLxDNqIncA7tI8WLz8poT@0B6V5dr/aDAMznse7lIPPAFGjSLfGzrvFnnYhEKm@dLPyTLARRPdrssQMor7kB1W9f64@Q4lkHaMyM/mgVjrSY56opsAjtP3bdh5aaXIpfw "Ruby – Try It Online") TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes. [Answer] # JavaScript (ES6), ~~121~~ 120 bytes ``` _=>["$&",..."aeiou"].map(v=>`${p=`Priletela ${q='muha na zid'},`} ${q}, ${q}. ${p} ${q}.`.replace(/[aeiu]/g,v)).join` ` ``` [Try it online!](https://tio.run/##HYxLDoMgFEXnrMIQUyGhzxXgGjo3prwoWgwCfgc1rJ1aJzcnJzl3xAPXdjFhezrf6dTL9JZVTfMHFQBAURu/0wYmDOyQlcrPINVrMVZv2mKWn7Mspv2DmcPsa7oiChX/Nop7gVxBJDcqWHSw2GpW1tft3pSDODiH0RunCFGp9W71VoP1A@sZ5@kH "JavaScript (Node.js) – Try It Online") ### Commented ``` _ => // anonymous function ignoring its input [ // "$&", // 1st stanza: use "$&" to leave the vowels unchanged ..."aeiou" // next ones: force all vowels to "a", "e", ..., "u" ] // .map(v => // for each replacement pattern v: `${ // build the stanza template p = `Priletela ${ // by defining p = "Priletela muha na zid," q = 'muha na zid' // and q = "muha na zid" },` // } ${q}, ${q}.\n${p}\n${q}.` // and using them to build the other parts .replace( // update the template: /[aeiu]/g, // replace each vowel ... v // ... with the replacement pattern // NB: there's no "o" in the template ) // end of replace() ).join`\n\n` // join with two line-feeds ``` [Answer] # [Python 2](https://docs.python.org/2/), 122 bytes ``` s="Priletela muha na zid," v="aeiou_" for x in v: w=s[10:-1]+".\n";print s,s[10:],w+s+"\n"+w for y in v:s=s.replace(y,x) ``` [Try it online!](https://tio.run/##dZHBbsMgDIbvfgqL06ZkaN2xU96h962arM0VSASiAE2Tl88g7aFI4eDDb32fLcMwB@Xsx7r6TpxGbTiwIeyjIrSEi/5rBVw7Qaxd/BFwcSPeUFu8HgGnzn8d3o9vh3Mj5LcVn8OobUDfbu1zOzW@EanfTIBZnO@i77wceTD0yy9ze3td1/3F1SBhX4CCSRAZCpQhevQpD6oEWRGgYBLE22rGnhWjZVw4D6oEWRGgYLaDdEiFvVYarX4cXQmyIkDBJMgZF1Jh75RD63BxeVAlyIoABZOgaGJIlR8/oo24xPsH7QZZEeCZ@Qc "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~146~~ 134 bytes ``` w="muha na zid";a="Priletela ";s=""<>{a,w,", ",w,", ",w,". ",a,w,", ",w,"."};c=Characters@"aeiou";s<>(StringReplace[" "<>s,c->#]&/@c) ``` [Try it online!](https://tio.run/##TYxBCsIwEEX3OUUYQRRSPUCaUPACoktxMcTBBJJakikFxbPHQDeuHv/xeQnZU0IODmtdDKTZoxxRvsMDNBo45xCJKaIEXQxAbz@oFgVKwh8OAtSqxbrhq505eczomHIZACm85pbo7e7KOYzPC00RHd1AiBYtynV2c98eB7evtXZTu/AP "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + sed, 98 bytes ``` sed -ney/{%/\\n,eiu/aaa,a/e,e/i,i/o,o/u}/\;p<<<"${x=Priletela ${y=muha na zid}}, $y, $y.%$x,%$y.%" ``` [Try it online!](https://tio.run/##FcXBCYAwDADAVYK0v2gGsO7gAP1EDBjQKmrBWjp7xcdxE19LrZfM0AZJlC15H1A0EjMjk6CQotKOO8VCvj@cc43JzzCeusotK4PJadjiwhAYXp1LQTDp11nzoP1vav0A "Bash – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 62 bytes ``` 3,2µ“muha na zid”Wẋjị⁾ ¶ṭ”,Ɗ⁶;“!b^ṙzḳ“)»j)Y ØẹµØẹW;y¢)¢W¤;j⁾¶¶ ``` [Try it online!](https://tio.run/##y0rNyan8/99Yx@jQ1kcNc3JLMxIV8hIVqjJTHjXMDX@4qzvr4e7uR437FA5te7hzLVBM51jXo8Zt1kC1iklxD3fOrHq4YzOQo3lod5ZmJNfhGQ937Ty0FUyFW1ceWqR5aFH4oSXWWUAjDm07tO3/fwA "Jelly – Try It Online") ## Explanation ``` 3,2µ“muha na zid”Wẋjị⁾ ¶ṭ”,Ɗ⁶;“!b^ṙzḳ“)»j)Y Auxiliary niladic link 3,2 [3, 2] µ ) For each: “muha na zid”W ["muha na zid"] ẋ Repeat that many times j Ɗ Join with: ị⁾ ¶ Index with the number into " \n" ṭ”, Append that to "," ⁶; Prepend a space “!b^ṙzḳ“)»j Join ["Priletela", "."] with this Y Join with a newline ØẹµØẹW;y¢)¢W¤;j⁾¶¶ Main niladic link Øẹ "aeiou" µ ) For each: ØẹW ["aeiou"] ; Append the vowel y¢ Translate the result of the previous link with this table ¢W¤; Prepend list with result of previous link j⁾¶¶ Join with double newlines ``` [Answer] # [Red](http://www.red-lang.org), 150 bytes ``` e: rejoin[a:"Priletela "b:"muha na zid"c:", "b c b d:".^/"a b c"^/"b d]v: charset w:"aeiou"foreach u w[print e parse e[any[change v u | skip]]]print e ``` [Try it online!](https://tio.run/##LYvBCsIwEAXvfsVjz6L3/QrxGiJsk9VGaxLSpkXx32MEb8MwU9S3s3pjmzKK3lOIRphOJUy66CSggelZR0EUvIMnx7TvEg4DPNPhciTp6KhDN3blnRulzLpgYxINqdI1FRU3omIzuYS4QJF/DdRIfJk@xJti7cEH8yNka@2/a@0L "Red – Try It Online") [Answer] For a start, this is my attempt in Javascript: # [JavaScript (Node.js)](https://nodejs.org), 184 bytes ``` a='aeiou' x='muha na zid' y='Priletela' z=`${y} ${x}, ${x}, ${x}.\n${y} ${x},\n${x}.` console.log([z].concat(a.split('').map(e=>z.replace(new RegExp('['+a+']', "g"), e))).join('\n\n')) ``` [Try it online!](https://tio.run/##TYhLCoMwFAD3niKI8BK0uUG66750q4IPfdhITIKfViOe3dpVuxlmpsMXjvWg/XSxrqHjQAVI2s0QLQr6@YnMIgu6gWhVcB@0oYkMQhRUlWzrzpJt2bM/ysL@/tfPVUW1s6MzJI1reR5KeXaNE0c5eqMnDiBkj56TugY5kDdYE7f0Zg9qb4vnkEOKKZSQsbiNRcZICCE7py2HwhYWhDiODw "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I feel like `”u”aØẹe?ṙ1Øẹ,y` could be golfed ``` ”u”aØẹe?ṙ1Øẹ,y 820Dṃ“!b^ṙzḳ“¢ʋỴM$ƊEⱮ/¥ɦ8»K€YF”.0,48¦ÇƬj⁾¶¶ ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw9xSIE48POPhrp2p9g93zjQEM3UquSyMDFwe7mx@1DBHMSkOKFH1cMdmIOfQolPdD3dv8VU51uX6aOM6/UNLTy6zOLTb@1HTmkg3oFF6BjomFoeWHW4/tibrUeO@Q9sObfv/HwA "Jelly – Try It Online")** [Answer] # [Perl 5](https://www.perl.org/) (`-0777p`), 91 bytes ``` s//Priletela muha na zid/;/ /;$_.=", $', $'. $_, $'. ";for$i(a,e,i,o,u){say;s/[aeiou]/$i/g} ``` [Try it online!](https://tio.run/##FcWxCsIwEADQvV8RSkCFa64OJUPwE4TuIuXAqAexCUkzVPHXPenweMnnMIgUxDFz8IsPpF71SWom9eYbOlTo9GROLSi925hGT9Bst@4es@Y9gQeGCPXwKbS6ghfyHOsVNePjK/KLaeE4F@nOg@mP0vXW2vQH "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 84 bytes ``` .•bKÜ2TÐhrŒ°•'b.•[÷‚rµ₃•™:'c.•AΩJεмF‚•:…fgj…,. ‡DžMŽh’‡1'a‡D'a'e‡D'e'i‡D'i'o‡D'o'u‡» ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f71HDoiTvw3OMQg5PyCg6OunQBqCAehJIOPrw9kcNs4oObX3U1AzkPmpZZKWeDJJwPLfS69zWC3vcgNJArtWjhmVp6VlAUkeP61HDQpej@3yP7s141DATyDFUTwQJqSeqp4LpVPVMMJ2png@m89VLgfSh3f//AwA "05AB1E – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~154~~ ~~152~~ 146 bytes I wrote nonprintables that won't show up on SE in hex using `<kbd>`. ``` i,p[]=L"muha na zid`0x00`Priletela ";main(){for(;i<48;p["`0x14``0x12``0x10``0x0e``0x09``0x06``0x03``0x01`"[i%8]]="aeiou"[i++/8])i%8?:printf("%S%S, %2$S, %2$S.\n%1$S%2$S,\n%2$S.\n\n",p+12,p);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9TpyA61tZHKbc0I1EhL1GhKjOFIaAoMye1JDUnUUHJOjcxM09Dszotv0jDOtPGxMK6IFpJREiAj5ONmVEpOlPVIjbWVikxNTO/FMjT1ta3iNUECtpbFRRl5pWkaSipBqsG6yioGqlASb2YPFVDlWCwAJAJEYnJU9Ip0DY00inQtK79/x8A "C (gcc) – Try It Online") ``` #include <stdio.h> int main(void) { // These are merged together with a raw null byte in the golfed code. // I set them to wchar_t (L"") solely because of implicit int, cuz screw // Windows and its UTF-16. :P char pril[] = "Priletela"; // golfed code has trailing space char muha[] = "muha na zid"; // The golfed code does a different loop pattern where it does one big // loop which replaces a char each iteration and prints when i%8==0. // However, that is difficult to follow. for (int i = 0; i < 6; i++) { // Note: golfed code doesn't use positionals on the first two arguments, // and it uses %S because they are wchar_t strings. // // Priletela muha na zid, muha na zid, muha na zid. // %1$s %2$s , %2$s , %2$s .\n // Priletela muha na zid, // %1$s %2$s ,\n // muha na zid. // %2$s .\n\n printf("%1$s %2$s, %2$s, %2$s.\n%1$s %2$s,\n%2$s\n\n", pril, muha); // Replace the vowels one by one. // The golfed version loops 8 times since it is one string. for (int j = 0; j < 4; j++) { // Nope, never y. const char vowels[] = "aeiou"; // Vowel indexes. This is encoded in a binary string in the golfed // code, and it is one array because the strings are merged. const int pril_lut[] = { 2, 4, 6, 8 }; const int muha_lut[] = { 1, 3, 6, 9 }; pril[pril_lut[j]] = vowels[i]; muha[muha_lut[j]] = vowels[i]; } } } ``` ~~Unless we find a way to kill the printf string, I don't see any other options to make this smaller.~~ I have clearly been proven wrong more than once. :P -2 bytes thanks to ceilingcat for better variable declaration and looping backwards. -6 bytes thanks to gastropner for ~~making me eat my words~~ combining the two for loops. [Answer] # [Vim](https://www.vim.org/), 95 bytes ``` iPriletela<esc>3a muha na zid,<esc>r.Ypo<esc>k7f r k4f Dk4YGoaeiou<esc>:s/./&<C-r>0/g 5Gqrx:,+2s/[aeiu]/<C-r>"/g 2jq4@r ``` [Try it online!](https://tio.run/##K/v/PzOgKDMntSQ1J9EmtTjZzjhRIbc0I1EhL1GhKjNFByxWpBdZkA9mZZunKRRxZZukKbhkm0S65yemZuaXgmWsivX19NVsnHWL7Az007lM3QuLKqx0tI2K9aOBikpj9cFSSkApo6xCE4ei////65YBAA "V (vim) – Try It Online") This approach leaves two blank lines at the end of the song. If that's not acceptable, add `Vkd` to the end for +3 bytes: [Try it online!](https://tio.run/##K/v/PzOgKDMntSQ1J9EmtTjZzjhRIbc0I1EhL1GhKjNFByxWpBdZkA9mZZunKRRxZZukKbhkm0S65yemZuaXgmWsivX19NVsnHWL7Az007lM3QuLKqx0tI2K9aOBikpj9cFSSkApo6xCE4eisOyU////65YBAA) ### Explanation ``` iPriletela<esc>3a muha na zid,<esc>r. ``` Insert `Priletela`; then append three copies of `muha na zid,` and replace the last comma with a period. ``` Ypo<esc> ``` Duplicate the line and insert a blank line below the second copy. ``` k7f r<cr>k4f D ``` Replace the seventh space on the second line with a newline. Go back up to the second line and delete from the fourth space to the end of the line. We now have the first verse of the song. ``` k4YGoaeiou<esc> ``` Go up to the first line and yank all four lines. Then insert `aeiou` after the last line. ``` :s/./&<C-r>0/g ``` Replace each letter of `aeiou` with itself followed by the yanked lyrics. ``` 5Gqr ``` Go to line 5 (the start of the second verse) and begin recording into macro `r`. ``` x ``` Delete the first character, which is the `a` prepended to the verse. ``` :,+2s/[aeiu]/<C-r>"/g ``` Within this line and the next two (i.e. this verse), replace any of `aeiu` with the character we just deleted. ``` 2jq ``` Go down two lines to the start of the next verse. Stop recording the macro. ``` 4@r ``` Run the macro four more times, converting the four remaining verses. [Answer] # PHP 8, ~~170~~ 166 bytes This is [the JavaScript solution of @jgosar](/a/216412/40534) rewritten in PHP and improved. ``` $a='aeiou';$x='muha na zid';$y="Priletela $x,";echo implode(" ",array_merge([$z="$y $x, $x. $y $x."],array_map(fn($e)=>preg_replace("/[$a]/",$e,$z),str_split($a)))); ``` The code is not wrapped on multiple lines for readability but because this way a real newline character embedded in a string uses only one byte vs. two bytes used by the escape sequence `\n`. [Try it online!](https://tio.run/##NYxRCoMwEET/c4oQFowQ6gFs2iv0X0SWujWBqEtUMF4@TT86MAw8HsOOc74/2bEAtBWSX4@qhdNW8@FQLigvPxaQrHpFH2ingBJOo1p6u1X6mcM6klZCKIMxYhpmihPpDi6rIP3U0puAJMqo/i8h68@igWr74EjTEIkDvstR0wH2jTJABq7abHscNg5@14B1SZvzFw) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 70 bytes ``` Pm, m, m.¶Pm,¶m.¶ P Priletela m muha na zid ~(K`vaeiou L$`. \T`vo`$& ``` [Try it online!](https://tio.run/##K0otycxLNPz/nysgV0cBhPQObQMyD20DMbgCuAKKMnNSS1JzEhW4crlySzMSFfISFaoyU7jqNLwTyhJTM/NLuXxUEvS4YkISyvITVNT@/wcA "Retina – Try It Online") Explanation: ``` Pm, m, m.¶Pm,¶m.¶ ``` Insert placeholders for the first verse. ``` P Priletela m muha na zid ``` Expand the placeholders. ``` ~(` ``` Compose and execute a Retina script. ``` K`vaeiou ``` Create a list of transliteration targets. ``` L$`. \T`vo`$& ``` Expand each target into a transliteration command that transliterates vowels into the given target and outputs the verse after the transliteration. The resulting script is as follows: ``` \T`vo`v \T`vo`a \T`vo`e \T`vo`i \T`vo`o \T`vo`u ``` Here the `v` represents the vowels `aeiou`. The `o` on its own usually means "insert the other set", however this has no effect on the transliteration as the vowels are already present. The exception is the `T`vo`o` command, where the presence of `o` on both sides causes it to be treated as a literal, although this does not affect the expansion either. [Answer] # [Lua](https://www.lua.org/), 150 bytes Just because Lua doesn't get enough love. ``` a='aeiou'for i=0,5 do print((('pm, m, m.\npm,\nm.\n'):gsub('p','Priletela '):gsub('m','muha na zid'):gsub('['..(i>0 and a or'_')..']',a:sub(i,i))))end ``` :gsub():gsub():gsub() :-) [Answer] # [Java (JDK)](http://jdk.java.net/), 161 bytes ``` v->{for(var s:"$0,a,e,i,o,u".split(","))System.out.print(s.format("%s%s, %2$s, %2$s.%n%1$s%2$s,%n%2$s.%n%n","Priletela ","muha na zid").replaceAll("[aeiu]",s));} ``` [Try it online!](https://tio.run/##LY5Ba8MwDIXv/RXCJBAP12w7Llth7Dw26LH0oLpO58yxgyUHtpLfnnmhF0nve9JDPU647c/fixvGmBj6onVm53WXg2EXg75rN8YjEbyjC3DdAIz55J0BYuTSpujOMBSv2XNy4XI4AqYLyXUV4C0GyoNNzx@n3hreQQcvsEzb3bWLqZkwAT2J6l6hssqpqLLQNHrHjVBCyv0PsR10zKzHEs4N6XI2YLFrqklB/Vjdqq5D/VDRCsp4I6HEfCbnLVuPUMSQvxACwq87C6mTHT0a@@p9Iw5oXT4KRVK289Ku33cajbEjNyF7L//ZvJmXPw "Java (JDK) – Try It Online") ## Credits * -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # PHP 7.4, 164 bytes This is the same as [my solution for PHP 8](/a/216420/40534) but it does not surround the value of `$a` (`aeiou`) in apostrophes or quotes and saves 2 bytes. This exploits the fact that before PHP 8, the undefined constants were reported as warning and converted to strings. This behaviour changed in PHP 8, they are now reported as errors and the code does not work any more. ``` $a=aeiou;$x='muha na zid';$y="Priletela $x,";echo implode(" ",array_merge([$z="$y $x, $x. $y $x."],array_map(fn($e)=>preg_replace("/[$a]/",$e,$z),str_split($a)))); ``` In order to hide the warnings, the option `-d error_reporting=0` needs to be added to the command line (or set in `php.ini`). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 76 bytes ``` Ac." zMzÊ(ºZ¾þXGÈ-gÚe¿P"\qJ", "K+\.b =s[GHJHJHKGH\,bHK)V=d"aeiou":G++\[d\]N ``` [Try it online!](https://tio.run/##K6gsyfj/3zFZT0mhyrfqcJfGoV1Rh/Yd3hfhfrhDN53j8KzUQ/sDlGIKvZR0FJS8tWP0krhsi6PdPbyA0NvdI0YnycNbM8w2RSkxNTO/VMnKXVs7JjolJtbv/38A "Pyth – Try It Online") --- Python 3.8 translation: ``` import re b = "\n" [G, H] = "Priletela qmuha na zid".split("q") J = ", " K = "." + b print(G := "".join([G,H,J,H,J,H,K,G,H,",",b,H,K])) for N in (d := "aeiou"): print(re.sub("[" + d + "]", N, G)) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 138 bytes ``` s="Priletela muha na zid, " v="aeiou_" n='\n' print(n.join([[s+s[10:]+(w:=s[10:-2]+n)+s+n+w,[s:=s.replace(y,x)for y in v]][0]for x in v])) ``` [Try it online!](https://tio.run/##dZFNasMwEEb3OsXgTWzkirTdlIDv0L1riminWEUeGVlKYl/elZwsasgsBvSG943@xjn0jl7fRr@uU1O8e2MxoNUwxF4DaVjMdw2FODeFRuPiZyGoOXzQQYzeUChJ/TpDZdtOcmqfj6dOlpdTsy2fXjpJlZwkyUvdTqmrPI5Wf2E519fqx3mYwRCcu649dhmvN6yqdWUOwoESjwNi5yRJWx10lvS9r/MgBhQTEDsnSbhtjTBgj0AIC@ZBDCgmIHbOdiETUsFgegNk7pdmQDEBsXOS5KwLqWBwvQNysLg8iAHFBMTOSVK0MaTKjx@BIizx9kEPQTEB8d/5Aw "Python 3.8 (pre-release) – Try It Online") Modified version of [answer by xnor](https://codegolf.stackexchange.com/a/216441/100510) using list comprehension. It is not shorter, but it has fewer lines, so I thought I'd post it. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 68 bytes ``` 1→a`10, 0, 0. 10, 0.`₀ «ƛ&…-∪⋎5wµ\Ė⌊ɾ≤«¡\x€Ŀ£¥kV⇩(←a›→a ¥nkV⇩←a iV)W ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=1%E2%86%92a%6010%2C%200%2C%200.%0A10%2C%0A0.%60%E2%82%80%0A%C2%AB%C6%9B%26%E2%80%A6-%E2%88%AA%E2%8B%8E5w%C2%B5%5C%C4%96%E2%8C%8A%C9%BE%E2%89%A4%C2%AB%C2%A1%5Cx%E2%82%AC%C4%BF%C2%A3%C2%A5kV%E2%87%A9%28%E2%86%90a%E2%80%BA%E2%86%92a%20%C2%A5nkV%E2%87%A9%E2%86%90a%20iV%29W&inputs=&header=&footer=) [Answer] # JavaScript, 137 bytes ``` o="";for(v of ["$&",..."aeiou"])for(c of`12, 2, 2. 12, 2. `)o+=+c?[,"Priletela ","muha na zid"][c].replace(/[aeiu]/g,v):c;console.log(o) ``` [Try it Online!](https://tio.run/##FYzLCoMwEEX3fkUYSjGYRtplRfoL3YeAYRxtSnQkPhb9@TTChXPgwP26w60Y/bLdZu4pJW4BmoFjeQgehIHLFZTWGhx53sHKM2FO3f2hxDldZCsyik5y1Vb4Mgre0QfaKDgBCqb948TsxM/3YA1aHWkJDqmsTX7dbT2qQz6xQZ5XDqQDjyXLlP4) ## Explanation: ``` o=""; // Define o for(v of ["$&",..."aeiou"]) // Repeat for each vowel + $& being the RegExp returned value. for(c of`12, 2, 2. // Numeric values will be replaced later on 12, 2. `) o+= // Add at the end of o... +c? // ...if c is numeric (NaN being falsey): [,"Priletela ", // replace it by the index of the array... "muha na zid"][c] .replace(/[aeiu]/g,v) // ...and replace every vowel by the current vovel (or $& which doesn't affect it) :c; // otherwise, add c console.log(o) // Finally, output o ``` ]
[Question] [ [Brun's constant](https://en.wikipedia.org/wiki/Brun%27s_theorem) is the value to which the sum of the reciprocals of [twin prime](https://en.wikipedia.org/wiki/Twin_prime) pairs (`1/p` and `1/(p+2)` where `p` and `p+2` are both prime) converges. It is approximately `1.902160583104`. Given a positive integer `N`, approximate Brun's constant by summing the reciprocals of the twin prime pairs where both primes in the pair are less than `N`, and output the approximation. ## Rules * `N` will be a positive integer within the representable range for your language. * The output must be as accurate as possible to the true value, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic. * Alternatively, an exact fraction may be output in any consistent, unambiguous format. * If a prime appears in multiple twin prime pairs (e.g. `5`, part of both `(3, 5)` and `(5, 7)`), its reciprocal contributes to the sum each time. ## Test Cases ``` 2 -> 0 6 -> 0.5333333333333333 10 -> 0.8761904761904762 13 -> 0.8761904761904762 100 -> 1.3309903657190867 620 -> 1.4999706034568274 100000 -> 1.67279958482774 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ ~~77~~ ~~75~~ ~~70~~ ~~68~~ 62 bytes ``` f=lambda n,k=3,m=1,j=0:k<n and-m%k*j*2/k+f(n,k+2,m*k**4,m%k/k) ``` *Thanks to @xnor for golfing off ~~2~~ 4 bytes and paving the way for 4 more!* [Try it online!](https://tio.run/nexus/python3#FYxBCsIwFETXeorZhDbpr00TyaIY7xIpgTbmK0XPH7@LYQbe8FqOz1QfawJTiZ5qnGmPdik3RuJ1rKqY3bipDLmXx@CommLMlQRMRbf8OsDYGI4QCLOV@H/LCM4u59P72PjTd8p/Md6hLnPIHRTEBlFqrdsP "Python 3 – TIO Nexus") ### Background Recall that [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem "Wilson's theorem - Wikipedia") states that for all integers **k > 1**, ![](https://i.stack.imgur.com/bmCcO.png) where **a ≡ b (mod d)** means that **a - b** is evenly divisible by **d**, i.e., **a** and **b** have the same residue when divided by **d**. In [Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials](https://arxiv.org/abs/1302.3676 "[1302.3676] Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials"), the authors prove generalizations for double factorials, on which this answer builds. The [double factorial](https://en.wikipedia.org/wiki/Double_factorial "Double factorial - Wikipedia") of an integer **k ≥ 0** is defined by ![](https://i.stack.imgur.com/iCGD4.png) Theorem 4 of the aforementioned paper states the following. ![](https://i.stack.imgur.com/rhz9x.png) Elevating both sides of the congruences to the fourth power, we deduce that ![](https://i.stack.imgur.com/NbNii.png) for all odd primes **p**. Since **1!! = 1**, the equivalence holds also for **p = 2**. Now, doing the same to Wilson's theorem reveals that ![](https://i.stack.imgur.com/JPDKa.png) Since ![](https://i.stack.imgur.com/Zt2g7.png) it follows that ![](https://i.stack.imgur.com/MkN6e.png) whenever **p** is prime. Now, let **k** be an odd, positive, composite integer. By definition, there exist integers **a, b > 1** such that **k = ab**. Since **k** is odd, so are **a** and **b**. Thus, both occur in the sequence **1, 3, …, k - 2** and ![](https://i.stack.imgur.com/7nyHV.png) where **|** indicates divisibility. Summing up, for all odd integers **k > 1** ![](https://i.stack.imgur.com/V4Wzw.png) where **p(k) = 1** if **k** is prime and **p(k) = 0** if **k** is composite. ### How it works When the function **f** is called with a single argument, **k**, **m**, and **j** are initialized as **3**, **1**, and **0**. Note that **((k - 2)!!)4 = 1!!4 = 1 = m**. In fact, the equality **m = ((k - 2)!!)4** will hold at all times. **j** is a *float* and will always be equal to **((k - 4)!!)4 % (k - 2) / (k - 2)**. While \$k < n\$, the right argument of `and` will get evaluated. Since \$j = \frac{\mod(\left(\left(k - 4\right)!!\right)^4 , k - 2)}{k - 2}\$, as proven in the first paragraph, \$j = \frac{1}{k - 2}\$ if \$k - 2\$ is prime and \$j = 0\$ if not. Likewise, since \$\mod(m,k) = \left(\left(k - 2\right)!!\right)^4\$ equals \$1\$ if \$k\$ is prime and \$0\$ if not, \$\mod(-m,k) = k - 1\$ if \$k\$ is prime and \$\mod(-m , k) = 0\$ if not. Therefore, `-m%k*j*2/k` evaluates to \$\frac{2\left(k - 1\right)}{k\left(k - 2\right)} = \frac{\left(k - 2\right) + k}{k(k - 2)} = \frac{1}{k} + \frac{1}{k - 2}\$ if the pair \$\left(k - 2, k\right)\$ consists of twin primes and to \$0\$ if not. After computing the above, we add the result to the return value of the recursive call `f(n,k+2,m*k**4,m%k/k)`. \$k\$ gets incremented by \$2\$ so it only takes odd values‡†, we multiply \$m\$ by \$k^4\$ since \$mk^4 = \left(\left(k - 2\right)!!\right)^4k^4 = \left(k!!\right)^4\$, and pass the current value of \$\frac{\mod(m,k)}{k}\$ – which equals \$\frac{1}{k}\$ if the "old" \$k\$ is a prime and \$0\$ if not – as parameter \$j\$ to the function call. Finally, once \$k\$ is equal to or greater than \$n\$, \$f\$ will return *False* and the recursion stops. The return value of \$f(n)\$ will be the sum of all \$\frac{1}{k} + \frac{1}{k - 2}\$ such \$\left(k - 2, k\right)\$ is a twin prime pair and \$k < n\$, as desired. --- ‡ The results from the *Background* paragraph hold only for odd integers. Since even integers cannot be twin primes, we can skip them safely. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` ’ÆRµ_2fµ+2;µİS ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYebhtqBDW@ON0g5t1TayPrT1yIbg/0f3HG5/1LTG/f9/Ix0FMx0FQwMgNgbRQIaZkQEA "Jelly – TIO Nexus") ### How it works ``` ’ÆRµ_2fµ+2;µİS Main link. Argument: n ’ Decrement; yield n-1. ÆR Prime range; yield all primes in [1, ..., n-1]. µ New chain. Argument: r (prime range) _2 Subtract 2 from all primes. f Filter; keep all p-2 that appear in r. µ New chain. Argument: t (filtered range) +2 Add 2 to all primes in s. ; Concatenate with s. µ New chain. Argument: t (twin primes) İ Take the inverses. S Sum. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes (with a little help from @Dennis) ``` ’ÆRṡ2_/2+$$ÐḟFİS ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYebhtqCHOxcaeR7pPrT08IQ0I7cjG4L/RxvpmOkYGugYGgNJAx0zI4PYw@2Pmtb8BwA "Jelly – TIO Nexus") While trying to improve my previous answer, I thought up a totally different algorithm, and it comes in somewhat shorter. I'm using a different post for it, as is the standard here for an answer that uses a different technique. Dennis suggesting replacing `_/2+$$Ðḟ` with `Iċ¥Ðf2`; I'd completely forgotten about the possibility of a dyadic filter. As such, this algorithm now ties with the one that Dennis' answer used. ## Explanation ``` ’ÆRṡ2Iċ¥Ðf2FİS ’ Decrement. ÆR Primes from 2 to the argument inclusive (i.e. 2 to the original input exclusive). ṡ2 Take overlapping slices of size 2. Ðf Keep only elements where the following is true: ¥ {the second parse of, which parses like this} Iċ 2 the differences (I) contain (ċ) 2 F Flatten. İ Take 1/x {for every list element}. S Sum. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 [bytes](https://github.com/JCumin/Brachylog/wiki/Code-page) ``` {>I-₂:I{ṗ/₁}ᵐ}ᶠc+ ``` [Try it online!](https://tio.run/nexus/brachylog2#ASMA3P//ez5JLeKCgjpJe@G5ly/igoF94bWQfeG2oGMr//82MjD/Wg "Brachylog – TIO Nexus") This is the brand new version of Brachylog, with a shiny code page! ### Explanation ``` { }ᶠ Find all valid outputs of the predicate in brackets c+ Output is the sum of that list after flattening it >I Input > I -₂:I The list [I-2, I] { }ᵐ Map: ṗ/₁ Must be prime and the output is its inverse ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` liqZqtd2=)t2+h/s ``` [Try it online!](https://tio.run/nexus/matl#@5@TGVVYkmJkq1lipJ2hX/z/v5mRAQA "MATL – TIO Nexus") Consider input `13` as an example. ``` l % Push 1 % STACK: 1 i % Input N % STACK: 1, 13 q % Subtract 1 % STACK: 1, 12 Zq % Primes up to that % STACK: 1, [2 3 5 7 11] t % Duplicate % STACK: 1, [2 3 5 7 11], [2 3 5 7 11] d % Consecutive differences % STACK: 1, [2 3 5 7 11], [1 2 2 4] 2= % Compare with 2, element-wise % STACK: 1, [2 3 5 7 11], [0 1 1 0] ) % Use as logical index to select elements from array % STACK: 1, [3 5] t % Duplicate % STACK: 1, [3 5], [3 5] 2+ % Add 2, element-wise % STACK: 1, [3 5], [5 7] h % Concatenate horizontally % STACK: 1, [3 5 5 7] / % Divide, element-wise % STACK: [0.3333 0.2 0.2 0.1429] s % Sum of array. Implicitly display % STACK: 0.8762 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 14 bytes (-5 @Emigna) ``` <LDpÏÍDpÏDÌ«zO ``` [Try it online!](https://tio.run/nexus/05ab1e#@2/j41JwuN/l0FKjwOJDK4qBTCPtQ6ur/P//NzQGAA "05AB1E – TIO Nexus") [Answer] # Mathematica, ~~48~~ 47 bytes *Thanks to JungHwan Min for saving 1 byte!* ``` If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}& ``` Unnamed function taking a positive integer as input and returning an exact fraction; for example, `If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&[10]` returns `92/105`. `If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]` tests whether both `i` and `i-2` are prime, returning the sum of their reciprocals if so and `0` if not. `~Sum~{i,#-1}&` then returns the sum of those contributions for all values of `i` less than the input. Previous submission: ``` If[And@@PrimeQ@{i,g=i-2},1/i+1/g,0]~Sum~{i,#-1}& ``` [Answer] # Octave, 45 bytes ``` @(n)sum(all(isprime(m=[h=3:n-1;h-2]))*m'.^-1) ``` Explanation: ``` m=[h=3:n-1;h-2] generate an concatenate two ranges 3:n-1 and 1:n-3 rec=m'.^-1 transpose and reciprocal idx=all(isprime(m)) create a logical [0 1 ..] array if both ranges are prime set 1 else set 0 sum1 = idx * rec matrix multiplication(extrat elements with logical index and sum along the first dimension) sum(sum1) sum along the second dimension ``` [Try It Online!](https://tio.run/#blfF2) [Answer] ## JavaScript (ES6), ~~67~~ 66 bytes *Saved 1 byte thanks to @Arnauld* ``` f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n) ``` Outputs `false` for test case `2`, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/9067/12012). ### Test snippet ``` f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n) g=n=>console.log("Input:",n,"Output:",f(n)) g(2) g(6) g(10) g(13) g(100) g(620) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ’ÆRḊµ_Æp=2Tịµ_2;µİS ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYebhtqCHO7oObY0/3FZgaxTycHc3kG1kfWjrkQ3B/6ONdMx0DA10DI2BpIGOmZFB7OH2R01r/gMA "Jelly – TIO Nexus") I have a feeling that this is improvable, but I can't immediately see how. ## Explanation ``` ’ÆRḊµ_Æp=2Tịµ_2;µİS ÆR Generate all primes from 2 to n inclusive ’ Subtract 1 Ḋ Remove first element ’ÆRḊ Generate all primes from 3 to n-1 exclusive _Æp Subtract the previous prime (i.e. calculate the prime gap) =2 Compare to 2 Tị Take elements of the input where the comparison is true _Æp=2Tị Filter a list of primes to the latter halves of prime pairs _2 Subtract 2 ; Append _2; Append the list to the list with 2 subtracted from it İ Take reciprocals S Sum İS Take the sum of the reciprocals ``` The `µ` connect all these portions together pipeline-style, with each taking the output of the one before as its input. [Answer] # Pyth - ~~22~~ ~~21~~ 17 bytes I think that refactoring will help. ``` scL1sf.APM_MTm,tt ``` [Test Suite](http://pyth.herokuapp.com/?code=scL1sf.APM_MTm%2Ctt&test_suite=1&test_suite_input=2%0A6%0A10%0A13%0A100%0A620&debug=0). [Answer] # [Julia 0.4](http://julialang.org/), ~~48~~ 46 bytes ``` !n=sum(1./[(p=n-1|>primes)∩(p-2);p∩(p+2)]) ``` [Try it online!](https://tio.run/nexus/julia#@6@YZ1tcmqthqKcfrVFgm6drWGNXUJSZm1qs@ahjpUaBrpGmdQGYpW2kGav5Py2/SCFPITNPQcNIx0zH0EDH0BhIGuiYGRlocnE6ALXmlaRpKKkalyro2imo6hmapcXkKenk6SjmaXKl5qX8BwA "Julia 0.4 – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), ~~59~~ 51 bytes ~~`{sum 1 «/»grep((*-(2&0)).is-prime,^$_).flatmap:{$_-2,$_}}`~~ ``` {sum 1 «/»grep(*.all.is-prime,(-2..*Z ^$_)).flat} ``` `-2..* Z ^$_` zips the infinite list `-2, -1, 0, 1, ...` with the list `0, 1, ... $_-1` (`$_` being the argument to the function), producing the list `(-2, 0), (-1, 1), (0, 2), ..., ($_-3, $_-1)`. (Obviously none of these numbers less than 3 can be in a prime pair, but `3..* Z 5..^$_` is a few bytes longer, and none of the extra numbers are prime.) The `grep` selects only those pairs where all (that is, both) numbers are prime, and the `flat` flattens them into a plain list of numbers. `«/»` is the division hyperoperator; with the list on the right and `1` on the left, it turns the list of prime pairs into their reciprocals, which is then summed by `sum`. [Answer] # Clojure, 147 bytes ``` (fn[n](let[p #(if(> % 2)(<(.indexOf(for[a(range 2 %)](mod % a))0)0))](reduce +(for[a(range 2 n)](if(and(p a)(p(- a 2)))(+(/ 1 a)(/ 1(- a 2)))0))))) ``` And Clojure comes dead last, as usual. Ungolfed: ``` ; Returns the primality of a number. (defn prime? [n] (if (> n 2) (< (.indexOf (for [a (range 2 n)] (mod n a)) 0) 0))) ; Calculates the actual Brun's Constant. ' (Stupid highlighter) (defn brunsconst [n] ; Adds all of the entries together (reduce + ; For a in range(2, n): (for [a (range 2 n)] (let [b (- a 2)] ; If both a and a-2 are prime: (if (and (prime? a) (prime? b)) ; Place (1/a + 1/a-2) on the array, else 0 (+ (/ 1 a) (/ 1 b)) 0))))) ``` [Answer] # APL NARS, 216 bytes, 108 chars ``` r←z n;h;i;k;v i←0⋄n-←1⋄h←1+⍳n-1⋄→B A:k←i⊃h⋄h←k∪(0≠k∣h)/h B:→A×⍳(⍴h)≥i+←1 r←+/÷(v-2),v←(h=1⌽h+2)/h ``` this would use the "Crivello di Eratostene" for find the sublist in 1..arg of request primes. Test: ``` z¨2 6 10 13 100 620 0 0.5333333333 0.8761904762 0.8761904762 1.330990366 1.499970603 z 100000 1.672799585 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ṁ\Σfo=2F-Ẋefṗŀ ``` [Try it online!](https://tio.run/##ASIA3f9odXNr///huYFczqNmbz0yRi3huoplZuG5l8WA////MTAw "Husk – Try It Online") ### Explanation ``` ṁ\Σfo=2F-Ẋefṗŀ ŀ lowered range, 0..n-1 fṗ filter primes Ẋe get each consecutive pair f F- filter where difference o=2 equals 2 Σ concat, list of pairs to flattened list ṁ\ map 1/n and then sum ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes ``` n->forprime(p=s=0.,n,isprime(q=p-2)&&s+=1/p+1/q);s ``` [Try it online!](https://tio.run/##JYrBCsMwDEN/xfRQYpq0SQa9FPdHxg49LCOweW6yy74@czuB0JOQbCW7h7QE1Nit6V2k5NfdCFXyo2Wb63/YSVzEvq8DhUmGMO241LaJPL@Gwa2gN/4odkfpIBlGtHCNFmYLwasvRyrM0Z@kumH7AQ "Pari/GP – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `sḋ`, ~~13~~ 12 bytes ``` ~æ2l'÷ε2=;fĖ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyJz4biLIiwiIiwifsOmMmwnw7fOtTI9O2bEliIsIiIsIjEwMCJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJz4biLQSIsIiIsIn7DpjJsJ8O3zrUyPTtmxJYiLCIiLCIyXG42XG4xMFxuMTNcbjEwMFxuNjIwIl0=). Explanation: ``` ~ # Filter the range 0 to n-1 by: æ # Is prime 2l # Get the overlapping groups of 2 ' ; # Filter those by: ÷ε # Absolute difference of the list 2= # Equals 2 f # Flatten to make one list Ė # Take the reciprocal of each # Sum with the s flag # Convert to decimal format with the ḋ flag ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~86~~ 85 bytes ``` for((k=4;k<$1;k++,j=k-2)){ [ `factor $k $j|wc -w` = 4 ]&&x=$x+1/$k+1/$j;};bc -l<<<0$x ``` [Try it online!](https://tio.run/nexus/bash#@5@WX6ShkW1rYp1to2Jona2trZNlm61rpKlZrRCtkJCWmFySX6Sgkq2gklVTnqygW56gYKtgohCrplZhq1Khbaivkg0isqxrrZOA0jk2NjYGKhX///83AwA "Bash – TIO Nexus") Constructs a large arithmetic expression and then feeds it to `bc -l` to evaluate it. *Edit: Mistakenly left in a $(...) pair from an old version with nested command substitution; changed to backticks to save a byte.* ]
[Question] [ **Input:** * An array containing three integers: `0`, `1` and `2` in any order (i.e. `[2, 0, 1]`) * And a string of length >= 2 only containing alphabetic letters (both lower- and uppercase) and digits (i.e. `a1B2c3`) **Output:** Based on the array we sort and output the string. How does this work? * The array indicates the order precedence of `a-z`, `A-Z` and `0-9`, the first being `0`; second being `1`; and third being `2`. * The individual characters of the string can then be ordered based on that. **Example:** * Array: `[2, 0, 1]` * String: `a1B2c3` Based on the array, we know our order precedence is `0-9a-zA-Z`. Based on that, we can convert and output the string: `123acB`. **Challenge rules:** * For the array you can choose to use 0-indexed or 1-indexed input, so `[3, 1, 2]` is also a valid input if you prefer to use 1-indexed arrays. * The string (both input and output) only contains valid characters: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`. * If your language doesn't support arrays (or if you choose to), you are free to use strings instead of arrays for the first parameter (i.e. `012`, `[0,1,2]`, etc.). **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. * Also, please add an explanation if necessary. **Test cases:** ``` [2, 0, 1] & a1B2c3 -> 123acB [2, 1, 0] & aAaA909UuHWw9gh2 -> 02999AAHUWaaghuw [2, 1, 0] & 6Bx43 -> 346Bx [1, 0, 2] & jfjf33g -> ffgjj33 [0, 2, 1] & AbC13 -> b13AC [1, 2, 0] & Qfl0l -> Q0fll [0, 1, 2] & 9870abcABC -> abcABC0789 [0, 2, 1] & test123 -> estt123 [2, 0, 1] & WHAT -> AHTW [2, 0, 1] & WhAt -> htAW [1, 0, 2] & 102BACbac -> ABCabc012 ``` [Answer] # Python 2, ~~67~~ 66 bytes ``` lambda s,k:`sorted(s,key=lambda c:`k.index(3-ord(c)/32)`+c)`[2::5] ``` Test it on [Ideone](http://ideone.com/TsKRBZ). [Answer] ## JavaScript (ES6), 87 bytes ``` (a,s)=>a.map(n=>[...s].sort().join``.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join`` ``` If the input array gave the order, rather than the precedence, of the three ranges (this only makes a difference for `[1, 2, 0]` and `[2, 1, 0]` whose effects are swapped) then this would have worked for 80 bytes: ``` (a,s,o=c=>a[(c<'a')+(c<'A')])=>[...s].sort((a,b)=>o(a)-o(b)||(a>b)-(a<b)).join`` ``` I misread the question and still got 7 upvotes with this. Feel free to remove your upvotes and give them to @CharlieWynn instead, who came up with the best correction to my approach. ``` (a,s)=>a.map(n=>s.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join`` ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 12 bytes Code: ``` v²žK26ôyèÃ{? ``` Explanation: ``` v # For each in the input array. žK # Push a-zA-Z0-9. 26ô # Split into pieces of 26. yè # Get the element-th element of the array. ² à # Keep the characters of that element from the second input. {? # Sort pop and print without a newline. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dsKyxb5LMjbDtHnDqMODez8&input=WzIsIDEsIDBdCmFBYUE5MDlVdUhXdzlnaDI). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2_ịØWs26¤Ff@€ ``` [Try it online!](http://jelly.tryitonline.net/#code=Ml_hu4vDmFdzMjbCpEZmQOKCrA&input=&args=WzIsIDAsIDFd+ImExQjJjMyI) or [verify all test cases](http://jelly.tryitonline.net/#code=Ml_hu4vDmFdzMjbCpEZmQOKCrArDpyJq4oG3&input=&args=WzIsIDAsIDFdLCBbMiwgMSwgMF0sIFsyLCAxLCAwXSwgWzEsIDAsIDJdLCBbMCwgMiwgMV0sIFsxLCAyLCAwXSwgWzAsIDEsIDJdLCBbMCwgMiwgMV0sIFsyLCAwLCAxXSwgWzIsIDAsIDFdLCBbMSwgMCwgMl0+ImExQjJjMyIsICJhQWFBOTA5VXVIV3c5Z2gyIiwgIjZCeDQzIiwgImpmamYzM2ciLCAiQWJDMTMiLCAiUWZsMGwiLCAiOTg3MGFiY0FCQyIsICJ0ZXN0MTIzIiwgIldIQVQiLCAiV2hBdCIsICIxMDJCQUNiYWMi). ### How it works ``` 2_ịØWs26¤Ff@€ Main link. Arguments: k (permutation of [0, 1, 2]), s (string) 2_ Subtract the integers in k from 2, mapping [0, 1, 2] -> [2, 1, 0]. ¤ Combine the three links to the left into a niladic chain. ØW Yield the string following string. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' s26 Split it into chunks of 26 chars, i.e., ['A...Z', 'a...z', '0...9']. ị Retrieve the chunks from the right result at the indices of the left result. The indices of the chunks are modular and 1-based; 1 retrieves 'A...Z', 2 retrieves 'a...z', and 3 retrieves '0...9'. F Flatten the resulting array of strings. f@€ Filter (swapped, each); for each character in the constructed string, select all occurrences of that character from s. ``` [Answer] ## Pyth, ~~17~~ ~~16~~ 15 bytes ``` s@RSz@L[GrG1`UT ``` [Test suite.](https://pyth.herokuapp.com/?code=s%40RSz%40L%5BGrG1%60UT&test_suite=1&test_suite_input=%5B2%2C+0%2C+1%5D%0Aa1B2c3%0A%5B2%2C+1%2C+0%5D%0AaAaA909UuHWw9gh2%0A%5B2%2C+1%2C+0%5D%0A6Bx43%0A%5B1%2C+0%2C+2%5D%0Ajfjf33g%0A%5B0%2C+2%2C+1%5D%0AAbC13%0A%5B1%2C+2%2C+0%5D%0AQfl0l%0A%5B0%2C+1%2C+2%5D%0A9870abcABC%0A%5B0%2C+2%2C+1%5D%0Atest123%0A%5B2%2C+0%2C+1%5D%0AWHAT%0A%5B2%2C+0%2C+1%5D%0AWhAt%0A%5B1%2C+0%2C+2%5D%0A102BACbac&debug=0&input_size=2) ``` [ array literal containing... G the alphabet (lowercase) rG1 the alphabet, converted to uppercase `UT inspect-range-10, generating the range [0,10) and stringifying it, resulting in a string that contains no letters and all numbers (so equivalent to '0123456789' for filtering) this creates ['ab...z', 'AB...Z', '01...9'] @L map over first (implicit) input (the ordering array) and take the nth element in this array for each item this gives us ['01...9', 'ab...z', 'AB...Z'] Sz take another line of input as a string and sort it, and then... @R map over intersection: filter the line of input over presence in each element in the new array this results in ['123', 'ac', 'B'] s concatenate all and implicitly output ``` Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for a byte and [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube) for another! [Answer] # Javascript es6 77 bytes ``` (a,s)=>a.map(o=>s.match([/[a-z]?/g,/[A-Z]?/g,/\d?/g][o]).sort().join``).join`` ``` --- ``` //test f=(a,s)=>a.map(o=>(s.match([/[a-z]/g,/[A-Z]/g,/\d/g][o])||[]).sort().join``).join`` f([2, 0, 1], "a1B2c3") == "123acB" && f([2, 1, 0], "aAaA909UuHWw9gh2") == "02999AAHUWaaghuw" && f([2, 1, 0], "6Bx43") == "346Bx" && f([1, 0, 2], "jfjf33g") == "ffgjj33" && f([0, 2, 1], "AbC13") == "b13AC" && f([1, 2, 0], "Qfl0l") == "Q0fll" && f([0, 1, 2], "9870abcABC") == "abcABC0789" && f([0, 2, 1], "test123") == "estt123" && f([2, 0, 1], "WHAT") == "AHTW" && f([2, 0, 1], "WhAt") == "htAW" && f([1, 0, 2], "102BACbac") == "ABCabc012" ``` [Answer] # TSQL, ~~199~~ 191 bytes **Golfed:** ``` DECLARE @i varchar(99)='abA7B34',@s char(3)='213' ,@ varchar(99)=''SELECT @+=n FROM(SELECT top 99n FROM(SELECT top 99substring(@i,row_number()over(order by 1/0),1)n FROM sys.messages)c ORDER BY CHARINDEX(CHAR(ascii(n)/32+48),@s),n)d SELECT @ ``` **Ungolfed:** ``` DECLARE @i varchar(99)='abA7B34' -- 1 numbers, 2 upper case, 3 lower case DECLARE @s char(3)='213' ,@ varchar(99)='' SELECT @+=n FROM ( SELECT top 99 n FROM ( SELECT top 99substring(@i, row_number()over(order by 1/0), 1)n FROM sys.messages )c ORDER BY CHARINDEX(CHAR(ascii(n)/32+48),@s),n )d SELECT @ ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/511595/post-determined-array-sorting)** [Answer] # [APLX](http://www.dyalog.com/aplx.htm), 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` s[(∊(⎕a⎕A⎕D)[a])⍋s] ``` `⎕a⎕A⎕D` lower upper digits `(`…`)[a]` reorder according to array *a* `∊` flatten `(`…`)⍋s` according to that "alphabet", give the indices that would sort string *s* `s[`…`]` use that to reorder *s* [Answer] # Python 2, 121 Bytes ``` lambda a,s:"".join(sum([[sorted(filter(eval(u),s))for u in["str.islower","str.isupper","str.isdigit"]][i]for i in a],[])) ``` [Answer] # Clojure, 74 bytes ``` #(apply str(mapcat sort(for[i %](re-seq([#"[a-z]"#"[A-Z]"#"[0-9]"]i)%2)))) ``` For each value in first list, gets appropriate regex and apply it to the input string. The result is a list of lists of symbols which match the regex. Then sort each one and concatenates the result into one list and transform it to string. You can see it online here: <https://ideone.com/dqAkxg> [Answer] ## [Retina](https://github.com/m-ender/retina), ~~43~~ 39 bytes Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant. ``` 2=`. !$&" T04`¶d`#^@% O`\W?. O`.\w+ \W ``` Input is expected to be the sort order as a zero-based list without delimiters on the first line, and the string to be sorted on the second line, e.g. ``` 120 fOo42BaR ``` [Try it online!](http://retina.tryitonline.net/#code=Mj1gLgohJCYiClQwNGDCtmRgI15AJQpPYFxXPy4KT2AuXHcrClxXCg&input=MTIwCmZPbzQyQmFS) ### Explanation I will use the above input example to walk you through the code: ``` 120 fOo42BaR ``` **Stage 1: Substitution** ``` 2=`. !$&" ``` The regex itself is just `.` (matches any non-linefeed character), which is surrounded with `!..."`. However, the `2=` is a *limit* telling Retina to apply the substitution only to the second match of the regex. So we get this: ``` 1!2"0 fOo42BaR ``` **Stage 2: Transliteration** ``` T04`¶d`#^@% ``` A transliteration stage simply does a character-by-character substitution. The `¶` represents a linefeed and `d` expands to `0123456789` (although we can ignore all digits after `2`). That means, this transliteration corresponds to the following mapping: ``` ¶012 #^@% ``` The `04` at the front are two limits, which together indicate that only the first four characters from this set should be transliterated. That happens to be the digits on the first line, as well as the linefeed separating the two lines, so we get this: ``` @!%"^#fOo42BaR ``` At the front of the string we've now got three pairs of these characters: ``` @! %" ^# ``` Note that the second characters of the pairs are simply in their normal ASCII order (and will always be the same). We'll use these later to sort the groups of characters in the main input into the required order. The first characters are bit more interesting: their significance is that `%` comes before digits in the ASCII table, `@` comes before upper case letters (but after digits), and `^` comes before lower case letters (but after upper case letters). This will help us group the position markers (i.e. the second character in each pair) with the right set of characters. **Stage 3: Sort** ``` O`\W?. ``` This is a simple sort stage. It matches two characters if the first one isn't a word character (thereby matching all three pairs I just talked about) or a single character otherwise (matching each character of the main input individually), and sorts those strings. This has two purposes: it brings the characters *within* each group in the correct order (and since sorting is stable, this order won't be messed up in the next stage), and it due to the `%@^` markers, it inserts the pairs in the right positions: ``` %"24@!BOR^#afo ``` **Stage 4: Sort** ``` O`.\w+ ``` This stage sorts all matches of the `.\w+` regex which, due to greediness, matches one position marker (i.e. one of `!"#`) together with all the word characters after it. That is, it sorts these three strings, whose order is determined solely by the marker character: "24 !BOR #afo While this shuffles around those markers (while leaving the other three markers in place), most importantly it brings the digits and letters in the correct order: ``` %!BOR@"24^#afo ``` **Stage 5: Substitution** ``` \W ``` All that's left is a little clean-up, where we remove all the markers by matching them and replacing them with nothing. [Answer] # Ruby, 56 bytes Ported from @Dennis answer. ``` ->a,s{s.chars.sort_by{|c|a.index(3-c.ord/32).to_s+c}*''} ``` An alternate 58 bytes solution that I like better, inspired by @Neil and modified slightly from his answer. ``` ->a,s{a.map{|i|s.scan([/[a-z]/,/[A-Z]/,/\d/][i]).sort}*''} ``` [Try either version online!](https://repl.it/Cbi9) (commented-out version is the alternate solution) [Answer] # JavaScript (ES6), 65 Note: 'natural' ASCII order is 0-9, A-Z, a-z, that is just the opposite of the OP 0,1,2. So * order the string adding invalid chars to separate runs * split it in 3 segmenents - invalid chars mark each * get segments one by one in the requested order * reassemble ``` s=>w=>w.map(w=>[...'^@'+s].sort().join``.split(/\W/)[2-w]).join`` ``` ``` F=s=>w=>w.map(w=>[...'^@'+s].sort().join``.split(/\W/)[2-w]).join`` ;[['201','a1B2c3','123acB'] ,['210','aAaA909UuHWw9gh2','02999AAHUWaaghuw'] ,['210','6Bx43','346Bx'] ,['102','jfjf33g','ffgjj33'] ,['021','AbC13','b13AC'] ,['120','Qfl0l','Q0fll'] ,['012','9870abcABC','abcABC0789'] ,['021','test123','estt123'] ,['201','WHAT','AHTW'] ,['201','WhAt','htAW'] ,['102','102BACbac','ABCabc012']] .forEach(t=>{ var w=t[0],s=t[1],k=t[2], r=F(s)([...w]) console.log(w,s,r,(r==k?'OK':'KO (expected '+k+')')) }) ``` [Answer] ## Haskell, ~~62~~ 63 bytes ``` a#b=[c|i<-b,c<-[' '..],d<-a,d==c,div(fromEnum c)16==[6,4,3]!!i] ``` Usage example: `"cD12ab" # [2,0,1]` -> `"12abcD"`. How it works: ``` i<-b -- loop i through the input array [c| c<-[' '..]] -- loop through all chars c d<-a -- loop through all chars d in the input string d==c -- and keep those that are in the input string div(fromEnum c)16==[6,4,3]!!i -- and where the the ascii value divided by -- 16 equals the number from [6,4,3] indexed -- by the current i ``` Edit: @Christian Sievers found a bug. Thanks! Fixed for 1 additional byte. [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┐°!'àÉgYg8∟╗`╖ë ``` [Run and debug it online](http://stax.tomtheisen.com/#c=%E2%94%90%C2%B0%21%27%C3%A0%C3%89gYg8%E2%88%9F%E2%95%97%60%E2%95%96%C3%AB&i=%5B%22a1B2c3%22%2C%5B2%2C0%2C1%5D%5D&a=1) This 15 byte submission is [packed](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) into a variant of the CP437 character set. The corresponding ascii representation takes 18 bytes: ``` EVlVd+26/s@:fs{[Io ``` Pretty sure it can be further trimmed down though. ``` E Put the two inputs on main stack Vl "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" Vd "0123456789" + Concatenate 26/ Partition to blocks of size 26 (array `a`) s@ Index array `a` with the input index array :fs Flatten to get a string `s` {[Io Order the input string Using the char array `s` as the key Implicit output ``` `VlVd+` can also be `VLA|(`, which left rotates the `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` by ten elemenets. The whole code can also be `VlVd+26/,e@:f,{[Io`, which reads the input stack twice instead of reading them all at the beginning to the main stack, and uses a different (more traditional) input format, as shown in [this](http://stax.tomtheisen.com/#c=%E2%94%90%C2%B0%21%E2%86%90%E2%95%9B%E2%95%96%E2%98%BC01%E2%97%98%E2%95%AB%C2%BD%C2%A7%2A%E2%96%8C&i=%5B2%2C0%2C1%5D%0Aa1B2c3&a=1). [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 22 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` s[s⍋⍨∊(819⌶⎕A)⎕A⎕D[a]] ``` `(819⌶⎕A)` fold the uppercase alphabet to lowercase `(`…`)⎕A⎕D[a]` lower upper digits reordered according to array *a* `∊` flatten `s⍋⍨` for string *s*, get the indices that would sort *s* according to that "alphabet" `s[`…`]` use that to reorder *s* [Answer] ## PowerShell v2+, 107 bytes ``` param($n,[char[]]$s)-join(-join(($s=$s|sort)|?{$_-ge97}),-join($s|?{$_-in65..96}),-join($s|?{$_-lt58}))[$n] ``` I'm exploring algorithms using regex, but thus far they all seem longer. Takes input as explicit array `$n` (see examples below) and string `$s` which is immediately cast to a char-array. We're then constructing three elements of a new dynamic array, each of them encapsulated with a `-join`: - `(($s=$s|sort)|?{$_-ge97})` - `($s|?{$_-in65..96})` - `($s|?{$_-lt58})` The first we take `$s` and run it through `Sort-Object`. Thankfully, since we've already cast it as a char-array, it's case-sensitive sorting. That gets re-saved into `$s` and then piped to a `Where-Object` with a clause of greater than `97` (i.e., ASCII lowercase `a-z`). The second is for `A-Z` and the third for `0-9`. Thus we now have an array of strings, where each string is composed one of the three character types and is sorted. We slice that with `[$n]` and then `-join` the result together to form our final output string. That is left on the pipeline and printing is implicit. ## Test Cases ``` PS C:\Tools\Scripts\golfing> $test = (@(2,0,1),'a1B2c3'), (@(2,1,0),'aAaA909UuHWw9gh2'), (@(2,1,0),'6Bx43'), (@(1,0,2),'jfjf33g'), (@(0,2,1),'AbC13'), (@(1,2,0),'Qfl0l'), (@(0,1,2),'9870abcABC'), (@(0,2,1),'test123'), (@(2,0,1),'WHAT'), (@(2,0,1),'WhAt'), (@(1,0,2),'102BACbac') PS C:\Tools\Scripts\golfing> $test |%{"($($_[0]-join',')) & $($_[1])".PadRight(28)+" -> " + (.\post-determined-array-sorting.ps1 $_[0] $_[1])} (2,0,1) & a1B2c3 -> 123acB (2,1,0) & aAaA909UuHWw9gh2 -> 02999AAHUWaaghuw (2,1,0) & 6Bx43 -> 346Bx (1,0,2) & jfjf33g -> ffgjj33 (0,2,1) & AbC13 -> b13AC (1,2,0) & Qfl0l -> Q0fll (0,1,2) & 9870abcABC -> abcABC0789 (0,2,1) & test123 -> estt123 (2,0,1) & WHAT -> AHTW (2,0,1) & WhAt -> htAW (1,0,2) & 102BACbac -> ABCabc012 ``` [Answer] # 32-bit x86 machine code, 70 bytes In hex: ``` fc31c031c95189e3ac84c0740a34cf0404880c0341ebf189fe9160ac88c2c0e805d788c652ac88c2c0e805d788c658740e6639d076029241aa92aa4e4febdc85c96175d658c3 ``` This procedure expects character class sorting order to be a 3-char (0..2) NULL-terminated string in `ESI` and the string to sort in `EDI`. Sorting is done in-place using extremely sub-optimal (performance-wise) version of bubble sort. ``` 0: fc cld 1: 31 c0 xor eax, eax 3: 31 c9 xor ecx, ecx 5: 51 push ecx ;Allocate 4 bytes on the stack 6: 89 e3 mov ebx, esp ;char EBX[4] _loop0: ;Parsing class order string 8: ac lodsb 9: 84 c0 test al,al ;Break on NULL b: 74 0a jz _break0 d: 34 cf xor al, 0xCF ;AL=~atoi(AL) f: 04 04 add al, 4 ;'0'->3, '1'->2, '2'->1 11: 88 0c 03 mov [ebx+eax], cl ;EBX[AL]=CL 14: 41 inc ecx 15: eb f1 jmp _loop0 _break0: 17: 89 fe mov esi,edi 19: 91 xchg eax,ecx ;ECX=0 _bsort: 1a: 60 pusha _cx2b: 1b: ac lodsb ;Get the first char to compare 1c: 88 c2 mov dl,al ;Save to DL 1e: c0 e8 05 shr al,5 ;Char class: [0-9]->1, [A-Z]->2, [a-z]->3 21: d7 xlat ;AL=EBX[AL] - priority for the char class 22: 88 c6 mov dh,al ;... goes to DH 24: 52 push edx ;First "comparable char" in DX goes to the stack 25: ac lodsb ;Get the second char to compare 26: 88 c2 mov dl,al ;\ 28: c0 e8 05 shr al,5 ; > Same as the above 2b: d7 xlat ;/ 2c: 88 c6 mov dh, al ;Second "comparable char" in DX 2e: 58 pop eax ;The first one goes to AX 2f: 74 0e jz _endpass ;ZF is set by the last 'shr', and only on AL==0 31: 66 39 d0 cmp ax,dx ;Upper halves of 32-bit regs may contain trash 34: 76 02 jbe _sorted 36: 92 xchg eax,edx ;Now AX<=DX 37: 41 inc ecx ;Swap counter _sorted: 38: aa stosb ;Store AL in-place 39: 92 xchg eax,edx ;AL=DL 3a: aa stosb ;Store the second char 3b: 4e dec esi ;Move pointers... 3c: 4f dec edi ;...back one byte 3d: eb dc jmp _cx2b ;Repeat with the next two chars _endpass: 3f: 85 c9 test ecx,ecx ;Full pass completed, checking # of swaps made 41: 61 popa ;Restores ECX(0), ESI, EDI. Doesn't affect flags 42: 75 d6 jnz _bsort ;If there were changes, repeat _end: 44: 58 pop eax ;Deallocate EBX[] 45: c3 ret ``` [Answer] ## Emacs Lisp, 183 bytes ``` (lambda(s p)(let(l u n)(apply'concat(mapcar(lambda(l)(sort l'<))(dolist(e(string-to-list s)(mapcar(lambda(i)(nth i(list l u n)))p))(push e(cond((< ?` e)l)((< ?@ e)u)((< ?/ e)n)))))))) ``` Slightly shorter than Java... [Answer] **Clojure, 77 bytes** ``` #(apply str(mapcat sort(map(group-by(fn[v](condp <(int v)90 0,57 1,2))%2)%))) ``` Not quite as short as the `re-seq` based one, and I couldn't figure out how to express that "`(apply str(mapcat sort(map(...))))`" in less space. `group-by` creates a hash-map which can be used as a function, when queried with an ingeger between 0 and 2 it returns the corresponding group, this orders the three different classes of characters. This would be more compact than the `re-seq` solution if there were more character classes to handle as this only takes 5 extra characters / group like `57 1,` instead of 8 for expression like `#"[a-z]"`. [Answer] # Python 2, ~~140~~ ~~117~~ ~~101~~ ~~100~~ 99 bytes Everyone say, "Ewww!". At least it's readable... *cough not really cough* ``` lambda l,s:`sorted(s,key=lambda c:[[c<'a',c<'A'or'Z'<c,c>'9'][l[i]]for i in 0,1,2]+[ord(c)])`[2::5] ``` [**Try it online**](https://repl.it/Cb9d/5) [Answer] # [R](https://www.r-project.org/), 101 bytes ``` function(a,s,o=unlist(list(letters,LETTERS,0:9)[a]))cat(o[sort(match(strsplit(s,'')[[1]],o))],sep='') ``` Creates a vector with a-z, A-Z and 0-9 in given order and reorders characters of input string to match this ordering. [Try it online!](https://tio.run/##hZFPa4MwGMbv/RTCDiYshSSWtdnWQZSCh126WTw4D1GMVpwWE@m@vbPaljH7J4f3EJ7f8zwvb91K43XayqaM9bYqgUAKVcumLLZKg2EkWie1Qu8rz1t9fCL8zGAgQghjoUEVqKrW4FvoOANK12pXbDVQyDRhEJAwRBWEIVLJbtn9tBLEgCIDI4PAR4IMUxCbxpYJXw5e5ldpwgfj75u@dYNQS8T25Ah3GD7CXHCG2aZx/T1LM/rfpocxZYxx7m58IdKs2Y9tnuyf2Y0Kg40162Q9S/r@dGBzmUvLSq/SPStlmueW1dMH9Lw9jxxyNzkiFndOyfTcei0LXNxj11gWxSmXnFuzxRyLKOa2c9mgZwcBni/YuLhOlO6ucnvtTnMQTUZH913u3Wg@0Nz1/AtoxvVdNNPcH5@KYGpzJxLxFX5ItZ1ub0xo@ws "R – Try It Online") [Answer] # J, 40 bytes ``` ;@:{[:(<@/:~@}./.~2-64 96 I.3&u:)'aA0'&, ``` [Answer] # Java 8, ~~221~~ ~~212~~ ~~193~~ 156 bytes I should of course try to answer my own challenge as well. :) (And as usual in Java.) ``` a->i->{for(byte c[],j=0;j<3;System.out.print(new String(c)))java.util.Arrays.sort(c=i.replaceAll("[^a-z];[^A-Z];[^0-9]".split(";")[a[j++]],"").getBytes());} ``` -28 bytes saved thanks to *@cliffroot*. **Explanation:** [Try it here.](https://tio.run/##rZLNauMwFIX3eQrhlURjYTtDZ4yTgBwo3XQxtCUwxoVrVU7lUWRjyW3TkGfPKD/QjunKZCWB7vl0zuVU8Ap@3QhdPf/dcwXGoDuQejtCyFiwkqPKTdDOSkXLTnMra01vzpep1DbLx9@NLGpturVop/e2lXo1nyOOZnvw59Kfb8u6xcXGCsSdupoFSTWdJPcbY8Wa1p2ljZNYrMUbOqkxJ4R8fsLaFjaGmrq1mM8kbUWjgAumFPayJ/A/8iR7Yv6fwxH4ce5R0yhpsZd4JIOsurrK87HnEboSNnU2DCYk2e2TEXKpm65QLvU5/Gstn9HaLQSfnGQ5AnJYDkKcQtOozdHmcQ9bFI1RMEYh2hEKnIvGfQlhGvGJR5Kjpp9RaXx@@Z4WOuB/NAYsDuLH7nb5Fq9eoktxr9P3H8NMhsfI0VdYVVblZLIahDuwehtkxSIc7C3qBf1dqkANdRb2gsa/fgZQcJYuLpXVddGG0eC69Mu3vGUPF2O9MHuphoRBlLJFAfwE3I12@38) ``` a->i->{ // Method with integer-array and String parameters and no return-type for(byte c[], // Temp byte-array j=0;j<3; // Loop from 0 to 3 (exclusive) System.out.print(new String(c))) // After every iteration: print the byte-array as String java.util.Arrays.sort( // Sort the byte-array c= // After we've replaced the byte-array with i.replaceAll("[^a-z];[^A-Z];[^0-9]".split(";")[a[j++]],"").getBytes());} // all bytes of the uppercase letters, lowercase letters, or digits, // depending on the next number in the input-array ``` ]
[Question] [ Oh, No! the sentences are out of balance. Quick! balance them. --- A word is defined as follows: > > A sequence of letters [A-Za-z] separated by **any** non-letter character ([0-9] ~+- etc.) > > > A word is BaLanCeD if its capitalization is the same forwards as it is backwards. Given a sentence with words, balance each word by capitalizing a letter on the right-hand side for each uppercase letter on the left-hand side, and the other way around. Do not make uppercase letters lowercase. ## Rules * For each letter `n` chars from the beginning of a word, it and the letter `n` chars from the end of the word should both be made uppercase if either of them is upper case. * All input will be printable ASCII (codepoints 32 to 126 `~`). **No need to balance if:** * The capital is in the middle of a term (word) (equal amount of letters on each side) * No capitals are present in the term **Example:** ``` eeeeE → EeeeE eEeee → eEeEe eeEee → eeEee Eeee. → EeeE. {EEee}1EEeEEEeeeeee → {EEEE}1EEeEEEEEEeEE ``` **TesT CaSeS:** ``` It was the first new century. → IT was the first new century. IiIIiiIIiiiI Ii iI iiiI iiii iIi. → IiIIIIIIIIiI II II IiiI iiii iIi. I sueD the airport for misplacing my Luggage. – I lost my Case. → I SueD the airport for misplacing my LuggagE. – I lost my CasE. The Policemen CraCked THE CaSE of the lost cocaIne. → ThE PolicemeN CraCkeD THE CASE of the lost coCaIne. JUST IN CASE. → JUST IN CASE. If(!1){ /\hElloBinOLIngo}elsE{ print( 'bOn aPPetit')} → IF(!1){ /\hElLOBinOLInGo}ElsE{ print( 'bOn aPPeTIt')} xK/TH"E7k['VyO%t>2`&{B9X.8^$GWc=!+@ 3Us}]JFM)jbuI,-:alPw*Qvpq5zi\Z(_n1dC~?<;fDAm0SR|eYg6#rN4Lho → XK/TH"E7k['VyO%t>2`&{B9X.8^$GWC=!+@ 3US}]JFM)JbuI,-:aLPw*QvpQ5zi\Z(_n1DC~?<;fDAm0SR|eYg6#RN4LhO Foo_bar → FoO_bar ``` (the " →" will not be included in the input) This is codegolf, so attempt to achieve least amount of bytes [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~76~~ 72 bytes *Saved 2 bytes thanks to @tsh* ``` s=>s.replace(/[a-z]+/gi,w=>Buffer(w).map((c,i,a)=>c&=a[w.length+~i]|95)) ``` [Try it online!](https://tio.run/##HVDtdhIxEP3PU0xRSyKwtNWqVRctdGlTsaBL/QKsIWSXtCHZJtmulNLjO/iGvgim/Jh7ZubMvXdmLukNtcyIzNWVnvJ1Eq5t2LSB4ZmkjKPGkNZvx9VGKmpF2GzlScINKnAwpxlCrCZqFIdNth3SYRFIrlI3q96L8d3BPsZrw69zYTiqJLaCvSKddoTk8UIxtIMDp2NnhEoRDmwmhUPlkSrjINEmomyGLIRNYFpZLXkgdYoSZLEXJQ4KasHNOCTCWAeKF8C4crlZBCUiCBGbEASIAI@b1MNDIfwE2JwfbfhUmEwbB94S5sI@HOz3gfkCunma0pQH8O/PXyAgtffx7Ta1PCgNPLWvpWB8zhVA29D2FZ/C4CTyA3EEOtmob0hMM0qUJ52exwMgZ9A@jCO/RIK2dvESGqNZJKVuCdXrEpXqFZc2WkLm/@IQVCY9BbTf5064Cl6Vfn9oDE7K0curYeXLovfENfd@bS9bB9@CVz8fH39l4Vb1PTw7t6vxaecjvpzkpFZ/TWW/ePrpJrvevxWjH@hC7U7b9@/evkmODuc78ec7/j198cicPe/OdKmj9cWEmv8 "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string s.replace( // replace in s: /[a-z]+/gi, // match all words in a case-insensitive way w => // for each word w: Buffer(w) // turn it into a Buffer .map((c, i, a) => // for each character c at position i in this array a[]: c &= // bitwise AND of c with: a[w.length + ~i] // the counterpart character taken from the end of // the word | 95 // OR 0b1011111 /// (all letter bits except the lowercase bit) ) // end of map() // implicit coercion of the Buffer to a string ) // end of replace() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly) ``` =ŒsŒgṁ@µŒu=ŒuṚTƲ¦) ``` A full program that takes a string argument and prints the result. **[Try it online!](https://tio.run/##HU5NSsNAFN73FJ@rNpuKBxDUGHCk2EDizs0YJ9Onk5kwM6GEUtArxJ0H8ACCi24L9R7tReIki/fxvsf3816FUm3fXx46d@jkcfdxtf89dE3gzXH3lf/97L@jvu@Zx5o7@JVASdZ5aLFGIbRvbDufTBgxRuMQAyMEHNcAA6FBAteI2zGBk62N9SiNRUWuVrwgLVG1WDRScinmOL1/gkGZ0BTOMXciROTBmxpFhaiEBmLL4zfxgvwuCYosgSnH@NFVmIIzPbjuH7Mc7AHxdZYMf5Szs4tog/OnVaKUuSG9XDAtzVYol2xQW9J@hunzUoOnqfDkp9H2Hw "Jelly – Try It Online")** ### How? ``` =ŒsŒgṁ@µŒu=ŒuṚTƲ¦) - Main Link: list of characters (S) Œs - swap-case (only affects alphabetic characters) = - (S) equals (that); vectorises Œg - group runs of equal elements ṁ@ - (S) mould-like (that) -> list of "words" (any single non-alphabetic character is now a word) µ ) - for each (word in that): ¦ - sparse application... Ʋ - ...to indices: last four links as a monad: Œu - upper-case (word) = - (word) equals (that); vectorises Ṛ - reverse T - truthy indices Œu - ...action: upper-case (the character at the index) - implicit, smashing print (just prints the characters in the list of lists) ``` Seems a bit long to me: * The partitioning atoms (`œṖ`, `œṗ`, `œP`, and `œp`) don't seem to help much here even though it seems like they should. * Perhaps there is a way to shorten code by zipping (`"`) a dyadic function with the reverse of each (`U`)? [Answer] # [Perl 5](https://www.perl.org/) `-p`, 60 bytes ``` s|\pL+|$i=0;join'',map$F[--$i]=~/[A-Z]/?uc:$_,@F=$&=~/./g|ge ``` [Try it online!](https://tio.run/##FcgxCsIwFADQ3VP8IdjBpnVxUYqKUih0crSWEkuMX9L@kKSDUMQ7eEMPYtQ3PiOtXoTgxpMpZyPDbL66EfZRFHfCsLzinGGdPdJqy491uh7aJWviTZ6x6S@TVI1KhlCAG@Qe/FWCQGvIeriQhQ6d0aLFXkF3h3JQSiiZwPv5ggI0Of/vnXAymeREzVkcPmQ8Uu8CN/oL "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~132~~ \$\cdots\$ ~~115~~ 114 bytes Saved ~~3~~ 11 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` f(s,e)char*s,*e;{for(;!isalpha(*s);++s);for(e=s;isalpha(*++e););for(*e&&f(e);s<e;++s)*--e&*s&32||(*s&=95,*e&=95);} ``` [Try it online!](https://tio.run/##jZP/VtMwFMf/5ykuVUbbbfwUFctQ6AoUJxtsKEoHZlnaRbq2NpnbGPX4Dr6hD@JMf2xO2eHQ06TJzf3em@aTi4sOxuOxLbMCUXAHhSorqEQb2X4oa4uUITfoIFllipbPiy42kxLTpgv5PFG01K6SXM6WxZTtkMRbLRZJTmW5zY27OxEiV9reErHjj6JFY@px6CLqycrCaAHEk2QHThhnl00owUgyOfQRA94hYNOQcfBIHzDxeC8crkgFkExqmjRp1ASTguiToejiCU2dgPVIOYmCaBj4IQexXehSFrgIU8@B7hAqPcdBDlmBXz9@ggmuL7IJs44YSYI0hLrmuxSTLvEA9BDpN6QNjSND@NQN8O0kQaLDPkaml@qOz@sNME9A36sb6W5seXFdGcGqZXUM1/X3qVetmJ7jR8RlxgiCUByMDMutqgeoViOc8mUlipWDt6uNI0syXtxcLr8fVpf47sbn3Gh/@2Ll5dXTww@4tJh/A5vnLGoeH7xTvrR6ZqH4Crm1vnr6Lfi6dUst65N87a239e@vdzS7vNddq5/dkY/O8yfhybNKx4@THPj@dQuFUqTNMCGDgGBO2hMsjUdgSZ8YS/rOwVJ/LBZjDhYjw2JMsZxMsJRTLHv3sOgPYDmYxVKpZlgO/ciYi6VhTrBcPIxFz7DUUyzHGZZKiuX0L5byfSxnMZZqiqV6HwvuEHxDwoyKNTA2rMG2LtpWLJmZb0508QHLceFRr00GQramZcMdYPSW@KJ@M9bKamZQpxYN8vnEW4G0YmeqVsRKKzdxaGrT9TibK1YZD13iyVzR/pFCq2fbl@6MQDjiYCjH9gLMutuJ7T@9uJwi@PSCzsseIMbSDeBukMUlCpTiv586JnxtWbKkJWZJUNyFbCQ6TxwnL0CqnBx6HLWZbSZaiMa/se0ih42L/T8 "C (gcc) – Try It Online") Modifies the input string to have in-word balanced capitalisation. ### Explanation ``` f(s,e)char*s,*e; // function taking a string { // parameter s and also declares // e as a string pointer for(;!isalpha(*s);++s); // loop until s pointes to the // beginning of the next word for(e=s;isalpha(*++e);); // loop until e pointes to one // past the end of that word for( // loop over this word *e&&f(e); // while e points to one past // the current word // recursively handle the next // word if we're not at the end s<e; // loop while s is before e ++s)*--e // bump s and e towards the middle ++s) // bump s forwards at the end of // each loop *--e // bump e backwards at the // beginning of each loop *--e&*s&32|| // if both characters aren't ( // both lower case then *s&=95 // make the first character upper , // case regardless of its case *e&=95 // and also make the second // character upper case ); // regardless of its case } // ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 13 bytes ``` ṁṠzo?aID↔ġo¬√ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxoc7F1Tl2yd6ujxqm3JkYf6hNY86Zv3//99Tobg01UWhJCNVITGzqCC/qEQhLb9IITezuCAnMTkzL10ht1LBpzQ9PTE9VU/hUcNkBU@FnPziEpCwc2Jxqh4A "Husk – Try It Online") ``` ġo¬√ # first ġroup the input into sublists (words) according to whether the elements are/aren't letters ṁ # now map across this list of words and concatenate the results into a string, with the function Sz ↔ # zip together each word and its reverse using μ ) # 2-argument lambda function: ? D⁰ # if arg 1 is uppercase a ² # return uppercase of arg 2 I # otherwise return arg 2 unchanged ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~73~~ 72 bytes ``` ->s{s.gsub(/[A-Z]+/i){|a|r=0;w='';a.bytes{|b|w<<(a[r-=1]>?Z?b:b&95)};w}} ``` [Try it online!](https://tio.run/##JY7tdpNAEIb/exVTP7JgG9JYq7YJiSlFu21sokn9SIi60IWshQV3l1IEPN6Dd@iNREp@zJyZOe/zviNSN9/45qY9kIU0Apm6Wmc5ai9Wux2mFyUphbnfy0yEesRwc0VlUbpl1u9rZCnaZnc1GC6G7rHbOjrUq15WVZskVRKWCCvIiAS1puAzIRVwmoFHuUpFbqC9BwgzjFlTDANmUPdmrNv9wrYikCk9bVwIE0ksFPixgIjJJCQe4wFEOYzTICABNeDfn7@AIYzrtPpsEUkbk3lNT@OQeTSiHMASxLqh1zA/s2vNzIbYbwIazos9gvmWO7@azQFfgjWa2dtvfG2nqxfQcdZ2GMYnjE/GmAdxRUNpF5AIxpUGDnInHMh0ShVTDtKre/TuojM/e2i/vFk66GM@eaIGz763ipOjz8arr4/ffvLMnd3XcHAlq9X5m3f6DzfFe@1jEk6zp@9vk5@Hv5iz0L7x7rX1e9jv@aejaH/2oaRfghePxOXz8Tp2EFoZEUm0lq9v/gM "Ruby – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 62 bytes ``` T`l`L`.(?=([A-Za-z])*)(?<=(?=(?>(?<-1>.)*)[A-Z])(?>[A-Za-z]+)) ``` [Try it online!](https://tio.run/##NVDbUsIwEH3nKxZvtChFvN8AoRYJIqDUG4oQSlqiJcE0iIA4/oN/6I9g6IwPe2b37Dm7OyuIpAzP53bbb5fbhpZNa4@5RAMnJk09rmvZk/SCymZUlkhlDMUt2k3Vyfzr1nV9PkcSRjgA2SPgUhFIYGQEDmFyKMZGBFGEaBgUAaKgMEwVLAqqFBAMyVnox1QMuJDgcgF9Ggx87FDmQX8M5aHnYY8Y8Pv9Awh8rvYo2sQBMSK2sta4Tx3SJwzAFNh8JV2wi5YS1C3gbjg9NDncwYgpU@mmbgOqgJmrW@oIV4um9Ckkn3qW7/M8ZdUyYh6fET@wpjAQlEkNYp0qA1yrqc/JmD6LfFwk7eKStf/6GLsdV1dlZqu9Ns0f3hsHzyvnd046un4K2zfBrFkqXOovnSHaSBxhvzaKX70P3nYn9KmhtViqa35lT47ds1x/s379SR68vWVR2Sn3eKTAeauDxR8 "Retina 0.8.2 – Try It Online") Explanation: ``` .(?=([A-Za-z])*) ``` Count the number of letters following the match. ``` (?<=(?=)(?>[A-Za-z]+)) ``` Skip back to the beginning of the word, and then... ``` (?>(?<-1>.)*) ``` ... match the same number of characters, ... ``` [A-Z] ``` ... followed by an uppercase letter. ``` T`l`L` ``` Uppercase matching letters. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~19~~ 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Å;√∩b₧Aµ╗∞q«J,╕* ``` [Run and debug it](https://staxlang.xyz/#p=8f3bfbef629e41e6bbec71ae4a2cb82a&i=It+was+the+first+new+century.%0A%0AIiIIiiIIiiiI+Ii+iI+iiiI+iiii+iIi.%0A%0AI+sueD+the+airport+for+misplacing+my+Luggage.+%E2%80%93+I+lost+my+Case.%0A%0AThe+Policemen++CraCked+THE+CaSE+of+the+lost+cocaIne.%0A%0AJUST+IN+CASE.%0A%0AIf%28%211%29%7B+%2F%5ChElloBinOLIngo%7DelsE%7B+print%28+%27bOn+aPPetit%27%29%7D%0A%0AxK%2FTH%22E7k%5B%27VyO%25t%3E2%60%26%7BB9X.8%5E%24GWc%3D%21%2B%40+3Us%7D%5DJFM%29jbuI,-%3AalPw*Qvpq5zi%5CZ%28_n1dC%7E%3F%3C%3BfDAm0SR%7CeYg6%23rN4Lho%0A%0AFoo_bar%0A&m=1) Replaces each match of `[A-Za-z]+` using the ruleset. -3, borrowing the untruth idea from Jonathan Allan's answer. ## Explanation ``` V^{c{96<mr:1{]^}&}R implicit input of string V^ regex: "[A-Za-z]+" {c{96<mr:1{]^}&}R replace each occurrence with the following regex: c copy the match {96<m boolean array for uppercase letters r:1 reverse and take truthy indices {]^}& uppercase the match at those indices ``` [Answer] # [Red](http://www.red-lang.org), ~~155~~ 152 bytes ``` func[s][a: charset[#"A"-#"Z"#"a"-#"z"]parse s[any[change copy w some a(repeat i d: length? w[if w/:i < #"["[n: d - i + 1 w/:n: w/:n and 95]]w)| skip]]s] ``` [Try it online!](https://tio.run/##PVH9dtIwFP9bnuK3oAJOQNSpq3OTsc514sDB/FjWzdCmbaRNalOsjOHxHXxDXwQDTnJO7rk39/dxz03G/cUp96lbCiwsgon0qHYps@BFLNM8p2XSJvUyOSdlwpbJNXHTZQeaMjmlBiZDDk@lUxTQKuFg1YynnOUlAd9CzGWYR3soqAhQNC2BHZQJJVRa8FGHwCZay4aplxFM@tject2idgM9FqnrancRqIwzL4IGLcEc4uQomEYecQQi0zkkL@BxmU@yaYPcYoTjiNUVDhwBE1epCctCrHHQE36w0mIiS1WWw/ghETqNmSdkiGSK7iQMWcgb@PPrNxzEynia5w7T/L/O0Aj0VSw8nnAJdDLWGXMfwyPbwAY2VLDyWFE95TFHrqnHZ4MhnBN02gN7PVZQ3WjVZmheRHYcq30he11HhmrOY23PkGZC5lVURj2zs36f5yKv1Oa33B9vm8OjS2I/H9PKh2nvXr77@Mv92f72p8aLy7tvPnqvNjZf48mZnrvHh@9qX0cT52HdYnG/ePD@e/pt61pcnFevZMvv/NzbeRkctJNHg9Mb/jl8Vs5OnnYjdWtzqNTViGWk5NJ/84CazSXmm0h9lyCAdt07i78 "Red – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (-p), 32 bytes ``` s/\pL+/$&&~reverse~$&&$"x"@+"/ge ``` The trick, to uppercase, is to AND characters with the negation of space. How it works For each sequence of letters bitwise NOT bitwise AND with space character repeated (at least the size of the match, here majorant is the position after match @+) Reverse bitwise negate bitwise AND with matched. [Try it online!](https://tio.run/##FcixCsIwEADQ3a84QulSbCZ3QREKnZwFiXLGQNo77lLRpfgP/qEf4qnb4zFKXpmpP3Df@KquZ8EbiuL8c@Xubt04H9GsA51wC@WKEJIwSYELCQxJOYdzGiMMD@inGEPEFt7PF3SQScu/N0GxXeyIjqew/xCXRKPakvMX "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~236~~ ~~230~~ 217 bytes My first answer in Code Golf! Edit: *-6 bytes thanks to @movatica* *-6 bytes thanks to @Danis* *-7 bytes thanks to @Alex bries* ``` s=input()+'_' o='' i=0 for j in range(len(s)): p=s[j] if p<'A'or'a'<p<'Z'or p>'z':u=[c<'a'for c in s[i:j]];b=[x|y for(x,y)in zip(u,u[::-1])];o+=''.join([c,c.upper()][x]for(c,x)in zip(s[i:j],b))+p;i=j+1 print(o[:-1]) ``` [Try it online!](https://tio.run/##NY/9etIwFMb/71Wc@ZVWum44PwudMta5ThwozI91FUOWlnQliWkrFIaP9@AdeiMYusc/cp73nJzfmzeyKqaCH2w2uce4LAvTaqAxMoSHkMG8fSMWClJgHBTmCTUzys3cslwDpJeHaWQAi0G2UQcJhTBqa3mpJchDtERu6YWkrcdbE7I1yUPmplHUmnjh4rYCPTcXdmXpmyWTZmmXoevuNiMraomGTuCkgnEzJDZxSimpMq0oXERbitiL/9Sdpz2xrIZsMS9tNA2pGC9MEdZem01QwBznUEwpxEzlBXA6B0J5UarKMQIWBKw@LICAga611GXbML0BeUmPax4zJYUqtslhxnKZYcJ4ArMKemWS4IQ68Pf3HwggE/odPe7inDrGSKMDkTFCZ5QDdBXu3tBrGJ36emHog4hr9xoiguCAa@jsYjiC4By6naGvQ8TmTtNawd7V1M8yccR4vxfwRKxplvsruPsyoEmfAx4MaMEKZK2Nxbu90ek9/8VNiD5V/YfF4ZPvj1ZHr744L789ePuZeDuNN3Bwka@js5P3VjopA3vXxdlg/vjDT/nj2ZJdXZpj3rzu/nrdbsXHndn@8OMt/Zo8v6/On/amwjgRYjzB6h8 "Python 3 – Try It Online") Commented code (*original*): ``` import re ``` ...import the regex module to find non letter characters ``` s=input()+'_' ``` ...take the imput from the console, and append a non letter character to complete the last iteration in the loop ``` o='' ``` ...initialize the output string ``` i=0 ``` ...initialize the index to find the start of each new identified word ``` for j in range(len(s)): ``` ...loop on the characters of the input ``` if re.match('[^A-Za-z]',s[j]): ``` ...identify a non letter character that separates words ``` u=[ord(c)<97for c in s[i:j]]; ``` ...list of boolean values corresponding to the letters in the word: True if uppercase ``` b=[x|y for(x,y)in zip(u,u[::-1])]; ``` ...reverse the list of boolean values, and apply `or` elementwise to obtain the symmetric list of uppercase characters ``` o+=''.join([[c,c.upper()][x]for(c,x)in zip(s[i:j],b)])+s[j]; ``` ...builds the output string: convert to uppercase according to the symmetric list built before; add the non letter character ``` i=j+1 ``` ...update the starting index of the next word. ``` print(o[:-1]) ``` ...prints the output balanced string (discarding the added last character)! [Answer] # [Julia](http://julialang.org/), 76 bytes ``` n->replace(n,r"[a-zA-Z]+"=>x->(L=length(x)+1;map(c->c-32(x[L-=1]<'['<c),x))) ``` [Try it online!](https://tio.run/##fVBbdtowEP33Kib0gV0wKUnfAVowJog4QALkASGpMLIRyJIj28FA6ekeusNuhBrylY9E58ycmTtz78xoGjGK8/HGKW64XpLEZ9gmKs/K1ADry7LeH2ZSxVKsl1SryAh3w4kaa5n8kYd91dZLtn54oMYDSy/mh4X0IF2wtWysadrGERJCEoRAOUiCx4xyEqiaAsnzJeUh4@q2/hRxHrGnoKYQPt6gEOY4gHBCwKEyEeZkDjbhYSQXOQVRhOjOKAJEIfG7MHHbhCYdEESkuuNjKn0hQ9ju6NFgezLlLngLsCLXxS7Jwb8/fwEBE8mcBDZwQHJKN6G2BaM28QgHMCQ2ZmQM3bqZNHRMEM5OfUeyhY0RT0iNXqcLqAlGuWMmSzjqXl5bwf7NxGRMVChvWYi7Yk1YYK4eL1YhPWpxwO02CWmY1tZKfLLfrafMz7NB@mLRehOWDn6@XVW@XuW@3L4@vrSLe5kfcNgL1sNG7VSbjiKU1b9h1p6/O3vw7z8u6U1fveP5sfH7e@HIqZa9953zX@Ta/fRKNj9YE6HUhLgbYangkT0mjjuh0xnzuPDvk2@OHubxYlmuGFWzdlxHjRPrtNlqn513ur2Ly6vrvvJ86Xm5Fya9oPcf "Julia 1.0 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` F⁺Sψ¿№α↥ι⊞υι«⭆⮌⮌υ⎇№α⊟υ↥κκ¿℅ιι ``` [Try it online!](https://tio.run/##RVBbdtMwEP1uVjENlMiQppQ3hFfrulQlbUzt8KpLURzZVqNIRpYSTAiHPbBDNmJk53D6oZFGM/femRtnRMWS8KpKpALkc1MgLHKjA62YSJHThdJxgCWAXGmERqQLozynKiYFRcyxNd8UGTJdYE6/RXlBYdna8C1YozXHCcnRGZ1TZQH/b@NY4pAqQVR5TezLfF25VpjabGpV@q2NeoahmjBBeC0Ma41adVVV5@12G2tYkAJ0RiFhqtAg6AJiKrRRZS9SmGHMmsMwYAY2Nk8b6oTVLVAYetAwEKZyqTTUtsxYkXMS211gVsLApClJaQ/@/v4DGLi0SvbbteNaitBifclZTGdUALiKuFM6gfDIsx2BBzJp6BtULGOCRY06HgUh4FNw9wKvniNBm7vOEnaizONc7jMxHGCRypX111tC3mwOnfFQAPF9qpnuOKtIfX@7Ex61vcfT8877crilX977emu5//Rj78mXm28@xC8277yG@6NidXF8eOJcjQ3ubj8j3F/cfjfPvz38waLP6FLsTtxfr573k4O92d3g7Cf9lD66oU4fDDIZqUMpL8dEWa8vqu05/wc "Charcoal – Try It Online") Link is to verbose version of code. Link includes test suite. Explanation: ``` F⁺Sψ ``` Loop over the input with a null terminator. ``` ¿№α↥ι ``` If the current character is a letter, ... ``` ⊞υι« ``` ... push it to the predefined empty list, otherwise: ``` ⭆⮌⮌υ⎇№α⊟υ↥κκ ``` Loop over a copy of the saved letters, retrieving them in reverse order each time, and uppercasing the copy if the reverse order letter is uppercase. ``` ¿℅ιι ``` Print the non-letter unless it's the null terminator. [Answer] # Java, 320 Bytes ``` s->java.util.regex.Pattern.compile("[a-zA-Z]+").matcher(s).replaceAll(m->java.util.stream.IntStream.range(0,m.group().length()).mapToObj(i->(Character.isUpperCase(m.group().charAt(m.group().length()-1-i))?Character.toUpperCase(m.group().charAt(i)):m.group().charAt(i))+"").collect(java.util.stream.Collectors.joining())) ``` [Try it online!](https://tio.run/##fVFNSwMxEL37K4Y9JegGvVqtlKViD6LQelF6mKbTbbbZJCSzYhV/e03dQgXFXGaY95HMS4OvWDbLzS50C2s0aIspwT0aBx8nAHAYJ0bO5dWbJbQZFFOOxtUvc8BYJ/lN3Z8m26mOjVWrzmk23qnbQ3PVS86gr0NYXe9SOTwqItX0ph6RmaJT2rfBWBLFC5bvo/J5flpI1SLrNUWRZGYHi5pG1or2p0viSNiqieNp30V0NYnzs1bV0XdBSGXJ1bwWcu8XZv5h0QhTDkW1xog6X65MegqBYoWJxFGmMz5i8dunvCiNlDdHPft/9Jl6@dfwtMgLam8taRa/9ql6wMekGm9cDjC/X@4Gh9z7/KfbxNQq37EKOWO2TqwUhmC3opitCR59/ktqyQFUEasNLWF2N4YKp2PwK@BMsT4xaK9x4kgVUg72zp8nn7sv) ## Explanation ``` s->java.util.regex.Pattern.compile("[a-zA-Z]+").matcher(s)//match words .replaceAll(m->//replace each word, m is MatchResult, m.group() is current word java.util.stream.IntStream.range(0,m.group().length())//iterate over indexes of word .mapToObj(i->(Character.isUpperCase(m.group().charAt(m.group().length()-1-i)) //check if character at reflected index is uppercase ? Character.toUpperCase(m.group().charAt(i))//make uppercase :m.group().charAt(i)) //do not modify + "" //concatenate with empty string to force result to be a String ).collect(java.util.stream.Collectors.joining()))//collect as single String ``` [Answer] # [J](http://jsoftware.com/), 60 bytes ``` [:;]<@((+.&(91>3&u:)|.)`(,:toupper)});.1~1,2|@-/\e.&Alpha_j_ ``` [Try it online!](https://tio.run/##jZDdTsJAEIXveYqjF2wbYRG9sqhBsZhNmkCUOzFYybYdUrpNuw0hUOM7@Ia@SC0/iibEMNlJJrvfOXOyk@KYMw9XFhhqOIVVdp2j8@B0iyer9XzZNowTXjUumtfn1cwyl9x8MWqWVlkcy8TMzRZvvjVrZ8t2vTGUvHoTxoE7mowKs1KR40DBAxMaMzeFDiQ8SlKNSM4wlpHOkjlnG4yxLc/E4D8adetgS0FiWyQgNofKkcoCCdq5lSCtewWu3kB/wW9HPGbybr3WpSRWiYanEkwpjUN3TJGP6RxO5vuub3N8vn9AIFRlvPK646b2biPSQ43kHiO5S9Q1jprmAo1hYIdO75ainiOie5XbYWovECcUaaP83ddeBLfflwOhGTPznxzeL3motnJf5XK/XNNGXnwB "J – Try It Online") Well this is shockingly verbose for J. Surely I am missing some better alternatives, but this is what I have for now... [Answer] # [Python 3](https://docs.python.org/3/), ~~153~~, ~~149~~, ~~148~~, 110 bytes *Using `re.sub` is even more elegant than re.finditer...* ``` lambda s:re.sub('[a-zA-Z]+',lambda w:''.join([c,c.upper()][d<'a']for c,d in zip(w[0],w[0][::-1])),s) import re ``` [Try it online!](https://tio.run/##jZLBjtMwEIbP5CmGvTgWbmDFLaJIpU3BqNpWSriQjZCbOqkhsSPbUdVdVeIdeENepMROF7FihbDi0cT@v38m0XRHu1fy9bma3p4b1m53DEyseWT6bYhyNrmbTT4XLxC53B1ihKKvSsgwL0kZ9V3HdYiLfPcGMVRUSkNJdiAk3IkuPOSvCuJCHseT6wJjYnAg2k5pC5qfLTfWwBTC4FmIqIUDM2D3HCqhjQXJD1ByaXt9jBABRLN/CTDxJoJS4begQAUM0adDcC9iNBoE43Ki8XksupiB6fnCF2RC@6bd97XCdA0rhayhPcKqr2tW8wh@fv8BFBo1NDYcz5nhYzFI/9ckecIkeWgmGww2qhElb7kEmGs2/8Z3kH1IBlmagKp8DY@WqmRUjvWzffKbu3ngFiM3@4ubj9xY8uOnNAN643Xe6/GBF@krWoXPr/E9vLzdJ02j3gm5XlFZqxNvTHIPnRbShoC2awlss@FWWIRPVwQGcvkHuVpfyPfqlDxJZtSTY29Lpb5smXZdLdXap@4CB4H7u4IoN4J@vuIAoBuGrAoFdql3zdFyRlfJIkYEbWZp6rIiV9NpVxBB0OQtIh0@/wI "Python 3 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 113 bytes 141 bytes ``` {for(b=1+split($0,l,"[ ]");--b;$b=e){a=split(toupper(m=l[b]),c,d=e=x);for(split(m,f,d);a;a--){if(f[++d]==c[d])f[a]=c[a];}for(;d;)e=f[d--]e}}1 ``` [Try it online!](https://tio.run/##JYwxC4MwFIT/SpAOBpNS5/AmEdqtULeQ4Zm8UDEaUUsL4m@3ijcdd98dftttW3wc0xrybBpCM6eXmwgi0cwkXElZq0sNxBeEs53jZxhoTDsIujZcWOGA4MfVcXIinfDCcYUKpeRL41Ovs8wZAKud4V6j2R0atR4T5RQn8NpJaWhd822r3sSeMTSWOurZoWLEoiXHqnvJCnyVLPojnncwxGlmzEaLj56ufw "AWK – Try It Online") *The code got longer to address a bug related to whitespace parsing as noted by Dominic van Essen.* This isn't all that short, but AWK isn't well suited to this challenge (as far as I can tell) so I think it's worth posted anyway. Here's how it works... The first `for` loop processes each commandline argument in reverse order. First it has to break the arguments into words explicitly, since TIO doesn't provide a way to set `RS` and `ORS` variables easily. ``` b=1+split($0,l,"[ ]") ``` which sets variable `b` to the number of space delimited words found, and stores the array of words (some of which might be empty strings) in variable `l`. The `1+` is necessary to keep the code from skipping the last word. then at the top of each loop, ``` --b ``` the code decrements `b`. The words in the array are processed in reverse order to avoid having to use another variable. The body of the loop consists of three statements, the first one is: ``` a=split(toupper(m=l[b]),c,d=e=x) ``` which does a couple of things. * converts the current argument `l[b]` to upper case * splits that word into a character array, assigns that to variable `c` * sets variables `d` and `e` to an empty string * set variable `a` to the number of characters in the argument * stores the untranslated value of the current argument in variable `m` The second statement is another loop, checking character by character and translating to uppercase as needed. It does that by initializing the loop with: ``` split(m,f,d) ``` which converts the current commandline argument to a character array, stored in variable `f`. At this point `f` has the original characters, and `c` has the same characters translated to uppercase. The loop condition and "end of loop" action cause the code to iterate `a` times, which is the number of characters in the current argument. The body of this second loop is single statement: ``` if(f[++d]==c[d])f[a]=c[a] ``` which translates the paired character to uppercase if the character we're checking is already uppercase. The loop decrements `a` and increments `d` each iterations, which keeps the pairing in sync. The third statement in the body of the outer loop, is essentially a "join" operation concatenating the characters in the translated character array. ``` for(;d;)e=f[d--]e ``` The only trick here is using the `d` variable as the iteration control, since it was incremented up to the length of the commandline argument in the previous loop. Also working backwards means we can use `f[d--]e` without having to use a space between them since the closing bracket separates the variables. Then the "end of loop" action on the outer loop assigns the re-assembled string to the current commandline argument. ``` $b=e ``` And all that's left to do is add a "truthy" test without any action to print everything. ``` 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) -1 thanks to [Makonede](https://codegolf.stackexchange.com/users/94066/makonede)! (Duplicate-TOS and then reverse-TOS has a one-byte built-in, `Â`.) -1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! (Take a list of characters.) ``` .γa}εÂ.uÅÏu]˜ ``` **[Try it online!](https://tio.run/##yy9OTMpM/R/8X@/c5sTac1sPN@mVHm493F8ae3rOf6//nmkaioaa1Qr6MRmuOTn5Tpl5/j6eeen5tak5xa7VCgVFmXklGgrqSf55CokBAaklmSXqmrUA "05AB1E – Try It Online")** ### How? ``` .γa}εÂ.uÅÏu]˜ - (accepts a list of characters) .γ } - group by: a - is alphabetic? ε - for each:  - push a copy and then push a reversed copy .u - is upper-case? (vectorises) ÅÏ - apply at truthy indices (of that, to the forward copy): u - upper-case ] - } } (close all loops) ~ - flatten ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 130 bytes ``` a->{for(int i=0,l=a.length,c,s,e;i<l;i++){for(s=i;i<l&&(c=a[i]&95)>64&c<91;i++);for(e=i;s<e;a[e]&=c)a[s]&=c=a[s++]^a[--e]^32|95;}} ``` [Try it online!](https://tio.run/##ZVLrUtpAFP6fpzj2golAFG8tDaFVjDUWlRbsDVGXZRMWk126uwEpptN36Bv2RegmouNMdybn@n0nZ8@eEZqg8mhws6DxmAsFI@3biaKRveYY/8WChGFFOcuS46QfUQw4QlLCCaIM5gbAMioVUlpNOB1ArHNmWwnKwm4PkAillSEBGpzJJCaihodIdHt1CNwFKtfnARcmZQqou1GKXGRHhIVqWMIlWSIOrUUOLRatHCVdmgUKBRO7qEt7heqOVd/dLuBatZKjnAxFNErWiIO6pFdwsYW6MtOaIYvF3iXqlsukd7m1eVfdcdJ04eTNKTEDc4IESIwYIwJcYGQK7XvPbM@kIrFNmWXB/W0ApkMaETCXBHuI5Cm5VU3KiPkEBZBVza4sdc0HMHtE2oo3dHJPCDQzLeeRFdgIYzJWZk59kli2whNlj/WQVcTMvNN84kv0Izw1HmRqpAuij2cQTyuDZMrITNuYe1qnFS29zMqO4SuYIglqSCCgQqp8HJgwlYiZbfjU92n@UR98ClrmphaZQzUCZEIOcj6iIl8s/TgQUzmOENatQjyDZhKGKCQ2/P39B3yIuP6PDjeQ1F11NLXF9XqRmDC9PgI1bsgAOkeeBrQ94EFePSdhjpHPNOn4vN0B/xQae21PNxGYKxVrDusXQy@K@D5lZ02fhTwlkfTmkM/PhNX@GQPUahFF1aqVGrcf1jtHz7xXN93Vz7Ozl6q@eV2Y71e/2q8vX7z/gt2V4jvYOpdp7/jwxBr1E79UfoOi1nTt42T8Y@cnvfhuXrHKoPHrbc0JDvbijfanO/It3H0uTrebQ24ccn7VR@If "Java (JDK) – Try It Online") ## Credits * -3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). [Answer] # [Japt](https://github.com/ETHproductions/japt), 30 bytes ``` òÈ+Y è"%L" ®íZmr"%a" ÔÏ?Xu:XÃc ``` [Try it online!](https://tio.run/##y0osKPn///Cmwx3akQqHVyip@ihxHVp3eG1UbpGSaqKSwuEph/vtI0qtIg43J///H63kqaSjlAbEGkCsCMSGQKwJxNVArADE@kAcA8QZQOwKxDlQnA/ETkCcCcR5QOwPxD5A7Anlp0PV1AJxKlRPMdQMmNkFQFyEZEYJ1B0gOXUgToKamwcVSwTiAChOharPhNLqUHfXKsUCAA "Japt – Try It Online") I'm not happy with this, but I haven't actually been able to find something better. Inputs and outputs as an array of characters. Explanation: ``` òÈ+Y è"%L" ò # Partition the input between pairs of characters where truthy: È+Y # Join the two characters into a string è"%L" # Count how many are not in [A-Za-Z] # Implicitly store as U ®íZmr"%a" ÔÏ?Xu:XÃc # ® # For each word: Zmr"%a" # Replace lowercase letters with "" Ô # Reverse it í Ï Ã # Pair each with the original letter at that index ? # If the modified array has anything other than "": Xu # Replace the original letter with upper-case :X # Otherwise leave it unchanged c # Flatten all the words back into a single array of chars ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~91~~ 82 bytes ``` $args-replace'[a-z]+',{-join(&{($w="$_")|% t*y|%{[char]($w[--$i]-bor95-band$_)}})} ``` [Try it online!](https://tio.run/##jVPtVtMwGP6/q3iZHW1hHaKiIk6BLoPipIMNRccYXUm7QNeMtHOMrh7vwTv0RmaatiAHjtrT5k2ePB9pk47oBLNggD1vLjnVaC5ZzA00hkeeZWO5Y2k33WW5HGkXlPjKYqRIk2pR6hXVWQnCpemsFHXsgcW6HO9omkS6Wp@y9TWtb/nnUk@NYzWex4XCplIoKzLmF5LLMhJVFVDS5xCvCGdQgiWQqAJKSJVUiCocSrAI8VG8yluU9LDwKQAkEwjlE0iUTGKEMLECCAcYHMKCEHw8ARv74ZhNK6nYaP@NktkQwyDiIQYYBHgrurxJBiS34pT0SmjpfZ@W2UEwxjURaRE2oiwEhzIYkiDZA@K7MJxCY@y6losr8OvHTzDAo3xpHNatAOdx0PpfG/SIze13bXODJvWIjYfYB9CZpV/ic2jvIk5rIaCOyBBSm9qW4ecraA/QrXI/V9ZS5dYDpZ4q09C9o1YbjH3By9zuQ4JWNBxlYVWNYOVkgDyPbhPfbBi@S2PsBSiCESN@qIDcN32wmk0cklBW42JiVzTqf0gbZibdoTF6VNo2hDSNvf6w0t49K6JXlx3509Qshe@enS1G2@vHldenZ9LOZ7u6sLwJz4@CuLtX/6he9MdGWXtjec3J0sG30dXaDTn5qvT81XP9@/u3G05ta/i0dTjDX9yXT9j@i8aApks8/keMnsW00pi9LKaRxhzcxtQexhwmMWb6OnKd0l7fYvx/qlNT9NSCCjMoQcSXASAF/Lxj38ZlkPD1CNsh3/8qSL10luFg7IUcWJScO66Y6zRb@jgI6dDsX3BZdzPih9K2cRAk@kyo2fjqzngDDnO/nBAX4vlv "PowerShell – Try It Online") where: * `&{` creates a new context each contains `$i=0` * `-bor` is bitwise `or`, `-band` is bitwise `and` have inspired by the [Arnauld's answer](https://codegolf.stackexchange.com/a/219704/80745) ]
[Question] [ As [TIO can show](https://tio.run/#), every letter of the Latin alphabet is represented when it comes to languages. For every letter there is at least 1 programming language whose name begins with that letter. Your task is to create a polyglot in order to demonstrate that. Your program should be runnable in between 2 and 26 different languages, each of which starts with a different letter. However, if your program runs in \$N\$ languages, the languages used must have the first \$N\$ letters of the alphabet as the first letter of their names. So if your program runs in 5 languages, the languages must start with `A`, `B`, `C`, `D` and `E`. (e.g. [A Pear Tree](https://tio.run/#a-pear-tree), [BrainSpace](https://tio.run/#brainspace), [C++](https://tio.run/#cpp-gcc), [Dash](https://tio.run/#dash) and [Enlist](https://tio.run/#enlist)) Your program should take no input, and output a constant string: the alphabet (case-irrelevant, in order), but with the letter of the language name removed. So the language beginning with `A` should output `BCDEFGHIJKLMNOPQRSTUVWXYZ` (or the equivalent lower case version). Case doesn’t have to be consistent for different languages, but it does between runs in the same language. Any languages are fair game, so long as no letters are repeated. This rules out using different versions for most languages (e.g. Python 2 vs Python 3), but this is only as a consequence of having unique letters. Seriously and Actually, for example, are considered different versions, but can both be used in the same answer as they start with different characters. If using languages with custom code pages, then, as is standard, the bytes must match between programs, not characters. Submissions are scored by number of languages used, with a tie breaker of shortest code. [Answer] # [AsciiDots](https://github.com/aaronduino/asciidots), [Bash](https://www.gnu.org/software/bash/), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [Dash](https://wiki.debian.org/Shell), [evil](https://web.archive.org/web/20070103000858/www1.pacific.edu/%7Etwrensch/evil/index.html), [fish](https://fishshell.com/), [goruby](https://docs.ruby-lang.org/en/master/extension_rdoc.html#label-goruby+Interpreter+Implementation), [Haystack](https://github.com/kade-robertson/haystack), [Implicit](https://github.com/aaronryank/Implicit), [J-uby](https://github.com/cyoce/J-uby), [ksh](http://www.kornshell.com/), [Ly](https://github.com/LyricLy/Ly), [mksh](http://www.mirbsd.org/mksh.htm), [Numberwang](https://esolangs.org/wiki/Numberwang_(brainfuck_derivative)), [OSH](https://www.oilshell.org/), [Python 3](https://docs.python.org/3/), [QuadR](https://github.com/abrudz/QuadRS), [Ruby](https://www.ruby-lang.org/), [Super Stack!](https://github.com/TryItOnline/superstack), [Taco](https://github.com/TehFlaminTaco/TacO), [Unefunge-98 (Pyfunge)](https://pythonhosted.org/PyFunge/), [V (Vim)](https://github.com/DJMcMayhem/V), [Wumpus](https://github.com/m-ender/wumpus), [xonsh](https://xon.sh/), [yash](https://yash.osdn.jp), [Zsh](https://www.zsh.org/), 1009 bytes 9 shells, 3 Rubies, some 2D (and 1D!) languages and many languages I learned just for this challenge. I really enjoyed this challenge and learned some new languages and features. I enjoyed finding a shorter way than just the raw string in some languages (in some languages generating the string seemed longer) and trying to re-use the `s` variable as many times as possible was fun too. I've also tried to keep the byte-count as low as possible. If I find the time and the inclination, I wonder if I could start adding the letters of the alphabet to the end instead... Crazy talk... ``` ' # "194940711909711999999999999940391270919999999999994039127zaeeeawawawawavaeeaaaaamvawvusb"' #165#1#1;.040;"ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q"ABCDEFGIJKLMNOPQRSTUVWXYZ"o¡72"8:é9:é8++:90+1®;65µ '\&p"A""K"R"M""Z"R&o;';# x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x.-$"BCDEFGHIJKLMNOPQRSTUVWXYZ" 0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi "ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o @"ABCDEFGHIJKLMNOPQRSUVWXYZ" s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#' 0//1; try:echo -n;print(s[0:23]+"YZ"); except:print(s[0:15]+s[16:]);"""/.__id__;begin ~:*;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end;' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;';/ ('Q'⎕R'')⎕A⋄'\} #<esc>ggdG¬AZ:s/#\|V//"""#\'⍵ ``` # [AsciiDots](https://github.com/aaronduino/asciidots) The relevant code is: ``` .-$"BCDEFGHIJKLMNOPQRSTUVWXYZ" ``` This needs to be wrapped in `[`...`]` to avoid [Extended Brainfuck Type I] from outputting rubbish before the desired string because of the `.`. [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRmH9irBNW8yHJsZoNDGJ4hAixDKdinUhsanmqned9q4P0MvOdHqXF7BvkhexC9FWZ1hYmD3nd/7nA0zadRzL9ehsJgIPCCsZJSNvYazISvBcXhk5reDUlqzgCOu9adu2eTe/btnJDNb7W/Pu1qfXiKnjXJbHPCZJOSMT1Lq8OG@eNuontepx5ah8eFAq7u/t7hQ0lIf0xrvND0gr7Ozu7RcPDstHleNq7aTeOD1rnl9ctpA7/bGVQnn1z0@F7Xw8ripyHE9/k1x2@siJemyANITKqI4qCLVQPeYSkfAAMHrBVAPRUoTqKJkQ0HPOKDfIkMsGt3MDA3cAlv@882mg/vXC6vrewPfMYKws4MYJjRhMywphBYcwswcDaJ5FDoBPZWMuq/bNYgTL5cyr4eh2lHdRLJF5kZMlCRPOG35U7e5bFxJ9Mhg6fW@NtmU1le7EEQPXCWePuvbAU//7cLYTp22cUzvrBCEkJQ3DsQyDXNs9pw8P6gZhLVKgyV7Qy@vDTYTI0KZd354j2ipQXAJWHPXAYfetcItcGxL3IFDoxGJhwWF/Ue0x/8jxSAhdtVmIZ3o@hW026EWsLnyiUkuazNE26DZsP4C9Clz@A/QwuS4kQF9KH0B8UMZ/nZAqaI1S7WB3VawsrVCCUW1WjJp2WoLOeBxiAh17Q0hYUI1EwlDm6INw1tirG0GClQwVaTJXCo8FaXLFfmyJWxNPxKdv3@uiuM5e2tOXz6I@Af4lG/mrXs8qTn9pLZVKvD5uShL7orwuPn19nM3@Ag "AsciiDots – Try It Online") # [Bash](https://www.gnu.org/software/bash/) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` This first line sets `$s` to be the full alphabet in uppercase, so `-z $s` is false and skipped over. `$status` is unset, `\e` is treated as an escape, not a `\` and `e`, `$BASHPID` is set, `$_OVM_PATH` is not and `$USER_ID` isn't set so `B` is replaced with the empty string in `$s` (`${s/B/}`) and `echo`ed it out. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg4FEzHQKlE2UWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fSdukN7OZCDwgrKSUlLyFsSIr/nN5peSkghNbsoJDrPembdvm3fy6ZSfTXx9uzbtbj7YRU8eZNI95TOJySiaofnlxXjut6ieV8nHpqHh4UMjv7@3u5DSUheTG@82PSMvt7O7t5w8Oi0el43LlRK@entXOLy7rqD/9uZVAWfXvL4XtbDSqKnIUT/@QTHr6yIlGZIA0hIpIRyWE6kiP9IlIeAAYvWKqvmghRHUUjwnoOWeYG2TIpP3buYZBfwCW97yzSaBee2Hte@7Ac03acRwWcO0ERgymZQWwggOY2f0B1M5CB8An0pE@q/bdYgTL5cyr4eh2mHdRLJF5kZMlCRPOHX5S7c5NH2I9Mhg6PXeNNmQ1kWxGEQPXCWePOvbAVV98ON2M0gbOqM11ghCS4q2WY7VapG13nR48qBuEtUiBxrt@L28PNxEiQ5t2PHuOaKtAfglYcei@w@5ZwRa5BsTuQaDQjESCgoP@wtpj/pHjkgC6arAQ13Q9Ctts0ItYQ/hMpbo0maMNMGzYfgB7Fbj8DxhBckOIgbGU3od4v4wXnYDKadVC5WB3VaworVBCq1wrtSraaQGa43GACXTsDiFmQTkUCUKZowfCWXVPb/kJVjKUpMlcKTjmpMkV@7Elbk08EZ@@/9BFcZ29tKevX0RjAvxrNvI33a6Vn/7W6iqVeGNckyT2RXlDfPr2OJv9Aw "Bash – Try It Online") # [Cardinal](https://www.esolangs.org/wiki/Cardinal) The relevant code is: ``` x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x ``` The cursors spawn from the `%` and are terminated by the `x`s. This needed to be moved slightly to prevent additional output. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg4FEmmkLlE2UWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fScccWk7PfD@bicADwkpKSclbGCuy4j@XV0pOKjixJSs4xHpn2rZt3s6vG3Yy/fXhxry98WgbMXWcSfOYxyQup2SC6pcX57XTqn5SKR@XjoqHB4X8/t7uTk5DWUhuvNv8iLTczu7efv7gsHhUOi5XTvTq6Vnt/OKyjvrTn1sJlFX//lLYzkajqiJH8fQPyaSnD5xoRAZIQ6iIdFRCqI70SJ@IhAeA0Qum6osWQlRH8ZiAnnKGuUGGTNq/nWsY9AdgeU87mwTqtRfWvucOPNekHcdhAddOYMRgWlYAKziAmd0fQO0sdAB8Ih3ps2rfLEawXM68Go5uh3kXxRKZFzlZkjDh3OEn1e687UOsRwZDp@eu0YasJpLNKGLgOuHsUcceuOqzD6ebUdrAGbW5ThBCUrzVcqxWi7TtrtODe3WDsBYp0HjX7@X14SZCZGjTjmfPEW0VyC8BKw7dd9g9K9gi14DYHQgUmpFIUHDQX1h7zD9yXBJAVw0W4pquR2GbDXoRawifqVSXJnO0AYYN2/dgrwKX/wEjSG4IMTCW0vsQ75fxrBNQOa1aqBzsrooVpRVKaJVrpVZFOy1AczwOMIGO3SHELCiHIkEoc/RAOKvu6S0/wUqGkjSZKwXHnDS5Yj@2xK2JJ@Lj9x@6KK6zl/b49YtoTIB/yUb@qtu18tPfWl2lEm@Ma5LEvihviI/fHmazfw "Cardinal – Try It Online") # [Dash](https://wiki.debian.org/Shell) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` As per Bash, this first sets `$s` to be the full alphabet in uppercase. so `-z $s` is false. `$status` is empty, `\e` is an escape sequence and doesn't match `e`, but `$-` is empty in Dash so that conditional is met and we `echo` out `ABC` followed by `$s` with the prefix `ABCD` removed (`${s#ABCD}`). [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIEwOJmOkUKBuUWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fiW3Rm9lMBB4QVlJKSt7CWJEV/7m8UnJSwYktWcEh1nvLcRzrbn7dspPlrw@31t3tkLYQU8eZNI95TOJySiaofnlxXjut6ieV8nHpqHh4UMjv7@3u5DSUheTG@82PSMvt7O7t5w8Oi0el43LlRK@entXOLy7rqDf9uZVAWfXvL4XtbDSqKnIUT/@QTHr6yIlGpI80hIpIRyWE6kiP9IhIeAAYvWKqvmghRHUUjwnoOWeYG2TIpP3bvYZ@rw/28Hlnk0CHrYW1N/T6Q8@ibddlAdduYMRg2XYAKziAmd0fQO0sdAB8Ih3psWrfLUawXM68Go5uh3kXxRKZFzlZkjDhvMEn1Wnf9CDWJf2B2/XWaENWE8lmFDFwnXDOqO30PfXFh9PNKG3gjNpcJwghKW6arm2apOV03C48qBuEtUiBxjt@L28PNxEiA4e2h84c0VaB/BKw4tB9h9O1gy1yDYjdg0ChGYkEBQf9hbXH/CPXIwF01WAhnuUNKWyzQS9iDeEzlerSZI42wHBg@wGcVeDyP2AEyQ0hBsZSeh/i/TJedAIqp1ULlYPdVbGitEIJZrlWMivaaQGa43GACXTsDSBmQzkUCUKZowvCWXVPN/0EKxlK0mSuFBxz0uSK/dgStyaeiE/ff@iiuM5e2tPXL6IxAf41G/mbTsfOT39rdZVKvDGuSRL7orwhPn17nM3@AQ "Dash – Try It Online") # [evil](https://web.archive.org/web/20070103000858/www1.pacific.edu/%7Etwrensch/evil/index.html) The relevant code is: ``` zaeeeawawawawavaeeaaaaamvawvusb ``` [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg5FEmmkLlE2QWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fiT103s9mIvCAsJJSUvIWxoqs@M/llZKTCk5syQoOsd6Ztm2bt/NryE6mvz4MzduhR68RU8eZNI95TOJySiaofnlxXjut6ieV8nHpqHh4UMjv7@3u5DSUheTGu82PSMvt7O7t5w8Oi0el43LlRK@entXOLy7rqDf9uZVAWfXvL4XtbDSqKnIUT/@QTHr6wIlGpI80hIpIRyWE6kiP9IhIeAAYvWCqvmghRHUUjwnoKWeYG2TIpP3buYF@rw@W97SzSaDe9cLa89y@55q07Tgs4MYJjBhMywpgBQcws/sDqJ2FDoBPpCM9Vu2bxQiWy5lXw9HtMO@iWCLzIidLEiacO/ik2u23PYh1SX/gdN012pDVRLIZRQxcJ5w9att9V3324XQzShs4ozbXCUJIirdajtVqkWu743ThXt0grEUKNN7xe3l9uIkQGdi07dlzRFsF8kvAikP3HXbXCrbINSB2BwKFZiQSFBz0F9Ye848clwTQVYOFuKbrUdhmg17EGsJnKtWlyRxtgGHD9j3Yq8Dlf8AIkhtCDIyl9D7E@2U86wRUTqsWKge7q2JFaYUSWuVaqVXRTgvQHI8DTKBjdwAxC8qhSBDKHF0Qzqp7estPsJKhJE3mSsExJ02u2I8tcWviifj4/YcuiuvspT1@/SIaE@BfspG/6nSs/PS3VlepxBvjmiSxL8ob4uO3h9nsHw "Extended Brainfuck Type I – Try It Online") # [fish](https://fishshell.com/) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` In fish, variables aren't assigned via the `s=...` syntax so `$s` is empty meaning the first conditional is hit, the required string is `echo`ed out and then `exit` is called. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg5FEzNQCZROlFrzqXae96wP0sjOd3vkC9E18EbqJUGEmm2wye87v/M9HcuXQ6xi9tm9uplMReEBYSSkpeQNjRVb85@JKyUkFJzZkBYdY703bts272XXLTqa/Ptyad7cevURMHWfSPOYxicspmaD6@dlp7biqH1XKh6WD4v5eIb@7s72V01AWkmvv1z8iLbe1vbOb39svHpQOy5UjvXp8Ujs9O6@j3uTnRgJl1b@/FLaz0aiqyFE8@UMy6ckjJxqRPtIQKiIdlRCqIz3SIyLhAWD4iqn6ooUQ1WE8JqDnnGFukCGT9m/nCvq9Plje884mgXqXc2vPc/uea9K247CAKycwYjAtK4AVHMDM7g@gdhI6AD6RjvRYte/mI1gsZ1YNRzfDvPNiicyLnCxJmHDu4JNqt697EOuS/sDpuiu0IauJZDOKGLhKOHvYtvuu@uLD6WaUNnBGba4ShJAUb7Ucq9Uil3bH6cKDukZYixRovOP38nZ/HSEysGnbs2eItgzkF4Alh@477K4VbJFrQOweBArNSCQoOOgvrD3mHzouCaCLBgtxTdejsMkGPY81hM9UqkvjGdoAw4bNB7CXgfP/gBEkN4QYGAvpfYj3y3jRCaicVi1U9raXxYrSEiW0yrVSq6IdF6A5GgWYQEfuAGIWlEORIJQ5uiCcVHf0lp9gKUNJGs@UgmNOGl@wH1viVsQj8en7D10UV9lLe/r6RTTGwL9mI3/T6Vj5yW@trlKJN0Y1SWJflDfEp2@P0@k/ "fish – Try It Online") # [goruby](https://docs.ruby-lang.org/en/master/extension_rdoc.html#label-goruby+Interpreter+Implementation) + `--disable=gems` This isn't available on TIO, but is distributed with the official Ruby source and can be compiled (after the normal `autoconf` and `./configure` steps) with `make goruby`. Tested on version `ruby 2.8.0dev (2020-08-24T10:24:07Z master 1eb1add68a) [x86_64-linux]`. The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0 0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end ``` # [Haystack](https://github.com/kade-robertson/haystack) The relevant code is: ``` "ABCDEFGIJKLMNOPQRSTUVWXYZ"o ``` which `o`utputs the required string. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg5FEzDgFyiaKFrzqXae96wP0sjOd3vkC9E18EbqJUGEmm2wye87v/M9Hcm3eU9ds30ynIvCAsJJSUvIGxoqs@M/FlZKTCk5syAoOsT6Ytm2bd7Prlp1Mf328Ne9uPXqJmDrOpHnMYxKXUzJB9fOz09pxVT@qlA9LB8X9vUJ@d2d7K6ehLCTXbtY/IS23tb2zm9/bLx6UDsuVI716fFI7PTuvo97k50YCZdW/vxS2s9GoqshRPPlDMunJEycakT7SECoiHZUQqiM90iMi4QFg@Iap@qKFENVhPCagl5xhbpAhk/Zv5wr6vT5Y3svOJoF6l3Nrz3P7nmvStuOwgCsnMGIwLSuAFRzAzO4PoHYSOgA@kY70WLUf5iNYLGdWDUc3w7zzYonMi5wsSZhw7uBetdvXPYh1SX/gdN0V2pDVRLIZRQxcJZw9bNt9V3314XQzShs4ozZXCUJIirdajtVqkUu743ThUV0jrEUKNN7xe3m/v44QGdi07dkzRFsG8gvAkkP3HXbXCrbINSD2AAKFZiQSFBz0F9Ye8w8dlwTQRYOFuKbrUdhkg57HGsJnKtWl8QxtgGHD5iPYy8D5f8AIkhtCDIyF9D7E@2W86gRUTqsWKnvby2JFaYkSWuVaqVXRjgvQHI0CTKAjdwAxC8qhSBDKHF0QTqo7estPsJShJI1nSsExJ40v2I8tcSvikfj8/YcuiqvspT1//SIaY@DfspG/63Ss/OS3VlepxBujmiSxL8ob4vO3p@n0Hw "Haystack – Try It Online") # [Implicit](https://github.com/aaronryank/Implicit) The relevant code is: ``` ¡72"8:é9:é8++:90+1®;65µ ``` This pushes the range of `1`..`72` and joins the last 8 items on the stack to a string, duplicates the top the stack, increments all codepoints by 9, duplicates the stack again, increments all codepoints in the string by 8, pushes `90` to the stack and concatenates all, reverses the stack, pop off the top 65 elements then prints the stack. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5LUtsEPUEQwKCqEiZFEmrFCyiZKLXjVu0571wfoZWc6vfMF6Jv4InQTocJMNtlk9pzf@Z@PhDg37gebeGbnejrlgQWEpYyUETcwlkQpeC6ujJiWcGpDlHCE9d60bdu8m1239GQG6@bWvLv1ySWi6jiXZTGLlaSYERXUPD87bRzXtaNa9bByUN7fKxV3d7a3CirKQ3rtev0jUgtb2zu7xb398kHlsFo70urHJ43Ts/Mm6k9@bqRQXv77S6I7H4/LkhjHkz9KLjt5ZHg95iIVoTLSUAWhJtJifYVXWAAYvqKqgWgpQnWYTHDoOWeUG0TIZYPbuQK374LlP@98Goh/Obf2fc/1PZN0HIcGXDmhEYNpWSEs4RCm9mAAjZPIAbCpbKxPq303H8FiObNqGLIZ5Z0Xq4gsz4iCgBXGG3yS7c77PiR6ijtwet4KaYlyKt2OIwquKow97NiuJ7/4cLYdJy2ck9urCkJISBqGYxmGcml3nR48yGsKbZEASXaDXt7uryOkDGzS8e0Zoi4DxQVgyaEFDrtnhZtnWpC4B45AOxYLCw77i2qP@oeOp4TQRYuGeKbnE9ikg57H6txnIjSF8QxtgW7D5gPYy8D5f0APk@tcAvSF9AHEBmW86IRUQa2Xanvby2JlYYnijGqjYtTU4xK0R6MQ48jIG0DCgmokEoZSRw@4k/qOZgQJljJUhPFMKTwWhPEF/bEFZoU/4p@@/9B4fpW@1KevX3h9DOxrOvI33a5VnPxWmzIRWH3UEAT6RVmdf/r2OJ3@Aw "Implicit – Try It Online") # [J-uby](https://github.com/cyoce/J-uby) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0 0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end ``` This shares the declaration of `s` with the shells and other Ruby implementations and and `.gsub`s `J` from the string before `puts`ing it as long as `~:*&?,` doesn't cause an error. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg4FEmnYKlE0ULXjVu0571wfoZWc6vfMF6Jv4InQToYWZbLLJ7Dm/8z8fybuY176bzUTgAWElpaTkLYwVWfGfyyslJxWc2JIVHGK9N23bNm/n1w07mf76cGPe3ni0jZg6zqR5zGMSl1MyQfXLi/PaaVU/qZSPS0fFw4NCfn9vdyenoSwkN95vfkRabmd3bz9/cFg8Kh2XKyd69fSsdn5xWUf96Y@tBMqqf34qbGejUVWRo3j6m2TS00dONCIDpCFURDoqIVRHeqRPRMIDwOgFU/VFCyGqo3hMQM85w9wgQybt3841DPoDsLznnU0C9doLa99zB55r0o7jsIBrJzBiMC0rgBUcwMzuD6B2FjoAPpGO9Fm1bxYjWC5nXg1Ht8O8i2KJzIucLEmYcO7wTrU7b/sQ65HB0Om5a7Qhq4lkM4oYuE44e9SxB67634fTzSht4IzaXCcIISneajlWq0XadtfpwYO6QViLFGi86/fy@nATITK0acez54i2CuSXgBWH7jvsnhVskWtA7B4ECs1IJCg46C@sPeYfOS4JoKsGC3FN16OwzQa9iDWET1SqS5M52gDDhu0HsFeBy3@AESQ3hBgYS@l9iPfL@K8TUDmtWqgc7K6KFaUVSmiVa6VWRTstQHM8DjCBjt0hxCwohyJBKHP0QDir7uktP8FKhpI0mSsFx5w0uWI/tsStiSfi07fvuiius5f29OWzaEyAf8lG/qrbtfLTX1pdpRJvjGuSxL4ob4hPXx9ns78 "J-uby – Try It Online") # [ksh](http://www.kornshell.com/) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` `$s` is set as the other shells and `$status` is empty, `\e` doesn't match `e`, `$-` is not empty, but `$BASHPID` is so `$s` is `echo`ed removing `K` (`${s/K/}`). [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KttcEPUEQwKCqEwUgiZpwCZROlFrzqXae96wP0sjOd3vkC9E18EbqJUGEmm2wye87v/M9HcktvplMReEBYSSkpeQNjRVb85@JKyUkFJzZkBYdYH0zbts372XXHTqa/PtyZ93cevUJMHWfSPOYxicspmaD6xflZ7aSqH1fKR6XD4sF@Ib@3u7Od01AWkmu36x@Rltve2d3L7x8UD0tH5cqxXj05rZ2dX9RRb/JzI4Gy6t9fCtvZaFRV5Cie/CGZ9OSJE41IH2kIFZGOSgjVkR7pEZHwADB8w1R90UKI6jAeE9BLzjA3yJBJ@7dzDf1eHyzvZWeTQL2rubXnuX3PNWnbcVjAtRMYMZiWFcAKDmBm9wdQOw0dAJ9IR3qs2vfzESyWM6uGo5th3nmxROZFTpYkTDh38Em12zc9iHVJf@B03RXakNVEshlFDFwlnD1s231XffXhdDNKGzijNlcJQkiKt1qO1WqRK7vjdOFRXSOsRQo03vF72TpYR4gMbNr27BmiLQP5BWDJofsOu2sFW@QaEHsAgUIzEgkKDvoLa4/5h45LAuiywUJc0/UobLJBz2MN4TOV6tJ4hjbAsGHzEexl4OI/YATJDSEGxkJ6H@L9Ml51AiqnVQuV/Z1lsaK0RAmtcq3UqmgnBWiORgEm0JE7gJgF5VAkCGWOLgin1V295SdYylCSxjOl4JiTxpfsx5a4FfFYfP7@QxfFVfbSnr9@EY0x8G/ZyN91OlZ@8lurq1TijVFNktgX5Q3x@dvTdPoP "ksh – Try It Online") # [Ly](https://github.com/LyricLy/Ly) The relevant code is: ``` &p"A""K"R"M""Z"R&o; ``` which first clears the stack then pushes the `R`anges from `A`-`K` and `M`-`Z`, before `&o`utputting the stack contents and terminating (`;`). [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KttcEPUEQwKCqEwUgizbQFyiaKFrzqXae96wP0sjOd3vkC9E18EbqJUGEmm2wye87v/M9H8uFuOhWBB4SVlJKSNzBWZMV/Lq6UnFRwYkNWcIj13rRt27ydXTfsZPrr4415e@PRK8TUcSbNYx6TuJySCapfnJ/VTqr6caV8VDosHuwX8nu7O9s5DWUhufZ@/RPScts7u3v5/YPiYemoXDnWqyentbPzizrqTX5uJFBW/ftLYTsbjaqKHMWTPySTnjxyohHpIw2hItJRCaE60iM9IhIeAIavmKovWghRHcZjAnrOGeYGGTJp/3auod/rg@U972wSqHc1t/Y8t@@5Jm07Dgu4dgIjBtOyAljBAczs/gBqp6ED4BPpSI9V@3Y@gsVyZtVwdDPMOy@WyLzIyZKECecO7lS7/a4HsS7pD5yuu0IbsppINqOIgauEs4dtu@@qLz6cbkZpA2fU5ipBCEnxVsuxWi1yZXecLjyoa4S1SIHGO34vWwfrCJGBTduePUO0ZSC/ACw5dN9hd61gi1wDYvcgUGhGIkHBQX9h7TH/0HFJAF02WIhruh6FTTboeawhfKZSXRrP0AYYNmw@gL0MXPwHjCC5IcTAWEjvQ7xfxotOQOW0aqGyv7MsVpSWKKFVrpVaFe2kAM3RKMAEOnIHELOgHIoEoczRBeG0uqu3/ARLGUrSeKYUHHPS@JL92BK3Ih6LT99/6KK4yl7a09cvojEG/jUb@ZtOx8pPfmt1lUq8MapJEvuivCE@fXucTv8B "Ly – Try It Online") # [mksh](http://www.mirbsd.org/mksh.htm) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` As per the previous shells, the first line sets `$s` to be the full alphabet in uppercase, so `-z $s` is false and skipped over. `$status` is unset, `\e` is treated as an escape, not a `\` and `e`, `$BASHPID` is set, `$_OVM_PATH` is not and `$USER_ID` is set so `M` is replaced with the empty string in `$s` (`${s/M/}`) and echoed it out. Tested on version `58-1`. # [Numberwang](https://esolangs.org/wiki/Numberwang_(brainfuck_derivative)) The relevant code is the big number as Numberwang is just a transliteration of brainfuck: ``` 194940711909711999999999999940391270919999999999994039127 >+[+[<]>>+<+]>>+++++++++++++[<.+>-]<+>++++++++++++[<.+>-] ``` There's a minor amount of work to balance `4`s and `7`s throughout the rest of the code, alongside making sure things appear in the right order, but nothing major. Might be able to save some bytes by moving stuff around here... [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRmH9ikDTFvOhiTEaTEyiOASFWKYTtC4kNtVc9a7T3vUBetmZTu/yAvZN8iJ2IdroDAsLs@f8zv98gOvfdOzhnen2ZjMeWEBYykgZcQtjSZSC5/LKiGkJp7ZECUdY703bts27@XVLT2awbm7Nu1ufdBBVx7ksi1msJMWMqKDm5cV547SundSqx5Wj8uFBqbi/t7tTUFEe0hsfNj8itbCzu7dfPDgsH1WOq7UTrX561ji/uGyi/vTnVgrl5b@/JLrz8bgsiXE8/aPkstNHhtdjA6QiVEYaqiDURFqsr/AKCwCjV1Q1EC1FqI6SCQ4954xygwi5bHA71zDoD8Dyn3c@DcTvLKx93xv4nkm6jkMDrp3QiMG0rBCWcAhTezCAxlnkANhUNtan1b5bjGC5nHk1DNmO8i6KVUSWZ0RBwArjDT/Jdvd9HxKuMhg6rrdGWqKcSrfjiILrCmOPuvbAk198ONuOkxbOye11BSEkJA3DsQxD6dg9x4UHeUOhLRIgyV7Qy9vDTYSUoU26vj1H1FWguASsOLTAYbtWuHmmBYl74Ai0Y7Gw4LC/qPaof@R4SghdtWiIZ3o@gW066EWszn0mQlOYzNEW6DZsP4C9Clz@B/Qwuc4lQF9KH0BsUMaLTkgV1HqpdrC7KlYWVijOqDYqRk09LUF7PA4xjoy9ISQsqEYiYSh1uMCd1fc0I0iwkqEiTOZK4bEgTK7ojy0wa/wJ//T9h8bz6/SlPn39wusTYF/Tkb/p9azi9LfalInA6uOGINAvyur807fH2ewf "Numberwang – Try It Online") # [OSH](https://www.oilshell.org/) Oh look, another shell! As per the others the relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` The main difference here is that `$_OVM_PATH` is set in OSH, but not in Bash, so the correct string is `echo`ed using `tr` to remove the `O`. [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRgG/ImzTFvOhiTEaTEyiOASFGKZTsS4kNtVc9a7T3vUBetmZTu/yAvZN8iJ2IdroDAsLs@f8zv98gEtuZjMeWECSnJEz4pYkyaIcPJdXRkzLUmpLlKUI671p27Z5N79u6ckM1odb8@7WJx1E1aVclpVYCSfFjIhR8/LivHFa105q1ePKUfnwoFTc39vdKagoD@mN95sfkVrY2d3bLx4clo8qx9XaiVY/PWucX1w2kTv9uZVCeeXvL5nufDyuyGJcmv7Buez0keH12ACpCJWRhioINZEWczGPWQAYvaKqgWgpQnWUTHDoOWeUG0TIZYPbuYaBOwDLf975NBC/s7C6vjfwPZN0HYcGXDuhUQLTskJYlkKY2oMBNM4iB8CmsjGXVvtuMYLlcubVMGQ7yrsoFossz4iCIGHGG35S7O6NC4k@HgydvrdGWqKSSrfjiILrmLFHXXvgKS8@KduOk5aUU9rrGCEkJA3DsQwDd@ye04cHZQPTFgmQZC/o5e3hJkJ4aJOub88RdRUoLgErDi1w2H0r3DzTgsQ9cATasVhYcNhfVHvUP3I8HEJXLRrimZ5PYJsOehGrc5@J0BQmc7QFug3bD2CvApf/AT1MrnMJ0JfSBxAblPGiE1IFtV6qHeyuipWFFYozqo2KUVNPS9Aej0OMI2NvCAkLqpFIGEodfeDO6nuaESRYyVARJnOl8FgQJlf0xxaYNf6Ef/r@Q@P5dfpSn75@4fUJsK/pyN/0elZx@lttKkRg9XFDEOgXZXX@6dvjbPYP "OSH – Try It Online") # [Python 3](https://docs.python.org/3/) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0 0//1; try:echo -n;print(s[0:23]+"YZ"); except:print(s[0:15]+s[16:]);"""...""" ``` This shares the declaration of `s` with the shells and Rubies and is also shared with xonsh. The code in the `try` will fail in Python (`echo -n`), but works in xonsh so the code in the `except` is called, printing slices of `s`. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLwJcnW2uAHKCIYFBXCYCQRM52SlE0ULXjVu0571wfoZWc6vfMF6Jv4InQTocJMNtlk9pzf@Z@PxL33bpx@ejrlgQUkyRk5I25IkizKwXNxZcS0LKU2RFmKsD4YlmUZd7Prlp6MYH28Ne5ufXKFqLqUy7ISK@GkmBExal6cnzVO6tpxrXpUOSwf7JeKe7s72wUV5SG99mH9E1IL2zu7e8X9g/Jh5ahaO9bqJ6eNs/OLJnImPzdSKK/8/SXTnY/HFVmMS5M/OJedPDG8HnORilAZaaiCUBNpMQfzmAWA4RuqGoiWIlSHyQSHXnJGuUGEXDa47WtwHRdM/2Xn00D8q7nV8T3X9wzStW0acG2HRgkM0wxhWQphag8G0DiNHACbysYcWu37@QgWy5lVw5DNKO@8WCyyPCMKgoQZb3CvWN0bBxJ97A7svrdCWqKSSrfjiIKrmLGGXcv1lFeflG3HSUvKKe1VjBASkp2ObXY6@Mrq2X14VNYwbZEASfaCXrYO1hHCA4t0fWuGqMtAcQFYcmiBw@qb4eaZFiQegCPQjsXCgsP@otqj/qHt4RC6bNEQz/B8Apt00PNYnftMhKYwnqEt0C3YfARrGbj4D@hhcp1LgL6QPoDYoIxXnZAqqPVSbX9nWawsLFFcp9qodGrqSQnao1GIcWTkDSBhQjUSCUOpow/caX1X6wQJljJUhPFMKTwWhPEl/bEFZoU/5p@//9B4fpW@1OevX3h9DOxbOvJ3vZ5ZnPxWmwoRWH3UEAT6RVmdf/72NJ3@Aw "Perl 5 – Try It Online") # [QuadR](https://github.com/abrudz/QuadRS) The relevant code is: ``` ('Q'⎕R'')⎕A⋄'...'⍵ ``` In QuadR, when the final line contains `⍵` all the preceding lines are patterns to match and the final line is a transformation function. This particular transformation function just takes the alphabet `⎕A` and `⎕R`eplaces `'Q'` with `''`, the rest of the function after the statement separator (`⋄`) is just to close off all the other strings/comments/regex literals and comment out the end of the function. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg4FEmukUkE2UWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fyY1nWsPZTAQeEFZSSkrewliRFf@5vFJyUsGJLVnBIdZ707Zt825@3bKT6a@Pt@bdrUfbiKnjTJrHPCZxOSUTVL@8OK@dVvWTSvm4dFQ8PCjk9/d2d3IaykJy48PmDdJyO7t7@/mDw@JR6bhcOdGrp2e184vLOupPf24lUFb9@0thOxuNqoocxdM/JJOePnKiERkgDaEi0lEJoTrSI30iEh4ARq@Yqi9aCFEdxWMCes4Z5gYZMmn/dq5h0B@A5T3vbBKo115Y@5478FyTdhyHBVw7gRGDaVkBrOAAZnZ/ALWz0AHwiXSkz6p9txjBcjnzaji6HeZdFEtkXuRkScKEc4efVLvzvg@xHhkMnZ67Rhuymkg2o4iB64SzRx174KovPpxuRmkDZ9TmOkEISfFWy7FaLdK2u04PHtQNwlqkQONdv5e3h5sIkaFNO549R7RVIL8ErDh032H3rGCLXANi9yBQaEYiQcFBf2HtMf/IcUkAXTVYiGu6HoVtNuhFrCF8plJdmszRBhg2bD@AvQpc/geMILkhxMBYSu9DvF/Gi05A5bRqoXKwuypWlFYooVWulVoV7bQAzfE4wAQ6docQs6AcigShzNED4ay6p7f8BCsZStJkrhQcc9Lkiv3YErcmnohP33/oorjOXtrT1y@iMQH@NRv5m27Xyk9/a3WVSrwxrkkS@6K8IT59e5zN/gE "QuadR – Try It Online") # [Ruby](https://www.ruby-lang.org/) The relevant code is shared with J-uby and goruby: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0 0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end ``` Like the other Rubies, `s` is shared from the shells but in Ruby here, both the other clauses `~:*&?,` and `A` will raise exceptions so the final statement is executed which replaces `R` in `s` with the empty string. [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg4FEmukUKJsoWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fydBr381mIvCAsJJSUvIWxoqs@M/llZKTCk5syQoOsd6btm2bt/Prhp1Mf328MW9vPNpGTB1n0jzmMYnLKZmg@uXFee20qp9Uyselo@LhQSG/v7e7k9NQFpIbHzY/IS23s7u3nz84LB6VjsuVE716elY7v7iso/7051YCZdW/vxS2s9GoqshRPP1DMunpIycakQHSECoiHZUQqiM90ici4QFg9Iqp@qKFENVRPCag55xhbpAhk/Zv5xoG/QFY3vPOJoF67YW177kDzzVpx3FYwLUTGDGYlhXACg5gZvcHUDsLHQCfSEf6rNp3ixEslzOvhqPbYd5FsUTmRU6WJEw4d3in2p33fYj1yGDo9Nw12pDVRLIZRQxcJ5w96tgDV33x4XQzShs4ozbXCUJIirdajtVqkbbddXrwoG4Q1iIFGu/6vbw93ESIDG3a8ew5oq0C@SVgxaH7DrtnBVvkGhC7B4FCMxIJCg76C2uP@UeOSwLoqsFCXNP1KGyzQS9iDeEzlerSZI42wLBh@wHsVeDyP2AEyQ0hBsZSeh/i/TJedAIqp1ULlYPdVbGitEIJrXKt1KpopwVojscBJtCxO4SYBeVQJAhljh4IZ9U9veUnWMlQkiZzpeCYkyZX7MeWuDXxRHz6/kMXxXX20p6@fhGNCfCv2cjfdLtWfvpbq6tU4o1xTZLYF@UN8enb42z2Dw "Ruby – Try It Online") # [Super Stack!](https://github.com/TryItOnline/superstack) The relevant code is: ``` 0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi ``` This pushes `0` and `65` (twice) to the stack, then `if` (which is "while top of stack is truthy" - non-zero), `pop`s the top element, `dup`licates the new top element twice, pushes `83` and `sub`tracts it from the next stack item down. Then `if` top of stack is truthy (e.g. it's not 83 - `S`), `pop` it, `outputascii`, push `0` and terminate with `fi` (since top of stack is now `0`). Finally, `pop`, push `1`, `add` the two top elements together (increment), `dup`licate, push `91` and `sub`tract, terminate the loop, which will happen if the last output char was `90` (`Z`). [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRmH9ikDTFvOhiTEaTEyiOASFWCZTpS4kNtVc9a7T3vUBetmZTu/yAvZN8iJ2IdroDAsLs@f8zv98APFde0g8s3szm/HAAsJSRsqIWxhLohQ8l1dGTEs4tSVKOMJ6b9q2bd7Nr1t6MoP14da8u/VJB1F1nMuymMVKUsyICmpeXpw3TuvaSa16XDkqHx6Uivt7uzsFFeUhvXGz@RGphZ3dvf3iwWH5qHJcrZ1o9dOzxvnFZRMNpj@3Uigv//0l0Z2Px2VJjOPpHyWXnT4yvB5zkYpQGWmoglATabGBwissAIxeUdVAtBShOkomOPScM8oNIuSywe1cgztwwfKfdz4NxO8srAPfc33PJF3HoQHXTmjEYFpWCEs4hKk9GEDjLHIAbCobG9Bq3y1GsFzOvBqGbEd5F8UqIsszoiBghfGGn2S7@34Aib7iDp2@t0ZaopxKt@OIgusKY4@6tuvJLz6cbcdJC@fk9rqCEBKShuFYhqF07J7Thwd5Q6EtEiDJXtDL28NNhJShTbq@PUfUVaC4BKw4tMBh961w80wLEvfAEWjHYmHBYX9R7VH/yPGUELpq0RDP9HwC23TQi1id@0yEpjCZoy3Qbdh@AHsVuPwP6GFynUuAvpQ@gNigjBedkCqo9VLtYHdVrCysUJxRbVSMmnpagvZ4HGIcGXtDSFhQjUTCUOroA3dW39OMIMFKhoowmSuFx4IwuaI/tsCs8Sf80/cfGs@v05f69PULr0@AfU1H/qbXs4rT32pTJgKrjxuCQL8oq/NP3x5ns38 "Super Stack! – Try It Online") # [TacO](https://github.com/TehFlaminTaco/TacO) The relevant code is: ``` @"ABCDEFGHIJKLMNOPQRSUVWXYZ" ``` [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRmH9irBNW8yHJsZoNDGJ4hAixDKdinUhsanmqned9q4P0MvOdHqXF7BvkhexC9FWZ1hYmD3nd/7nAzyz685mIvCAsJJRMvIWxoqsBM/llZHTCk5tyQqOsN6btm2bd/Prlp3MYL2/Ne9ufXqNmDrOZXnMY5KUMzJBrcuL8@Zpo35Sqx5XjsqHB6Xi/t7uTkFDeUhvvNv8gLTCzu7efvHgsHxUOa7WTuqN07Pm@cVlC7nTH1splFf//FTYzsfjqiLH8fQ3yWWnj5yoxwZIQ6iM6qiCUAvVYy4RCQ8AoxdMNRAtRaiOkgkBPeeMcoMMuWxwOzcwcAdg@c87nwbqXy@sru8NfM@kXcdhATdOaMRgWlYIKziEmT0YQPMscgB8KhtzWbVvFiNYLmdeDUe3o7yLYonMi5wsSZhw3vCjanffupDok8HQ6XtrtC2rqXQnjhi4Tjh71LUHnvrfh7OdOG3jnNpZJwghKWkYjmUY5NruOX14UDcIa5ECTfaCXl4fbiJEhjbt@vYc0VaB4hKw4qgHDrtvhVvk2pC4B4FCJxYLCw77i2qP@UeOR0Loqs1CPNPzKWyzQS9ideETlVrSZI62Qbdh@wHsVeDyH6CHyXUhAfpS@gDigzL@64RUQWuUage7q2JlaYUSjGqzYtS00xJ0xuMQE@jYG0LCgmokEoYyRx@Es8Ze3QgSrGSoSJO5UngsSJMr9mNL3Jp4Ij59@14XxXX20p6@fBb1CfAv2chf9XpWcfpLa6lU4vVxU5LYF@V18enr42z2Fw "TacO – Try It Online") # [Unefunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/) The relevant code is: ``` "ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q ``` There are a few commands before this that are executed and push things to the stack, but basically this just pushes the required chars in reverse, then pushes `8` and `3` and multiplies them. The `k` command repeats the next command TOS (`24`) `+ 1` times, outputting the required string and `q`uits. [Try it online!](https://tio.run/##bZLdcppAFMfveYqdhUoSg7B@RaBpi/nQxBgNJiZRHIKysUynSF1ITKq56l2nvesD9LIznd7lBeyb5EXsQrTRGYAF9pzf@Z8PCFx8Hbh9LMgFwbuLXmczHrAAIjkrZ6UthGRJDu/LR1bKyCi9JckoxnpvYYyt2/l5Q3dWeHy8sW5vAtKFVB3lcyxikZqSspIKW5cX583Thn5Srx1XjyqHB@XS/t7uTlGDBZDZ@LD5CWrFnd29/dLBYeWoelyrn@iN07Pm@cVlCw6mP7fSsKD8/SXTVUgmFVlKoukfNZ@bPjK8kfCgBmEF6rAKYQvqiYHKqywAYPSKqoai5RjVUUrg4HPOODeQQD4XXs418AYesIPnVcgAEnQX1kHge4FvkZ7j0IBrJzIiYNl2BMsogqk9HEDzLHYAbDqXGNBq3y1GsFzOvBqGbMd5F8WqEsszkigilfGHdwruvR8AwVW9oeP6a6QtKelMJwkpuK4yeNTDnq@8@FCukyRtlFc66yqEUEyZpmObptrFfccFD8qGSlskgKT6YS9vDzchVIeY9AI8R7RVoLQErDj00IFdO1o80wbCPeAI6CQSUcFRf3HtUf/I8dUIumrTEN/yAwK26aAXsQb3mYgtcTJH28DAYPsB4FXg8j9gRMkNTgDGUvoQYsMyXnQiqqg1yvWD3VWxirhCcWatWTXr2mkZdMbjCOPI2B8CwQa1WCQKpQ4XcGeNPd0ME6xkqIqTuVK0LYqTK/pji8waf8I/ff@h8/w6fWhPX7/wxgSwr@nI3/T7dmn6W2spRGSNcVMU6RdlDf7p2@Ns9g8 "Unefunge-98 (PyFunge) – Try It Online") # [V (vim)](https://github.com/DJMcMayhem/V) + `-v` The relevant code is: ``` <esc>ggdG¬AZ:s/V//"... ``` Which first leaves insert mode (`<esc>`), goes to the first line of text (`gg`), deletes to the last line (`dG`), inserts the letters from `A` to `Z` (`¬AZ`), then finally replaces `V` with the empty string (`:s/V//`). The rest of the line is commented out (`"`). [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KttcEPUEQQFBXCxEgizXQKlE2QWvCqd532rg/Qy850eucL0DfxRegmQoWZbLLJ7Dm/8z8fyXA2E4EHhJWUkpK3MFZkxX8ur5ScVHBiS1ZwiPXetG3bvJtfQ3Yy/fVhaN4NPXqDmDrOpHnMYxKXUzJBjavLi/pZrXpaKZ@UjotHh4X8wf7ebk5DWUhuvN/8iLTc7t7@Qf7wqHhcOilXTqu1s/P6xeVVA/WmP7cSKKv@/aWwnY1GVUWO4ukfkklPHzlRj/SRhlARVVEJoQaqRnpEJDwAjF4xVV@0EKI6iscE9JwzzA0yZNL@7dxCv9cHy3ve2SRQ72Zh7Xlu33NN2nYcFnDrBEYMpmUFsIIDmNn9AdTPQwfAJ9KRHqv27WIEy@XMq@Hodph3USyReZGTJQkTzh18Uu32ux7EuqQ/cLruGm3KaiLZiiIGrhPOHrXtvqu@@HC6FaVNnFFb6wQhJMUNw7EMg9zYHacLD@oGYS1SoPGO38vO0SZCZGDTtmfPEW0VyC8BK46q77C7VrBFrgmxexAotCKRoOCgv7D2mH/kuCSArpssxDVdj8I2G/QiVhc@U6khTeZoE3Qbth/AXgWu/gN6kFwXYqAvpfch3i/jRSegclqtUDncWxUrSiuUYJTrJaOinRWgNR4HmEDH7gBiFpRDkSCUObognNf2q4afYCVDSZrMlYJjTppcsx9b4tbEU/Hp@4@qKK6zl/b09YuoT4B/zUb@ptOx8tPfWkOlEq@P65LEviivi0/fHmezWWz4Dw "V (vim) – Try It Online") # [Wumpus](https://github.com/m-ender/wumpus) The relevant code is: ``` ...#220#1#1;. ..."ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o @ ``` The `#220#1#1` pushes `220`, `1`, `1` to the stack, then `;` pops off the last item then calls `.` which jumps the IP to line 1, char 220 and executes. We need to just because TacO mandates only one `@` in the code. [Try it online!](https://tio.run/##bZLdcppAFMfveYozC5UkRmH9ikDTFvOhiTEaTEyiOASFWKYTpS4kNtVc9a7T3vUBetmZTu/yAvZN8iJ2IdroDAsLs@f8zv98wJ1/4/pkNuOBBYSljJQRtzCWRCl4Lq@MmJZwakuUcIT13rRt27ybX7f0ZAbr5ta8u/VJB1F1nMuymMVKUsyICmpeXpw3TuvaSa16XDkqHx6Uivt7uzsFFeUhvfFh8yNSCzu7e/vFg8PyUeW4WjvR6qdnjfOLyyYaTH9upVBe/vtLojsfj8uSGMfTP0ouO31keD3mIhWhMtJQBaEm0mIDhVdYABi9oqqBaClCdZRMcOg5Z5QbRMhlg9u5BnfgguU/73waiN9ZWAe@5/qeSbqOQwOundCIwbSsEJZwCFN7MIDGWeQA2FQ2NqDVvluMYLmceTUM2Y7yLopVRJZnREHACuMNP8l29/0AEn3FHTp9b420RDmVbscRBdcVxh51bdeTX3w4246TFs7J7XUFISQkDcOxDEPp2D2nDw/yhkJbJECSvaCXt4ebCClDm3R9e46oq0BxCVhxaIHD7lvh5pkWJO6BI9COxcKCw/6i2qP@keMpIXTVoiGe6fkEtumgF7E695kITWEyR1ug27D9APYqcPkf0MPkOpcAfSl9ALFBGS86IVVQ66Xawe6qWFlYoTij2qgYNfW0BO3xOMQ4MvaGkLCgGomEodTRB@6svqcZQYKVDBVhMlcKjwVhckV/bIFZ40/4p@8/NJ5fpy/16esXXp8A@5qO/E2vZxWnv9WmTARWHzcEgX5RVuefvj3OZv8A "Wumpus – Try It Online") # [xonsh](https://xon.sh/) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0 0//1; try:echo -n;print(s[0:23]+"YZ"); except:print(s[0:15]+s[16:]);"""...""" ``` xonsh is a Python based shell so the code is shared with Python 3 and uses the same `s` var as the shells and Rubies. I've used a technique I've used in many polyglots with Ruby to get this code in. `0//1` is integer division and the `echo -n` works fine since xonsh is a shell so the execution of printing the required substring portion of `s` with the literal string `YZ` concatenated, then the rest of the program is a `"""` string. # [yash](https://yash.osdn.jp) The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` Like the other shells, but in yash, the sequence `\e` is not an escape sequence and so is just the string `\e` which matches `e` so `$s` is printed substituting `Y` for the empty string (`${s/Y/}`). [Try it online!](https://tio.run/##bZLdUtpAFMfv8xRnNilREZLlS5KtbYMfoIhgUFQIg5FEzHQKlE0QLXjVu0571wfoZWc6vfMF6Jv4InQToYWZbLLJ7Dm/8z8fyb1Jb2czEXhAWEkpKXkLY0VW/OfySslJBSe2ZAWHWB9M27bNu/k1ZCfTXx@G5t3Qo9eIqeNMmsc8JnE5JRNUv7w4r51W9ZNK@bh0VDw8KOT393Z3chrKQnLj/eZHpOV2dvf28weHxaPScblyoldPz2rnF5d11Jv@2EqgrPrnp8J2NhpVFTmKp79JJj194kQj0kcaQkWkoxJCdaRHekQkPACMXjFVX7QQojqKxwT0kjPMDTJk0v7t3EC/1wfLe9nZJFDvemHteW7fc03adhwWcOMERgymZQWwggOY2f0B1M5CB8An0pEeq/bdYgTL5cyr4eh2mHdRLJF5kZMlCRPOHdyrdvu2B7Eu6Q@crrtGG7KaSDajiIHrhLNHbbvvqv99ON2M0gbOqM11ghCS4q2WY7Va5NruOF14VDcIa5ECjXf8Xt4ebiJEBjZte/Yc0VaB/BKw4tB9h921gi1yDYg9gEChGYkEBQf9hbXH/CPHJQF01WAhrul6FLbZoBexhvCJSnVpMkcbYNiw/Qj2KnD5DzCC5IYQA2MpvQ/xfhn/dQIqp1ULlYPdVbGitEIJrXKt1KpopwVojscBJtCxO4CYBeVQJAhlji4IZ9U9veUnWMlQkiZzpeCYkyZX7MeWuDXxRHz@9l0XxXX20p6/fBaNCfCv2cjfdDpWfvpLq6tU4o1xTZLYF@UN8fnr02w2iw3/Ag "yash – Try It Online") # [Zsh](https://www.zsh.org/) + `--continueonerror` The relevant code is: ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...' [ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' # ``` Zsh is less tolerant of errors in a script than the other shells and so necessitates the `--continueonerror` flag. In Zsh `$status` is also set (in fish too) when a command fails, so if `$status` is `1`, then `$s` is `echo`ed out, substituting `Z` for the empty string (`${s/Z/}`). [Try it online!](https://tio.run/##bZLNcppQFMf3PMWZC5UkBgG/ItC0xXxoYowGE5MojiFCDNMpWC4k1mpW3XXaXR@gy850ussL2DfJi9gL0UZnuHBh7jm/8z8fMMK3s9kI3wLH9VzHt53Ach3L81wPUrYzCPyUb7uzGQs0IFHKSllhSxQlQQqfyysrZCQxvSVIYox1ZFiWZdzPrztyMsL14c64vwvwNSLqYj5Hi7SopISsoKDW5cV587ShndRrx9WjyuFBubS/t7tTVFEBMhvvNz8itbizu7dfOjisHFWPa/UTrXF61jy/uGwhd/pzK40K8t9fEtmFZFKWhKQ4/aPkc9NHitUTA6QiVEEaqiLUQlrCVViFBoDhK6IaipZjVIcpjkHPOePcIEA@F972DQzcAZjB8y5kAAfXC6sb@GSiBu7ZNgm4sSOjCIZpRrAkRjCxhwNonsUOgE7nEi6p9t1iBMvlzKuh8Hacd1GsItAsJfC8qFC@90m2ercucI4y8GzHX8NtQU5nOklEwHWFsoY9a@DLLz4x10nitpiXO@sKQohPdbu22e0q11bfduBB3lBIixhwqh/28vZwEyHFs3AvsOaIugqUloAVhxY6LMeMNku1gRsBg6GTSEQFR/3FtUf8Q9tXIuiqTUJ8ww8wbJNBL2J15jPmW/xkjrZBt2D7AaxV4PI/oEfJdYYDfSl9CNFhGS86EVVUG@X6we6qWIVfoZhurVnt1tXTMnTG4whj8Nj3gDOhFotEocThAHPW2NO6YYKVDFV@MleKjkV@ckV@bJ5aY0/Yp@8/NJZdJy/16esXVp8A/ZqM/E2/b5amv9WWjHlaHzd5nnxRWmefvj3@Aw "Zsh – Try It Online") --- [Validation suite.](https://tio.run/##jZfbdtpGFIbv9RQ7gho5jhDyKQbVbcAn8AkMNo5tvIiQBMgGSdYBjGPnqndd7V0foJddq6t3eQH3TfIi7oxg8MAIUmyk0T979H/a2jNIDdVrv7z0NRA1SJqWE/hJ37Q5LgZZTzPNbdv3OHUzLjgDv21bKyDZji@puEtHXVK93lVNq15POgNq@CJ3BXxc5WET@NzW9s7uXr6wf3B4dFwsnZQrp2fV848XlzxcLywYWtvGoSBkF0EER/U8/vFxSt3NFg7fvOExVA7hcg3E00ANxrEROmb/j2MDhBzrSFTKcUt1ddNSO5w2zsIwCdqoY9yYzIEC@JxDLm3IlfsfXBoIWywXUSmubZwJHTHpUZnQR45b33fUQdhmHYlKORo9s8MZyPFG7amoXjpogKP67WE6cG8YMiMHBiHa/i6RAcIOS0RUiqhpohw0ERFuMDlojh13vufYBGGXdSQq5diy3UYw4MIA1A4aA7BsH1BNnBaKOCCvDjxf1W659vSkaY96xo26ZfRxzYjNGSlrv17A7t78C2iDkGcvgKjUBRS6TsfUTJ8zEV/I5ZlIMoZoVBuCGVQmTZWfS2WCUGCpiEpR7Ysok9wNQtL0YbZusKJAmGHT8g3XcQ20TboNkNp215DcwLIMV5q@6TcTdIV5dDcg7LN0RKXoblGV3SK224giu53025/jdwvCAetHVMrvcMB1pqunM0D/UatsZwrgYDZAB4RDFoCoFEAXX3HYjVtTFX4cdBuG21etFme9LgbOENMad1JxDLM1zXx4NIvZAuGYZSYqxVys5Dmb1LTttaWGaeE9iv6MyOvFEtoeV64@XD/xDJDNAh3PALJBKLJARKWASsPfihXOoe7ltLETYVyMNnZAKLHGRKWMTwJVL3N3JBd36NAdbj00QOh4II4mWVcfqB27Jb2V1lelwDI1WzfgEXwVreKivEjnCXgeykPmuyjmUiTzHQgnLDNRKeYynv8uQg4n/HSW3EjHkyhHF4Qy60hUyrESOIYLFbzUveG88S1aHmbGw72jNXHcjJp@XjRaOQLNA6HCohGVQjtVNZvzEVInUIc4yN2W8JNWEkvTDP4MhgrL4INwyjIQlWI4s4xmYLUMMb3BBWF2wkMQRc/XN9MbqBGMQhieYBbPKcMTgHDG8hCV4qlyPVLQPalHF6Z4D2JvaNybaXw2bdwDocoaE5UyPg@6TuBxfVKbIUI/FEc7/Js0nYL@bJLqFEkfhHOWhKgUyb1tkWU5bE6tywP8QDhAmIOoB8LBHKDzjxNAAxAuWCCiUkAPyPABGaI9KgfNtnzTCgwb/Sy7tssQPMwluKAJHkC4ZAmISgheXhIQA15Or6ZXU@9lOZ1K4y39WU2tpOXl96m0HKE@qIZhqP3RXw8dqfjT7an9XuA1eHR2eX0tJsdkJZlaTSn85cXH8@pppXxSKh4fHR7sF/J7uzvbW7ksvwErb2/f3c15VrOf/3y/zG9k/v0rjb4bS0uZdGpJfv5HWV97/solagsOn@X5A77MH/H8JV9esJWEEgOA@x/mvDjcJ8X4vDesFKyv4X@zCY7tgB4Mvxsr4AUNotqBj25U@E6HBjTNUJRB1fUwOC2HwUjHCaieRSYgtry2YCPaD3OWIbTKzr79l7ySiiW4lCTJCue7g0x400VLcVz0@Cd4V6nM8sr1Eo8CFxXOuNcMx8@89slr10velbyeuV5UeJ6XkvW6qdfrSsNomRZ8ybxV0CV64CVb@Fp@3n/H84preFpgjEKykwF7VMBERxl3GJYefhOosMUHQGs4qd2Zbxuo/970lTDo0xUa4qt@4KEZIY/H1uKfPelSehqFXkHNgM0vYEwGXIwDaqF5LS5CjbLHQTGM8XqeMCqXreRLhe3Jkx1IE1HxerF6VC9lT/NwPZp2ce/Rd/EDQzEyJByKOiyIn1V2ynVsMOFwJD2NzhQe5qSnT6iwJU5InCS@/f5HOZFYRLvst19/SdSeIPYjSvlPrZa@9/x39jLjSbHaY1WS0B2N1RLffvv6Hw "Bash – Try It Online") [Answer] # Arcyou, Braille, COW, Deadfish~, Emoji, Forked, Gaot++, Hyper-Dimensional Brainfuck, 3389 Bytes ``` "BCDEFGHIJKLMNOPQRSTUVWXYZ";11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@&------------------------.+.+.+.+.+.+.++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiciciciicicicicicicicicicicicicicicicicicicicicicich⠆⠄⡒⡆⡘⠀⢕⢍⢅⠽⠵⠭⠥⠝⠕⠍⠅⢼⢴⢬⢤⢜⢔⢌⢄⠼⠴⠬⠤⠜⠌💬ABCDFGHIJKLMNOPQRSTUVWXYZ💬➡MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO Moo MoO MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet bleeeeet ``` Try it online in [Arcyou](https://tio.run/##7ZK7TkJREEV/hVDY3EhCbeP7hYDvVwfEBBKSmxgo7CiAChoiiQXqvhPsrh12@DP7C/yDi6gxCBg1OKMFs@dkcs5J1momdZ65cItBEF5cWl5ZXVvf2IxtxRPJ7Z3dvf2Dw6Pjk9PwXDTq/G3mP/bIww96ZvaTijiDcSJfJzdpZV7yNr6VLFElyvQa9Kr0rogSpUmpUyrEI/FA3BN3xDXRJOpEhdKldCg@pU1pUS4pNUqZ6BIdwifaRIuoPd02/IXnPRi7Bv1P3nhxNxmaHndojnv7/zOdmrhC6fzZexV@g6iBVGHqQJWoWlhFsCJZE63K1oUr07Xx6nx9gYHBQmHisJEYWaw0Zh47kaFpRPV6KwRBDw "Arcyóu – Try It Online"), [Braille](https://tio.run/##7ZK7TgJREIZfhVDYbCChtvF@R/AudqwhcZNNSAwPYAFU0BBJLFD/nWC3dtjBy/xP4Bus1xiVJWpwRgvmn5PJOSf5vmbc06Ln@6UoSs7NLywuLa@srq1vZDdz@a3tnd29/YPDwlFyOpNx/jYzH3vo4Qc9lRpRaed9nPTX8cat4@e8jm/lhKgTVQYtBnUGF8QZpU1pUmrEgLgjbokb4pJoE02iRulTepSQ0qV0KOeUBqVK9IkeERJdokM07q9b4ezjHsSuwdMnr4JsOZeYnPKnGff2/6dbHLsSrl96q8pvEDWQKkwdqBJVC6sIViRrolXZunBlujZena8vMDBYKEwcNhIji5XGzGMnMjQNqV5ulSh6AA "Braille – Try It Online"), [COW](https://tio.run/##7ZK7TkJREEV/hVDY3EhCbeMbHyC@ATshJpqY3IbElgKooCGSWKDuO4Hu0kGHP7O/wD@44CNGBIMGZrBw9pxMzjnJWs3k3JsgCK@urW9sxra2d3bjib3k/sHh0fHJaSqdOQsvRaPOfLM83CMPv@iFxW8q4nyOE5mcq2kr95r38aNcEmWiSK9Gr0zvjihQ6pQqpUQ8EV2iTbSIe6JOVIkSpUfpUHxKk9Kg3FIqlCLRIzqETzSJBlF5fqz5K4M9GLsGL5988BJuMvR/3C9z3Nvfn9nzqSuUvb74qPwsiBpIFaYOVImqhVUEK5I10apsXbgyXRuvztcXGBgsFCYOG4mRxUpj5rETGZpGVG@3fBD0AQ "COW – Try It Online"), [Deadfish~](https://tio.run/##7ZK7TkJREEV/hVDY3EBCbaPiWxDBJ3YgGEhIKOQDLIAKGgKJBeq@E@wuHXb4M/sL/IPrM0YBIwZntHD2nEzOOclazeTymdxp8awQ8v3gUnR5ZXVtfWNzKxbfTuwkU7t7@weHR@nj4Hwk4vxuFj722MM3ei70SYWd93HCX6c4a50853VMlQJRJ6p0W3TrdC@Ic0qH0qTUiDvilugTN8Ql0SGaRI0ypAwoHqVH6VLalAalSgyJAeERPaJLNO6vW97i4x5MXIOnT1658XIi8H/KI3PS29@f2czMFciW8m9V@QmiBlKFqQNVomphFcGKZE20KlsXrkzXxqvz9QUGBguFicNGYmSx0ph57ESGpjHVy63i@w8 "Deadfish~ – Try It Online"), [Emoji](https://tio.run/##7ZI9TkJREIW3QihsXiShplERwR9E8A/txJCI0byGBVgAFTQEEguU8ybQPTvscDNnBe7gqWCMCkYNzmjhnLmZ3HuT72umeO6eloIgvBRfTqwkU6tr6xvpzcxWNre9s7u3nz84DMeiUed3s/C2Jx6@0XPzH1TEeR0n8nlKs9bxKM/jSzkhakSFXpNejd4lcUFpUxqUKnFH3BI3RJ@4ItpEg6hShpQBxaf0KB1Ki1KnVIghMSB8okd0iPp9t@kvPu7B1DV4@uS1l3Yzof/jvpvT3v7@LBzNXKHCWfGlyj9B1ECqMHWgSlQtrCJYkayJVmXrwpXp2nh1vr7AwGChMHHYSIwsVhozj53I0DShGt/KQfAA "Emoji – Try It Online"), [Forked](https://tio.run/##7ZK7TkJREEV/hVDY3EhCbeP7gSK@X508DESSmxg@gAKooCGSWADuO8Hu2mGHP7O/wD@4ihqigkGDM1o4e04m55xkrWbO3IvzTDoIwvMLi0vLK6trsfWN@GZia3tnd2//4PDo@CQ8E406v5vZ9z308I2emv6kIs7bOJHxyU1aqee8ji8lS1SIEr06vQq9K6JIaVBqlDJxT9wRt8QN0SIaRI0oU3qULsWndChNyiWlSikRPaJL@ESHaBLVh@u6P/e0ByPXoP/Jthd3E6H/436Yo97@/kyeTlyhZD4zqMJPEDWQKkwdqBJVC6sIViRrolXZunBlujZena8vMDBYKEwcNhIji5XGzGMnMjQNqV5uhSB4BA "Forked – Try It Online"), [Gaot++](https://tio.run/##7ZK7TgJREIZfhVDYbCShtlG8IgLebx0QoyYmS7EPYAFU0BBJLFD/nUC3dtjhy/xP4BusisbIxSiBGS2cf04m55zk@5o5zblesRiG0cTi0vLK6lpyPbWRzmQ3t7Z3dvf2Dw6PjqNz8bjzu5nv76GHMXpm9ouKOZ/jxL7P@aRV6OV9/ChnRIUo0a/Tr9C/Ji4pDUqNUiYeiQfinmgTN0SDqBFlSpfSoQSUFqVJuaJUKSWiS3SIgGgRTaL6dFcPFl72YOQavH7y1k@72cj/cQfmqLe/P/O5iSuSvzj5KG8aRA2kClMHqkTVwiqCFcmaaFW2LlyZro1X5@sLDAwWChOHjcTIYqUx89iJDE1DqrebF4bP "Gaot++ – Try It Online"), and [Hyper-Dimensional Brainfuck](https://tio.run/##7ZI9TkJREIW3QihsXiShtsFfFET8F@18gsHEhIYFWAAVNEQSC9TzJtg9OuhwM2cF7uCJYIwKRA3OSOGcuZnce5Pvayafdc@DILy0vLK6Fl/fSCQ3U1vp7Z3dvf2Dw6PM8Ul4IRp1/jaxjz3y8IOem59QEed9nMjXuZi2zgZ5Hd9KnqgQJXp1ehV6N8QVpUGpUcrEI9El2sQDcUs0iBpRpvQoHYpPaVGalGtKlVIiekSH8IkW0SSqT/d1f7G/B2PX4OWTd16qkA79n8KnOe5t9qd7OnWF3MvcWxV/g6iBVGHqQJWoWlhFsCJZE63K1oUr07Xx6nx9gYHBQmHisJEYWaw0Zh47kaFpRDW8FYPgGQ "Hyper-Dimensional Brainfuck – Try It Online"). I'll explain each part below: ### Arcyou ``` "BCDEFGHIJKLMNOPQRSTUVWXYZ"; ``` Implicitly prints the string, and ignores everything afterwards with a comment `;`. ### Braille ``` ⠆⠄⡒⡆⡘⠀⢕⢍⢅⠽⠵⠭⠥⠝⠕⠍⠅⢼⢴⢬⢤⢜⢔⢌⢄⠼⠴⠬⠤⠜⠌ ``` All non braille symbols are ignored, so this is an easy choice. ### COW ``` MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO Moo MoO MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo ``` All non-moo tokens are ignored, making this easy as well. We also use a moo-exit (`Moo`) so that if we accidentally have a moo token in the future we don't run it. ### Deadfish~ ``` iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiciciciicicicicicicicicicicicicicicicicicicicicicich ``` Uses `i` to increment, `o` to output, and `h` to halt meaning we don't interpret future tokens. ### Emoji ``` 💬ABCDFGHIJKLMNOPQRSTUVWXYZ💬➡ ``` All non-emoji tokens are ignored, making this another easy choice. ### Forked ``` 11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@& ``` This language has a lot of tokens, but halts on `&` meaning we can put in it early. The `"BCDEFGHIJKLMNOPQRSTUVWXYZ";` in front from Arcyou acts as a no-op. ### Gaot++ ``` baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet bleeeeet ``` All non-sheep tokens are ignored, making this another easy choice. I hope the cows and the sheep can get along. ### Hyper-Dimensional Brainfuck ``` 11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@&------------------------.+.+.+.+.+.+.++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+. ``` Basically brainfuck with some extra command we can ignore. Notice we use part of the Forked solution as a starter. [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), [Brainfuck](https://github.com/TryItOnline/brainfuck), [Canvas](https://github.com/dzaima/Canvas), 127 bytes ``` 밤밦뚜 나타뺘우차빠빠빠 떠벓벓벅멓더희뎌 >+[+[<]>>+<+]>.+>>++++[<++++++>-]<[<+.>-] ABDEFGHIJKLMNOPQRSTUVWXYZ ``` Try it online in [Aheui](https://tio.run/##S8xILc38///1hiWvNyx7PWsO1@umGW@bG17vmvFm1oY3G1a83rkAgrheT1vwetNkMGp9vXLy694pb@eued3Xw2WnHa0dbRNrZ6dtox1rp6cNZABBtI02GNjpxtoA2XpAmsvRycXVzd3D08vbx9fPPyAwKDgkNCw8IjLq/38A "Aheui (esotope) – Try It Online"), [Brainfuck](https://tio.run/##SypKzMxLK03O/v//9YYlrzcsez1rDtfrphlvmxte75rxZtaGNxtWvN65AIK4Xk9b8HrTZDBqfb1y8uveKW/nrnnd18Nlpx2tHW0Ta2enbaMda6enDWQAQbSNNhjY6cbaANl6QJrL0cnF1c3dw9PL28fXzz8gMCg4JDQsPCIy6v9/AA "brainfuck – Try It Online"), and [Canvas](https://tio.run/##S07MK0ss/v//9YYlrzcsez1rDtfrphlvmxte75rxZtaGNxtWvN65AIK4Xk9b8HrTZDBqfb1y8uveKW/nrnnd18Nlpx2tHW0Ta2enbaMda6enDWQAQbSNNhjY6cbaANl6QJrL0cnF1c3dw9PL28fXzz8gMCg4JDQsPCIy6v9/AA "Canvas – Try It Online")! Just a trivial solution of three languages which ignore each other's code entirely. * Aheui ignores all non-Korean(Hangul) characters. * Brainfuck ignores all characters that are not Brainfuck instructions `+-.,<>[]`. * Canvas treats all ASCII characters as string literals and prints the last line. [Answer] # [axo](https://esolangs.org/wiki/Axo), [Befunge-93](https://github.com/catseye/Befunge-93), [Canvas](https://github.com/dzaima/Canvas), [Deadfish~](https://github.com/TryItOnline/deadfish-), 104 bytes ``` "%A","EDC",,,"F">::,"Z"-| {>B">[[("Z"-#%\{i}}dddci@ cici^icici +1<{c^i}{ci+1<} ABDEFGHIJKLMNOPQRSTUVWXYZ ``` [Try axo online!](https://tio.run/##S6zI//9fSdVRSUfJ1cVZSUdHR8lNyc7KSkcpSkm3hqvazknJLjpaA8RTVo2pzqytTUlJSc504ErOTM6MywSRCtqGNtXJcZm11cmZQGYtl6OTi6ubu4enl7ePr59/QGBQcEhoWHhEZNT//wA "axo – Try It Online") [Try Befunge-93 online!](https://tio.run/##S0pNK81LT/3/X0nVUUlHydXFWUlHR0fJTcnOykpHKUpJt4ar2s5JyS46WgPEU1aNqc6srU1JSUnOdOBKzkzOjMsEkcnahjbVyXGZtdXJmUBmLZejk4urm7uHp5e3j6@ff0BgUHBIaFh4RGTU//8A "Befunge-93 – Try It Online") [Try Canvas online!](https://tio.run/##S07MK0ss/v9fSdVRSUfJ1cVZSUdHR8lNyc7KSkcpSkm3hqvazknJLjpaA8RTVo2pzqytTUlJSc504ErOTM6MywSRydqGNtXJcZm11cmZQGYtl6OTi6ubu4enl7ePr59/QGBQcEhoWHhEZNT//wA "Canvas – Try It Online") [Try Deadfish~ online!](https://tio.run/##S0lNTEnLLM7Q/f9fSdVRSUfJ1cVZSUdHR8lNyc7KSkcpSkm3hqvazknJLjpaA8RTVo2pzqytTUlJSc504ErOTM6MywSRydqGNtXJcZm11cmZQGYtl6OTi6ubu4enl7ePr59/QGBQcEhoWHhEZNT//wA "Deadfish~ – Try It Online") ## Explanations ### axo ``` "% >B">[[("Z"-#%\ ^ +1< ``` It activates stringmode, pushes the B, then starts printing and incrementing that B until it's a Z. ### Befunge-93 ``` "%A","EDC",,,"F">::,"Z"-| @ ^ +1< ``` Print ACDE, push an F, print and increment it until it's a Z. ### Canvas Canvas prints the last line. ### Deadfish~ ``` {{i}}dddciciciicicic{ci}{ci} ``` [Answer] # [AlphaBeta](https://github.com/TryItOnline/alphabeta), [brainfuck](https://github.com/TryItOnline/brainfuck), [Cauliflower](https://github.com/broccoli-lang/broccoli), [Dreaderef](https://github.com/ScratchMan544/Dreaderef), [emotifuck](https://github.com/Romulus10/emotif___), 413 bytes ``` ebbbkiigZUaCILQ++++++++[>++++++++<-]>+.+<+++++[<+++++>-]<-[->>+.<<]deref16 4deref?7bool?9?7 13chro?add1 21 16deref100-1"abcefghijklmnopqrstuvwxyz"\;(print abdefghijklmnopqrstuvwxyz)🔥😂😂😂😂😂😂😂😂🌚🔥😂😂😂😂😂😂😂😂💯💩🐸🔥😂💞😂💞😂💞😂💞😂💯😂😂😂🌚💯😂😂😂😂😂😂😂🔥💩🐸💯🌚💩🔥🔥😂💞💯💯🐸 ``` Try [AlphaBeta](https://tio.run/##S8wpyEhMSi1J/P8/NSkpKTszMz0qNNHZ0ydQGwqi7WAsG91YO209bRuIMISy04210Y3WtQNK2NjEpqQWpaYZmimYgBn25kn5@Tn2lvbmCobGyRlF@faJKSmGCkaGCoZmEJUGBrqGSolJyalp6RmZWdk5uXn5BYVFxSWlZeUVlVVKMdYaBUWZeSUKiUkp2JVofpg/ZemH@TOa8OOeWcSpm7QeiFd@mD9hB0L9pHkE6PWYdqGLoWOQ2TB7QGrBelZCxJHtBbtnPUjd//8A "AlphaBeta – Try It Online"), [brainfuck](https://tio.run/##SypKzMxLK03O/v8/NSkpKTszMz0qNNHZ0ydQGwqi7WAsG91YO209bRuIMISy04210Y3WtQNK2NjEpqQWpaYZmimYgBn25kn5@Tn2lvbmCobGyRlF@faJKSmGCkaGCoZmEJUGBrqGSolJyalp6RmZWdk5uXn5BYVFxSWlZeUVlVVKMdYaBUWZeSUKiUkp2JVofpg/ZemH@TOa8OOeWcSpm7QeiFd@mD9hB0L9pHkE6PWYdqGLoWOQ2TB7QGrBelZCxJHtBbtnPUjd//8A "brainfuck – Try It Online"), [Cauliflower](https://tio.run/##S04szclMy8kvTy36/z81KSkpOzMzPSo00dnTJ1AbCqLtYCwb3Vg7bT1tG4gwhLLTjbXRjda1A0rY2MSmpBalphmaKZiAGfbmSfn5OfaW9uYKhsbJGUX59okpKYYKRoYKhmYQlQYGuoZKiUnJqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVUox1hoFRZl5JQqJSSnYlWh@mD9l6Yf5M5rw455ZxKmbtB6IV36YP2EHQv2keQTo9Zh2oYuhY5DZMHtAasF6VkLEke0Fu2c9SN3//wA "Cauliflower – Try It Online"), [Dreadref](https://tio.run/##SylKTUxJLUpN@/8/NSkpKTszMz0qNNHZ0ydQGwqi7WAsG91YO209bRuIMISy04210Y3WtQNK2NjEgk0yNFMwATPszZPy83PsLe3NFQyNkzOK8u0TU1IMFYwMFQzNICoNDHQNlRKTklPT0jMys7JzcvPyCwqLiktKy8orKquUYqw1Cooy80oUEpNSsCvR/DB/ytIP82c04cc9s4hTN2k9EK/8MH/CDoT6SfMI0Osx7UIXQ8cgs2H2gNSC9ayEiCPbC3bPepC6//8B "Dreaderef – Try It Online"), [emotifuck](https://tio.run/##S83NL8lMK03O/v8/NSkpKTszMz0qNNHZ0ydQGwqi7WAsG91YO209bRuIMISy04210Y3WtQNK2NjEpqQWpaYZmimYgBn25kn5@Tn2lvbmCobGyRlF@faJKSmGCkaGCoZmEJUGBrqGSolJyalp6RmZWdk5uXn5BYVFxSWlZeUVlVVKMdYaBUWZeSUKiUkp2JVofpg/ZemH@TOa8OOeWcSpm7QeiFd@mD9hB0L9pHkE6PWYdqGLoWOQ2TB7QGrBelZCxJHtBbtnPUjd//8A "emotifuck – Try It Online") online! --- ### AlphaBeta The relevant part is ``` e ;add 100 to register 1 bbb ;subtract 3 from register 1 (=97) k ;add 100 to register 2 ii ;add 20 to register 2 g ;add 1 to register 2 (=121) ZU ;add 10 to position register ;loop: prints 'bcd...xyz' a ;add 1 to register 1 C ;set value of register to register 1 I ;set value of memory to register 3 L ;print value in memory as char Q ;if reg1 <= reg2, jump to stored position (10) ``` There are no comments in *AlphaBeta*, which means most uppercase letters need to be avoided, as they break stuff and errors are printed to *stdout*. ### brainfuck ``` ++++++++[>++++++++<-]>+ ;calculate 65 .+ ;print A and increment <+++++[<+++++>-]<- ;push 24 [->> <<] ;24 times: +. ; increment and print ``` Since brainfuck ignores any other characters, this doesn't cause any further issues. ### Cauliflower I haven't found any good documentation on this language, so this was mostly trial and error: ``` \; ;escaped comment? (print abdefghijklmnopqrstuvwxyz) ;print string ``` ### Dreaderef The relevant part is ``` deref16 4deref?7bool?9?7 13chro?add1 21 16deref100-1"abcefghijklmnopqrstuvwxyz"\; ``` This is adapted from the Hello World in the [documentation](https://github.com/ScratchMan544/Dreaderef). The `;` comments out the rest of the line. ### emotifuck ``` 🔥😂😂😂😂😂😂😂😂🌚🔥😂😂😂😂😂😂😂😂💯💩🐸🔥😂💞😂💞😂💞😂💞😂💯😂😂😂🌚💯😂😂😂😂😂😂😂🔥💩🐸💯🌚💩🔥🔥😂💞💯💯🐸 ``` is equivalent to the brainfuck program ``` ++++++++[>++++++++<-]>+.+.+.+.+<+++[<+++++++>-]<[->>+.<<] ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), [Bash](https://www.gnu.org/software/bash/), 68 bytes ``` echo ACDEFGHIJKLMNOPQRSTUVWXYZ END{print"BCDEFGHIJKLMNOPQRSTUVWXYZ"} ``` [Try it online (AWK)!](https://tio.run/##SyzP/v8/NTkjX8HR2cXVzd3D08vbx9fPPyAwKDgkNCw8IjKKy9XPpbqgKDOvRMkJlxql2v//AQ "AWK – Try It Online") [Try it online (Bash)!](https://tio.run/##S0oszvj/PzU5I1/B0dnF1c3dw9PL28fXzz8gMCg4JDQsPCIyisvVz6W6oCgzr0TJCZcapdr//wE "Bash – Try It Online") ]
[Question] [ I noticed a certain game had a peculiar life counter, which instead of stopping at `999`, gained a new digit – the next number was *crown* hundred or `👑00`. After `👑99` came *crown hundred crownty* (`👑👑0`) and the last number, after `👑👑9`, was *crown hundred crownty crown* or `👑👑👑`, which would be 1110 in decimal. Your task is to write a [program or a function](https://codegolf.meta.stackexchange.com/a/2422/60340) that [outputs](https://codegolf.meta.stackexchange.com/q/2447/60340) this counter. Given an integer from the range `[0,1110]` (inclusive on both ends), output a three character string where * every character is from the list `0123456789👑` * the crown (👑) can only appear as the leftmost character or when there's a crown to the left of it * when this number is read as a decimal number but with the crown counting as `10`, you get back the original number ## Test cases ``` 0 → "000" 15 → "015" 179 → "179" 999 → "999" 1000 → "👑00" 1097 → "👑97" 1100 → "👑👑0" 1108 → "👑👑8" 1110 → "👑👑👑" ``` You may use any non-decimal character instead of the crown. To encourage pretty printing, the crown character (UTF8 byte sequence "\240\159\145\145") counts as one byte instead of four. Your program doesn't have to work for numbers outside the valid range. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer, measured in bytes, wins! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 50 bytes ``` f=(n,p=1e3)=>n<p?(n+p+'').slice(1):'#'+f(n-p,p/10) ``` [Try it online!](https://tio.run/##bc1NCoMwFATgfU8RzCIJ/r1HEU2p7VnExqKEJDSl17dZmAqmMIuBj2GW4TP48TW7d2nsQ61TH8JN4XpUZ9HfzNXducldzpiovJ5HxVFcGGX5xE3pClcjiHW0xlutKm2ffOKEEBCC1DXJACA7HRWbqNgkiq3cNLREpYwa2lExvG1K018E2UaVbaK4byn80e6nXaq4b2m2fgE "JavaScript (Node.js) – Try It Online") TIO was based on Arnauld's answer. Show 👑 as `#`. [Answer] # JavaScript (ES6), ~~ 62 46 ~~ 44 bytes *Saved 2 bytes thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)* Outputs crowns as `x` characters. ``` n=>(n+1e4+'').replace(/1+0/,'xxx').slice(-3) ``` [Try it online!](https://tio.run/##bc1NCsMgFATgfU8h2UTJj@/RBuMivUuwpqSIhqQUb29dxAZid8N8DPMaP@Om1nl5N9Y9dJiGYIc7tRXqW1WWrF31YkalKccKeF1672O5mTlWzZUF5ezmjG6Ne9KJEkKAMcI5KQCguJwVu6TYZYpC7hpTplImjemsGN929fkvghRJpcgUj62HP9r/tM8Vj60vwhc "JavaScript (Node.js) – Try It Online") ### How? We add \$10000\$ to the input, coerce it to a string, look for the `/1+0/` pattern and replace it with `xxx`. Finally, we return the 3 trailing characters. *Examples:* $$\begin{align}&0 &\rightarrow &\text{ "}\color{red}{\text{10}}\text{000"} &\rightarrow &\text{ "xxx000"} &\rightarrow &\text{ "000"}\\ &123 &\rightarrow &\text{ "}\color{red}{\text{10}}\text{123"} &\rightarrow &\text{ "xxx123"} &\rightarrow &\text{ "123"}\\ &1023 &\rightarrow &\text{ "}\color{red}{\text{110}}\text{23"} &\rightarrow &\text{ "xxx23"} &\rightarrow &\text{ "x23"}\\ &1103 &\rightarrow &\text{ "}\color{red}{\text{1110}}\text{3"} &\rightarrow &\text{ "xxx3"} &\rightarrow &\text{ "xx3"}\\ &1110 &\rightarrow &\text{ "}\color{red}{\text{11110}}\text{"} &\rightarrow &\text{ "xxx"} &\rightarrow &\text{ "xxx"} \end{align} $$ [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~763~~ ~~692~~ ~~690~~ ~~689~~ 683 bytes ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Ajax:You big big cat.Scene V:.Ajax:Remember the remainder of the quotient betweenI twice the sum ofa cat a big big cat.Ford:You be the quotient betweenyou twice the sum ofa cat a big big cat.Ajax:You be the sum ofyou a pig.Be you nicer zero?If solet usScene V.Ford:You big big cat.[Exit Ajax][Enter Page]Page:Recall.Ford:You be I.Scene X:.Page:Recall.Am I nicer zero?If notopen heart.If notlet usScene L.Ford:You big big big big big cat.Speak thy.Am I worse a cat?If soyou zero.Scene L:.[Exit Page][Enter Ajax]Ford:You be the sum ofyou a pig.Is you nicer a cat?[Exit Ajax][Enter Page]Ford:If solet usScene X. ``` [Try it online!](https://tio.run/##jVJLa4QwEP4r0/sS@rjlUrawBcFDaaFsWTxEndW0mthkxLV/3iZRaNZtoYcEMzP5XtF2zTRt2PZdnDbsUZtyw55Eha5SECScvRSo0H8cdorQgB8EoUrws5nfeCotoQLSVI9Xvs/fdA@5rMIqBC0grzzQ8Gdssc0dFtUIBlshVelO@hgKn70miYogRxoQVQI0yAJDz/atGxMeE8QZQxASaPFXlNG1/oPzIz@e9LcFdLJiDwj@oBySgS80@j45gtUNEvR2sRmJiZAPu5OkEF@2ROlzzvzmEilE05yZSJbQ9pzFI9sWkhW70qQ7l3@NwhCbC7Ge9FJPvML7dCg@nN9xxh@0sQghntmet@zpFk0pX9wEB9GPka2fYR1fYqP4ZoI/cglIF9nu2TTdXN/efQM) Uses `" "` instead of crowns. At the cost of 4 more bytes, this could be modified to show a "visible" character instead. ## Explanation: ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford] Boilerplate, introducing the characters. Ford:Listen tothy! Input a value to Ajax. Ajax:You big big cat. Set Ford's value to 4 (we will be pushing 4 digits from Ajax onto Ford's personal stack). Scene V:.Ajax:Remember the remainder of the quotient betweenI twice the sum ofa cat a big big cat.Ford:You be the quotient betweenyou twice the sum ofa cat a big big cat. DIGIT-PUSHING LOOP: Push Ajax's last digit onto Ford's stack; divide Ajax by 10. Ajax:You be the sum ofyou a pig.Be you nicer zero?If solet usScene V. Decrement Ford; loop until Ford is 0. Ford:You big big cat. Set Ajax's value to 4 (we will pop 3 digits from Ford's stack in the next loop). [Exit Ajax][Enter Page]Page:Recall.Ford:You be I. Pop the top value off Ford's stack, and store that into Page. Here, Page will contain 0 if there are no crowns to be drawn, and 1 if there are crowns to be drawn. Scene X:.Page:Recall.Am I nicer zero?If notopen heart.If notlet usScene L. DIGIT-DRAWING LOOP: Pop the top value off of Ford's stack and set Ford equal to that value. If there are no crowns to be drawn, output Ford's literal value here, and skip the crown-drawing section. Ford:You big big big big big cat.Speak thy.Am I worse a cat?If soyou zero. Draw crown. If we are drawing crowns, and Ford contains 0 here, then we are now done drawing crowns, and thus we store 0 into Page. (Put in one more "big" for the crown to look like an @ symbol.) Scene L:.[Exit Page][Enter Ajax]Ford:You be the sum ofyou a pig.Is you nicer a cat?[Exit Ajax][Enter Page]Ford:If solet usScene X. Decrement Ajax; loop until Ajax is 1 (i.e. 3 times). ``` [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes Hats off to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for **-22 bytes**. Recursion still wins, though. ``` lambda k:re.sub("1+0","CCC",`k+10000`)[-3:] import re ``` [Try it online!](https://tio.run/##TY7LasMwEEXX8VcMs5KJEqS2wbHA7UJ0231xDXnJ1E1iGUmBFvrv7lh2TLW5nHvmgrqf8Gnbh74uPvrL/no47eGsnFn724GhXArkqLVGvjsvpaC3S8vVo6qS5tpZF8CZPhgfPBRQMsEBAOkIU54smNyMLDcTZzkVSDFynkemmDwtOaCe9yLPBs6zieXotZh5G3l7Zzl6jWmVJLV1MPwNmjamV8mic00bwAfHhqYUVbp2Xzcf2FNKy9UzcqhnRc0vvH535hjMSZGKQlax19Y5Ei8KSOC78QhN/W8MRXG/B3PxBvDNYv8H "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 51 bytes This instead implements [tsh's recursive method](https://codegolf.stackexchange.com/a/171863/59487). Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). ``` f=lambda n,p=1000:n/p and'C'+f(n-p,p/10)or`n+p`[1:] ``` [Try it online!](https://tio.run/##TY7LasMwEEXX8VcMs4lElEYqDY4Fahem2@6LMcSpJeqSykJSoYX@uys/Yrq6nHvmwrif@N7b@2Ew6tp8XtoGLHNKcM6lPThobLsttztD7N4xdxCc9v5sd@5cCVkPUYcYQEFFOAMATCukLNsQcZxZHBfOi1RgipmLYuIUi09LBliue17kIxf5wmL2JV/5NPHpxmL2JdI6y0zvYfwNOjtlkNnG@c5GCNGTsal4Te/8x1eI5IGm5f4RGZhVpeYXnr@dfou6lUlNQtRTX/beJ/EkIQl81QGhM//GoNTtHvQ1aMCXHoc/ "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` lambda n:['%03d'%n,'%3s'%`n`.lstrip('1')[1:]][n>999] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlpd1cA4RV01T0dd1bhYXTUhL0Evp7ikKLNAQ91QXTPa0Co2NjrPztLSMvZ/QVFmXolCmoahoaGBJheMB5RCcAwNLJB5yOoMDRFsI83/AA "Python 2 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes ``` \b((.)|..)\b $#2$*00$& T`d`_#`(?=....)1+0 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JklDQ0@zRk9PMyaJS0XZSEXLwEBFjSskISUhXjlBw95WDwg0DbUN/v834DI05TI0t@SytLTkMjQwAPINLM25DA1BLEMDCyBhaAAA "Retina 0.8.2 – Try It Online") Uses `#`s instead of `👑`s. Link includes test cases. Explanation: ``` \b((.)|..)\b $#2$*00$& ``` Pad 1- and 2-digit numbers to three digits. ``` T`d`_#`(?=....)1+0 ``` Change leading `1`s of 4-digit numbers to `#`s and delete the next `0`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) - 0 = 19 ``` <ȷ¬ȧDi0ɓ⁶ẋ⁹Ḋ;+ȷDḊṫʋ ``` A full program printing the result using a space character as the crown. (As a monadic Link a mixed list of integer digits and space characters is yielded) **[Try it online!](https://tio.run/##ATMAzP9qZWxsef//PMi3wqzIp0RpMMmT4oG24bqL4oG54biKOyvIt0ThuIrhuavKi////zExMDg "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/mxPZDa04sd8k0ODn5UeO2h7u6HzXufLijy1r7xHYXIP1w5@pT3f8Ptz9qWhP5/7@BjqGpjqG5pY6lpaWOoYEBkG9gaa5jaAhiGRpYAAlDAwA). ...maybe a recursive implementation will be shorter. ### How? ``` <ȷ¬ȧDi0ɓ⁶ẋ⁹Ḋ;+ȷDḊṫʋ - Main Link: integer, N e.g. 1010 or 10 ȷ - literal 1000 1000 1000 < - less than? 0 1 ¬ - logical not 1 0 D - to decimal list [1,0,1,0] [1,0] ȧ - logical and [1,0,1,0] 0 0 - literal zero 0 0 i - first index - call this I 2 1 (0 treated as [0] by i) ɓ - new dyadic chain with swapped arguments - i.e. f(N, I) ⁶ - literal space character ' ' ' ' ⁹ - chain's right argument 2 1 ẋ - repeat [' ',' '] [' '] Ḋ - dequeue [' '] [] ʋ - last four links as a dyad - i.e. f(N, I) +ȷ - add 1000 2010 1010 D - to decimal list [2,0,1,0] [1,0,1,0] Ḋ - dequeue [0,1,0] [0,1,0] ṫ - tail from index (I) [1,0] [0,1,0] ; - concatenate [' ',1,0] [0,1,0] - implicit print " 10" "010" ``` [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` lambda n:'%3s'%`10000+n`.lstrip('1')[1:] ``` [Try it online!](https://tio.run/##TY/RSsMwFIav16c4HBhNWB2JOroEqhfirfdSC5suZZWaliSCgu9eT9OuLDeH7//ODyf9bzh39naoi7ehPX69n45gdbq@8@n6IAW9jT1sWx9c07NUpryUuhqC8cFDASUTGQAgrSHPkhWTu4nlbuZcUYA0JlYqMo3ZUzMDhKUvVD6yymeWkwex8D7y/sJy8oC8SpK6czDeBo2N0@tk1bvGBqAPsDEpRcW37vPbB3bPqXnzgBnUi6LkD55/evMRzEmTikJWMX/qnCPxqIEEvhqP0NRXZSiKyz6Y1hvAlw6Hfw "Python 2 – Try It Online") Implements an idea similar to [Mr. Xcoder's regex-based answer](https://codegolf.stackexchange.com/a/171864/20260) but without a regex. We remove leading 1's in `10000+n` as well as the next character, then pad with spaces to length 3. The result is similar to [ovs's solution](https://codegolf.stackexchange.com/a/171877/20260) using `lstrip` but without needing two cases. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₄‹i₄+¦ëTð.;„1 „ : ``` Uses spaces for crowns. [Try it online](https://tio.run/##yy9OTMpM/f//UVPLo4admUBK@9Cyw6tDDm/Qs37UMM9QAUgoKFj9/29oYGAIAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr0S56O2SQoKSvb/HzW1PGrYmQmktA8tO7w65PAGPetHDfMMFYCEgoLV/1p1Jb3DO3T@G3AZApEpl6G5JZcFkGlpaQkUMQAJGxiCCBAXpMTA0pzL0BAkYQiSMDSwABKGBgA). **Explanation:** ``` ₄‹i # If the (implicit) input is smaller than 1000: ₄+ # Add 1000 to the (implicit) input ¦ # And remove the leading 1 (so the leading zeros are added) # i.e. 17 → 1017 → "017" ë # Else: Tð.; # Replace the first "10" with a space " " # i.e. 1010 → " 10" # i.e. 1101 → "1 1" # i.e. 1110 → "11 " „1 „ : # Replace every "1 " with " " (until it no longer changes) # i.e. " 10" → " 10" # i.e. "1 1" → " 1" # i.e. "11 " → " " ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 87 bytes Doesn't output crowns (uses `c`). ``` import StdEnv,Text $n#i=3-n/1000-n/1100-n/1110 =("ccc"+lpad(""<+n rem(10^i))i'0')%(i,9) ``` [Try it online!](https://tio.run/##Xc9Ba8MgFAfw8/wUYjuq1DBllFRobt1hsMOgu60diEmKoCYkL2P78nNmyXLo5f35vceTp3GVDtE35eAq7LUN0fq26QCfoHwKn/yt@gK0DitbPGbhQQohxpBzSIEKSowxZOtaXVJCDtuAu8pTKT4sY3YjNuyeWq5YPIHuAK0wVD30uMDvVHBM0oOEcXRH5W6U3M3KVWKqE5Uameo8TVvJZtkVKh@t8tlymhuxeP/n/b/lNDeEXdJJ9RAM2Cakq9ZovGxp2NAOwHEzQEqGz2dMb1qHbPrRJf6Y2ulrH7Pnl3j8DtpbM@HVaaibzv8C "Clean – Try It Online") ``` $ n // function $ of `n` # i = // define `i` as (the number of digits that aren't crowns) 3 - // three minus n / 1000 - // 1 if first digit is crown n / 1100 - // 1 if second digit is crown n / 1110 // 1 if third digit is crown = ( // the string formed by "ccc" + // prefixing three crowns to lpad ( // the padding of "" <+ n rem (10^i) // non-crown digits of `n` ) i '0' // with zeroes ) % (i, 9) // and removing the extra crowns ``` # [Clean](https://github.com/Ourous/curated-clean-linux), 99 - 3 = 96 bytes This one has crowns. ``` import StdEnv,Text $n#i=3-n/1000-n/1100-n/1110 =("👑👑👑"+lpad(""<+n rem(10^i))i'0')%(i*4,99) ``` [Try it online!](https://tio.run/##Xc/BSsQwEADQs/2KkF3ZxE0xQZduYHvTg@BBWG/uCiFtJdAkpZ2KfsZ@gb/oFxhT2@3BQ2Z4M8ww0XWpXLC@6OsSWWVcMLbxLaA9FPfunT2XH5As3cLkN6m7FpzzIYkpCZ7kBH9/nU7nh9d1owqC8W7tUFtaIvirodSs@IpeEnN1y6SkYQ@qhWSBoOygQzl6IZwhHJdjypILIjaDxGZSJiNjHCnlwBinbpyK1vMsl9lgmU0WY1/z2ds/b88WY19jeownVb3TYLyLVy2T4bK5YFzTA0O@h5gpOhwQ@VfapeOPjuFHV7V660L68BjuPp2yRo94qhVUvrW/ "Clean – Try It Online") [Answer] # Japt, 20 bytes A naïve (and slightly drunk!) port of Arnauld's solution. Uses `"` for crown. ``` U+A³ s r"^21*0"_çQÃÅ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=VStBsyBzIHIiXjIxKjAiX+dRw8U=&input=MTExMA==) [Answer] # Java 10, ~~84~~ 83 bytes ``` n->{for(int p=100,t;p>0;n-=t%12*p,p/=10)System.out.printf("%c",t=n/p>9?46:48+n/p);} ``` Port of [*@tsh*' C comment](https://codegolf.stackexchange.com/questions/171860/crown-hundred-crownty-crown/171926#comment414886_171871). Uses `.` instead of crowns. [Try it online.](https://tio.run/##XZFNboMwEIX3nGIUKRK0QKBKm1AEPUGzybLqwnUgcgLGgiFVFXF2OnZYYDaWv/H8vDe@sBsLLqfryCvWdfDJhLw7AEJi0ZaMF3DQCHBrxAm4S3GQXkqhwaGjQ4aCwwEkZDDKIL@XTWuSVBZHkY@pyqNUBhmu45cn5asNhb3jX4dFHTY9hqql5NJdrfnKx0xuVJ58bN/et/tnunvpMKZ6jOp/KhozTTNSahLqHpHKz1/fwLyHSi0fatIii18DrtEKgEWHbjSH@NWiXTLHJLGQrNi1UbzgZGdxvMinggXvbZ76zZdqbJpnvU8hVY@TSxnqj9D86LHcZzXZHpxh/Ac) **Alternative approach (84 (87-3) bytes):** ``` n->f(n,1000)String f(int n,int p){return n<p?(n+p+"").substring(1):"👑"+f(n-p,p/10);} ``` Port of [*@tsh*' JavaScript's answer](https://codegolf.stackexchange.com/a/171863/52210). [Try it online.](https://tio.run/##XZFLboMwEIb3OcWIlS3AxYsqpenjBM0my6oLh5jKKZlYeEhVRRwiJ@gVewNqDAtgM9bn@f17Hkd1Uenx8NUVlXIO3pTB6wrAIOm6VIWGbY8AO6oNfkLBfAaQb/xlu/JhCwjP0GH6UjJMZJZlfDNqy0Gb9NHya62pqRHwyb4yjG0cRVy4Zu@CmEn@GP393m5R7H1Sm9g76Z3aDsA2@8oU4EiRPy5nc4CTr5INv7x/gOJDiaQdsSyUNoK8n9E6n2Kez3Aofcpywfl6xnKh9w8W/DDn0S@MbdpNSPdDMmgbGpvZ/TjSJ3FuSFjfJ1XIUH@H/TAuUPSL6NWjZdv9Aw) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 bytes ``` 1e3∘{⍵<⍺:1↓⍕⍵+⍺⋄'C',(⍵-⍺)∇⍨⍺÷10} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zDV@FHHjOpHvVttHvXusjJ81Db5Ue9UIFcbyH3U3aLurK6jAeTqArmajzraH/WuALIObzc0qP2f9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/P@pdlXZohYGCoamCobmlgqWlpYKhgQGQb2BprmBoCGIZGlgACUMDAA "APL (Dyalog Unicode) – Try It Online") Prefix direct function. Port of [@tsh's JS Answer](https://codegolf.stackexchange.com/a/171863/52210). ### How: ``` 1e3∘{⍵<⍺:1↓⍕⍵+⍺⋄'C',(⍵-⍺)∇⍨⍺÷10} ⍝ Main function, arguments ⍵ and ⍺ (⍵ → input, ⍺ → 1000). ⍵<⍺: ⍝ If ⍵<⍺ 1↓ ⍝ Drop (↓) the first element (1) of ⍕ ⍝ Format (⍕); 'stringify' ⍵+⍺ ⍝ ⍵+⍺ ⋄ ⍝ else 'C', ⍝ Concatenate (,) the literal 'C' with ∇⍨ ⍝ Recursive call (∇) with swapped arguments (⍨) (⍵-⍺) ⍺÷10 ⍝ New arguments; ⍵ → ⍵-⍺; ⍺ → ⍺÷10 ``` [Answer] # PHP, 71 bytes ``` for($n=$argn,$x=1e4;1<$x/=10;$n%=$n<$x?$x/10:$x)echo$n<$x?$n/$x*10|0:C; ``` prints `C` for the crown. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/5f05b30fbdb0fbb154ad609e981136f7dbc83387). [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` ('2'#).show.(+1000) n#(a:x)|n==a='c':'1'#x|1>0=x ``` [Try it online!](https://tio.run/##Hc1BDoIwEAXQvaeYBJNpQyFTV4WknEBXLsWYxogQoTaCkQWX4ARe0RNYqZuf9zPJ/Nr0t0vb@kqXnuEGI5729f2VslgSEV/ZiJl85JPV2mj8vOcZc5QYjZMsSI@@M40FDZ1xuxOwsoGkAPcc9sNja2ENLDyDhscxlgPmrFrM4UBCCalElollRSgV@DeFCAo13JYIknT033PVmmvvk7NzPw "Haskell – Try It Online") [Answer] # C, ~~ 84 ~~ 58 bytes *Thanks to @tsh for saving 25 bytes and thanks to @ceilingcat for saving a byte!* ``` f(n,p){for(p=1e3;p/=10;)n-=putchar(n/p>9?46:48+n/p)%12*p;} ``` [Try it online!](https://tio.run/##bcxBDoIwEAXQPacgJCZTtaGjKNSmepamsUACdQK4Ilzd2oU7O6ufl//H8tbaEBz4I7HVvSYgjc@zolKjUMxzTe/FdmYCX9JdPqrrrWoOMbMdnvakttD7JR9N74Fla5bHcyCYiqsZioKpH@ElYbX8RykTiEKkfgpZJxSTXRRNSjF2sy18rBtMOwc@jF8) [Answer] # [sed](https://www.gnu.org/software/sed/), 39 48 bytes, but score is 39, since each 👑 counts as 1. ``` /..../s/^1+0/👑👑👑/ s/^/00/ s/.*(...)/\1/ ``` [Try it online!](https://tio.run/##NUrJDcIwEPxvJRDk7MwDme0F5QWK8rEjDIW4AlqkApb1g5Hm1LT7La3l5a5zQJsuPEE/797/VIlRgeHzdIjXUa9UdwjPwmxiZkIgOiwLORJxCSG@dX9utTRPjx8 "sed – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 - 9 = 29 bytes *-2 bytes thanks to Jo King* ``` {~m/...$/}o{S/1+0/👑👑👑/}o*+1e4 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ui5XX09PT0W/Nr86WN9Q20D/w/yJE2EYKKqlbZhq8t@aqzixUkElXkdBXeFR2yQFdR2FNA2VeE2FtPwiBQMdBUNTIDa31FGwtAQShgYGIDEDS3MgaQhmGxpYgEhDg/8A "Perl 6 – Try It Online") Inspired by Arnauld's JavaScript solution. [Answer] # [Pip](https://github.com/dloscutoff/pip), 21 bytes ``` (a+t*mR`1+0`'xX3)@>-3 ``` [Try it online!](https://tio.run/##K8gs@P9fI1G7RCs3KMFQ2yBBvSLCWNPBTtf4////hgYGBgA "Pip – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` çi╖@u;╟w☼7ø4σcH ``` [Run and debug it](https://staxlang.xyz/#p=8769b740753bc7770f370034e56348&i=0%0A15%0A179%0A999%0A1000%0A1097%0A1100%0A1108%0A1110&m=2) Same idea as Arnauld's answer. ]
[Question] [ ## Summary Inspired by the recent popularity of ASCII art challenges, this challenge's purpose is to draw an ASCII checkerboard, like one on which Chess can be played. Write a program that takes a positive integer `n` as an argument, in `stdin`, or as user input, and output an checkerboard with `n`x`n` squares, along with a border that is 1 character thick. Each square should be 2x2 characters. The squares should follow the normal alternating white-black (white first, as in top-left corner) pattern of a checkerboard. White squares should be made out of space () characters, and black squares should be made out of pound (`#`) characters. The border should be made out of dashes (`-`) with a plus (`+`) on the border or perpendicular point of a square. **Input** Positive integer in representing the number of squares (dimensions in squares) to draw in the checkerboard, with each square being 2x2 characters. ## Example Results `n=2` ``` +--+--+ | |##| | |##| +--+--+ |##| | |##| | +--+--+ ``` `n=3` ``` +--+--+--+ | |##| | | |##| | +--+--+--+ |##| |##| |##| |##| +--+--+--+ | |##| | | |##| | +--+--+--+ ``` `n=4` ``` +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ ``` ... and so on. --- ## Notes * Trailing spaces and new lines are acceptable. * You may write either an entire program or a function. * No leading spaces. * Your program should display correct results for n=15. * For less-known esoteric languages and similar, provide a link to the language. * `n=0` should produce `+`. (optional, but highly recommended and encouraged.) * **Shortest code in bytes wins, as this is code golf.** [Answer] # J, 24 bytes An anonymous function: ``` 2 2&$&.>@(' #'{~2|+/~@i.) ``` Usage: ``` f =: 2 2&$&.>@(' #'{~2|+/~@i.) f 4 +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ ``` [Answer] ## Python 2, 79 ``` N=3*input()+1 for i in range(N):print('+||- #- #+||-# -# '*N)[3**i%7/2%3:3*N:3] ``` For each row, selects one of the patterns ``` +--+--+--+--+--+ | |##| |##| | |##| |##| |##| ``` and prints `3*n+1` characters from it. The pattern is chosen by repeating its first 6 characters, selected with the string interleaving trick, which also serves to extract a snippet of the correct length. The correct pattern is selected based the value of the row index `i` modulo 6 by an arithmetic expression `3**i%7/2%3` that gives the repeating pattern [0,1,1,0,2,2]. I found it using the fact that `x**i%7` has period `6`, then trying different values of `x` and different postprocessing to get the right pattern. [Answer] # Pyth, 37 ``` VJh*3Qsm@?+\|*2@" #"+/N3/d3%N3"+--"dJ ``` Rather hacked together, but short. [Demonstration.](https://pyth.herokuapp.com/?code=VJh*3Qsm%40%3F%2B%5C%7C*2%40%22%20%23%22%2B%2FN3%2Fd3%25N3%22%2B--%22dJ&input=10&debug=0) [Answer] # CJam, ~~43~~ 42 bytes ``` ri3*)_2m*{_3f%:!2b\3f/:+2%(e|"#|-+ "=}%/N* ``` [Try it online](http://cjam.aditsu.net/#code=ri3*%29_2m*%7B_3f%25%3A!2b%5C3f%2F%3A%2B2%25%28e%7C%22%23%7C-%2B%20%22%3D%7D%25%2FN*&input=6). Each coordinate is mapped to a char, e.g. the top left corner is `(0, 0) -> "+"`. Specifically, we calculate ``` [(y%3 == 0)*2 + (x%3 == 0)] or [(x//3 + y//3) % 2 - 1] ``` and index into the string `"#|-+ "` accordingly. [Answer] # [Retina](https://github.com/mbuettner/retina), 106 bytes ``` 1 $_0$_x 1(?=1*0) +-- 1(?=1*x) s (0s.*?0)s $1o (s\D*?)s $1o s | o |## \D*?x $0$0 0 +n x |n (.*?n).* $0$1 ``` Takes input as unary (based on [this meta discussion](https://codegolf.meta.stackexchange.com/q/5343/7311)). Each line should go to its own file and `n` should be changed to newline in the files. This is impractical but you can run the code as is, as one file, with the `-s` flag, keeping the `n` markers. You can change the `n`'s to newlines in the output for readability if you wish. E.g.: ``` > echo -n 111|retina -s checkerboard|tr n '\n' +--+--+--+ | |##| | | |##| | +--+--+--+ |##| |##| |##| |##| +--+--+--+ | |##| | | |##| | +--+--+--+ ``` Further golfing and some explanation comes later. [Answer] # JavaScript (ES6), 117 ``` n=>Array(n*3+1).fill("+--".repeat(n)+"+").map((v,i)=>v.replace(/./g,(k,x)=>i%3?"| |##| "[x%6+(i%6>2)*3]:k)).join` ` ``` Snippet: ``` <input type="range" min=2 max=15 step=1 value=1 id="i" oninput="o.textContent=f(this.value)"><pre id="o"></pre><script>function f(n){ return Array.apply(0,Array(n*3+1)).map(function(){return "+--".repeat(n)+"+"}).map(function(v,i){ return v.replace(/./g,function(k,x) { return i%3?"| |##| "[x%6+(i%6>2)*3]:k}) }).join("\n") };o.textContent=f(2)</script> ``` Anonymous function. Starts with a full array of `+--+--+--...` lines, and on appropriate lines, replaces the `+` for `|` and `-` for or `#` as appropriate. The expression that decides the replacement character, `"| |##| "[x%6+(i%6>2)*3]`, could probably be golfed further, but I've found that using a longer, redundant string saves more characters than a complex calculation. [Answer] # CJam, 59 bytes This .. is .. too .. long .. ``` ri:I," #"f=2f*_I({__sff^_}*]'|I)*f.\2/Nf*'+I)*"--"*aI)*.\N* ``` [Try it online here](http://cjam.aditsu.net/#code=ri%3AI%2C%22%20%23%22f%3D2f*_I(%7B__sff%5E_%7D*%5D'%7CI)*f.%5C2%2FNf*'%2BI)*%22--%22*aI)*.%5CN*&input=4) [Answer] ## CoffeeScript with ES6, 106 bytes ``` f=(n,y=z='+--'[r='repeat'](n)+'+\n')->y+=('|##| '[r](n).substr(i%2*3,n*3)+'|\n')[r](2)+z for i in[1..n];y ``` --- ## JavaScript (ES6), 111 bytes Newlines are significant and counted as 1 byte each. The explicit return made it a bit longer: ``` f=n=>{for(i=0,y=z='+--'[r='repeat'](n)+`+ `;i<n;)y+=('|##| '[r](n).substr(++i%2*3,n*3)+`| `)[r](2)+z;return y} ``` ### Demo At time of writing, Firefox is the only major browser compatible with ES6. ``` f=n=>{for(i=0,y=z='+--'[r='repeat'](n)+`+ `;i<n;)y+=('|##| '[r](n).substr(++i%2*3,n*3)+`| `)[r](2)+z;return y} // Demonstration related things document.getElementById('O').innerHTML = f(document.getElementById('n').value); document.getElementById('n').addEventListener('change', function () { document.getElementById('O').innerHTML = f(this.value); }); ``` ``` <p><input id=n type=number min=0 step=1 value=6></p> <pre><output id=O></output></pre> ``` [Answer] # Python 3, ~~114 108~~ 100 ``` def f(n): for i in range(3*n+1):print(("|##| "*n+"|")[::i//3%2*2-1][:3*n+1]if i%3 else"+--"*n+"+") ``` --- --- ## Previous solutions ### 108 ``` def f(n): for i in range(3*n+1): a=("|##| "*n+"|")[::i//3%2*2-1][:3*n+1];print(a if i%3 else"+--"*n+"+") ``` ### 114 ``` def f(n):a="+--"*n+"+\n";b="| |##"*n+"|";print(a+a.join(([(b[:3*n+1]+"\n")*2,(b[::-1][:3*n+1]+"\n")*2]*n)[:n])+a) ``` ### 118 (not submitted) ``` def f(n): for i in range(3*n+1):print((("|##| "*n)[:3*n+1]if i//3%2 else("| |##"*n)[:3*n+1])if i%3 else"+--"*n+"+") ``` [Answer] # Ruby, 87 ``` ->n{a=[b="+--",c="| |##",c,b,d="|##| ",d] 0.upto(n*3){|i|puts"".ljust(n*3+1,a[i%6])}} ``` This is an anonymous function. Call it like this (all possibilities from 0 to 5) ``` f=->n{a=[b="+--",c="| |##",c,b,d="|##| ",d] 0.upto(n*3){|i|puts"".ljust(n*3+1,a[i%6])}} 6.times{|j|f.call(j)} ``` It makes use of the `ljust` method on an empty string. Ruby allows a padding string to be specified for justification, so we use `ljust` with one of the three possible padding strings `b,c,d` per array `a`, ordered as `bccbdd`. [Answer] # CJam, 46 bytes ``` li3*)_2m*[{_3f/2f%:=\3f%:g+2b"+-|#+-| "=}/]/N* ``` [Try it online](http://cjam.aditsu.net/#code=li3*)_2m*%5B%7B_3f%2F2f%25%3A%3D%5C3f%25%3Ag%2B2b%22%2B-%7C%23%2B-%7C%20%22%3D%7D%2F%5D%2FN*&input=5) Well, I was hoping that I would at least have an original solution (I normally don't look at other answers before working on my own). Turns out that @Sp3000 had already done something very similar, only better. But since I already did the work, I thought I'd post it anyway. Explanation: ``` li Get input n. 3*) Calculate 3*n+1, which is the total width/height. _ Copy size. We'll need it at the end to insert the newlines. 2m* Calculate cartesian power with 2. This enumerates all coordinate pairs. [ Wrap characters in array for split operation at the end. { Loop over all coordinate pairs. _ Copy coordinate pair. 3f/ Divide coordinates by 3. 2f% Modulo 2. This characterizes even/odd squares. := Compare the two coordinates. This gives 0/1 for white/black squares. \3f% Grab second copy of coordinates, and calculate modulo 3. :g Sign. This gives 0 for grid lines, 1 for interior of squares. + Concatenate the two results. We now have a 3 bit code. 2b Convert the 3 bits to a number in range 0..7. "+-|#+-| " Lookup table to convert 0..7 number to character. = Lookup character. }/ End loop over coordinate pairs. ] End wrapping characters. / Split character array into lines. N* And join them with newlines. ``` [Answer] # [HackVM](http://www.hacker.org/hvm/), 158 bytes Definitely not a winner, but this looked like a nice challenge to do in HVM. Place the size into the first memory cell and use the following code: ``` 77*1+c0<0^84*1+?1-11<-1>99*85++0^cc77*1+c066*5+-g!0<0^45*2+?1-95*0^0^2-PPP064*-6-gd95*2-P25*P$1<2>555**1-P0<0^76*6-?1-12<-2>2<3*48*+0^PP555**1-P076*2+-gd25*P$ ``` **Note:** The code needs to be exactly in one line to work. **Explanation:** ``` Call PLUSHDASHLINE 77*2+c Read the cell and skip if done 0<0^84*1+?1- Flip row parity 11<-1> Call NORMALLINE twice 99*85++0^cc Call PLUSHDASHLINE 77*1+c Jump back to start of loop 066*5+-g! DEFINE_PLUSDASHLINE 0<0^45*2+?1-95*0^0^2-PPP064*-6-gd95*2-P25*P$ DEFINE_NORMALLINE 1<2>555**1-P0<0^76*6-?1-12<-2>2<3*48*+0^PP555**1-P076*2+-gd25*P$ ``` The code calls 2 functions `PLUSHDASHLINE` and `NORMALLINE`, maintains a global state for parities (i.e. whether to put a `' '` or a `'#'` in a cell). **Explanation for `PLUSDASHLINE`:** ``` Repeat N times 0<0^45*2+?1- Print "+--" 95*0^0^2-PPP End Repeat 064*-6-g Print "+" d95*2-P Print "\n" 25*P Return $ ``` **Explanation for `NORMALLINE`:** ``` Copy Parity into Cell 2 1<2> Print '|' 555**1-P Repeat N times 0<0^76*6-?1- Flip Cell 2 (i.e. Flip Column Parity) 12<-2> Calculate ' ' or '#' based upon parity 2<3*48*+0^ Print it twice PP Print '|' 555**1-P End Repeat 076*2+-g Print "\n" d25*P Return $ ``` Would appreciate it if someone gave tips for improving it further :) [Answer] ## Python 2, 98 ``` n=input() f=lambda a,b,s:s+s.join(([a*2,b*2]*n)[:n])+s+'\n' print f(f(*' #|'),f(*'# |'),f(*'--+')) ``` Not the shortest way, but an amusing method. The function `f` takes in two strings `a,b` and a separator `s` and interleaves its arguments like `saasbbsaasbbsaas`. The rows of the board are created in this form with their respective characters, then are themselves interleaved this way to produce the result. [Answer] # Ruby: 83 characters ``` f=->n{puts d=?++'--+'*n,(0...n).map{|i|[?|+'%2s|'*n%(['','##',''][i%2,2]*n)]*2<<d}} ``` Sample run: ``` irb(main):001:0> f=->n{puts d=?++'--+'*n,(0...n).map{|i|[?|+'%2s|'*n%(['','##',''][i%2,2]*n)]*2<<d}} => #<Proc:0x000000007c51a0@(irb):1 (lambda)> irb(main):002:0> f[0] + => nil irb(main):003:0> f[1] +--+ | | | | +--+ => nil irb(main):004:0> f[2] +--+--+ | |##| | |##| +--+--+ |##| | |##| | +--+--+ => nil irb(main):005:0> f[3] +--+--+--+ | |##| | | |##| | +--+--+--+ |##| |##| |##| |##| +--+--+--+ | |##| | | |##| | +--+--+--+ => nil ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 52 bytes ``` (x|`+--`*\++,2(⁰(n←x+₂[`| `|`|##`]₴)\|,))`+--`*\++, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28x%7C%60%2B--%60*%5C%2B%2B%2C2%28%E2%81%B0%28n%E2%86%90x%2B%E2%82%82%5B%60%7C%20%20%60%7C%60%7C%23%23%60%5D%E2%82%B4%29%5C%7C%2C%29%29%60%2B--%60*%5C%2B%2B%2C&inputs=4&header=&footer=) A. Big. Mess. [Answer] # Julia, 124 bytes ``` n->(t="+--"^n*"+";a="| ";b="|##";m=n÷2;c=n%2>0;p=println;p(t);for i=1:n p(((i%2<1?(b*a)^m*b^c:(a*b)^m*a^c)*"|\n")^2*t)end) ``` This creates an unnamed function that accepts an integer and prints to stdout. Ungolfed + explanation: ``` function f(n) # Define the portions of the board t = "+--"^n * "+" a = "| " b = "|##" # There will be n÷2 repeated a*b or b*a per line m = n ÷ 2 # If n is odd, there will be an extra a or b c = n % 2 != 0 # Print the top println(t) # Print each horizontal section of the board for i = 1:n # In even numbered sections, b precedes a j = (i % 2 == 0 ? (b*a)^m * b^c : (a*b)^m * a^c) * "|\n" println(j^2 * t) end end ``` [Answer] # Javascript, ES6 149 ``` n=>(r="+--".repeat(n)+"+",[...r].map((_,i)=>i%3?(x=i%6&&i%6<3?" ":"#",[...r].map((_,e)=>e%3?e%6&&e%6<3?x:"#"==x?" ":"#":"|").join('')):r).join('\n')) ``` Pretty fun to write though it's a bit long **Works on firefox** 1 - Open console 2 - Type the following ``` console.log((n=>(r="+--".repeat(n)+"+",[...r].map((_,i)=>i%3?(x=i%6&&i%6<3?" ":"#",[...r].map((_,e)=>e%3?e%6&&e%6<3?x:"#"==x?" ":"#":"|").join('')):r).join('\n')))(15)); ``` Output (n=15): ``` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ``` [Answer] # Haskell, 99 This is partially inspired by [the previous Haskell answer by catgocat](https://codegolf.stackexchange.com/a/53352/3994); I wrote my own version, then looked at it, then wrote another. I'm playing by the same rules — the input is an argument, but the output is stdout. (If it could be a pure function, subtract 7 characters `putStr$`.) ``` f n=putStr$unlines$t$map t$y[a,b,b,a,c,c]where t=take(n*3+1) a=y"+--" b=y"| |##" c=drop 3b y=cycle ``` We use `t` to take a region of 3*n* + 1 characters from an infinite checkerboard built using `cycle`, and that's it. The primary idea I took from the other answer is that of putting the patterns of both the border and checker cells *together* in strings. My first version (140 characters) used the strategy of calculating the character at each point, which might be better for a more complex problem than this one. ``` f n=putStr$unlines$map(\y->map(g y)r)r where r=[0..n*3] g y x=s(s '+'y '|')x$s '-'y$cycle" #"!!(x`div`3+y`div`3) s c i d|i`mod`3==0=c|True=d ``` [Answer] # Haskell, 118 This is my first haskell code golf answer and here it is: ``` f n=mapM_(putStrLn.s)[0..3*n]where;d x=(++)$take(3*n)$cycle x;s x|x`mod`3<1=d"+--""+"|x`mod`6<3=d"| |##""|"|1<2=d"|##| ""|" ``` **More readable version:** ``` func num = do let -- Range rag = 3 * num -- `+--+` a = d "+--" "+" -- `| |##` b = d "| |##" "|" -- `|##| ` c = d "|##| " "|" -- generate line d x y = take rag (cycle x) ++ y -- step step x | x `mod` 6 `elem` [1, 2] = b | x `mod` 3 == 0 = a | otherwise = c mapM_ (putStrLn . step) [0..rag] ``` **Output** ``` *Main> :load test [1 of 1] Compiling Main ( test.hs, interpreted ) Ok, modules loaded: Main. *Main> f 1 + *Main> f 4 +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ | |##| |##| | |##| |##| +--+--+--+--+ |##| |##| | |##| |##| | +--+--+--+--+ *Main> f 15 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| |##| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |##| |##| |##| |##| |##| |##| |##| | | |##| |##| |##| |##| |##| |##| |##| | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ``` [Answer] # C - ~~119~~ 101 Uses now the calculation similar to @Sp3000 answer. Also couple optimizations. ``` i,j;f(n){for(i=j=0;j<=n*3;i++)putchar(i-n*3-1?" -|+#"[!(j%3)+2*!(i%3)?:(i/3+j/3)%2*4]:(j-=i=-1,10));} ``` I think that `?:` is a GCC extension... Old answer: ``` f(n){int i,j;char p[]=" -|+";for(i=j=0;j<=n*3;*p=" #"[(i++/3+j/3)%2])putchar(i-n*3-1?p[!(j%3)+2*!(i%3)]:(j-=i=-1,10));} ``` It maintains 2 coordinates and honestly calculates which character to print for each pair. List of characters to print is stored in array and this alone prints an "uncolored" grid. First element of the array is modified to draw black squares. I might change this so that instead of two independent coordinates it's one value counting up or (maybe even better) down, but can't wrap my head around that right now. Bonus - replacing 3 with any other number results in a program that draws valid checkerboard with different cell size. [Answer] # awk - 91 ``` { for(k=i=3*$0+1;i--;print"") for(j=k;j--;)printf i%3?j%3?234~(i+j)%6?FS:"#":j%3?"-":"|":"+" } ``` Was quite a fight to get it below 100. Counting backwards and using the match operator were the breakthroughs ;) The rest is pretty much straightforward logic. [Answer] ## Pyke, 47 bytes ``` "+--"Q*\+j+i QQ]Uas 2%" #"@2*)F\|JjR+"+ "+2*pi <Newline needed> ``` [Try it here!](http://pyke.catbus.co.uk/?code=%22%2B--%22Q%2a%5C%2Bj%2Bi%0AQQ%5DUas+2%25%22+%23%22%402%2a%29F%5C%7CJjR%2B%22%2B%0A%22%2B2%2api%0A&input=6) ]
[Question] [ If you think this could be fun, but too much work, consider participating in [this](https://codegolf.stackexchange.com/q/66921/43319) much smaller challenge. --- A bit of fun (and possibly frustration!) for 2016... [Dyalog's "puzzle of the year"](http://dyalog.com/2016-year-game.htm). Enjoy! # The Objective Find Dyalog APL ([download](http://dyalog.com/download-zone.htm)) expressions (other languages are allowed, see *Eligibility* below) involving exactly the digits 2 0 1 6 in that order to equal the numbers 0 to 100. For example: `20=16` `×2016` `2⌊016` `2+0+1*6` ... The aim is to use as few characters as possible in each expression (the minimum number of characters for an expression is 5 – the four digits 2 0 1 6 and a single primitive function/operator). # The Rules * Each expression must contain the digits 2 0 1 6 (in that order) and no other digits. Pre-set constants and variables are also not allowed. * In addition to the four digits 2 0 1 6, only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used. The resultant expressions must be deterministic (that is, give the same result on repeated evaluations). For non-APLs, functions/operators with a name are also allowed; same rules as [here](https://codegolf.stackexchange.com/q/66921/43319). * Assume all default settings for your language. For Dyalog APL, this means `⎕ML` and `⎕IO` are both 1, and `⎕PP` is 10. * Each entry comprising correct expressions for all the numbers from 0 to 100 inclusive will be rated according to the number of characters used by those expressions excluding redundant spaces (minimum 505 for all 101 expressions). # Eligibility Anyone can enter. You may answer in any language, but only APL answers will be considered for accepting. If you use another language than APL, you may use snippets, programs, functions, etc. as alternatives to expressions, and you may print, leave the number in an accessible memory location, or otherwise return the result, as long as your code directly evaluates to the desired number as any standard numeric data type for your language. # Closing Date 30 November 2016. # Prizes * Have your answer accepted * Be immortalised in Dyalog's 2016 Hall of Fame! # Submitting Your Entry After 30 November 2016, I will accept the shortest answer, and submit your answer, in *your* name, to Dyalog's 2016 Hall of Fame. # FAQ * Is `J` (e.g. 37=`⌈⍟!20J16`) allowed? * No: *In addition to the four digits 2 0 1 6, only only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used.* * Is output as a string acceptable? * No: *equal the numbers 0 to 100.* * Physical digits, or data digits? * Data digits, as per OP: same rules as [here](https://codegolf.stackexchange.com/q/66921/43319), where one of the examples contain `LOG10(`. * Is assigning variables then using them as part of the expression (e.g. 56=`a+16+a←20`) allowed? * Yes, but you may not use an assignment from one expression in another one. --- I have explicit written permission to post this challenge here from the original author of this challenge. Feel free to verify by following the [provided link](http://dyalog.com/2016-year-game.htm) and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own. [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), 888 bytes Okay, first some ground rules for Hexagony, in case anyone wants to beat this: * I'm interpreting "snippet" as a linear piece of code that can be dumped into any sufficiently large program, provided the current and adjacent memory edges are zero. * The snippet has to be entered from the left and exited from the right. I'd be able to save quite a bunch of bytes without that (e.g. `2|016` for 22), but it seems most in the spirit of the challenge. * The snippet "produces" a given number, if any memory edge (not necessarily the current one) holds that value after execution. * The rule forbidding any other numbers in the snippet affects both other digits as well as any letters, since they effectively act as integer literals in Hexagony. (Those would save a ton of bytes.) So here is the list. I did test most of them but not all (some are trivial modifications of others), so I hope I didn't make any mistakes: ``` 2016 20&1}6 2}016 2)}016 20{16'- 201}6( 201}6 201}6) 2}016": 2(0(}16 2(0}16 2(0)}16 )2}016 )2)}016 20}16(( 20}16( 20}16 20}16) 20}16)) 20(}16 20}16 20)}16 20))}16 20)))}16 20}1)6(( 20}1)6( 20}1)6 20}1)6) 201{6)': 2)0(}16 2)0}16 2)0)}16 2{016'* 201{6': 2{016)'* 20}1))6( 20}1))6 20}1))6) 20}1))6)) 2))0(}16 2))0}16 2))0)}16 2))0))}16 2))0)))}16 20)){1)'6* 2){016('* 2){016('*) 2){016'*( 2){016'* 2){016'*) 2)))0}16 2){016)'* 2){016)'*) 2{01)6)'*( 2{01)6)'* 2{01)6)'*) 2{01)6)'*)) 2{01)6)'*))) 2))))0((}16 2))))0(}16 2))))0}16 2))))0)}16 2)0){1)'6* 2)){016'*( 2)){016'* 2)){016'*) 2)){016'*)) 2)){016'*))) 2{01))6('*( 2{01))6('* 2{01))6'*(( 2{01))6'*( 2{01))6'* 2{01))6'*) 2{01))6)'* 2){01)6('* 2){01)6'*(( 2){01)6'*( 2){01)6'* 2){01)6'*) 20{1)))'6* 2){01)6)'* 2){01)6)'*) 2){01)6)'*)) 2){01)6))'* 2){01)6))'*) 2){01)6))'*)) 2){01)6)))'* 2{01)))6(('* 2{01)))6('*( 2{01)))6('* 2{01)))6'*( 2{01)))6'* 2{01)))6'*) 2{01)))6)'* 2{01)))6)'*) 2{01)))6))'* 2(01((((}16 2(01(((}16 2(01((}16 2(01(}16 ``` I got a bit lazy towards the end, so I'm sure this isn't optimal. Might be interesting (and possible) to brute force these. [Answer] # Jelly, 686 bytes ``` 20=16 20>16 2+0%16 201%6 20%16 20%16‘ 201a6 20>1+6 20%16Ḥ 2016DS 20Ho16 2016BL 20:1.6 20_1_6 20×1_6 20+1_6 20&16 20:+16 2+0+16 20+1^6 20|16 20|16‘ 20|16‘‘ 20%16!’ 20%16! 20²:16 20H+16 20+1+6 20×1_6Ḥ 20×1_6Ḥ‘ 20+1_6Ḥ 2016&½’ 2016&½ 201:6 201:6‘ 20Cạ16 20+16 20+16‘ 20+1^6Ḥ 20|16Ḥ’ 20|16Ḥ 20|16Ḥ‘ 20|16‘Ḥ 2016½Ḟ’ 2016½Ḟ 2016½Ċ 2016½Ċ‘ 20Ḥ+1+6 2r0×16S 201a6‘² 20²:16Ḥ 2r016+S 201ÆC+6 20&16ÆN 20H_1×6 20ạC+16 20Ḥ+16 20_1×6H 20_1×6H‘ 20_1×6H‘‘ 20+1_6ḤḤ 2+0+16ÆN 20:.16H 20+1×6H 2²+0×16 201:6Ḥ’ 201:6Ḥ 201Ḥ:6 201Ḥ:6‘ 20Cạ16Ḥ’ 20Cạ16Ḥ 20+16Ḥ’ 20+16Ḥ 20+16Ḥ‘ 20+16Ḥ‘‘ 20+ÆN_16 20+1^6ḤḤ 20+1^6ḤḤ‘ 20×16HH’’ 20×16HH’ 20×16HH 20×16HH‘ 20|16Ḥ‘Ḥ 20|16Ḥ‘Ḥ‘ 20|16‘ḤḤ 201½×6Ḟ 201½×6Ċ 20ÆN+16 2016½ḞḤ 20Æn16¡ 20r16S 20r16S‘ 20r16S‘‘ 20Ḥ+1+6Ḥ’ 20Ḥ+1+6Ḥ 20ḤḤ+16’ 20ḤḤ+16 20ḤḤ+16‘ 201a6‘²Ḥ 201’Ho6’ 201’Ho6 ``` I wrote about 50 of these, then autogenerated the rest by appending `Ḥ` (×2) and `‘’` (±1) as needed. I’ll improve them later! [Answer] # J, ~~1041~~ ... 838 bytes ~~981~~ ~~961~~ ~~952~~ ~~860~~ ~~859~~ I got a little lazy to the end, but it should be more fixed than less. ~~I don't think I'll ever overtake Hexagony, but you never know!~~ beating hexagony! Saved 9 bytes thanks to Zgarb! and so much more to Lynn! ``` 20=16 *2016 2[016 2+01[6 20-16 p:2[016 201]6 2+0-1-6 -:20]16 2+01+6 -:20[16 p:20-16 +/2$01]6 <:20-1]6 20-1]6 <:20]16 20]16 p:201]6 2+016 20-1[6 20[16 20+1[6 20++~1[6 +/q:2016 20-(+:1)-6 <:20+1]6 20+1]6 20+1+6 +:20-1]6 p:2+01+6 -2-+:016 <:2*016 2*016 >.201%6 <.201%6 <:20+16 20+16 20+>:16 +~20-1[6 -20-p:16 +:20[16 p:2*01*6 >:p:2*01*6 <:<.%:2016 <.%:2016 >.%:2016 +/q:*:2016 p:20-1]6 >:p:20-1]6 *:2+0-1-6 +:20-1-6 20++:16 <.%:20^%:1+6 20+#i:i:16 */2,01]$~-:6 <:<.o.2+016 <.o.2+016 >.o.2+016 <:p:20]16 p:20]16 >:p:20]16 2+p:016 <.o.20[16 <:2^01]6 2^01]6 >:2^01]6 <:p:2+016 p:2+016 >:p:2+016 >:>:p:2+016 <:p:20-1[6 p:20-1[6 +/+~20 16 p:20[16 >:p:20[16 >:>:p:20[16 -:+/2+i.016 <:<:p:20+1[6 <:p:20+1[6 20+p:16 20*.16 *:2+01+6 >:*:2+01+6 p:20++~1[6 <.o.20+1+6 >.o.20+1+6 >:>.o.20+1+6 <.o.+:20-1]6 >.o.+:20-1]6 p:+/q:2016 >:p:+/q:2016 <.o.p:2+01+6 >.o.p:2+01+6 (*:-:20)-1+6 >:(*:-:20)-1+6 <:(++:)2*016 (++:)2*016 p:20-(+:1)-6 2**~p:-:01]6 <:*:-:20[16 *:-:20[16 ``` # Highlights and Notes I used prime numbers *a lot* in this. In fact, I used `p:` (the Nth prime) function *37* times in this thing. ``` *:-:20[16 ``` 90 was made using a fork. Yay! It's approximate to this: ``` (*+&1)2+01+6 ``` Translated as ``` inc =: + &1 mul =: * nin =: 2 + 1 + 6 NB. since (f g) y = y f (g y): (mul inc) nin = nin mul (inc y) = 9 * 9+1 = 90 ``` 54 uses a shaping ravel! ``` */2,01]$~-:6 ``` Is equivalent to ``` */ 2 , $~ -:6 */ 2 , -:6 $ -:6 */ 2 , 3 $ 3 */ 2 , 3 , 3 , 3 2 * 3 * 3 * 3 54 ``` [Answer] # JavaScript, 1021 bytes Fixed and saved two bytes thanks to [Charlie Wynn](https://codegolf.stackexchange.com/users/50053/charlie-wynn) and [ETHProductions](https://codegolf.stackexchange.com/users/42545/ethproductions). ``` 201&6 -~!2016 2%016 201%6 20%16 2^0^1^6 2*0*1+6 2|0|1|6 2*01+6 2-~01+6 ~2+016 ~2+016 2^016 20-1-6 2|016 20+1-6 20&16 2-~016 2.0+16 20^1+6 20|16 -~20|16 20*1|6 20|1|6 -2*~01*6 20-1+6 20+1*6 20+1+6 2*016 -~(2*016) 2*-~016 ~-(2.0*16) 2.0*16 -~(2.0*16) 2.0*-~16 ~-20+16 20+16 -~20+16 -~-~20+16 -~2*~-016 20*-~1.6 ~-(-~2*016) -~2*016 ~-~-(~2*~016) ~-(~2*~016) ~2*~016 20<<1|6 20*-~1-~6 ~2*~-~016 -~(~2*~-~016) ~-~(~-~2*~-016) ~2*~-~-~016 -~-~2*~-016 20*-~-~1+~6 20*-~-~1-6 20*-~-~1-~-6 -~-~2*016 -~20*-~-~1-6 -~-~(-~-~2*016) ~-(20*~-~(1-6)) ~-~2*~016 -~(20*~-~(1-6)) -~-~(20*~-~(1-6)) -~20*~-~(1-6) ~-~2*~-~016 20*-~-~1+~-6 20*-~-~1+6 20*-~-~1-~6 ~-~2*~16 -~20*-~-~1+6 -~-~-~2*016 ~-(~-~2*~-~16) ~-~2.0*~-~16 -~(~-~2*~-~16) 20*-~-~-~1-6 ~-~-~2*~016 ~-20*~(1-6) -~(~-20*~(1-6)) ~-~-(20*~(1-6)) ~-(20*~(1-6)) 20*~(1-6) -~(20*~(1-6)) ~-~-(~20*-~(1-6)) ~-(~20*-~(1-6)) ~20*-~(1-6) 20*-~-~-~1+~-6 20*-~-~-~1+6 20*-~-~-~1+-~6 20*-~-~-~1+-~-~6 ~-(~-~-20*-(1-6)) ~-~-20*-(1-6) -~(~-~-20*-(1-6)) ~-~-~-(~-20*-(1-6)) ~-~-(~-20*-(1-6)) ~-(~-20*-(1-6)) ~-20*-(1-6) -~(~-20*-(1-6)) ~-~-~-(20*-(1-6)) ~-~-(20*-(1-6)) ~-(20*-(1-6)) 20*-(1-6) ``` [Answer] # Dyalog APL (This is a joke, please don't submit), 25,957 bytes. ``` 2016⊢≢⍬ 2016⊢(⊢+≢)≢⍬ 2016⊢(⊢+≢)(⊢+≢)≢⍬ ... ``` Yeah, this is a joke entry, we need an APL solution, even if it's completely horrible. Works by incrementing `≢⍬` (`0`) `n` times. I don't want to give any secrets away from my actual submission. Obviously could be golfed much more. [Answer] # JavaScript (ES7), 836 bytes Everything should work in any browser except 81, 88, and 97, which use the new `**` operator. Mostly everything here was done by hand. I've been working on a brute-forcer to improve anything that can be improved. Currently it has saved 103 bytes on various items. ``` 0: 201&6 1: 2-01%6 2: 2%016 3: 201%6 4: 20%16 5: 201%~6 6: 2%01+6 7: 2-01+6 8: 2*01+6 9: 2+01+6 10: 2-~01+6 11: ~2+016 12: 2^016 13: 20-1-6 14: 2|016 15: 20+1-6 16: 2+016 17: 2-~016 18: 2+0+16 19: 20-1%6 20: 20|16 21: 20+1%6 22: 20*1|6 23: 20+1|6 24: 20+~1+6 25: 20-1+6 26: 20*1+6 27: 20+1+6 28: 2*016 29: 20-~1-~6 30: -2*~016 31: 20|~-16 32: 20*1.6 33: 20*~1^~6 34: -20*~1-6 35: 20+~-16 36: 20+16 37: 20-~16 38: 20-~-~16 39: -~2*~-016 40: 20<<1%6 41: -20*~1-~!6 42: ~2*-016 43: ~20^-1<<6 44: ~20*~1^6 45: ~2*~016 46: 20<<1|6 47: -20*~1-~6 48: ~20*~1+6 49: ~20*~1-~6 50: ~2/.01/-6 51: ~2.0*~16 52: 20|1<<~-6 53: -20*~-~1+~6 54: ~2.0*~-~16 55: -20*~-~1-~-6 56: ~-~2*-016 57: ~20*~-~1-6 58: -20*~-~1^6 59: ~(20/~1*6) 60: -20/~1*6 61: ~2^0-1<<6 62: -2^0-1<<6 63: ~20/~1*6 64: 2-01<<6 65: 2+~0|1<<6 66: 2|01<<6 67: 2-~0|1<<6 68: 2*~!0*~16 69: ~20*~-~1+6 70: 20/~1*~6 71: -~(20/~1*~6) 72: 2+~0/.1*~6 73: -20<<-~1^~6 74: -20<<-~1^-6 75: ~-~-~2*~016 76: ~-20*(~1+6) 77: ~-~20/~1*-~6 78: ~-20<<-~1|6 79: -20<<-~1^~!6 80: 20*(~1+6) 81: ~2*~0**(~1+6) 82: ~-~-20|1<<6 83: ~-20|1<<6 84: 20|1<<6 85: -~20|1<<6 86: 20<<-~1|6 87: 20<<-~1|-~6 88: .2**~!0|1<<6 89: ~20*~-~-~1+~-6 90: ~2*~!0*~-16 91: ~20*~-~-~1-~6 92: ~-2/.01+~-~6 93: ~-2/.01+~6 94: ~-2/.01-6 95: ~-20*1*~-6 96: 2+01<<~-6 97: ~2+.01**~.6 98: ~-2/.01^6 99: ~-2/.01+~.6 100: 20*1*~-6 ``` ## Brute-forcer It ain't the prettiest code, but that doesn't seem to matter around these parts. **WARNING: Do not run** unless you are prepared for your browser/engine to freeze for a few minutes. Nobody likes to calculate 7 nested loops. ``` var a=new Array().fill("000000000000000000000000000"), // An array of non-solutions to start time=new Date(), // For timing how long this takes o=["","+","-","*","/","%","&","|","^",".","<<"], // Operators for between numbers p=["",".","~.","-","~","~-","-~","~-~","~-~-","~!"]; // Prefixes for each number for(i=0;i<o.length;i++) for(j=0;j<o.length;j++) for(k=0;k<o.length;k++) for(I=0;I<p.length;I++) for(J=0;J<p.length;J++) for(K=0;K<p.length;K++) for(L=0;L<p.length;L++) { // 7 nested loops = O(len(o)^3 * len(p)^4) z= p[I]+2 +o[i]+p[J]+0 +o[j]+p[K]+1 +o[k]+p[L]+6; // Put all the current chars in one string. try { v=eval(z) } // Try setting v to the evaluated value of z. catch(e) { v=-1 } // If an error occurs, set v to -1. if( (v === (v|0)) && // If v is an integer, and v>=0 && v<=100 && // v is between 0 and 100, inclusive, and z.length<a[v].length ) // z is shorter than the current entry, a[v]=z; // overwrite the current entry. } console.log("time: " + ((new Date()-time)/1e3) + "seconds\n" + "length: " + (a.join("").length) + "\n" + a.map((x,y) => y + ": " + x).join("\n")) ``` [Answer] ## PowerShell v3+, ~~1575~~ 1499 bytes ``` 2*0*16 2*0+1%6 2%016 201%6 20%16 2*0+-1+6 2*0+1*6 2*0+1+6 2+0*1+6 2+01+6 2*(0-1+6) #10 2*($a=01)*6-$a ################################## First variable 2*01*6 20-1-6 20*1-6 20+1-6 2*0+16 !!20+16 ################################## First Boolean not 2+016 2+!0+16 20+!16 #20 20+1+!6 !2+0x16 ################################## First use of 0x16 (20+1)-bor6 ################################## First binary or 2+0x16 20-1+6 20*1+6 20+1+6 20+($a=1)+6+$a 20+($a=1)+6+$a+$a 2*-bnot-016 #30 ############################## First binary not -bnot(-2*016) 2*016 -(-bnot(2*016)) -2*-bnot016 -bnot(-20)+16 20+16 20-(-bnot16) -(-bnot20)-(-bnot16) (20-shl1)-!!6 ################################## First binary shl (20-shl1)+!6 #40 (20-shl1)+!!6 ($a=2)*0x16-$a ($a=2)*0x16-$a/$a 2*0x16 -(-bnot2)*(-bnot-016) (20-shl1)+6 $a=20;$b=1;$a+$a+$b+6 -(-bnot2*016) 2*0+($a=1+6)*$a (20-shr($a=1))*(6-$a) #50 (-bnot2)*(-bnot016) 20+($a=16)+$a ($b=20*($a=1)+6)+$b+$a ($a=20+1+6)+$a ($a=20+($b=1)+6)+$a+$b ($a=20)+16+$a (($a=(2+!0))+16)*$a (20-shr($a=1))*6-$a-$a (20-shr($a=1))*6-$a (20-shr1)*6 #60 (20-shr($a=1))*6+$a (($a=2)*0+1-shl6)-$a -bnot-(2*0+1-shl6) 2*0+1-shl6 (2*0+($a=1)-shl6)+$a (-bnot2)*-0x16 ($a=201)/($a%6) 20+($a=16)+$a+$a 20+($a=16)+$a+$a+$a/$a -($a=2)*-bnot016*$a+$a #70 2*01*($a=6)*$a-$a/$a 2*01*($a=6)*$a ($a=2+01+6)*$a-$a+$a/$a ($a=2)*01*($b=6)*$b+$a ($a=20)+16+$a+$a-$a/$a ($a=20)+16+$a+$a ($a=20)+16+$a+$a+$a/$a 2*01*($a=6)*$a+$a ($a=20)%16*$a-$a/$a ($a=20)%16*$a #80 ($a=2+01+6)*$a ($a=2)*0x16*$a-$a*$a-$a 20+(($a=1)-shl6)-$a 20+(1-shl6) 20+(($a=1)-shl6)+$a ($a=2)*0x16*$a-$a ($a=2)*0x16*$a-$a/$a ($a=2)*0x16*$a ($a=2)*0x16*$a+$a/$a ($a=2)*0x16*$a+$a #90 ($a=2)*0x16*$a+$a+$a/$a ($a=2)*0x16*$a+$a+$a 20*(-1+($a=6))-$a-$a/$a 20*(-1+($a=6))-$a 20*($a=-1+6)-$a 2*(!0+1+($a=6))*$a 20*(($a=-1)+6)+$a+$a+$a ($a=2)*($b=01+6)*$b 20*(($a=-1)+6)+$a 20*(-1+6) #100 ``` 100% manually golfed - no brute force programs or other aids enlisted. ~~I feel that 1500 is *maybe* within reach~~ **Sub-1500 achieved!** Let's see how well I can do on getting this lower. (NB - This was only tested in v4, but should work in v3 and v5 without modification. Will not work in v2 or v1 as those versions did not have bitwise shift operators.) Key points are marked with `##.hashes.##` in the above code. **#11** is the first assignment to variable `$a`. Unlike some other languages, variables don't need to be pre-initialized for parsing, and it's only during execution that variables are resolved. Since the `($a=01)` is surrounded by parens, it's evaluated first and so the second `-$a` is equivalent to `-1`. This is used rather extensively from here on out, and is one of the biggest things keeping the bytecount down. **#17** shows the first use of `!` for Boolean not. In PowerShell, types are pretty loosely cast, so if casting can be implied, it'll work. Here, we're using the fact that `!!20` equals `!$false`, which is `$true`, which can be implicitly cast as `[int]1`, which results in `17`. This is used several times to either get another `1` or make a portion go to `0`. **#22** Showcases the `0x` hexadecimal cast operator, here turning `0x16` into `22`. However, since `0x16` is the only number we can get, its usefulness is limited. **#23** has the `-bor` operator, for "binary or." However, since both `-bor` and `-bxor` have *lower* [precedence](https://technet.microsoft.com/en-us/library/hh847842.aspx) than simple arithmetic operators, using them usually requires parens, which severely limits usefulness. This is the only one I've found where it's shorter to use the binary or operator (I eliminated the `-bxor` operator from 22). **#30** is the first time the `-bnot` operator is introduced. This is the "binary not" operator, and functions similarly to `~` in (e.g.) JavaScript. However, it usually needs parens, since the negation will show as `--bnot` and result in a parse/syntax error, and since it's five characters compared to one for `~`, it gets used sparingly. **#39** is the first use of our binary shift operators, `-shl` and `-shr`. These are similar to `<<` or `>>` in other languages, but are explicitly dyadic, meaning we need a number on both sides for them to work, which limits their usefulness in this challenge. Additionally, their precedence isn't explicitly called out in documentation, but testing shows them to be lower than simple arithmetic, meaning that parens need to be used liberally, so they don't make as much of an appearance as in other language answers. [Answer] ## CJam, ~~792~~ 791 bytes I kind of got lazy near the end, a lot of them just ended up being increments and decrements (101 is a lot!), although I'm not sure if there is any other way for a few of the numbers. There's still plenty of time to golf it if I need to. Around #40 there are some winky faces ;) ``` 2016! e# 0 2016g 2016g) 201 6% 20 16- 20)16- 20 1>6* 20 1>6+ 201mQ6- 201mQ6-) 2 01 6*(* e# 10 2 01*6*( 2 01*6* 2~016+ -2 016+ 2)016(| 20;16 2(016+ 2 016+ 2)016+ 20 16| e# 20 20)16| 20 1*6| 20 1|6| 20 16mQ+ 20_*16/ 20 1 6*+ 20 1+6+ 20 1)6++ 20)1)6++ 2 016(* e# 30 2 016*( 2 016* 201 6/ 2 016)* 20(16+ 20 16+ 20)16+ 20)16)+ 20_+16;( 20_+16; e# 40 20_+16;) 20)_+16; 20)_+16;) 20(1m<6+ 2)016(* 20 1m<6+ 2)016*( 2)016* 2)016*) 2)016)*( e# 50 2)016)* 20 16_++ 20)1 6(m<+ 20(_16++ 20_16++( 20_16++ 20_16++) 20)_16++ 20)_16++) 20 16mQ(* e# 60 20 16mQ(*) 2 01*6#(( 2 01*6#( 2 01*6# 2 01*6#) 201_+6/( 201_+6/ 201_+6/) 201mQ6(*( 201mQ6(* e# 70 20_16_+++( 20_16_+++ 20_16_+++) 20)_16_+++ 20(16mQ*( 20(16mQ* 20(16mQ*) 20_16^*(( 20_16^*( 20_16^* e# 80 2)016mQ# 201mQ6*(( 201mQ6*( 201mQ6* 201mQ6*) 201mQ6*)) 201mQ6*))) [20_16__]:+ [20_16__]:+) [20)_16__]:+ e# 90 [20_16)__]:+ [20__16_]:+ 20(1*6(*(( 20(1*6(*( 20(1*6(* 20(1*6(*) 201mQ6)*( 201mQ6)* 20 1*6(*( 20 1*6(* e# 100 ``` [Answer] # Mathematica, ~~2912~~ ~~2502~~ ~~2282~~ 2180 bytes Could *definitely* be golfed further. Mostly just solves a few separate Frobenius equations, which yields O(*n*) length solutions. The rest were generated by my brute-forcer. ``` 2 0 16 2-01^6 2 01^6 2+01^6 20-16 2 0-1+6 201;6 2-01+6 2 01+6 2+01+6 a=2;01 6+a+a 2#-01&@6 2 01 6 20-1-6 20 1-6 20+1-6 20;16 2^0+16 2+016 20-1^6 20 1^6 20+1^6 a=2;b=016;a+a+a+b a=2;b=01;c=6;a+a+b+c+c+c 201;a=6;a+a+a+a 20-1+6 20 1+6 20+1+6 a=2;b=016;a+a+a+a+a+a+b a=2;b=01;c=6;a+a+b+c+c+c+c 201;a=6;a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b 2 016 a=2;b=01;c=6;a+b+c+c+c+c+c a=2;b=016;a+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c 20+16 2;a=01;b=6;a+b+b+b+b+b+b a=2;b=016;a+a+a+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c a=20;16;a+a a=2;b=01;c=6;a+a+b+c+c+c+c+c+c 201;a=6;a+a+a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b a=2;b=016;a+a+a+a+a+a+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c a=2;b=016;a+a+a+a+a+a+a+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c 201;6!! 2;a=01;b=6;a+b+b+b+b+b+b+b+b 2 01+6!! a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c a=20;b=16;a+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c 201;a=6;a+a+a+a+a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b a=20;16+a+a a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c a=2;b=016;a+a+a+a+a+b+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c a=20;16;a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b a=2;b=016;a+a+a+a+a+a+a+b+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c 2&@01^6 a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c 201;a=6;a+a+a+a+a+a+a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b 20 1+6!! a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c a=2;b=016;a+a+a+b+b+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c+c 2#01#&@6 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b+b a=2;b=016;a+a+a+a+a+b+b+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c a=20;16+a+a+a a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c+c+c 201;a=6;a+a+a+a+a+a+a+a+a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b+b+b a=20;16;a+a+a+a a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c+c a=2;b=016;a+b+b+b+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c+c+c+c a=20;b=16;a+b+b+b+b 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b+b+b+b a=2;b=016;a+a+a+b+b+b+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c a=20;b=16;a+a+b+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c 201;a=6;a+a+a+a+a+a+a+a+a+a+a+a+a+a+a 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b+b+b+b+b a=20;b=16;a+a+a+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c a=2;b=016;a+a+a+a+a+a+a+b+b+b+b+b a=2;b=01;c=6;a+a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c 2 01 6!! 2;a=01;b=6;a+b+b+b+b+b+b+b+b+b+b+b+b+b+b+b+b a=2;b=016;a+b+b+b+b+b+b a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c a=20;16;a+a+a+a+a ``` [Answer] # JavaScript, 5244 chars Could probably be golfed a lot further. Test in the Chrome console. I kinda gave up at 10. ``` 201&6 !!2016 2%016 20+~16 20-16 -2+0+1+6 2*0*1+6 2*0+1+6 2*01+6 2+01+6 -~-~-~-~-~-~20-16 -~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~20-16 20*1-6 !!2+016 2+016 !!20+16 2.0+16 2+!0+16 20+!16 20+!!16 -~20+!!16 -~-~20+!!16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 2*016 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 (2+0)*16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16 20+16 -~20+16 -~-~20+16 -~-~-~20+16 -~-~-~-~20+16 -~-~-~-~-~20+16 -~-~-~-~-~-~20+16 -~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16 20*-(1-6) ``` [Answer] # Java 7, 1,083 bytes For the byte-count I've only counted the expressions itself between the parenthesis. So I've excluded the `System.out.println`s and `class`. Including those it would be **3,049 bytes**. PS: Not entirely sure if the int-cast for `72` is valid.. Although it does add 5 bytes anyway.. ``` 201&6 2-01%6 2%016 201%6 20-16 201%~6 2%01+6 2-01+6 2*01+6 2+01+6 ~2+016 ~2+016 2^016 20-1-6 2|016 20+1-6 2+016 2-~016 2+0+16 20-1%6 20|16 20+1%6 20*1|6 20|1|6 20+~1+6 20-1+6 20*1+6 20+1+6 2*016 20-~1-~6 -2*~016 20|~-16 (2+0)*16 20*~1^~6 -20*~1-6 20+~-16 20+16 20-~16 20-~-~16 -~2*~-016 20<<1%6 ~-(-~2*016) ~2*-016 ~20^-1<<6 ~20*~1^6 ~2*~016 20<<1|6 -20*~1-~6 ~20*~1+6 ~20*~1-~6 -20/~1*~-6 ~2*~-~-~016 20|1<<~-6 -20*~-~1+~6 20*-~-~1-6 -20*~-~1-~-6 ~-~2*-016 ~20*~-~1-6 -20*~-~1^6 ~(20/~1*6) -20/~1*6 ~2^(0-1)<<6 -2^(0-1)<<6 ~20/~1*6 (2-01)<<6 (2+~0)|1<<6 2|01<<6 2-~0|1<<6 ~-~2*~16 ~20*~-~1+6 20/~1*~6 -~(20/~1*~6) ~-~(int)2.0*~-~16 -20<<-~1^~6 -20<<-~1^-6 ~-~-~2*~016 ~-20*(~1+6) ~-~20/~1*-~6 ~-20<<-~1|6 ~-(20*~(1-6)) 20*(~1+6) -~(20*~(1-6)) ~-~-20|1<<6 ~-20|1<<6 20|1<<6 -~20|1<<6 20<<-~1|6 20<<-~1|-~6 -~-~20*(~1+6) ~20*~-~-~1+~-6 ~-~-20*-(1-6) ~20*~-~-~1-~6 ~20*~-~-~1-~-~6 ~2^~-~01<<~-6 -2^~-~01<<~-6 ~-20*1*~-6 (2+01)<<~-6 -~(~2*~-~0*16) ~-~-(20*-(1-6)) ~-(20*1*~-6) 20*-(1-6) ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/MXJuik) ``` class M{ public static void main(String[]a){ System.out.println(201&6); System.out.println(2-01%6); System.out.println(2%016); System.out.println(201%6); System.out.println(20-16); System.out.println(201%~6); System.out.println(2%01+6); System.out.println(2-01+6); System.out.println(2*01+6); System.out.println(2+01+6); System.out.println(~2+016); System.out.println(~2+016); System.out.println(2^016); System.out.println(20-1-6); System.out.println(2|016); System.out.println(20+1-6); System.out.println(2+016); System.out.println(2-~016); System.out.println(2+0+16); System.out.println(20-1%6); System.out.println(20|16); System.out.println(20+1%6); System.out.println(20*1|6); System.out.println(20|1|6); System.out.println(20+~1+6); System.out.println(20-1+6); System.out.println(20*1+6); System.out.println(20+1+6); System.out.println(2*016); System.out.println(20-~1-~6); System.out.println(-2*~016); System.out.println(20|~-16); System.out.println((2+0)*16); System.out.println(20*~1^~6); System.out.println(-20*~1-6); System.out.println(20+~-16); System.out.println(20+16); System.out.println(20-~16); System.out.println(20-~-~16); System.out.println(-~2*~-016); System.out.println(20<<1%6); System.out.println(~-(-~2*016)); System.out.println(~2*-016); System.out.println(~20^-1<<6); System.out.println(~20*~1^6); System.out.println(~2*~016); System.out.println(20<<1|6); System.out.println(-20*~1-~6); System.out.println(~20*~1+6); System.out.println(~20*~1-~6); System.out.println(-20/~1*~-6); System.out.println(~2*~-~-~016); System.out.println(20|1<<~-6); System.out.println(-20*~-~1+~6); System.out.println(20*-~-~1-6); System.out.println(-20*~-~1-~-6); System.out.println(~-~2*-016); System.out.println(~20*~-~1-6); System.out.println(-20*~-~1^6); System.out.println(~(20/~1*6)); System.out.println(-20/~1*6); System.out.println(~2^(0-1)<<6); System.out.println(-2^(0-1)<<6); System.out.println(~20/~1*6); System.out.println((2-01)<<6); System.out.println((2+~0)|1<<6); System.out.println(2|01<<6); System.out.println(2-~0|1<<6); System.out.println(~-~2*~16); System.out.println(~20*~-~1+6); System.out.println(20/~1*~6); System.out.println(-~(20/~1*~6)); System.out.println(~-~(int)2.0*~-~16); System.out.println(-20<<-~1^~6); System.out.println(-20<<-~1^-6); System.out.println(~-~-~2*~016); System.out.println(~-20*(~1+6)); System.out.println(~-~20/~1*-~6); System.out.println(~-20<<-~1|6); System.out.println(~-(20*~(1-6))); System.out.println(20*(~1+6)); System.out.println(-~(20*~(1-6))); System.out.println(~-~-20|1<<6); System.out.println(~-20|1<<6); System.out.println(20|1<<6); System.out.println(-~20|1<<6); System.out.println(20<<-~1|6); System.out.println(20<<-~1|-~6); System.out.println(-~-~20*(~1+6)); System.out.println(~20*~-~-~1+~-6); System.out.println(~-~-20*-(1-6)); System.out.println(~20*~-~-~1-~6); System.out.println(~20*~-~-~1-~-~6); System.out.println(~2^~-~01<<~-6); System.out.println(-2^~-~01<<~-6); System.out.println(~-20*1*~-6); System.out.println((2+01)<<~-6); System.out.println(-~(~2*~-~0*16)); System.out.println(~-~-(20*-(1-6))); System.out.println(~-(20*1*~-6)); System.out.println(20*-(1-6)); } } ``` ]
[Question] [ Sometimes in chat, if someone says something you agree with, you'll send a message with an `^`, which points at the message above: ``` Radvylf: Cats are far superior to JavaScript You: ^ ``` Sometimes you'll also add some text: ``` Radvylf: I sure do like integers You: I mostly agree with ^ but floats are pretty neat too ``` You can also use multiple `^`s to refer to messages farther back: ``` Timmy: Puppies are adorable. Radvylf: I hate puppies. You: ^^ ``` In this challenge, given a chat log with `^`s, you'll replace the `^`s with the messages they refer to. **Task:** Given a multiline string of messages (without usernames), or an array where each message is a string (or some representation of one), resolve all of the `^` references in it. Note that messages can refer to messages that themselves have `^`s, which need to be properly resolved. For example: ``` Cats are funny sometimes ^ ^^, but I've met serious cats too. ^^ Opinions on static typing? It's okay. ^ It depends on the implementation, though. ^ Big difference between good and bad static ty ^ping Thanks ^_^ ``` This would become: ``` Cats are funny sometimes Cats are funny sometimes Cats are funny sometimes, but I've met serious cats too. Cats are funny sometimes Opinions on static typing? It's okay. It's okay. It depends a lot on the implementation, though. It's okay. It depends a lot on the implementation, though. Big difference between good and bad static ty It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing Thanks It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing_It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing ``` You'll never need to resolve a group of `^`s that points up more times than there are messages to point at. E.g., `^` will never be the first line, and `^^` will never be the second. **Test cases:** Input: ``` a ``` Output: ``` a ``` Input: ``` a ^b ^^ ``` Output: ``` a ab a ``` Input: ``` a ^b ^c ^ ^^ ^^^ ``` Output: ``` a ab abc abc ab a ``` **Other:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins. [Answer] # JavaScript (ES6), 56 bytes Expects and returns an array of strings. ``` a=>a.map((s,i)=>a[i]=s.replace(/\^+/g,s=>a[i-s.length])) ``` [Try it online!](https://tio.run/##jYtBDsIgEEX3nIJdh0jpCfAitSQjThGDQDqN18dWu3Rh8pOXn/f/A1/Ifol17XO5UZttQ3tG88QKwDqqrYxxsmwWqgk9wXBxpyFo/oieTaIc1vukVPMlc0lkUgkwwyik7LATmxE/jd7hrgfd30t/ULo93197Aw "JavaScript (Node.js) – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 240 bytes ``` +>>,[[->+<<+>]>----------[+[-<+++>]<+[[-]<.>>,>>>>]<[[[<]<]+[[>]>]<<,[->+++>+<<]+++++[->-----<]>-[[-]<<[[<]<]>>->[.[[>]>]>[->+<]<<+[[<]<]<+>>>-[[[>]>]<<+[[<]<]<+>>>-]>]<<<<[[->>>+<<<]<]>>>+[[>]>->>]<+[-<+>]>>]>[[-]<<+>]<]]<<[.[-]>>>+>>,>]<] ``` [Try it online!](https://tio.run/##VY6xboUwDEV3vsLbG0L4gsiV2ulNXbpFoQpgIHolQSS04uupE6pW9ebrc@91t1nnx71/nKdArLWWKJQSaFD@jhZaKiFYVIIBoxomkccorbUyyrDMDqNUnf1McoYReXgvGYoDi1ddDkSJurlsWEr5JK4b12OmfzL/qUXJIZI3brmy8HpAYnlRlv9zbinMf5tc3PCa2fw9S@f5YlMEuxGMu/cHxLBQcgvFqq3atoZuT3C/fRKwDJE2F/YIffakEBpGqtfVeRd8hOAhJptcD@lgbXqq7unG8sMeDMI9wUAr@aGQaSZwy/pBC/lsCr5mLezTnNlnN8HgxpE28j1BR@mLyMMUwgDWD9DZ4a@ranNb9TZb/4jQvrff "brainfuck – Try It Online") Now works with blank lines. This ended up saving bytes, and the slightly altered tape structure allowed the two other improvements I had tried earlier to save bytes as well. The tape structure of this program is as follows: ``` 1 firstline 0 0 0 1 secondline 0 0 0 ... 1 lastline 0 input ``` The 1 cell at the beginning of each line allows the program to cope with empty lines and lines beginning with `^` without additional effort. It also allowed me to shorten the gap between text lines, which saved a small number of bytes. With formatting and comments: ``` Initialize tape with first line marker and input +>>, While there is input: [ Duplicate input [->+<<+>] Test for newline >---------- If not newline: [ Test for ^ (94) +[-<+++>]<+ If anything else: [ Output letter and take next input [-]<.>>, Move so rest of loop will end at next input cell >>>> ] If caret <[ Place 1 between text lines to track which line to copy [[<]<]+[[>]>]<< Duplicate next input and check if caret (there's probably a shorter way to do this) ,[->+++>+<<]+++++[->-----<]>- If not another caret: [ Clear test cell [-] Move to start of line to copy and delete the 1 from it <<[[<]<]>>-> For each letter in that line: [ Output . Move next input cell to the right [[>]>]>[->+<] Populate cell to copy to; start backup copy too <<+[[<]<]<+>>>- Copy letter to (next letter in current line) and (backup 3 left) [[[>]>]<<+[[<]<]<+>>>-] >] Restore line and initial 1 cell <<<<[[->>>+<<<]<]>>>+ Clear indicators between lines [[>]>->>] Move input to correct cell (that cell contains negative one from the previous loop) <+[-<+>] >>] If was another caret: >[ Delete input and set indicator to repeat caret loop [-]<<+> ] <]] If newline: <<[ Output newline . Set up next line [-]>>>+>>,> ] <] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly),~~19~~ ~~18~~ 17 bytes ``` ɓŒgċ”^ịṭʋ€Ṛ}Fṭðƒḟ ``` [Try it online!](https://tio.run/##RY2xSsRAEIb7fYrprjl8BUFBSGVjY7OyyU6SvUtmQ3bjkUJQG8F0d50gFrYKFhaGA5vTg/MtNi8SdwU5mGLm4/vnn2FRtOO4W30vs69uuH7kbt25/vWnG25fXP9wdeKPzdt26T6exuHmkzGvrlz/7Nbvm7vz7b3XZuMoGBOMx4zz/yVhHHgYT46FNSBqhLQhasHoEq0q0TDuA1OIGwvR5BLBYzBYK90YSELGan0Qfp5WipQmA5rAWGFVArb1LDtkkZ14PBetFyGyILFCkn@mzRFUWRVYIoWQpqlnusny4B6pDKRKU6yREoQY7QKRINNagiAJsZD7LsZDGzvLBc0N8Av@Cw "Jelly – Try It Online") *-1 thanks to Jonathan Allan* *-1 thanks to Jonathan Allan again* Takes and returns lists of lines. ``` ð ḟ Starting with the input without any of its elements, ƒ reduce by: ɓ with reversed arguments: (line on left, lines on right) Œg Runs of consecutive equal elements. ʋ€ For each run: ṭ append the run to } the accumulated lines Ṛ reversed ị and get the item at the 1-index of ċ”^ the number of carets. F Flatten the runs and substitutions back together, ṭ and append to the list of accumulated lines. ``` Love when I shave two bytes off (from `ɓŒg=”^Sị⁸¹?ɗ€Ṛ}Fṭµƒ“”`) in the course of writing an explanation :P [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes ``` +1`(\^)+(?<=(.*)(?<-1>¶.*)+) $2 ``` [Try it online!](https://tio.run/##RY1NSsRAEIX3fYq3ECYx48C41hnQVVZuXEprJ11JmjHVIV1RcjEP4MVitSBCQT0@3s9MEthtW3V8K15sWRXnu/vicF3qvzmevr9UVqW5ut02Z4wztjHW/onWWNh8Sh6dJLiZ0C3MK1IctXikZKwG9mgWQb37IChGojnEJaHNGYnxkDufpsAhckJkJHESWsiqrD@bWnaKL25VI2qBp4nY/zplIIRxeqeROIci75XFpR@y9yH08KHraCZuCQ3JJxGjj9HDsUfj/P@WsXnNPA@OLwn21f4A "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +1` ``` Replace one match at a time, repeating until all matches have been replaced. (This allows a replaced line to be referenced in a later line.) ``` (\^)+(?<=(.*)(?<-1>¶.*)+) ``` Match a number of `^`s, then search back that many lines for the replacement text. ``` $2 ``` Replace the `^`s with the found text. [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` import re def f(a,*q): for x in a:q+=re.sub("\^+",lambda k:q[-len(k[0])],x), return q ``` [Try it online!](https://tio.run/##FY3NCoMwEITP5ikWT0lNRehN6JNYA7EmNBjzs0awT592YWBg@GYmfcsnhketbk8RC6Bhq7FguZa3LEbW2IhwgQugx9w90fTHufD2pbpWer0vq4ZtzNPdm8C3aZjFLC8hWYOmnBggV@p7FwxNWB7TnxtEj0avXPRHQZfIk3eFqIMLOk3oQuEUiKqZWph6MwWKpH4 "Python 3 – Try It Online") -11 bytes thanks to Unrelated String [Answer] # [Ruby](https://www.ruby-lang.org/), ~~57~~ 51 bytes ``` ->c,*q{c.map{|l|q<<l.gsub(/\^+/){|r|q[-r.size]}};q} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5ZR6uwOlkvN7GguianptDGJkcvvbg0SUM/Jk5bX7O6pqimMFq3SK84syo1trbWurD2f0FRZl6JQppecmJOjka0UqJSrKaCsgKYwcWFIamjFJcEIuIgysAiiSAR/MqTQYRCHAjFISyAaU1KhpAKiUkKQHP@AwA "Ruby – Try It Online") * Saved 6 Bytes thanks to @G B Lambda taking and returning an array of lines. Instead of iterating the size of the array G B proposed to build the output by adding lines one by one, so that we take from that the previous (size of match) line. We use *gsub* and the {|match| block form } which brings the last match every time. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εD'^ÃηRāR(N+¯sè:=ˆ ``` Input as a list of lines. [Try it online](https://tio.run/##RY0xS8RAEIX/ypAmByb@gAMR1CaNwmEnrmyyk2S5y0zITJTYieBvsbMSe89OuL8Ud2NxxbyB977HY7Glx3k@fF6lZv96@Nr8vGxW1yffH7J/X5/9vs3zXXJpVcAOCPVINIFwh@o7lCRLTDyTQTkqFOkjQohAcPA8ClSxp8ynCxTkpvfkmQSYQNSqr0Cn4DXnISw0DcHWTgsOhYLDHskttLYIvut32CHFIlMWPB6b9p@@8A04X9c4IFUIJeoTIkHD7MCSg9K642JsxNXwb1tLWwHzYJL7Oc@J8519nv4A) or [verify all test cases](https://tio.run/##XU/NSsNAEL77FMNeIrjxAQoSUC@5WCjeSiObZJosbWZDdlKJ4EEEn8WbF3/uqTehr5TuJoIgDDPM9zMfY6xKNQ47EVPd8gxE1MkTMW952mQ3HD6ug2T/fPhafD8tTm/O@je7f51d/LwMj/1n1L8Py6VQYiXBDymS1LfkP5D5BomvX@5KsQXVIKxbog6sqZB1hdYLxxMS0pYhDnYIjgKLjTathcz72JjzKUeKea1JG7JgCCwr1hlw57AicmTMgSM2qhvlEDPkWCPlo5pLBF3VW6yQvNGQdJhpi3JSX@oCcr1eY4OUIaTI94gEhTE5KMohVflfonf4VDdvS0UbC8mde3U1hCGZcKseuiM). **Explanation:** ``` ε # Foreach of the (implicit) input-list: D # Duplicate the current line '^à '# Pop the copy, and only keep its "^" η # Pop and push the list of prefixes of this "^"-string R # Reverse this list of prefixes ā # Push a list in the range [1,length] (without popping) R # Reverse it to range [length,1] ( # Negate each to range [-length,-1] N+ # Add the 0-based loop-index to each: range [N-length,N-1] ¯ # Push the global array s # Swap so the list of indices is at the top again è # Index each into the global array : # Replace all "^"-strings with these strings in the current line = # Print the modified line with trailing newlines (without popping) ˆ # Pop and add it to the global array ``` [Answer] # [D](https://dlang.org/), 100 bytes Returns by modifying its input, exits with error. ``` import std;void f(string[]s){for(int i;;i++)s[i]=s[i].replaceAll!(x=>s[i-x[0].length])=`\^+`.regex;} ``` [Try it online!](https://tio.run/##RVFLb4MwDL7zK7xeCupD3Rl10zbt0NMuu3WwBmIgKjhVYvpQxW/vHDZ1UuIo/h7@lOjbzXQH6xg86/RojYYq9uwM1dvMJ9fKutgQg0lTM5slfmuydShLh4dWlfjStg/xef0kvcV5u8qWLVLNTZasd1/5bCe0Gs/pcBudXU93b2D0nMA1AmB3kaHjPYVScdlA/O6cdYBCGAJDsCWqsnk4OcPYUhoNUTR6dspQnASb7URN5pO8CKUMBfKw8omE7UUB8CeOp4tpyI@K48dVkqSj@E2xB@UQqp7oAt52yKZDH5zCzudQ9Ayb6RFBIPDojO19COyBrV2OJCkfB0PGkgdL8qiKTQl8kV79LOCGpwLs1WWkw4ZBSxDSI5sbBPmNFjukILQ0l57t6@aX/Wpq0Kaq0CGVCAXyCZGgtlaDIg2F0v8TgyJMlfOzUbT3kH/f32K4/QA "D – Try It Online") --- # [D](https://dlang.org/), 97 bytes This one returns a Range and doesn't error. ``` import std; ``` ``` (string[]s,int i=0)=>s.map!(r=>s[i++]=r.replaceAll!(x=>s[i+~x[0].length])=`\^+`.regex) ``` [Try it online!](https://tio.run/##RZBNb4MwDIbv/RUuF0BlqDsjNm079bTLbh2sKTEQFRyUmH5o6v46S@jUSYlt2c9rW5bTpPpBGwbLMhMja6jzyLJR1GwLmyhiUPk6zp9s2othGRkXbdVqVeQmNTh0osKXrltG51v@57xdF2mH1HBbxPnus1ztHNfgOZ6yxVErCWak@wBgtBzD9wKgjuY4RVG1y5NRjB1li@viJuqFoij23DYQQRKUe28qb6D0rwyK1HXOHPEnjsKH0K@IgqPHdRxns/hNsAVhEOqR6AJW98iqR@s7@V8msB8ZNuERwZXAolF6tFB5HWudzpAz74MipcmCJnc7waoCvrhc8@yKGw5d4SAuMw4bBukWITnT3CK4o3fYI3mhpsTl9Ni0N/pVNSBVXaNBqhD2yCdEgkZrCYIk7IX8n@gVfqrzH62gg4Xy636L6/QL "D – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 43 bytes Full program. Prompts for and prints list of strings. ``` ⊢{(⍵⊃t)←'\^+'⎕R{t⊃⍨i-≢⍵.Match}t⊃⍨i←⍵}¨⍳≢t←⎕ ``` [Try it online!](https://tio.run/##RY@/TsMwEId3P8VtAdFW8ARIIIYOCEQZUZAbXxOrjR3FF1BUdQLxpyiIhZWhXbpXvACP4hcJ5yBUL7Y@fb/7nWUx66tazmzaOlK2Iv/0Mffvn3z55nvxs/HLtX97ZDI6G1gzQue0NZelNsGM/jIRG/zSpgs3XyHWbIV/eS5av1zN93iUXz7QfojcxAcRj7uaEyPfbHTfv65YGJxLSrLFP90t0GxZCG2canlmC90pRFcJR4fiVJIDWSJMKmNqcDZH0jk6EYs47sG4IhhGdwiMwWGpbeUgCRmydsCKuCi04W85sAYcSdIJUM0sPRZDihhPZc0iDAkUFmhUZ1KGoPNihjmaELKmx8xWaRbcE52C0pMJlmgShDHSPaKB1FoF0igYS7XrEnFoE9eZNFMH8W38Cw "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for text from console `t←` store in `t` `≢` tally of texts `⍳` **i**ndices 1 through that `{`…`}¨` apply the following anonymous lambda to each text; argument is `⍵`:  `i←⍵` store argument as `i`  `t⊃⍨` pick that element from the input  `'\^+'⎕R{`…`}` **R**eplace each run of carets with:   `⍵.Match` the match   `≢` the length of that   `i-` subtract that from `i`   `t⊃⍨` pick that element from the input  `(⍵⊃t)←` in-place update the argument'th element of `t` with that (and implicitly return it) `⊢` return (and implicitly print) that [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 106 bytes ``` T =TABLE() I X =X + 1 I =INPUT :F(END) R I SPAN('^') . K =T[X - SIZE(K)] :S(R) T[X] =OUTPUT =I :(I) END ``` [Try it online!](https://tio.run/##FYzBCsIwDEDPyVfktgRREDwVepisQpnUsXYwlAWcV3EH/58a4Z0evPf9bOv2PtUKhXxpz9fAghFm8jPt6IgQycc0TAXchUPqBEdTeWgTN9oIHai37jHTnnK8B@5lAZd5FASzC/nbVKy2CTiOgrao9Ym6or5QSf/oDw "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # Lua, 83 bytes ``` s=...;for i,l in ipairs(s)do print((l:gsub("%^+",function(m)return s[i-#m]end)))end ``` Must be loaded as a "chunk" (file or string). Expects input as table of strings. Prints output. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~191~~ ~~186~~ 181 bytes ``` #import<regex> int f(std::string*a,int n){for(int b=0,c,i;b<n;++b)for(i=-1;++i<a[b].size();c?a[b].replace(i-c,c,a[b-c]),i+=a[b-c].size()-c:0)for(c=0;a[b][i]==94;++c)++i;} ``` [Try it online!](https://tio.run/##TU7RaoQwEHz3K4KFXlJjuYIvZ5L2Q6xC3IuycCaiEUrFb7eJ3kOXZZgddmcHxjHvAfb9BYfRTV5Opjc/nwlaTzo6@3tZzn5C279pHjXL1s5NNNJWXTlwFK20Istadugq/wgDSl219fuMv4YyAV/HNJnxocFQzCHcBSmHmnHM1Emf2zmU18MK1FXEuwprpW5FcAUWnMUWolp4LHcj0YVsRg9n3EGjpSxZExLqX3Kiq6JeU53ytGkjQATSxG7STRz7HdW8YE8evzs7e6IX78grkpJodlqCWzyRkmCEy7e9iGRL9j8) Dang, this is bad. Only wins the Brainfuck answer lol. For anyone trying to help here's the ungolfed code: ``` #include <iostream> #include <vector> #include <string> void chat_reference(std::vector<std::string> &chat) { for(int list_message = 0; list_message < chat.size(); ++list_message) { int reference_counter = 0; for(int i = 0; i < chat[list_message].size(); ++i) { while(chat[list_message][i] == '^') { ++reference_counter; ++i; } if(reference_counter > 0) { chat[list_message].replace(i - reference_counter, reference_counter, chat[list_message - reference_counter]); i += chat[list_message- reference_counter].size() - reference_counter; reference_counter = 0; } } } } ``` *-6 bytes thanks to ceilingcat* *-4 bytes thanks to ceilingcat* *-11 bytes thanks to ceilingcat* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~51~~ 43 bytes ``` WS«⊞υω≔⁰θF⪪⁺ιψ^¿κ«⊞υ⁺⁺⊟υ⎇θ§υθω⁻κψ≔±¹θ»≦⊖θ»υ ``` [Try it online!](https://tio.run/##RY89b4MwEIbn@FecssRItGrnDFU/Foa0kZKZyoEDLOBM7HNSVOW3U5uk7XKSXz3vh4tG2cKobprOje4QZEaD5x1bTbVMEvgWi613jfQpnJO1WDw7p2uSDykc47MyFuRu6DTLbeed1CmMSQrLfBm8ugLZzhF/GTN0PWaQPqB7tKTsKI8pPHNGJX5F7pjEvnA2mgLcxtgkFv4OeMdaMcrH5DbkIhbYOYSNGm7EGxYWeyTG8spcxDb8ikPreppeFTtQFqHyRCM40yPrHp3IRZ6ncPAM2eqEEGRwaLXxDoroYWPuAyI@Bk3akAND4FixLoDHoNVPIuNVkFs1BhAyhhIHpHImuUHQ/dDNw4LJUBo04@smsi@6hlJXFVqkAuGAfEYkqI0pQVEJB1X@d4k8tol9o6h1kH/mYro7dT8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated lines. Explanation: ``` WS« ``` Repeat for each line. ``` ⊞υω ``` Add a new empty output line to the predefined empty list. ``` ≔⁰θ ``` Start with no `^`s. ``` F⪪⁺ιψ^ ``` Append a null character to the input line, split the result on `^`s and loop over the pieces. ``` ¿κ« ``` If this piece is not empty, then... ``` ⊞υ⁺⁺⊟υ⎇θ§υθω⁻κψ ``` ... remove the last line, concatenate a previous line if there were `^`s accumulated, concatenate the split piece without any null characters, and add it back to the list of lines (the indexing for the previous line works because the last line isn't in the array during the concatenation); then... ``` ≔±¹θ ``` ... set the number of `^`s to `1` assuming that there's a following piece that was separated from this piece with a `^`. ``` »≦⊖θ ``` Empty pieces correspond to consecutive `^`s so simply increment the number of `^`s. ``` »υ ``` Output the final list of lines. ]
[Question] [ Repost and improvement of [this](https://codegolf.stackexchange.com/questions/125/test-if-a-given-number-is-a-vampire-number) challenge from 2011 A [vampire number](http://en.wikipedia.org/wiki/Vampire_number) is a positive integer \$v\$ with an even number of digits that can be split into 2 smaller integers \$x, y\$ consisting of the digits of \$v\$ such that \$v = xy\$. For example: $$1260 = 21 \times 60$$ so \$1260\$ is a vampire number. Note that the digits for \$v\$ can be in any order, and must be repeated for repeated digits, when splitting into \$x\$ and \$y\$. \$x\$ and \$y\$ must have the same number of digits, and only one can have trailing zeros (so \$153000\$ is not a vampire number, despite \$153000 = 300 \times 510\$). You are to take a positive integer \$v\$ which has an even number of digits and output whether it is a vampire number or not. You can either output: * Two consistent, distinct values * A (not necessarily consistent) truthy value and a falsey value + For example, "a positive integer for true, 0 for false" You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. The first 15 vampire numbers are \$1260, 1395, 1435, 1530, 1827, 2187, 6880, 102510, 104260, 105210, 105264, 105750, 108135, 110758, 115672\$. This is sequence [A014575](https://oeis.org/A014575) on OEIS. **Be sure to double check that your solution checks for trailing zeros; \$153000\$ should return false.** [Answer] # [Husk](https://github.com/barbuz/Husk), ~~18~~ ~~17~~ ~~14~~ ~~13~~ 12 bytes *Edit: -3 bytes, and then another -1 byte, thanks to Leo, and -1 byte thanks to inspiration from [pajonk's R answer](https://codegolf.stackexchange.com/a/218803/95126) (3rd edit)* ``` €¹mΠ†dm½f→Pd ``` [Try it online!](https://tio.run/##AS8A0P9odXNr/23igoH/4oKswrltzqDigKBkbcK9ZuKGklBk////WzEyNjAsMTUzMDAwXQ "Husk – Try It Online") Outputs nonzero integer if it's a vampire number, zero otherwise. Commented penultimate version: ``` €¹ # index of input if present, zero otherwise, in mΠ # products of each element-pair †d # combining digits as a number from m½ # first & second halves of P # all permutations of d # digits of input; f # and filtering only element-pairs for which ṁ→ # sum of last digits is nonzero ``` [Answer] # [R](https://www.r-project.org/), ~~156~~ ~~146~~ ~~143~~ 135 bytes *-10 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* ``` function(n,s=strsplit){for(i in 1:n)if(!n%%i&nchar(j<-n/i)==nchar(i)&all(el(s(paste0(j,i),''))%in%el(s(c(n,''),'')))&i%%10)return(T) F} ``` [Try it online!](https://tio.run/##JYxBCoMwEEX3PYVdRGfA0kSJSmm2PUEvIGLoSBgliavSs6cSV//99@H7ZE2yO0@RVgaugwnRh81RxK9dPVBBXKgHI1m4shBU8vQZPSzPG98JjTkrYTk6B7ODANsY4ixhqQnrqkIUxCIP0/F/iCyxJCGURD/H3TO88fL6JQuq6SRejtStlJn6XOWgWp1JyV4PJ@mubzD9AQ "R – Try It Online") [Answer] # [J](http://jsoftware.com/), 43 bytes ``` ".e.-@-:@#((0<[:".{:\)*[:*/".\)"1 i.@!@#A.] ``` [Try it online!](https://tio.run/##XY9RT4MwFIXf9yuO8ABMqC1zGzZjQY17MnvY6@YDYskwDAgtukTjX5@lTBNt0ub29Lvn3L6eLOLkiDkc@KDgegcE95vHlX4RJEgCntiuSxdbbpEPvvPGWz6@ssjOsxgKklwk9i15Onmj9R3BwzE9NKWAElIhS6WQyOsWshFZkRcZqu7wLFpJCDH4qm4PKCQ3l36JbF9jIY6aV@IFrZBdqZaIkWNRVE2nlgbdCNW1lYQeIIfan/OaVOpAMhoZF2a6HBbOqDMo9Fdhzl@GTWfz8B81nVCqOwfRCYJA1332un4f4tKyhHgT1c@n0DVQNWZRREe9LmMC1/4CjcNPO7G4RT2wy4IYYLB1@@l8NrmZ@ux6og8d6rMonPshi@Z@T3oIuLHJzxbG@vQN "J – Try It Online") Takes digits as a string. For each permutation `i.@!@#A.]`, use half the digit length `-@-:@#` to take non-overlapping infixes -- which slices into 2 halves -- and multiply those halves`([:*/".\)"1`. Then (to handle the trailing zero constraint) multiply *that* by `(0<[:".{:\)*`, which takes the last digits of each half, cats them, evaluates that as a two digit number, and checks if it's greater than 0. Finally, check if the input number `".` is an element of that list `e.`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 88 bytes ``` f=(n,i=1)=>n<i*i*10&&i%10&&[...''+i+n/i].sort()+''==[...''+n].sort()||n*10>++i*i&&f(n,i) ``` [Try it online!](https://tio.run/##XYxBDoIwEEX3nGI2th2qtdWgCygXMS4IWlNDpgaIG/HstRhNjJvJn/fz/rW5N0Pb@9u4onA6x@isoKW3Bm1Nlc99bjRjfjHfg1KKc@klrf1RDaEfBUrOrf0U9IXTREmrpUw@Y24exNgGGkJ3Vl24CCeMKXb7DWL2h4ut1jrhzIVeEFgw6S@BoHqnOUqJ8MgAvINkECL8bhCW2TO@AA "JavaScript (Node.js) – Try It Online") * `[...''+i+n/i].sort()+''==[...''+n].sort()` two factors use and only use digits in original number + if `n/i` is not an integer, it converted into a string with `.` and not equals to another side which doesn't contain a `.`. * `n<i*i*10`, `n*10>i*i`: lengths of two numbers are the same. + It equip to `i/10 < n/i < i*10`. And since `n` has even number of digits (as question mentioned), `i` and `n/i` will have same number of digits. * `i%10`: `i` is not end with "0" [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œ2δäÅΔPQy€θĀà* ``` Outputs a non-negative integer as truthy and `-1` as falsey. [Try it online](https://tio.run/##ASgA1/9vc2FiaWX//8WTMs60w6TDhc6UUFF54oKszrjEgMOgKv//MTUzMDAw) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZX/j042Orfl8JLDreemBBxaF1j5qGnNuR1HGg4v0Ppfq/M/2tDIzEDH0NjSVMfQxBhImBoDuRZG5jpGhhbmOmYWFkCugZGpIYgyAas1MDUyhFBmJiDK3BTEszAE6TY0MDe1AFKmZuZGYLMMgHJGxiamZrEA). **Explanation:** ``` œ # Get all permutations of the (implicit) input δ # Map over each permutation: 2 ä # And split it into two equal-sized halves ÅΔ # Get the 0-based index of the first truthy result, # or -1 if none are found: P # Take the product of the two halves Q # And check that it's equal to the (implicit) input y # Push the halves again €θ # Only leave the last digit of each halve Ā # Check that it's not 0 (1 if [1-9]; 0 if 0) à # Get the maximum of these two * # Multiply the checks to verify both are truthy # (after which the found index is output implicitly as result) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~286~~ ~~240~~ 218 bloody bytes (o,\_,o) -55 bloody bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)! ``` #define S(x,y)x^=y^=x^=y o,a,b,c,r;f(int*_){c=atoi(_);v(o,_,o=strlen(_),r=0);r=r;}v(k,_,o,i)char*_;{--k?({for(v(k,_,o,0);i<k;v(k,_,o,!++i))S(_[k%2*i],_[k]);}):(a=atoi(_)/exp10(o/2))*(b=atoi(_+o/2))==c&&(a+b)%10?r=1:0;} ``` [Try it online!](https://tio.run/##bU5Nb8IwDL3zKwxTJ7sNou1thIgfwZFBVULLIkqD0oBAVf/6uoTxscN8sJ/t9@wnxzsp@/5tW5SqLmCBF3aly1pc18LngWY52zDJDC9R1TbMqJUit1phRvyMmmVMi8aaqqjdhBkREzfC8O6Me79jiuRXbsKMt@Pxfo5tqQ0@do6rZnv@aIdRpIgWmC33QRqqFXNgRbyjKeaPn5Pickxi1JOUKMTNfRzdeiHk@zvm0YaCJJ4bkUxj3vXONRxyVSOctdoCDdoBuPCuwBaNXX6s@G1yS96eV1gQkHBXZpDGPhyOIoL2RfWhSoQhegVVeueM4VafNlVBliCAlIDcidCdivlT8wTN0Thhid4Fg1GwHTGw9A/Rf/ml@YN3leN/1n8U3cuZKezJ1OB@dv23LKt81/Tj6vAD "C (gcc) – Try It Online") The input is a string and the output is either 1 or 0. The core of the answer is the function `v()`, which implements [Heap's algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm) to generate all the possible permutations of the input digits. Here's an explanation of the code before some golfing: ``` #define S(x,y)x^=y^=x^=y // Macro used to swap digits o, // length of the input string a, // first half of one of the possible permutations of digits b, // second half r; // result: 1 if the input is a vampire number, 0 otherwise char c[9]; // copy of the original input that will be compared with the permutations f(_)char*_;{ // That's a simple function taking the input string r=!strcpy(c,_); // initializing `r` to 0 and `c` to the input v(o,_,o=strlen(_)); // calling v(o,_,o) while initializing `o` to the length of the input r=r; // and returning rhe result `r` } v( // v() is a recursive function taking three parameters: k, // the length of a substring of digits being permuted _, // the whole current permutation o, // the length of the whole permutation i) // `i` is here just to avoid declaring `int i` inside the `for` loop char*_;{ if(k-1){ // if `k` is not 1 v(k-1,_,o); // call v() to permute `k-1` digits for(i=0;++i<k; // until `i` is less than `k` v(k-1,_,o)) // call v() to permute `k-1` digit, but only after having S(_[k%2?0:i-1],_[k-1]); // swapped _[k-1] with either _[0] or _[i-1] } else // else (i.e. if k == 1) (a=atoi(_)/exp10(o/2)) // if `a` (getting the first half of the permutation, converted to integer) *(b=atoi(_+o/2)) // multiplied by `b` (getting the second half) ==atoi(c) // equals the original input &&(a+b)%10? // and only one between `a` and `b` has trailing zeros r=1 // then the result is set to 1 :0; // otherwise do nothing, this permutation wasn't the right one } ``` I tried other algorithms, but couldn't find a shorter one. I leave here [the dumbest](https://tio.run/##fVLBbtswDL37K4gWKSRbXu1cFQ3Ypadip@2UZYAsy5lSRR4UBUgW@NfnUUrdJC0wGqAIiu@RfLIq10qN98Ypu281LHahNf2nX5/H@1Z3xml4Igd2pF3viXEBDqLih8WRH4qCnjLJGqaYZxuedcQxS7Ekd/y089K1JJitJl@/Pz9TyhXinojBEiVUXleFW5oVH1Iqxy812AjLy3LD6cmLxEBnyOyWm9VP4ZY@@SnmUjSJ84XZxzmVQp5ZX1a8Ec1rXOAVdjEdkXkjhHp4ILJo6KyuqNdh7x3UfBiGMW6Wo/vWf/FeHtOmgUE8rHaUZ1kMt9I4QrNTBmgJ4li85ymR3CRTAIHUeCxgXkXDGBWDM/atPBF1BAiyIIJELLX9uq4Iaft9YzUNtKgphRnMIcLfYNFwAmxT8ZskUhXFJTV87BhbXS0b2LTk9UjxPVMeBPbA3r89YjpyN2t/uDsGgfKPzJ3Xmrj3N8NFn1fVceThrOl/VL8RGkfeSmt7RWBn/ui@S1JBHithmn1S32A15kt8AVNEV5Y32sV/D0sCqnqtXoDHi5xDdj0wvvEw/lWdlevdWNrtPw) of the tries, which is a solution that doesn't solve the problem. It only finds most of the vampire numbers (probably). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` ⊞υ⟦ωθ⟧FυFE§ι¹⟦⁺§ι⁰κΦ§ι¹⁻λν⟧⊞υκ⊙EΦυ¬⊟ιI⪪⊟ι⊘Lθ∧Σ﹪ιχ⁼θIΠι ``` [Try it online!](https://tio.run/##XY1Pa8MwDMXv/RQ6SuBBS9dTT2F0rNAMQ4@jB5OkjalqJ47dP5/eU0ILYwIheO/p/arWhMobzlmnocWk4OemoD/Qenb0ATARTLc0HRZx6@rmjlbBgiSoOQ1/xbmIZ9lPy7EJ/@OldRJnBY7oQAQv3llQOlgXsXCPifP8F@/bR9S@Q0tS8GGGiPuO7UtT8GX42tS4a9wpttjTOAoKV@M@XbD0dWI/8eejvumT4QH7Z5UO4ldxLJdZ57x4X67y25V/AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for vampire, nothing if not. Explanation: ``` ⊞υ⟦ωθ⟧ ``` Start a breadth-first enumeration of permutations of the input string. ``` Fυ ``` Loop over each partial permutation so far. ``` FE§ι¹⟦⁺§ι⁰κΦ§ι¹⁻λν⟧⊞υκ ``` Append each unused character to the permutation so far and push the result plus the remaining characters to the list. ``` ⊙EΦυ¬⊟ι ``` Find whether any of the entries where all of the characters were used, ... ``` I⪪⊟ι⊘Lθ ``` ... after being split into halves and cast to integer, ... ``` ∧Σ﹪ιχ ``` ... have a non-zero sum of the last digits, ... ``` ⁼θIΠι ``` ... and have the product of the halves resulting in the original string. [Answer] # [Python 2](https://docs.python.org/2/), ~~113 ... 112~~ 109 bytes ``` def f(n,s=sorted):x=s(`n`);l=10**(len(x)/2);return any(x==s(`i`+`n/i`)for i in range(l/10,l)if i%10and n%i<1) ``` [Try it online!](https://tio.run/##XY3BCoMwEETP7VfsRdi1gkmO2vxLBJN2IaySRNCvT821c3oMb5j9Kt9NTK2rDxBQhmzzlopfaTptRieO5mi16nuMXvCk0dCcfDmSwCIXnrZZ7F5ORnYUtgQMLJAW@XiMo1ZDJA7AnVaLrCAdvzXVP8@oFpqej1ttP7kkZKLOgLWgoC3DXUx7Yik31B8 "Python 2 – Try It Online") -3 byte thanks Kevin Cruijssen [Answer] # [Ruby](https://www.ruby-lang.org/), ~~104~~ 96 bytes It almost looks like a complete English sentence. Which probably is a bad thing for golfing. ``` ->n{n.digits.permutation.any?{|s|a,b=s.each_slice(s.size/2).map{|x|x.join.to_i};a%10>0&&a*b==n}} ``` [Try it online!](https://tio.run/##lVBBboMwELzzilUkIKmoazsx0FYk34iUosgJTuMqMSg2EmngFb32df0ItSGHXnvZ0ax2Z0ZzqXfX/pC99Y9LdVOokO/SaFSJy7k23MhSIa6uq1urWx7tMo0E3x@3@iT3YqqRlp/iic7QmVe3tmkb9FFKhUy5ld0r9wle4iDgD7ssU13Xm0ttjlfIYENojCMyf2YRWcztYHNLU5pElKRJFKeppZgy4mAx3GJGyQjxwkHCHEuJ@yY4YakFFic0B/BGnyEoFCW0qrVLgKo2GiZ@UoCvJ@DDRkVw2KgcVhD@fH@F8ALhOnQCQhXDh3fgJy3GxDYixvnf9b8M1oO8s7kbeF4FU4IQsbJ4hrQ4ib1xHULj@hurtSIUsgwwBIGVavKu/wU "Ruby – Try It Online") It can be written in 94 bytes with [Ruby 2.7](https://rubyreferences.github.io/rubychanges/2.7.html#numbered-block-parameters): ``` ->n{n.digits.permutation.any?{|s|a,b=s.each_slice(s.size/2).map{_1.join.to_i};a%10>0&&a*b==n}} ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ ~~95~~ 94 bytes -10 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! (switch to Python 2) -1 byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! Very inefficient, segfaults for \$ n \gtrsim 18500\$ on TIO. ``` f=lambda n,k=2,S=sorted:k<n and(k%10>n%k<(len(`k`)==len(`n/k`)<S(`k`+`n/k`)==S(`n`)))|f(n,k+1) ``` [Try it online!](https://tio.run/##JY1BCoMwEEX3nmI2QoLSGjcFMb2EFzCtSTtEJ5KkC6F3t6MdGHhvYP5ft/wO1O64rCFmSFsqeC/J5mifn5gw0IwLZqEaHrk7PZvlMRmg2uu2HnTiNzt1vicwNAlfquZOpe/FbEmMfpRan0RX5n44TtVftGajUUr5dYLjKsXxIQICEkRDLytUDbejtisA0IETeCLAGpEy2/4D "Python 2 – Try It Online") **Commented**: ``` f=lambda n,k=2,S=sorted # recursive function k<n # if k>=n return False and # otherwise: ( ... ) # long boolean expression which is True if k and n//k make n a valid vampire number k%10 # the last digit of k is > n%k # larger than n%k which is < ( ... ) # less than another boolean expression # These two comparisons can only be satisfied with k%10>0<1 len(`k`) # the number of digits of k == len(`n/k`) # is equal to the number of digits of n//k < S(`k`+`n/k`) # and sorting the digits of k and n//k == S(`n`) # results in the same list as sorting the digits of n | f(n,k+1) # bitwise OR with result of the recursive call ``` [Answer] # JavaScript (ES6), 93 bytes Assumes that the input has an even number of digits. Returns a Boolean value. ``` f=(n,[...a]=n,p='')=>a[p.length]?a.some((v,i)=>f(n,a.filter(_=>i--),p+v)):p%10&&p*a.join``==n ``` [Try it online!](https://tio.run/##Xc/RSsMwFAbg@z7FMbAux7YhqWzCZib4GnNsYSZbRjwJbakX4rPXOHah3v0/34HDfzGj6Y@dT0ND8c1Ok9Oc6q0Qwuw01UnP56g3ZptEsHQazrtnI/r4bjkfa5/F5WsjnA@D7fheb3zTYJ2qEXGVZkqWZbo34hI9HQ5a03SM1MdgRYgn7jhTarF8bBli8R8WD1LKH/gj7JVebIgfoNrMcsWwcLHjBBrUGgiebpBzVSF8FgB3PHMFecZtAcygRShLcFdg7Fp@fyFcF1/TNw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 97 bytes Expects the integer as a string. Returns **0** or **1**. ``` f=(n,[...a]=n,p,q,k)=>a.some((v,i)=>f(n,a.filter(_=>i--),k?[p]+v:p,k?q:[q]+v,!k))|p%10*!(p*q^n|k) ``` [Try it online!](https://tio.run/##XY5BbsIwEEX3OcVgqchDHMtuBUihplKvEaCyqI1C0rGToHRRevbUFZuW3fvzvr7mbEc7HPs6XgoK726avOEkKiml3RsSUXSiQbO1cggfjvNR1Cn5VLHS1@3F9fzNbOuiQNG8VHGfj2VM1JVVl1jMGsRrfNBqMeNx0R3o2uB0DDSE1sk2nLjnTOvlav3IELN7sXxSSv2Kf4bt6NW14RN0sqpkmPnQcwIDegMEz7d7wjxH@MoA0reQA2MI8zn8XSLcZN/TDw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input integer, as a string [...a] = n, // a[] = list of digits of n p, q, // n is split into p and q (both initially undefined) k // k is a flag, set on odd iterations ) => // a.some((v, i) => // for each digit v at position i in a[]: f( // do a recursive call: n, // pass n unchanged a.filter(_ => i--), // remove the i-th entry from a[] k ? [p] + v : p, // append v to p if k is set k ? q : [q] + v, // append v to q if k is not set !k // toggle k ) // end of recursive call ) // end of some() | // success if: p % 10 * // the last digit of p is not 0, !(p * q ^ n | k) // p * q = n and k is not set ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Œ!ŒH€SṪ$ƇḌP€=ḌẸ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWjkzweNa0Jfrhzlcqx9oc7egKAPFsg/XDXjv///0cb6hjomOoY6ZjpmMQCAA "Jelly – Try It Online") Takes a list of digits. [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 bytes ``` á mó f_dÌîmì ×Ãd¥Uì ``` [Try it online!](https://tio.run/##AS8A0P9qYXB0///DoSBtw7MgZl9kw4zDg8KubcOsIMOXw4NkwqVVw6z//1sxLDIsNiwwXQ "Japt – Try It Online") or [check all test cases](https://tio.run/##JYwxCgJBDEWvkgOMkGQmM/EagjbLIsJiIQxYeINt7a0t7BYbb7A52JjR5j8eyf@X0/XWbGn2hGofOB8nu9u8vqstYA@bp/W19/PgAYexDcQZA8WtBErRQ6KrcglMWkJWdUUW6ki/XxSmP3LqKNJNqbcJi6hDcuEAfQxxhE3dfQE) (specifically the 15 vampire numbers and 153000) Takes input as an array of digits. Input as an integer is [one byte longer](https://tio.run/##y0osKPn///AahcMLFXIPb1ZIi0853HO4@dC6XJDY9MPNKYeWhv7/b2hkZgAA) Explanation: ``` á mó f_dÌîmì ×Ãd¥Uì á # Get all permutations of the input digits mó # Divide each permutation into two groups of equal length f_ à # Only keep ones where: dÌ # At least one of the groups ends with a non-zero number ® à # For each remaining pair of groups: mì # Treat each group of digits as an integer × # Multiply those integers d # Return true if at least one of the results... ¥Uì # ... Is equal to the original number ``` ]
[Question] [ ## Background My user ID is 78410, or \$1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0\_2\$. One interesting property of this number is that, in binary, * it doesn't have three consecutive identical digits, and yet * it has a substring \$100100100\$ which is three copies of \$100\$. So, I define a **Bubbler number** as a positive integer whose binary representation satisfies the following: * it doesn't have three consecutive identical digits (so it is a member of [A063037](http://oeis.org/A063037)), and * it contains a substring which is three consecutive copies of some nonempty string (so it is NOT a member of [A286262](http://oeis.org/A286262)). ## Task Given a positive integer as input, determine if it is a Bubbler number. You can use truthy/falsy values in your language or two distinct values to indicate true/false respectively. There are 55 Bubbler numbers under 1000: ``` 42 84 85 106 149 169 170 171 212 213 292 298 299 338 339 340 341 342 362 365 405 425 426 427 438 585 596 597 598 618 658 661 676 677 678 681 682 683 684 685 724 725 730 731 804 810 811 850 851 852 853 854 874 876 877 ``` Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ḃsᶠ~j₃ˢlⁿ1 ``` [Try it online!](https://tio.run/##Fc9NSkMxFAXgrZQ3Ppbc5N6bvIkuRBxU8Qd5ILRKkdJCLUiduQRxokMnijhxAa7iZSPP8wYfJzcJ4eR0Pju7uu9uLuOwWjaTg8NJszxa1ceP@rCr@7fmdn53Pm2mdf/eXMy6Bdfr/udp3X8@D/33btF/vWyuefXvtavbXxmGY40oimKQ4BBtIU45kCBKpITYMttCLVIqxNRAQhHJRwYNFEdOGcq7xretdcpU4EJGLvDslIlz4VwiJVIy5KjETIEEJbCqBOLamDYmf2CJeJZHThlsjwSFwcGJZQP7gY2V2wo1xDB@IZ38Aw "Brachylog – Try It Online") This was meant to only be a partial solution, but it turns out that `ⁿ` fails on empty inputs. ``` ᶠ Find every s substring of ḃ the input's binary digits, ˢ then for each substring ~j₃ map it to the string which it is three copies of ˢ (ignoring and discarding it if there is no such string). ⁿ For none of those strings (of which there is at least one) l is its length 1 1. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` bŒʒ3ä1ìË}{нË ``` Outputs `0` for truthy and `1` for falsey. [Try it online](https://tio.run/##AR8A4P9vc2FiaWX//2LFksqSM8OkMcOsw4t9e9C9w4v//zQy) or [verify some more test cases](https://tio.run/##Fcw9CsJAEAXgq4TUr5iZ/XG3ykHEIgELKwtBCGJrk27PYOkVrBYbq5zBi6wvxccbHsw7X8bpdGzXeei736N0/TC36VO@xdWn1ldd7rf1XZeGtveG5JECVCLUZ2iknZDC1MjBMjMnynAuEdMLKRlc3HCDK1D@BQQeQlvGxDWjAGNn7ILI4Q8). **Explanation:** ``` b # Convert the (implicit) input to a binary-string Œ # Take all substrings of the binary-string ʒ # Filter it by: 3ä # Split the substring into 3 equal-sized parts 1ì # Prepend a 1 to each part Ë # Check that the three parts are equal # (the prepend 1 is necessary, because ["01","01","1"] would be truthy, # since strings and integers are interchangeable in 05AB1E) }{ # After the filter: sort all remaining substrings # (this causes any "000" and/or "111" to be leading) н # Pop and push the first substring (or "" if none are left) Ë # Check if all characters in this string are equal (also truthy for "") # (after which the result is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~64 63 61~~ 58 bytes ``` f=lambda n,i=2:[n>i>0<f(n,i+1),i>3][3*bin(i)[3:]in bin(n)] ``` [Try it online!](https://tio.run/##NdDNboMwDAfwO0/hI2wc8p1QDV4EcaAb2SK1KWJU6p6e@Z9uh/xkW46jeP3Zv25ZHUfsL/P1/DFTblOvTmMe0iDeYs3pq2zaNOhp1C/nlOvUjPo0pUxIcjMdy2Nd3nfqaTSqpWD42JakcIzpGAe8ALIlJRXQTIeoC4BbtA4AkRFAAm7RrsBDjQCq4IBncM3iSds54AHXnAQWOB7lvAMeoBZQCwpoYABP8coARFoA7gsCv5ICILWIbInwZasBWnzBAT9V1bZ83y9lNZnibaNMvLdtzp9LLYWQDaVIEUusqnVLeaf/Xfb0vPpXfibHLw "Python 2 – Try It Online") A recursive function that returns `True` if the number is a Bubbler number, and `False` otherwise. Generates all possible binary string, then for each binary string checks if `n` contains 3 consecutive copies of that string. The binary strings are generated by evaluating `bin(i)[3:]` for \$i\$ from \$2\$ to \$n-1\$. The slice `[3:]` gets rid of the first 3 characters in the binary representation of \$i\$, which are always `0b1`. This allows us to generate binary strings that has leading 0. [Answer] # JavaScript (ES6), ~~54~~ 49 bytes *Saved 5 bytes thanks to @l4m2!* ``` n=>/^(?!.*(.)\1\1).*(.+)\2\2/.test(n.toString(2)) ``` [Try it online!](https://tio.run/##FcxBDsIgEEDRq@CqM1qnwJ4az@BS1JAKDQ2FBoiJp8e6@Xmrv5iPKVP2Wz3H9LbNqRbVODzhcqAjEGqhBf51Qi21HKjaUiFSTbeafZxBIrYpxZKCpZBmuBPRNWfzBcE5xwetZgN49cwjU@Necj5Um8EhLclH6HrW7Y8f "JavaScript (Node.js) – Try It Online") ### Regular expression ``` /^(?!.*(.)\1\1).*(.+)\2\2/ ^ // match the beginning of the string (?! ) // must NOT be followed by: (.) // a single character .* // appearing anywhere \1\1 // immediately followed by 2 copies of itself // must also match: (.+) // a string .* // appearing anywhere \2\2 // immediately followed by 2 copies of itself ``` --- # JavaScript (ES6), 55 bytes This version uses a helper function to test `/(.+.)\1{2}/` and `/(.)\1{2}/` separately. ``` n=>(g=p=>n.toString(2).match(p+".)\\1{2}"))`(.+`&&!g`(` ``` [Try it online!](https://tio.run/##DctBDoIwEADAryAH2A24Ae5t4hs8irENQi0p26Y0Jsb49splbrPqt96naEM6s3/OeRGZhQQjgpBMyV9TtGxgQNp0ml4QmpJwHPvv8CsRFVCjqupkFKg8ed69m8l5AzciusSoP9B3XYf3YweAR1tYLIQ8pMW6NEdYkFZvGeq2qBHzHw "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BẆẋ3ẇɗƇ$ḢḊ ``` A monadic Link accepting a positive integer which yields a list - in Jelly an empty list (non-Bubbler) is falsey while a non-empty list is truthy (Bubbler). **[Try it online!](https://tio.run/##y0rNyan8/9/p4a62h7u6jR/uaj85/Vi7ysMdix7u6Pr/qGGOU2lSUk5q0aOGuUBOXn6eLkLgcLv9///mFiaGBgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ASoA1f9qZWxsef//QuG6huG6izPhuofJl8aHJOG4ouG4iv8xMDAwUsOH4oKsVP8 "Jelly – Try It Online") (identifying all Bubbler numbers in \$[1..1000]\$). ### How? ``` BẆẋ3ẇɗƇ$ḢḊ - Link: positive integer, n B - convert n to binary (say b) $ - last two links as a monad - f(b): Ẇ - all sublists (say s) - Note these are sorted from shortest to longest Ƈ - filter keep those x of s which are truthy under: ɗ - last three links as a dyad - f(x, b): 3 - three ẋ - repeat (e.g. [1,0] -> [1,0,1,0,1,0]) ẇ - is a sublist of (b)? Ḣ - head (given an empty list this yields 0) Ḋ - dequeue ``` [Answer] # [APL (Dyalog 18.0)](https://www.dyalog.com/), ~~34~~ 33 bytes ``` ⊃1<∘⍸⊢{∨/⍺⍷⍨∊3/⊂1↓⍵}Ö(2∘⊥⍣¯1)¨2↓⍳ ``` [Try it online!](https://tio.run/##PdC9SgNBEAfwPk8xZQJKdvb7wM7GVILxBQISm2AEKwk2Csd5sEERg62KcF0KCYrl5U3mRc7/pgjs7@b2ZnZ2byfXs8OL28lsftnJ8nV0KuWT6m1XCIu@pA0GSfobAAbtv2zuOqkf@EiqN0m/Un8spGqGu6ofSY1UtRlKfc9SvuTi7aqvc2n9JemzXfOgbfQu9d1NsZWkJbq1ayPlM04xPjvG8/xkNO4mVzfIW03RUnTEyhPbgthDUMCkWYMhXSAWEQoyJgKiVcCgyfjM9dDyIPdUjqzOPASyWOKwhSs8BIjkGRx4Jh88BMA8Yh41GLCwbxu0pYC2wShgigoHZwV4d4guR/yPM4BcyDyE3EIe3/N9VvW0bXA7rJT6Bw "APL (Dyalog Unicode) – Try It Online") This uses `⎕IO←0` and the Over operator (`⍥`, which was added in 18.0). The current version on TIO is 17.1, so it's been implemented manually (thanks Bubbler!). I think this does well for a non-regex answer. ### Explanation ``` 2↓⍳ ⍝ The range 2 to n-1 ⊢ (2∘⊥⍣¯1) ⍝ Convert this range and the input to base 2 {∨/⍺⍷⍨∊3/⊂1↓⍵}Ö ¨ ⍝ Before applying the function to each 1↓⍵ ⍝ Drop the first 1 of the binary number ∊3/⊂ ⍝ Repeat the list 3 times and flatten ∨/⍺⍷⍨ ⍝ Is this sublist in the binary input? ⊃ ⍸ ⍝ Is the index of the first element 1<∘ ⍝ Greater than one? ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 46 bytes ``` {(*/0<3!+/+3':x)>*/^a?,/'3#','a:,/,\'|',\x}@2\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW0NI3sDFW1NbXNla3qtC009KPS7TX0Vc3VlbXUU+00tHXiVGvUdeJqah1MIrh4jLUVktTN9RWtLS0BACy7A3c) `2\` binary encode `{` `}@` apply function first condition: * `,/,\'|',\x` all substrings of the argument, i.e. prefixes (`,\`), reverse each (`|'`), prefixes each (`,\'`), raze (`,/`) * `a:` assign to `a` * `,/'3#','` triplicate each, i.e. enlist each (`,'`), 3-reshape each (`3#'`), raze each (`,/'`) * `a?` find - indices in `a`, or nulls (`0N`) for not found * `^` is null? * `*/` all second condition: * `3':` sliding window of size 3 * `+` transpose * `+/` sum * `3!` mod 3 * `0<` positive? * `*/` all `>` and not (between the two conditions) [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 44 bytes ``` dc -e2o?n|egrep -v 000\|111|egrep '(.+)\1\1' ``` [Try it online!](https://tio.run/##S0oszvj/PyVZQTfVKN8@ryY1vSi1QEG3TMHAwCCmxtDQECqirqGnrRljGGOo/v@/iTEA "Bash – Try It Online") Input is on stdin, and the output is the exit code (0 for truthy, 1 for falsey, as usual with shell scripts). Or [verify the Bubbler numbers under 1000](https://tio.run/##NY7LCoMwEEX3@YpLKagEH@lWa1fttj/gxibRCDqRVKUL/z0V0c0wc7nnMJ/6a7ysJ5Sjs62rBxTF5fl@XbySiPXNPmjVrdMj4gVZllWrEOJIgjDhUSUqEfiNYEyawSrM/IfDxRrrEIZ0FzkVYqNz4jyKGKDsNoCugZbG4kpYkaTnCyVSpZeU5r7fa8BkNB0rTmS/m263kfZ/). [Answer] # perl -M5.010 -n, 45 bytes ``` $_=sprintf"%b",$_;say!/(.)\1\1/&&!!/(.+)\1\1/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRNSTVJSUcl3ro4sVJRX0NPM8YwxlBfTU0RxNGG8P7/N@Qy4jLmMjHisjDhsjDlsjDjsjDnMrcwMTT4l19QkpmfV/xf19dUz8DQ4L9uHgA "Perl 5 – Try It Online") Turns the input into a string with the binary representation of the number, applies regexes to test the requirements, then prints 1 or an empty string accordingly. Two bytes (the `!!`) could be saved if there wasn't a restriction for two distinct values -- without them, for bubbly numbers, it prints the thrice repeated string. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` tṠḟ·€*3Qḋ ``` Returns a list, which is nonempty iff the input is a Bubbler number. In Husk, empty lists are falsy and nonempty lists are truthy. [Try it online!](https://tio.run/##AR8A4P9odXNr//904bmg4bifwrfigqwqM1HhuIv///8xNjIz "Husk – Try It Online") ## Explanation ``` tṠḟ·€*3Qḋ Implicit input: a number, say n=84. ḋ Binary representation: [1,0,1,0,1,0,0] Q Sublists: [[1],[0],[1,0], …, [1,0,1,0,1,0,0]] ḟ Find the first one that satisfies this (or an empty list if none do): Example list: [1,0] *3 Repeat three times: [1,0,1,0,1,0] Ṡ ·€ It occurs in the list of sublists: yes. Result: [1,0] t Remove the first element: [0], truthy. ``` The correctness of this program relies on the fact that `Q` enumerates the sublists in a "good" order (all sub-sublists of a sublist occur in the result before the sublist itself) and `ḟ` returns the first match it finds. If 000 occurs in the binary representation, then [0] is listed before any longer triply repeated sublist (unless that sublist consists of only 1s, in which case [1] is listed before it). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~13~~ ~~12~~ ~~11~~ 10 bytes ``` BẆẋ3eɗƇ`ḢṖ ``` [Try it online!](https://tio.run/##Fc89TgMxEMXxC73CHzNju@UWdDRpUC5AS5FI0ENPzQFIWqRIOYa5iPlb8k9vZ71avXk@HI8vaz3M62le3@vh/nk7P82fr3n5WL/neTlxbm9/r9@Pa1lRN3VXTqFsQznQErJKLqgqgxwdQ7V2kJaQUVRjc1lC2QJNxrfOv30EGroiwxFZ0QINzJ25F1QYXK0YyJqQ1RNVcwLPTvpONvAK7toWaKK9qkyuEBNlE/1EY@O1yVwl7RXqPw "Jelly – Try It Online") *The third -1 takes some inspiration from Kevin Cruijssen's 05AB1E solution.* *Fourth -1 thanks to Jonathan Allan reminding me of Jelly's truthiness semantics.* Outputs truthy or falsy. ``` Ẇ Every substring of B the input's binary digits. Ƈ Filter them by ẋ3 ɗ repeated three times e membership in BẆ ` every substring of the input's binary digits. Ṗ Is there more than one element to remove from Ḣ the first (i.e., shortest) of the filtered substrings? ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 44 bytes ``` .+ $* +`(1+)\1 $+0 01 1 A`000|111 1`(.+)\1\1 ``` [Try it online!](https://tio.run/##Fck7DoAgFETRftaBCUpC3vANpZWboMDCwsbCWLp3xO6e3Pt4zmvvk95atwZqgWmaZq6EMgIhiLWJyEuObtr@r7J3FxAcmApYElzw8MM@RcTkEUtGLvED "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary ``` +`(1+)\1 $+0 01 1 ``` Convert to binary. ``` A`000|111 ``` Delete the string if it contains `000` or `111` (`A`(.)\1\1` also works for the same byte count). ``` 1`(.+)\1\1 ``` Check whether there are three consecutive substrings. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔⍘N²θ¿⬤01¬№θ×ι³⊙θΦκ№θ׳✂θλ⊕κ ``` [Try it online!](https://tio.run/##XYzBCsIwEETvfsXiaQMRWiso9FQFoZci1B@oca1L09QmW8Gvj61HB@Yyb3jm2XgzNDbGIgRuHR6bQLV4di2W7jVJNfU38qg0bOeOKl/xA7CwFtdJutZQDYKnYXKCo4Yr9xSQNWRqCVxmj2DhPgs8s5XZ1Gn4@2caasuGlsVqKJ3x1JMTumP386g8xv1hlyZx87Zf "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation: ``` ≔⍘N²θ ``` Input the number and convert it to base 2 as a string. ``` ¿⬤01¬№θ×ι³ ``` Test whether neither digit `0` nor `1` appears triplicated in the string. ``` ⊙θΦκ№θ׳✂θλ⊕κ ``` Check whether any nontrivial substring appears triplicated. (I use `Φ` instead of a second `⊙` since Charcoal doesn't currently accept an implicit range there, but the effect is the same.) [Answer] # T-SQL, 258 bytes Added some line changes to make it readable ``` DECLARE @ char(99)='' WHILE @i>0 SELECT @=left(@i%2,1)+@,@i/=2; WITH C as(SELECT number+1n FROM spt_values WHERE'P'=type) SELECT count(*)FROM C,C D WHERE not(@ like'%000%'or @ like'%111%'or len(@)<D.n*3+C.n+2) and @ like'%'+replicate(substring(@,C.n,D.n+1),3)+'%' ``` Returns 1 or more for true, 0 for false **[Try it online](https://data.stackexchange.com/stackoverflow/query/1244668/bubbler-numbers)** [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ ~~120~~ ~~114~~ 113 bytes ``` b,c,i,j;f(a){for(b=c=1;a;a/=2)for(b&=a&7^7&&a&7,i=~3,j=1;++j<11;i*=2)c&=~i&(a>>j^a|a>>j*2^a)||!(a>>j*3-1);b&=!c;} ``` [Try it online!](https://tio.run/##VY3LbsMgEEX3/gqSKggMaU2yiBSM@yOVJQx1O1ZqR3lUSLHz6@5A2kVnMVc6OnPHrT@cm5@gd4erfyfl@eJheP6ssn/oAE1kGfQX8mWhZ98DeE5uGcGJ0A1X3IYUOqF2OLGIAyKlMUqiiqLQRIjwd5Y8Fvjr8YRqy5Yrvycr/9YvJQnyt1GY5PD942N41E/ZNDfSSZCdbpnlt/ivMc4obbV9MRueADWW7uodpRgSzH0rOzSE6EqlNOSoOWruQJmtqq62Y4x8U1s@jovE8u1acY09C6enef4B "C (gcc) – Try It Online") ~~-4~~ -5 bytes: ceilingcat [Answer] # [Raku](http://raku.org/), 37 bytes ``` {.base(2)~~/(.+)$0$0/&none /(.)$0$0/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi8psThVw0izrk5fQ09bU8VAxUBfLS8/L1UByIdwa/8XJ1YqpBelFgD16CgY6ukZGhgY/AcA "Perl 6 – Try It Online") This matches the base-2 representation of the input number against the junction ``` /(.+)$0$0/ & none /(.)$0$0/ ``` ...which succeeds if it matches the first pattern, but not the second one. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` bṅÞS'3/≈;h≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJi4bmFw55TJzMv4omIO2jiiYgiLCIiLCI3MjUiXQ==) or [get all the Bubbler numbers up to a given number](https://vyxal.pythonanywhere.com/#WyIiLCInIiwiYuG5hcOeUyczL+KJiDto4omIIiwiwqwiLCIyMDAiXQ==). Port of Kevin Cruijssen's 05AB1E answer. Outputs \$0\$ for truthy and \$1\$ for falsy. #### Explanation ``` bṅÞS'3/≈;h≈ # Implicit input bṅ # Input as a binary string ÞS # All substrings ' ; # Filtered by: 3/ # Split into three parts ≈ # All equal? h # First item ≈ # All equal? # Implicit output ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->n{n.to_s(2)=~/^(?!.*(.)\1\1).*(.+)\2\2/} ``` [Try it online!](https://tio.run/##Hc/PTsMwDAbw@57C3BroMuefnR4KD7IOJNB2mgpauwPaxqsXfz3kpy@WYyuX6@fvcuqX7et4G/38/TE10fV/u/fm7ck/N94NYQgO6cUNcYi7x/JznSdq2HsfmNn56Xg@fs10o/t4p9N@PNCD@p72G6IcW6rZTmkpsBi5MwQog9BSDBEko0PqKrCWlCpAygwCsJYkK6XFCrbZOa4IUAMPC5aWToACq0kABYgNExWgALWKWo0ggQzWLRotK7ZoYmCdlfGzwADXglTWhG@XBNCiKwJ0c1j@AQ "Ruby – Try It Online") ### How it works: ``` ->n{ n.to_s(2) # convert to binary representation string =~ / # check if it matches regex ^(?!.*(.)\1\1) # (from the start) assert that there are no 3 # repeated characters anywhere in the string .* # skip any number of characters (.+)\2\2/ # check that there is a sequence of 1 or more # characters repeated 3 times (note that there # are no 3 repetitions of a single character so # the 1 case is irrelevant (equivalent to ..+)) } ``` *squints eyes* "regex..." [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 74 bytes ``` ($s=[Convert]::ToString("$args",2))-notmatch'(.)\1\1'*($s-match'(.+)\1\1') ``` [Try it online!](https://tio.run/##TdFdT8IwFAbga/YrGjKFyUbafbQbCQkJ8Voj3AEhOMuHAYZrpybIb8fzThEv9uT0zelp2h2KD12atd5ug7wo9dld9o/ntmv6k2Gxf9elnfV642Jky81@1W66i3Jlmn7oecG@sLuFzdetdtebiqlo3dGu4BJ1fjLvfHIc15aVHi6MNqzPBu049Fka05f4THBJxBkhgeJA@CwUIYiIDFWWAmqJohSgijkQgFoiWUNDYw7CGgkUgW0JjkwyCRSgTAqQAEmjpJJAAWQpsjQEEYgBTVFhDFBFHFBfynErwQGWCaqkrnDlJAJoUTUS0EEqjQX3HId3u4LzTr30M6XC7OuGHZ2GW2pTbS293a27ZO6cEv150LnVL5S5cxZs9uz6xk5j8jgaVsYWu4fnV2qbDWhIY1TluTb4A5d5gX5jf5OoY6yN7dfzG0@XE397Kbr/d@R108k5Oedv "PowerShell Core – Try It Online") ]
[Question] [ Let's have a function \$f\$ that takes a string and removes all pairs of adjacent identical characters. For example \$f(a\color{red}{bb}ba\color{red}{cc}) = aba\$ Note that when two pairs overlap we only remove one of them. We will call a string perfectly paired if repeated application eventually yields the empty string. For example the string above \$abbbacc\$ is not perfectly paired because if we apply \$f\$ again we still get \$aba\$. However a string like \$eabbccadde\$ is perfectly paired because if we apply \$f\$ three times we get the empty string \$f(ea\color{red}{bbcc}a\color{red}{dd}e) = eaae\$ \$f(e\color{red}{aa}e) = ee\$ \$f(\color{red}{ee}) =\$ --- Your task is to write perfectly paired computer code that takes a string (of printable ASCII) and decides if it is perfectly paired. **The bytestring of your source must be itself a perfectly paired string**, although your code doesn't necessarily have to be restricted to printable ASCII. You may output two distinct values: one for the case where the input is perfectly paired, and another one for cases where it isn't. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored by the size in bytes of their source with fewer bytes being better. --- ## Test Cases \$abbbacc \rightarrow \mathrm{False}\\ abcba \rightarrow \mathrm{False}\\ abab \rightarrow \mathrm{False}\\ abbbaabacc \rightarrow \mathrm{True}\\ eabbccadde \rightarrow \mathrm{True}\\ bbbb \rightarrow \mathrm{True}\$ [Answer] ## Haskell, ~~146~~ 124 bytes ``` ((""##)) a===bb=bb==a ((aa:bb))##((cc:dd))|aa===cc=bb##dd|1==1=((cc:aa:bb))##dd a##""=""===a ""##cc=((cc!!00:cc!!00:""))##cc ``` No comments. Returns either `True` or `False`. [Try it online!](https://tio.run/##PYzNCoNADITvPsWa9LALLehVyJO0PeRHW6nKUnv02bvdFSkMTDL5Mk9eX/00pYHcLXkPgBhCxUQkUkRcec/ciYSA6L1qZxbCxgVRzQii2dYStbRf/6xZxYgAlFVqSnV@KFBdN013GECBVdPM4@LIxfe4fNzJzRzd4K7AIsKqcM6TCu@eEz7CPm@qbNbDPX11mPixpovG@AM "Haskell – Try It Online") Edit: -22 bytes thanks to @Cat Wizard [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes ``` ss='' for cc in input():ss=[cc+ss,ss[1:]][cc==ss[:1]] print''==ss##tnirp[,+[=:)(tupni nirof= ``` [Try it online!](https://tio.run/##NY/RisQgDEXf/QrpPESpLHQfBb/E8UGjZYRZddSyO1/fsaULgdx7EzhJefdHTt87Zh/UNE17awqAkDVXikhjGlW2zrgcA404tyZa04s0ZjilhpaLMYSUGlMHOJLbradYixazVpKzvpUU6UjyqvaB@Gq9xsI4IS/1tD/OW9pkDX7DwC5fBUqNcxX1IilVT45oAoCr88STSDWk3GkJdQ3YQcC/MvrFjqe4meGexvrvIz4DXWT4C0iPyQ7WOWcRgQyFzp59JPYKw3CI1vsAHw "Python 2 – Try It Online") The whole update step `ss=[cc+ss,ss[1:]][cc==ss[:1]]` cancels to just `=[+,[`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26 24 22 20~~ 18 bytes -2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). Outputs **0** if the string is perfectly paired, **1** otherwise. ``` ΔγʒgÉ}JJ}ĀqqĀÉgʒγΔ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3JRzm09NSj/cWevlVXukobDwSMPhzvRTk85tPjcFvywA "05AB1E – Try It Online") ``` ΔγʒgÉ}JJ}ĀqqĀÉgʒγΔ – Full program. Δ } – Until the result no longer changes: γʒ } – Split the string into chunks of equal characters and filter by: gÉ – Is the length odd? JJ – And after filtering, join the parts back together, but do this twice to save 2 bytes, as in the previous versions. Ā – Check whether the result is empty q – Terminate (quit) execution. The rest of the code is ignored. qĀÉgʒγΔ – Mirror the non-matched part to help with the source layout. ``` --- ### Previous versions This one purely relies on undefined behaviour (so there's no "dead code"), and outputs **[['0']]** for perfectly paired strings and **[['1']]** for non-perfectly matched strings: ``` ΔγεDgÉ£}JJ}ĀĀ£ÉgDεγΔ ``` And the 22-byte version, explained, which is just the above but not abusing UB, and yielding *sane* values. ``` ΔγεDgÉ£}JJ}ĀqqĀ£ÉgDεγΔ – Full program. Δ } – Until fixed point is reached (starting from the input value): γε } – Group equal adjacent values, and for each chunk, DgÉ – Duplicate, get its length mod by 2. £ – And get the first ^ characters of it. This yields the first char of the chunk or "" respectively for odd-length and even-length chunks respectively. JJ – Join the result to a string, but do this twice to help us with the source layout, saving 2 bytes. Ā – Check if the result is an empty string. q – Terminate the execution. Any other commands are ignored. qĀ£ÉgDεγΔ – Mirror the part of the program that isn't otherwise removed anyways. This part forgoes }JJ} because that substring will always be trimmed by the algorithm anyway. ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 54 bytes ``` U#;[[email protected]](/cdn-cgi/l/email-protection)>??>i..??O.@1^^...u--u.u!ww;..#..U..;..;!^^! ``` Outputs nothing if the string is perfectly paired and `1` otherwise. [Try it here](https://ethproductions.github.io/cubix/?code=VSM7IXUxQC5PaT4/Pz5pLi4/P08uQDFeXi4uLnUtLXUudSF3dzsuLiMuLlUuLjsuLjshXl4h&input=VSM7IXUxQC5PaT4/Pz5pLi4/P08uQDFeXi4uLnUtLXUudSF3dzsuLiMuLlUuLjsuLjshXl4h&speed=60) ### Cubified ``` U # ; ! u 1 @ . O i > ? ? > i . . ? ? O . @ 1 ^ ^ . . . u - - u . u ! w w ; . . # . . U . . ; . . ; ! ^ ^ ! ``` ### Explanation Most of the characters are filler needed to perfectly pair the code. Replacing those with `.` (no-op), we get ``` U # ; ! u 1 @ . O i . ? . > i . . ? . . . . . ^ . . . . u - . . . . . . w ; . . . . . . . . ; . . ; ! ^ ^ ! ``` This can be broken into three steps: * Check against the empty string (the left `i` and the `?`). * Loop, throwing characters onto the stack and popping duplicates (everything on the bottom and right). * Check if the stack is empty (the stuff at the top). [Answer] # [V](https://github.com/DJMcMayhem/V), ~~20~~, 18 bytes ``` òóˆ±òø‚ ::‚øò±ˆóò ``` [Try it online!](https://tio.run/##K/v///Cmw5sPdRzaCKR3HGri4rKyOtR0eMfhTYc2Huo4vPnwpv//E5OSEpOTAQ "V – Try It Online") Hexdump: ``` 00000000: f2f3 88b1 f2f8 820a 0a3a 3a82 f8f2 b188 .........::..... 00000010: f3f2 .. .... ``` Outputs 0 for truthy, 1 for falsy. Thanks to nmjcman101 for indirectly saving 2 bytes. ``` ò ò " Recursively... ó " Remove... <0x88> " Any printable ASCII character ± " Followed by itself ø " Count... <0x82> " The number of non-empty strings ::<0x82>øò±<0x88>óò " NOP to ensure that the code is paired ``` [Answer] # [R](https://www.r-project.org/), ~~142~~ 126 bytes Tighter logic and some comment bytes golfed by @Giuseppe ``` f=function(x,p="(.)\\1")"if"(grepl(p,x),f(sub(p,"",x)),!nchar(x))##x(rahcn!,x,,p(bus(f,)x,p(lperg("fi")"1\\).("=p,x(noitcnuf=f ``` [Try it online!](https://tio.run/##xc5BCoQwDIXh/dzCuPAFguABvEk3bTFakFqqhd6@U5xDzO7L5n/JremqJfonXBFV0kqY2ZiFmIIS9rylE0kqi@IurpOoXyxD9IfN6BzHimwPHwepIgmu3FDhHsOZtryDNPTcYgzPoLXHEK/w@Fj6dFOQdc57S/x5/cP037cmbl8 "R – Try It Online") ``` f=function(x,p="(.)\\1")"if"(nchar(x),"if"(grepl(p,x),f(sub(p,"",x)),0),1)##)1,)0,xp(bus(f,)x,p(lperg("fi",)x(rahcn("fi")"1).("=p,x(noitcnuf=f ``` Original: [Try it online!](https://tio.run/##xY6xCoQwEAX7@4y18C0sYj7AP7FJgtGAxBAN@Pe5Rdvrr5tphimthSnU5K94JNySJ8LA82yIKQZC8pstuFkeW8uSd2RRDzirUyRSYxlZDHcdG@FR7gxXTwRhDWLPS1lBIZI6it18eozJ8ACaNId0xMunqistgKxz3lviz8Mv9D83/zjac/sC "R – Try It Online") Recursive detector function followed by comment with all the characters in the function in reverse order. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 146 bytes ``` D,g,@~~,L2_|*;;*|_2L,@,g,D D,ff,@^^,BG€gBF;;FBg€GB,@D1:?: xx:? aa:1 `bb Bxx;;B Waa*bb,`yy,$ff>xx,`aa,xx|yy,`bb,Byy,xx:yy O;;O:,B,`,|,`,>$,`,*W` ``` [Try it online!](https://tio.run/##zU47CoQwFOzfOaxkGi0T0PAIbiNY2mkSJLaWLxAs9jx7qr2I@46xxXwYZmDicVzX83iccPeNud9ra21b936G09CTR85w2wZ@fd@fkydrJz7VvhjOd2Y0RCJmJIrRdBRSIhaxlmmNsU0JoRQ0OQ8iCDFCpGqgNbCqLkshWqxdDBgBVTE0Su0ann899gM "Add++ – Try It Online") Fun fact: This was 272 bytes long before the explanation was started, now it beats Java. Outputs `True` for perfectly balanced strings, and `False` otherwise To my great satisfaction, this beats the boring [palindromize version](https://tio.run/##zc6xDYNADAXQ3nNQod9AeQWcrBM0kSjpwGchaClt6USReTJVFiGMkQney9t2nvedcCBeeLVrqSlhR1zA4/f9OXggCz3l0JAosdGca4U4qr0zSIYVhyjYYcFpUiKdyIPBGSrwYsgC6/YKLtA6z2RMKtSETH0wGvh4oJGxxAdOVJe1feGKTynd/1v7AQ) by **2** bytes, to prevent the result being printed twice. I have also aimed to have as little dead code as possible, nevertheless there are still some commented-out sections, and the code exits with an error code of **1**, after printing the correct value. *NB* : A bug with the `BF` commands was [fixed](https://github.com/cairdcoinheringaahing/AddPlusPlus/commit/17d68bf59505bcef7058c2e7319d3c897447883a) while this answer was in development. ## How it works The code starts by defining the two key functions, \$\mathit{ff}\$ and \$g\$. These two functions are used to calculate the next step in the process of removing pairs, and work entirely from \$\mathit{ff}\$ i.e. only \$\mathit{ff}\$ is called from the main program, never \$g\$. If we define the input string as \$S\$, \$\mathit{ff}(S)\$ modifies \$S\$ in the following way: First, identical adjacent characters in \$S\$ are grouped together. For an example of \$abbbaabacc\$, this yields the array \$[[a], [bbb], [aa], [b], [a], [cc]]\$. Over each of the sublists (i.e. the identical groups), we run the function \$g\$, and replace the sublists with the result of the function. \$g\$ starts by unpacking the group, splatting the characters onto the stack. It then pushes the number of characters on the stack and takes the absolute difference with \$2\$ and that number. We'll call this difference \$x\$. Lets see how this transforms the respective inputs of \$[a]\$, \$[bb]\$ and \$[ccc]\$: $$[a] \Rightarrow [a, 1]$$ $$[bb] \Rightarrow [b, b, 0]$$ $$[ccc] \Rightarrow [c, c, c, 1]$$ As you can see \$x\$ indicates how many of the next character we wish to keep. For simple pairs, we remove them entirely (yielding **0** of the next character), for lone characters we leave them untouched, or yield **1** of them, and for groups where \$x > 2\$, we want \$x - 2\$ of the character. In order to generate \$x\$ of the character, we repeat the character with `*`, and the function naturally returns the top element of the stack: the repeated string. After \$g(s)\$ has been mapped over each group \$s\$, we splat the array to the stack to get each individual result with `BF`. Finally, the `^` flag at the function definition (`D,ff,@^^,`) tells the return function to concatenate the strings in the stack and return them as a single string. For pairs, which yielded the empty string from \$g\$, this essentially removes them, as the empty string concatenated with any string \$r\$ results in \$r\$. Anything after the two `;;` is a comment, and is thus ignored. The first two lines define the two functions, \$\mathit{ff}\$ and \$g\$, but don't execute \$\mathit{ff}\$ just yet. We then take input and store it in the first of our 4 variables. Those variables are: * \$\mathit{xx}\$ : The initial input and previous result of applying \$\mathit{ff}\$ * \$\mathit{yy}\$ : The current result of applying \$\mathit{ff}\$ * \$\mathit{aa}\$ : The loop condition * \$\mathit{bb}\$ : Whether \$\mathit{yy}\$ is truthy As you can see, all variables and functions (aside from \$g\$) have two letter names, which allows them to be removed from the source code fairly quickly, rather than having a comment with a significant amount of \$\mathit{xyab}\$. \$g\$ doesn't do this for one main reason: If an operator, such as `€`, is run over a user defined function \$\mathit{abc}\$, the function name needs to be enclosed in `{...}`, so that the entire name is taken by the operator. If however, the name is a single character, such as \$g\$, the `{...}` can be omitted. In this case, if the function name was \$\mathit{gg}\$, the code for \$\mathit{ff}\$ and \$g\$ would have to change to ``` D,gg,@~~,L2_|*;;*|_2L,@D (NB: -2 bytes) D,ff,@^^,BG€{gg}BF;;FB}gg{€GB,@D?: (NB: +6 bytes) ``` which is 4 bytes longer. An important term to introduce now is the *active* variable. All commands except assignment assign their new value to the active variable and if the active variable is being operated on, it can be omitted from function arguments. For example, if the active variable is \$x = 5\$, then we can set \$x = 15\$ by ``` x+10 ; Explicit argument +10 ; Implicit argument, as x is active ``` The active variable is \$x\$ by default, but that can be changed with the ``` command. When changing the active variable, it is important to note that the new active variable doesn't have to exist beforehand, and is automatically assigned as 0. So, after defining \$\mathit{ff}\$ and \$g\$, we assign the input to \$\mathit{xx}\$ with `xx:?`. We then need to manipulate our loop conditions ever so slightly. First, we want to make sure that we enter the while loop, unless \$\mathit{xx}\$ is empty. Therefore, we assign a truthy value to \$\mathit{aa}\$ with `aa:1`, the shortest such value being \$1\$. We then assign the truthiness of \$\mathit{xx}\$ to \$\mathit{bb}\$ with the two lines ``` `bb Bxx ``` Which first makes \$\mathit{bb}\$ the active variable, then runs the boolean command on \$\mathit{xx}\$. The respective choices of \$\mathit{aa} := 1\$ and \$\mathit{bb} := \neg \neg \mathit{xx}\$ matter, as will be shown later on. Then we enter our while loop: ``` Waa*bb,`yy,$ff>xx,`aa,xx|yy,`bb,Byy,xx:yy ``` A while loop is a *construct* in Add++: it operates directly on code, rather than variables. Constructs take a series of code statements, separated with `,` which they operate on. While and if statements also take a condition directly before the first `,` which consist of a single valid statement, such as an infix command with variables. One thing to note: the active variable cannot be omitted from the condition. The while loop here consists of the condition `aa*bb`. This means to loop while both \$\mathit{aa}\$ and \$\mathit{bb}\$ are truthy. The body of the code first makes \$\mathit{yy}\$ the active variable, in order to store the result of \$\mathit{ff}(x)\$. This is done with ``` `yy,$ff>xx ``` We then activate our loop condition \$\mathit{aa}\$. We have two conditions for continued looping: * 1) The new value doesn't equal the old value (loop while unique) * 2) The new value isn't the empty string One of Add++'s biggest drawbacks is the lack of compound statements, which necessitates having a second loop variable. We assign our two variables: $$\mathit{aa} := \mathit{xx} \neq \mathit{yy}$$ $$\mathit{bb} := \neg \neg (\mathit{yy})$$ With the code ``` `aa,xx|yy,`bb,Byy ``` Where `|` is the [inequality](https://github.com/cairdcoinheringaahing/AddPlusPlus/blob/master/add%2B%2B.py#L2444) operator, and `B` [converts to boolean](https://github.com/cairdcoinheringaahing/AddPlusPlus/blob/master/add%2B%2B.py#L2453). We then update the \$\mathit{xx}\$ variable to be the \$\mathit{yy}\$ variable with `xx:yy`, in preperation for the next loop. This while loop eventually reduces the input into one of two states: the empty string or a constant string, even when applied to \$\mathit{ff}\$. When this happens, either \$\mathit{aa}\$ or \$\mathit{bb}\$ result in False, breaking out of the loop. After the loop is broken, it can break for one of two reasons, as stated above. We then output the value of \$\mathit{aa}\$. If the loop was broken due to \$\mathit{x} = \mathit{y}\$, then both the output and \$\mathit{aa}\$ are False. If the loop was broken because \$\mathit{yy}\$ was equal to the empty string, then \$\mathit{bb}\$ is falsy and \$\mathit{aa}\$ and the output are truthy. We then reach our final statement: ``` O ``` The program can now be in one of three states, in all of which the active variable is \$\mathit{bb}\$: * 1) The input was empty. In this case, the loop didn't run, \$\mathit{aa} = 1\$ and \$\mathit{bb} = \mathrm{False}\$. The correct output is \$\mathrm{False}\$. * 2) The input was perfectly balanced. If so, the loop ran, \$\mathit{aa} = \mathrm{True}\$ and \$\mathit{bb} = \mathrm{False}\$. The correct output is \$\mathrm{False}\$ * 3) The input was not perfectly balanced. If so, the loop ran, \$\mathit{aa} = \mathrm{False}\$ and \$\mathit{bb} = \mathrm{True}\$. The correct output is \$\mathrm{True}\$ As you can see, \$\mathit{bb}\$ is equal to the expected output (albeit reversed from the *logical* answer), so we simply output it. The final bytes that help us beat Java come from the fact that \$\mathit{bb}\$ is the active variable, so can be omitted from the argument, leaving us to output either \$\mathrm{True}\$ or \$\mathrm{False}\$, depending on whether the input is perfectly balanced or not. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 38 bytes ``` ''≡{'(.)\1'⎕R''⊢⍵}⍣≡⍝⍝≡⍣}⍵⊢R⎕'1\).('{≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wR19UedC6vVNfQ0YwzVH/VNDQIKdC161Lu19lHvYqDUo965IARiLAYKbQVKBgGVqRvGaOppqFcDJYDmKKgnJiUlJSYnq3OB2clJiVAWUDQRLpEK5CcnJ6akpIK5IAC2HGo71HoiHQB1AdgJ6gA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~28~~ 26 bytes ``` +`(.)\1 C`^$ $^`C1\).(`+ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F87QUNPM8aQi8s5IU6Fi0slLsHZMEZTTyNB@///xKSkpMTkZK7EpOSkRC4wLxEskApkJycnpqSkckH1H9p2aBvIBBCNZAYA "Retina – Try It Online") Outputs ``C1\).(`+0`C1\).(`+` for falsy and ``C1\).(`+1`C1\).(`+` for truthy cases. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~228~~ 200 bytes ``` (()){{{}([]<<{{(({}<<>>)<<>>[({})]){{{{}(<<<<>>()>>)((<<>>))}}}{}{}<<>>{}<<>>}}{}<<>>>>[[]])}}{}(<<({{(())(<<()>>)}}<<>>)>>){{{{}{}}((){{}{}{}{}{}}(()())())[[]((){{}{}}())[]]((){{}{}}[[][]]()){{}{}}}} ``` [Try it online!](https://tio.run/##3Y9BCsMwDAS/oz3kByIfMTq4h0JpyCFXsW9PtHZK/xBshMa7WuHX0T/78t769zzNgMyktXDPNEu6rytUWgFCcunuejKUZjYsIJmc/ll5U422CAjLaooF1Gmac0HdEZxkqaOZRyg7UCE/icL4Y0lC3Eg@6CdLvwA "Brain-Flak – Try It Online") This is a bit of a proof of concept. It could probably be shorter. It doesn't use any comments however. Outputs `0,0` if the input is perfectly paired and `0,1` if the input is not. [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 34 bytes ``` :;:t;ss((..??\??))\1ss1;t;/..??/cc ``` [Try it online!](https://tio.run/##hYwxEoAgDMB2XgKDcKx06EdY2sLgIp7l/VblA25JhmhvZgXKBFXvY0SsiCHUrJphQvpKEjEjZiYRRyxMbhmt0F8Woda6@//c45z7ONS26wE "sed 4.2.2 – Try It Online") Paired strings give empty output, unpaired ones give `ct:` The trivial palindromic version is at 32 `:;ss(.)\1ss;t;/./cc/./;t;1\).(;:`. Old solution was `:;ss((..??\??))\1ss1;t;;/./cc/./t:` (changed because current one abused `c` less, edit: yay now there's only 1 character after `c` :D) (note that `;` is the statement separator) `:` declares an empty label `:t` declares the label `t` `ss((..??\??))\1ss1` is a substitution, in sed you can change the delimiter to a substitution, and this is what I did by changing it to `s`, so what this does is substitute the first (as is denoted by the `1` at the end) * match of `((..??\??))\1` + `.` any character + `.??` followed by an optional optional character + `\??` and an optional `?` + followed by the same thing right beside it * with nothing Now this substitution is paired with itself, so the `;`s before and after it get cancelled out too `t` and loop back to the label until there are no more successful substitutions `/..?/` if `.` (wildcard) followed by `.?` an optional character is matched * `cc` change the buffer to `c` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~112 110~~ 108 bytes ``` (()){{}({<<(({}<<>>)<<>>[({})]){{((<<>>)<<>>)}}{}{##{ }<<>>>>{}<<>>}<<>>)}{}((){{<<>>[[]]}})##}{}])}{([)}(} ``` [Try it online!](https://tio.run/##vY2xDYAwDAR71kjzLrJBlEWiFKFAQiAK2tfPHkwiMQKNJf/5/Ovd9ituZzt6B8xIgSkBVEo52zuKL1YdAV9mEsUQuCzjMOcpTMuZPyOHXWqVLAQPqxMUE/RzW2wP "Brain-Flak – Try It Online") This is based on [my answer](https://codegolf.stackexchange.com/a/163534/76162) from *[Are the brackets matched?](https://codegolf.stackexchange.com/q/77138/76162)*. Tried not to use comments, but got stuck trying to make the pop nilads (`{}`) pair up. The problem lies in the easiest way to pair up a pair of brackets is to surround it in another pair of the same kind. While this is easy for other nilads, the `{...}` monad creates loops. In order to exit the loop you have to push a 0, but once you've exited the loop, you then have to pop the 0, which compounds the problem. The 66 byte pre-paired solution is: ``` (()){{}({<(({}<>)<>[({})]){((<>)<>)}{}{}<>>{}<>}<>)}{}((){<>[[]]}) ``` [Try it online!](https://tio.run/##TYwxCsUwDEMP08UaeoOQi4QM6VAov3ToKnT21E4I/EW2Zekdb7ue/bzbr3czgJQxmVEpI@XiCypoNk6Iik8O0by9RQ@WWoV/xoR4FiELFKTlQRPn6yD6nIVFjd7gbpt7YSMKdJBoBTL1vX0 "Brain-Flak – Try It Online") Outputs `1` or `1,0` if the input is a perfect pairing, `0,0` if not. ### No comment version, 156 bytes ``` (()){{{}({<<(({}<<>>)<<>>[({{}((<<[[]]>>)){}}{}(<<[]>>){{}{}}{})]){{((<<>>)<<>>)}}{{}{}{}}{}{}<<>>>>{}<<>>}<<>>)}}{{}{}}{}((){<<>>[[]]})(<<()()>>){{}{}{}}{} ``` [Try it online!](https://tio.run/##zY49DoAgDIWv897ADRouQhhwMDEaB9emZ8cWNPEILsD76VeWq21nWo@29w6QqmpQEUBNJGfGURAuREqp1T2qmRuuQ3k2NKs/o/VM0c2IRjhpOc/bvnmgQB2LnG90BAi@6NH4@e9SuwE "Brain-Flak – Try It Online") As Cat Wizard pointed out, the first answer does not work for all interpreters, as not all handle `#` comments. This version contains no comments. [Answer] # Japt, ~~24~~ 22 bytes Outputs `false` for truthy and `true` for falsey. ``` &&!!e"(.)%1"PP"1%).("e ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=JiYhIWUiKC4pJTEiUFAiMSUpLigiZQ==&input=WwoiYWJiYmFjYyIKImFiY2JhIgoiYWJiYmFhYmFjYyIKImVhYmJjY2FkZGUiCiJiYmJiIgonJiYhIWUiKC4pJTEiUFAiMSUpLigiZScKXS1tUg==) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 96 bytes ``` {<<>>(({})<<>>[(([{}<<>>]))]){((<<[[]]>>))}{}{}{}{}<<>>}<<>>{{{}{}{}{}{}}((<<>>){{}{}}){{{}}}}{} ``` [Try it online!](https://tio.run/##vU0xCoBADPtOM/iD0o@UDucgiOLgGvr283qITzCBEJJA1rvt17Kd7eidqmYiTJRxEWeWCyBAEVX3CDMg@bLqKSS/MGs6ZjNKVDXA/OFhaQ8 "Brain-Flak – Try It Online") Outputs nothing if the input is perfectly paired, and `0` otherwise. Non-perfectly paired (original) version: ``` {<>(({})<>[({}<>)]){((<()>))}{}{}{}<>}<>{((<>))}{} ``` [Try it online!](https://tio.run/##RU07CsAwCL2Ob8gNxItIhnQolJYOXcWzp5qEVkXlfXR72nGX/Wpn78ZCZA4WjcGCCiNiggBuI1miEpxQeliWKxYl0hDFVrHcrFqr/BcmPZqZfaCnNGQDciQVER9KewE "Brain-Flak – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 66 bytes ``` null.foldr((%))"";;cc%((r:t))|cc==r=t;;t%s=t:s--s:t=s%=r|t:dlof.un ``` [Try it online!](https://tio.run/##lY5BDsIgEEWvQogkkNgeADInsS6GoWgjpQTormcvEuPKnav/31u9J5bXHELzMLW4hzD6LbgspVCKc2OIhJRZV6UOIoAM1ZgqClRdhqHoCkVAPqp2YfPjHtuKS4SUl1jZha2YmGc3jtZaJOLX/sjiZ7vBr5w7EaFzc4efholP/1fwezvJB3yUNlBKbw "Haskell – Try It Online") Cat Wizard saved 6 bytes. [Answer] # JavaScript (ES6), 76 bytes Returns a boolean. ``` ff=ss=>ss==(ss=ss.replace(/(.)\1/,''))?!ss:ff(ss)//)(:!?,/1\).(/(ecalper.=(> ``` [Try it online!](https://tio.run/##hc/BCsIwDAbgu08xd1kLs2XXQbebT@BxlzRLRSnraNTXrzkoCIMZSE4ff/jv8ALGfFsfpyXNVEoIjtkNsk7JYTaZ1ghIyiqjp862TaP1eGTuQxChrdWqP46t7SZtBBFCXCkbp4aCaeEUycR0VaJr8N4DYq11JWNtdYbIdNgy9PBBu0zS4Bso7JKfW0XCEGGeaU/9qb3fe1P851N5Aw "JavaScript (Node.js) – Try It Online") Suggested by @Shaggy: [**58 bytes**](https://tio.run/##fZC9DsIwDIR3nsIwlEQqiZhRO/IEjCyu6/CjiFZxQEKIZy8pIP6FBw/@7s7SbfGAQmHTxsmuqbnrnCtEilIky5xTIiZw65FYWWX0cmrz8Vhra3M7XWqTjkzoWw5GlV1kiVCAQFHCCWI4pj3sQzRkGVCzk8az8c1KxbBnPYMzEEZaK9ZJ@coderkKzoNBn6pGWFUVEo00pLEW5r3iwajCG/nBkg/v1sQW6fMdcWJEWNf8hf6X8N7CZw3PsO4C) by returning an empty string for *perfectly paired* or throwing an error otherwise. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~70~~ 64 bytes ``` {#//.{aa___,bb__,bb_,cc___}:>{aa,cc}}=={{}}(**(,{>:}_,{.#{&)**)& ``` [Try it online!](https://tio.run/##pY1BCsIwFET3OUYCpQ2x3VdaAl5A1yrh5zelXbSLGFeff/YYUPQAboaZNzCzQVrCBmlFyPNQZ1Jd1xKAc854/xaDWCL3Y@HFMw8DEXOtdW1o7NkZahVVjdZNlZujEJfnGpI9x3VPV3UYZ3taIAKmEB9WGXnb5b3qLAkh/72TpoyA9x4QPx49/Ch8i1AyIkxTkEJwfgE "Wolfram Language (Mathematica) – Try It Online") ### Without comments, 92 bytes ``` ((#//.bb_:>StringReplace[00[ecalpeRgnirtS>aa__:_.#&];bb,{{,}};00>00;00;aa:_~~aa_:>""]))==""& ``` [Try it online!](https://tio.run/##rY5BCoMwEEX3OcYIomA164jBIxRdaggzMbaCikh2ole3KZX2At0M/8185v8J3dNO6AaDZ19EZxQFWZYSaSFrtw7zo7LLiMY2nDfW4LjY6jEPq6slotZCp0GocqJk25J9zzmXnPuZIwp9HN4iJICK46IACM84Z@zun7oGGCgPFwU32ZdBAu0MKszKjTH4f48W2k@Ttwgh8SFIRGjMpQ3hb4vfg/VsDHadBcb28wU "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Lua](https://www.lua.org), 178 bytes ``` p=...S={}for a in p:gmatch"."do E=S[#S]~=a;S[E and#S+1 or#S]=E and a or X end;print(#S==0)--)0S#(tnirp;dne X ro a dna E=]S#ro 1+S#dna E[S;a=~]S#[S=E od"."hctamg:p ni a rof}{=S.=p ``` [Try it online!](https://tio.run/##1Y49CoQwEIWvMiSNIhu0NUzpCaZZCBbB@AdrEkK2Er16dvAWW36P972Zz9eWElEpRXheS0hgYfcQ@/WwedqEEi7AgGQkjTdaTWYA652kpoOQOMSH2WL1DbN3Oqbd50oSYlu/XnVLssp@T1E7P3MlBS47b3l1JMnUNSQfNqQt3hwa4tXg@Pg2ZXusfQS/s5XCcp1ICmMpRfzf1@IH "Lua – Try It Online") While it is a terribly long solution, this does make quite a bit of use of Lua-specific quirks. This is actually a minified brute force stack algorithm. The program is made complicated by the fact that Lua's patterns don't allow replacing pairs and regex is not built in. Explanation: ``` p=... -- command-line argument S={} -- the stack for c in p:gmatch"." do -- shorter than "for i=1,#p do ..." E=S[#S]~=c -- check whether we have the right letter on top of stack -- could've saved some bytes by doing == instead of ~= -- but the double negation is necessary for ternary operator -- to work with nil values S[E and #S+1 or #S]=E and c or X -- Lua's awesome "ternary operator" end -- i'm sure there is a better way to output this (table indexing?) print(#S==0) ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 30 bytes ``` 1ll1**F:}}:{=Q{~~||lzBBzl{Q={F ``` [Try it online!](https://tio.run/##S8/PScsszvhv6JiW6Zpm5ZpR998wJ8dQS8vNqrbWqto2sLqurqYmp8rJqSqnOtC22u0/AXkA "Gol><> – Try It Online") Everything after the first `B` is excess code and is not executed. A function that returns the top of stack as `1` if the input is a perfect pairing, `0` otherwise. ### Explanation: ``` 1 Push 1 as the end string marker ll1** Push n, where n (len+1)*(len+2), This is larger than the amount of steps needed to determine pairing F | Repeat that many times :}}:{= Compare the first two characters of the string Q | If they are equal {~~ Pop both of them String is also rotated by 1 If the string becomes empty, the 1 is compared to itself and removed. lzB Return whether the length of the stack is 0 Bzl{Q={F Excess code to match unpaired symbols ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 30 bytes ``` 1O@;??;@ii??O;>>;;;..1Wcc1??1W ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9/Q38Ha3t7aITPT3t7f2s7O2tpaT88wPDnZ0N7eMJyQPAA "Cubix – Try It Online") Outputs `1` if the string is perfectly paired and nothing otherwise. ### Cubified ``` 1 O @ ; ? ? ; @ i i ? ? O ; > > ; ; ; . . 1 W c c 1 ? ? 1 W . . . . . . . . . . . . . . . . . . . . . . . . ``` ### Simplified ``` 1 O @ ; ? . . @ . i ? . . . . > ; ; ; . . . W c . . . ? 1 W . . . . . . . . . . . . . . . . . . . . . . . . ``` The logic and general structure are the same as in Mnemonic's answer, but without an explicit check for the empty string. [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` gg"" gg((aa:cc:bb))dd|aa==cc=gg bb dd gg aa""=""==aa gg aa((bb:c))=gg((bb:aa))c--c:=c:| ``` [Try it online!](https://tio.run/##NYwxDsMgEAR7vwKhFFDwAaSr8gGXKdLsHeRihVgxUPrtIXYRaYvRaLRPtFcuZWx0H6rWTpOqc0AUiczep7QDRCKkaphNSmdhDGAtHSPgL5xjjuI9nQ8HAt5LCBJJ4j7eWFb61GXtl8323HpvteZux1ceBdpGuF3n@Qc "Haskell – Try It Online") [@nimi's answer](https://codegolf.stackexchange.com/a/167436/56656) is pretty cool, it doesn't use any comments. This one is shorter but does use a comment. [@xnor's answer](https://codegolf.stackexchange.com/a/167455/56656) is also pretty cool, it does use comments and is shorter than this one. [Answer] # [Python 2](https://docs.python.org/2/), 114 bytes ``` import re e=lambda i,nn=1:e(*re.subn('(.)\\1','',i))if nn else''==i##ieslef'1).('(nbus.er*(e:1=,i adbmal=r tropmi ``` [Try it online!](https://tio.run/##Xc5BasQwDAXQfU4hmILsIRjS5RSveo1sZFuhAscxsgc6p0890MW028fX/6qP/nWU91P2emgH5Skeib0i4otN7DPtIRHIXIpfbmyuyq7dQzFonF3XBWfEWayVDUoBzo0RvZfLRbhl3nCxbkRLuDfHejV8W/wsQCnslL1C16Puco5Z17pKNfYD@JsjPN@ZpqpSOrBBCiFQjGhfKQb6CyND/2M8OEZKiYf@Mn6OdpAGlXXj2PMDKolyuuE8bp7bTrlmiqNgLQPxDa09fwA "Python 2 – Try It Online") Returns `True` for perfectly-paired strings, `False` otherwise. (Actually fails to verify itself, because `(.)` won't match the newlines in the code! But @Cat Wizard said this is okay, because newlines aren't printable ASCII characters, so my program needn't handle them.) --- This is a perfectly-paired version of: ``` import re;p=lambda s,n=1:p(*re.subn('(.)\\1','',s))if n else''==i ``` for which a “lazier” perfectization of `code + '##' + f(code[::-1])` would give 120 bytes. (That is, renaming the variables etc. to introduce more collapsed pairs inside the *comment* half of the code saved 6 bytes.) --- > > `re.subn` is a little-known variant of `re.sub` that returns a tuple `(new_string, number_of_substitutions_made)`. It's pretty good for finding regex substitution fixpoints! > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26 24~~ 22 bytes ``` ẠƬµF€ḂLḣgŒŒgḣLḂ$$€FµƬẠ ``` [Try it online!](https://tio.run/##y0rNyan8///hrgXH1hza6vaoac3DHU0@D3csTj866eikdCADyGlSUQFKuB3aemwNUOH/h7u3HG4HCvz/r6urFs8VFeEcxpWYlJSUmJwMpJOTEiG8RLBAKpCdnJyYkpLKRYolXIZGxiamZrq6ZqYmxkaGAA "Jelly – Try It Online") Weirdly seems to work without moving the backwards code to an unused link. Returns **0** if the input is perfectly paired, **1** otherwise. Active code: ``` ŒgḣLḂ$$€FµƬẠ Œg Group runs 'abbbcc'->['a','bbb','cc'] € For each of these strings: $ Monad{ $ Monad{ L Find the length... Ḃ ...mod 2. } -> [1, 1, 0] in this example. ḣ Take this many characters from the string. } -> [['a'], ['b'], []] F Flatten -> ['a', 'b'] Ƭ Repeat... µ The last monadic chain until a fixed point is reached. Ạ All. If it is not a perfectly paired string, all elements in the result of Ƭ will be nonempty and 1 is returned. If it is perfectly paired, the last element is [] which is falsy and 0 is returned. ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 82 bytes ``` {0=#Fixpoint[{Replace[_,/"(.)\\1",""]},_]}??}]_,}],"1).("/,_[ecalpeR{[tniopxiF#=0{ ``` [Try it online!](https://tio.run/##LU49i4NAEO39FcvGIoHBxPZAUgSsjnDIdZNBxtkxtyC6xC0E8bd7m@Oq98V7PI6R5Uf33nxU@3qpDrVfwuTHiGujYWBRbOFsj8Xp8SgtWEsbtLRdrxu1sBHY8lQc7RlaVOEhaLNiHP0UFl8fqsu6y@Q0TZtPP@qMtR@0UXZoi3dQRD9ZIiwpy@6qbsY8BHlS9vVKD751jjeeU60Hgzl3XcciYBKTjv8wOfxvalIi7JyCeW8T7b8 "Attache – Try It Online") Nothing incredible here. `Fixpoint`s a function which removes consecutive pairs. [Answer] # Java 8, ~~158~~ ~~156~~ 154 bytes ``` n->{for(;n.matches(".*(.)\\1.*");n=n.replaceAll("(.)\\1",""));return n.isEmpty();}//};)(ytpmEsi.ruter;,"1).("(Aecalper.n=n;)"*.1).(*."(sehctam.n;(rof{>-n ``` Returns a boolean (`true`/`false`). -2 bytes thanks to *@raznagul*. [Try it online.](https://tio.run/##lVKxbsMgFNzzFU9MYCVYWYtSKUO6NUu6lQ7PmDROMbYAR7Iif7tLHKdDG7mKBAO8494d7454wsUx/@qVQe/hFQt7ngEUNmi3R6VhezkCZFVlNFpQdBdcYT/BMxELXdxx@YChULAFC6veLp7P@8pRYXmJQR20p4QnlDMplzwhTNiV5U7XJtKvjaHkWiJzQhgTTofGWQDLC78p69BSJro07QSjbajLjS@4a6I4MSdLxuPjtVZoau14pBWMJPxynXBCvT6ogCW3grpqf35e2F5c5dZNZqLcUfWpKnIoo/HR2vsHILu6TlN4i90O7dNw3LU@6JJXTeB1RAZjqeWKEo1ZphTmub44mIRGZIaYoVJT0LFy0/CCxut/NAzE06wjTmX4QO9d1bgYA1XlGorgtdlP67gzfXkb/xAA@TcBktzKkswlkY/lQA5BkL@TIH@iIO9lYfyCbtb13w) **Explanation:** ``` n->{ // Method with String parameter and boolean return-type for(;n.matches(".*(.)\\1.*"); // Loop as long as the String still contains pairs n=n.replaceAll("(.)\\1","")); // Remove all pairs return n.isEmpty();} // Return whether the String is empty now //};)(ytpmEsi.ruter;,"1).("(Aecalper.n=n;)"*.1).(*."(sehctam.n;(rof{>-n // Comment reversed of the source code, // minus the pairs: '\\';'ll';'\\';'""))';'n n';'//' ``` ]
[Question] [ You have a square board with a bunch of items laid out on it in one of a \$3 \times 3\$ grid of cells and you want to lift it up using balloons, but you can only attach balloons to the corners of the board. Your task is to determine the minimum number of balloons in each corner to make sure the board won't tip over in flight, but can still lift all its contents. ## "Physics" Model * Each balloon can lift 0.25kg (these are very strong balloons) * The board itself weighs 1kg, so you would need 1 balloon in each corner to lift an empty board * Items in each corner cell only exert force on their respective corners (i.e. 4 balloons are needed in the corresponding corner per kg) * Items on each edge cell split their force evenly between their neighboring corners (i.e. 2 balloons on each of the two corresponding corners per kg) * Items in the center cell split their force evenly across all corners (i.e. 1 balloon is needed in each corner per kg) ## Example Test Cases ### 1 ``` Input: 0 0 0 0 0 0 0 0 0 Output: 1 1 1 1 ``` ### 2 ``` Input: 1 2 1 2 4 2 1 2 1 Output: 17 17 17 17 ``` ### 3 ``` Input: 5 0 0 0 0 2 0 1 0 Output: 21 5 3 7 ``` ### 4 ``` Input: 12 9 35 1 32 2 4 6 18 Output: 101 195 63 121 ``` ### 5 ``` Input: 9999 9999 9999 9999 9999 9999 9999 9999 9999 Output: 89992 89992 89992 89992 ``` ### 6 ``` Input: 9999 2 9001 0 9999 9999 9999 999 9999 Output: 50000 66006 51994 71992 ``` ## Rules and Assumptions * You may assume each cell is filled with a whole number between \$0\$ and \$9999\$ kg weight worth of items * Use any convenient format for I/O * Shortest code wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` 3Ḷ×þ`ZU$Ƭ×µ§§‘ ``` [Try it online!](https://tio.run/##y0rNyan8/9/44Y5th6cf3pcQFapybM3h6Ye2Hlp@aPmjhhn///@PNjTSUbDUUTA2jdVRiDYEMoB8IxDbREfBTEfB0CIWAA "Jelly – Try It Online") Takes input as a 3x3 matrix and outputs a list going clockwise starting from the bottom-right. # Explanation ``` 3Ḷ×þ`ZU$Ƭ×µ§§‘ Main Link 3Ḷ [0, 1, 2] ×þ` outer product by multiplication with itself ([0, 0, 0], [0, 1, 2], [0, 2, 4]) Ƭ (include the original, plus) rotate clockwise until results are no longer unique (4 results total) ZU$ zip and upend (clockwise rotation) × vectorized multiply with original (gets the workload distributions to each balloon) §§ sum results for each balloon (vectorized-sum rows in the matrix; sum the results) ‘ increment ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ ~~57~~ 56 bytes ``` lambda c,*b:[b[~i]*4-~c+b[i]*2+b[i-2]*2for i in 0,2,4,6] ``` [Try it online!](https://tio.run/##hZAxT8MwEIX3@xVPsCTFRYnTlhapI4ywsIUI2Y1DXVInch0BC3@9nAst3bClu3e@Z/vT9Z9h3Tm5b5bP@1Ztda2wEiN9W@ryy1ajyfhrdaVLVjKmsWTRdB4W1iETUkzErNpbV2OJkjATyAXmglAIbuOG1URgKiAFVfS@tq3Bkx/MLeESCnaHzbALCGuDplUhGGdq6E75mrjNb1aE4D/ZjtO3XrlXkxRpPGTT1RKt3YVkq/rEuiC8en@xrh9Ckl7v@tZyTlOC@ViZPuDu8f7O@84fLl/CMHnX4OCPJ9ob9RbZdGSLWGoVBtUeHToyPXTOVBhhQT9QYhOxjBu2xqtgmKI@wOlyU7Ff8fgIvWc4NMlIp8fi4oJwRrvPwJvOI@WQyEliAvmraXrqS475wSWBBYopcVmwljx1YIZ8TrTghVP4p/ypeRVYZFkeJ5LFzvzMjT/3Nw "Python 2 – Try It Online") **Input**: 9 numbers, representing the board in the following orders: ``` 6 1 8 3 0 7 4 5 2 ``` **Output**: list of length 4, representing the balloons as follow: ``` 1 0 2 3 ``` ## Explanation `lambda c,*b:` separates the 9 numbers into the center `c` and a list of length 8 representing the corner and edge values: ``` 5 0 7 2 _ 6 3 4 1 ``` The reason for this is because length 8 works nicely with negative index, as shown as follow: ``` Indices | Indices mod 8 Edge 1 (i) 0 2 4 6 | 0 2 4 6 Edge 2 (i-2) -2 0 2 4 | 6 0 2 4 Corner (~i) -1 -3 -5 -7 | 7 5 3 1 ``` *-1 byte thanks to @xnor!* [Answer] # [Python 3](https://docs.python.org/3/), ~~86~~ ~~78~~ 77 bytes Saved 8 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!! Saved a byte thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!! ``` lambda b:[[4*b[i][j]+2*b[1][j]+2*b[i][1]-~b[1][1]for j in(0,2)]for i in(0,2)] ``` [Try it online!](https://tio.run/##jVFRb4IwEH73V1x4sZUzoa0uQuLe97QfUHnACBsEKoGabDHur7NaZoWp2a7hrvfdfaXftf7U73slumy96cqk2u4S2EZSLmZbmceyiH1udsztDMbi@ZeFWJztGyggVyRATm2Wu6zTaatbWAOZgDEpAzQrxl8xxp8yQ47MwBwXyE3sc1deDljcRjZicwxRLC1PcNuxwCdkq2tLaAydMw1/AWMmCIQwCJj9NxhkZb3jwcU5Ip2cJ6LNRMDOIrJoZUZSpoq0uiFV8mE/beYKl/FBk6i3lAh6Np9ZUt3kShPvRdUHHXnUYjf9/fmXUnG/dD0t8466f@Po@VidTh5CqnbrKUzpZNxJh3fYqNeDHlzj/MQZ0X1S3hHX3hHHh@Juag@F8EdCWiek/LeQuTcjFfjA6EwMC7T7Bg "Python 3 – Try It Online") Uses a list of lists for both input (\$3\times3\$) and output (\$2\times2\$). [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~63~~ ~~59~~ ~~58~~ 57 bytes ``` lambda l:[2*(2*l[i]+l[i%2]+l[i/2])-~l[8]for i in 4,5,6,7] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKtpIS8NIKyc6M1YbSKgagSl9o1hN3bqcaIvYtPwihUyFzDwFEx1THTMd89j/OQq2CtGWQLahjpGOoZGOiY6xqY6hhY6xUSxXQVFmXolGmkaOpuZ/AA "Python 2 – Try It Online") The input is in this order: ``` 4 0 6 2 8 3 5 1 7 ``` and output is ``` 0 2 1 3 ``` -1 thanks to @SurculoseSputum I kept this solution because I started thinking about shuffling indices with it: ### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~82~~ ~~81~~ 80 bytes ``` def f(l):*l,d=l;return[(l:=l[2:]+l[:2])and-~d+2*(l[1]+l[7]+2*l[0])for _ in'0'*4] ``` [Try it online!](https://tio.run/##HY3BCsMgEETv/Qpv0SQFYykNBr9kWUrBSAPLRhZ76CW/bk1nGHgzl8nf8t75NmepNa5JJU3G9zTGQIus5SMMmnwgcB4HAu/QvDhejzi4XhNM5/jAVggsmrSLeqqNO9vUYSUVFNxH2@xapj9ZvGTZuOjzy9Qf "Python 3.8 (pre-release) – Try It Online") Thanks HyperNeutrino, SSAnne and Surculose Sputum for -1 each! [Answer] # [R](https://www.r-project.org/), ~~76~~ ~~64~~ 50 bytes -12 bytes thanks to Giuseppe! -8 bytes with outer product `%*%` -6 bytes by changing the order of the output ``` scan()%*%matrix(c(y<-2:0%o%c(2:0,0:2),rev(y)),9)+1 ``` [Try it online!](https://tio.run/##DcUxCoAwDADAr2QJJFqhSVW0@JlSHBxUqCL29dFbrphdOR3E2OCe7rK9lKkunUaPJ2b6dz4qu7I@VJndzK2YKMwQBhAICgo9jCCTfQ "R – Try It Online") Takes input as 9 integers, top to bottom and left to right. Output is in order (NW, SW, NE, SE). Performs the matrix multiplication of the input vector with the matrix ``` 4 0 0 0 2 0 2 0 0 0 4 0 2 2 0 0 1 1 1 1 0 0 2 2 0 4 0 0 0 2 0 2 0 0 0 4 ``` which is constructed by inputting the values of the first two columns, and then combining with those columns in reverse. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~25~~ ~~17~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2Ý‚Dδδ*€€*OO> ``` -8 bytes by porting [*@HyperNeutrino*'s Jelly answer](https://codegolf.stackexchange.com/a/200932/52210), so make sure to upvote him!! -3 bytes thanks to *@Grimmy*. I/O are both integer-matrices. The output-matrix is mirrored diagonally (i.e. if the input-matrix would be `[[a,b,c],[d,e,f],[g,h,i]]` the output-matrix would result in `[[I,G],[C,A]]`). [Try it online](https://tio.run/##yy9OTMpM/f/f6PDcw02PGma5nNtybovWo6Y1QKTl72/3/390tKGRjqWOsWmsTrShjrGRjhGQYaJjpmNoERsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3lopQ6Xkn9pCZT/3@jw3MNNjxpmuZzbcm6L1rmt57YeWqdVW@vvb/df59A2@//R0dEGOkAYq4NGAxnRhjpGOoZAhpGOiY4RkIbwQTKmSGqNwLQhTI@RjqWOsSlYtbERWNJEx0zH0AIsawkEOnACKEJIAK7JWMfSwMAQbBWQa4GuHKo6FgA). **Explanation:** ``` 2Ý # Push list [0,1,2]  # Bifurcate it (short for Duplicate & Reverse copy) ‚ # Pair those two together: [[0,1,2],[2,1,0]] D # Duplicate it δ # Apply double-vectorized: δ # Inner apply double-vectorized: * # Multiply: # [[[[0,0,0],[0,1,2],[0,2,4]], # [[0,0,0],[2,1,0],[4,2,0]]], # [[[0,2,4],[0,1,2],[0,0,0]], # [[4,2,0],[2,1,0],[0,0,0]]]] € # Map over each inner pair of matrices: € # Map over each matrix in this pair: * # Multiply each by the (implicit) input-matrix at the same indices O # Sum each row of the inner-most matrices O # Sum those row-sums together as well > # And increase each by 1 for the board itself # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 47 bytes ``` x=scan();4*x[1:4]+2*x[5:8]+2*x[c(6:8,5)]+x[9]+1 ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PT2kSrItrQyiRW2wjIMLWygDCSNcysLHRMNWO1K6ItY7UN/xsaKRibKhhaKJgoGCpYKhgpmCkYG/0HAA "R – Try It Online") Input is a vector in the order ``` 1 6 2 5 9 7 4 8 3 ``` And output ``` 1 2 4 3 ``` [Answer] # JavaScript (ES6), ~~63~~ 57 bytes Takes input as a flat array of 9 integers. Outputs a flat array of 4 integers. ``` a=>[0,2,6,8].map(i=>a[i]*4+2*(a[3+i%6]+a[i>2?7:1])-~a[4]) ``` [Try it online!](https://tio.run/##lU7LDoIwELz7Fb2YtFAILVDBBPyQpocNgqlBSsR49NdrxWjUlIObzWQfM7N7hCtMzVmPl2gw@9Z2lYWqlgnlVNBCxScYsa5qkFoFWcgDDDIN9Vqo0I1qvttsmSLRDWSmiG3MMJm@jXtzwB12JsifipDVD5dRxCl6YvZRMw83/7bjM7IFX7ctKUrzmZHy1wHh@sLDL104xV@4aPO4nSRs/s8rfevtHQ "JavaScript (Node.js) – Try It Online") ### How? Below is the matrix of the item indices: $$\pmatrix{ 0&\color{red}1&2\\ \color{blue}3&4&\color{blue}5\\ 6&\color{red}7&8}$$ We iterate on the indices of the corners \$i\in\{0,2,6,8\}\$. The index of the left or right edge (\$\color{blue}3\$ or \$\color{blue}5\$) is given by: $$H\_i=3+(i\bmod6)$$ The index of the top or bottom edge (\$\color{red}1\$ or \$\color{red}7\$) is given by: $$V\_i=\cases{ 1&\text{if $i\le2$}\\ 7&\text{if $i>2$} }$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` F⁴«≔E³E⮌θ§μκθ⟦I⊕ΣEθ×λΣEκ×νμ ``` [Try it online!](https://tio.run/##NYw9D4IwFEVn@BVvfE2eAx8ajRNxYjAx6tZ0IFCVQIu0lZgYf3sFA3e5957hlI/ClF3Ren/rDGDK4BMGmbX1XeOxeGJCMNVZDtJYiT0jyFyuK/lGRdAwNoKe7cPgZGrtkB8K6zDXpZFKaicrvLzUX9QTXGslLbYEC2sWpgkUmyNG29d7znkUE8COIFkLCgE4ROOeWDz/dNwbgmgrhPCrof0B "Charcoal – Try It Online") Link is to verbose version of code. Outputs the four corners in order top right, top left, bottom left, bottom right as compared to the test case format. Explanation: ``` F⁴« ``` Process each corner in turn. ``` ≔E³E⮌θ§μκθ ``` Rotate the board. ``` ⟦I⊕ΣEθ×λΣEκ×νμ ``` Multiply each row and column by its coordinate, then sum the results, and increment the final total. [Answer] # [Python 3](https://docs.python.org/3/), ~~90~~ 86 bytes ``` lambda a,b,c,d,e,f,g,h,i:(4*a+2*b+2*d-~e,2*b+2*f+4*c-~e,2*d+4*g+2*h-~e,2*f+2*h+4*i-~e) ``` [Try it online!](https://tio.run/##LYhBCoMwFAWv4jKJT7DRbgqepLpITL4JtBrETTdePf4SeQzMvPQ7wrZ2mYYxf8zXOlMZWMxw8CAsCIgv0StTa2UZ15weRanu1VzSsS58hZL0V74ip8xpj@shSKj3E@09zTzQTlLmCw "Python 3 – Try It Online") Thanks @xnor for the -4. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytes ``` 1+{⍉⊥2↑⍉↑⍵⍮⌽⍵}⍣2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/31C7@lFv56OupUaP2iaCWCBy66PedY969gIZtY96Fxv9T3vUNuFRb9@jvqme/o@6mg@tNwYp65saHOQMJEM8PIP/pykAhTQMFIBQE5XigkgZAjmGIDFDkBSEB5cyAkkZKZgoGGlCeTApIwVLBWNTkKixEUjWRMFMwdBCEwA "APL (Dyalog Extended) – Try It Online") An anonymous function that takes a 3x3 matrix and returns a 2x2 matrix. ### How it works ``` 1+{⍉⊥2↑⍉↑⍵⍮⌽⍵}⍣2 ⍝ Input: 3x3 matrix of numbers { ↑⍵⍮⌽⍵} ⍝ Join the input with its horizontal reverse, ⍝ adding a leading length-2 axis ⍉ ⍉ ⍝ For each row (last axis), 2↑ ⍝ Take the first two numbers x, y and ⊥ ⍝ Apply base-2, i.e. evaluate (2×x)+y ⍝ (equivalent to dot product with [2 1 0]) ⍣2 ⍝ Repeat the above twice 1+ ⍝ Increment element-wise ``` [Answer] # Excel (as CSV), 92 bytes ``` ,,,=1+A1*4+(B1+A2)*2+B2,=1+C1*4+(B1+C2)*2+B2 ,,,=1+A3*4+(B3+A2)*2+B2,=1+C3*4+(B3+C2)*2+B2 ,, ``` To use: Input between `,`'s, save as CSV, open in Excel. Eg: ``` 12,9,35,=1+A1*4+(B1+A2)*2+B2,=1+C1*4+(B1+C2)*2+B2 1,32,2,=1+A3*4+(B3+A2)*2+B2,=1+C3*4+(B3+C2)*2+B2 4,6,18 ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 73 bytes ``` :a;0{..2/2*:x;2%2*:y;).2%!a...x=y=4*\x=1=2*+\1=y=2*+\1=1=+)`" "+\n*+\}4*; ``` Just here to submit something. Cool question! stack-based languages are NOT the solution. Fuck this shit, lmfao. Could probably golf with better modulo shit, but I've stopped caring lol [Try the really "golf-inputted" one, awkward for input](https://tio.run/##JcdBCsIwEEbhvaf4LXTRBEZnGkUb5iRJwCIoQlFRFyni2WPE1Xvf@TadnsfH5f4qIbAAe/SbtEBg9FXyWwdswbuUyjD69ZtIVmKG7KWtmX1H0i5HIso6qzMxK6sYG7nyX1bbHRo0Nl6rP874Ur4 "GolfScript – Try It Online") [Same program, weird header and footer to format OP's input into the one above, easier to use and test. Plus, look at that identically-formatted output. Gorgeous, ainnit?](https://tio.run/##JY3RCoIwGIXvfYo/YRfut183Lcqx8D1akASGGCuqC2XMV1@Trs754PCd@/PRf27v4fUNtnAppMwtnnkWmk6VjkgWkjeTkizGrDKSbNMR0aRnXXMzaaElRyMi/lNozK5Rg8ZG9jVXARHtdjWXzajWC6R8PDnKI3rnh96zCKNZN9ygZ@fFtu0lCAlwhGqXgIAqdplADbAHcfgB "GolfScript – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -MPOSIX -a`, 76 bytes ``` map$_*=++$i==5||$i%2*2+2,@F;map{say ceil.25+sum@F[$_,$_+1,$_+3,$_+4]}0,1,3,4 ``` [Try it online!](https://tio.run/##FYzLCsIwFER/5S7ipklLHo1oJdBVQVAURBBEQpAuAqkNJi7E@uvGdHNmOAPj@6eTKQ3GI10ojJFVSk4TsgtecMxJ223y9gnmDffeuopLHF5D212RJkhjNkPMqG9fShgRpE6JcYA1CAkMRK4caoAlsNVv9NGOj5DKvawoozl3NsSmOUfrVP7N4ng4bS@pNH8 "Perl 5 – Try It Online") ### Input: If the grid is denoted as: ``` a b c d e f g h i ``` Then the input is space separated: ``` a b c d e f g h i ``` ### Output: Output is line separated: ``` balloons attached at a balloons attached at c balloons attached at g balloons attached at i ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 19 bytes ``` 3,1p`ạ€3Rp`¤P€€×³§‘ ``` [Try it online!](https://tio.run/##y0rNyan8/99Yx7Ag4eGuhY@a1hgHFSQcWhIAZAHR4emHNh9a/qhhxv///6MNjXQULHUUjE11FAyBFJAHRCY6CmZAvkUsAA "Jelly – Try It Online") # How? Notice that we can create the weight matrices for each corner by finding the absolute difference to the opposite corners. For example, for the first balloon, the weight matrix is ``` 4 2 0 2 1 0 0 0 0 ``` This can be found by, for each coordinate, find the absolute difference to the corner (3, 3), and product. For example, (1, 1) has an absolute difference (2, 2) and product 4. ``` 3,1p`ạ€3Rp`¤P€€×³§‘ Main link 3,1 Get 3,1 pair p` cartesian product with itself, gives the 3 corner coordinates 3Rp`¤ Get all the coordinates ạ€ get the absolute differences for each corner coordinate P€€ product each subsublist ׳ vectorize multiply with the input §‘ sum each sublist and increment ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒJḂ§2*ṁ×⁸+Ɲ⁺€‘ ``` A monadic Link accepting a list of lists of integers which yields a list of list of integers: `[[top-left, top-right], [bottom-left, bottom-right]]` **[Try it online!](https://tio.run/##y0rNyan8///oJK@HO5oOLTfSeriz8fD0R407tI/NfdS461HTmkcNM/7//x9taKSjYKmjYGwaq6MQbQhkAPlGILaJjoKZjoKhRSwA "Jelly – Try It Online")** ### How? ``` ŒJḂ§2*ṁ×⁸+Ɲ⁺€‘ - Link: list of lists of integers, T e.g. [[ 3, 9, 5],[ 1, 3, 2],[ 4, 6, 1]] ŒJ - multidimensional indices (T) [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] Ḃ - least significant bit (vectorises) [[1,1],[1,0],[1,1],[0,1],[0,0],[0,1],[1,1],[1,0],[1,1]] § - sums [2,1,2,1,0,1,2,1,2] 2 - literal two 2 * - exponentiate [4,2,4,2,1,2,4,2,4] ṁ - mould like (T) [[ 4, 2, 4],[ 2, 1, 2],[ 4, 2, 4]] ⁸ - chain's left argument, T [[ 3, 9, 5],[ 1, 3, 2],[ 4, 6, 1]] × - multiply (vectorises) [[12,18,20],[ 2, 3, 4],[16,12, 4]] Ɲ - for neighbours: + - add (vectorises) [[14,21,24],[18,15, 8]] € - for each: ⁺ - repeat last link [[35,45],[33,23]] - (...i.e +Ɲ for each) ‘ - increment (vectorises) [[36,46],[34,24]] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~67~~ 66 bytes ``` f a b c d e f g h i=[2*v+e+1|v<-[2*a+b+d,b+2*c+f,d+2*g+h,f+h+2*i]] ``` [Try it online!](https://tio.run/##LYZBCoAgFAWv8pbVNyihXZ4kWmj6UyqJClfd3VzEMMx4fW9u33NmaBgssHBgrPAIapJNIkf9m8a2vCZDVhiSzUIsbOlKXjD5cmGe86FDhMJ5hfhUjAHdjyz26Or8AQ "Haskell – Try It Online") Inspired by [my Python answer](https://codegolf.stackexchange.com/a/200937/75323). [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 138 bytes ``` ,[->++++<],[->++>++<<],[->>++++<<],[->++>>++<<<],[->+>+>+>+<<<<],[->>++>>++<<<<],[->>>++++<<<],[->>>++>++<<<<],[->>>>++++<<<<]>+.>+.>+.>+. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXThsIbGIhLCCygbAhwnBxsASUB4E2NgiVUGkoH6oVwUOVhUnbxNpp68HR//8A "brainfuck – Try It Online"), just for the byte count. [Try it here](https://copy.sh/brainfuck/?c=LFstPisrKys8XSxbLT4rKz4rKzw8XSxbLT4-KysrKzw8XSxbLT4rKz4-Kys8PDxdLFstPis-Kz4rPis8PDw8XSxbLT4-Kys-PisrPDw8PF0sWy0-Pj4rKysrPDw8XSxbLT4-PisrPisrPDw8PF0sWy0-Pj4-KysrKzw8PDxdPisuPisuPisuPisu), by pasting this input: `\12\9\35\1\32\2\4\6\18` and hitting the "view memory" button to compare it with the expected output `101 195 063 121`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes ``` mh+eQ+ys<.<ecPQ4d2yy@Qd4 ``` [Try it online!](https://tio.run/##K6gsyfj/PzdDOzVQu7LYRs8mNTkg0CTFqLLSITDF5P//aEMjHWNTHUMLHRMdQx1LHSMdMx1jo1gA "Pyth – Try It Online") I/O format: List `[0, 1, 2, 3, 4, 5, 6, 7, 8]` (input) and `[0, 1, 2, 3]` (output) with positions ``` Input: 0 5 1 Output: 0 1 = Q 4 8 6 3 2 3 7 2 ``` ### Explanation ``` m 4 # map [0, 1, 2, 3] to (current number = d) h # 1 + +eQ # Q[-1] + 1 + ys # 2 * sum of ec 4 # chop into pieces of length 4, take last element PQ # Q[:-1] -> [4,5,6,7] .< d # rotate left by d < 2 # first two elements -> [4,5], [5,6], [6,7] or [7,4] + # + yy # 4 * @Qd # Q[d] ``` [Answer] # [PHP](https://php.net/), 101 bytes A rather inelegant solution. Just multiples corners by 4, sides by 2 and adds 1 to the center than adds up each corner. Some form of matrix multiplication may be possible with `array_map()`. ``` parse_str($argv[1]);$e++;echo$a*4+$b*2+$d*2+$e,$c*4+$b*2+$f*2+$e,$g*4+$d*2+$h*2+$e,$i*4+$f*2+$h*2+$e; ``` [Try it online!](https://tio.run/##RclBDoMgEAXQy0wmVlxg24UGSQ/SNA3iAK4kYHp96qhpZ/F/5v0YYhkecctoUqZ3XlMFJvnPs31dFJAQimxYwNR3AWN9FTBxUAP2J@4Uz7LP4ZSZxf1FlVKM7rfDUd/Q6l7KFictkVg7dMfojwpcOO/PFw "PHP – Try It Online") It takes input as a string in a html query format e.g. `a=9999&b=3&c=9001&d=0&e=9998&f=9999&g=9999&h=999&i=9999` +7 bytes if the output can't be an unseparated list, by making it into an array and using `print_r()` # [PHP](https://php.net/), 108 bytes ``` parse_str($argv[1]);$e++;print_r([$a*4+$b*2+$d*2+$e,$c*4+$b*2+$f*2+$e,$g*4+$d*2+$h*2+$e,$i*4+$f*2+$h*2+$e]); ``` [Try it online!](https://tio.run/##RcxNDoJADAXgyzQNMi4GdSHBiQchhgwwfxvTFOL1xykQ7eK99GtSipQfTypJlhc3LCtXYDl8@uZ16sAp1RGn9zpw1YOtbwrG@qJglnBnmH7iDwki2zkekkT8X8rfnLM1bRkczRUn02rd4Gw0OtE7@v0Y9opSmLblCw "PHP – Try It Online") ]
[Question] [ A positive integer can be *diluted* by inserting a `0` between two bits in its binary expansion. This means that an `n`-bit number has `n-1` dilutions, which are not necessarily all distinct. For example, for `12` (or `1100` in binary), the dilutions are ``` 11000 = 24 ^ 11000 = 24 ^ 10100 = 20 ^ ``` In this challenge, we're going to be taking the sum of all the dilutions, exclusive of the original number. For `12`, taking the sum of `24, 24, 20` results in `68`, so `68` should be the output for `12`. ### Challenge Given a positive integer `n > 1` as input, output/return the diluted sum as explained above. ### Examples ``` in out --- --- 2 4 3 5 7 24 12 68 333 5128 512 9216 ``` ### Rules * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given in [any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~43~~ 39 bytes ``` f=lambda n,i=2:n/i and n*2-n%i+f(n,i*2) ``` [Try it online!](https://tio.run/##FcjBCkBAEAbgu6f4L5tdRjKb1JaHWWkzxRAunn5x@/qO51525ZzTuMZtmiOUZOSgrSDqDK24USN1st9X7HLaTwhEwQRPGAjdL/@57zgUwHGK3iiNvwLMVRorhGTFufwC "Python 2 – Try It Online") --- ## How? Each call of the recursive function calculates a single dilution. The position of the inserted `0` is `log2(i)`. The function recurses until `i` gets bigger than `n` and the insertion would be on the left of the number. If `i>n`, `n/i` evaluates to `0`, which is a falsy value in Python. `n*2` shifts the entire number one binary digit left, `n%i` or `n % 2**(position of insertion)` calculates the value of the part that should not be shifted left. This value gets subtracted from the shifted number. ## Example (n=7) ``` call n/i bin(n) n*2 n%i dilution return value f(7, i=2) 3 => truthy 0b111 0b1110 0b1 0b1101 = 13 13 + f(7, 2*2) = 13 + 11 = 24 f(7, i=4) 1 => truthy 0b111 0b1110 0b11 0b1011 = 11 11 + f(7, 4*2) = 11 + 0 = 11 f(7, i=8) 0 => falsy 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` BJṖ2*ɓdḅḤ}S ``` [Try it online!](https://tio.run/##y0rNyan8/9/J6@HOaUZaJyenPNzR@nDHktrg/0f3HG5/1LTG/f9/Ix0FYx0Fcx0FQxDLGMg2NTQCAA "Jelly – Try It Online") ### How it works ``` BJṖ2*ɓdḅḤ}S Main link. Argument: n (integer) B Binary; convert n to base 2. This yields a digit array A. J Indices; yield [1, ..., len(A)]. Ṗ Pop; remove the last element, yielding [1, 2, ..., len(A)-1]. 2* Elevate 2 to these powers, yielding [2, 4, ..., 2**(len(A)-1)]. Let's call the result B. ɓ Begin a new, dyadic chain, with left argument n and right argument B. d Divmod; yield [n/b, n%b], for each b in B. Ḥ} Unhalve right; yield 2b for each b in B, i.e., [4, 8, ..., 2**len(A)]. ḅ Unbase; convert each [n/b, n%b] from base 2b to integer, yielding (2b)(n/b) + (n%b). S Take the sum. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` tZl:W&\5ME*+s ``` Try it at [MATL Online!](https://matl.io/?code=tZl%3AW%26%5C5ME%2a%2Bs&inputs=333&version=20.6.0) Or [verify all test cases](https://matl.suever.net/?code=jU%22%40%0AtZl%3AW%26%5C5ME%2a%2Bs&inputs=2+3+7+12+333+512&version=20.6.0). ### Explanation Consider input `12` as an example. ``` t % Implicit input. Duplicate % STACK: 12, 12 Zl % Binary logarithm % STACK: 12, 3.584962500721156 : % Range (rounds down) % STACK: 12, [1 2 3] W % Power with base 2, element-wise % STACK: 12, [2 4 8] &\ % 2-output modulus, element-wise: pushes remainders and quotients % STACK: [0 0 4], [6 3 1] 5M % Push array of powers of 2, again % STACK: [0 0 4], [6 3 1], [2 4 8] E % Multiply by 2 % STACK: [0 0 4], [6 3 1], [4 8 16] * % Multiply, element-wise % STACK: [0 0 4], [24 24 16] + % Add, element-wise % STACK: [24 24 20] s % Sum of array. Implicit display % STACK: 68 ``` [Answer] # C, ~~58~~ 56 bytes *Thanks to @Dennis for saving two bytes!* ``` s,k;f(n){for(s=0,k=2;k<=n;k*=2)s+=n/k*k*2+n%k;return s;} ``` [Try it online!](https://tio.run/##fYxBCsIwEEX3PUUoFGbSiJoiLsa5iRuJRsrgKEldlZ49Ftwa//I/3gubewilZCcUQXGOzwSZd07Yk5xYSSx7zD3rVqxY32snlG7TO6nJtJRRJ/O4jArYzI1Z90rrFaHtrmdtnYngEek3GarkWCX7P7mhHjx8vaV8AA) # [C (gcc)](https://gcc.gnu.org/), 50 bytes ``` s,k;f(n){for(s=0,k=2;k<=n;)s+=n%k+n/k*(k+=k);k=s;} ``` Returning by `k=s;` is undefined behaviour, but works with gcc when optimizations are disabled. Also, `n%k+n/k*(k+=k)` has [unspecified behaviour](https://en.wikipedia.org/wiki/Unspecified_behavior), but seems to work fine with gcc. [Try it online!](https://tio.run/##fYxBCsIwEEX3PUUoFGZMRG2RLsa5STcSiYTBUZruSs8eA90a//I/3vPHp/c5JycUQHEN7xkSn51wT3JjJUyWtROrJzmAWBYk4URbjrqY1z0qYLM2puwzlytA2z0mbZ0J0CPSbzJUyVgllz@5oR687t6Wvw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` BḊḄÐƤạḤS ``` [Try it online!](https://tio.run/##y0rNyan8/9/p4Y6uhztaDk84tuThroUPdywJ/n90z@H2R01r3P//N9JRMNZRMNdRMASxjIFsU0MjAA) ``` B to binary 42 -> 1 0 1 0 1 0 Ḋ drop first 0 1 0 1 0 ḄÐƤ each suffix to decimal 10 10 2 2 0 Ḥ double the input 84 ạ absolute difference 74 74 82 82 84 S add them up 396 ``` Vice versa, `B¹ƤṖ+BḄS`: get prefixes, drop last, add them to input, and sum. [Answer] # [J](http://jsoftware.com/), ~~20 15~~ 14 bytes ``` +/@}:@:+[\&.#: ``` [Try it online.](https://tio.run/##y/r/P81WT0Fb36HWysFKOzpGTU/Z6n9qcka@QppCallqUaWCkYKxgrmCIZAyNlYwNTT6DwA) ### 15 bytes ``` 1#.-,+:-#.\.@#: ``` [Try it online!](https://tio.run/##y/r/P81WT8FQWU9XR9tKV1kvRs9B2ep/anJGvkKaQmpZalGlgpGCsYK5giGQMjZWMDU0@g8A) ``` +: Input×2 - Subtract #.\.@#: The list of binary suffixes of input (in decimal) -, Append negative input 1#. Add them up ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 11 bytes ``` ¢¬£¢iYTÃÅxÍ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=oqyjomlZVMPFeM0=&input=ODg4) --- ## Explanation ``` :Implicit input of integer U ¢ :Convert to base-2 string ¬ :Split to an array of individual characters/digits £ à :Map over the elements, with Y being the current 0-based index ¢ : Convert U to a base-2 string iYT : Insert a 0 in that string at index Y Å :Slice off the first element of the array Í :Convert each element to a base-10 integer x :Reduce by addition ``` [Answer] # JavaScript (ES6), ~~41~~ 40 bytes *Saved 1 byte thanks to Mr.Xcoder* ``` f=(n,k=1)=>k<n&&(n&k)+2*(n&~k)+f(n,k-~k) ``` ### Test cases ``` f=(n,k=1)=>k<n&&(n&k)+2*(n&~k)+f(n,k-~k) console.log(f(2 )) // 4 console.log(f(3 )) // 5 console.log(f(7 )) // 24 console.log(f(12 )) // 68 console.log(f(333)) // 5128 console.log(f(512)) // 9216 ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~53~~ ~~50~~ 47 bytes ``` .+ * +`(_+)\1 $1O O_ _ L$`\B $`O$' +%`\B ¶$`¶ _ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0uLSztBI15bM8aQS8XQn8s/niuey0clIcaJSyXBX0WdS1sVxD60TSXh0Dau@P//jbiMucy5DIGUsTGXqaERAA "Retina – Try It Online") Link includes test cases. Edit: Saved 3 bytes thanks to @MartinEnder. Explanation: ``` .+ * +`(_+)\1 $1O O_ _ ``` Convert from decimal to binary, but using O to represent 0, as it's not a digit, and \_ to represent 1, as it's the default repetition character in Retina 1. ``` L$`\B $`O$' ``` Insert an O between each pair of digits, and collect the results as a list. ``` +%`\B ¶$`¶ ``` Convert from binary to unary. (This conversion produces extra `O`s, but we don't care.) ``` _ ``` Sum and convert to decimal. [Answer] # [Pyth](https://pyth.readthedocs.io), 13 bytes ``` smiXd.BQZ2Ssl ``` **[Try it here!](https://pyth.herokuapp.com/?code=smiXd.BQZ2Ssl&input=333&debug=0)** ### Explanation ``` smiXd.BQZ2Ssl | Full program. sl | The base-2 logarithm of the input, floored to an integer. S | Create the integer range [1 ... the floored logarithm]. m | And map a function over it. ------------+-+----------------------------------------------------- iXd.BQZ2 | The function to be mapped (uses a variable d). .BQ | In the binary representation of the input... X Z | ... Insert a zero... d | ... At index d. i 2 | And convert the result from base 2 to an integer. ------------+-+----------------------------------------------------- s | Sum the resulting list. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` BµLḤ_J’×µḄ ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//QsK1TOG4pF9K4oCZw5fCteG4hP///zEy "Jelly – Try It Online") Not the shortest currently, but it could be if there's a way around `Bµ µḄ`... ### Explanation ``` BµLḤ_J’×µḄ Main link. Argument: n (integer) B Binary; convert n to an binary of binary digits. Call this A. µ Start a new monadic link with argument A. L Length; yield len(A). We'll call this l. Ḥ Unhalve; yield l * 2. J Length range; yield [1, 2, ..., l]. _ Subtract; yield [l*2 - 1, l*2 - 2, ..., l]. ’ Decrement; subtract one from each item. × Multiply each item by the corresponding item in A. Call this B. µ Start a new monadic link with argument B. Ḅ Unbinary; convert from a binary array to a decimal. ``` Basically, this works by multiplying each binary digit by a magic number. I can't explain it without visualizing it, so here's the binary number we'll be working with: ``` 1111 ``` As explained by the challenge, he output we want is the sum of these binary numbers: ``` 10111 = 2^4 + 2^2 + 2^1 + 2^0 11011 = 2^4 + 2^3 + 2^1 + 2^0 11101 = 2^4 + 2^3 + 2^2 + 2^0 ``` However, we don't actually have to insert zeroes: Jelly's "unbinary" atom will accept numbers other than just `0` and `1`. When we allow ourselves to use `2`, this pattern gets simpler: ``` 2111 = 2*2^3 + 1*2^2 + 1*2^1 + 1*2^0 2211 = 2*2^3 + 2*2^2 + 1*2^1 + 1*2^0 2221 = 2*2^3 + 2*2^2 + 2*2^1 + 1*2^0 ``` When we sum up the digits in each column, we get ``` 6543 = 6*2^3 + 5*2^2 + 4*2^1 + 3*2^0 = 48 + 20 + 8 + 3 = 79. ``` The trick this answer uses is to generate this pattern, and multiply each digit by the corresponding digit in the original to cancel out the necessary columns. 12, for example, would be represented as ``` 1100 ×6543 =6500 = 6*2^3 + 5*2^2 + 0*2^1 + 0*2^0 = 48 + 20 + 0 + 0 = 68. ``` [Answer] # Java 8, 55 bytes ``` n->{int r=0,i=2;for(;i<=n;r+=n%i+n/i*(i*=2));return r;} ``` Port of [Steadybox' C answer](https://codegolf.stackexchange.com/a/154310/52210), and golfed 3 bytes in the process. [Try it online.](https://tio.run/##hY67DsIwDEV3vsILUsqjvIQYQvgDujAihpCmyKW4VZpWQlW@vaQ8ViLZlnyvda5z2cp5WWnK03uvClnXcJRI3QgAyWqTSaUhGda3AIoNkyLuFefbV22lRQUJEAjoaX7ohhMjljMUa56VhnHcC@JmKmiMU1rghOFErKOIG20bQ2C46/kHVjXXwsO@zLbEFB7@H3ayBul2vsjo88vpWVv9iMvGxpV3bEGMYsUG6D9/E/B3AX8VDNiEIrY/hhu5/gU) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 12 bytes -1 byte thanks to @Mr. Xcoder! ``` ṁḋ§z·+Θḣotṫḋ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxoc7ug8trzq0XfvcjIc7FueXPNy5Gij0//9/Y2NjAA "Husk – Try It Online") ### Explanation ``` ṁḋ§z·+Θḣ(tṫ)ḋ -- example input: 6 ḋ -- convert to binary: [1,1,0] § -- fork argument (tṫ) -- | tail of tails: [[1,0],[0]] ḣ -- | heads: [[1],[1,1],[1,1,0]] z -- and zipWith the following (example with [1,0] [1]) · Θ -- | prepend 0 to second argument: [0,1] + -- | concatenate: [1,0,0,1] -- : [[1,0,1,0],[1,1,0,0]] ṁ -- map the following (example with [1,0,1,0]) and sum ḋ -- | convert from binary: 10 -- : 22 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` .²LoDЉø`r·*+O ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f79Amn3yXowseNWw4vCOh6NB2LW3///8NjQA "05AB1E – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~21~~ 18 bytes ``` 2*a-a%2**_MS1,#TBa ``` [Try it online!](https://tio.run/##K8gs@F/930grUTdR1UhLK9432FBHOcQp8X@tgi9XNJeCEZeCMZeCOZeCIYhlDGSbAlmx///r5gEA "Pip – Try It Online") ### Explanation Call our input number `a`. For each binary index `i` at which we want to insert a zero, we can calculate the bits left of the insertion point as `a // 2**i` (where `//` is integer division and `**` is exponentiation), the bits right of the insertion point as `a % 2**i`, and therefore the diluted integer as `2 * (a // 2**i) * 2**i + (a % 2**i)`. But `(a // 2**i) * 2**i` is equal to `a - (a % 2**i)`, and so we can rearrange to a shorter formula: `2 * (a - a % 2**i) + a % 2**i` = `2 * a - a % 2**i`. ``` 2*a-a%2**_MS1,#TBa a is 1st command-line argument (implicit) TBa Convert a to binary # Length of the binary expansion 1, Range from 1 up to (but not including) that number MS Map this function to the range and sum the results: 2*a-a%2**_ The above formula, where _ is the argument of the function The final result is autoprinted ``` [Answer] # [R](https://www.r-project.org/), ~~141~~ 48 bytes ``` function(n,l=2^(1:log2(n)))sum(n%%l+(n%/%l*2*l)) ``` [Try it online!](https://tio.run/##DcQxCoAwDADAva9wKSS1ok23ol8RRIgIMRWrg6@v3nBX5WbsKj@63ntWUC8TzRCS5I1AEbE8B6i10v73Vhw5QawMgdAwxBjRlOU85QVKYfCM9QM "R – Try It Online") ~~Either I'm doing something really wrong or R is just terrible at bit manipulation.~~ Porting [Luis Mendo's approach](https://codegolf.stackexchange.com/a/154311/67312) is easy, correct, and golfy. But if you really just want to muck around with bit operations, [MickyT](https://codegolf.stackexchange.com/users/31347) suggested the following 105 byter: ``` function(i)sum(sapply(1:max(which(b<-intToBits(i)>0)),function(x)packBits(head(append(b,F,x),-1),"i")))-i ``` [Try it online!](https://tio.run/##PY1BCoMwEEX3PUVxNQMTMIZuRLrooifwAjEaMrTG0EQaT59qKV19Pv89/qvYcyeKXb1JvHhgjOsMUYfw3EC2s87wdmwcDJ1gn/rlxinu1LVGpL@VMWjz@E5u0iPs@uRHGOhOGUlIpIorRBRcLMgGTxaUUkdcjva7a1pZk8XyAQ "R – Try It Online") [Answer] # Python 3, ~~92~~ ~~80~~ 78 bytes ``` def b(x):x=f'{x:b}';return sum(int(x[:i]+'0'+x[i:],2)for i in range(1,len(x))) ``` [Try It Online](https://tio.run/##K6gsycjPM/7/PyU1TSFJo0LTqsI2Tb26wiqpVt26KLWktChPobg0VyMzr0SjItoqM1Zb3UBduyI60ypWx0gzLb9IIVMhM0@hKDEvPVXDUCcnNQ9ohqbm/4IikI4kDSNNTS4Y2xiJbY7ENkRRZIyszBQk9x8A) Thanks to [Mr.XCoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) and [ovs](https://codegolf.stackexchange.com/users/64121/ovs) for -12 bytes and -2 bytes respectively. [Answer] ## Batch, ~~92~~ 77 bytes ``` @set/an=2,t=0 :l @if %1 geq %n% set/at+=%1*2-(%1%%n),n*=2&goto l @echo %t% ``` Edit: Switched to the same formula everyone else is using. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` BLḊṬœṗ¥€Bj€0ḄS ``` [Try it online!](https://tio.run/##y0rNyan8/9/J5@GOroc71xyd/HDn9ENLHzWtccoCEgYPd7QE////39TQCAA "Jelly – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 36 + 1 (`-p`) = 37 bytes ``` $\+=$_*2-($_&$.-1)while($.*=2)<=$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWJV7LSFdDJV5NRU/XULM8IzMnVUNFT8vWSNMGKFdb/f@/sbHxv/yCksz8vOL/ugUA "Perl 5 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 57 bytes ``` Sum##UnBin=>{Join[Join=>_,"0"]}=>SplitAt#1&`:@{#_-1}##Bin ``` [Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8z@4NFdZOTTPKTPP1q7aKz8zLxpE2NrF6ygZKMXW2toFF@RkljiWKBuqJVg5VCvH6xrWKisDlf@P5QooyswrUbC1UwBpUVNS0LVTUAJxw5TTQFS0kY6CsY6CuY6CIYhlDGSbGhrF/gcA "Attache – Try It Online") I thought I'd approach the problem from a non-bit manipulation approach, as such an approach is impractical in Attache. I have to investigate some of the parts of this approach for alternatives. ## Explanation Here is an expanded version: ``` Define[$joinByZero, {Join[Join=>_,"0"]}] Define[$insertionPoints, SplitAt#1&`:@{#_-1} ] Define[$f, Sum##UnBin=>joinByZero=>insertionPoints##Bin ] ``` This simply takes the binary representation of the number, splits it at certain points, inserts zeroes there, converts back to decimal, and sums them together. [Answer] # [J](http://jsoftware.com/), 33 bytes ``` 1#.[:}:#.@(<\;@(,0;])"0<@}.\.)@#: ``` Most probably there is much room for further golfing. ## How? `@#:` convert to binary and `<@}.\.` - find all suffices, drop the first digit from each and box `<\` - find all prefixes and box them `(,0;])"0` - to each prefix append 0 then append the corresponding beheaded suffix `;@` raze (unbox) `1#.[:}:#.@` - convert to decimal, curtail and sum [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1oq1qrZT1HDRsYqwdNHQMrGM1lQxsHGr1YvQ0HZSt/mtyKXClJmfkK6QppJalFlUqGCkYK5grGAIpY2MFU0Oj/wA "J – Try It Online") ]
[Question] [ I have a stupid old alarm clock with two buttons: `hour` and `minute`. The `hour` button increments the hour of a set alarm, and `minute` increments the minute time of a set alarm. However, some smart designers realized that pressing both buttons at the same time should have a meaning, and decided that pressing `hour` and `minute` simultaneously would cause the alarm to be set to `12:00 am`/`0:00`. Your task is to simulate this behavior. # Task Given a start time and a sequence of button states, figure out the end time. Starting from the start time, increment the hour for each occurrence of `(1,0)`, increment the minute for each occurrence of `(0,1)`, and set the time to `0:00` for each occurrence of `(1,1)`. The states `(0,0)` should be ignored because they correspond to neither button being pressed. When adding to minutes and hours, if the minute/hour goes above the maximum, set it to `0`, i.e. incrementing a minute value of `59` should set the minute value to `0` and incrementing an hour value of `23` should set the hour value to `0`. Incrementing minute/hour values above their limits do not affect the other value, for example incrementing the minute of `10:59` yields `10:00`, not `11:00`. # Example Given the input time `13:58` and steps `[(0,1),(0,1),(0,1),(0,0),(1,1),(1,0)]`, 1. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:59`. 2. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:00`. 3. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:01`. 4. `(0,0)`. This corresponds to neither button being pressed. The time,unaffected, is now `13:01` 5. `(1,1)`. This corresponds to both buttons being pressed. The time is now `0:00`. 6. `(1,0)` This corresponds to `hour` being pressed. The time is now `1:00`. Since we end with `1:00`, it is the output. # I/O The input will consist of a time and a sequence of button states. The output is a single time. The input time and output time may be * a 2-tuple of `(hour, minute)` or `(minute, hour)` in `24`-hour time such as `(13, 30)` (`hour` ranges from `0` to `23` and `minute` ranges from `0` to `59`) * same as the previous but in `12`-hour time and a Boolean `am`/`pm` switch (`hour` ranges from `0` to `11` or `12` and `1` to `11` with `minute` from `0` to `59`). * a number of minutes since `0:00` such as 810 (from 0 to 1439, inclusive) * any other format which encodes the same information The sequence of button states is a representation of a list of Boolean 2-tuples, for example: * a list of tuples: `[(0,1),(1,0),(0,0),(1,1)]` * a space-delimited string: `"01 10 00 11"` * a string: `"01100011"` * in Quaternary: `[1,2,0,3]` * converted to an integer: `99` * any other format which encodes the same information # Test Cases ``` time,steps -> output 06:49,[(0, 1)] -> 06:50 12:23,[(1, 0)] -> 13:23 02:23,[(0, 1), (1, 0)] -> 03:24 21:40,[(0, 1), (0, 1), (0, 1), (0, 1)] -> 21:44 13:10,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (1, 1), (0, 1), (0, 1)] -> 00:02 21:33,[(1, 0), (0, 1), (1, 0), (0, 1)] -> 23:35 14:21,[(0, 1), (0, 1), (0, 1)] -> 14:24 02:39,[(0, 0), (0, 1)] -> 02:40 16:07,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1)] -> 19:16 17:55,[(0, 1), (1, 0), (0, 1)] -> 18:57 15:55,[(1, 0), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0)] -> 23:00 22:11,[(0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1)] -> 00:19 03:58,[(1, 0), (0, 0), (0, 0), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1)] -> 07:03 13:02,[(0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0)] -> 16:06 04:37,[(1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (1, 0)] -> 08:47 00:01,[(0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1)] -> 03:08 02:58,[(1, 0), (1, 0), (0, 1)] -> 04:59 01:43,[(0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1)] -> 04:52 07:54,[(1, 0), (0, 1), (1, 0), (1, 0), (1, 1)] -> 00:00 09:33,[(0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1)] -> 10:38 09:01,[(0, 1), (0, 1)] -> 09:03 19:04,[(0, 1), (1, 0), (0, 1), (1, 0)] -> 21:06 11:17,[(0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (1, 1), (0, 1), (0, 1)] -> 00:02 19:32,[(0, 1), (1, 0), (0, 1), (1, 0), (1, 0), (1, 0)] -> 23:34 17:31,[(0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 0), (1, 1), (0, 1)] -> 00:01 06:46,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)] -> 18:16 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` _`+Ạ}?/%24,60 ``` [Try it online!](https://tio.run/##y0rNyan8/z8@QfvhrgW19vqqRiY6Zgb///@PjjY01lEwNIjVUYg2ADLw0YY6CgZQGlM@FgA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ 75 bytes ``` lambda c,a:reduce(lambda(h,m),(d,e):(d&e)and(0,0)or((h+d)%24,(m+e)%60),a,c) ``` [Try it online!](https://tio.run/##VYvBCsIwEAXv/YpcKrv0HZKiQgt@Se1hzaZEMGkJ9eDXR8WTp2EGZnvtcc19XS7X@pB0UzEeMpagTx/oVygiMUgReCQ9BJasZGF5LUSxU277Iyh1gduzZQg8163c824WmtyA0zBj@gzGMQw5GPvln8/cNPUN "Python 2 – Try It Online") Function that takes time as a tuple (hour,minute); outputs same way. [Answer] # C, ~~89~~ 87 bytes *Thanks to @Jonathan Frech for saving two bytes!* ``` f(h,m,s)char*s;{for(;*s;++s)*s++&1?*s&1?h=m=0:++h:*s&1&&++m;printf("%d %d",h%24,m%60);} ``` [Try it online!](https://tio.run/##fVPRjoMgEHzvVzQkGpW9hBXUs6a5b2lsPPtg20jvqem3eyAlKnAnBpWZHXaHtf34bttp6pIeBpBp25/GTDbP7jYmjXqhVKaZpDTGr0yqqT8OR3agtD/ozzimdGju4@X66BISnffRmUAf5QKGqGRp85oUsh9Ol2uS7p67LilB1EAYkrS5/zxkQtSLWsYccg4EmbNulhn6AIJgGjHDleOAK9TcHktp8HlTDfsaAhSBBPVz4LqKQFAJ1WZfZp7hLCsoClOdjxUzZoTWanZ2M8oB0Wot@wd25VB8zkXry0nStzG3mpbkUATwyli4HTbEC2DwTnMp6w@LTZqhtEBwY7JbbICsPBb2jDXLgeu5Bf6xq4Z3E7hJ1CAWb1wQAavlNN4zhmX4ymM9/C7huE5xVpvJDlP9W@W6@dzz2Lq@9n/bprbFlmit/5p@AQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ (17?) 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 17 bytes? -- If the input format: `[[initHour, initMinute], [a1, b1], [a2, b2], ...]` is acceptable we'd have a monadic link and may remove `W;` from the beginning of the second line. Note: This is now converging towards [Erik the Outgolfers Jelly answer](https://codegolf.stackexchange.com/a/142983/53748), so I wont bother golfing more (I had not seen it)... ``` N⁹⁹Ạ¤?+⁸ W;ç/%24,60 ``` A dyadic link taking a list of the initial time as integers `[hour, minute]` (24-hour) on the left and a list of button states `[[hourPressed, minPressed], ...]` on the right which returns a list of the end result time as integers, again `[hour, minute]` (24-hour). **[Try it online!](https://tio.run/##y0rNyan8/9/vUeNOIHq4a8GhJfbajxp3cIVbH16ur2pkomNm8P///2hLHWPj2P/R0QY6hrE6KKShjgGKSCwA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##lVS9TsQwDN55iluYMKL5aUuFBG/AyhB1ZKnuBdiuPAITA0gMSCzMJw4hhqJ7kMuLhLRpr0nkNmkVOaljf7bjn@p@vX5Q6lbWO70O32/N@82ZrL9O7q7@Pi5OKYcsUfsffZaPn/unw@5Z73pV7bZ5WZ1fr@TmtZL1b7NttkoJITLgRQlCJEDKsj0QCpR1B0gMZ2C0ImCxCfBk5PvUgDEgMzIGraWIrsZnR0dc@RGfAyUYfu8462NzlTLIY3xKUD4eZw5p6r6RfZv2tzYyjobd4hwTIQVCMLsQiM7zn0F6aT@1TZc8zJB0ivuEq3ZKHFjuJzueThk5wpvfQBzBNFPnmfywgTO/rJYmxIPUVcXxDhj7phMs@laJTHcBXtOYAArg03kzItpiPldvGAfrF@3wbI2MdOgvRsIButbdydLh6GmXhVt/acXFV1VMzcUOnulRMee5/v4B "Jelly – Try It Online") ### How? ``` N⁹⁹Ạ¤?+⁸ - Link 1, nextState: list, currentState [cH, cM]; list, presses [pH, pM] ? - if: ¤ - ...condition: nilad followed by link(s) as a nilad: ⁹ - chain's right argument, presses Ạ - all truthy? (1 for [1,1] 0 otherwise) N - ...then: negate (the left argument, currentState, i.e. [-cH, -cM]) ⁹ - ...else: chain's right argument, presses ⁸ - chain's left argument, currentState + - add i.e.: if presses was [1,1] then [cH+-cH,cM+-cM]=[0,0] otherwise [cH+pH,cM+cM] W;ç/%24,60 24,60 - literal list of integers [24,60] % - modulo by (vectorises) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 75 bytes ``` .*,1:1 : \d+ $* O`\D1* , 1>`: +`1{24}:|:1{60} : (?<=^|:)1* $.& \b\d\b 0$& ``` [Try it online!](https://tio.run/##hVPLboMwELzvd9AoJSjatQ2UVR@XSj32B6yKRumhlx6i3JJ8O11bkGCwycGSdz2eGcbL4ef4@/fdPaw/2m6bF8QEDHa/gSyHz9a@Uw4FAL22DLBp6aTMhc9MpwovAly/Pb98nflRUNl2BXZn93YHmK26Dis2TYHCR4qVFmYE9Dvp@UoRG/TVaAFpplnX4Z23K0ruas95PfV3DauQTRS1c9GfV4x1ghuDOnBUc1mGOqXrDPcm@KA32YNSTFGVmDqg5vKp7wxr0bNLD1XAM0EBGtZ1Uj3mZOwfxUTcQSw5Sb/3P/hDeXOdwqeUAeUFzCxTN6vYuDlI5tcMbn02UpnZF5HQ1LGkRvsbh8jN4@2XGxS9HCHexhjcD1ItPf/i2b3BSzuguwMb0f4H "Retina – Try It Online") Link includes test cases. Explanation: ``` .*,1:1 : ``` Delete everything up to and including the last double button press, replacing it with an empty time (in case that's the last button press). ``` \d+ $* ``` Convert to unary. ``` O`\D1* ``` Sort the minutes to the end. ``` , ``` Add the hours together. ``` 1>`: ``` Add the minutes together, but keeping the hours separate. ``` +`1{24}:|:1{60} : ``` Reduce the hours and minute modulo 24 or 60 as appropriate. ``` (?<=^|:)1* $.& ``` Convert to decimal. ``` \b\d\b 0$& ``` Format to two digits. [Answer] # Python 3, ~~135~~ ~~117~~ 115 bytes -20 bytes thanks to Jonathan Frech ``` def a(m,f): for b,c in f: if b&c:m=[0,0] elif b:m[0]=-~m[0]*(m[0]<23) elif c:m[1]=-~m[1]*(m[1]<59) return m ``` [Try it online!](https://tio.run/##pVbNjpswEL77KVwOFaxINYPNn7XpsU/QG@WQTYkaKWGjkFTJpa@ejnFgISEOyXLAYr7PM2PPD7M57v68l@J0@l0s@Mxd@wtPMb543/I3f86XJV/QJ18u@NvXuVpPM/AhJ0Gx0iK1ziCfTv7p5cXV79dAeA1M/AwNjDWM@WuYErwtdvttyden@awqKj7ljuNApGTqZy74HL2cT75zkoTAMFCBIDn6HIwcBUkYnOU13@cdHAiXLEAloYMPrjVfMyUjrXiX39gx6w19AAoCbV@0fg/s79gXSoQMpQrwln1zbqnPRecW53u60EOIpPuKFMSPnQNsuMWfVGHEMFZheBmHPi9RYcwwNLxLu1Y7Fp5V3twrAAsChXjLvxHrIL@JM6aMsi1M@nG@XJ@/d2MnViB0fkJgOYdVn4kDZUbEQCoRD@Tls@s9Pzp1mSgZM10dQ/EYmwe385EiAYmuj148Bu5TqpDiRlUvBurks/kxbC9gFMVQWvpBr6@0fQQYpKaPPJ6fCEokej9c9RWjP63zit7yXl41fZLyB1FhPKKeLHJr3yR/xJg8761tH5W6Hwl84L4G/Lzu761/yPR/Knqgv362np6tk0fr6an/wIj@POrczX8CI5oEvlWb1XLnOr9Kx2PNhJAdGrGmOl49oRz0fFIz8g@ie6AxpCH7jjFzoNnDtsfNluXOPXQoR9LSUaQcL/d58Xe2cmuE1JHagV3Y22KgY8dmtZ/Pi0pb/bndF0zDGmkZetriNCFV@9WOSDP3RYvJpFcDm602eUuEPZFRci3h0ynv0WlWOyNfWsT4oZ8Pj3/MVlXRUedMmociZURnsnf6Dw) Takes the time as a list in the form `[hour, minute]`. [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` foldl(#) _#(1,1)=(0,0) (h,m)#(x,y)=(mod(h+x)24,mod(m+y)60) ``` [Try it online!](https://tio.run/##LcxBCsIwEIXhfU8xEBczdIRJ1eImJ1GR0BpTTNpgXbSXN0bo5uPxFr@38@sRQnbmmt0U@oCKqrtCzZoMCgtV6DmSwoXX8sSpR18v1Bz5P2O9UiuUox1GMJDew/iBHTjA5sCnM8GlNDRx6UlRNvXmLX87F@xzzvsupR8 "Haskell – Try It Online") Example usage: `foldl(#) (23,58) [(0,1),(1,0),(0,0),(0,1),(0,1)]`. [Answer] # JavaScript (ES6), 55 bytes ``` t=>a=>a.map(x=>x>2?t=[0,0]:t[x-1]++)&&[t[0]%60,t[1]%24] ``` Takes input in currying syntax, with the starting time in the array form `[min, hour]` and the steps as a Quaternary array. Output time is in the same format as the input time. ## Test Cases ``` let f= t=>a=>a.map(x=>x>2?t=[0,0]:t[x-1]++)&&[t[0]%60,t[1]%24] ;[[[49, 06], [1]], [[23, 12], [2]], [[23, 02], [2, 1]], [[40, 21], [1, 1, 1, 1]], [[10, 13], [1, 1, 1, 1, 2, 3, 1, 1]], [[33, 21], [2, 1, 2, 1]], [[21, 14], [1, 1, 1]], [[39, 02], [1, 0]], [[07, 16], [1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 1]], [[55, 17], [1, 2, 1]], [[55, 15], [2, 2, 2, 1, 1, 1, 2, 2, 1, 2, 2, 1, 2]], [[11, 22], [1, 2, 1, 1, 1, 1, 1, 2, 1, 1]], [[58, 03], [2, 0, 0, 1, 1, 2, 2, 1, 1, 2, 1]], [[02, 13], [1, 2, 1, 2, 1, 1, 2]], [[37, 04], [2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2]], [[01, 00], [1, 2, 2, 1, 1, 1, 2, 1, 1, 1]], [[58, 02], [2, 2, 1]], [[43, 01], [1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1]], [[54, 07], [2, 1, 2, 2, 3]], [[33, 09], [1, 1, 1, 2, 1, 1]], [[01, 09], [1, 1]], [[04, 19], [1, 2, 1, 2]], [[17, 11], [1, 2, 1, 1, 2, 1, 1, 3, 1, 1]], [[32, 19], [1, 2, 1, 2, 2, 2]], [[31, 17], [1, 1, 1, 2, 1, 2, 1, 0, 3, 1]], [[46, 06], [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1]]] .forEach(([time,steps])=>{ let res = f([...time])(steps) console.log(JSON.stringify(time)+" -> "+JSON.stringify(res)) }) ``` ``` .as-console-wrapper{max-height:100%!important} ``` [Answer] # [Perl 6](https://perl6.org), 40 bytes ``` {.reduce({(@^a Z+@^b)X*[[email protected]](/cdn-cgi/l/email-protection)})Z%24,60} ``` [Try it online!](https://tio.run/##pVVLT8JAED7bXzFoye5qbWa7S1uGiPViYjTxajiQgJQEIz5ADwb57bitBQQqbfU0053H9@08ti/x5NFfjD/AHsLZYuZO4sH7fcxnPOr2oHMSdfvi7rgW9d3x6GkuOnVPOz7OF0eg0TJR0RucAbc4Q0WNkDnAuXQAhVFwV8qfcuknC@zpt1EYBoSKCcegSUXopWi53kVZk2zSJ/S/s6EmFWxzl/@RRWxWLDAkHWQskFDm3qmI1V57imLKFWYo3nafduusqdHMvCVptcGpFGbViixRvQw1oIbO7cc2Z7mKNsXDLLpJKp/zXu7pTCCpcJVlqxtrps31HBpVF89hEuXJ1bxJSTLYG1Xi/JdOY7IYS26q3I5syJSrIqWzLAEpWamaOZxxh/OSq8yq7ZP296L8de7KVrjsjlXdxaqdLcKrdP90pkOS6dyJljV8niQv9mkbuD11IOo7YMcCZtZB8gOYmKfcHnJjcqcvj6M3zsjEwWfUF6Lddodjc1JHb8CE@/A8ekrNLetg2vuAQxNsxzBLksSviXp@Duz2mkGtBuzy4uqGwfywZc0XXw "Perl 6 – Try It Online") Takes a list containing the start time followed by the button presses. Returns the end time. Times and buttons are `(hour, minute)` pairs. 24-hour time. [Answer] # [Perl 5](https://www.perl.org/), 70 bytes 69 bytes of code + 1 for `-n` flag ``` s/.*d/0:0/;/(.*):(\d+)/;printf"%02d:%02d",($1+y/c//)%24,($2+y/b//)%60 ``` [Try it online!](https://tio.run/##FcdbCoMwEEDRvYhC4iMzCR0/kjV0B/7koSCUGNSfbr7TCJcLp6znh5gvUH0CtAgOhOqlFUsaJLhy7vnemg5Nss@aUbR6@EIEkJ15VZmq8GhGZk2WaIwxeu/rauF3lHs/8sXTmxRq5Cn/AQ "Perl 5 – Try It Online") **Input Format** `hh:mm,abcdabcdabcdaddccbbaa` *where:* ``` hh=start hour mm=start minute a = (0, 0) = no buttons pressed b = (0, 1) = minute button pressed c = (1, 0) = hour button pressed d = (1, 1) = both buttons pressed ``` Spaces or other separators between the presses are insignificant. **Explanation** ``` s/.*d/0:0/; # If both buttons were ever pressed, previous presses # don't matter. Get rid of them and set start time to midnight. /(.*):(\d+)/; # Extract start hour and minute printf"%02d:%02d", # Output numbers with leading 0 ($1+y/c//)%24, # Take starting hour, add number of presses, remainder 24 ($2+y/b//)%60 # Take starting minute, add number of presses, remainder 24 ``` [Answer] # [Swift](https://developer.apple.com/documentation/swift), ~~106~~ 96 bytes -10, thanks to Xcoder ``` func x(m:(Int,Int),n:[(Int,Int)]){let i=n.reduce(m){($0.0+$1.0,$0.1+$1.1)};print(i.0%24,i.1%60)} ``` [Try it on ideone!](https://ideone.com/I3OoRy) function will take initial value and array of tuples and returns final time. [Answer] # Terrapin Logo, 304 bytes Not optimized; lots of spaces. ``` MAKE "M :B MAKE "H :A LABEL "L IF EMPTY? :I OP LIST :H :M MAKE "C FIRST :I IF AND ((ITEM 2 :C)=1) ((ITEM 1 :C) = 0) MAKE "M :M+1 IF :M=60 MAKE "M 0 IF AND ((ITEM 1 :C) = 1) ((ITEM 2 :C)=1 MAKE "M 0 MAKE "H 0 IF AND ((ITEM 1 :C)-1) ((ITEM 2 :C) = 0) MAKE "H :H + 1 IF :H = 23 MAKE "H 0 MAKE "I BF :I GO "L ``` Takes a list as its first input and the starting hour+minute (seperate inputs) as second and third, respectively. I can't copy+paste from Terrapin Logo as it's a trial version so that's that :( [Answer] # Mathematica, 54 bytes ``` Switch[#2,a={0,0},#,a+1,a,_,Mod[+##,{24,60}]]&~Fold~#& ``` Anonymous function. Takes a list of 2-tuples as input and returns a 2-tuple as output. [Answer] # [R](https://www.r-project.org/), 61 bytes ``` function(I,B){for(b in B)I=I+"if"(sum(b)>1,-I,b) I%%c(24,60)} ``` Takes `I` as a length-2 vector `c(H,M)` and `B` as a list of length-2 vectors for the buttons, `c(H,M)`. Iterates through `B`, setting `I` to `c(0,0)` if the sum is `2`. Then it mods down at the end. There's also a function in the header to translate the button presses into the right R format if you'd like to test them all; it takes the array `[(H,M),...]` as a string. [Try it online!](https://tio.run/##lZAxC8IwEIV3f0U4EO7whESlLurgllXc1MEUI4XaSpO6iL@9pqBWECVmyOUdefe9pGpM7X1ZuHW5ErOhsHWR@qws0NHhss/xvK/cAf386GqDsN3ugIGAn3ITZJ45j10rHCENm6N29WyY2rymal7S1ZYVGpEVYkl6rgeQWUBXn9DQQvFQs6Ge7vdTHE04kXRrLKaopjxWxF1YhA1KFqEnPqpiIX9p@dDq3beDNm1AJTxJYkk/CFH1m091CWWMP/ZeLPdf3l/vb3@6uQM "R – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 bytes ``` (n,l)=>{for(int i=0,x;i<n.Length;){x=n[i++];if(x>1)l[0]=l[1]=0;else{l[x]=++l[x]%(24+36*x);}}} ``` [Try it online!](https://tio.run/##VY5BS8QwEIXv/RVhYSExcWl3xYPZFMTrehAPHkoOpWa7A3ECTVxrQn57bSseZIZ5j5kP3nT@tnODmT49YE9ev30wH7LobOs9eUmFD22AjlwdvJPnFpCyVDx2ARweAUOjxTrrXk0UhWWqTmc30HlJQJVilHDE3clgHy6SpVFhA5xrCWc61hWzTamVbSqtSmmsN8k2o1acL7Kl@zt@uL8Zmcw5T7IgZO5rO5Co0HyRNTdV4rdKsV80yz/mH3QQVbmeehpFjGyxTw69s2b3NkAwJ0BDY5zf4ZuHDZ9dpVcqF3n6AQ "C# (.NET Core) – Try It Online") Takes input as in trinary, with 0==(1,0),1==(0,1),2==(1,1), and the time in an array with index 0 being hours and 1 being minutes. Modifies the time array in place. [Answer] # Pyth, 22 bytes ``` %Vu?.AH,00+VGHEQ,24 60 ``` [Try it here.](http://pyth.herokuapp.com/?code=%25Vu%3F.AH%2C00%2BVGHEQ%2C24+60&input=%5B13%2C+10%5D%0A%5B%5B0%2C+1%5D%2C+%5B0%2C+1%5D%2C+%5B0%2C+1%5D%2C+%5B0%2C+1%5D%2C+%5B1%2C+0%5D%2C+%5B1%2C+1%5D%2C+%5B0%2C+1%5D%2C+%5B0%2C+1%5D%5D&debug=0) [Answer] # [Scala](http://www.scala-lang.org/), 116 bytes So I just take the start time as two first parameters of my func (`h` and `m`), and I take the input sequence as an Array[Tuple2]. ``` var x=h var y=m for(u<-a)u match{case (0,1)=>y=(y+1)%60 case (1,0)=>x=(x+1)%24 case (1,1)=>{x=0;y=0} case _=>} (x,y) ``` I wonder ... should I count the func declaration (`def time(h:Int,m:Int,a:Array[Tuple2[Int,Int]]):Tuple2[Int,Int]={` plus the ending `}`) in byte count? [Try it online!](https://tio.run/##jVDRasMgFH33K3wZKLsDTUJhWS30cQ9721spw6WWpDRpMGYoId@exYSOYMs2QS@cc889x9tk8iyHy@dJZQa/yaLCyhpVHRq8resOoYM6YlOUiuTpa2WgnF6ZbrWWbvfe1mcV7Tw03v2epgEiuuFLamxFjnx1okTHiybt@knSFpfSZHmXyUZhwoBTsXGCuEdOH1YMzTAHNsJWEOvhKPmBfXdnBXtxgvUz@iE2PSIWHB16VOuiMmRKvoLkGabAZLIZz5LmEUTxlfd@Ab@kGWBOwfvj2z4OCQsb79YwQAz8f8Kr81z/HDwmihc/m4XhoLuJEhi1vyW62VG8WHEwGPXDNw "Scala – Try It Online") ]
[Question] [ Here is the sequence I'm talking about: ``` {1, 4, 5, 9, 10, 11, 16, 17, 18, 19, 25, 26, 27...} ``` Starting from 1, keep 1, drop the next 2, keep the next 2, drop 3, keep 3 and so on. Yes, it's on [OEIS (A064801)](https://oeis.org/A064801), too! **The Challenge** Given an integer `n>0`, find the nth term of the above sequence **Test Cases** ``` Input -> Output 1->1 22->49 333->683 4444->8908 12345->24747 ``` This is code golf so the shortest answer in bytes wins! Good luck! [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~45~~ 44 bytes ``` n->{int i=0;for(;++i<n;n-=i);return~-n+i*i;} ``` [Try it online!](https://tio.run/##ZU@xTsMwEJ3jr7jRJo1VWN1kAiQGpo6IwaROemlytmynalWFXw@GBpBgunfv3r131@mjLqwz1O0OMw7O@ghd4uQYsZfNSHVES/JxAYr904TojR7kE8XtF1KMufGtxxrqXocAzxqJXVi2kCHqmMrR4g6GNOJpC6l9eQXt2yBYlqTZj5n0mlrDb1dwtxaysf5B13uOUFSwPYdoBmnHKF1yiD3xgzHu3lvHUQihWDaxv7FJB7@q1JyWxO8HNynatMavYAEVNFACy2YqqsvnBpZrlQ7hKs9xQ4qKEoXyJo6e3gvK8QbVNKfw7MpBI7Vz/ZmfrhdN8wc "Java (OpenJDK 8) – Try It Online") *-1 byte thanks to @Nevay* After staring at this for a while, I noticed a pattern. Every time we drop `n` numbers, the next number in the sequence is a perfect square. Seeing this, I mentally broke the sequence into convenient chunks: `[[1],[4,5],[9,10,11],...]` Basically, the `i`th chunk starts with `i*i`, and iterates upwards for `i` elements. To find the `n`th number in this sequence, we want to find first which chunk the number is in, and then which position in the chunk it occupies. We subtract our increment number `i` from `n` until `n` is less than `i` (which gives us our chunk), and then simply add `n-1` to `i*i` to get the correct `position` in the chunk. Example: ``` n = 8 n > 1? Yes, n = n - 1 = 7 n > 2? Yes, n = n - 2 = 5 n > 3? Yes, n = n - 3 = 2 n > 4? No, result is 4 * 4 + 2 - 1 = 17 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~47~~ 46 bytes 1 byte thanks to Mr. Xcoder. ``` def f(n):a=round((2*n)**.5);return~-n+a*-~a//2 ``` [Try it online!](https://tio.run/##TcoxDoMwDIXhnVN0tIMoih2jQtXDRCJRWRwUhYGFq6ddkPKm/5PefpZvUq51DfERQXHxn5wOXQHIKBrzFHznUI6s16C9N8Plx5HqnjctEMEidncTNWDmRu6/hpbYSXu2zspMk7C8ZsT6Aw "Python 3 – Try It Online") VERY fast for higher numbers [Answer] ## Haskell, ~~48~~ ~~43~~ 41 bytes ``` n#l=[l..l+n]++(n+1)#(l+2*n+3) ((0:0#1)!!) ``` 4 extra bytes for 1-based indexing instead of 0-based. An unnecessary restriction, IMHO. [Try it online!](https://tio.run/##y0gszk7Nyfn/P085xzY6R08vRzsvVltbI0/bUFNZI0fbSCtP21iTK81WQ8PAykDZUFNRUfN/bmJmnoKtQko@l4JCQVFmXomCikKagiEKzwQIUKWNjE1M/wMA "Haskell – Try It Online") ``` n#l -- n is one less than the number of element to keep/drop and -- l the next number where the keep starts [l..l+n] -- keep (n+1) numbers starting at l ++ -- and append a recursive call (n+1)# -- where n is incremented by 1 and (l+2*n+3) -- l skips the elements to keep & drop 0#1 -- start with n=1 and l=0 and 0: -- prepend a dummy value to shift from 0 to 1-based index !! -- pick the i-th element from the list ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes An anonymous function. Use as `((!!)$0:do n<-[1..];[n^2..n^2+n-1]) 1` ``` (!!)$0:do n<-[1..];[n^2..n^2+n-1] ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8vFlZuYmWebmVeSWpSYXKJSmpeTmZdarJebWKBRnJFfrpemV5SamKKpBxbm4kqzjfmvoaioqWJglZKvkGejG22opxdrHZ0XZ6SnByS083QNY///N@QyMuIyNjbmMgECLkMjYxNTLgA "Haskell – Try It Online") * Constructs the sequence as an infinite list, then indexes into it with `!!`. The `0:` is a dummy element to adjust from 0- to 1-based indexing. * The range `[n^2..n^2+n-1]` constructs a subsequence without gaps, starting with the square of `n` and containing `n` numbers. * The `do` notation concatenates the constructed ranges for all `n>=1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Ḷ+²µ€Ẏ⁸ị ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//4bi2K8KywrXigqzhuo7igbjhu4v/w4fFkuG5mP//Nw "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` f=lambda x,y=0,z=0:y<x and f(x,y+z,z+1)or~-y+x ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoUKn0tZAp8rWwKrSpkIhMS9FIU0DKKZdpVOlbaiZX1SnW6ld8b@gKDOvRCNNw1BTkwvGNjJC4hgbGyPxTIAAiWtoZGxiqqn5HwA "Python 3 – Try It Online") [Answer] # TeX, 166 bytes ``` \newcommand{\f}[1]{\count0=0\count1=0\loop\advance\count0 by\the\count1\advance\count1 by1\ifnum\count0<#1\repeat\advance\count0 by#1\advance\count0 by-1 \the\count0} ``` ## Usage ``` \documentclass[12pt,a4paper]{article} \begin{document} \newcommand{\f}[1]{\count0=0\count1=0\loop\advance\count0 by\the\count1\advance\count1 by1\ifnum\count0<#1\repeat\advance\count0 by#1\advance\count0 by-1 \the\count0} \f{1} \f{22} \f{333} \f{4444} \f{12345} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/vyXG0.png)](https://i.stack.imgur.com/vyXG0.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` LεÝÁćn+}˜¹<è ``` [Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//0zOtcOdw4HEh24rfcucwrk8w6j//zc "05AB1E – Try It Online") [Answer] # [Perl 6](https://perl6.org), 43 bytes ``` {(1..*).rotor({++$=>++$+1}...*).flat[$_-1]} ``` [Test it](https://tio.run/##PY7BasMwDIbvegpRQnHm2J1jL00JMb3u3ttWRpe4EEjjkLhlI@TJetuLpU5XqoPQ///6kFrT1cl07g1eEl5kcPrFZWFLg/k0EMH5S8g762xHBkqDXPtGxcjv/rE@uI/gi4n9OHls60zvMMe6akxPwr8rL@zpm6w@S7qa1XvjMpgP7fxeBm19aJDeoQyOtnvwTCMJqqY9uygwP60pnClDHACx6nF@7JGGET7zCBf/5kw/3QWMk2BaIEIcM602fpBSMp2kEpQvptPNawoiluqN6Vit1foG "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( 1 .. * ) # range starting from 1 .rotor( # break it into chunks { ++$ => ++$ + 1} ... * # infinite Seq of increasing pairs # 1 => 1 + 1 ==> 1 => 2 ( grab 1 skip 2 ) # 2 => 2 + 1 ==> 2 => 3 # 3 => 3 + 1 ==> 3 => 4 # ... => ... + 1 ).flat\ # reduce the sequence of lists to a flat sequence [ $_ - 1 ] # index into the sequence # (adjusting to 0-based index) } ``` `(1..*).rotor({++$=>++$+1}...*)` produces: ``` ( (1,), (4, 5), (9, 10, 11), (16, 17, 18, 19), (25, 26, 27, 28, 29), ... ).Seq ``` [Answer] ## Mathematica, 37 bytes ``` Flatten[Range@#+#^2-1&~Array~#][[#]]& ``` ## Explanation ``` Range@#+#^2-1& ``` `Function` which takes a positive integer `#` and returns the run of `#` consecutive numbers in the sequence. ``` ...~Array~# ``` Produces the list of all such runs up to the input `#` ``` Flatten[...][[#]] ``` `Flattens` the resulting list and returns the `#`th element. [Answer] # Javascript, ~~43~~ 38 bytes ``` n=>eval("for(r=1;n>r;)n-=r++;r*r+n-1") ``` [Try it online!](https://tio.run/##ZcpBCsMgFATQfU4RstKKTdV0Zc1dJNVikf/DT8n1rS6Dsxl4M19/@mOjtP8k4DuU6Aq4NZw@sykiMXLKwkqWg3QkhKUbCZBq4mWe255SPYwpvfSjlRB83BAOzOGe8cNiPXBuh@GKqtmVtO7NGNPjUtOr0mZ5Vi5/ "JavaScript (Node.js) – Try It Online") I use the fact, that for each [triangular number](https://en.wikipedia.org/wiki/Triangular_number) plus one, the result is a square number. As an example: triangular numbers are 0, 1, 3, 6, 10... so for 1, 2, 4, 7, 11... we observe 1, 4, 9, 16, 25... in our sequence. If the index is somewhere between these known numbers, the elements of our sequence only advance by one. For instance, to calculate the result for 10, we take 7 (as a triangular number plus one), take the result (16) and add 10-7=3. Thus, 16+3=19. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` v₍ʁ²ṠfJi ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24oKNyoHCsuG5oGZKaSIsIiIsIjIyIl0=) Would beat Jelly if zero-indexing were allowed (remove `J`). ``` v₍ʁ²ṠfJi v # For each in a range [1, n]: ₍ # Apply both of the next two elements and wrap in a list: ʁ # Range [0, n), and: ² # Square n Ṡ # Sum each (vectorizing) # For an input of 4, this will give [[1], [4, 5], [9, 10, 11], [16, 17, 18, 19]] # Basically, for each x in [1, n], add x^2 to each in [0, x) f # Flatten J # Prepend the input to the beginning (doesn't matter what we prepend) i # Index the input into this ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 27 bytes ``` #R(2B)^.5)|1:b~-B+A*-b~A//2 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/XzlIw8hJM07PVLPG0CqpTtdJ21FLN6nOUV/f6P9/EwA "cQuents – Try It Online") Currently a port of [Leaky's Python answer](https://codegolf.stackexchange.com/a/139906/65836), I think there's a better way though. [Answer] # [Swift 3](https://www.swift.org), 72 bytes Port of my [Python solution](https://codegolf.stackexchange.com/a/139917/59487). ``` func f(_ x:Int,_ y:Int=0,_ z:Int=0)->Int{return y<x ?f(x,y+z,z+1):y+x-1} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/599b038cbb3c087fee1d8915)** [Answer] # [C# (Mono)](http://www.mono-project.com/), 164 bytes ``` using System.Linq;n=>{var a=new int[1]{1}.ToList();for(int i=1,m;a.Count<n;a.AddRange(new int[++i*2].Select((_,d)=>m+d+1).Skip(i).Take(i)))m=a.Max();return a[n-1];} ``` [Try it online!](https://tio.run/##TVBLa8MwDL77V@hoL67BSXdKXRiFnVoYa2GHEoZJ1M60kbfY6TZCfnvmDsqmgx6fXp9Uh1nryU99cHSE7XeI2Jbsf6TWjj5KxuqzDQGe2MBCtNHVcPGugY11xEUCH3uqF46ihKSWcAAzkVkOF9uBNYSfV3ivq0GPaufXLkQuyoPveILBGS3b0qqV7ykuKHkPTfNs6Yj81pll7i6v1BbPWEfOX2UjzLLNmkwLtT25d@6E2tkTJitEa6za2K@0ocPYdwR2TzNdleOU7rhOqyBiiCsbMICBQcs8l0VRyHkSqfNifj@WLLFDW7/BL8VbfSLz1yvYylPwZ1QvnYuYHoX8wG9pIdK2kY3TDw "C# (Mono) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 33 + 1 (-p) = 34 bytes ``` $\+=$.--?1:2+($.=++$s)while$_--}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWRU9X197QykhbQ0XPVltbpVizPCMzJ1UlXle3tvr/f0MjYxPTf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` :"@U@:q+]vG) ``` [Try it online!](https://tio.run/##y00syfn/30rJIdTBqlA7tsxd8/9/EyAAAA "MATL – Try It Online") ### Explanation ``` : % Push range [1 2 ... n], where n is implicit input " % For each k in that range @U % Push k^2 @: % Push range [1 2 ... k] q % Subtract 1: gives [0 1 ... k-1] + % Add: gives [k^2 k^2+1 ... k^2+k-1] ] % End v % Concatenate all numbers into a column vector G) % Get n-th entry. Implicitly display ``` [Answer] # [Tampio](https://github.com/fergusq/tampio), ~~310~~ 308 bytes ``` n:n uni on n unena 1:lle a unena k:lle on a vuona k:lla vähennettynä a:sta ja k a vuona nollalla ja k on a a vuona k:lla vähennettynä nollasta ja k on a a vuona b:n seuraajalla ja k on yhteenlaskun kutsuttuna k:n kerrottuna 2:lla arvolla ja k:n vähennettynä a:sta arvolla unena k:n seuraajalle seuraaja ``` Usage: `4:n uni` evaluates to `9`. Explanation: ``` n:n uni on n unena 1:lle uni(n) = n `uni` 1 a unena k:lle on a vuona k:lla vähennettynä a:sta ja k a `uni` k = (a `vuo` (k `vähennetty` a) ) k a vuona nollalla ja k on a (a `vuo` 0 ) k = a a vuona k:lla vähennettynä nollasta ja k on a (a `vuo` (k `vähennetty` 0) ) k = a a vuona b:n seuraajalla ja k on (a `vuo` (b + 1) ) k = yhteenlaskun kutsuttuna k:n kerrottuna 2:lla arvolla (yhteenlasku (k * 2 ) ja k:n vähennettynä a:sta arvolla unena k:n seuraajalle seuraaja (( k `vähennetty` a ) `uni` (k + 1) ) ) + 1 ``` From standard library: ``` a `vähennetty` b = b - a yhteenlasku a b = a + b ``` [Answer] # JavaScript (ES6), 33 bytes Recursive solution inspired by [Xanderhall's observations](https://codegolf.stackexchange.com/a/139941/58974). ``` f=(n,x=1)=>n<x?n+x*x-1:f(n-x,++x) ``` --- ## Try it ``` o.innerText=( f=(n,x=1)=>n<x?n+x*x-1:f(n-x,++x) )(i.value=12345);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` def f(n): a=i=0 while a<n:a+=i;i+=1 return~-a+n ``` [Try it online!](https://tio.run/##TcrBCkIhEIXhvU8xSwcJGkeje8uHEVLuQEwXMaJNr25tAs/q/@Ds7749lMe4lQrVKq4GcpJ0NPDa5F4gX3XNLslFXCIDrfRn088hOx17E@22WkI0//Z@AjNPCr9NJM8hzmcKFBd/ihzPC@L4Ag "Python 3 – Try It Online") [Answer] # Mathematica, 82 bytes ``` Complement[Range[3#],Array[#+⌊((r=Sqrt[1+8#])-1)/2⌋⌊(r+1)/2⌋/2&,3#]][[#]]& ``` [Answer] # [Python](https://docs.python.org/2/), 40 bytes ``` lambda n:(round((2*n)**.5)+.5)**2//2+n-1 ``` [Try it online!](https://tio.run/##TcrBCsIwEATQu1@R426q1t1NxBb8Ey@RGg3YTQn14NfHXoQMDMyDWb7rK6vUeL3Vd5jvUzA6QskfnQDYKlp79NhttZb7njs9UI25mGSSmhL0@QDa0wnHpSRdIUJC3P03cwMRaeS2NCQW59szOfIDn734y4BYfw "Python 3 – Try It Online") Optimizing [Leaky Nun's expression](https://codegolf.stackexchange.com/a/139906/20260). --- # [Python](https://docs.python.org/2/), 41 bytes ``` f=lambda n,k=1:n*(n<=k)or-~f(n-k,k+1)+2*k ``` [Try it online!](https://tio.run/##TccxDoMwDEDRvafIaEOQaocuqDlMUJsSuXVQxNKFqwcWpPzpv/W/LVm51ui/4Te/glErnibtQJ9eMJdhj6CDWOkJe@6kxlxMMklNCfp5A1m647SWpBtESIi365kbOOcajWcNid34QKwH "Python 2 – Try It Online") Recursive expression. [Answer] # Javascript (ES6) 100 98 Bytes ``` var k=n=>{var s=[],i=1,c=1,j;while(s.length<n){for(j=i;j<i+c;j++){s.push(j)}i+=c*2+1;c++}return s} ``` Kind of did this one fast, so I bet there is a lot of room for improvement, just basic loops and counters. [Answer] # [Retina](https://github.com/m-ender/retina), 27 bytes ``` .+ $* ((^1|1\2)+)1 $1$2$& 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS0MjzrDGMMZIU1vTkEvFUMVIRY3L8P9/Qy4jIy5jY2MuEyDgMjQyNjEFAA "Retina – Try It Online") Port of @LeakyNun's Python answer. The first and last stages are just boring decimal ⇔ unary conversion. The second stage works like this: `((^1|1\2)+)` is a triangular number matcher; `$1` is the matched triangular number while `$2` is its index. The trailing `1` means it matches the largest triangular number strictly less than the input, thus resulting in exactly one fewer iteration than the Python loop, meaning that `$1` is equivalent to `a-i` and `$2` to `i-1` and their sum is `a-1` or `~-a` as required. (`$&` just prevents the match from being deleted from the result.) Note that for an input of `1` no matching happens and the output is simply the same as the input. If you were perverse you could use `^((^1|1\2)*)1` to match in that case too. [Answer] # [C (gcc)](https://gcc.gnu.org/), 38 bytes Using @Xanderhall's algorithm here ``` i;f(n){for(i=0;++i<n;n-=i);n=n-1+i*i;} ``` [Try it online!](https://tio.run/##XY5BCoMwEEX3niIUCkntgCZpVVKz76oXcFMsKbPoVCSuxLOnycrqXw3vP4bfw7vvQ0DjOInZfUeObWHyHG9kCFoUhlqCMscTmiV8nkhcZHPGYoYRyTt@uNMweQaWPSafLsY6OgizcUqwZeePr9icHS/FrpYSrG5WQcq9oZQCe63V6kSyl3QM2Lop6lVLLHpsO0cqfQErdaWrv1mJpp9L@AE "C (gcc) – Try It Online") [Answer] # PHP, ~~48 42~~ 37+1 bytes ported from [Leaky Nun´s answer](https://codegolf.stackexchange.com/a/139916/55735) ``` while($argn>$a+=$i++);echo$a+~-$argn; ``` Run as pipe with `-F` or [try it online](http://sandbox.onlinephpfunctions.com/code/d22b7f8877f1fc3a09a84ee95093858b3536ee1a). **direct approach, 42+1 bytes** (ported from [Leaky Nun´s other answer](https://codegolf.stackexchange.com/a/139906/55735)) ``` <?=($a=(2*$argn)**.5+.5|0)*-~$a/2+~-$argn; ``` Run as pipe with `-nR` or uncomment in above TiO. **older iterative solution, 48+1 bytes** ``` for(;$argn--;$n++)$c++>$z&&$n+=++$z+$c=1;echo$n; ``` [Answer] # TI-Basic, ~~41~~ 22 bytes ``` Input N int(.5+√(2N N-1+.5Ans(Ans+1 ``` Port of [Leaky Nun's Python 3 answer](https://codegolf.stackexchange.com/a/139906/11261). **I was quite happy with my previous 41-byte solution so here it is:** ``` Input N For I,1,N For J,1,I(N>0 DS<(N,0 Ans+1 Ans+1 End End Ans-1 ``` Needs a fresh calculator, or at least `Ans` initialized to `0` [![demo](https://i.stack.imgur.com/pfo8om.jpg)](https://i.stack.imgur.com/pfo8om.jpg) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~37~~ 36 bytes -1 byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) Port of [Leaky Nun's Python 3 answer](https://codegolf.stackexchange.com/a/139906/11261). ``` ->n{~-n-(a=((2*n)**0.5).round)*~a/2} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3VXTt8qrrdPN0NRJtNTSMtPI0tbQM9Ew19YryS_NSNLXqEvWNaqFq7QsU3KINY7lAlJERhDY2NoYwTIAAwjI0MjYxhcoamhiaWhqZmRqbWljGQoxZsABCAwA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 0-indexed ``` g°Uô²cÈóY ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z7BV9LJjyPNZ&input=OA) ``` g°Uô²cÈóY :Implicit input of integer U g :Index into °U : Prefix increment U ô : Range [0,U] ² : Square each cÈ : Flat map each X at 0-based index Y óY : Range [X,X+Y) ``` ]
[Question] [ Given a string of ASCII letters (upper and/or lower case), output the raw MathJax required to display that string bifurcating at each character, into superscripts and subscripts. For example, the inputs `cat` and `horse` would result in outputs which MathJax renders as the following, respectively: [![image of cat bifurcating](https://i.stack.imgur.com/oo1cl.png "bifurCat")](https://i.stack.imgur.com/oo1cl.png "bifurCat") [![image of horse bifurcating](https://i.stack.imgur.com/73LLx.png)](https://i.stack.imgur.com/73LLx.png) Note that only one input is required to be taken - these two are listed side by side simply to save vertical space. # Markup meaning * `_` indicates a subscript. * `^` indicates a superscript. * Braces are required around superscripted or subscripted substrings that contain further superscripting or subscripting in order to prevent them all being at the same level. # Test cases Test cases are in the format `input : output`. The first test case shows the empty string as input should result in the empty string as output. ``` "" : "" "a" : "a" "me" : "m_e^e" "cat" : "c_{a_t^t}^{a_t^t}" "frog" : "f_{r_{o_g^g}^{o_g^g}}^{r_{o_g^g}^{o_g^g}}" "horse" : "h_{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}^{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}" "bifurcate" : "b_{i_{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}^{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}}^{i_{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}^{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}}" ``` You can see how these are rendered by pasting the output into [mathurl.com](http://mathurl.com/). # No redundant braces MathJax will happily render markup that has redundant braces. For example, the following will all look identical when rendered: `a`, `{a}`, `{}{a}`, `{{{{a}}}}`. However, valid output for this challenge has no redundant braces. Note in particular that single characters in the output are not surrounded by braces. # Order The order of subscript and superscript is unimportant. The following are equivalent and will be indistinguishable when rendered (and are all equally valid outputs): ``` c_{a_t^t}^{a_t^t} c_{a^t_t}^{a_t^t} c_{a_t^t}^{a^t_t} c_{a^t_t}^{a^t_t} c^{a_t^t}_{a_t^t} c^{a^t_t}_{a_t^t} c^{a_t^t}_{a^t_t} c^{a^t_t}_{a^t_t} ``` # Scoring For each language, the winner is the shortest code in bytes. Too many notifications? Type `</sub>` to unsubscript [Answer] # Python, ~~95~~ ~~90~~ ~~86~~ ~~92~~ 82 bytes *10 bytes saved thanks to @ConnerJohnston* ``` f=lambda s:s and s[0]+(s[1:]and'_{0}^{0}'.format(s[2:]and'{'+f(s[1:])+'}'or s[1])) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRodiqWCExL0WhONogVlujONrQKhbIVY@vNqiNA2J1vbT8otzEEqCMEUSmWl07DaJOU1u9Vj2/CKjVMFZT839BUWZeiUaahrq6piYXnJOIyktC4WbkFxWnAkX@AwA) [Answer] # Mathematica, ~~72~~ ~~84~~ ~~77~~ 76 bytes ``` a_±b__:={"{",a,"_",±b,"^",±b,"}"};±(a_:""):={"",a,""};""<>Most@Rest@±##&@@#& ``` Uses CP-1252 (Windows) encoding. Takes a list of characters as input. ## Explanation ``` a_±b__:= ``` Define the function `±`, with 2 or more arguments. Label the first argument `a`, and second and on `b`. ``` {"{",a,"_",±b,"^",±b,"}"} ``` Create a `List` equivalent to `"{a_±b^±b}"` (`±b` is evaluated again, recursively). ``` ±(a_:""):= ... ``` Define the function `±`, with 1 or 0 arguments. Label the first argument`a`, if it exists, and assign `""` to `a` otherwise. ``` {"",a,""} ``` Create a `List` equivalent to `"a"`, padded with empty `String`s. ``` ""<>Most@Rest@±##&@@#& ``` A pure function that applies `±` to the input, drops first and last element, and converts `List` to `String`. [Answer] ## CJam (35 bytes) ``` MqW%{"^{ }_{ }"{AW$,)3e<#<},S/@*+}/ ``` This is a full program. [Online demo](http://cjam.aditsu.net/#code=MqW%25%7B%22%5E%7B%20%7D_%7B%20%7D%22%7BAW%24%2C)3e%3C%23%3C%7D%2CS%2F%40*%2B%7D%2F&input=abcde). 3 bytes work around a bug in the interpreter (see below). ### Dissection ``` M e# Start building from the empty string qW%{ e# For each character in the reversed input "^{ }_{ }" e# Take a template { e# If the accumulator is of length n, remove all characters whose A e# codepoints are greater than pow(10, W$,)3e< e# min(n+1, 3)) #< e# When the accumulator is the empty string, that's all of them. }, e# When the accumulator is one character, that's {} e# When the accumulator is any longer, it's none of them. S/@* e# Substitute the accumulator for the spaces. + e# Append to the new character. }/ ``` Note that the `min(n+1, 3)` is to work around a bug in the interpreter: there must be some pattern in the powers of 10 that `'}` is smaller than, but [it's not obvious](http://cjam.aditsu.net/#code='%7DA50%2Cf%23f%3C). [Answer] ## JavaScript (ES6), ~~57~~ 55 bytes ``` f=([c,...s])=>s+s?c+`_${p=s[1]?`{${f(s)}}`:s}^`+p:c||'' ``` ~~Θ(len(s)) complexity!~~ According to @PeterTaylor, this is actually Θ(2^len(s)), which is still the best possible... [Answer] # [Haskell](https://www.haskell.org/), 71 bytes ``` f[x,y]=x:'_':y:'^':y:[] f(x:y@(_:_))=x:"_{"++f y++"}^{"++f y++"}" f x=x ``` [Try it online!](https://tio.run/##7VVdaoQwEH73FCEsmKC9QMDSC/QEVkPWJirVVUykkdCz24lmoXRf9qWUUl8yM9988xcGphH6TXbduqrcpkuRWRbzmC0sLv2bF5Eili1PhDNOKXgxdzhJFFqSBH@UX3QcKWQzu0or@rGTOssJxinCmKYRIlh4XQSjl97quSxlQCphPFRxJ7gpDWTeZXCraai9X3E3cTfwuqyBsktQbrEQ1wyT3mo1nuF52hcF3i732G/YluVebih0btU8wRBbsTN3LXfQ67yl2YZyJgSaa7JbDLT7uXs7P5Qb9L/bOxjH3//W34N17P6x@/9z9zEtol60l6wX4zMiL0SnSFL08IjGqb2Yk4ZDyRDcTKKb4f0ks0whTQFERNpRVka@MvBKj4jKzKLzJgkkiim6Xtf1Ew "Haskell – Try It Online") If we just had to output valid code the following would work for 44 bytes: ``` f[a]=[a] f(a:b)=a:"_{"++f b++"}^{"++f b++"}" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/Py06MdYWiLnSNBKtkjRtE62U4quVtLXTFJK0tZVq45DYSv9zEzPzbAuKMvNKVNKUkhNLlP4DAA "Haskell – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 21 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ±K;{╔+;lH?"{ŗ}”}1 ^Ο+ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUIxSyUzQiU3QiV1MjU1NCslM0JsSCUzRiUyMiU3QiV1MDE1NyU3RCV1MjAxRCU3RDElMjAlNUUldTAzOUYr,inputs=Y2F0) Explanation: ``` ± reverse the string K take off the first letter - will slowly convert to the output ; get the rest of the string ontop { iterate over the rest of the characters ╔+ append "_" to it ; get the output string ontop lH? } if it's length - 1 [isn't 0] "{ŗ}” push the string "{ŗ}" where ŗ is replaced by the output string 1 ^Ο wrap "^" around with the output string + prepend to it the current character + "_" ``` [Answer] # [Perl 5](https://www.perl.org/), 54 + 1 (-p) = 55 bytes ``` s/\{(.)\}/$1/g while s/([a-z])([a-z]+)/$1_{$2}^{$2}/ig ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP6ZaQ08zplZfxVA/XaE8IzMnVaFYXyM6UbcqVhNCaWsCJeOrVYxq40CEfmb6//@JScn/8gtKMvPziv/r@prqGRga/NctAAA "Perl 5 – Try It Online") **How?** The substitution in the while condition breaks occurrences of multiple letters in the first letter, followed by the rest in braces like this: ``` abc -> a_{bc}^{bc} ``` The while loop executes the substitution until no more multi-letter sequences remain. The substitution inside the loop removes braces from around single letters. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~76~~ ~~73~~ ~~72~~ ~~68~~ ~~67~~ 57 bytes Use of lambda saving 4 bytes thanks to [Tutleman](https://codegolf.stackexchange.com/users/64834/tutleman) ``` f=->s{(r=s[1..-1])[0]?s[0]+?_+[r[1]??{+f[r]+?}:r]*2*?^:s} ``` [Try it online!](https://tio.run/##FchBCsIwEEDRfU8xG0EbGozLQs1BhlFik9iNRmZaiqQ5e6ybD@/z8vjWGofuKvnIg6DRujN0wjNZ2aPsXSGjIWuzisj7KD1Te2ntrZdSD2t28AowuhkipydMiSUUHdw4gU@wrYn91gB8llkg4p/UhLevPw "Ruby – Try It Online") Ungolfed: ``` def f(s) r = s[1..-1] if r.size > 0 if r.size > 1 x = "{" + f(r) + "}" else x = r end return s[0] + "_" + [x, x].join("^") else return s end end ``` [Answer] # [Python 2](https://docs.python.org/2/), 84 bytes ``` def b(s):q=s and(s[2:]and'{%s}'or'%s')%b(s[1:]);return s[1:]and s[0]+'^%s_'%q+q or s ``` [Try it online!](https://tio.run/##HYxBCsIwEAC/spewWXrRHiO@pMQSbcVeNsluShHx7XHxNgPDlHd7ZR57X9Yn3L1SqFeFxIvXaQzRAD9Ov5gFnSI5S6ZziHSRte3C8DerDE5xwJvTGV0dKmQB7UU2braVdMwbl715ov5I7Qc "Python 2 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 47 bytes ``` Ljk[hb|&ttbs[\_\{ytb"}^{"ytb\})&tbs[\_htb\^htb; ``` [Try it online!](https://tio.run/##K6gsyfj/3ycrOzojqUatpCSpODomPqa6siRJqTauWglIx9RqqkGEM4CcOCBh/b/yv1JGflFxqhIA "Pyth – Try It Online") This is pretty much a straight port of @Uriel's Python answer. Going to golf it down in a bit. [Answer] # PHP, 121 bytes ``` function b($s){return $s[0].($s[1]?'_'.($s[2]?'{'.($b=b(substr($s,1))).'}^{'.$b.'}':"$s[1]^$s[1]"):'');}echo b($argv[1]); ``` The function itself is 104 bytes and shows a PHP Notice. [Answer] # [Retina](https://github.com/m-ender/retina), 43 bytes ``` (.)(.)$ $1¶$2 +`(.)¶(.*) ¶{$1_$2^$2} ¶{|}$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPE4hUuFQMD21TMeLSTgDyDm3T0NPS5Dq0rVrFMF7FKE7FqBbEqalV4fr/P5ErN5UrObGEK60oP50rI7@oOJUrKTOttAgolgoA "Retina – Try It Online") Link includes test cases. Explanation: ``` (.)(.)$ $1¶$2 ``` Get the ball rolling by slicing off the last character. (But if it's the only character, them leave it alone.) ``` +`(.)¶(.*) ¶{$1_$2^$2} ``` Move the ¶ character back one step at a time, each time taking the previous result and making it a subscript and superscript of the next character. ``` ¶{|}$ ``` Remove the now redundant ¶ and the outer {}s. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 121 bytes ``` s->{int l=s.length;String r=--l<0?"":""+s[l];for(;l-->0;)r="{"+s[l]+"_"+r+"^"+r+"}";return r.replaceAll("^\\{|\\}$","");} ``` [Try it online!](https://tio.run/##VVDBbsIwDL3zFZa1Q6vSiDOlTGjSbjtxpDCFLi1hIamcFAl1/fYupR10kZL42c/Wez7zK49NJfT567ur6qOSOeSKWwsfXGpoZgBj1jru/Hc18gsuvhZsHUld7vbAqbThnQpw9vNY7aRiRa1zJ41m72Owyk@cdvv50LeGoyxqyrkzBCl0Nl43UjtQqWVK6NKdkoEIlMaxWi1eEZeIkd2pfVIYChIVx@tFElKKzZCO8BMjivBwf1tMSLiaNBAjUSmei41SAR6yrPnJsvYF54hh0nbJXfjDjRPWWa9o8NMfxPkz5lNwEVPkvUxhQaac4pMh@4//twCBY64dpPTuRu@9mOUgKXwo2t6sExdmascqz3JKB89dMl5V6hb0LcyZN7/yDRG/BWEYDtPbWX/b7hc "Java (OpenJDK 8) – Try It Online") [Answer] # Javascript, 73 Bytes ``` s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1') ``` ## Explanation ``` s=> // take the input string [...s] // split the string into an array .reduceRight( // reduce the array in reverse order (m,c)=>`${c}_{${m}}^{${m}}` // storing the result of each iteration in the memo m ) // and returning m at the end .replace(/{(.)}/g,'$1') // replace redundant {} ``` Because there is no specified initial value of `m`, `reduceRight` takes the last element of `s` as the initial value, and begins iterating at index `s.length-2`. ``` const f=s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1'); const input = document.querySelector('#input'); const output = document.querySelector('#output'); output.textContent = f(input.value); input.addEventListener('keyup', e => output.textContent = f(input.value)); ``` ``` Enter text to bifurcate: <input type="text" id="input" value="cat" /> <br /> <span id="output"></span> ``` ]
[Question] [ Given an positive integer as input determine if it is a magnanimous number. A magnanimous number is a number such that any insertion of a `+` sign between any two digits in base 10 results in an expression of a prime integer. For example 40427 is magnanimous because ``` 4+0427 = 431 is prime 40+427 = 467 is prime 404+27 = 431 is prime 4042+7 = 4049 is prime ``` ## Output You should output two distinct values, one when the input is magnanimous and one when the input is not. ## Scoring The goal of this contest will be to make the size of the source code written to solve this task, given in bytes, as small as possible. ## Test Cases ``` 1 -> True 2 -> True 4 -> True 10 -> False 98 -> True 101 -> True 109 -> False 819 -> False 4063 -> True 40427 -> True 2000221 -> True ``` **[OEIS 253996](http://oeis.org/A252996)** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ### Code ``` η¨¹.s¨R+pP ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//3PZDKw7t1Cs@tCJIuyDg/38TAxMjcwA "05AB1E – Try It Online") or [Verify all test cases!](https://tio.run/##MzBNTDJM/V9TVvn/3PZDKyr1ig@tCNIuCPhfqXR4P6euHefh/Uo6/w25jLiMuUy4TLnMuMy5LLgsuQwNuCwtgKQhEFtyWRhacpkYmBiZAwA) ### Explanation ``` η¨ # Take the prefixes of the input and remove the last element ¹.s¨ # Take the suffixes of the input and remove the last element R # Reverse the array of suffixes + # Vectorized addition p # Check if each element is prime P # Product of the array ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 83 ~~84~~ ~~85~~ ~~83~~ ~~84~~ ~~86~~ ~~75~~ ~~111~~ bytes All optimizations turned off and only on GCC 32-bit. -1 byte thanks to @ceilingcat +some bytes for `1` case. +some bytes for reusable functions. ``` i,j,r,s;f(a){for(i=10,r=1;a/i;i*=10)for(s=a%i+a/i,r*=s-1,j=2;j<s;)r*=s%j++>0;a=!r;} ``` Takes input as an integer. **Return 1 for false cases, 0 for true cases.** [Try it online!](https://tio.run/##bY/RagMhEEXf/QoTWNCsoWpDk2Dsl/RFNlpmSdyiplBCvn3jShNWyH07M5d7Z7r1d9eNI7CeBRaVI4Ze3RAIaMFZ0EKZN1CwykSncdSmgTbPWFjpuBas11L1h6joxE3ftp9cGb0I6jb@DnDEycZEwCecKLoinAWOLBxJlBaa9BOywZFlc8R/Nn75JctuVdb2FO0rnx@ethtCU/7ZgCePjtIq/jMKyDnkZ2a039U7UeN@jjtR4YZ/vNe8kduqlnMu5SMx2HQJHvNyNBrv "C (gcc) – Try It Online") See my another answer for Mathematica code (55 bytes). [Answer] ## [Retina](https://github.com/m-ender/retina), 38 bytes ``` \B $`$*_$'$*_ S`\d G`^_$|^(__+)\1+$ ^$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP8aJSyVBRSteRR1IcAUnxKRwuSfExavUxGnEx2trxhhqq3DFqfz/b8hlxGVpwWVoYAjEllwWhpZcJgYmRuYA "Retina – Try It Online") Prints `1` for magnanimous numbers and `0` otherwise. ### Explanation ``` \B $`$*_$'$*_ ``` We start by matching each position between two digits (positions that aren't word boundaries) and inserting both the prefix and the suffix of that match in unary, using `_` as the unary digit. So instead of inserting `+`s, we directly insert the unary result of the sum there. ``` S`\d ``` Now we split the string around digits, so that each sum goes on its own line and we get rid of those digits (there'll be an empty leading and trailing line as well, but that's not important). ``` G`^_$|^(__+)\1+$ ``` This is the standard regex to match non-prime numbers in unary. Using a `G`rep stage here means that we simply keep all lines that contain positive non-primes (discarding the empty lines). ``` ^$ ``` Finally we check whether the string is empty. If the input was magnanimous, the previous stage will have discarded all lines (because they were all primes), and this gives us `1`. Otherwise, if any line wasn't a prime, it will remain in the string and the regex fails, giving `0`. [Answer] # [Python 2](https://docs.python.org/2/), ~~82~~ ~~79~~ 78 bytes ``` f=lambda n,d=10:n<d or d/n<all((n/d+n%d)%k*f(n,10*d)for k in range(2,n/d+n%d)) ``` This is *slow* and can only cope with the test cases with memoization. [Try it online!](https://tio.run/##RU/NbsMgDD6Hp/AFFTqqAqvWHzV7kWmHTMAaNXEimh3Wqs@e2YmiXWzs78cf/e9w6dCPYyqbqv0KFaAJpbMnPAfoMoQtnqumUQq34QVl0PK6TgqNs@ugExGuUCPkCr@j8mYh6THEBG1su/oeVdInUfAAJTyeomDsEps@ZjKCQFtnmVLUCaaNBuwG9mURA5P6Y8Y@iZ/mJyE5Dj95Ji64WJbzDSESKf6z0Eyxke2dAW/ouIHjgbvjcjRwcFR29u2V687viWat9d5Rlj7XOMBK7m@weQd5W4GcQlMk@vYf "Python 2 – Try It Online") ### Alternate version, 79 bytes ``` f=lambda n,d=10:n<d or f(n,10*d)>d/n<all((n/d+n%d)%k for k in range(2,n/d+n%d)) ``` Sped up at the cost of one byte. [Try it online!](https://tio.run/##NY7LDoIwFETX@hWzaSh6DW0l8gjwLzVXlIAXgmz8emwXbs4szmQyy3d7zeL2vW8n/76zhxC31tTSMOYVvRay5sRpx5k0fpq0lozPojhVI/rQGDEIVi/Ph3b0d@kelURlCY5gDaEqY9qIilDagNzcrpG5K0LNGOOcrY@HZR1kQ6KKDy4d1CeBQjgS34TpHw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` DJ⁵*⁸dṖS€ÆPẠ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//RErigbUq4oG4ZOG5llPigqzDhlDhuqD///80MDQyNw "Jelly – Try It Online") [Verify all test cases.](https://tio.run/##y0rNyan8/9/F61HjVq1HjTtSHu6cFvyoac3htoCHuxb8P9wOZP//b6hjpGNpoWNoYKhjYWipY2JgYmQOAA) [Answer] # Java 8, ~~175~~ ~~171~~ ~~94~~ 88 bytes ``` n->{long d=10,r=0,i,t;for(;d<=n;d*=10,r|=t-i)for(t=n/d+n%d,i=1;t%++i%t>0;);return r==0;} ``` -77 thanks to *@PeterTaylor* by using an arithmetic (instead of String with `.substring`) and getting rid of the separate method to check if the integer is a prime. -6 bytes using [*@SaraJ*'s prime-checking method](https://codegolf.stackexchange.com/a/181611/52210), so make sure to upvote her! [Try it here.](https://tio.run/##jZDRboMgFIbvfYpzY6KrOnTNVsPoE2y96eWyCyq0odODwWOXpfPZHXW9VwIh5@cDPjjLi0xtq/Gsvsaqll0H79LgNQAwSNodZaVhdysBDtbWWiJUUW3xBBhzHw9@@L4DBAEjptvrtKhEzhInWGIS4kfrIq5eBXL1MOW/glIT32IS@KhWGKrEiJxTuFqZkLaMx9xp6h2CE4LxYeSBv6TtD7WpoCNJfrpYo6DxstGenMHTxyfI@N/09gRovBDq76mIJleA/U9HuslsT1nr91CNUZNhVkX5WzyHFPNIzuaZcrPknHwJVM5Dm3wBtGbPT0uodfGy4JsYY0WxwL@8tzs5BMP4Bw) **Explanation:** ``` n->{ // Method with long as both parameter and return-type long d=10,r=0,i,t; // Some temp longs for(;d<=n // Loop as long as `d` is below or equal to input `n` // (inclusive instead of exclusive due to special case 10) ; // After every iteration: d*=10, // Multiple `d` by 10 r|=t-i) // and Bitwise-OR `r` with `t-i` for(t=n/d+n%d, // Set `t` to `n` integer-divided by `d` plus `n` modulo-`d` i=1; // Set `i` to 1 t%++i%t>0;); // Inner oop as long as `t` modulo `i+1` modulo `t` is not 0 yet // (after we've first increased `i` by 1 with `++i`) // (if `t` equals `i` afterwards, it means `t` is a prime) return r==0;} // Return if `r` is still 0 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` .AmP_ssMcQ]dtU ``` [Try it online!](https://pyth.herokuapp.com/?code=.AmP_ssMcQ%5DdtU&input=%2240427%22&debug=0) Will display `True` if the number is magnanimous, `False` otherwise. Takes the number as a string. **Explanations** ``` .AmP_ssMcQ]dtU Q # Implicit input Q tU # Generate the range [1, 2, ..., len(Q)-1] m # For each index d in the above range... cQ]d # Split Q at index d sM # Convert the two parts to integers s # Sum P_ # Check it is a prime .A # ...end for. Check all elements are True ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~104 102 98 96~~ 103 bytes * Thanks to @Wheat Wizard for 2 bytes: made `i` completely anonymous since it is called only once. * Thanks to @Hyperneutrino for 4 bytes: smarter way of obtaining the numbers from the main number instead of slicing * @Hyperneutrino saved another 2 bytes: `x-1` to just `x` for the prime checking rarnge. * Fixed failure for case `x=10`,thus adding 7 Bytes, thanks to @Dennis and @Wheat Wizard for spotting it: my earlier version was considering 1 a prime ``` lambda x:all((lambda x:x>1and all(x%j for j in range(2,x)))(x/10**j+x%10**j)for j in range(1,len(`x`))) ``` [Try it online!](https://tio.run/##XYtBCoMwEEX3nmI2QmIH6gShKtiLtAWnaFs1xiAupqe3SRdddDF/@J/3/Ht7Lc7sU3PdLc/3jkFqtlapX5MzsesgjpKO8FhWGGFwsLJ79sqgaK2VHCnPsvEg6ffrP4rQ9k610gZ273jj5kJokHKsypAUrsKSKizywpxuSdR91CNbJ@DXwW1qUj7oHw "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~24~~ 16 bytes This was pretty much a collaboration between @Shaggy, @ETHproduction, and myself. ``` ¬£[YîU UtY]xÃÅej ``` [Try it online!](https://tio.run/##y0osKPn//9CaQ4ujIw@vC1UILYmMrTjcfLg1Nev/fyUTAxMjcyUA "Japt – Try It Online") Takes input as a string. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~25~~ 24 bytes ``` $&0N_%,_=1M$+(a^@_)M1,#a ``` [Try it online!](https://tio.run/##K8gs@P9fRc3AL15VJ97W0FdFWyMxziFe09dQRznx////JgZmxgA "Pip – Try It Online") ### Explanation `a` is the first command-line argument. `1,#a` generates a Range containing numbers `1` through `len(a)-1`. To this, we map a lambda function: ``` $+(a^@_) a^@_ Split a at this index $+( ) Fold the resulting 2-element list on + ``` Next, we map another lambda function, `0N_%,_=1`, that tests for primality. I took it from [this answer](https://codegolf.stackexchange.com/a/108295/16766); you can read the explanation there. Finally, we fold the list on logical AND (`$&`). The result is `1` iff all the sums were prime, `0` if any of them weren't. Example, with input of `4063`: ``` 1,#a [1; 2; 3] $+(a^@_)M [67; 103; 409] 0N_%,_=1M [1; 1; 1] $& 1 ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 22 bytes ``` r:L,({)_L<i\L>i+mp!},! ``` [Try it online!](https://tio.run/##S85KzP3/v8jKR0ejWjPexyYzxscuUzu3QLFWR/H/fxMDEyNzAA "CJam – Try It Online") Prints positive integer for truthy, zero for falsy. -1 thanks to a clever trick by [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor). -3 thanks to another tip by Peter Taylor. [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes Takes input as a string. Dang it; [beaten to the punch](https://codegolf.stackexchange.com/a/128681/58974) on a much shorter alternative I was working on. ``` ¬£i+YÃÅe@OxXr"%+0+"'+)j ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=rKNpJytZw8VlQE94WHIiJSswKyInKylq&input=IjQwMDQzIg==) [Answer] ## Mathematica, 75 bytes ``` And@@Table[PrimeQ@ToExpression@StringInsert[#,"+",n],{n,2,StringLength@#}]& ``` `Function` which expects a `String`. `PrimeQ@ToExpression@StringInsert[#,"+",n]` returns whether inserting a `+` after the `n`th digit gives a prime number. `Table[...,{n,2,StringLength@#}]` gives the list of these values as `n` ranges from `2` to the length of the string. We then take `And` of each of the elements of that list. Conveniently, if `StringLength@#<2`, then `Table[...]` is the empty list, for which `And@@{}==True` [Answer] # Mathematica, 55 ~~50~~ ~~45~~ ~~49~~ ~~50~~ ~~54~~ ~~62~~ bytes It seems I should post it separately. +6 bytes for code length remeasured. +5 bytes thanks to ngenisis. ``` And@@(qPrimeQ[#~Mod~q+⌊#/q⌋])@Rest@PowerRange@#& ``` Takes input as an integer and return regular `True` and `False`. The `` in-between is unicode 0xF4A1, short for `Function[,]`. Code length is measured on file size (UTF-8 without BOM), comment if it is not correct. `PowerRange[x]` returns 1, 10, 100... no greater than `x`, which is introduced in Mathematica 10. [Answer] # [Plain English](https://github.com/Folds/english) ~~4,204~~ ~~341~~ ~~315~~ ~~251~~ ~~241~~ 240 bytes (Re-)incorporated primality testing into Plain English's library, by moving 3,863 bytes into Plain English's library. Deleted 26 bytes of white space. Saved 64 bytes by abbreviating local variables. Saved 10 bytes by abbreviating the interface. Per [RosLuP](https://codegolf.stackexchange.com/users/58988)'s suggestion, saved 1 byte by changing how m is initialized and incremented. ``` To decide if a n number is g: Put 1 in a m number. Loop. Multiply the m by 10. If the m is greater than the n, say yes. Divide the n by the m giving a q quotient and a r remainder. Add the q to the r. If the r is not prime, say no. Repeat. ``` Ungolfed version of final code: ``` To decide if a number is magnanimous: Put 1 in another number. Loop. Multiply the other number by 10. If the other number is greater than the number, say yes. Divide the number by the other number giving a quotient and a remainder. Add the quotient to the remainder. If the remainder is not prime, say no. Repeat. ``` Notes: The Plain English IDE is available at [github.com/Folds/english](https://github.com/Folds/english). The IDE runs on Windows. It compiles to 32-bit x86 code. The [Osmosian Order](http://www.osmosian.com/)'s dynamic fork of Plain English already had primality testing in version 4700, but it used a very inefficient algorithm (as of January through June 2017). Versions 4001-4011 of the GitHub site's dynamic fork omitted primality testing. Version 4013 of the GitHub site's dynamic fork includes primality testing. The code to perform the primality testing was developed as part of previous revisions of this answer. [Answer] # [Perl 6](http://perl6.org/), 58 bytes ``` {?(10,10* *...^*>$_).map({$_ div$^a+$_%$^a}).all.is-prime} ``` [Try it online!](https://tio.run/##FYrRCoIwGEZf5btYMVeN/19ijsreRBmkMNhoKAQiPvtaF@ecm5PGOTQ5rjhOeObtJZnOTApKa92rTgyVji7JTQx4@6/o3UkMh5K90i4E7ZdLmn0c93zHJP/34lZMnxkPhgETbFvMBYuWLWpqrkW1ucEQkTHc5R8 "Perl 6 – Try It Online") `10, 10 * * ...^ * > $_` is the geometric sequence of multiples of ten, taken until one before the element that exceeds the input parameter `$_`. Then we just check that for each power of ten, the sum of the input parameter taken div and mod that power is prime. [Answer] # Haskell, ~~114~~ 110 bytes ``` p x=[x]==[i|i<-[2..x],x`mod`i<1] i!x|i<1=0<1|0<1=p(uncurry(+)$divMod x$10^i)&&(i-1)!x f x=(length(show x)-1)!x ``` Ungolfed with explanation: ``` -- Check if x is a prime number p x = [x] == [i | i<-[2..x], x`mod`i < 1] -- Checks all pairs of numbers a '+' can be put in between i ! x | i<1 = 0<1 -- Single-digit numbers are always truthy | 0<1 = p (uncurry (+) $ divMod x $ 10^i) -- Does x split at i digits from right sum up to a prime? && (i-1) ! x -- If so, check next pair -- Start (!) with the number of digits in x minus one f x = (length (show x)-1) ! x ``` [Answer] # Axiom, 88 bytes ``` f(n:PI):Boolean==(i:=10;repeat(q:=n quo i;q=0 or ~prime?(q+n rem i)=>break;i:=i*10);q=0) ``` test and results ``` (10) -> [[i,f(i)] for i in [1,2,4,10,98,101,109,819,4063,40427,2000221,999999999999999999999999999999999999999999999]] (10) [[1,true], [2,true], [4,true], [10,false], [98,true], [101,true], [109,false], [819,false], [4063,true], [40427,true], [2000221,true], [999999999999999999999999999999999999999999999 ,false]] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {~cĊℕᵐ+}ᶠṗᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8L@6LvlI16OWqUC2du3DbQse7pwOEv4fbahjpGOiY2igY2kBJA2B2FLHwtBSx8TAzBhImBiZ6xgZGBgYGRnGAgA "Brachylog – Try It Online") ``` { }ᶠ Find every + sum of Ċ two ℕᵐ whole numbers ~c which concatenate to the input, ᵐ and assert that all of them ṗ are prime. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes ``` {m:ex/^(.+)(.+)$/.all.sum.is-prime} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrXKrVCP05DT1sThFX09RJzcvSKS3P1Mot1C4oyc1Nr/6flFylo5GTmpRZrKlRzcRYnVirYp2lo5@rHpGjra3LV/jdUgABdO4WQotJULiM0vgka39AAzndLzClO5bK0QFdgiMa3RNVgYYgmYGJgZoxipYGJkTmykwwMDIyMDGF8AA "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block that m:ex/^ $/ # Match all (.+)(.+) # Splits of the input number .all # Are all of them .sum # When summed .is-prime # Prime? ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` Λȯṗṁd§e↑↓d¹ḣL ``` [Try it online!](https://tio.run/##ASkA1v9odXNr///Om8iv4bmX4bmBZMKnZeKGkeKGk2TCueG4o0z///80MDQyNw "Husk – Try It Online") -1 byte from user. [Answer] # [Risky](https://github.com/Radvylf/risky), 44 bytes ``` *0!?+0-_1+0___?+0+_1+0___?{?}_*+0+__?[?}_*+0_!\?+0+1111:!111111111+111111111111111111111 ``` [Try it online!](https://radvylf.github.io/risky?p=WyIqXG4wIT8rMC1fMSswIF8gX18_KzArXzErMFxuX1xuX18_ez99XyorMCArIF9fP1s_fV8qKzBcbl9cbiFcXD8rMCsxMTExIDogITExMTExMTExMVxuK1xuMTExMTExMTExMSAxIDExMTExMTExMTEiLCJbWzIsMCwwLDAsMiwyLDFdXSIsMF0) Takes input as an array of digits (which is [allowed by default](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/18097#18097)). Outputs `1` for true and `0` for false. [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `g`, 10 bytes ``` ṗΩL2=]“⌊ṠṄ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyJnIiwiIiwi4bmXzqlMMj1d4oCc4oyK4bmg4bmEIiwiIiwiWzgsMSw5XSIsIjMuNC4wIl0=) [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 51 bytes ``` [tostr:#'1-~>splitat tr['+',' '#`#~prime]map 1,all] ``` [Try it online!](https://tio.run/##FcxLCoMwFEbhuav4SwZRqpCbSmscSPchQkOrIL5CvB2VuvU0HZxveHa2z6l/hdDytrOvhaTiaHY3j2wZ7Ft5lrmEFA9xOD8ufbdYB8rtPHfhXg9JkhI0SMFUUYoZVGRQquslUuobtFJKa8rwOSFdIVE0kRVDhi/@u@3N4Qc "Stacked – Try It Online") This is a function. It works by converting its argument to a string (`tostr`), duplicating it and obtaining its length (`:#'`), subtracting 1 (`1-`), making a range from 1 to that number (`~>`). The stack looks something like this, for input `40427`: ``` ('40427' (1 2 3 4)) ``` We perform vectorized `splitat`, resulting in the following array to be at the top of the stack: ``` (('4' '40' '404' '4042') ('0427' '427' '27' '7')) ``` Transposing this with `tr`, we get: ``` (('4' '0427') ('40' '427') ('404' '27') ('4042' '7')) ``` Then, we map the function `['+',' '#`#~prime]`(with`map`). This function does: ``` ['+',' '#`#~prime] '+', concatenate a plus sign (string) `('4' '0427' '+') ' '#` join by spaces `'4 0427 +'` #~ evaluate `431` prime check primality `1` ``` Then, after the map, we concatenate `1`. This is since `all` returns `undef` for an empty list. [Answer] ## JavaScript (ES6), 70 bytes ``` P=(n,x=2)=>n%x?P(n,x+1):n==x f=(n,i=10)=>i>n||P((n/i|0)+n%i)&f(n,i*10) ``` Fails on the last case in my browser due to a "too much recursion" error while calculating `P(200023)`. Hopefully this doesn't invalidate it. [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 38 bytes ``` _L;|[a-1|q=q*µ!_sA,b|!+!_sA,b+1,a|!}?q ``` ## Explanation ``` _L | Create a variable a and set it to the length of ; the input string (A$) [a-1| FOR b = 1 to a-1 q=q* multiply q by µ -1 if prime, 0 if not, of ! a cast of _s a substring of A, A$ b from index 1 to index b (only one index is given, so that is assumed to be the req. length from 1) |! to number + plus ! a cast of _s a substring of A, A$ b+1 from index b+1 ,a for the length of a (does not error if it exceeds the end of the string) |! to number } NEXT ?q PRINT q, which is eitrher -1 or 1 for all-prime sums, or 0 otherwise ``` [Answer] ## CJam (21 bytes) ``` r:R,({RiA@)#md+mp!},! ``` [Online demo](http://cjam.aditsu.net/#code=r%3AR%2C(%7BRiA%40)%23md%2Bmp!%7D%2C!&input=40427), [online test suite](http://cjam.aditsu.net/#code=qN%250%3AF%3B1%3AT%3B%7B%22-%3Eruealse%22-~%5C%60%3AQ%3B%0A%0AQ%3AR%2C(%7BRiA%40)%23md%2Bmp!%7D%2C!%0A%0A%3D%7D%2F&input=1%20%20%20%20%20%20%20-%3E%20True%0A2%20%20%20%20%20%20%20-%3E%20True%0A10%20%20%20%20%20%20-%3E%20False%0A21%20%20%20%20%20%20-%3E%20True%0A22%20%20%20%20%20%20-%3E%20False%0A98%20%20%20%20%20%20-%3E%20True%0A101%20%20%20%20%20-%3E%20True%0A109%20%20%20%20%20-%3E%20False%0A819%20%20%20%20%20-%3E%20False%0A4063%20%20%20%20-%3E%20True%0A40427%20%20%20-%3E%20True%0A2000221%20-%3E%20True) ### Dissection ``` r:R e# Take a token of input and assign it to R ,( e# Take the length of R minus one { e# Filter i = 0 to (length of R minus two) Ri e# Push R as an integer value A@)# e# Push 10 to the power of (i + 1) md e# divmod +mp! e# Add, primality test, negate result }, e# The result of the filter is a list of splits which give a non-prime ! e# Negate result, giving 0 for false and 1 for true ``` [Answer] # Pyth, ~~15~~ 14 bytes ``` .AmP_svcz]dtUz ``` [Test suite](https://pyth.herokuapp.com/?code=.AmP_svcz%5DdtUz&test_suite=1&test_suite_input=1%0A2%0A10%0A98%0A101%0A109%0A819%0A4063%0A40427%0A2000221&debug=0) Saved a byte using Pyth's newest change. [Answer] # APL(NARS), chars 35, bytes 70 ``` {0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k} ``` test: ``` f←{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k} f¨1 2 4 10 98 101 109 819 4063 40427 2000221 1 1 1 0 1 1 0 0 1 1 1 ``` This would be the translation in APL from Axiom post algo here... ``` {0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k} 0≥k←¯1+≢⍕⍵:1⋄ assign to k the length as array of argument return 1 if that is <=0 ∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k m←10*⍳k m is the array pow(10,1..k) ⌊⍵÷m the array of quotient of argumet with m + sum (m∣⍵) with array of remander 0π build the binary array of "are prime each" ∧/ and that array ``` [Answer] # PHP, 100 bytes ``` for(;++$k<strlen($a=$argn);$x+=$i==1)for($i=$n=substr($a,$k)+$b.=$a[$k-1];--$i&&$n%$i;);echo$x+2>$k; ``` prints `1` if input is magnanimous, empty output if not. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/3f55db523d77f0ef91890bc3efc65c624c0e9bae). ]
[Question] [ ## Introduction Suppose you want to compute the tail maxima of a list of numbers, that is, the maximum of each nonempty suffix. One way to do it is to repeatedly choose one number and replace it by a higher number occurring after it, until this is not possible anymore. In this challenge, your task is to perform one step of this algorithm. ## The task Your input is a list of integers **L**, which may be empty. Your output shall be the list **L** where exactly one number **Li** has been replaced by another **Lj**, where **Li < Lj** and **i < j**. In other words, you shall replace one number with a higher number that occurs after it. You can choose **i** and **j** freely among all valid pairs, and the choice can be nondeterministic. If such **i** and **j** do not exist (i.e. **L** is non-increasing), your output shall be **L** unchanged. ## Example Consider the input **L = [ 3, 1, 4, -1, 2 ]**. The possible operations are to replace **3** by **4**, replace **1** by **4**, replace **1** by **2**, or replace **-1** by **2**. Thus the possible outputs are: ``` [ 3 , 1 , 4 , -1 , 2 ] ------------------------------ [( 4), 1 ,( 4), -1 , 2 ] [ 3 ,( 4),( 4), -1 , 2 ] [ 3 ,( 2), 4 , -1 ,( 2)] [ 3 , 1 , 4 ,( 2),( 2)] ``` If you repeat the operation enough times, the end result will be **[4,4,4,2,2]**, which is precisely the list of tail maxima of **L**. ## Rules and scoring You can write a full program or a function. In the latter case, you can modify the input in place instead of returning a new array, if your language allows that. Input and output formats are flexible within reason. The lowest byte count wins. ## Test cases All possible outputs are shown. ``` [] -> [] [1] -> [1] [1,2] -> [2,2] [2,1] -> [2,1] [4,4,4,4] -> [4,4,4,4] [-1,-3,-10] -> [-1,-3,-10] [1,3,10] -> [3,3,10] [10,3,10] [1,10,10] [1,1,2,1] -> [2,1,2,1] [1,2,2,1] [998,64,2,-94,-789] -> [998,64,2,-94,-789] [998,2,64,-94,-789] -> [998,64,64,-94,-789] [3,1,4,-1,2] -> [4,1,4,-1,2] [3,4,4,-1,2] [3,2,4,-1,2] [3,1,4,2,2] [-1,4,0,4,7,2,3] -> [4,4,0,4,7,2,3] [0,4,0,4,7,2,3] [-1,4,4,4,7,2,3] [7,4,0,4,7,2,3] [-1,7,0,4,7,2,3] [-1,4,7,4,7,2,3] [-1,4,0,7,7,2,3] [2,4,0,4,7,2,3] [-1,4,2,4,7,2,3] [3,4,0,4,7,2,3] [-1,4,3,4,7,2,3] [-1,4,0,4,7,3,3] [3542,-12311,7662,1672,6081] -> [7662,-12311,7662,1672,6081] [3542,7662,7662,1672,6081] [3542,1672,7662,1672,6081] [6081,-12311,7662,1672,6081] [3542,6081,7662,1672,6081] [3542,-12311,7662,6081,6081] ``` [Answer] # JavaScript (ES6), ~~41~~ ~~40~~ ~~39~~ 38 bytes *Saved a byte thanks to @Neil, another thanks to @user81655* ``` x=>x.map(c=>c<x[++i]>d?x[d=i]:c,d=i=0) ``` Just when it seems `reduceRight` might finally have a chance, `.map` shows up yet again... [Answer] # Mathematica, 37 bytes ``` #/.{a___,b_,c_,d___}/;b<c:>{a,c,c,d}& ``` Pure function taking a list of real numbers even, and returning a list of real numbers. Looks for the first pair of consecutive entries in the "wrong" order, and replaces the first of that pair with the second. Nice default behavior of `/.` means that it returns the input unaltered when appropriate. Amusing side note: if we replace `b<c` with `!OrderedQ[{c,b}]`, then the function works on strings (and really any data type once the appropriate ordering is described). For example, `#/.{a___,b_,c_,d___}/;!OrderedQ[{c,b}]:>{a,c,c,d}&` on input `{"programming", "puzzles", "code", "golf"}` returns `{"puzzles", "puzzles", "code", "golf"}`. [Answer] ## JavaScript (ES6), ~~43~~ ~~39~~ 38 bytes ``` a=>a[a.some(e=>e<a[++i],i=0)*i-1]=a[i] ``` Outputs by modifying the array in-place. Edit: Saved 4 bytes thanks to @ETHproductions. Saved 1 byte thanks to @user81655. [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` f(a:r@(b:_))|a<b=b:r|1>0=a:f r f e=e ``` [Try it online!](https://tio.run/nexus/haskell#PU5BCsMgELznFXuMsAsxCW2UWPqBvkCkKCjkkBBMjv49USll2ZndYRjmCq2V8d06@WUs2dkpJ2Pir05ZGSA2Abzy1@mP81BaG9S8LPYVM2P@QY9YJ4vEkQYk3lXDgPUQYsLHmM0kRqTnJH5aX9S/BqizP@dQyTfNapcNFKx2/8Ael@0E3ZYiGKAQSwVnqt3MdQM "Haskell – TIO Nexus") Look through the list for consecutive elements `a,b` with `a<b` and changes them to `b,b`. Improved from 37 bytes: ``` f(a:b:t)|a<b=b:b:t f(a:t)=a:f t f e=e ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` ṫJṀ€ż¹ŒpQ-ị ``` Replaces the rightmost of all possible numbers. [Try it online!](https://tio.run/nexus/jelly#@/9w52qvhzsbHjWtObrn0M6jkwoCdR/u7v5/uB0o4v7/f3SsjkK0IZjQMQJRRjpgnokOGIKYuoY6usY6uoYGEFXGOjAWUAdEsaWlhY6ZCZCna2mio2tuYQkTNAIJIwsCNQON1YXapQviGACxOVClMVje1ARoiqGRsaGhjrmZGdB8M3OgIQYWhrEA "Jelly – TIO Nexus") ### How it works ``` ṫJṀ€ż¹ŒpQ-ị Main link. Argument: A (array) J Yield all indices of A, i.e., the array [1, ..., len(A)]. ṫ Dyadic tail; for index k, take all elements starting with the k-th. This constructs the array of suffixes. Ṁ€ Maximum each; map the monadic maximum atom over the suffixes. ¹ Identity; yield A. ż Zip; construct all pairs of elements of the result to the left and the corresponding elements of the result to the right. Œp Cartesian product. Construct all arrays that, for each index, take either the left or the right element. Q Unique; deduplicate the resulting arrays. -ị At-index -1; select the second to last result. The last result is A itself, the first maxima of suffixes. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` tdt0>0whY>d*0h+ ``` [Try it online!](https://tio.run/nexus/matl#@1@SUmJgZ1CeEWmXomWQof3/f7SxjqGOiY6uoY5RLAA "MATL – TIO Nexus") I'm not a huge fan of this solution. It seems horribly inefficient to me. Particularly the `whY>d*` and `0h+` sections. [Answer] # Python 2, ~~139~~ ~~134~~ 93 bytes ``` a=input() for i in range(len(a)): for j in a[i+1:]: if a[i]<j:a[i]=j;print a;exit() print a ``` Terribly long, but it's a first attempt. -5 bytes thanks to TemporalWolf -41 (!!) bytes thanks to Value Ink [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` ttd0>fX>Q)2M( ``` [Try it online!](https://tio.run/nexus/matl#@19SkmJglxZhF6hp5Kvx/3@0samJkY6uoZGxoaGOuZmZkY6hmbmRjpmBhWEsAA "MATL – TIO Nexus") ### Explanation The following two conditions are equivalent: 1. There is a number that has a higher number to its right 2. There is a number that has a higher number immediately to its right The code uses condition 2, which is simpler. It computes consecutive increments and finds the last positive one, if any. For the two involved entries, it writes the value of the second entry into the first. [This trick](https://codegolf.stackexchange.com/a/79189/36398) is used to handle the case when no substitution can be done. Note also that MATL indexing is `1`-based. Let's use input `[3,1,4,-1,2]` as an example. ``` tt % Get input implicitly and duplicate it twice % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [3,1,4,-1,2] d % Consecutive differences % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [-2 3 -5 3] 0> % Are they positive? % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [0 1 0 1] f % Find indices of all positive differences. Result may be empty % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [2 4] X> % Maximum index with a positive difference. Empty input remains as empty % STACK: [3,1,4,-1,2], [3,1,4,-1,2], 4 Q % Add 1. Since the addition is elementwise, empty input remains as empty % STACK: [3,1,4,-1,2], [3,1,4,-1,2], 5 ) % Get the entry of the input at that position % STACK: [3,1,4,-1,2], 2 2M % Push maximum index with a positive difference, again % STACK: [3,1,4,-1,2], 2, 4 ( % Assign to that position. Implicitly display % STACK: [3,1,4,2,2] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~34~~ 33 bytes This is based on [the answer by xnor](https://codegolf.stackexchange.com/a/113835/), who suggested I post it myself. EDIT: xnor found a byte to save. ``` f(a:r@(b:_))=max(b:r)$a:f r f e=e ``` [Try it online!](https://tio.run/nexus/haskell#PU5BCsMwDLv3FT7skIANaxu2JiywD@wFoYwMEuihpaQ97LC/d3YYw1iShTA6soqu3NXLPbX2c3yzKvoUXYbSZEg@HXva9s2HMGJoZbGryIx8QzBYh01qkXqk9lwDPVZh7YAXw2GyBuk62J/Xifv3AAPn@Q/J/7GZ47SAhzmuD1jLtOwQlBTBDEL6I3ij2m08vg "Haskell – TIO Nexus") Basically, I observed that the branching of xnor's method always ends up choosing whichever of the branch expressions is largest, since Haskell uses lexicographic ordering for lists. (The case when `a==b` also works because `f r>=r`, which can be proved separately by induction.) Put differently, whenever `b:r > a:f r`, then `b:r` is a correct answer, and otherwise we can recurse to `a:f r`. So instead of checking `a<b` in advance, I just calculate both expressions and take the maximum. This could give an exponential blowup, although Haskell's laziness avoids that unless `a` and `b` are equal. [Answer] # Python 3, 79 bytes ``` def f(x): for i,a in enumerate(x): m=max(x[i+1:]) if m>a:x[i]=m;break ``` Mutates the original array (list) given to it. I'm unhappy that this isn't a lambda and I'm sure there are better optimizations; I'll hopefully address those later. ### Brief explanation It takes the max of the array past the current element (starting with the zeroth). It then compares this to the element itself: if the max is greater, replace the current element with it and stop, otherwise, increment by one and keep trying that. [Answer] # Ruby, ~~66~~ 61 bytes ``` ->a{i=r=-1;a.map{|e|m=a[i+=1,a.size].max;r&&m>e ?(r=!r;m):e}} ``` [Try it online!](https://tio.run/nexus/ruby#bY5BCoMwEEX3nsJupKUz4sQ0mkrsQcRFKAqCAbGbUvXsduzKSAmBzPvJy19bg6WdOjMapMLGzg7T3MzO2Kq7GgIbv7pPUzN/F2MUubIJH@fRnMbCXe7NsgTBELbx0/Z9WNW7M3kDiP0owEsl/NYeIQGmgJT4lhSOhM2@TOsclGSKWgJmuT6GYov/hSznGnjoihtMeGf8MvXu3yT/QiIlgkwp7qEylic51ev6BQ "Ruby – TIO Nexus") [Answer] # C, 47 bytes ``` f(p,n)int*p;{n>1?*p<p[1]?*p=p[1]:f(p+1,n-1):0;} ``` Recursive implementation taking as its input a pointer to the first element of an array, and the length of the array. Modifies the array in place. [Answer] ## SWI-Prolog, 70 bytes ``` f([H|T],[S|T]):-max_list(T,S),S>H,!. f([H|T],[H|R]):-f(T,R),!. f(I,I). ``` First clause replaces the first element of the list with the maximum value of the rest of the list, but only if this max is bigger. The second clause recursively calls the predicate for the tail of the list. If none of these clauses succeed, the third clause simply returns the input. This return just one of the possible solutions. It's trivial to find all of them with very similar code, but then the case where no change is possible takes a lot more bytes to handle. Example: ``` ?- f([-1,4,0,4,7,2,3], O). O = [7, 4, 0, 4, 7, 2, 3] ``` [Answer] ## R, 71 bytes ``` a=scan() l=length(a) lapply(1:l,function(x){ a[x]=max(a[x:l]) a }) ``` [Answer] # C, 80 bytes ``` i,j;f(l,n)int*l;{for(i=0;i<n;++i)for(j=i;++j<n;)if(l[i]<l[j]){l[i]=l[j];j=i=n;}} ``` Call with: ``` int main() { int a[5]={3,1,4,-1,2}; f(a,5); for(int k=0;k<5;++k) printf("%d ", a[k]); } ``` [Answer] ## Python 2, 89 bytes [Try it online](https://tio.run/nexus/python2#@5@SmqbgpuGoacWlkJZfpJCpkJmnUJSYl56qkZOaBxQHSnAW2UZXgmUrQbKO0ZnahlaxmWkKlXZAdmwsFyeQXWQFYtsWRRvEWicVpSZm/3e0jTY00DHRAWFzHSMd41gukEVcBUWZeSUKjv8B) -1 byte thanks to @TemporalWolf -25 bytes thanks to @ValueInk -7 bytes thanks to @Cole Function that mutates input array ``` def F(A): for i in range(len(A)): r=[y for y in A[i+1:]if y>A[i]] if r:A[i]=r[0];break ``` If there was no need to stop after first iteration, it would be a bit prettier [Answer] # Python 2, 60 bytes ``` f=lambda x:x and[x[:1]+f(x[1:]),[max(x)]+x[1:]][x[0]<max(x)] ``` [Try it Online!](https://tio.run/nexus/python2#TcvBCoMwDADQu1@Ro2IEU7valu1LQg4dUihMN2SH/r2rxcMICclLcsTHK6zPJUD2GcK2cGZP0sc2M3npkNeQ29xJX2cp61Hulx3xvUOCtAGzINOZqEpVePYaa1QtXs05i0aXYXAah9m6y9SpfzbddLkhNRHhbEx5NnO5GS2J@AY@e9q@ENvUNccP) **Explanation:** Recursively checks if a given element is less than the `max` element in the rest of the list. If so, returns the list with `max` replacing the first element. [Answer] # TI-Basic, 72 bytes ``` Prompt L1 If 2≤dim(L1 Then For(A,1,dim(L1)-1 For(B,A,dim(L1 If L1(A)<L1(B Then L1(B→L1(A Goto E End End End End Lbl E L1 ``` Explanation: ``` Prompt L1 # 4 bytes, input list If 2≤dim(L1 # 7 bytes, if the list has 2 or 1 element(s), skip this part and return it Then # 2 bytes For(A,1,dim(L1)-1 # 12 bytes, for each element in the list other than the last For(B,A,dim(L1 # 9 bytes, for each element after that one If L1(A)<L1(B # 12 bytes, if the second is larger than the first Then # 2 bytes L1(B→L1(A # 10 bytes, replace the first with the second Goto E # 3 bytes, and exit End # 2 bytes End # 2 bytes End # 2 bytes End # 2 bytes Lbl E # 3 bytes L1 # 2 bytes, implicitly return L1 ``` [Answer] # sh, 118 bytes Input integers are passed as arguments to the script. ``` l=("$@");for i in "$@";{ for j in "$@";{(($i<$j))&&{ l[$x]=$j;echo ${l[@]};exit;};};shift;x=`expr $x+1`;};echo ${l[@]} ``` Breakdown: ``` l=("$@"); #copy original list for i in "$@";{ for j in "$@"; #check all elements j that follow element i in list {(($i<$j))&&{ l[$x]=$j;echo ${l[@]};exit;};}; #if i<j, make i=j; print list, done shift; #makes sure that i is compared only to j that occur after it x=`expr $x+1`;}; #keeps track of i'th position in the list echo ${l[@]} #prints list if it was unchanged ``` [Answer] # PHP, 88 Bytes ``` <?for(;$i+1<$c=count($a=$_GET)&&$a[+$i]>=$a[++$i];);$i>=$c?:$a[$i-1]=$a[$i];print_r($a); ``` ## Breakdown ``` for(; $i+1<($c=count($a=$_GET)) # first condition end loop if the item before the last is reach &&$a[+$i]>=$a[++$i] # second condition end loop if item is greater then before ;); $i>=$c?:$a[$i-1]=$a[$i]; # replace if a greater item is found print_r($a); #Output ``` [Answer] ## Haskell, 48 bytes ``` f(b:l)|l>[],m<-maximum l,b<m=m:l|1<2=b:f l f x=x ``` Usage example: `f [1,1,2,1]` -> `[2,1,2,1]`. [Try it online!](https://tio.run/nexus/haskell#@5@mkWSVo1mTYxcdq5Nro5ubWJGZW5qrkKOTZJNrm2uVU2NoY2SbZJWmkMOVplBhW/E/NzEzT8FWoaAoM69EQUUhTSHaUMdQx0jHMPY/AA "Haskell – TIO Nexus"). If the input list has at least one element, bind `b` to the first element and `l` to the rest of the list. If `l` is not empty and `b` less than the maximum of `l`, return the maximum followed by `l`, else return `b` followed by a recursive call of `f l`. If the input list is empty, return it. [Answer] ## Racket 202 bytes ``` (let((g(λ(L i n)(for/list((c(in-naturals))(l L))(if(= c i)n l))))(ol'())) (for((c(in-naturals))(i L))(for((d(in-range c(length L)))#:when(>(list-ref L d)i)) (set! ol(cons(g L c(list-ref L d))ol))))ol) ``` Ungolfed: ``` (define (f L) (let ((replace (λ (L i n) ; sub-function to replace i-th item in list L with n; (for/list ((c (in-naturals)) (l L)) (if (= c i) n l)))) (ol '())) ; outlist initially empty; (for ((c (in-naturals)) ; for each item in list (i L)) (for ((d (in-range c (length L))) ; check each subsequent item in list #:when (> (list-ref L d) i)) ; if greater, replace it in list (set! ol (cons (replace L c (list-ref L d)) ol)))) ; and add to outlist. ol)) ; return outlist. ``` Testing: ``` (f '(3 1 4 -1 2)) ``` Output: ``` '((3 1 4 2 2) (3 2 4 -1 2) (3 4 4 -1 2) (4 1 4 -1 2)) ``` [Answer] # C, 67 bytes **Single Run, 67 bytes** [Live](http://ideone.com/fe8XI4) ``` j;f(l,i)int*l;{j=i-1;while(i-->0)while(j-->0)l[j]=fmax(l[i],l[j]);} ``` **Single Step, 78 bytes** [Live](http://ideone.com/xp8tpi) ``` j;f(l,i)int*l;{j=i-1;while(i-->0)while(j-->0)if(l[j]<l[i]){l[j]=l[i];return;}} ``` **Tail Maxima, 96 bytes** [Live](http://ideone.com/JeDMAp) ``` x;i;j;f(l,n)int*l;{do{x=0;for(i=0;i<n;i++)for(j=0;j<i;j++)if(l[j]<l[i])l[j]=l[i],x=1;}while(x);} ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~103~~ 102 bytes ``` lambda a:([a[:i]+[max(a[i:])]+a[i+1:]for i in range(len(a))if-~i==len(a)or max(a[i+1:])>a[i]]+[[]])[0] ``` [Try it online!](https://tio.run/##PU7bDsIgDH33K4hPkBXjLlFHsv0I9qHGTUkcmo0HjdFfnwWNEOjp6elpb49wvvpy7pv9fKHhcCRBRlqyxmFmB7pLss6gwoxjlhvsr6Nwwnkxkj918tJ5SUq5Xr9d03wzVvwaY4NqGSCbWURl1ziHbgpTwynYPD4o@K8gXUY6B12CztepVkICdb2DTQUF6LoCvd3VP66I7J8TYFnPPjqa4iLuGqfFddNUsxB8bqPzQS6fL6Fb8XwtV6wbKMgogT4FpdT8AQ "Python 3 – Try It Online") ]
[Question] [ > > To find the *digital hardness* of an integer, take its binary representation, and count the number of times both a leading *and* trailing `1` can be removed until it either start or ends with a `0`. The total number of bits removed is its digital hardness. > > > That's quite a wordy explanation - so let's break it down with a worked example. For this example, we'll use the number 3167. In binary, this is: ``` 110001011111 ``` *(Note that, during the conversion to binary, you should make sure to strip leading zeroes)* It doesn't start or end with `0`, so we remove 1 pair of bits: ``` 1 1000101111 1 ``` And another: ``` 11 00010111 11 ``` But now there is a 0 at the beginning, so we can't remove anymore `1` pairs. In total, 4 bits we removed, and so **4** is the digital hardness of **3167.** However, for numbers that can be written as **2n-1** for positive **n** (i.e. contain only `1` in binary representation), 0 will never be reached, and so all the bits can be removed. This means that the hardness is simply the integer's bit length. --- ## The Challenge You task is to write a program or function which, given a non-negative integer `n >= 0`, determines its digital hardness. You can submit a full program which performs I/O, or a function which returns the result. Your submission should work for values of `n` within your language's standard integer range. --- ## Test Cases Please notify me if any of these are incorrect, or if you'd like to suggest any edge cases to add. ``` 0 -> 0 1 -> 1 8 -> 0 23 -> 2 31 -> 5 103 -> 4 127 -> 7 1877 -> 2 2015 -> 10 ``` Here's the ungolfed Python solution which I used to generate these test cases (not guaranteed to be bug-less): ``` def hardness(num) -> int: binary = bin(num)[2:] if binary.count('0') == 0: return num.bit_length() revbin = binary[::-1] return min(revbin.find('0'), binary.find('0')) * 2 ``` [Answer] # [Python](https://docs.python.org/), ~~76~~ ~~69~~ ~~68~~ ~~63~~ ~~62~~ ~~60~~ 57 bytes ``` f=lambda n,k=0:n>>k&(n&n>>k>n>>k+1)and(n&n+1>0)-~f(n,k+1) ``` [Try it online!](https://tio.run/nexus/python3#HY3BCsMgEETP7VfMxahkA2paEgLxXywihLSbEnrur9u1l7fDY5mpZX2m1yMnMO2rWzjGvTPctRsbem8T52Z6H50dvsXIp9hajhOMjWEcwRNmQhgJo0TvJPgwCeZJGJy/2@V6eZ8bf4xWt6yhZBF6iJoArcLfSLe19Qc "Python 2 – TIO Nexus") ### How it works This is a recursive solution that takes an input **n** and keeps incrementing **k** – starting at **0**– while both **LSBk(n)** (bit at index **k** from the right) and **MSBk(n)** (bit at index **k** from the left) are set. Once finished, it returns **k** if all of **n**'s bit are set and **2k** if not. Let's start by rewriting the lambda **f** as a named function **F**, with an auxiliary variable **t**. ``` def F(n, k = 0): t = n >> k return t & (n & t > t >> 1) and (n & (n + 1) > 0) + 1 + F(n, k + 1) ``` In each invocation of **F**, we first bit-shift **n** a total of **k** units to the right and store the result in **t**. This way, **LSB0(t) = LSBk(n)**, so **t** is odd if and only if **LSBk(n)** is set. Determining whether **MSBk(n)** is set is slightly trickier; this is what `n & t > t >> 1` achieves. To illustrate how it works, let's consider an integer **n = 1αβγδεζη2** of bit-length **8** and analyze the function call **F(n, 3)**, i.e., **k = 3**. We're trying to determine whether **MSB3(n) = γ** is set by examining the truth value of the comparison **(n & t > t >> 1) = (1αβγδεζη2 & 1αβγδ2 > 1αβγ2)**. Let's examine the involved integers. ``` MSB-index 012k4567 n 1αβγδεζη t 1αβγδ t >> 1 1αβγ ``` We claim that **γ = 1** if and only if **n & t > t >> 1**. * If **γ = 1**, then **n & t** has bit-length **5** while **t >> 1** has bit-length **4**, so **n & t > t >> 1**. This proves that **γ = 1** implies **n & t > t >> 1**. * If **n & t > t >> 1**, there are two options: either **γ = 1** or **γ = 0**. In the first case, there's nothing left to prove. In the second case, we have that **αβγδ2 ≥ n & t > t >> 1 = 1αβγ2**. Since **αβγδ2 > 1αβγ2**, we must have **MSB0(αβγδ2) ≥ MSB0(1αβγ2)**, meaning that **α = 1**. This way, **1βγδ2 > 11βγ2**, so we must have **MSB1(1βγδ2) ≥ MSB1(11βγ2)**, meaning that **β = 1**. In turn, this implies that **11γδ2 > 111γ2**. Remembering that **γ = 0** in the second case, we get the inequality **110δ2 > 11102**, which is false since **MSB2(110δ2) = 0 < 1 = MSB2(11102)**. Thus, only the first case is possible and **n & t > t >> 1** implies **γ = 1**. Summing up, if both **LSBk(n)** and **MSBk(n)** are set, **t** will be odd and **n & t > t >> 1** will be *True*, so **t & (n & t > t >> 1)** will yield **1**. However, if **LSBk(n)** or **MSBk(n)** is unset (or if both are), **t** will be even or **n & t > t >> 1** will be *False*, so **t & (n & t > t >> 1)** will yield **0**. Calling **F** with a single argument initializes **k = 0**. While the condition we've discussed earlier holds, the code after `and` is executed, which (among other things) recursively calls **F** with incremented **k**. Once **LSBk(n)** or **MSBk(n)** is unset, the condition fails and **F(n, k)** returns **0**. Each of the preceding **k** function calls adds **(n & (n + 1) > 0) + 1** to **F(n, k) = 0**, so **F(n)** returns **((n & (n + 1) > 0) + 1)k**. Now, if all bits of **n** are equal (i.e., if **n** is either **0** or all of its bits are set), **n + 1** will not have any bits in common with **n**, so **n & (n + 1) = 0** and **F(n)** returns **k**. However, if **n** has both set and unset bits, **n & (n + 1) > 0** and **F(n)** returns **2k**. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` BµQL××Ṛa\S ``` [Try it online!](https://tio.run/nexus/jelly#@@90aGugz@Hph6c/3DkrMSb4/9E9h9sfNa1x///fQEfBUEfBQkfByFhHwRjINDQAMgyNzIGEhTmQNDIwNAUA "Jelly – TIO Nexus") ### How it works ``` BµQL××Ṛa\S Main link. Argument: n B Binary; convert n to base 2. µ Begin a new, monadic chain. Argument: A (array of binary digits) Q Unique; deduplicate the digits. L Length; count the unique digits. × Multiply each digit by the result. ×Ṛ Multiply the results by reversed A. a\ Cumulative reduce by logical AND. This zeroes out all elements after the first zero. S Compute the sum of the result. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` Btv`6L&)}x@q ``` [Try it online!](https://tio.run/nexus/matl#@@9UUpZg5qOmWVvhUPj/v5GBoSkA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#U3L471RSlmDmo6ZZW@FQ@N/lf7SBgqGChYKRsYKxoYKhgbGCoZG5gqGFubmCkYGhaSwA). ### Explanation The code repeats each binary digit, and counts how many times it is possible to remove two outer ones. ``` B % Input number (implicit). Horizontal vector of binary digits tv % Duplicate and concatenate vertically ` % Do...while 6L&) % Flatten the array if needed (in column-major order), and split it % into two subarrays: one with the inner entries, and another % with the two outer entries. The latter will be used for deciding % if the loop continues or is exited } % Finally (execute before exiting the loop) x % Delete last subarray of inner entries @q % Push last iteration index minus 1 % End (implicit). The next iterarion is executed if the array at the % top of the stack is non-empty and only contains nonzero values. % Otherwise the loop is exited, executing the "finally" block first % Display (implicit) ``` [Answer] # Python, 82 bytes I feel like it can still be golfed, but I spent a while trying different methods and this was the shortest. ``` def f(n):b=bin(n)[2:];x=min(b.find('0'),b[::-1].find('0'));print(x<0)*len(b)or x*2 ``` [**Try it online**](https://tio.run/nexus/python2#VcvBCsIwDAbgu09R8LBmOEkzR0fnfJGxS9kKBa0yPPTtaypuw5zy5c@fptkJJwMY21sfeBnIjF3sHwx7dj5MssACTnYwplLjfoHutfjwlvGKUN5n/obnImJJyUkEwXMU1U3gwUm1UzHb/5RqWEnMWm1schdz/OUlk/RKndlq9tYlVM2PCtMH) Though this works similarly to the OP's Python program, I created this before the question was posted, after viewing the question in the Sandbox, which did not contain such a program. [Answer] ## Python 2, 66 bytes ``` s=bin(input())[2:].split('0') print len(min(s[-1],s[0]))<<1%len(s) ``` Splits the binary representation of the input into chunks of 1. Counts the number of 1's in the smaller of the first and last chunk, then doubles it, unless there's a single chunk that this would double-count. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~109~~ 106 bytes ``` $a=[convert]::ToString($args[0],2)-split0;(((($b=$a[0].length),$a[-1].length|sort)[0]*2),$b)[$a.count-eq1] ``` [Try it online!](https://tio.run/nexus/powershell#NYlBCoAgEAA/s4eMjCwoKHpF3cSDhVgQWrp16u@2l@Y2Mwn0KFfvHhNQ9f3sJwy7sxnoYKOsVFEzHs9jx2rICFhG0JTLwziLGyvIuPj1jT4go53XdBYmQZervx1ycwmVUmpE230 "PowerShell – TIO Nexus") Takes input `$args[0]`, uses the .NET call to `convert` it `toString` with base `2` (i.e., make it binary), then `-split`s that string on `0`s, stores that into `$a`. Important to note: the .NET call does not return leading zeros, so the first digit is always a `1`. There are thus two possibilities -- the binary string is all ones, or there was at least one zero. We differentiate between those with a pseudo-ternary indexed by `$a.count-eq1`. If the binary has at least one zero, the left case, we take the minimum of the length of the first `[0]` string of `1`s and the last `[-1]` string (found by `|sort` and then `[0]`). The shorter of those is the most pairs we could remove, so we multiply that by `2`. Note that if the original binary string ends in a `0`, like for input `8`, then the `[-1].length` will also be `0` (since it's an empty string), which when multiplied by `2` is still `0`. Otherwise, with the binary string all ones, we take just `$b` (which was previously set to be the length of the first `[0]` string, in this case, the entirety of the binary string). In either situation, that result is left on the pipeline and output is implicit. [Answer] ## JavaScript (ES6), 57 bytes ``` f= n=>n.toString(2).replace(/^(1*)(.*(\1))?$/,'$1$3').length ``` ``` <input oninput=o.value=1/this.value?f(+this.value):''><input id=o readonly> ``` Takes the binary and tries to match all `1s` or failing that an equal number of leading and trailing `1s`. [Answer] # [Retina](https://github.com/m-ender/retina), 48 bytes ``` .+ $* +`(1+)\1 $1o o1 1 m(+`^1(.*)1$ xx¶$1 x|^1$ ``` [**Try it online**](https://tio.run/nexus/retina#@6@nzaWixaWdoGGorRljyKVimM@Vb8hlyJWroZ0QZ6ihp6VpqMJVUXFom4ohV0VNnKHK//@GFubmAA) ### Explanation: ``` .+ # Convert to unary $* +`(1+)\1 # Convert to binary (but with `o` instead of `0` -- it's shorter) $1o o1 1 m(+`^1(.*)1$ # Replace pairs of surrounding ones with `xx` xx¶$1 x|^1$, # Count x's, including the possibility of a single remaining `1` ``` [Answer] ## C#, 133 bytes Function that returns hardness. Takes integer from argument. ``` int h(int b){var n=Convert.ToString(b,2);for(b=0;;){if(n[0]+n[n.Length-1]==98)n=n.Substring(1,n.Length-2);else break;b+=2;}return b;} ``` Well, today I found out `'1' + '1' = 98` in C#. [Answer] # C, ~~89~~ ~~88~~ 85 bytes Saved two bytes due to @FlipTack pointing out a useless declaration. Call `f()` with the number to test, the output is returned from the function. ``` t,h;f(l){for(t=l;t&&~t&1<<30;t*=2);for(h=0;t&1<<30&&l&1;t*=2,l/=2)++h;return h<<!!l;} ``` [Try it on ideone](http://ideone.com/SK3r6x). [Answer] ## JavaScript (ES6), ~~59~~ 58 bytes ``` f=(n,m=1<<30)=>m>n?f(n,m/2):m>1?n&m&&n&1&&2+f(n/2,m/4):n&1 ``` ### Test cases ``` f=(n,m=1<<30)=>m>n?f(n,m/2):m>1?n&m&&n&1&&2+f(n/2,m/4):n&1 console.log( [0, 1, 8, 23, 31, 103, 127, 1877, 2015].map( n => n + ' -> ' + f(n) ).join('\n') ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Eo2 BµŒg.ịṂS×Ç ``` [Try it online!](https://tio.run/nexus/jelly#AT0Awv//RW8yCkLCtcWSZy7hu4vhuYJTw5fDh//Dh@KCrFn//zAsMSw4LDIzLDMxLDEwMywxMjcsMTg3NywyMDE1 "Jelly – TIO Nexus") [Answer] # C, ~~137~~ ~~132~~ ~~122~~ ~~119~~ ~~117~~ ~~114~~ ~~98~~ ~~94~~ ~~92~~ ~~87~~ 85 Bytes Time to start golfing B-) ``` i,j;f(n){for(i=1<<30;i&~n;i/=2);for(j=0;n&i;n/=2,i/=4)j+=~n&1?i=0:2;return j-=n<1*j;} ``` Here's the proof ``` main() { printf("%d %d\n", 0, f(0)); printf("%d %d\n", 1, f(1)); printf("%d %d\n", 8, f(8)); printf("%d %d\n", 23, f(23)); printf("%d %d\n", 31, f(31)); printf("%d %d\n", 103, f(103)); printf("%d %d\n", 127, f(127)); printf("%d %d\n", 1877, f(1877)); printf("%d %d\n", 2015, f(2015)); printf("%d %d\n", 3167, f(3167)); } ``` and the output; ``` 0 0 1 1 8 0 23 2 31 5 103 4 127 7 1877 2 2015 10 3167 4 ``` [Answer] # [Java (OpenJDK)](http://openjdk.java.net/), ~~181~~ ~~156~~ 150 bytes ``` n->{int i=0;String s=n.toString(n,2);if(s.matches("1*"))i=s.length();else for(;!s.matches("(.*0)|(0.*)");s=s.substring(1,s.length()-1))i+=2;return i;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#TZBNb4MwDIbP8Cs8Tkk/IkI1tVLG7pM27dBj1UOggUaCgOJQbWL89iyITuvRr/08st0PRaNLKBuJCB9SGxjjCJ10IdTGKVvJUsG7bIuLhHGOwA6GvIVWrSx8UQGTiKM46hfRHb11@gJt0JGjs9rUpzNIWyOF8a6qIAdvtq/jbNR5KpY5wNww1y0FMZuMCl0RZK105VUhSfgqoVTnyBplanclVKgGFVSdJeLpYY6wVUp/SMpWNKECA4BDgYuWb/7xLQ@6dZ4Jq9xgDWgx@SgKF0Wz8m85/TJvf4eEXq/p8Rudalk3ONYHqWsMqdjDZ9hNNoP6rMgMnvSZUhqkUzx5n3ruDz7b@R33PN15nu09P@z3Pkv58y8 "Java (OpenJDK) – TIO Nexus") [Answer] # Mathematica, ~~63~~ 56 bytes ``` (2-Min[l=#~IntegerDigits~2])Min[Tr/@Split[l][[{1,-1}]]]& ``` **Explanation** ``` l=#~IntegerDigits~2 ``` Generate the base-2 representation of the input, wrapped with a `List`. Store that in `l` ``` (2-Min[...]) ``` If the min element of `l` is 1, output 1. If not, output 2. Multiply this by... ``` Split[l] ``` Split `l` into runs. ``` ... [[{1,-1}]] ``` Take the first and the last element. ``` Tr/@ ... ``` Take the total of both. ``` Min[ ... ] ``` Find the smaller between the two. (Multiply the first result (1 or 2) with this result). [Answer] # Octave, ~~56~~ 54 bytes ``` @(n)cummin(d=dec2bin(n)-48)*cummin(flip(d))'*2^!all(d) ``` [Try it Online!](https://tio.run/#IAfFY) Explanation: ``` d=dec2bin(n)-48 ``` binary representation of `n` ``` cumd= cummin(d); cumfd = cummin(flip(d)); ``` Take cumulative min of `d` and cumulative min of flipped `d` ``` res = cumd * cumfd '; ``` do matrix multiplication ``` out = res*2^!all(d) ``` multiply with 2 if all of digits is 1; [Answer] # Pyth, 18 bytes ``` ?*FJjQ2lJyhSxR0_BJ ``` A program that takes input of an integer and prints the result. [Test suite](http://pyth.herokuapp.com/?code=pQp%22+-%3E+%22%0A%3F%2aFJjQ2lJyhSxR0_BJ&test_suite=1&test_suite_input=0%0A1%0A8%0A23%0A31%0A103%0A127%0A1877%0A2015&debug=0) (First line for formatting) **How it works** ``` ?*FJjQ2lJyhSxR0_BJ Program. Input: Q ? If F reducing jQ2 the binary representation of Q as a list J (store in J) * by multiplication is truthy: lJ Yield len(J) Else: hS Yield the minimum xR0 of the first index of zero _BJ in J and its reverse y * 2 Implicitly print ``` [Answer] # APL, 26 bytes ``` +/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢ ``` Test cases: ``` ( +/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢ ) ¨ 0 1 8 23 31 103 127 1877 2015 0 1 0 2 5 4 7 2 10 ``` Explanation: ``` +/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢ ⊢ input 2⊥⍣¯1 convert to binary representation ( ) ( ⊢ ¨⌽) for each bit and its matching bit on the other side ( ∧) take the logical and of both bits, , make a list of both bits, ∧ then take the and of the list and the and ∊ flatten the resulting array ≢↑ take only the first N bits, where N is the length of the original list of bits ∧\ take a running logical and (leaving only the starting ones) +/∘ sum those ``` [Answer] # J, 22 bytes ``` (#<.2*(<.&(#.~)|.))@#: ``` This is based on the neat trick learned from this [challenge](https://codegolf.stackexchange.com/questions/98730/count-trailing-truths). [Try it online!](https://tio.run/nexus/j#BcHRCYAwDAXAf6d4WJCkSEhSpKVUcBex@OcC4ur1bnTsFRSaeKQmCwX5@BXmI9TpOu8HtEqflaEwFHhCMpgmmGdYyRmuto3xAw) ## Explanation ``` (#<.2*(<.&(#.~)|.))@#: Input: integer n #: Binary digits of n ( )@ Operate on those digits D |. Reverse D <. Take the minimum of &(#.~) the "trailing truths" of D and reverse(D) 2* Multiply by 2 # The length of D <. Minimum of length and the previous result ``` [Answer] # PHP, ~~83~~ 74 bytes 3+6 bytes saved by Jörg ``` <?=(~$s=decbin($argn))[$a=strspn($s,1)]?min($a,strspn(strrev($s),1))*2:$a; ``` takes input from STDIN; run with `-nR`. **breakdown** ``` <?= # print ... (~ $s=decbin($argn) # $s = binary representation of input )[ $a=strspn($s,1) # $a = number of leading `1`s ] # if $s has more than $a digits, ? min($a, # 2. minimum of $a and strspn(strrev($s),1) # 1. number of trailing `1`s )*2 # 3. *2 : $a # else $a (==strlen) ``` [Answer] # JavaScript (ES6), 83 Bytes ``` f=x=>(y=x.toString(2),y.match(/^1*$/)?y:([s,e]=y.match(/^1*|1*$/g),s<e?s:e)).length ``` Ungolfed: ``` function f(n) { var binStr = n.toString(2); if(binStr.match(/^1*$/)) { // If binary representation is all 1s, return length of binary return binStr.length; } else { // Grab the starting and ending 1s in the binary representation var [start1s, end1s] = binStr.match(/^1*|1*$/g); var startHardness = start1s.length; var endHardness = end1s.length; return Math.min(startHardness, endHardness); } } ``` [Answer] ## Mathematica, 62 bytes ``` (h=0;#~IntegerDigits~2//.{{1,m___,1}:>(h+=2;{m}),{1}:>h++};h)& ``` Pure function where `#` represents the first argument. `(h=0;...;h)&` sets `h=0`, does a bunch of stuff `...`, then returns `h` (the hardness). Let's look at the bunch of stuff: ``` #~IntegerDigits~2 Binary representation of the input //. Apply the following list of rules repeatedly until there is no change { Start of the list of rules {1,m___,1} If you see a list starting and ending with 1 with the sequence m (possibly empty) in between :>(h+=2;{m}), replace it with just {m} after incrementing h twice. {1} If you see the singleton list {1} :>h++ replace it with h, then increment h. } End of the list of rules ``` Thanks to Greg Martin for introducing me to [this trick](https://codegolf.stackexchange.com/a/105426/61980). [Answer] # [Haskell](https://www.haskell.org/), ~~94~~ 92 bytes ``` b 0=[] b n=mod n 2:b(div n 2) h n|(c,_:_)<-span(>0)$zipWith(*)n$reverse n=c++c|1<3=n sum.h.b ``` [Try it online!](https://tio.run/nexus/haskell#FcsxDoMgFADQvaf4AwPUlqBNFyu9RIcOTWMESWDgSwA1Md6d2u0tzw8OQUKY8ytH4JDstAKBNHtuuTrUiPpeFAj5@T4UoPTTCAhNq@jolr/YyQLuVF/6tmfdNYUB6VMwsrnwdtnSM0MSzWJiMkfXVaX3urtJLOUH "Haskell – TIO Nexus") Usage: ``` Prelude> sum.h.b $ 3167 4 ``` **Explanation:** `b` converts a number to binary and returns a list of zero and ones with the least significant bit first. In `h`, this list is reversed and element-wise multiplied with the original list, then `span(>0)` splits after the initial `1`s: ``` b 3167 = [1,1,1,1,1,0,1,0,0,0,1,1] = n reverse n = [1,1,0,0,0,1,0,1,1,1,1,1] = m zipWith(*)n m = [1,1,0,0,0,0,0,0,0,0,1,1] = z span(>0) z = ([1,1],[0,0,0,0,0,0,0,0,1,1]) ``` The resulting tuple is pattern matched with `(c,_:_)` where `_:_` matches any non-empty list, so `c = [1,1]`. Because the bytes are removed at front and back, `c++c = [1,1,1,1]` is returned and finally summed up to yield the *digital hardness*. If the second list of the tuple is empty, then the binary representation contains ones only, and the number of ones is the digital hardness. With the pattern matching failed `h` returns just `n`, which is again summed up. [Answer] # Perl, 61 bytes ``` sub f{$_=sprintf('%b',pop);length(/0/?/^(1+).*\1$/&&$1x2:$_)} ``` The heart of this is the regex `/^(1+).*\1$/` where 2 times the length of `$1` is the answer. Rest of the code is overhead and dealing with the all 1's special case. [Answer] # PHP, 65 Bytes ``` <?=strlen(preg_filter('#^(1*)(.*(\1))?$#',"$1$3",decbin($argn))); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/36911bed84d77ca7eeaa4df7270accd6bba87301) [Answer] ## CJam, 14 bytes ``` ri2b_0#\W%0#e< ``` Explanation: ``` ri e# Read integer: | 3167 2b e# Convert to binary: | [1 1 0 0 0 1 0 1 1 1 1 1] _ e# Duplicate: | [1 1 0 0 0 1 0 1 1 1 1 1] [1 1 0 0 0 1 0 1 1 1 1 1] 0# e# Index of first 0: | [1 1 0 0 0 1 0 1 1 1 1 1] 2 \ e# Swap: | 2 [1 1 0 0 0 1 0 1 1 1 1 1] W% e# Reverse: | 2 [1 1 1 1 1 0 1 0 0 0 1 1] 0# e# Index of first 0: | 2 5 e< e# Minimum: | 2 ``` ]
[Question] [ Your challenge is to take some source code as input, and output which programming language it is written in. For example, you could have the input ``` class A{public static void main(String[]a){System.out.println("Hello, World!");}} ``` And output ``` Java ``` Your two main goals are **diversity** (how many programming languages you can detect) and **accuracy** (how good you are at detecting these languages). For polyglots (programs valid in more than one language), you can decide what to do. You could just output the language that your program thinks is more likely, or you could output an error, or you could output an array of possible choices (which would probably get more upvotes than just an error!). This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), because it would be very difficult to specify a different objective winning criterion. Voters, please vote on how many languages it can detect and how accurate it is. [Answer] # 234 text formats - Unix Shell (not all of them languages - I need to count them carefully) ``` file $1 ``` I hesitate to post this somewhat smart-a$$ answer, but I don't see anything in the rules banning it and the `file` shell utility really does do a good job of this. e.g: ``` $ file golfscript.rb golfscript.rb: Ruby module source, ASCII text $ file template.c template.c: ASCII C program text $ file adams.sh adams.sh: Bourne-Again shell script, ASCII text executable $ ``` Furthermore you can use the `-k` option to "keep going" when testing a polyglot: ``` -k, --keep-going Don't stop at the first match, keep going. Subsequent matches will be have the string ‘\012- ’ prepended. (If you want a new‐ line, see the -r option.) ``` Also, the `-l` option will give you an idea of how good the algorithm is for differing languages: ``` $ file -l | grep shell unknown, 0: Warning: using regular magic file `/etc/magic' Strength = 280 : shell archive text [application/octet-stream] Strength = 250 : Tenex C shell script text executable [text/x-shellscript] Strength = 250 : Bourne-Again shell script text executable [text/x-shellscript] Strength = 240 : Paul Falstad's zsh script text executable [text/x-shellscript] Strength = 240 : Neil Brown's ash script text executable [text/x-shellscript] Strength = 230 : Neil Brown's ae script text executable [text/x-shellscript] Strength = 210 : Tenex C shell script text executable [text/x-shellscript] Strength = 210 : Bourne-Again shell script text executable [text/x-shellscript] Strength = 190 : Tenex C shell script text executable [text/x-shellscript] Strength = 190 : Bourne-Again shell script text executable [text/x-shellscript] Strength = 180 : Paul Falstad's zsh script text executable [text/x-shellscript] Strength = 150 : Tenex C shell script text executable [text/x-shellscript] Strength = 150 : Bourne-Again shell script text executable [text/x-shellscript] Strength = 140 : C shell script text executable [text/x-shellscript] Strength = 140 : Korn shell script text executable [text/x-shellscript] Strength = 140 : Paul Falstad's zsh script text executable [text/x-shellscript] Strength = 130 : POSIX shell script text executable [text/x-shellscript] Strength = 130 : Plan 9 rc shell script text executable [] $ ``` This is `file-5.09` (on Ubuntu 12.04) [Answer] # 18 programming languages, 1002 bytes, accuracy: test for yourself :) (yep I know this is not code golf, but for the fun of it) The program searches for iconic code snippets, the checks are ordered in a way that the most clear checks are at the top and programming languages embedded in other programming languages are below (e.g. HTML in PHP). This obviously fails for programs like `System.out.println('<?php');` ``` t = (p) -> h = (x) -> -1 != p.indexOf x s = (x) -> 0 == p.indexOf x if h "⍵" then "APL" else if h "<?php" then "PHP" else if h("<?xml") and h "<html" then "XHTML" else if h "<html" then "HTML" else if h "<?xml" then "XML" else if h("jQuery") or h "document.get" then "JavaScript" else if h "def __init__(self" then "Python" else if h "\\documentclass" then "TeX" else if h("java.") or h "public class" then "Java" else if s("SELE") or s("UPDATE") or s "DELE" then "SQL" else if /[-\+\.,\[\]\>\<]{9}/.test p then "Brainfuck" else if h "NSString" then "Objective-C" else if h "do |" then "Ruby" else if h("prototype") or h "$(" then "JavaScript" else if h "(defun" then "Common Lisp" else if /::\s*[a-z]+\s*->/i.test p then "Haskell" else if h "using System" then "C#" else if h "#include" if h("iostream") or h "using namespace" then "C++" else "C" else "???" program = "" process.stdin.on 'data', (chunk) -> program += chunk process.stdin.on 'end', -> console.log t program ``` Usage on node: `coffee timwolla.coffee < Example.java` Demo ([Online-Demo on JSFiddle](http://jsfiddle.net/TimWolla/wkJKY/)): ``` [timwolla@~/workspace/js]coffee puzzle.coffee < ../c/nginx/src/core/nginx.c C [timwolla@~/workspace/js]coffee puzzle.coffee < ../ruby/github-services/lib/service.rb Ruby [timwolla@~/workspace/js]coffee puzzle.coffee < ../python/seafile/python/seaserv/api.py Python ``` [Answer] # Bash — about ~~50~~ 35 bytes per compilable language Trick is to just compile, then you don't have to worry about linking errors from missing libraries, and it's more forgiving if you just have code snippets. Thanks to Shahbaz for shorter forms! ``` gcc -c $1 && (echo C; exit 0) g++ -c $1 && (echo C++; exit 0) gpc -c $1 && (echo Pascal; exit 0) gfortran -c $1 && (echo Fortran; exit 0) ``` etc... [Answer] This answer is a proof of concept, that will not likely receive any more work from myself. It falls short in several ways: * The output is not exactly as the question requests, but close enough and could easily be modified to produce the exact output required. * There are several ways to make the code perform better and/or better ways to represent the data structures. * and more The idea is to set a list of keywords/characters/phrases that can identify a specific language and assign a score to that keyword for each language. Then check the source file(s) for these keywords, and tally up the scores for each language that you find keywords for. In the end the language with the highest score is the likely winner. This also caters for polyglot programs as both (or all) the relevant languages will score high. The only thing to add more languages is to identify their "signatures" and add them to the mapping. You can also assign different scores to different keywords per language. For example, if you feel `volatile` is used more in Java than in C, set the score for `volatile` keyword to 2 for Java and 1 for C. ``` public class SourceTest { public static void main(String[] args) { if (args.length < 1) { System.out.println("No file provided."); System.exit(0); } SourceTest sourceTest = new SourceTest(); for (String fileName : args) { try { sourceTest.checkFile(fileName); } catch (FileNotFoundException e) { System.out.println(fileName + " : not found."); } catch (IOException e) { System.out.println(fileName + " : could not read"); } } System.exit(0); } private Map<String, LanguagePoints> keyWordPoints; private Map<LANGUAGES, Integer> scores; private enum LANGUAGES { C, HTML, JAVA; } public SourceTest() { init(); } public void checkFile(String fileName) throws FileNotFoundException, IOException { String fileContent = getFileContent(fileName); testFile(fileContent); printResults(fileName); } private void printResults(String fileName) { System.out.println(fileName); for (LANGUAGES lang : scores.keySet()) { System.out.println("\t" + lang + "\t" + scores.get(lang)); } } private void testFile(String fileContent) { for (String key : keyWordPoints.keySet()) { if (fileContent.indexOf(key) != -1) { for (LANGUAGES lang : keyWordPoints.get(key).keySet()) { scores.put(lang, scores.get(lang) == null ? new Integer(1) : scores.get(lang) + 1); } } } } private String getFileContent(String fileName) throws FileNotFoundException, IOException { File file = new File(fileName); FileReader fr = new FileReader(file);// Using 1.6 so no Files BufferedReader br = new BufferedReader(fr); StringBuilder fileContent = new StringBuilder(); String line = br.readLine(); while (line != null) { fileContent.append(line); line = br.readLine(); } return fileContent.toString(); } private void init() { scores = new HashMap<LANGUAGES, Integer>(); keyWordPoints = new HashMap<String, LanguagePoints>(); keyWordPoints.put("public class", new LanguagePoints().add(LANGUAGES.JAVA, 1)); keyWordPoints.put("public static void main", new LanguagePoints().add(LANGUAGES.JAVA, 1)); keyWordPoints.put("<html", new LanguagePoints().add(LANGUAGES.HTML, 1)); keyWordPoints.put("<body", new LanguagePoints().add(LANGUAGES.HTML, 1)); keyWordPoints.put("cout", new LanguagePoints().add(LANGUAGES.C, 1)); keyWordPoints.put("#include", new LanguagePoints().add(LANGUAGES.C, 1)); keyWordPoints.put("volatile", new LanguagePoints().add(LANGUAGES.JAVA, 1).add(LANGUAGES.C, 1)); } private class LanguagePoints extends HashMap<LANGUAGES, Integer> { public LanguagePoints add(LANGUAGES l, Integer i) { this.put(l, i); return this; } } } ``` [Answer] # Just a few broad generalizations. I think it's fairly accurate. This is Ruby btw. Takes (multiline) input from stdin. ``` puts case $<.read when /\)\)\)\)\)/ "Lisp" when /}\s+}\s+}\s+}/ "Java" when /<>/ "Perl" when /|\w+|/ "Ruby" when /\w+ :- \w+ \./ "Prolog" when /^[+-<>\[\],.]+$/ "brainfuck" when /\[\[.*\]\]/ "Bash" when /~]\.{,/ "golfscript" end ``` [Answer] # Javascript - 6 languages - high accuracy Current Languages: Java, C, HTML, PHP, CSS, Javascript I work on the principle that whenever an input satisfies a criteria, it is given a score, and based on that score results are given. ### Features: * No built-in functions that determine language type used. * Does not straightaway declare the input text is `x` language on seeing a keyword. * Suggests other probable languages also. Should you feel that any of your inputs of the programs (that I have done till now) are not caught or get invalid results, then please report and I'd be happy to fix them. ### Sample Input 1: ``` class A{public static void main(String[]a){System.out.println("<?php");}} ``` ### Sample Output 1: ``` My program thinks you have : Java with a chance of 100% Php with a chance of 25% ---------------- ``` ### Explanation: This should have failed the program and I would have printed `PHP`, but since my program works on the basis of scores, nothing fails and it easily identifies Java in the first place, followed by other possible results. ### Sample Input 2: ``` class A{public static void main(String[]a){System.out.println("HelloWorld!");}} ``` ### Sample Output 2: ``` Java ---------------- ``` ### Sample Input 3: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` ### Sample Output 3: ``` Language not catched! Sorry. ---------------- ``` ### The code: ``` // Helper functions String.prototype.m = function(condition){ return this.match(condition); }; String.prototype.capitalize = function(){ return this[0].toUpperCase() + this.substr(1); }; function getFuncName(func){ var temp = func.toString(); temp = temp.substr( "function ".length); temp = temp.substr( 0, temp.indexOf("(")); return temp.capitalize(); } // Get input var lang_input = prompt("Enter programming language"); // Max score of 4 per lang function java(input){ var score = 0; score += input.m(/class[\s\n]+[\w$]+[\s\n]*\{/) ? 1 : 0; score += input.m(/public[\s\n]+static[\s\n]+void[\s\n]+main[\s\n]*/) ? 1 : 0; score += input.m(/\}[\s\n]*\}[\s\n]*$/) ? 1 : 0; score += input.m(/System[\s\n]*[.][\s\n]*out/) ? 1 : 0; return score; } function c(input){ var score = 0; // if java has passsed if(checks[0][1] >= 3)return 0; score += input.m(/^#include\s+<[\w.]+>\s*\n/) ? 1 : 0; score += input.m(/main[\s\n]*\([\s\n]*(void)?[\s\n]*\)[\s\n]*\{/) ? 1 : 0; score += input.m(/printf[\s\n]+\(/) || input.m(/%d/) ? 1 : 0; score += input.m(/#include\s+<[\w.]+>\s*\n/) || input.m(/(%c|%f|%s)/) ? 1 : 0; return score; } function PHP(input){ var score = 0; score += input.m(/<\?php/) ? 1 : 0; score += input.m(/\?>/) ? 1 : 0; score += input.m(/echo/) ? 1 : 0; score += input.m(/$[\w]+\s*=\s*/) ? 1 : 0; return score; } function HTML(input){ var score = 0; // if php has passed if(checks[2][1] >= 2) return 0; score += input.m(/<!DOCTYPE ["' \w:\/\/]*>/) ? 1 : 0; score += input.m(/<html>/) && input.m(/<\/html>/) ? 1 : 0; score += input.m(/<body>/) && input.m(/<\/body/) ? 1 : 0; score += input.m(/<head>/) && input.m(/<\/head>/) ? 1 : 0; return score; } function javascript(input){ var score = 0; score += input.m(/console[\s\n]*[.][\s\n]*log[\s\n*]\(/) ? 1 : 0; score += input.m(/[\s\n]*var[\s\n]+/) ? 1 : 0; score += input.m(/[\s\n]*function[\s\n]+[\w]+[\s\n]+\(/) ? 1 : 0; score += input.m(/document[\s\n]*[.]/) || ( input.m(/\/\*/) && input.m(/\*\//) ) || ( input.m(/\/\/.*\n/) )? 1 : 0; return score; } function CSS(input){ var score = 0; score += input.m(/[a-zA-Z]+[\s\n]*\{[\w\n]*[a-zA-Z\-]+[\s\n]*:/) ? 1 : 0; // since color is more common, I give it a separate place score += input.m(/color/) ? 1 : 0; score += input.m(/height/) || input.m(/width/) ? 1 : 0; score += input.m(/#[a-zA-Z]+[\s\n]*\{[\w\n]*[a-zA-Z\-]+[\s\n]*:/) || input.m(/[.][a-zA-Z]+[\s\n]*\{[\w\n]*[a-zA-Z\-]+[\s\n]*:/) || ( input.m(/\/\*/) && input.m(/\*\//) ) ? 1 : 0; return score; } // [Langs to check, scores] var checks = [[java, 0], [c, 0], [PHP, 0], [HTML, 0], [javascript, 0], [CSS, 0]]; //Their scores // Assign scores for(var i = 0; i < checks.length; i++){ var func = checks[i][0]; checks[i][1] = func(lang_input); } // Sort the scores checks.sort(function(a,b){ return b[1] - a[1]; }); var all_zero = true; function check_all_zero(index){ if(checks[index][1] > 0){ all_zero = false; return 0; } // someone is above zero // check next index only if it defined, else return zero if(checks[index + 1]) check_all_zero(index + 1); } check_all_zero(0); if(all_zero){ console.log("Language not catched! Sorry."); }else { var new_arr = []; // temp checks.map(function(value, index){ if(value[1] > 0){ var temp = [getFuncName(value[0]), value[1]]; new_arr.push(temp); } }); checks = new_arr.slice(0); // array copy, because of mutation if(checks.length === 1){ console.log(checks[0][0]); }else{ console.log("My program thinks you have :"); checks.map(function(value){ var prob = (value[1]/4 * 100); console.log(value[0] + " with a chance of " + prob + "%"); }); } } // Main else block finish console.log("----------------"); ``` [Answer] # Python, 4 languages, can you test how accurate this is? Sorry, but you need to put the source code in a file. ``` import sys file = sys.argv[1] def detect(code: str): python_keys = {"#": 1, "print": 2, "def": 5, "with": 5, "in": 2, "tuple": 5, ":": 1.5, "except":5, "str": 1.5, "complex": 4, "_": 2, "match": 3} javascript_keys = {"{": 3, "function": 4, "=>": 5, "catch": 2.5, "switch": 2, "var": 5, "let": 5, "const": 5, "//": 2} c_keys = {"#include": 5, "#pragma once": 5, "#ifdef": 4.5, "#ifndef": 4.5, "*": 2, "size_t": 3, "{": 4, "struct": 5, "switch": 2, "//": 2} html_keys = {"<!--": 5, "<!DOCTYPE":5, "html": 5, "href": 5, ".css": 4, "</": 3, "http": 3} langs = ["Python", "JavaScript", "C", "HTML"] scores = {lang: 0 for lang in langs} for lang in langs: score = 0 for key, value in eval(f"{lang.lower()}_keys").items(): score += value * code.count(key) scores[lang] = score return scores with open(file) as file: results = detect(file.read()) if "-l" in sys.argv: summed = sum(results.values()) for lang, score in results.items(): print(f"{lang}: {100 * score / summed}% likely") else: max_score = max(results.values()) print(*filter(lambda lang: results[lang] == max_score, results.keys()), sep=", ") ``` This can also receive the `-l` flag to list how likely each language is. Here is it checking itself with the `-l` flag enabled (on powershell, current directory hidden for obvious reasons): ``` >py langdetect.py langdetect.py -l Python: 49.022346368715084% likely JavaScript: 18.01675977653631% likely C: 23.18435754189944% likely HTML: 9.776536312849162% likely ``` ]
[Question] [ # Task Your task is to draw these beautiful oak trees: ``` 1 -> @@@ @@@@@ @|.|@ _|_|_ 2 -> @@ @@@@@@ @@@@@@@@ @@| .|@@ | | __|__|__ 3 -> @@@@@ @@@@@@@@@ @@@@@@@@@@@ @@@| |@@@ @| .|@ | | ___|___|___ 4 -> @@ @@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@| |@@@@ @@| .|@@ | | | | ____|____|____ 5 -> @@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@@@@| |@@@@@ @@@| .|@@@ | | | | | | _____|_____|_____ 6 -> @@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@| |@@@@@@ @@@@| |@@@@ @| .|@ | | | | | | ______|______|______ ``` (that one sandbox commenter felt were similar to women with curly hair!) The trees are allowed to be surrounded by any extra whitespace your solution creates *as long as that doesn't break the tree*, of course. # Algorithm As per the examples above, we take `n` to represent the width of the trunk and the specs of the tree will be given in terms of that. Given `n`: 1. the height of the trunk is `n + 1`; 2. the width of the trunk in space characters is `n`; 3. the top row of the trunk is `n` times the character `@`, followed by `|`, `n` times the space character , another vertical pipe `|` and then `n` times `@`. 4. from the reference row up to the top of the crown, we only use `@` as follows: * there is one row with the same width as the reference row and each subsequent row above is shortened by one `@` than the previous shortening; 5. from the reference row downwards, we chop 2 `@` from each side and then each row we go down, we chop one more `@` than the previous row; 6. the last trunk row that is surrounded by a `@` has a `.` immediately to the left of the right vertical pipe `|`; 7. the bottom most row has the underscore `_` in all the tree width, except where the trunk vertical pipes `|` are. [Answer] # JavaScript (ES8), ~~215 ... 199~~ 197 bytes ``` f=(n,k=(W=3*n+2)**.5-.5|0,x=.5-k-(W-n)**.5,R=(n,k)=>S=''.padEnd(n,'.@_'[k]))=>k+n+2?(w=k*-~k/2,k<0?(x>0?s=R(n,k+n+3):R(w+=~k,s=R(n-1)+R(1,~~x))+R(n-w,1))+`|${s}|`+S:R(w)+R(W-w*2,1))+` `+f(n,k-1):'' ``` [Try it online!](https://tio.run/##XYzNboJQEIX3PsVdNLn/FDB2oY500xfABYumKUTE2GvmGmkKicir07l019V8Od@Z81X9VO3hdr5@W/T1cZoaEGgciAKWCnUqlYpWNloNsemByFlRWJxTk89VCbs9cB5dq/oNa0p49PrJ392HJOM0bWSiA6fs6J5T47ZxJvpdnLWQh2/yS7nORadhdGYObSJ1LhIzjr0MhLYzCVE5PN3bx1DqfegHU9hOpX9uUeom7NHzmvOp8TeBDFiyYci2dF8ItJbsvmDs4LH1l2N08SfBETjTDOXmn6A1SeFj@gU "JavaScript (Node.js) – Try It Online") or [Test it online!](https://tio.run/##jVPBjtowEL3zFbOoku04TpPQvQCGvZRbL3Dg0FZLREI3NXWQk22QFvLrdCZZFqqiVU8ev/fmvZEz@Zn8Tsq1y3eVskWanbZZBTPQYEFP4KUHQEDug/GhrBwSjI0Q3RSOG7yFPuR0jMCABzGMYYCnBQkxQVKDlLlojeBsACxw2S5LKm4ECtnD2/2tF1Tn1/LfLMMDmyn4@G94REljsLcD5buJlpJa7EAhV0piImIwSmKOhIhCYEoiGKKQXfXdcsS5zxO/DsKv/W@nvoOin7ik0DwKcjG62LPHmz7/h75O67Lq2dnutY@njebWN5ov9cCzMhaeF9yr4P4Q@nuNlVF8qWyL@vNWKvRkoRkLdkn62aaIsODhkX013wUyRqLHlNfaeKoxH2PfjMMp30/Caann1I38QAznvJa6MX4LqkjIOY/8ptkLqqyq/Qir1eHDS3k8rOSC9MQsVe3FHddbyQ35YfOQsRPti@0WxcJYQxyGIZX4ZKrhX5LqKXCJTYtfXODSfRLd@uQbvqG3udMaZlicl2pd2LLYZsG2@MH7syTfZiltJP0x0MeXtO0n@VtHRjfg2QWunlxRQz9zrnD9bm2OvWstWzyv11lZ3jFx@gM) against an ungolfed, straightforward implementation ### How? We define \$H\$ as the height of the upper part of the crown (where the width is increasing) and \$h\$ as the height of the lower part (where the width is decreasing). *Example for \$n=6\$:* [![heights](https://i.stack.imgur.com/qmYSy.png)](https://i.stack.imgur.com/qmYSy.png) We have: $$H\_n=\left\lfloor\sqrt{3n+2}+\frac{1}{2}\right\rfloor$$ and: $$h\_n=\left\lfloor\sqrt{2n+2}-\frac{1}{2}\right\rfloor$$ By computing these values beforehand, we can draw the tree from top to bottom with a single loop, which is implemented here as a recursive function. The total height of the tree is \$H\_n+n+1\$. We use a counter \$k\$ going from \$H\_n-1\$ to \$-n-1\$. ``` 3 | ......@@@@@@@@ | upper crown 2 | ...@@@@@@@@@@@@@@ | 1 | .@@@@@@@@@@@@@@@@@@ | 0 | @@@@@@@@@@@@@@@@@@@@ | ---+----------------------+------------- -1 | @@@@@@| |@@@@@@ | lower crown -2 | ..@@@@| |@@@@ | -3 | .....@| .|@ | ---+----------------------+------------- -4 | | | | trunk only -5 | | | | -6 | | | | ---+----------------------+------------- -7 | ______|______|______ | roots ``` The number of leading spaces for the upper part of the crown is the \$k\$-th triangular number: $$T\_k=\frac{k\times(k+1)}{2}$$ The number of leading spaces for the lower part of the crown is given by: $$\frac{(k+1)\times(k-2)}{2}=T\_k-k-1$$ ### Commented ``` f = ( // f is a recursive function taking: n, // n = input k = (W = 3 * n + 2) // W = 3n + 2 = total width of the tree ** .5 - .5 | 0, // k = counter, initialized to floor(sqrt(W) - 1/2) x = .5 - k - (W - n) ** .5, // x = 1/2 - k - sqrt(W - n) R = (n, k) => // R is a helper function returning and saving in S: S = // a character identified with k ('.', '@', '_' or ''.padEnd(n, '.@_'[k]) // a space) repeated n times ) => // k + n + 2 ? // if k is not equal to -n - 2: ( w = k * -~k / 2, // initialize w to the k-th triangular number k < 0 ? // if k is negative: ( x > 0 ? // if x is positive (trunk only or roots): s = // set s to: R(n, k + n + 3) // '_' * n if k = -n - 1, or space * n otherwise : // else (lower crown): R( // append ... w += ~k, // ... w - k - 1 spaces s = R(n - 1) + // and set s to n - 1 spaces followed by R(1, ~~x) // '.' if floor(x) = 0, or another space otherwise ) + // R(n - w, 1) // append '@' * (n - w) ) + // `|${s}|` + // append s surrounded by '|' characters S // append S : // else (upper crown): R(w) + // append w spaces R(W - w * 2, 1) // append '@' * (W - 2w) ) + // `\n` + // append a line-feed f(n, k - 1) // append the result of a recursive call with k - 1 : // else: '' // stop recursion ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~249~~ \$\cdots\$ ~~211~~ 210 bytes Saved ~~6~~ \$\cdots\$ ~~17~~ 18 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! ``` def f(n): i=j=1 t,y,e,w,s,x,S=[],n*'_','|',0,3*n+2,n*' ',n while s>1:t=[w*' '+s*'@']+t;s-=2*i;w+=i;i+=1 while S>0:j+=1;t+=[x[S:]+S*'@'+e+x[1:]+'. '[S>j]+e+S*'@'];S-=j return t+[(x+e)*2]*(n-j+1)+[(y+e)*2+y] ``` [Try it online!](https://tio.run/##jVTbjqIwGL7vU/xhLji0mkH3kEBq@gS7F1wSYjRTZsoaNNCNuss@u9sDWJhhdkcB@398/Q5GPF3ly7Fe325PvIQyqMMEgaAVjRFIciWcnElLLiSjeUHqyN/6xO988kjWUY1XGgGf1AjOL@LAod3EiaT5WaO4jXzmF1im7YKuIpGeMRWpwFrZsrPNY1KpOZWY5pc8Swqc6T2Y40seq8lfgp9nm6pQiLlTpNmCVggaLn82NUicBxfMw2hVREG9qHAcKuRqEHwtbpK3sgUKv1GcQI48YIx5BHmMDYtu2ZnFtlNvtSgIWlkqgKUAc2w2Xneg9loKdOowMkpFH1Zp7ZTYROyVnhuVDnQDF/TY5wPjMZhoC3Nan0@DjwsNMFYG9tZqBtEOxn7wN4hraTPYENNp2@exF5vq8yQVexNsLttsvDFoLG3Ge0gLLt33NkRzSf81b@@5@6uN/@V1/NkG75R4r8cEtxn6Mq7NBL8H7lH3c7iXGLX6D7IdlRw@bNk/6KE8NiBA1NDs6mcexOSr@id40HuleoLKQIR20ry95sn@tn6dGlHLYB@6DebRy0XxkU2ihN3hEJiT0r1h74jh/xKnQHuTQS8MZ4KGidXyvv/wQsQPLR@Ab0cJGrz9BQ "Python 3 – Try It Online") **Before golfing** ``` def f(n): w=s=3*n+2 t=[] i=1 while s>1: t=[' '*((w-s)//2)+'@'*s]+t s-=2*i i+=1 b=s=n i=2 while s>0: t+=[(n-s)*' '+s*'@'+'|'+~-n*' '+'. '[s-i>0]+'|'+s*'@'] s-=i b-=1 i+=1 while b: t+=[n*' '+'|'+n*' '+'|'] b-=1 t+=[n*'_'+'|'+n*'_'+'|'+n*'_'] return t ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~78~~ 71 bytes ``` Nθ≔×¹·⁵⊕θηW›ηⅈ«↑P×⁻ηⅈ@Mⅉ←»J⁰θ×θ_P×⊘⁺³θ_↑⊕θ⸿W›θⅈ«P×⁻θⅈ@M⁺²ⅉ¹»Jθⅉ↗‖OO﹪θ². ``` [Try it online!](https://tio.run/##bZBRS8MwFIWf118R@pRAHG6iD/NFn3RidYwJDgSp3d0aSNMkTeqD@NvjbdZJoXsK3HvOyfluUea2qHMZwlJp71589QWWGnab3DeNOCi6ERU0dDa95mSpCgsVKAc7VDBOSpR9l0ICoQ8WcofOkpN3yhgjP8kkq1ugizeNqknmpRPaCuX6xEwo35zknKR3KYu6zrOlOFk8w97h6Dd58pXe1PSSk67XahBi0PgZjaP8x1y22HMl8Zerzsn@tccELDZCOu3SD5uO2cyQ7TyPOcsTS8w52cbVbAhljlME6I@1Foeyw17DXkLhXluwMtf9Q7N652V0zQdtp1g2hJtw0co/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔×¹·⁵⊕θη ``` Calculate the half width of the reference row. ``` W›ηⅈ« ``` While there is still canopy left to print, ... ``` ↑ ``` ... move up a line, ... ``` P×⁻ηⅈ@ ``` ... print some canopy, ... ``` Mⅉ←» ``` ... and move to the start of the next row of canopy. ``` J⁰θ ``` Jump to the left side of the base. ``` ×θ_ ``` Print the left side of the base. ``` P×⊘⁺³θ_ ``` Print half of the middle of the base, allowing space for the trunk. ``` ↑⊕θ ``` Print the trunk. ``` ⸿ ``` Move to the beginning of the reference row. ``` W›θⅈ« ``` While there is still foliage to print, ... ``` P×⁻θⅈ@ ``` ... print some foliage, ... ``` M⁺²ⅉ¹» ``` ... and adjust the width of the foliage according to the number of lines of foliage already printed. ``` Jθⅉ↗ ``` Move to the mirror location of the `.`. ``` ‖OO﹪θ² ``` Reflect the half tree drawn so far to almost complete the tree and also move the cursor to the location of the `.`. ``` . ``` Complete the tree. [Answer] # Java 11, ~~282~~ 273 bytes ``` n->{String r="",y="_".repeat(n),e="|",N="\n",S=" ",q=S.repeat(n-1),z;int i=1,w=0,s=3*n+2;for(;s>1;s-=2*i,w+=i++)r=S.repeat(w)+"@".repeat(s)+N+r;for(i=1,s=n;s>0;s-=i)r+=S.repeat(n-s)+(z="@".repeat(s))+e+q+(s>++i?S:".")+e+z+N;return r+((q+=S+e)+q+N).repeat(n-i+1)+y+e+y+e+y;} ``` Port of [*@Noodle9*'s Python answer](https://codegolf.stackexchange.com/a/201746/52210), after I helped him golf it a bit. -9 bytes thanks to *@Arnauld*. [Try it online.](https://tio.run/##vVffb9owEH7vX3HzU1KHqHRvZG4zaZ1UaeOFx7aKsuBO7qgL@VHWAn87u/xw7JAQBJpKSWzfne@@77tAzVP4Gg6epn@20SxMEvgZCrk6AxAy5fFjGHEY50uASRoL@RsiCz0gbQ@NmzO8JWmYigjGIIHBVg6uVlVkzAhx3hgJiBvzOQ9TS9oOZ2RNnDEj95I4E0aAOAs2qQMGQ9t59/IKgg2dJbtwEvb5XNJL7/EltrzkauglA3Z5LpwlZYJSO9ablzYlfl0rsemYxsW2PFXCJO6@yHcLO6ZmSYy03lljq005XVAruaJUXE9GxCW55Z2OvZinWSwhppa1wCyU2xg4tnU2QYc2fcPo4vI2Wy8XaZ79mqFIlVavL2IKzyi0VUp19wChbaqMBv53zqOUT1FUyZe1fUXA9/176fvlsHbXOARr/CNOkeHgi@CV7wVfJfH1bA2YMHfCGt@YGRPn7@OS@0b@Rgm1wOSwLqMgXxQsoChaVs1rFtcxhRUxAF0M/N3arXVetEBTwinWSoUSUo7JnAcVuPJ2NER/B2UbaAdWbSpQlIArxKXJVYoqpAr2vlVQU6jupzDpINPJp5uSYS1hVbwUsYa1wl/Z1DNTM6oJ9qwDg60ajmRdMVe5m6QBOviB38d7v6OCrSSpNdlxKFmUWT@7mrrW4lhL0NCqHk8TrVu3vdL1qNcnYMOnqNQqahlbvlrJ2mN@pgxdDKn@my3YUVhPTtZ6r9x9iveLfkD3prump8U31O9w6wZop2t@9huimUp@jDVo9caYndAm838WtBu1t3kH@newhYe7uBOhVTBaafayM8JoZ9tvkDacxrd6U/1GUz7YHnR025ySjVe0vjhtlodXD8QXNrzAAU@pq@rBmLwlKX92X7LUneN5Lp1Ji9zKeZaOgFBheyqsOkDzJJul@QHQxVO39raTlJF9Eeo4eScGwweXL7Jwlqht10AmWRRxPuVTAgjl@9fbHzffPsGNOoNiJgQJIhkBnttpI1lf1cq3KX4rbLb/AA) **Explanation:** ``` n->{ // Method with integer parameter and String return-type String r="", // Result-String, starting empty y="_".repeat(n), // Temp-String `y`, consisting of the input amount of "_" e="|", // Temp-String `e`, containing "|" N="\n", // Temp-String `N`, containing a newline S=" ", // Temp-String `S`, contain a space q=S.repeat(n-1), // Temp-String `q`, consisting of the input-1 amount of spaces z; // Temp-String `z`, uninitialized int i=1, // Integer `i`, starting at 1 w=0, // Integer `w`, starting at 0 s=3*n+2; // Integer `s`, starting at 3 times the input + 2 for(;s>1 // Continue looping as long as `s` is larger than 1: ; // After every iteration: s-=2*i, // Decrease `s` by `i` twice w+=i // Increase `w` by `i` ++) // And increase `i` by 1 r=S.repeat(w) // Prepend `w` amount of spaces; +"@".repeat(s) // `s` amount of "@"; +N // and a newline +r; // to the result-String for(i=1, // Reset `i` to 1 s=n; // Reset `s` to the input s>0; // Continue looping as long as `s` is larger than 0: s-=i) // After every iteration: decrease `s` by `i` r+= // Append the result-String with: S.repeat(n-s) // The input minus `s` amount of spaces; +(z="@".repeat(s))// `s` amount of "@"; +e // a "|"; +q // the input-1 amount of spaces; +(s>++i? // If `s` is larger than `i+1` // (by first increasing `i` by 1 with `++i`) S // a space; : // Else: ".") // a "."; +e // a "|"; +z // the input minus `s` amount of spaces again; +N; // and a newline character return r // After both loops: return the result-String, + // appended with: ((q+=S+e) // `q` with an additional space and "|" appended +q // twice +N)// and a newline .repeat(n-i+1)// Repeated `n-i+1` amount of times +y+e+y+e // As well as two times `y` and "|" +y;} // And an additional third `y` ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~106~~ ~~105~~ ~~103~~ ~~99~~ ~~97~~ ~~95~~ ~~93~~ 92 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` $×0I>;úR©«D1s∍ILηOD¦<‚vyvDðyL<ǝ}r}r)ʒ1å}`'.I>ǝ)DJ0¢Iα®иIú0'_I×쬮¦∍«)˜IÉi.ºëº}»T„@|‡I≠i'.ð.; ``` [Try it online](https://tio.run/##AZAAb/9vc2FiaWX//yTDlzBJPjvDulLCqcKrRDFz4oiNSUzOt09EwqY84oCadnl2RMOweUw8x519cn1yKcqSMcOlfWAnLkk@x50pREowwqJJzrHCrtC4ScO6MCdfScOXw6zCrMKuwqbiiI3CqynLnEnDiWkuwrrDq8K6fcK7VOKAnkB84oChSeKJoGknLsOwLjv//zY) or [verify the first 10 test cases](https://tio.run/##AaMAXP9vc2FiaWX/VEUiSW5wdXQ6ICI/Tiwx/07DlzBOPjvDulLCqcKrRDFz4oiNTkzOt09EwqY84oCadnl2RMOweUw8x519cn1yKcqSMcOlfWAnLk4@x50pREowwqJOzrHCrtC4TsO6MCdfTsOXw6zCrMKuwqbiiI3CqynLnE7DiWkuwrrDq8K6fcK7VOKAnkB84oChTuKJoGknLsOwLjv/fSzCtj//). **Explanation:** ``` $ # Push 1 and the input-integer × # Pop both, and push a string consisting of the input amount of "1"s 0 # Push a 0 I>; # Push the (input+1)/2 ú # Prepend that many spaces to the "0" (truncates decimals) R # Reverse it so the spaces are trailing © # Store it in variable `®` (without popping) « # Append it to the string of 1s D # Duplicate it 1 # Push a 1 s # Swap the two values on the stack ∍ # Extend the "1" to a size equal to the string-length IL # Push a list in the range [1, input] η # Get the prefixes of this list O # And sum each inner prefix D # Duplicate this list of integer | # Remove the leading 1 < # Decrease each value by 1 ‚ # And pair the two lists together v # Loop over this pair of list of integers: yv # Inner loop `y` over each of those lists of integers: D # Duplicate the string at the top of the stack yL # Push a list in the range [1, `y`] < # Decrease it by 1 to make it [0, `y`) ð ǝ # And replace the characters at those indices with a space }r # After the inner loop: reverse all values on the stack }r # After the outer loop: reverse all values on the stack ) # And wrap all values on the stack into a list ʒ # Filter this list by: 1å # Only keep lines which contain a "1" }` # After the filter: Push all values separated to the stack again '.I>ǝ '# Replace the space at index input+1 with a "." ) # And re-wrap all values on the stack into a list again D # Duplicate this list of lines J # Join them all together 0¢ # Count the amount of "0"s in this string Iα # Get the absolute difference with the input ®и # Repeat `®` (the "|" with trailing spaces) that many times as list Iú # Prepend the input amount of spaces to each string 0 # Push a 0 '_I×ì '# Prepend the input amount of "_" ¬ # Push its first character (without popping), which is a "_" ®¦∍ # Repeat it the length of `®` - 1 amount of times « # Append it to the "0" with leading "_" ) # Wrap all values on the stack into a list again ˜ # Flatten it IÉi # If the input is odd: .º # Mirror each line with the last character overlapping ë # Else: º # Mirror each line without overlap }» # After the if-else: join all lines by newlines T # Push 10 „@| # Push string "@|" ‡ # Transliterate all "1" to "@" and all "0" to "|" I≠i # If the input is NOT 1: '.ð.; '# Replace the first "." with a space # (after which the result is output implicitly) ``` `r)ʒ1å}`'.I>ǝ)D` could alternatively be `)ʒþà}ć'.N>ǝšÂs` for the same byte-count. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~86~~ ~~81~~ ~~77~~ 67 bytes ``` Î×2.ø$×.ø©DSdJD.ΓN>·.$}`r[D¬≠#NÌF¦¨]\\0'..;R®1K¹;.D®TS'_:).c2Ý… @|‡ ``` [Try it online!](https://tio.run/##AWQAm/9vc2FiaWX//8OOw5cyLsO4JMOXLsO4wqlEU2RKRC7Ok04@wrcuJH1gcltEwqziiaAjTsOMRsKmwqhdXFwwJy4uO1LCrjFLwrk7LkTCrlRTJ186KS5jMsOd4oCmIEB84oCh//82 "05AB1E – Try It Online") ~~-5~~ ~~-9~~ -19 @ Kevin Cruijssen, thanks! --- This is some unorthodox stuff, definitely not my best answer... It's been awhile, I'm rusty. Also tried to use some of the new commands like `Δ` which did not go as planned, and I had to use a global register. Still trying to golf that whole part out. --- For the purpose of the explanation `I` will mean input for the duration. ``` [ Code ] # [ Explanation ] ====================#======================================== $ # Push 1 and I. 3*Ì # (3 * I) + 2 × # "1" repeat (3 * I) + 2 times. Ð # Triplicate. ====================# Setting up the first line of the bottom crown. ¹x # Push I and 2I. ‚ # [I, 2I] > # [I + 1, 2I + 1] o # [2 ^ (I + 1), 2 ^ (2I + 1)] ¥ # 2 ^ (I + 1) - 2 ^ (2I + 1) b # Convert to binary (I=2: 11000) - # Subtract from previous value (I=2: 11111111-11000=11100111) н # Remove from array (get first element) ====================# Setting up the first line of the bottom crown. ¹ # Push I. x>‚ # [I, 2I + 1) o # [2 ^ I, 2 ^ (2I + 1)] b # Convert to binary (I=2: [100,100000]) O # Sum (I=2: 100100) + # Add to previous (I=2: 11200211) ©ˆ # Store in register, push to global array. ====================# Setting up the first line of the top crown. ˆ # Push the line of 1's that starts the top crown. ====================# Creating the top crown. Δ # Until this code stops changing the value... N>· # (Iteration + 1) * 2 .$ # Remove (Iteration + 1) * 2 characters Dˆ # Dupe and push to global array. }¯R` # Push global array reversed, flatten. ====================# Creating the bottom crown. [ # Infinite loop... D¬≠# # Duplicate last value, break if it doesn't start with 1. NÌ # (2 * Iteration) + 1 F¦¨ # Loop (2 * Iteration) + 1 time and remove head/tail. ]\\ # End loop, remove 2 values. ====================# Adding the knot of the tree. 0'..; # Find and replace first 0 with a period. R # Reverse it from the left side to the right. ====================# Creating the trunk. ® # Push the register. 1K # Remove the extra leaves (1's). ¹;.D # Push I/2 copies of this. ====================# Creating the ground. ® # Push register for bottom TS'_: # Replace all leaves (1's) and spaces (0's) with '_' (3's) ====================# Pulling it all together. ) # Wrap stack to array. .c # Center. 2Ý # Push [0,1,2]. … @| # Push " @|". ‡ # Replace 0 with ' ', 1 with '@' and 2 with '|'. ====================# Done! ``` *working on updating the explanation, I am on my cell phone at the moment.* [Answer] # [Perl 5](https://www.perl.org/), 215 bytes ``` $n=pop;$y=$n*3+2;while($y>0){$_=$"x$x.'@'x$y.$/.$_;$x+=++$z;$y-=2*$z}print;$i=$x=$n++;$k=2;while($n--){$_=$"x$j.'@'x$i.'|'.$"x$x.'|'.'@'x$i.$"x$j;$k>=$i?($i&&s/ \|@/.|@/,$i=0,$j=$x):($i-=$k,$j+=$k++);$n||y/ /_/;say} ``` [Try it online!](https://tio.run/##PY1hqgIxDISvIjK4rrHtqghiiXqBdwNh8YdgVbrFFWx1vbo1@MQfYZJM5kvYX87znOE5NMEiMfxoRlN7O7jzfoi0qsoHakY/IupiU0QkDaNRW0RiItwlpHg6wv0ZLs5fLRwjCobI4sQ/klfqRzr@k5wuukJ/0dJ9l58Lya4Ybj2EGwxa09t2G6OlxoKvxjjKj3IppmKcZCQRotLCd10yPVMb2@7SM@e8eDXh6hrfZvU319WkegM "Perl 5 – Try It Online") Takes size of tree as single command-line argument. I'm sure it can probably be improved. Ungolfed: ``` $n = pop; # get tree size from command line ## Crown section ## $x = 0; # initial number of leading spaces to print $y = $n * 3 + 2; # initial number of @s to print $z = 0; # used for increment/decrement value while($y > 0) # build from bottom up as long as we have @s to add { $_ = ' 'x$x . '@'x$y . "\n" . $_; # new row of crown, prepended to existing crown $z++; # increase increment/decrement counter $x += $z; # increase leading spaces for next row $y -= 2*$z; # decrease number of @s for next row } print; # print the crown (don't use say to avoid extra LF) ## Trunk section ## $x = $n++; # width of trunk $i = $x; # number of @s before/after trunk $j = 0; # number of leading/trailing spaces $k = 2; # number of leading/trailing @s to remove in next row while($n--) # build each row of the trunk { $_ = ' 'x$j . '@'x$i . '|' . ' 'x$x . '|' . '@'x$i . ' 'x$j; # new row of trunk if($k >= $i) { # if next row won't have any @s s/ \|@/.|@/ if($i); # set dot in trunk for last row with any @s $i=0; # no @s in next row $j=$x; # spaces in next row equal to trunk width } else { $i -= $k; # reduce @s for next row $j += $k; # increase spaces for next row $k++; # increase increment/decrement counter } if($n == 0) { # if this is the last row y/ /_/; # replace spaces with underscores } say; # print the row } ``` ]
[Question] [ Your task is to print this exact text: ``` z yz xyz wxyz vwxyz uvwxyz tuvwxyz stuvwxyz rstuvwxyz qrstuvwxyz pqrstuvwxyz opqrstuvwxyz nopqrstuvwxyz mnopqrstuvwxyz lmnopqrstuvwxyz klmnopqrstuvwxyz jklmnopqrstuvwxyz ijklmnopqrstuvwxyz hijklmnopqrstuvwxyz ghijklmnopqrstuvwxyz fghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz defghijklmnopqrstuvwxyz cdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ``` **Case does not matter.** Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # Cheddar, ~~50~~ ~~45~~ ~~42~~ 37 bytes ``` 25|>0=>i->print" "*(i/2|0)+(65+i)@"90 ``` Straightforward, but utilizes cheddar's consise ranging syntax (both numerical and alphabetical) [Try it online!](http://cheddar.tryitonline.net/#code=MjV8PjA9PmktPnByaW50IiAiKihpLzJ8MCkrKDY1K2kpQCI5MA&input=) ## Explanation ``` 25 |> 0 => // Map range [0, 26) (i.e. [25, 0] reversed) over.... i -> print // Prints in it's own line... " " * (i/2 |0) + // Number of spaces is floor(n/2). // `|0` for flooring is hack from JS (65 + i) @" 90 // Char code range is this ``` `65` is char code for `A` and `90` for `Z` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ 13 bytes ``` A.svy12N;ï-ú, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=QS5zdnkxMk47w68tw7DDl8OsLA&input=) (slightly different from above as `ú` isn't on TIO yet) **Explanation** 1. Push alphabet 2. Compute the suffixes of the alphabet 3. Prepend 12-index/2 spaces 4. Print [Answer] # Python 2, 70 bytes Ported from [Emigna](https://codegolf.stackexchange.com/a/97460/53667)'s answer, -2 bytes for replacing `-i-1` with `~i` ``` for i in range(26):print' '*(12-i/2)+"abcdefghijklmnopqrstuvwxyz"[~i:] ``` [Answer] # R, 67 66 59 bytes EDIT: Saved a couple of bytes thanks to @rturnbull ``` for(i in 25:0)cat(rep(" ",i/2),letters[i:25+1],"\n",sep="") ``` Exploiting the fact that any number passed to the `rep` function is automatically rounded down to the closest integer (e.g. `rep("*",1.99) => "*"`) which means that the actual sequence passed is `floor(13-1:26/2)`: ``` 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` A.s.c ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fUa9YL/n/fwA "05AB1E – Try It Online") ``` A.s.c A Push 'abcdefghijklmnopqrstuvwxyz' .s Push suffixes starting from the shortest one .c Centralize focused on the left ``` [Answer] # Pyth, 15 bytes ``` j_m+*/d2\ >GdUG ``` A program that prints the result to STDOUT. [Try it online](https://pyth.herokuapp.com/?code=j_m%2B%2a%2Fd2%5C+%3EGdUG&debug=0) **How it works** ``` j_m+*/d2\ >GdUG Program UG Yield [1, 2, 3, 4, ..., 26] m Map over the range with variable d: >Gd Yield alphabet with first d-1 letters discarded + Prepend /d2 d//2 * \ spaces _ Reverse j Join on newlines Implicitly print ``` [Answer] ## Python 2, 52 bytes ``` n=26;s='' while n:n-=1;s=chr(97+n)+s;print n/2*' '+s ``` Accumulates the string `s` to print and updates the number of leading spaces `n/2`. A `while` loop terminating at `0` is a rare numerical loop than beats an `exec` loop (53 bytes): ``` n=26;s='' exec"n-=1;s=chr(97+n)+s;print n/2*' '+s;"*n ``` Also a 53-byte alternative: ``` s='' exec"s=chr(122-len(s))+s;print s.center(26);"*26 ``` [Answer] # JavaScript (ES6), ~~85~~ ~~75~~ ~~69~~ 68 bytes ``` for(s=a='',x=36;--x>9;)s+=` `.repeat(x/2-5)+(a=x.toString(36)+a)+` ` ``` *-1 byte thanks to [@l4m2](https://codegolf.stackexchange.com/questions/97456/draw-an-alphabet-party-hat/97462?noredirect=1#comment372785_97462)*. [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 244 bytes ``` ((((((()()()()())){}{}){}){}()){})((((()()()){}){}()){}){(({}[()]<>)<({}<(<>({})<>)>){({}[()]<(({})[()])>)}({}({})<>[({})]<>(((()()()){}){}){}())((<>)<>{<({}[()])><>([{}]())<>}<>[{}]<>{}){({}[()]<((((()()()()){}){}){})>)}((()()()()()){})><>)}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKCkoKSgpKCkoKSkpe317fSl7fSl7fSgpKXt9KSgoKCgoKSgpKCkpe30pe30oKSl7fSl7KCh7fVsoKV08Pik8KHt9PCg8Pih7fSk8Pik-KXsoe31bKCldPCgoe30pWygpXSk-KX0oe30oe30pPD5bKHt9KV08PigoKCgpKCkoKSl7fSl7fSl7fSgpKSgoPD4pPD57PCh7fVsoKV0pPjw-KFt7fV0oKSk8Pn08Plt7fV08Pnt9KXsoe31bKCldPCgoKCgoKSgpKCkoKSl7fSl7fSl7fSk-KX0oKCgpKCkoKSgpKCkpe30pPjw-KX08Pg&input=&args=LUE) --- This should be readable enough as is. If you need it, I have a full explanation: ``` push 122 (z): ((((((()()()()())){}{}){}){}()){}) push 26: ((((()()()){}){}()){}) loop 26 times (i = 25..0): { ( i--, push to b stack:({}[()]<>) < put 122 from a stack under i: ({}<(<>({})<>)>) i times push letter-1: {({}[()]<(({})[()])>)} replace top 0 with 26-i: ({}({})<>[({})]<>(((()()()){}){}){}()) devide by two: ((<>)<>{<({}[()])><>([{}]())<>}<>[{}]<>{}) add spaces: {({}[()]<((((()()()()){}){}){})>)} push 10 (\n): ((()()()()()){}) > flip stack back: <> push i--: ) } flip to results stack: <> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to @miles (formed a niladic chain I suspected existed but did not form) ``` ØaJ’H⁶ẋżṫJ$ṚY ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=w5hhSuKAmUjigbbhuovFvOG5q0ok4bmaWQ&input=)** ### How? ``` ØaJ’H⁶ẋżṫJ$ṚY - Main link Øa - alphabet yield -> ['a', 'b', 'c', ..., 'y', 'z'] J - range(length) -> [1, 2, 3, ..., 25, 26] ’ - decrement -> [0, 1, 2, ..., 24, 25] H - halve -> [0,.5 1, ..., 12, 12.5] ⁶ - literal [' '] ẋ - repeat list -> [[], [], [' '], ..., 12x' ', 12x' '] $ - last two links as a monad J - range(length) -> [1, 2, 3, ..., 25, 26] ṫ - tail (vectorises) -> [['a'-'z'], ['b'-'z'], ..., ['y','z'], ['z']] ż - zip -> [[[],['a'-'z']], [[],['b'-'z']], ..., [12x' ',['y','z']], [12x' ',['z]]] Ṛ - reverse whole array Y - join with line feeds (implicit print) ``` [Answer] # C, ~~72~~ 68 bytes ``` m(i){for(char*k=&k[i=26];i;printf("%*c%s\n",--i/2+1,0,k))*--k=64+i;} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ô2òΘé8└ ``` [Run and debug it](https://staxlang.xyz/#p=933295e98238c0&i=&a=1) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 4 bytes ``` kz¦R ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=C&code=kz%C2%A6R&inputs=&header=&footer=) Explanation: ``` kz # Lowercase backwards alphabet ¦ # Prefixes R # Reverse each # 'C' flag - Center top of stack, join on newlines, and print ``` [Answer] # [Turtlèd](http://github.com/Destructible-Watermelon/Turtl-d), ~~70~~ 68 bytes note the trailing space ``` #abcdefghijklmnopqrstuvwxyz#' -{ -{ +.r_}' l[ l-]d,(*@!' r)(!@*)_}' ``` ### Try it online! ## How it works: ``` #abcdefghijklmnopqrstuvwxyz# Set string var to this value ' - write space on first grid cell, string pointer-=1 { } While cell is space - decrement string pointer { } While cell is space +. increment string pointer, write pointed char r move right _ write non-space if pointed char is last char '[space] write space on cell l move left [ l-] move left, pointer-- until cell's space d, move down, write character var \ (initially *) (* ) if cell is * @! set char var=! ' r write space over *, move right (! ) if cell is ! @* set char var=* '[space] write space over ! _ (explanation below) write (*|!) if pointed char is last char '[space] Write space ``` ## Human-readable explanation(?): It uses the string var to contain the alphabet. Each iteration, it reduces the index by one, until it wraps around, and halts, after getting to the last line. For the alternating indents, it uses the char var. Each iteration it checks the char var and flips it. if it was \* it shifts right, so the first character aligns, otherwise not, so the last character aligns. [Answer] ## Perl, 44 bytes This is a port of @xnor's [answer](https://codegolf.stackexchange.com/a/97466/55508). ``` $n=26;say$"x($n/2),$@=chr(97+$n).$@while$n-- ``` Needs `-E` (or `-M5.010`) to run : ``` perl -E '$n=26;say$"x($n/2),$@=chr(97+$n).$@while$n--'; ``` [Answer] # PHP, 71 Bytes ``` for(;++$i<27;)echo str_pad(substr(join(range(a,z)),-$i),26," ",2)."\n"; ``` [Answer] # Java 7 ,~~128~~ 127 bytes Saved 1 byte.Thanks to kevin. ``` String c(int n,String s,char v,String d){String c="";for(int j=0;j++<(n-1)/2;c+=" ");return n>0?c(--n,s=v+s,--v,d+c+s+"\n"):d;} ``` # ungolfed ``` class A { public static void main(String[] args) { System.out.print(c(26, "", (char)122, "")); } static String c(int n, String s, char v, String d){ String c = ""; for (int j = 0; j++ < (n - 1)/2; c += " "); return n > 0 ? c(--n, s = v + s, --v, d + c + s + "\n" ) : d; } } ``` Without an passing 122 in a function # 132 bytes ``` String c(String s,int n,String d){String c="";int v=96,j=0;for(;j++<(n-1)/2;c+=" ");return n>0?c(s=(char)(v+n--)+s,n,d+c+s+"\n"):d;} ``` # ungolfed ``` class A{ public static void main(String[] args) { System.out.print(c("",26,"")); } static String c(String s, int n, String d) { String c = ""; int v = 96,j=0; for (; j++ < (n - 1)/2; c += " "); return n > 0 ? c(s = ( char) (v + n--) + s, n, (d + c + s + "\n")) : d; } } ``` [Answer] ## Ruby, 64 bytes ``` (0..26).each{|x|puts' '*(12-x/2)+('a'..'z').to_a[~x..-1].join()} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` ;C¬£SpY/2 +CsYÃw · ``` [Try it online!](https://tio.run/nexus/japt#@2/tfGjNocXBBZH6RgrazsWRh5vLFQ5t//8fAA) ### Explanation: ``` ;C¬£SpY/2 +CsYÃw · ;C // Alphabet shortcut ¬ // Split into an array of chars £ à // Map each item X and index Y by: SpY/2 // " " repeated floor(Y/2) times +CsY // + alphabet.slice(Y) w // Reverse the array of lines · // Join with newlines ``` [Answer] ## REXX, 52 bytes ``` do i=1 to 26 say centre(right(xrange(a,z),i),26) end ``` Output: ``` Z YZ XYZ WXYZ VWXYZ UVWXYZ TUVWXYZ STUVWXYZ RSTUVWXYZ QRSTUVWXYZ PQRSTUVWXYZ OPQRSTUVWXYZ NOPQRSTUVWXYZ MNOPQRSTUVWXYZ LMNOPQRSTUVWXYZ KLMNOPQRSTUVWXYZ JKLMNOPQRSTUVWXYZ IJKLMNOPQRSTUVWXYZ HIJKLMNOPQRSTUVWXYZ GHIJKLMNOPQRSTUVWXYZ FGHIJKLMNOPQRSTUVWXYZ EFGHIJKLMNOPQRSTUVWXYZ DEFGHIJKLMNOPQRSTUVWXYZ CDEFGHIJKLMNOPQRSTUVWXYZ BCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` [Answer] # Vim, 25 Keystrokes ``` :h<_␍jjYZZPqqPxYPr Yq12@q ``` Where ␍ is the Enter key, also sometimes notated as `<cr>`. ## Explanation ``` :h<_␍jjYZZ " get a-z P " initialize by pasting qq " start record macro @q Px " paste and remove the 1st char YPr␣ " yank and paste and replace 1st char with space Y " yank the whole line again q " end recording 12@q " call macro 12 @q times ``` I am new to ViM though -- I started in November. Wondering if there is a way to merge the initializing `P` with the one in the macro. What is the "correct" way to test a golfed ViM sequence? I tested with `\vi -u /dev/null`. However in a VM even `:h<_␍` doesn't work. Also not very sure why my ViM will move to the first non space character haha. P.S. Before I moved to use OS X, I golfed in Hexagony with great tools... Now on OS X I don't do wine and thus not running the great tools for explanations and debugging. So started my journey with ViM! [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 112 bytes ``` ()=>string.Join("\n",new int[26].Select((_,i)=>"".PadLeft(12-i/2)+"abcdefghijklmnopqrstuvwxyz".Substring(25-i))) ``` [Try it online!](https://tio.run/##dZBBawIxEIXv@RUhFxN0s3ShlrLVy0ILxYKwhx7aUmJ21GnXpCZZrRV/@xpRixR6nJk373087RNtHbSNRzOj5cYHWOTkcpKFrWvQAa3x8gEMONR/FCM0y5zoWnlPx1uSplwMhgbWFE14yfpvsoSDA@fvPTxdfHDRgHdop0evsgTTTHQv9lzPlRM86yfYvb0R8U0QH1RATe8bo@@OsiEtg0JXKA90QNtD6vEgHy0azl4N6/2PwZgcq2oE08DPBExNdAXT2Rw/PuuFsV9L50OzWn9vfpgsm8mJLrtOIpBoc3KGWlms6JOKoYJsSRGrsjXIZ4cBYjnAfzm5EDnZkV27Bw "C# (.NET Core) – Try It Online") ``` ()=>string.Join("\n", // OP doesnt want to output a sequence of string... new int[26].Select((_,i)=> // yield range from 0 to 25 "".PadLeft(12-i/2)+ // add spaces to center "abcdefghijklmnopqrstuvwxyz".Substring(25-i))) // remove letters ``` [Answer] # [Tcl](http://tcl.tk/), 92 bytes ``` set a {} time {set a [format %c [expr 123-[incr i]]]$a;puts [format %[expr 13+$i/2]s $a]} 26 ``` [Try it online!](https://tio.run/##K0nO@f@/OLVEIVGhuparJDM3VaEawo1Oyy/KTSxRUE1WiE6tKChSMDQy1o3OzEsuUsiMjY1VSbQuKC0pRiiDKjLWVsnUN4otVlBJjK1VMDL7/x8A "Tcl – Try It Online") # tcl, 94 ``` set a {} set i 123 time {set a [format %c [incr i -1]]$a;puts [format %[expr 74-$i/2]s $a]} 26 ``` [demo](http://rextester.com/YLNFPD87640) ## In the middle of the process, I accidentaly got the italic version of the hat: # tcl, 94 ``` set a {} set i 123 time {set a [format %c [incr i -1]]$a;puts [format %[expr $i/2-24]s $a]} 26 ``` [demo](http://rextester.com/XODP23160) --- # tcl, 101 ``` set a {} set i 123 while \$i>97 {set a [format %c [incr i -1]]$a;puts [format %[expr ($i-48)/2]s $a]} ``` [demo](http://rextester.com/SKUV47523) In the middle of the process, I accidentaly got the italic version of the hat: # tcl, 99 ``` set a {} set i 123 while \$i>97 {set a [format %c [incr i -1]]$a;puts [format %[expr $i/2-24]s $a]} ``` [demo](http://rextester.com/YMWTD54657) [Answer] # Common Lisp, SBCL, ~~83~~ 82 bytes ``` (dotimes(i 27)(format t"~26:@<~a~> "(subseq"ABCDEFGHIJKLMNOPQRSTUVWXYZ"(- 26 i)))) ``` ### Explanation ``` (dotimes(i 27) ; loop from i=0 to i=26 (format t"~26:@<~a~> "(subseq"ABCDEFGHIJKLMNOPQRSTUVWXYZ"(- 26 i)))) ;print out part of alphabet starting from character number 26-i (counting from zero) ;using justification (~26:@<~a~>) to center with weight 26 characters ``` *-1 using sugestion by ASCII-only to use `<enter>` instead of `~%`* [Answer] # T-SQL, 107 bytes ``` DECLARE @t VARCHAR(99)=SPACE(13),@ INT=27a:SET @t=STUFF(@t,@/2,@%2,CHAR(@+95))PRINT @t SET @-=1IF @>1GOTO a ``` Modifies the string for each line by cramming in the correct letter at the correct position using the SQL fuction `STUFF()`. Formatted: ``` DECLARE @t VARCHAR(99)=SPACE(13), @ INT=27 a: SET @t=STUFF(@t,@/2,@%2,CHAR(@+95)) PRINT @t SET @-=1 IF @>1 GOTO a ``` `@/2` uses integer division (no remainder) to determine the position to insert the letter. `@%2` is the `MODULO` function, and flips between 0 (insert the letter) and 1 (overwrite a space). If you prefer capitial letters, use `CHAR(@+63)` instead (doesn't change our byte count). [Answer] # [Perl 5](https://www.perl.org/), ~~40~~ 38 bytes *-2 bytes thanks to @Dom Hastings* ``` say$"x(13+--$x/2),@a[$x..-1]for@a=a..z ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFqULD0FhbV1elQt9IU8chMVqlQk9P1zA2Lb/IIdE2UU@v6v//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~62~~ ~~51~~ 46 bytes -11 bytes thanks to mazzy reminding me of a function -5 bytes thanks to mazzy ``` 25..0|%{' '*($_-shr1)+-join('a'..'z')[$_..25]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38hUT8@gRrVaXUFdS0MlXrc4o8hQU1s3Kz8zT0M9UV1PT71KXTNaJV5Pz8g0tvb/fwA "PowerShell – Try It Online") Uses the ~~`-replace`~~ `-shift-right 1` trick to bypass banker's rounding. Additionally, uses a character range to generate the alphabet. [Answer] # Haskell (Lambdabot), 73 bytes ``` unlines[([1..div(26-length x)2]>>" ")++x|x<-reverse.init$tails['a'..'z']] ``` same length: ``` do x<-reverse.init$tails['a'..'z'];([1..div(26-length x)2]>>" ")++x++"\n" ``` I use `init.tails` or `tail.inits` with a possible reverse in front in pretty much every challenge; I wish they would add it to Prelude already. [Answer] ## Python 2, ~~66~~ 64 bytes ``` i=91;exec'i-=1;print`map(chr,range(i,91))`[2::5].center(26);'*26 ``` [Answer] # Groovy, 53 bytes ``` ('z'..'a').each{println((it..'z').join().center(26))} ``` # Output: ``` z yz xyz wxyz vwxyz uvwxyz tuvwxyz stuvwxyz rstuvwxyz qrstuvwxyz pqrstuvwxyz opqrstuvwxyz nopqrstuvwxyz mnopqrstuvwxyz lmnopqrstuvwxyz klmnopqrstuvwxyz jklmnopqrstuvwxyz ijklmnopqrstuvwxyz hijklmnopqrstuvwxyz ghijklmnopqrstuvwxyz fghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz defghijklmnopqrstuvwxyz cdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ``` ]
[Question] [ Given \$k\$ arrays of length \$n\$, output the maximum sum possible using one element from each array such that no two elements are from the same index. It is guaranteed that \$k\le n\$. # Input A nonempty list of nonempty arrays of integers. # Output An integer that represents the maximum sum. # Examples ``` Input -> Output [[1]] -> 1 [[1, 3], [1, 3]] -> 4 [[1, 4, 2], [5, 6, 1]] -> 9 [[-2, -21],[18, 2]] -> 0 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 15 [[1, 2, 3, 4], [5, 4, 3, 2], [6, 2, 7, 1]] -> 16 [[-2, -1], [-1, -2]] -> -2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 6 bytes ``` ZŒ!ÆṭṀ ``` [Try it online!](https://tio.run/##y0rNyan8/z/q6CTFw20Pd659uLPh////0dGGOgpGOgrGOgomsToK0aZAGswzAvHMwHLmOgqGsbEA "Jelly – Try It Online") (4 bytes saved by @Dennis, who pointed out that Jelly had a "sum of main diagonal" builtin. I was *not* expecting it to have one of those; the previous solution implemented the operation without using the builtin. The operation in question, `Æṭ`, is defined as "trace", but the trace is only defined for square matrices; Jelly implements a generalisation to rectangular matrices too.) The improvement over the other answers is mostly from a simpler (thus terser to express) algorithm; this program was originally written in Brachylog v2 (`{\p\iᶠ∋₎ᵐ+}ᶠot`), but Jelly has some builtins for parts of the program that have to be spelled out in Brachylog, so this came out shorter. ## Explanation ``` ZŒ!ÆṭṀ Z Swap rows and columns Œ! Find all permutations of rows (thus columns of the original) Æṭ {For each permutation}, take the sum of the main diagonal Ṁ Take the maximum ``` It should be clear that for any solution to the problem, we can permute the columns of the original matrix to put that solution onto the main diagonal. So this solution simply reverses that, finding all possible main diagonals of permutations. Note that the "permute the columns" operation is done as "transpose, permute the rows" without bothering to transpose back; the rest of the algorithm happens to be symmetrical about the main diagonal, so we don't need to undo the transpose and thus can save a byte. [Answer] # [J](http://www.jsoftware.com), 28 bytes ``` >./@({.+1$:@|:\.|:@}.)@[^:]# ``` [Try it online!](https://tio.run/##XYzNCsJADITv@xSDLtRSid3dtmqgsu/h36G4qBcPPdo@@xoXS0GSgcmXSZ4x9C2hBKOMB9r41ZsKo9kPfKKB/Ui5P174vIy5WhCy0FKGNUZG6JW6dfcXAgyMNtNgpbQg99UMXYKVuBoN/tJXKy1fdrDTwv0uCjxoP8MqQZtcLXLiG9EWJn4A "J – Try It Online") ``` >./ @ ( {. + 1 $:@|:\. |:@}. ) @[^:] # (max of (1st row + recursive call on each "minor")) or count of arg if 0 ``` Here the recursive call is done by `$:` which represents the largest anonymous function containing it. We are lucky in J to have the primitive `x u\. y`, which applies `u` to successive "outfixes" of `y` obtained by suppressing successive infixes of length `x` of the items in `y`; here we want to surpress successive columns to get "minors", so we transpose `|:` the lower rows (or tail `}.`) of `y`, and then recurse on the transpose of their outfixes. [Answer] # [Python 3](https://docs.python.org/3/), ~~94 90 89 84~~ 80 bytes -4 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) (using sets instead of lists)! ``` f=lambda x,y={-1}:x>[]and max(e+f(x[1:],y|{i})for(i,e)in enumerate(x[0])if{i}-y) ``` [Try it online!](https://tio.run/##XVDLasMwELz7K@YWia5K5KRJa3B@RNVBJTIV1EqwHZBx/e3uyqQ09KTR7Mzs4zoOn5e4W5am/nLtx9kh0VhPSs9VOhnr4hmtS8I/NSIZXVkav6cwy@bSiUBehggfb63v3OBZsLUyNFxXo1xS6lHjvQAMjNHWMqKMCDvLYH0fyD2hzPwL4UD406uSoEptyejXLHmwlPcotmZXhkcCq97@qzj@nr1ff2unw1o7/jazRcFrgcfmrXj6irlrF@IgNtMMdcI0b55Z0bpBpJ74IL2UcvkB "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12 11~~ 9 bytes ``` ▲mȯΣ►L∂PT ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/j@atin3xPpzix9N2@XzqKMpIOT//@how9hYBTxAF2iEIRdQmY5xrA6YjMWlzASszETHCKjQVMdMB4vJIGWWQGW6Rjq6RoYgAy2AyrEqMwCbZgS21kQHaB6QNtex0LFEKAe7zRSmTscEbK8JkAVygRlQzBziBrA6M4i1CrpAaxWidQ2BLHSbQep0jSBhguplTJ9hegK3ewm5EGoWyCigu0DOAgA "Husk – Try It Online") Thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo) for suggesting a port of [ais523's answer](https://codegolf.stackexchange.com/a/177714/59487) and a 2-byte save, which I managed to improve on further, and in turn BMO shaved off 2 more bytes. --- ## Previous solution (14 bytes) ``` ▲moΣz!¹fS=uΠmŀ ``` [Try it online!](https://tio.run/##yygtzv7//9G0Tbn55xZXKR7amRZsW3puQe7Rhv//o6MNY2MV8ABdXTsFQy6gMh3jWB0wGYtLmQlYmYmOEVChqY6ZDhaTQcosgcp0jXR0jQxBBloAlWNVZgA2zQhsrYkO0Dwgba5joWOJUA52mylMnY4J2F4TIAvkAjOgmDnEDWB1Zv9xmgcA "Husk – Try It Online") I wasn't able to make a test suite because this answer uses the *first command line argument* command explicitly. But Husk doesn't use STDIN at all so I included all the test cases there, so you can just copy paste in the argument field to check it out. Also note that arrays in Husk may not contain spaces between elements while being inputted. ### How it works? **Code breakdown** ``` ▲moΣz!¹fS=uΠmŀ Full program. Takes a 2D list from CLA 1 and outputs to STDOUT. mŀ Length range of each list. Π Cartesian product. fS=u Discard those combinations which have at least 1 non-unique element. mo Map over the combinations with the following predicate: z!¹ Zip the 2D list input with the current combination and index accordingly. Σ Sum the resulting elements. ▲ Finally, pick the maximum. ``` **Example** Let's pick an example: $$\left(\begin{matrix}1&4&2\\5&6&1\end{matrix}\right)$$ One must pick exactly one index from each such that no two indices correspond. So, we generate the length ranges of the rows and only keep those without duplicates, yielding the following combinations (each combination is a column instead of a row to save space): $$\left(\begin{matrix}\color{red}{1}&\color{blue}{2}&\color{green}{1}&\color{orange}{3}&2&\color{pink}{3}\\\color{red}{2}&\color{blue}{1}&\color{green}{3}&\color{orange}{1}&3&\color{pink}{2}\end{matrix}\right)$$ Then, the program indexes in the input lists with each element of the combination, returning: $$\left(\begin{matrix} \color{red}{1}&\color{blue}{4}&\color{green}{1}&\color{orange}{2}&4&\color{pink}{2}\\ \color{red}{6}&\color{blue}{5}&\color{green}{1}&\color{orange}{5}&1&\color{pink}{6} \end{matrix}\right)$$ Summing all those results (here, each column, for the aforementioned reason), one obtains all possible valid sums according to the criteria, in this case \$9\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` ẈŒpQƑƇị"€¹§Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hro6jkwoCj0081v5wd7fSo6Y1h3YeWv5wZ8P/w@1AjkLk///R0dGGsbFcOkBKR8E4VkcBQsNETHQUjECCpjoKZjoKUJW6RjoKukaGYMUWIAUw1UZQI4C6QBpATHMdBaASSxQlQGOhZpqAeWAbzMBy5hBLYgE "Jelly – Try It Online") ### Alternate version, 11 bytes ``` ZLœ!Lị"€¹§Ṁ ``` This uses the newly added `œ!` built-in, which generates all permutations of a given length. [Try it online!](https://tio.run/##y0rNyan8/z/K5@hkRZ@Hu7uVHjWtObTz0PKHOxv@H24HchQi//@Pjo42jI3l0gFSOgrGsToKEBomYqKjYAQSNNVRMNNRgKrUNdJR0DUyBCu2ACmAqTaCGgHUBdIAYprrKACVWKIoARoLNdMEzAPbYAaWM4dYEgsA "Jelly – Try It Online") ### How it works ``` ẈŒpQƑƇị"€¹§Ṁ Main link. Argument: M (matrix) Ẉ Widths; compute the length of each row. For an n×m matrix, this yields an array m copies of n. Œp Cartesian product; promote each n to [1, ..., n], then form all arrays that pick one k out of all m copies of [1, ..., n]. QƑƇ Comb by fixed unique; keep only arrays that do not change by deduplicating their entries. ¹ Identity; yield M. ị"€ For each of the arrays of unique elements, use its m entries to index into the m rows of M. § Take the sums of all resulting vectors. Ṁ Take the maximum. ``` [Answer] # JavaScript (ES6), ~~74~~ 71 bytes *Thanks to @tsh for identifying 2 useless bytes that were used to fix a bug* *Saved 3 bytes thanks to @tsh* ``` f=([a,...r],k,i=1)=>a?Math.max(...a.map(n=>k&(i+=i)?-1/0:n+f(r,k|i))):0 ``` [Try it online!](https://tio.run/##jZFNjsIwDEb3cwqvRolw0iZTyo8UOAEnqLKIgEIotKggxIK7F6cgFlPoTDZ25Ojpe/HOXdxpWfvjWZTVat00uWGZQyllbbFAbxQ3MzdfuPNWHtyV0cBRc2SlmRXfzA@M53OhonhaDnJWY3HznPNp3Cyr8lTt13JfbVjOskxZyzn870QRqK8OAOHHIjzqHywCJO8ACYIOjCFCitATiQCTDkBoBKGVxUyNA6gvBAHidwn004KShBChHSEQbvILF/5g@IlAJk@NpL21Umk7G728AiHtSqggEd63Or1rIYLQzR0 "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` f(u:v)=maximum[e+f(take i<>drop(i+1)<$>v)|(i,e)<-zip[0..]u] f _=0 ``` [Try it online!](https://tio.run/##RYw9b4MwEIZ3fsWpymCLAwVKk7QyLO3YTB0RqixhghVsIzBJVPW/0wOGLs99PO9dK8er6rpZm94NHj6kl/HZWadrYMBEwYEHc8OmtxvPjXxoM5lShQ3z8qpAi6IeXM90mHCxK278l2lUXEQ/ui/3cVxNVdDAd76fjdQWcjCyPwOwfvJffvi0EMPFcWKnrRohFwIuyr8765X1I9xbNagAKAMPsgvCEJ4gKgjUja27A2tgB4OSNWk@l2VSVQERnytcuU0ZpjS/4AE3H6UYpckSOZHZMul6kyGlqB7xhK//BrP1PqNu@XSg3XH59Qc "Haskell – Try It Online") ## Explanation & Ungolfed The function `take i<>drop(i+1)` takes a list and removes the element at position `i`. The function `f` gets each possible element `e` at position `i`, removes the elements at position `i` from the remaining elements and adds `e` to the recursively computed optimum: ``` f(u:v)=maximum[e+f(removeElementAt i<$>v)|(i,e)<-zip[0..]u] ``` And the base case for the empty list is just `0`: ``` f _=0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` {hl⟦kp;?z₀∋₍ᵐ+}ᶠot ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzoj59H8ZdkF1vZVj5oaHnV0P2rqfbh1gnbtw20L8kv@/4@ONtRRMNJRMNZRMInVUYg2BdJgnhGIZwaWM9dRMIyN/R8FAA "Brachylog – Try It Online") ### Explanation ``` ot The output is the biggest result of… { }ᶠ …finding all outputs to the following predicate: hl⟦k Construct the range [0, …, n-1] p Take a permutation of that range ;?z₀ Zip that permutation with the Input, stopping when all elements of the input are used (important because the range is possibly bigger than the length of the input) ∋₍ᵐ In each element of the zip, take the head'th element of the tail + Sum the result ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 40, 32, 28, 19 bytes -13 bytes thanks to ngn! ``` {|/+/(prm'x)@''!#x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukZfW1@joChXvULTQV1dUbmi9n@agoahgpGCsYKJtYKpggmQYWStYAYUMVcw1PwPAA "K (oK) – Try It Online") ## Initial solution: ``` {|/+/'x./:/:(*t),'/:t:{x~?x}#+!(#x)##*x} ``` [Try it online!](https://tio.run/##Dcg7DoAgDADQq9R04Kc2IGpSBm/DwuDC0ETx6sj28spyl94zPy85UrISE2tbzayIKz/yXdLQTRrFIFppPYP2EGCDmGCHOBASHGNO8Kb/ "K (oK) – Try It Online") Note: Doesn't work for the first test case [[1]] ## Explanation: `{ }` - function with argument `x` ``` # - creata a list (#x) - with length number of rows of x #*x - of the length of the first row ! - odometer (ranged permutations) + - transpose # - filter out the rows {x~?x} - that have duplicates t: - save it to t ,'/: - pair up each number in each row with (*t) - a number from the first row x./:/: - index x with each of the above +/' - find the sum of each row |/ - reduce by max ``` [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` ([]%) p%(h:t)=maximum[x+(i:p)%t|(i,x)<-zip[0..]h,all(/=i)p] p%_=0 ``` [Try it online!](https://tio.run/##RYxNT4QwEIbv/IqJWZI2DLiL7Icb6sWrnjxiY5q1QGOBBrpZYvzt4gAHL09n@rzv1Gr40tZOpXifWCFDHriQ1WfPRaNG01ybYoyYOTse@h9mcOR5/G1csU0SWaOylt0Lw52k1ofYTo0yLQholHsFYO7q33z/0kICVceJ1rR6AJHnUGn/3LVet36AW617HQBlYCQ7I4rgDuInAk1D3d2AlbCBXqtP0nwqip2UAREfJC5ctwxT2vd4wNXHKcbpbo6cyKyZdOlkSCl6j3jCx3@D2dLPaJovHejvON/6vZRWVcMUX5z7Aw "Haskell – Try It Online") --- **71 bytes** ``` f m=maximum[sum b|(a,b)<-unzip<$>mapM(zip[0..])m,[x|x<-a,y<-a,x==y]==a] ``` [Try it online!](https://tio.run/##RYyxbsIwEIZ3nuJUMSTiHEGaApVsFtZ26mh5MKohUWMnih1hKt49PSdDl8//@f/uau1/TNtO0xWssDo2drTSjxYuz0zjJedsdL9Nz9cnq/vPjKLcFoXKLcr4jJxpfCREIR5KCK0mqxsHApINkPVj@ArDh4MCbl1ObBtnPAjO4WbCuXPBuODhXpvBrIAciNQmbDbwAuxEoOTr7g7ZFdYwGP1NdT5JuVNqRcRXhTOXqcKS5jfc49KzElm5S8qRmsUp550KyaL3gEd8/2@wmvcrSunSnv4O6dYf "Haskell – Try It Online") The `[x|x<-a,y<-a,x==y]==a` checks that the elements of `a` are distinct. This uses up a surprising number of characters, but I didn't see a shorter way. [Answer] # [J](http://jsoftware.com/), 14 bytes ``` {:@$>./ .+@{.] ``` [Try it online!](https://tio.run/##RY7NCgIxDITvfYpBhEVMq8l2/wqKIHjy5HUpe/PgK/jwa9JdFdomzTfT6WveBFRPnBIqwhFJtw@4Pu63@Z0u23M4IOwv75Dn3fwEg7fsrNaU9ChthFBq0MLIJLpYYQ8pVFQaoZhShx7Dd4hIjVprM7c66H52dU@snXNVNZYvuXHknOHPqtGWUGfCUss0LtNIEAMNaRpWx6DMC8ELZxq5N00Bx8Uk62tqNp@1HUFlw5rY/HUasb4fy62ktYV1v0Buv4ls2LNlL8iL230A "J – Try It Online") When I saw [xnor's comment](https://codegolf.stackexchange.com/questions/177673/non-overlapping-matrix-sum?rq=1#comment428500_177673) > > For square arrays, this is the matrix permanent over the tropical semiring which uses the operations (max, +) in place of (+, \*). > > > I immediately realized that it must be a job for J's generalized determinant/permanent built-in `f . g`. The permanent is `+/ .*`, so the modified permanent is `>./ .+` (6 bytes). Unfortunately this only works with square arrays (horizontally longer arrays give negative infinity `__` for some reason), so I needed to pad the input with zeros to make it square. ``` {:@$>./ .+@{.] NB. Tacit function, input: a matrix {:@$ NB. The horizontal length of the matrix {.] NB. Pad the matrix with zeros at the bottom to make it square >./ .+@ NB. Compute the modified permanent over the square matrix ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~50~~ 49 bytes ``` {max map *.map({.[$++]}).sum,permutations [Z] $_} ``` [Try it online!](https://tio.run/##bU7bCoJAEH3vK86DhOYo7GZaRD/SssQ@KARtLV4gEb992zUJEl9m5nBuY8r6kVvdY1vhAjto9YZWBrvUzXBIRRDHcozSptNkylp3rWrvr2cDcZUIbqNtVI8qFIJJGZ03P0TYS8J3L4iMwD13IOSEf1/CCQlnkgQ7etnCyudYF@Hd/iwITnlaU7qquSeb0NSaT1yxWsy8IGH@BU/aDw "Perl 6 – Try It Online") Decently short, even despite the long `permutations` call. This is an anonymous code block that takes a list of lists and returns a number. ### Explanation: ``` { } # Anonymous code block max # Finds the maximum permutations # Of all permutations [Z] $_ # Of the transposed input map # When mapped to .sum # The sum of *.map({.[$++]}) # The diagonal of the matrix ``` [Answer] # Pyth, ~~15~~ 12 bytes ``` [[email protected]](/cdn-cgi/l/email-protection) ``` Try it online [here](https://pyth.herokuapp.com/?code=eSms%40VQd.plh&input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%2C%5B7%2C8%2C9%5D%5D&debug=0). ``` [[email protected]](/cdn-cgi/l/email-protection) Implicit: Q=eval(input()) Trailing Q inferred lhQ Length of first element of Q .p Generate all permutaions of 0 to the above m Map the elements of the above, as d, using: @VQd Vectorised index into Q using d For i in [0-length(Q)), yield Q[i][d[i]] s Take the sum of the above S Sort the result of the map e Take the last element of the above, implicit print ``` *Edit: saved 3 bytes courtesy of issacg* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` нgLœε‚øε`è]OZ ``` ~~I have the feeling it's overly long, but I'm not sure how to do vectorized indexing byte-efficiently in 05AB1E..~~ And I was indeed right that it was too long.. -5 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//9C9Z0zFk8614oCaw7jOtWDDqF1Pw6D//1tbMSw0LDJdLFs1LDYsMV1d) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2SwqO2SQpK9v8v7E33OTr53NaIykcNsw7vOLc14fCK2lr/wwv@6/yPjo42jI3VUQBSOsaxOmASyjXRMQIKmOqY6UBV6Brp6BoZghRZAKWgqozA2kx0gOqAtLmOhY4lkpSOCdgIEyALZJgZUMwcZFwsAA). **Explanation:** ``` н # Take the first inner list (of the implicit input list of lists) g # Pop and take its length L # Create a list in the range [1, inner-length] œ # Create each possible permutation of this range-list ε # Map each permutation to: ‚ # Pair it with the (implicit) input ø # Transpose; swap rows/columns ε # Map each to: ` # Push both to the stack è # Index the permutation-nr into the inner list of the input ] # Close both maps O # Take the sum of each inner list à # Pop and push the maximum (and output implicitly) ``` **Example run:** * Input: `[[1,4,2],[5,6,1]]` * After step 1 (`нgL`): `[1,2,3]` * After step 2 (`œ`): `[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]` * After step 3 (`ε‚`): `[[[[1,4,2],[5,6,1]],[1,2,3]],[[[1,4,2],[5,6,1]],[1,3,2]],[[[1,4,2],[5,6,1]],[2,1,3]],[[[1,4,2],[5,6,1]],[2,3,1]],[[[1,4,2],[5,6,1]],[3,1,2]],[[[1,4,2],[5,6,1]],[3,2,1]]]` * After step 4 (`ø`): `[[[[1,4,2],1],[[5,6,1],2]],[[[1,4,2],1],[[5,6,1],3]],[[[1,4,2],2],[[5,6,1],1]],[[[1,4,2],2],[[5,6,1],3]],[[[1,4,2],3],[[5,6,1],1]],[[[1,4,2],3],[[5,6,1],2]]]` * After step 5 (`ε`è]`): `[[4,1],[4,5],[2,6],[2,5],[1,6],[1,1]]` (NOTE: 05AB1E is 0-indexed (with automatic wraparound), so indexing `3` into `[5,6,1]` results in `5`.) * After step 6 (`O`): `[5,9,8,7,7,2]` * Output / after step 7 (`à`): `9` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øœ€Å\Oà ``` Port of [*@ais523*'s Jelly CW answer](https://codegolf.stackexchange.com/a/177714/52210), so make sure to upvote it as well! [Try it online](https://tio.run/##yy9OTMpM/f//8I6jkx81rTncGuN/eMH//9HRhjomOkaxOtGmOmY6hrGxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wzuOTn7UtOZwa4z/4QX/df5HR0cbxsbqKAApHeNYHTAJ5ZroGAEFTHXMdKAqdI10dI0MQYosgFJQVUZgbSY6QHVA2lzHQscSSUrHBGyECZAFMswMKGYOMi4WAA). **Explanation:** ``` ø # Transpose the (implicit) input; swapping row/columns œ # Get all permutations €Å\ # Take the main diagonal of each O # Sum each à # Pop and push the maximum (which is output implicitly) ``` [Answer] ## Haskell, 84 bytes ``` import Data.List h l=maximum[sum$snd<$>r|r<-mapM id$zip[1..]<$>l,(==)=<<nub$fst<$>r] ``` [Try it online!](https://tio.run/##ZY3NCsIwEITvPsUceqiwLaT@Q@PJoz5B2ENEpcGmliYFEd@9NrWg6Gl3Z7@ZKbS7nsuy64ytb43HTnud7o3zkwKltPpubGuVa23kqlMebZtnkydW1weYU/QwtRJpyr1eUizlVOZ51R6ji/MB5c5qU0Fi4OO6MZVHimIKNQGglGCmcSPMmPCeX@KckAV9QVgSPnySEZJMMCmxDsiXJRujemtwhXVF6KnNL9XHj9nz4RqalsNv9VcmwjMRoZYZ4O4F "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74~~ ~~72~~ 69 bytes ``` ->a{[*0...a[0].size].permutation.map{|x|a.zip(x).sum{|y,z|y[z]}}.max} ``` [Try it online!](https://tio.run/##RY3LDoIwEEX3fMUkbtRMJ4A8ZCE/0syiGogsUMIj4VG@HVsguGpnzr1z6u45LPljEama5NUlIiVdpqYYM6Yqq8uuVW3x/VCpqkn3WtFYVOf@Qk1XTnrAUQ9y5Hk2vJ8X6UjpMeMJRAqeHRBujLC9@z7Y9gGCb1GIECEcrcRQ4SMI32OU3t2mduRuRX@/aQ7Yrv3GCCaYHObwnzSi3RKs0@qMVhav2q0ROUyZer0n3eoKctnyvPwA "Ruby – Try It Online") ]
[Question] [ Let an 8x8 chessboard be represented by any two distinct values, with one value being an empty square and the other being a queen. In the following examples, I use 0s as the empty squares and 1s as queens. For example: [![Queens on a chessboard](https://i.stack.imgur.com/oa2Ze.png)](https://i.stack.imgur.com/oa2Ze.png) is given by ``` 1 0 1 1 1 0 0 0 1 0 1 0 1 0 1 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 0 1 1 0 0 1 0 1 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 1 1 1 0 1 0 1 ``` Consider the number of pairs of queens that are attacking each that are at least one square away (as a reminder, queens attack orthogonally and diagonally). In the above example, the following incredible ugly diagram shows all these pairs as arrows. [![Attacking queens](https://i.stack.imgur.com/IRxGm.png)](https://i.stack.imgur.com/IRxGm.png) There are 43 pairs found above giving the following test case: ``` Input: 1 0 1 1 1 0 0 0 1 0 1 0 1 0 1 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 0 1 1 0 0 1 0 1 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 1 1 1 0 1 0 1 Output: 43 ``` ## Challenge Write a program that, given a board state represented by two distinct values, outputs the number of pairs of queens that attack each other with at least one square in between them. * You may input in whatever format is most convenient that uses two values to represent the empty squares and queens, e.g., a string of 64 "."s for empty squares and "Q"s for queens by rows from bottom to top, an 8x8 matrix of booleans, a list of list of integers 0 and 1 etc, as long as it is explained in your solution * Output is an integer * Standard I/O methods apply and standard loopholes forbidden * This is code golf so shortest answer in bytes wins ## Test cases: Using the 0 and 1 format, with 0 being empty squares and 1 being queens: ``` Input: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output: 0 Input: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output: 0 Input: 0 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 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 Output: 1 Input: 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 Output: 10 Input: 1 1 1 1 1 1 1 1 1 1 1 1 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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output: 4 Input: 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 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 Output: 11 ``` [Answer] # [Python 2](https://docs.python.org/2/), 105 bytes ``` lambda b:sum(b[i+d::d][:(8,7-i%8,i%8)[d%8%5]].find('1')*int(c)>0for i,c in enumerate(b)for d in[1,7,8,9]) ``` [Try it online!](https://tio.run/##PYvBDsIgEER/hQspKJpdE1Mk0R9BDqWUSNLSptKDX4/UqtnMJvNmZnqlxxhP2V/vuW8G6xpi1XMZmNVh75RyRismRX0IVIoirh2V9GzM0YfoWIUV34WYWMtv4MeZBNGSEEkXl6Gbm9Qxy1fsCtQoaiHFxfA8zWVDfJkDIgIAbofb/9k1QNgQfOyX/asVz28 "Python 2 – Try It Online") # Explanation We take the input as a string of 64 characters `'0'` or `'1'`. Using step slices, we cast four "lines of sight" from every queen we encounter. For example, when **i = 10** and **d = 7**, marking the queen as ♥ and the tiles selected by `b[i+d::d]` as █: ``` 1 0 1 1 1 0 0 0 1 0 ♥ 0 1 0 1 1 1 █ 1 0 1 1 0 1 █ 1 0 1 0 1 0 █ 0 1 1 0 0 1 █ 1 1 0 0 0 1 █ 0 0 0 1 0 0 █ 1 1 1 0 1 1 █ 0 1 0 1 ``` Clearly, we don't actually want vision to wrap around the board like this. So we compute how far away the edge of the board is in each direction, and view the tiles at `b[i+d::d][:…]`. For each tile-direction pair we count: ``` ray.find('1')*int(c)>0 ``` This will fail whenever * `c` is not a queen; or * the queen this ray sees is too close (`find` returns 0); or * this ray sees no queen (`find` returns −1). Each pair of queens is only checked once, since rays are always casted *forward* in reading order, from an "earlier" queen to a "later" one. [Answer] # JavaScript (ES7), 86 bytes Takes input as an array of 64 integers with **254** for a queen and **0** for an empty square. ``` a=>[s=0,6,7,8].map(d=>a.map(g=(n,p)=>(p%8-(p+=~d)%8)**2<n%4?a[p]?s+=n&1:g(n/2,p):0))|s ``` [Try it online!](https://tio.run/##fZBNDoIwEIX3nIINpoWClRglxIGVXoKwaPiLBtvGGsPCePVKiEbRwublzeSbl5k5sRtTxeUorz4XZaVr0AySTAElG7IlUR6cmUQlJGwwDSBOJIYESSfykfTgUWInwq4b7rizTlkm81R5wBeruEF8GfZwTDG@K10IrkRbBa1oUI0yy7Zpd9gT2lFKXu4jQ@8tJtTkeplHR@WAzgeOFjDF/A/9LGCiJlJN/OisyT99OyvHWD8B "JavaScript (Node.js) – Try It Online") This version abuses arithmetic underflow to get a stop condition in the recursive part. --- # JavaScript (ES7), 89 bytes Takes input as an array of 64 bits. ``` a=>[s=0,6,7,8].map(d=>a.map(g=(n,p,x)=>(p%8-(p+=~d)%8)**2>1|p<0?0:a[p]?s+=!x&n:g(n,p)))|s ``` [Try it online!](https://tio.run/##VU7LDoIwELzzFXjAdKGQ1oMS4sKHEA4NINFg21hjOBB/vWqVh5nMZncyM9mLeAhT3876HkvVtPaEVmBeGmR0Tw80rZKr0KTBXLilQyKppgNgTnSQxkRH@GwgSCEMdzkf9ZEVLBOlrgoT4WbYyqz7JABgNLZW0qi@TXrVkRMpPd/nlFHuwBxmaSL/l77zLa09vyCbe2bXVLuqXw4@1S8vOHoVgH0B "JavaScript (Node.js) – Try It Online") ### How? We recursively call a named callback function of `map()` to walk through the squares in a given direction. Although we don't really need the content of the third parameter of the callback (the array `map()` was called upon), we indirectly use it nonetheless to know whether it is the first iteration or not. > > *arr.map(function callback(currentValue[, index[, array]])* > > > This is the **x** variable in the code. ``` a => // given the input array a[] [ s = 0, // initialize the sum s to 0 6, 7, 8 ].map(d => // for each direction d in [0, 6, 7, 8]: a.map(g = (n, p, x) => // for each square n at position p in a[]: ( // we are out of the board if: p % 8 - // - abs(p % 8 - p' % 8) is greater than 1 (p += ~d) % 8 // where p' = p - (d + 1) ) ** 2 > 1 | // (squaring is shorter than using Math.abs) p < 0 ? // - or p' is less than 0 0 // if so, stop recursion : // else: a[p] ? // if there's a queen on the target square: s += // increment s if: !x & // x is undefined (this is not the 1st iteration) n // and n = 1 (there's a queen on the source square) : // else: g(n, p) // do a recursive call to g(), with x undefined ) // end of inner map() ) | s // end of outer map(); return s ``` [Answer] # [Snails](https://github.com/feresum/PMA), 14 bytes ``` A rdaa7\1\0+\1 ``` [Try it online!](https://tio.run/##K85LzMwp/v/fkasoJTHRPMYwxkA7xvD/f0MDQ0NDAwMDLiADBA0hDCDigggApUBcEJMLpBCsGEwCNXKBdQMhAA "Snails – Try It Online") Input is the 0/1 format, without spaces within lines. Snails was [created for a 2D pattern matching language design PPCG challenge](https://codegolf.stackexchange.com/a/47905/6972). Most importantly, it by default outputs the number of matches found, which is perfect for this challenge. --- `A` sets the "all paths" option, so that if a queen is in multiple pairs, each of those pairs would generate a match. `rdaa7` sets the match direction to S, SE, E, and NE. Setting to all directions (`z`) would cause double counting. `\1\0+\1` matches a `1`, then one or more `0`s, then another `1`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~41~~ ~~39~~ 32 bytes ``` (+/+⌿-⌈⌿)2<⌿0⍪⊢,⍉,8 31⍴⊢,≠⍨,⌽,≠⍨ ``` [Try it online!](https://tio.run/##pY/PDsFAEMbvnqK3JdqYD4dGvExDKqIJwUXETUTpikfASZy5SETiUeZFamiJ@B92k9n5ZnZ/O5/T8Kxyx/HqFavkOa1WtRSGLg@myXQmzcHe4mAoRypblEisVzxamKx90zZyYL0@S3/GemlysIvTMGwLoct6w/68KanLeltQ9ZricV@5TtVTUpB2s5fI59rygvXksLQNW4gKBICIEG1E8SJPDVBUorOMa9erKmHQPZP@XM@Y@HMJE1/PeTX6aU68845HHGKNu99w6z3/i3d66x14ZNJLBn3DPAI "APL (Dyalog Classic) – Try It Online") `≠⍨` is "not equal to itself" - an 8x8 all-zero matrix `⊢,≠⍨,⌽,≠⍨` - if the original matrix is `ABC...`, this expression returns: ``` A B C D E F G H 0 0 0 0 0 0 0 0 H G F E D C B A 0 0 0 0 0 0 0 0 I J K L M N O P 0 0 0 0 0 0 0 0 P O N M L K J I 0 0 0 0 0 0 0 0 Q R S T U V W X 0 0 0 0 0 0 0 0 X W V U T S R Q 0 0 0 0 0 0 0 0 Y Z A B C D E F 0 0 0 0 0 0 0 0 F E D C B A Z Y 0 0 0 0 0 0 0 0 G H I J K L M N 0 0 0 0 0 0 0 0 N M L K J I H G 0 0 0 0 0 0 0 0 O P Q R S T U V 0 0 0 0 0 0 0 0 V U T S R Q P O 0 0 0 0 0 0 0 0 W X Y Z A B C D 0 0 0 0 0 0 0 0 D C B A Z Y X W 0 0 0 0 0 0 0 0 E F G H I J K L 0 0 0 0 0 0 0 0 L K J I H G F E 0 0 0 0 0 0 0 0 ``` `8 31⍴` reshapes it from 8x32 to 8x31, reusing the elements in row-major order: ``` A B C D E F G H 0 0 0 0 0 0 0 0 H G F E D C B A 0 0 0 0 0 0 0 0 I J K L M N O P 0 0 0 0 0 0 0 0 P O N M L K J I 0 0 0 0 0 0 0 0 Q R S T U V W X 0 0 0 0 0 0 0 0 X W V U T S R Q 0 0 0 0 0 0 0 0 Y Z A B C D E F 0 0 0 0 0 0 0 0 F E D C B A Z Y 0 0 0 0 0 0 0 0 G H I J K L M N 0 0 0 0 0 0 0 0 N M L K J I H G 0 0 0 0 0 0 0 0 O P Q R S T U V 0 0 0 0 0 0 0 0 V U T S R Q P O 0 0 0 0 0 0 0 0 W X Y Z A B C D 0 0 0 0 0 0 0 0 D C B A Z Y X W 0 0 0 0 0 0 0 0 E F G H I J K L 0 0 0 0 0 0 0 0 L K J I H G F E ``` `⊢,⍉,` prepends the original matrix and its transpose (extra spaces for clarity): ``` A B C D E F G H A I Q Y G O W E A B C D E F G H 0 0 0 0 0 0 0 0 H G F E D C B A 0 0 0 0 0 0 0 I J K L M N O P B J R Z H P X F 0 I J K L M N O P 0 0 0 0 0 0 0 0 P O N M L K J I 0 0 0 0 0 0 Q R S T U V W X C K S A I Q Y G 0 0 Q R S T U V W X 0 0 0 0 0 0 0 0 X W V U T S R Q 0 0 0 0 0 Y Z A B C D E F D L T B J R Z H 0 0 0 Y Z A B C D E F 0 0 0 0 0 0 0 0 F E D C B A Z Y 0 0 0 0 G H I J K L M N E M U C K S A I 0 0 0 0 G H I J K L M N 0 0 0 0 0 0 0 0 N M L K J I H G 0 0 0 O P Q R S T U V F N V D L T B J 0 0 0 0 0 O P Q R S T U V 0 0 0 0 0 0 0 0 V U T S R Q P O 0 0 W X Y Z A B C D G O W E M U C K 0 0 0 0 0 0 W X Y Z A B C D 0 0 0 0 0 0 0 0 D C B A Z Y X W 0 E F G H I J K L H P X F N V D L 0 0 0 0 0 0 0 E F G H I J K L 0 0 0 0 0 0 0 0 L K J I H G F E ``` `2<⌿0⍪` adds 0s on top and compares using `<` every element against the element below it, so we get a 1 for the leading 1 in every vertical group of 1s, and we get 0s everywhere else `+⌿-⌈⌿` the sums by column minus the maxima by column - we compute the number of gaps between the 1-groups in every column, 0 if there are none `+/` sum [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes ``` t0ŒgL:2 Z,U;ŒD$€ẎÇ€S ``` [Try it online!](https://tio.run/##y0rNyan8/7/E4OikdB8rI64onVDro5NcVB41rXm4q@9wO5AO/v//fzRXtKGOgY4hGBqAYKwOTAiGDVGFwCRICFkNVKMB3By4KqixyMbDORB7ERrh5sVyxQIA "Jelly – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~45~~ 43 bytes -2 bytes thanks to @coltim ``` {+/0|-1+/0|-':x,'+x,+8 31#,/+x,a,(|x),a:^x} ``` [Try it online!](https://ngn.codeberg.page/k#eJylj8sKgzAQRff5ioAFFVOciy4k+RRJURdCaaEgLiI+vr2tLxRrS3ECk3lxZm4ua8+n5oze29II2zPCi3gAS/ivMBVOY1yRyotpGStlfYqrrpA5Nyp53JST5On1royqVOHqlpVxxCMLBICIMDwMfkrfDdBQoj4da/NopsNgRNFByzSn6aqDtkDtrpvV/LwKWxRWwQKFNRLLFZnGPwLpu8BwRm0Haef/jALYExxlfoE=) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~60~~ 58 bytes ``` 1 ¶1$';___¶ _ $n$%`7$*_ (.)(?=.*;(_)*)(?<-2>.)* $1 m`^10+1 ``` [Try it online!](https://tio.run/##K0otycxL/B@ScGibQoJO/H9DrkPbDFXUrePj4w9t44rnUslTUU0wV9GK59LQ09Swt9XTstaI19QCMm10jez0NLW4VAy5chPiDA20Df//N1BAgVwQ2hCNDxfhQpIDsVDkkfnYzMMiDwA "Retina 0.8.2 – Try It Online") Takes input as 8 comma-separated 8-character binary strings, but the header converts the provided format for you. Explanation: ``` 1 ¶1$';___¶ ``` Create all of the substrings of the board starting at a queen. Suffix a marker value to each substring. Edit: Saved 2 bytes by leaving some garbage strings behind; these are effectively ignored. ``` _ $n$%`7$*_ ``` Split each marker up into an inclusive range, and add 7 to the non-zero elements. ``` (.)(?=.*;(_)*)(?<-2>.)* $1 ``` Delete every run of characters that equals the length of the marker. This is equivalent to finding each east, southwest, south or southeast ray from each queen. ``` m`^10+1 ``` Count all the rays that pass through at least one empty square before meeting another queen. [Answer] # JavaScript (ES6) + [SnakeEx](http://www.brianmacintosh.com/snakeex/), 38 bytes ``` s=>snakeEx.run('m:<*>10+1',s).length/2 ``` Takes input in the form `'10111000\n10101011\n10101101\n01010100\n01100101\n10001000\n01000111\n01110101'`. Turns out, SnakeEx can still be used outside of its original challenge! ]
[Question] [ # Goal: Given an array of strings, create abbreviated​ versions of each string. # Specification: For this challenge, an abbreviation is the first N characters of a string. For the string `abc`: `a`, `ab`, and `abc` are all valid abbreviations, while `bc`, and `ac` are not. Given an array of strings, we want to find the shortest set of abbreviations, such that given the input and any abbreviation, you could determine which item of the input that the abbreviation was referring to. # Example: Input: `["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]` We work our way through the strings starting with the first one. * Monday is only the item string with an `M`, so the shortest possible abbreviation is `M`. * Tuesday starts with`T`, but so does Thursday. This means that we try the string `TU`. Since no other strings start with that, we use `TU`. * Wednesday is `W`, Thursday is `Th`, and Friday is `F`. # More Examples: ``` Input: "one,two,three,four,five,six,seven" Output: "o,tw,th,fo,fi,si,se" Input: "red,orange,yellow,green,blue,purple" Output: "r,o,y,g,b,p" Input: "a,ab,abc" Output: Not valid! No abbreviation for `a` that doesn't apply to the other items. ``` # Notes: * You make input and output in any reasonable way. * You can assume that input will always be a valid array of strings. * You can assume that there will always be a solution, unlike in the last test case. * Strings will only consist of printable ASCII (or the printable characters in your encoding) * This is code golf, so fewest bytes win! [Answer] ## [Retina](https://github.com/m-ender/retina), 29 bytes ``` !ms`^(.+?)(?!.+^\1)(?<!^\1.+) ``` Input and output are linefeed-separated lists of strings. [Try it online!](https://tio.run/nexus/retina#DcqxCoMwFIXh3bfIUIjkEOhe8Ak6dRXR0qMV0hu5Mdo@fZrp/4b/Yh8jyt180jhY77rWdsa7ob9W3Eytd23ppUGJQuxnxP5WEnPMink9iLR@kXhQGuULUSdZiB9DiCeWugqeIRNb1i3wDw "Retina – TIO Nexus") (Test suite with comma-separation for convenience.) ### Explanation This simply matches all the prefixes with a single regex and prints them (`!`). `m` and `s` are the usual regex modifiers to make `^` match line beginnings and `.` match linefeeds. ``` ^(.+?) # Match the shortest possible prefix of a line and capture # it in group 1. (?!.+^\1) # Make sure that this prefix does not show up in a line after # the current one. (?<!^\1.+) # Make sure that this prefix does not show up in a line before # the current one. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~87~~ 86 bytes ``` lambda a:[b[:min(i for i in range(len(b))if sum(s[:i]==b[:i]for s in a)<2)]for b in a] ``` [Try it online!](https://tio.run/nexus/python2#NcuxDgIhEATQX9lQQWJleZHWzspLLJBiCaCbHHsGjsKvx8Cd1bxJZqJ@tgWT8wg4GWemRCwJ4pqBgBgy8ivIJbB0SlGEUpMsZiKrtevRh6UPUV3OalQ3qm2fTLxBlEbcVvb4FScx11B2PYLnv@d3zQevmXbccav5YB1vq9oP "Python 2 – TIO Nexus") [Answer] ## JavaScript (ES6), ~~81~~ ~~78~~ ~~74~~ 70 bytes Takes input as an array of strings. ``` a=>a.map(s=>[...s].reduce((y,c)=>a.some(x=>x!=s&!x.indexOf(y))?y+c:y)) ``` ### Formatted and commented ``` a => // given an array of strings 'a' a.map(s => // for each string 's' in 'a': [...s].reduce((y, c) => // starting with 'y' = first character of 's', // for each subsequent character 'c' of 's': a.some(x => // if we find a string 'x' in 'a' such that: x != s & // - 'x' is different from 's' !x.indexOf(y) // - and 'y' appears at the beginning of 'x' ) ? // then: y + c // append 'c' to 'y' : // else: y // keep 'y' unchanged ) // end of reduce(): returns the correct prefix ) // end of map() ``` ### Test cases ``` let f = a=>a.map(s=>[...s].reduce((y,c)=>a.some(x=>x!=s&!x.indexOf(y))?y+c:y)) console.log(JSON.stringify(f(["Monday","Tuesday","Wednesday","Thursday","Friday"]))) console.log(JSON.stringify(f(["one","two","three","four","five","six","seven"]))) console.log(JSON.stringify(f(["red","orange","yellow","green","blue","purple"]))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ;\w@þ=1Si1⁸ḣð€ ``` [Try it online!](https://tio.run/nexus/jelly#@28dU@5weJ@tYXCm4aPGHQ93LD684VHTmv8Pd295uGMTkHW4HUh4A3Hk///5eakKJeX5CiUZRampCmn5pUUKaZllqQrFmRUKxallqXlcRakpCvlFiXnpqQqVqTk5@eUK6UCleQpJOaWpCgWlRQU5qQA "Jelly – TIO Nexus") ### How it works ``` ;\w@þ=1Si1⁸ḣð€ Monadic link. Argument: A (string array) ð Collect all links to the left into a chain (arity unknown) and begin a dyadic chain. € Map the previous chain over A. The current chain is dyadic and the mapped one inherits its arity. Thus, the right will be A for all invocations, while the left argument will iterate over A. For each string s in A, the following happens. ;\ Cumulative reduce by concatenation; yield all prefixes of s. w@þ Window index swapped table; for each string t in A and each prefix p of s, find the index of the substring t in p. The first index is 1; 0 means not found. =1 Compare the indices with 1, returning 1 iff t begins with p. S Sum the Booleans across columns, counting the number of strings in A that begin with a given prefix. i1 Find the first index of 1, the shortest prefix that is unique across all strings in A. ⁸ Head; truncate s to the computed length. ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` [_]#x="" a#(c:y)=c:[z|d:z<-a,c==d]#y f=map=<<(#) ``` [Try it online!](https://tio.run/nexus/haskell#NYu9DoMwEIN3HiN0AInyAIis3bohdUCoSskBkcIFHYQ/9d1pQtvF/mzLvVDIFU5Aop4uFrVCGNNeDNHYmSVtUgIh4/Ssj/JZhStnLBBhVGdbzOus3N8y2/OrSGrOZRVuQcPdm@d5FMbHUbK7QSk2lrDCwvilB0j8c9FZ@uGNlIcqKJlBcMW0GK8dgU@NseRNzT6NavUKM@D5IJAuGxLY@nkDrc3ioHVndP7S1veDpUEDqz4 "Haskell – TIO Nexus") * `f` is the main function, taking a list of `String`s and returning a `String`. Its definition is a monadic shortcut for `f a=map (a#) a`. * `a#x` looks at the string `x` and the list `a` and tries to find the shortest prefix of `x` that is unique in `a`. If `a` has a single element, just use the empty string. If `a` isn't already a single element, chop off the first character of `x`, filter and chop the elements of `a` starting with the same character, then recurse. [Answer] ## Mathematica, 64 bytes ``` #&@@@StringCases[#,Shortest@x__/;Tr@Boole@StringStartsQ[#,x]<2]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes ``` ḣ€JṙLḶ$ḟ/€Ḣ€ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx@JHTWu8Hu6c6fNwxzaVhzvm6wP5D3csApL/H@7e8nDHJiDrcDuQ8AbiyP//8/NSFUrK8xVKMopSUxXS8kuLFNIyy1IVijMrFIpTy1LzuIpSUxTyixLz0lMVKlNzcvLLFdKBSvMUknJKUxUKSosKclIB "Jelly – TIO Nexus") ### How it works ``` ḣ€JṙLḶ$ḟ/€Ḣ€ Main link. Argument: A (string array) J Yield the 1-based indices of A, i.e., [1, ..., len(A)]. ḣ€ Head each; for each string s in A, take the first 1, ..., and len(A) characters. This builds the 2D array of prefixes of all strings in A. LḶ$ Length-unlength; yield [0, ..., len(A)-1]. ṙ Rotate the 2D array 0, ..., and len(A)-1 units to the left. ḟ/€ Reduce filterfalse each; for each rotation, remove all prefixes from the first set that also occur in later sets. Ḣ€ Head each; for each rotation, keep only the shortest unique prefix. ``` [Answer] # Javascript ES6, 70 chars ``` s=>(s+'#'+s).replace(/(\w+?)(\w*)(?=(\W(?!\1(?!\2))\w+)+$)|#.+/g,"$1") ``` ``` f=s=>(s+'#'+s).replace(/(\w+?)(\w*)(?=(\W(?!\1(?!\2))\w+)+$)|#.+/g,"$1") console.log(f("one,two,three,four,five,six,seven")==="o,tw,th,fo,fi,si,se") console.log(f("red,orange,yellow,green,blue,purple")==="r,o,y,g,b,p") console.log(f("one,two,three,four,five,six,seven".split`,`)==="o,tw,th,fo,fi,si,se") console.log(f("red,orange,yellow,green,blue,purple".split`,`)==="r,o,y,g,b,p") ``` [Answer] # C++11 (MinGW), 198 bytes ``` #import<list> #import<iostream> f(std::list<std::string>l){int i,m;for(auto s:l){for(i=0,m=1;++i<s.length();)for(auto t:l)if(t!=s&&t.substr(0,i)==s.substr(0,i))m=i+1;std::cout<<s.substr(0,m)<<" ";}} ``` Call with: ``` int main() { f({"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}); } ``` Adding `void` identifier before the function should make it compile on other compilers too, thereby adding 5 bytes to the length. [Answer] # PHP, ~~131 120 119~~ 118 bytes Thanks @Jörg for `preg_grep`. ``` for(;a&$s=$argv[++$k];$i=+$t=!print"$t ")for(;a&$s[$i]&&1<count(preg_grep("(^".preg_quote($t.=$s[$i++]).")",$argv));); ``` takes input from command line arguments; prints results one line each. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/6ca707651a82122e2e248a50aab3b711b605eb42). * may fail if input contains anything starting with `-`. +15 bytes to fix: replace the second `$argv` with `array_slice($argv,1)`. * yields warnings in PHP 7.1; replace `a&` with `""<` (+1 byte) to fix. * -12 bytes if input contains no regex special chars: Insert `&($t.=$c)` before `&&` and replace `". preg_quote($t.=$c)."` with `$t`. **breakdown** ``` for(;a&$s=$argv[++$k]; # loop $s through arguments $i=+$t=! # 3. reset $i and $t to empty print"$t\n") # 2. print abbreviation for(;a&($c=$s[$i++]) # 1. loop $c through characters &&1<count( # 3. if count==1, break loop preg_grep("(^" # 2. find matching arguments . preg_quote( $t.=$c # 1. append $c to abbreviation ).")",$argv) ); ); ``` **non-regex version, ~~131~~ 130 bytes** ``` for($a=$argv;a&$s=$a[++$k];$i=+$t=!print"$t ")for($n=1;$n&&a&$c=$s[$i++];)for($n=$m=1,$t.=$c;a&$u=$a[$m++];)$n-=0===strpos($u,$t); ``` Replace the first and the last `a&` with `""<` (+2 bytes) to fix for PHP 7.1. **breakdown** ``` for($a=$argv;a&$s=$a[++$k]; # loop through arguments $i=+$t=!print"$t\n") # 2. print abbreviation, reset $i and $t to empty for($n=1;$n&&a&$c=$s[$i++];) # 1. loop through characters while $n<>0 for($n=$m=1, # reset $n and $m to 1 $t.=$c; # append current character to prefix a&$u=$a[$m++]; # loop through arguments: )$n-=0===strpos($u,$t); # -$n = number of matching strings -1 ``` completely uninteresting note: `strstr($u,$t)==$u` and `0===strpos($u,$t)` have the same length and the same result. [Answer] # PHP, 127 Bytes works not with invalid arrays ``` <?foreach($a=$_GET as$k=>$v)for($i=0,$c=2,$s="";$c>1;$r[$k]=$s)$c=count(preg_grep("_^".($s.=$v[$i++])._,$a));echo join(",",$r); ``` ## PHP, 132 Bytes ``` <?foreach($a=$_GET as$v)for($i=0,$s="";a&$v[$i];)if(count(preg_grep("_^".($s.=$v[$i++])._,$a))==1){$r[]=$s;break;}echo join(",",$r); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/45b4bc835b8c5c1269dc9fa8ca75349086865eef) ## 151 Bytes supports special characters ``` <?foreach($a=$_GET as$v)for($i=0,$s="";a&$v[$i];)if(count(preg_grep("_^".preg_quote($s=substr($v,0,++$i),_)._,$a))==1){$r[]=$s;break;}echo join(",",$r); ``` ## PHP, 140 Bytes ``` <?foreach($a=$_GET as$k=>$v)for($i=0;a&$v[$i];)if(count(preg_grep("#^".($s=substr($v,0,++$i))."#",$a))==1){$r[]=$s;break;}echo join(",",$r); ``` [Answer] ## Clojure, 118 bytes ``` #(reduce(partial map(fn[a b](or a b)))(for[i(range 1e2)S[(for[c %](take i c))]](for[s S](if(=((frequencies S)s)1)s)))) ``` This works on prefixes up-to length of `1e2` but the same byte count can support up-to `1e9`. `i` loops lengths of prefixes, `S` is the sequence of substrings of length `i`. The last `for` replaces those substrings with `nil` which occur more frequently than once. The reduction keeps the first non-nil value for each string, too bad `or` isn't a function so I had to wrap it. This actually returns lists of lists of characters like `((\M) (\T \u) (\W) (\T \h) (\F))`, but I guess it is acceptable. Clojure is quite verbose with strings, and `subs` would throw `StringIndexOutOfBoundsException` unlike `take`. Full examples: ``` (def f #(reduce(partial map(fn[a b](or a b)))(for[i(range 1e2)S[(for[c %](take i c))]](for[s S](if(=((frequencies S)s)1)s))))) (f ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]) (f (re-seq #"[^,]+" "one,two,three,four,five,six,seven")) (f (re-seq #"[^,]+" "red,orange,yellow,green,blue,purple")) ``` [Answer] # SQL (PostgreSQL 9.4 flavour), 219 bytes Now for the longest answer:) I don't think this could even beat Java. I will try to shave a few more off this. Hoping to get rid of one of the nested queries, but don't like my chances. This assumes that there is a table that contains the strings to be worked on. As this is SQL the order of the return is not guaranteed to be the same as the table order and in this case unlikely. If this is a problem I will delete. ``` SELECT R FROM(SELECT*,RANK()OVER(PARTITION BY A ORDER BY C,N)Z FROM(SELECT*,SUM(1)OVER(PARTITION BY R)C FROM(SELECT*FROM A JOIN LATERAL(select left(A,n)R,N FROM generate_series(1,length(A))S(n))L ON 1=1)X)Y)Z WHERE Z=1 ``` [SQL Fiddle](http://sqlfiddle.com/#!15/fbd37/2/0) Explanation ``` SELECT * FROM A JOIN LATERAL(SELECT LEFT(A,n)R,N FROM generate_series(1,length(A))S(n))L ON 1=1 ``` The innermost query uses `generate_series` and a `LATERAL` join to create rows for the string split into increasing lengths, so 'one' becomes 'o','on','one'. The number of characters in the return is also kept. ``` SELECT *, SUM(1)OVER(PARTITION BY R)C FROM ( ... )X ``` Then we add the number of records which have the same result. For example 'f' from four and five has 2, but 'fo' and 'fi' each have one. The `OVER` statement in SQL can be quite powerful. `COUNT(*)` would be the usual way, but `SUM(1)` gives the same result. ``` SELECT *, RANK()OVER(PARTITION BY A ORDER BY C,N)Z FROM ( ... )Y ``` Then we rank the results for each input based on the least repetitions and characters. `ROW_NUMBER` would work here as well, but is longer. ``` SELECT R FROM ( ... )Z WHERE Z=1; ``` Finally we select the lowest rank number for each word. [Answer] # [Pure Bash](https://www.gnu.org/software/bash/), 146 bytes ``` for i in $@;{ K=1;U=${i::1};((M++));L=;while [[ `for v in $@;{ ((L++));(($L!=$M))&&echo ${v::K}||:;}` =~ $U ]];do U=${i::K};((K++));done;echo $U;} ``` [Try it online!](https://tio.run/nexus/bash#PYyxCsIwFEV/5QmhJIhD1zwCTi5ptxaHUmhpIglIApVWpI1/7RxtFKdzhntuvPgRLFgH5IgLSJFjLchiOc8DUlru94xhIfBu7FVD00C3BfM/oLRIE0pJsROkZCzL9GA8kGXmXIZ15Rg6EE8gNbQtKg@/f7n9yxQr7zR@qxpDjLH0TvWPWE36tvGslUtSmWlMchrtBy/nD0M/GP0G "Bash – TIO Nexus") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 27 bytes ``` {⍵↑¨⍨1⍳⍨¨↓+/(↑,\¨⍵)∘.(⊃⍷)⍵} ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG1C9aPerY/aJh5a8ah3heGj3s1ACshum6ytrwEU1okBSWzVfNQxQ0/jUVfzo97tmkB@7f//aQrq@Xmp6grqJeX5IDKjKBXES8svLQJRmWUgXnFmBYhMLUvNU@cC6ihKTQHy84sS89JB0pWpOTn55UBGOlBzHpBOyikFiReUFhXkpKoDAA "APL (Dyalog Unicode) – TIO Nexus") `{` an anonymous function, where ⍵ represents the argument...  `∘.(` a function table where the function is   `⊃` the first element of   `⍷` the Boolean list "left argument begins here in the right argument?"  `)` where the right arguments are  `⍵` the arguemts  `(` and the left argument is   `↑` a table with rows consisting of   `,/` prefixes of   `¨` each of   `⍵` the arguments  `+/` sum across (counts how many of the arguments befin with this prefix)  `↓` split table into list of rows  `⍳⍨¨` in each one, find the location of the first  `1` one (i.e. the first prefix that only heads one argument)  `↑¨⍨` for each location, takes that many characters from the corresponding element of  `⍵` the argument `}` end of anonymous function [Answer] # PowerShell, 151 139 bytes ``` $x,$w=@(),$args[0];$w|%{$k=$_;$a='';foreach($l in [char[]]$k){$a+=$l;if($a-notin$x-and!($w|?{$_-ne$k-and$_-like"$a*"})){$x+=$a;break;}}};$x ``` Interested if there's a better way to do this. Had to use a `foreach` (over a `|%`) to be able to perform a `break` in the nested loop without labeling it. Edit: 2 golfs from AdmBorkBork [Answer] # APL, 26 bytes ``` {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵} ``` Explanation: * `↓↑⍵`: pad each string in `⍵` to match the length of the longest string * `∘.(`...`)⍨`: for each possible pair of strings, find the shared prefix: + `≢`: array inequality + `∧`: and + `=`: itemwise equality + `∧\`: and-scan (keep only the leading matches) * `+/¨`: sum each vector in the table, giving the length of the shared prefixes * `⌈/`: find the maximum value in each column * `1+`: add one, giving the amounts of characters needed to keep each string unique * `⍵↑¨⍨`: take that many characters from each string Test: ``` {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' ┌─┬──┬─┬──┬─┐ │M│Tu│W│Th│F│ └─┴──┴─┴──┴─┘ {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'one' 'two' 'three' 'four' 'five' 'six' 'seven' ┌─┬──┬──┬──┬──┬──┬──┐ │o│tw│th│fo│fi│si│se│ └─┴──┴──┴──┴──┴──┴──┘ {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'red' 'orange' 'yellow' 'green' 'blue' 'purple' ┌─┬─┬─┬─┬─┬─┐ │r│o│y│g│b│p│ └─┴─┴─┴─┴─┴─┘ ``` [Answer] ## Q, 93 bytes ``` {n:1;{$[any e:(,/)1<{(+/)i like x}each i:z#'x;[z+:1;y:?[e;z#'x;i];.z.s[x;y;z]];y]}[x;n#'x;n]} ``` Solved recursively, takes string as input, gets first n elements of each string with every recursion. If any of those elements aren't unique it replaces them with first n+1 elements. ]
[Question] [ This time, you are working on a regex. Your regex is meant to approximately full-match the base-10 representations of primes \$0 \le p < 1000\$, while ignoring any non-numeric string or composite in the range. You can full-match 2, 53 or 419, but not 0, 82 or example. The approximately is important -- a minimum of **900** numbers have to produce the right output. You can match more numbers correctly (but as this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge you probably shouldn't). For clarification, how numbers above 1000 are matched **doesn't matter** and they can produce whatever output you like. Test cases part 1, strings which should be matched ([primes under 1000](https://www.infoplease.com/math-science/mathematics/numbers-formulas/prime-numbers-between-1-and-1000)): ``` 5 739 211 617 103 503 11 13 17 23 71 89 257 ``` Part 2: strings that shouldn't be matched ``` five 5o 2q11 716 102_3 42 + 1 term in A000040 16 204 ``` Your score is the number of characters in your regex. Lowest score wins. Have fun! [Answer] # ~~90~~ ~~79~~ ~~72~~ ~~67~~ ~~65~~ 64 bytes `^(?!([258][0369]*[147]|[1475][258]|[147]{3}|[0369])+$)\d+[1379]$` Matches 2–3-digit numbers not divisible by 2, 3, or 5, with an added bit (the `5` in `[1475]`) that removes 8 false positives (527, 529, 551, 553, 559, 581, 583, 589) and adds 4 false negatives (521, 523, 557, 587). -2 thanks to Nahuel Fouilleul; -9 by removing `[258]{3}`, which was not necessary; -7 by removing one `[0369]*`; -5, -2, -1 with successive improvements on an idea from tsh. [Answer] # ~~101~~ 96 bytes This is manually optimized and probably sub-optimal. ``` ^((10?|19|82)[1379]|(31|46?|64|88)[137]|(6?5|8|17|23?|26|3[578]|44|5[069])[39]|(22|61|85)[379])$ ``` [Try it online!](https://tio.run/##bZJNbxMxEIbv@RVLBW1WccP626ZEOcERVVyjoEbpEi0K2SgbKiTMbw/PhFJRxGG09qzfd54Z@8vqYTWsD93@eL3r79tTW82qj@3m3ff9@O70aTzWzbzoXJKpF9rGvCxjq4sL8xJcSemcJBfmvqSiYzF2XkwoduFjWhbnil80IS/rhRWpMSXokjxbrOqXp7vpsO3W7Vir6lrX9Wi0P3RfBWFhlFVeRaW10lZpFlkZq0xWVisbldPKWeWi8pzLKmgVoopaRatiVsmqlFVG1aBvMGhknbFjbVhb8ZUvOUd49p594D9OOkpR8ol8lmAvfhkMmIyw4GOMYLHGx8BkvAR5fEwgB5KJ7PExSfitsrBYPCwsls6sdASLdRI0SEuWniwcFg5mpSxaS0sWBkdPjl4cI3FG5iDBMGBwMhQ8HAyOoTg4HD4OD5f40oujB89MPB4evacXD7uXaaLzaDzsHnYPu0fns4yZOVM7wB9gD1q@5KgfnAQ5PAL8Qe7kfCms8QjwB2rHRiJzUwTzi3BHuCPayOwi9SO6SP0od0ntSM8JTWJmyUhwu2iTkYsmqJfQJWom2BP1EvNO8grQZ3gz2kzNjCYz6wxvhjWjzcwn02tGl9FkOHOOy5vR6PNqO7S3/cCLPC8/tBuWjfzpD@Nh3R/kse7OOT5vK900sppM6urHqKq64fbxQZ8f9rTbrbff7tthvKtv@P3bYDKr2umxHY5kq9nsj0gOPNV/dubysnrx7yEh49CLZ6eeDv0crfvd0G/b6bbfPHK/BraaVFevrmD5@/fFezGs9v3QHbuH9s2FeuL4/8ldu1k9OwlMfXP6BQ "JavaScript (Node.js) – Try It Online") This matches 68 prime numbers and nothing else. [Answer] # 69 primes, 831 composites, 83 bytes ``` ^((3+|46?|60?|1[0359]?|75|9[479])[17]|(3?[78]|6?[15]|[15][069]|2[236]?|4[34])[39])$ ``` [Try it online!](https://tio.run/##FYsxDsMgEAT7@0XEWQIjRcZgCBVlqrzgjCFSXKRJEaW8d@UB@RjBxa52pNn3/nm@7g1ijDj@vgB4rjDIa22blFaz84n9lNjQZJeYE4eFI7kQsyITMkubKFwy@0RmyXwUTT5mnmm2vvuOrOuu7QdsOApQdX1owLHAcKsb8lZ6ZClarUYfM52kEJ1mjUqAaX8 "Retina 0.8.2 – Try It Online") Link is to test suite that counts the number of correctly matched integers. (The composite number that it incorrectly detects as prime is 169.) # 68 primes, 832 composites, 85 bytes ``` ^((31?|46?|60?|1[0359]?|75|9[479])[17]|(1[079]?|2[236]?|5[069]?|73?|82?|3[578])[39])$ ``` [Try it online!](https://tio.run/##HZK7jhxBCEVzfmNtaTbr4lFA1OF@RGusdeDAiQPLYf/7@LABqiqmLxwu8/fXv99/fr6@Pz4@Xz8eD1vn7fu893He6zos@nneGXdfnv18v1Y@7wc/5OT1UtuccR376zs779Lztiuy@NhQfHu9yfvHp7y9VExCUtaSZbK4tKiJttgSS/ElbuIpwXcte8lOySVpki1lUi2N6kB/UOCYe1OOu3K3qTsnOSeCd/De/E6lldOUfJHvCd5Tr8GASYeFOqqDxZ06CpPGBHnq6CYHkiZv6mgNv4nBYtQwWIzJbCaCxXyCARkJK8XgMDgMDkNrjGQwODM5sziWuI4PE5gBg48p1HAYHFMcDqcO@xAvTmZxZgg8CWoE@mCWgD3GTXSBJmAP2AP2QBc9NuMzvTf8G/a95iRH/@0T5Kix4d@zk6@lcKfGhn/TO4@JZlME/iXcCXeiTbxL@ie6pH/OLumdzFxoCs9KJ9gu2tJZNEG/Qlf0LNiLfoXfNf8C9A1vo216NprG64a3YW20jT/NrI2u0TSc3fkf "Retina 0.8.2 – Try It Online") Link is to test suite that counts the number of matched prime numbers. [Try it online!](https://tio.run/##HUs9DsIgFN7fLQzPBEpiChQo0xudPAFtwUQHFwfj@M7lAbwYUocv3//r/n48rw1SSjh8PwB4qnCU59o2KZ0hngJxGIlNHp1PK3H0nPIU06qyiSvLXsQ9t9m60NnnMfx3jni2xC77OPex6w9sOAhQdblpwKHA8VI35K10yFK0WozeJR2kEN1ZjUqAaT8 "Retina 0.8.2 – Try It Online") Link is to test suite that counts the number of correctly matched integers. [Answer] # Classic regex, ~~526~~ 452 characters. ``` 9(9(7|1)|83|7(|7|1)|67|53|4(7|1)|37|29|1(9|1)|07)| 8(9|8(7|3|1)|77|63|5(9|7|3)|3(|9)|2(9|7|3|1)|11|09)| 7(|9(|7)|87|73|6(9|1)|5(7|1)|43|3(|9|3)|27|1(|9)|0(9|1))| 6(91|83|7(|7|3)|61|5(9|3)|4(7|3|1)|31|1(|9|7|3)|0(7|1))| 5(|9(|9|3)|87|7(7|1)|6(9|3)|57|4(7|1)|3|2(3|1)|0(9|3))| 4(9(9|1)|87|7(|9)|6(7|3|1)|57|4(9|3)|3(|9|3|1)|21|1(|9)|0(9|1))| 3(|97|8(9|3)|7(|9|3)|67|5(9|3)|4(9|7)|3(7|1)|1(|7|3|1)|07)| 2(|9(|3)|8(3|1)|7(7|1)|6(9|3)|5(7|1)|41|3(|9|3)|2(9|7|3)|11)| 1(9(|9|7|3|1)|81|7(|9|3)|6(7|3)|5(7|1)|49|3(|9|7|1)|27|1(|3)|0(9|7|3|1)) ``` **This is non-competitive answer for reference, giving the accurate match.** Two more bytes `^...$` may be needed in a given implementation language/utility to anchor this. In POSIX world, this is an "extended" regex (ERE); a basic regex (BRE) requires escaped parentheses, otherwise they are literal. This was calculated by creating a trie structure out of the data set, applying path compression, and then converting to regex. This can be improved by reducing patterns like `(9|7|3|1)` into `[9731]` character classes, and empty branches `(|3)` into `3?` and such: ``` 9(9[71]|83|7[71]?|67|53|4[71]|37|29|1[91]|07)| 8(9|8[731]|77|63|5[973]|39?|2[9731]|11|09)| 7(97?|87|73|6[91]|5[71]|43|3[93]?|27|19?|0[91])?| 6(91|83|7[73]?|61|5[93]|4[731]|31|1[973]?|0[71])| 5(9[93]?|87|7[71]|6[93]|57|4[71]|3|2[31]|0[93])?| 4(9[91]|87|79?|6[731]|57|4[93]|3[931]?|21|19?|0[91])| 3(97|8[93]|7[93]?|67|5[93]|4[97]|3[71]|1[731]?|07)?| 2(93?|8[31]|7[71]|6[93]|5[71]|41|3[93]?|2[973]|11)?| 1(9[9731]?|81|7[93]?|6[73]|5[71]|49|3[971]?|27|13?|0[9731]) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 405 bytes ``` 1(0[1379]|13?|27|3[179]?|49|5[17]|6[37]|7[39]?|81|9[1379]?)|2(11|2[379]|3[39]?|41|5[17]|6[39]|7[17]|8[13]|93?)?|3(07|1[137]?|3[17]|4[79]|5[39]|67|7[39]?|8[39]|97)?|4(0[19]|19?|21|3[139]?|4[39]|57|6[137]|79?|87|9[19])|5(0[39]|2[13]|3|4[17]|57|6[39]|7[17]|87|9[39]?)?|6(0[17]|1[379]?|31|4[137]|5[39]|61|7[37]?|83|91)|7(0[19]|19?|27|3[39]?|43|5[17]|6[19]|73|87|97?)?|8(09|11|2[1379]|39?|5[379]|63|77|81|9)|97 ``` [Try it online!](https://tio.run/##TZCxbsMwDET3fkVHaWhgmpZpDYWm/kBXwUCC1AlSJHaQBEkH/rtLUoWbxZDEO97zfW/um@v2cjjf3sbpa5h37@sZXJUBKfYMmLgmxgxyS9xEDnLsuc0oX8qorx1wLPrkuXYAXGdzY5k38O@K6tJzJ46eIyafGF1FDLpC1GjjJuuCYIaWliS7RxJPo4xKGIUQ1FWyTBFIssAQZdyR8sXecxCTzmsLR1FrlqmfyFSuyySl1RR5A/shgQP16OI/NFA0xe6QI3imZyxaGsClAR0SWghpQueqyFZZaRzFGEp9LTKRtetFPK9fttN4nY7D6jjt3Tg8Xj@H/cfP2e1Wt8vh5Lz38y8 "JavaScript (Node.js) – Try It Online") Similar to the one below, but optimized by a simple program I wrote similar to <https://github.com/noprompt/frak> --- # [JavaScript (Node.js)](https://nodejs.org), ~~578 bytes~~ ``` 2|3|5|7|11|13|17|19|23|29|31|37|41|43|47|53|59|61|67|71|73|79|83|89|97|101|103|107|109|113|127|131|137|139|149|151|157|163|167|173|179|181|191|193|197|199|211|223|227|229|233|239|241|251|257|263|269|271|277|281|283|293|307|311|313|317|331|337|347|349|353|359|367|373|379|383|389|397|401|409|419|421|431|433|439|443|449|457|461|463|467|479|487|491|499|503|509|521|523|541|547|557|563|569|571|577|587|593|599|601|607|613|617|619|631|641|643|647|653|659|661|673|677|683|691|701|709|719|727|733|739|743|751|757|761|769|773|787|797|809|811|821|823|827|829|839|853|857|859|863|877|881 ``` [Try it online!](https://tio.run/##HZExbgJBDEX7nCIlFEE7Y3s8U6TMBXICEAFERAABSlL47pvnFNZ6DP/72f7cfG/u29vx@ng5Xz528/51PdeQsPAoJYpEIRlRJeoIKSEeWkIl1MP434hWonl4CZfwEV2ijxioJvQTBlPmAzvySi7pm19qShhv4934Hafi2ZR6pz4yeKffAAOmmiz41JpY5PhUmKplUMenNmogVeeNT@3JLyGwCB4CizCZ5ESwiGYwICMJMwkcAofAIWiFkQQGZSZlFmUlWnMPGSwDBs2l4KEwKEtROBQfxUM7X2ZRZjB2YngYemMWg91ym@gMjcFusBvshs5Grpk907vB32BvJb/U6N80gxoeDf6WN/k/CjkeDf5Gb58yBpci2J/D7XA7Wmd3Tn9H5/T3vCW9nZk7ms7Oes3gumh7zUMT9OvoOj077J1@vZd5/bS9nO@X0251uhwW593P8/vu8PZ7XexXj9vxa7FcLuc/ "JavaScript (Node.js) – Try It Online") contains 152 of the 168 prime numbers under 1000 ~90% cant get simpler can it? [Answer] # Any flavor, 148 bytes ``` ^([389]?113?|2(39?|2[379]|[147]1|[9862]3)?|(1[023569]?|4[568]?|6[147]?|9[03469]?|3[013469]?|8[8572]|7[259]|5[4578]|)7|1?[357]|[258]9|[37]1|[4785]3)$ ``` [Try it online!](https://tio.run/##LZLLaiMxEEX3/gotBtINItNS6VWB4FW@oumBTHASg1@0HZghnW/3nHJmUZZU7nvrVEmnv5f340Haab5et/vTcb64ebM6zdv95vz4Gb347KsPwQfxgY36KD6ql@Cl@hR8Ep@qz3ynvgRfqq/BV/FVfRPf1CuqAf2AwWB7xY59ZC/mayu5RGTOmXPhf5xCtaLkG3m14Gx@CgZM0VjwidGw2OMTYYrZgjw@sZADKVbO@MRm/OIFFsFDYBE6E@sIFkkWNEhLQk8Ch8AhcAhaoSWBIdFTopfESFK0OVgwDBiSDQWPBENiKAmOhE/CIzVWekn0kJlJxiOjz/SSYc82TXQZTYY9w55hz@iy2piZM7UL/AX2EmwlR/2SLMjhUeAvdie3S2GPR4G/ULsOFspNEcyvwl3hrmgrs6vUr@gq9avdJbUrPTc0jZm1aMHtom3RLpqgXkPXqNlgb9RrzLvZK0Cv8CpapaaiUWat8CqsilaZj9KrolM0Cqdq/VqtVq/HmUf5tvnjtge3fz5158t8T2xP3h1Pm0M39P3Dyj25Rzf@Ph533by5f/3Y7fbPl5f37qb0ju@7bd/37vHRdVtz@n7kvTP7W2J@PrxtujAMQz@t3PnlOG@wPH/su6fe/XQ7Kj31K9MdLt3r3TfS5235enCfN8HXXX@9/upGnsm05p2vl9iJ8jvygKZlDKlOYRm1lThJv166MA5RuOhpvaQxl8Zabl@tFx0HSbd/ZBzC/20bmXKcljrGjGEeeWRtWvq6hPUouVIj5jbpQkGrlCon6X/8Aw "Python 3.8 (pre-release) – Try It Online") Matches 68 of the 168 primes between 0 and 1000 as being prime, and all 832 of the composites, totalling 900, or 90% of the total 1000. [Answer] # .NET regex, ~~236~~ ~~229~~ ~~222~~ ~~210~~ ~~202~~ ~~198~~ 192 bytes `^(?!(?(((?<-4>(){10})|){99}((?<4-2>)|){990}(?=[6-9](?<4>){6})?(?=[3-59](?<4>){3})?([258](?<4>)|[147])?).)+$(?(5)|(\6)?()){31}(?(4)(?(6)(?<A-6>(?<-4>))){31}(?>(?<6-A>)(\4)?|){31}){499}\7|[01]$)` [Try it online!](https://tio.run/##RZDhboIwFIVfhZEm9obVgEMcYkGz33sCZAlxdTSphUCNi6XPzlqd25@bnK/nnp7crr2wfmiYEBPqadmzL/ZdrdeSXfB2Nn3g4gkXGONiQ@Icg45CAyPoNDWOxWSR32VocEHLhKSVwznoxEDh0AtZ/rEXx8rF8vUXjGUUryooYA4Bst8sYcT7xHrAeiObiGOwI7FjsyNJfm8Bj1enE7LLAe9jKMYbBR3bbvvVWIZRhWCabZ/9t/bUccE@fcjQlYbZse1ZfWgwEh6XHuKyOyvQqKZIkKETXPnEz/gRo3p@aM9SEaG8hTMEFNVlWBkbgJGkJZequpEMSSLYQ0dOBwFol3GiqJ@/1@rQsMEuwZ1eQV96rhhp2kEZ2yrK/rVHZGvvL7hkno@kb4yZQpKm6Q8 "PowerShell – Try It Online") [Try it online!](https://tio.run/##VVJtb5swEP4rCFmqrYyKwwHjIpRK@7xfgDIJZe6C5JqIUGVqjt@e3Zmm6775Xp6Xe@A0Xtx0Pjrvb2Jqu8n9dn/2T0/BXeTzw@2ntNJ2BvZYazT82GFlsNS4jV1tsLAInaV3bhTW0mLdGU2lMVhpLDtrNO3ZHRb8pAEA5lahkdbssDZoNFaRoIyUW426s5qECoNAuJyHinSlhQ8bPK2AyYl7u@ppYB9xlDORwpKsRyIWidxVBJTm7p48MTTnNilsGcC30j4JVytxXGcc2@IACvjiCzXdQTfzglnlOKAPZ9YwjLUgku04JWKQVpOtKP6fszUB@ExgTQ@AMMDmVo4aPqU4izvMMix@Ik5OR4cMUErcHp6/pd/H19Pg3a9UNeK9zZuXcXL94SiFT4aQiCGc3mZ1FX0rfHY@@WFOs7QZXqToHw/jW5gzPycFL2xa0Xf5fiECKULbDWHex04jQubdvQauNxt1ZY7XVkyPP/r5cHRnAqm1@66ul2mYXXYcz/NCrqD5VydZGOk/9ENwSSpCuizLLc@stX8B "PowerShell – Try It Online") - [Kaz's 456 byte POSIX ERE compatible solution](https://codegolf.stackexchange.com/a/230608/17216), for comparison [Try it online!](https://tio.run/##RY/RaoQwFER/xYYLJs1m0b65Enahz/0CayHYuzWQvZGYxbDit1ttKX08M8MwM/gJw9ijcysE3QT8wtSeToQTv@TrBz8/8ZSkeC8liJTW/HJgr/42WIefTNTw0EV99QFN13NwmaUMLA33KGYwGpwaB2cjU6y2Vw7m2Pk7ReVi9rIHpAbTFO2yFXAg3ViK7Y9SAymHf1zuLKWY946bhnB8M7HrceR5yp@BxK/zEPMUbETV@zEu27Ky/udMkd8@OUuYMSC2LMtaqKqqvgE "PowerShell – Try It Online") - primes matched in unary, for comparison This correctly identifies all \$168\$ primes and \$832\$ non-primes in the range \$[0,999]\$. (Processing that entire range on TIO takes ~~30~~ **4 seconds**.) As such it competes in the 100% category, as [one other answer](https://codegolf.stackexchange.com/a/230608/17216) to this challenge has done, and not 90%-or-better as the challenge asks for. Earlier versions of this were split into two levels of golf, one running in a reasonable amount of time, and the other experiencing exponential slowdown (being probably too slow to finish processing the entire range before the heat death of the universe). But since the 194 byte mark was reached, that version became obsolete, and now the shortest version is approximately equal in speed to the fastest version. *-8 bytes (210 → 202) by using a variant of [jimmy23013's digit capture technique](https://codegolf.stackexchange.com/questions/150534/a-regex-to-match-three-consecutive-integers-iff-the-third-integer-is-the-sum-of/150631#150631) instead of binary* The primary challenge here is that a regex can only do its work within the space of the input. In unary, this is no problem as far as matching primes go. But in decimal, the digits don't provide enough space to do the necessary computational work – numeric variables cannot be stored in the form of captured portions of the input string, as the number of possible states of each such a capture, including the unset state, would only be \$n({n+1})/2+2\$ at best (if every digit is unique), or \$n+2\$ at worst (if all digits are identical), when it needs to be \$10^n\$ – where \$n\$ is the number of decimal digits in the input. This regex uses .NET's Balanced Groups feature to do its magic. In .NET, each time a capture has been made to a particular group, using `(`...`)` or `(?<n>`...`)`, it is pushed onto that group's capture stack, which retains the full information of every substring contained in that stack, in order. That's overkill in this case, as this regex only pushes empty strings\* onto the capture stacks. Each emulated numeric variable is stored as the number of times a capture has been pushed onto the stack of a particular group. (Popping is done using `(?<-n>`...`)`, which asserts the stack is non-empty and removes the capture at the top of that stack – as well as matching the enclosed pattern, which can be unrelated. As far as this regex is concerned, it simply asserts that the variable is nonzero and then decrements it.) \*Not that it makes any difference given how the regex works, but following the 210 → 202 golf, if the last digit of the input is in `[124578]`, the topmost capture on the `\4` stack will contain that digit. The rest are empty. But even with this trick, it is impossible to do unbounded arithmetic. A repeated operation (incrementing and/or decrementing a capture stack variable) can only be either done as many times as there are characters in the input, or done a hard-coded maximum number of times. These can be combined and multiplied, but that still only means it could be repeated a number of times that is proportional to a polynomial function of the input string's length, whereas to be able to scale with decimal input (or any base besides unary), it'd need to be an exponential function. So at the time of this posting, I had thought it impossible to match all primes up to infinity in decimal with a pure regex. But it turns out to be possible after all, by doing base-encoded arithmetic and long division; [that regex is much longer](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/260450#260450). In the commented explanation below, I use the shorthand `Cn` to signify the capture count of group `\n`: ``` ^ # Anchor to start (?! # Negative lookahead - assert that none of the following two # alternatives can match. # Match any composite number in decimal # Parse the number, translating decimal into the capture count C4 (?( # This entire section is wrapped inside a lookahead conditional, # which just acts as a golfed lookahead since it always matches. ((?<-4>(){10})|){99} # C2 += C4 * 10; C4 = 0 ((?<4-2>) |){990} # C4 += C2; C2 = 0 # Read this digit, adding it to C4 (?= [6-9] (?<4>){6})? # C4 += 6, if digit is in [ 6789] (?= [3-59](?<4>){3})? # C4 += 3, if digit is in [ 345 9] ( [258] (?<4>) | # C4 += 2, if digit is in [ 2 5 8 ] [147] )? # C4 += 1, if digit is in [ 1 4 7 ] ) . # Consume digit )+$ # Loop until all digits have been read. # C6 = any number from 2 to 31 (31 is the largest prime ≤ sqrt(999)) (?(5)| # Conditional - On each iteration, only do anything if \5 is # unset. (\6)? # On any iteration after the first, \5 can be set, which # signals that no further iterations after the next will # increment C6. Doing it this way ensures that C6 will be # incremented at least twice. () # C6 += 1 ){31} # Iterate 31 times, to give C6 a possible range from 2 to 31. # We can't accomplish this as "{2,31}" because then .NET, # like Perl but unlike PCRE, would only do the minimum number # of iterations (i.e. 2) before exiting the loop due to a # zero-width match. # Divide C4 / C6, enforcing that the remainder is zero. The quotient is the # number of iterations that start with C4 != 0, i.e. the number of non-NOP # iterations. (?(4) # Make each iteration of this loop conditional upon C4 != 0, so # that if the division finishes and C4 is still nonzero, the # loop will fail to match and will immediately backtrack to try # a different value of C6; this provides a huge speedup, # relative to putting "(?!\4)" after the end of the loop (which # would can't do anyway now, since it doesn't always capture # empty strings). Thus, the loop can only finish and exit if # C4 == 0 after the division has completed, which, if C7 ≥ 2, # means that C4's original value was composite. # Total effect of the following loop: C4 -= C6; CA = C6; C6 = 0 (?(6) # Make each iteration conditional upon C6 != 0, so that # this loop can't finish without fully subtracting C6 # from C4. If C4 was less than C6, this loop will fail # to match before it can finish, and the regex will # backtrack to try a smaller value of C6. (?<A-6>(?<-4>)) # CA += 1; C6 -= 1; C4 -= 1 ){31} # Do the above the maximum of up to 31 times, # the maximum value that C6 could have had. (?>(?<6-A>)(\4)?|){31} # C6 = CA; CA = 0; # \7 = set if C4 != 0, i.e. if quotient ≥ 2 ){499} # Handle a quotient of up to floor(999 / 2) \7 # Assert that the quotient was ≥ 2 | # or... # Match the decimal numbers 0 or 1 [01]$ ) ``` This algorithm can do \$[0,3333]\$ in 56 seconds on TIO (the regex becomes **195 bytes**): [Try it online!](https://tio.run/##RZHRboIwFIZfhZEm9oTVgEDdRKhm13sCZAlxdTSphUCNi9Bnd@3U7eYk39fTc/60XXvm/dBwKa@oz8uef/HvarVS/Iw3s@sHZk@YYYzZmiQFhjEKDUwwxnFsnEzIorhzaDDLS0peK@cLGKkB5lRM0j8XO1cu0pe7mMooWVbAYA4BsotSmPCO2h6AMbUrGE7AFmrLektoccsBj1PHlGwLwLsE2PRrbUZKl2a3nMowqhBcZ5tn/609dkLyTx8ydMnD7ND2vN43GElPKA8J1Z00jKjOkSRDJ4X2iZ@JA0b1fN@elCZSewvXEOSoLsPK2AEYqbwUSle/JkOKSP7gyHEQwOhmHHPUz99rvW/4YC/BzV5gPPdCc9K0gzY2VZT9s0dUa79ACsU9HynfGHMNiX3l@Ac "PowerShell – Try It Online") --- Here is an alternative **195 byte** version that does not do any direct matching against the digits after their initial reading. I'm including this not just because it's an interesting variation of the algorithm, more like `^(?>(x(x*))\1+$)\2` whereas the above version is like `^(?!(xx+)\1+$)xx`, but because it just might be possible to golf to a shorter length than the above version. `^(?=(?(((?<-4>(){10})|){99}((?<4-2>)|){990}(?=[6-9](?<4>){6})?(?=[3-59](?<4>){3})?([258](?<4>)|[147])?).)+$(?(6)|(|())){31}(?(4)(?(5)(?<9-5>(?<-4>))){31}(?>(?<5-9>)(\9)?(\4)?|){31}){499}\8)(?!\7)` [Try it online!](https://tio.run/##RZHhaoMwFIVfxUmgubgUbbVtatXCfu8J1IG4dAbSKJrSUc2zu6Tduj8XznfPPTmQrr2yfmiYEDPqk7xnX@y73O8lu@LjYv7AWYIzjHF2IGGKYQx8DROMlGrLQrJKH9LXxplvCC0tTmHcaMgsWpPoydaW5ato9wumPAi3JWSwBA@ZZzYw4QkDGGdg8nAIZkRmHCiJ0keH59bqiNAUcEFNbBFCNt1XMIamXrEzdy/FFubF8dV9a88dF@zThRjdEj8@tT2r6gYj4XDpIC67i4IRVQkSZOgEVy5xY37CqFrW7UUqIpSzsgYvQVXul9oEYCSTnEtV3kmMJBHsTwdWex6MNuOcoH75Xqm6YYM5gge9wXjtuWKkaQelTasg/tcOka35AsElc1wkXa21M/uEUvoD "PowerShell – Try It Online") ``` ^ # Anchor to start (?= # Atomic lookahead # Parse the number, translating decimal into the capture count C4 (?( # This entire section is wrapped inside a lookahead conditional, # which just acts as a golfed lookahead since it always matches. ((?<-4>(){10})|){99} # C2 += C4 * 10; C4 = 0 ((?<4-2>) |){990} # C4 += C2; C2 = 0 # Read this digit, adding it to C4 (?= [6-9] (?<4>){6})? # C4 += 6, if digit is in [ 6789] (?= [3-59](?<4>){3})? # C4 += 3, if digit is in [ 345 9] ( [258] (?<4>) | # C4 += 2, if digit is in [ 2 5 8 ] [147] )? # C4 += 1, if digit is in [ 1 4 7 ] ) . # Consume digit )+$ # Loop until all digits have been read. # C5 = any number from 1 to 31 (31 is the largest prime ≤ sqrt(999)) (?(6)| # Conditional - On each iteration, only do anything if \6 is # unset. (|()) # C5 += 1; if this chooses to set \6, then for the rest of the # loop, C5 will no longer be incremented. This has the effect of # trying values in the order from 31 down to 1. ){31} # Iterate 31 times, to give C5 a possible range from 2 to 31. # We can't accomplish this as "{2,31}" because then .NET, # like Perl but unlike PCRE, would only do the minimum number # of iterations (i.e. 2) before exiting the loop due to a # zero-width match. # Divide C4 / C5, enforcing that the remainder is zero. The quotient is the # number of iterations that start with C4 != 0, i.e. the number of non-NOP # iterations. (?(4) # Make each iteration of this loop conditional upon C4 != 0, so # that if the division finishes and C4 is still nonzero, the # loop will fail to match and will immediately backtrack to try # a different value of C5; this provides a huge speedup, # relative to putting "(?!\4)" after the end of the loop (which # would can't do anyway now, since it doesn't always capture # empty strings). Thus, the loop can only finish and exit if # C4 == 0 after the division has completed, which, if C7 ≥ 2, # means that C4's original value was composite. # Total effect of the following loop: C4 -= C5; C9 = C5; C5 = 0 (?(5) # Make each iteration conditional upon C5 != 0, so that # this loop can't finish without fully subtracting C5 # from C4. If C4 was less than C5, this loop will fail # to match before it can finish, and the regex will # backtrack to try a smaller value of C5. (?<9-5>(?<-4>)) # C9 += 1; C5 -= 1; C4 -= 1 ){31} # Do the above the maximum of up to 31 times, # the maximum value that C5 could have had. # Total effect of the following loop: C5 = C9; C9 = 0 # (as well as the possible setting of \7 and/or \8) (?> (?<5-9>) # C5 += 1; C9 -= 1 (\9)? # \7 = set if C9 == 0, i.e. C5_initial ≥ 2 (\4)? # \8 = set if C4 != 0, i.e. if quotient ≥ 2 | ){31} ){499} # Handle a quotient of up to floor(999 / 2) \8 # Assert that the quotient was ≥ 2 ) (?!\7) # Assert C5_initial == 1, i.e. that the largest divisor # resulting in a quotient ≥ 2 was 1 ``` --- It should also be possible to implement a finite-bounded primality test in regex flavors that don't have balanced groups, but do have persistent backreferences (Perl / Java / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE); it would have to be done in emulated binary, so there'd have to be a capture group for each bit, at each location where emulated addition/subtraction is done – which means \$10\$ of them for each variable at each arithmetic location to handle \$[0,999]\$, and each one would have to implement its own copying and carry/borrow in each addition/subtraction operation – so, such a regex would probably be enormous, and would likely only pass the breaking-even point against POSIX ERE at a larger maximum range of handled primes (maybe one more decimal digit would be enough, or maybe not). ]
[Question] [ Given an integer \$N>3\$, you have to find the minimum number of bits that need to be inverted in \$N\$ to turn it into a [square number](https://en.wikipedia.org/wiki/Square_number). You are only allowed to invert bits **below the most significant one**. ## Examples * \$N=4\$ already is a square number (\$2^2\$), so the expected output is \$0\$. * \$N=24\$ can be turned into a square number by inverting 1 bit: \$11000 \rightarrow 1100\color{red}1\$ (\$25=5^2\$), so the expected output is \$1\$. * \$N=22\$ cannot be turned into a square number by inverting a single bit (the possible results being \$23\$, \$20\$, \$18\$ and \$30\$) but it can be done by inverting 2 bits: \$10110 \rightarrow 10\color{red}0\color{red}00\$ (\$16=4^2\$), so the expected output is \$2\$. ## Rules * It is fine if your code is too slow or throws an error for the bigger test-cases, but it should at least support \$3 < N < 10000\$ in less than 1 minute. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! ## Test cases ``` Input | Output ----------+-------- 4 | 0 22 | 2 24 | 1 30 | 3 94 | 4 831 | 5 832 | 1 1055 | 4 6495 | 6 9999 | 4 40063 | 6 247614 | 7 (smallest N for which the answer is 7) 1049310 | 7 (clear them all!) 7361278 | 8 (smallest N for which the answer is 8) 100048606 | 8 (a bigger "8") ``` Or in copy/paste friendly format: ``` [4,22,24,30,94,831,832,1055,6495,9999,40063,247614,1049310,7361278,100048606] ``` [Answer] ## Ruby, 74 bytes ``` ->n{(1..n).map{|x|a=(n^x*x).to_s 2;a.size>Math.log2(n)?n:a.count(?1)}.min} ``` [Try it online!](https://tio.run/##FYpdCoJAFIXfXcV9nAm7ODpaFuoKWoFYTP6kkFdJBctx7TYeON8Hh/OZnt@tgmg7xrQwgUgcW9UvetYqYnSfDzPHsXsMzOVXhUPzK@ObGmt8dy@XEU/oojDvJhpZIviKbUPrlkobXNfU2HNsCI3PnthhVuH4vg2BDA1DExuk4wTefj8FQmZYqryGogNN2gKTfhoHqFLKrJKK7Q8) This simply generates the sequence \$\left[1^2, 2^2, \ldots, n^2\right]\$ (which is far more than enough), XORs it with \$n\$, and then takes either the number of 1s in its binary representation if the number of bits is less than or equal to \$\log\_2n\$, or \$n\$ otherwise. It then takes the minimum number of bits flipped. Returning \$n\$ instead of the number of bits flipped when the highest bit flipped is greater than \$\log\_2n\$ prevents these cases from being chosen as the minimum, as \$n\$ will always be greater than the number of bits it has. Thanks to [Piccolo](https://codegolf.stackexchange.com/users/26724/piccolo) for saving a byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` ²,BẈEðƇ²^B§Ṃ ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//wrIsQuG6iEXDsMaHwrJeQsKn4bmC////ODMx "Jelly – Try It Online") [Check out a test suite!](https://tio.run/##y0rNyan8///QJh2nh7s6XA9vONZ@aFOc06HlD3c2/T@653D7o6Y17v//R5voGBnpGJnoGBvoWJroWBgbArGRjqGBqamOmYmlqY4lEMQCAA) Monadic link. Should be golfable. ~~But I am too dumb to think of a way to get rid of the `³`s.~~ It's my first answer in which I successfully use filtering / mapping / looping in general along with a dyadic chain \o/ ### Explanation ``` ²,BẈEðƇ²^B§Ṃ – Full program / Monadic link. Call the argument N. ðƇ – Filter-keep [1 ... N] with the following dyadic chain: ²,BẈE – The square of the current item has the same bit length as N. ² – Square. , – Pair with N. B – Convert both to binary. Ẉ – Retrieve their lengths. E – And check whether they equate. ²^ – After filtering, square the results and XOR them with N. B – Binary representation of each. § – Sum of each. Counts the number of 1s in binary. Ṃ – Minimum. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 20 bytes ``` ▼mΣfo¬→S↑(Mo¤ż≠↔ḋİ□ḋ ``` [Try it online!](https://tio.run/##ATcAyP9odXNr///ilrxtzqNmb8Ks4oaSU@KGkShNb8KkxbziiaDihpThuIvEsOKWoeG4i////zQwMDYz "Husk – Try It Online") ## Explanation ``` ▼mΣf(¬→)S↑(M(¤ż≠↔ḋ)İ□ḋ) -- example input n=4 S↑( ) -- take n from n applied to (..) ḋ -- | convert to binary: [1,0,0] İ□ -- | squares: [1,4,9,16,...] M( ) -- | map with argument ([1,0,0]; example with 1) ḋ -- | | convert to binary: [1] ¤ ↔ -- | | reverse both arguments of: [1] [0,0,1] ż≠ -- | | | zip with inequality (absolute difference) keeping longer elements: [1,0,1] -- | : [[1,0,1],[0,0,0],[1,0,1,1],[0,0,1,0,1],[1,0,1,1,1],.... -- : [[1,0,1],[0,0,0],[1,0,1,1],[0,0,1,0,1]] f( ) -- filter elements where → -- | last element ¬ -- | is zero -- : [[0,0,0]] mΣ -- sum each: [0] ▼ -- minimum: 0 ``` [Answer] # [Perl 6](http://perl6.org/), 65 bytes ``` {min map {+$^a.base(2).comb(~1) if sqrt($a+^$_)!~~/\./},^2**.msb} ``` [Try it online!](https://tio.run/##DcPdCoMgAAbQV/kWMvoZVqaxYPUkQ7GREORquZsQe3W3A2eb9qWN9sDVoI/ezm9YvcEXRGo6ajelLKOv1Y7pWWeYDdxn/6ZEF5Ko7HKe5ZOW4SZZnlPrxhCdPpAQhX6ANyAqJDDrjgcHY2AcTYWO497U/wx1JQRa3okh/gA "Perl 6 – Try It Online") I feel a little dirty for testing for a perfect square by looking for a period in the string representation of the number's square root, but...anything to shave off bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Lnʒ‚b€gË}^b1öß ``` -5 bytes thanks to *@Mr.Xcoder* using a port of [his Jelly answer](https://codegolf.stackexchange.com/a/170373/52210). [Try it online](https://tio.run/##ASIA3f8wNWFiMWX//0xuypLigJpi4oKsZ8OLfV5iMcO2w5///zk0) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o5OZ5eILLoZX2SgqP2iYpKNn/98k7NenQukcNs5IeNa1JP9xdG5dkeHjb4fn/df6bcBkZcRmZcBkbcFmacFkYGwKxEZehgakpl5mJpSmXJRBwmRgYmBkDAA) (the biggest four test cases are removed, because they'll timeout after 60 sec). **Explanation:** ``` L # Create a list in the range [1, (implicit) input-integer] # i.e. input=22 → [0,1,2,...,20,21,22] n # Take the square of each # i.e. [0,1,2,...,20,21,22] → [0,1,4,...,400,441,484] ʒ } # Filter this list by: , # Pair the current value with the (implicit) input-integer # i.e. 0 and 22 → [0,22] # i.e. 25 and 22 → [25,22] b # Convert both to binary strings # i.e. [0,22] → ['0','10110'] # i.e. [25,22] → ['10000','11001'] €g # Take the length of both # i.e. ['0','10110'] → [1,5] # ['10000','11001'] → [5,5] Ë # Check if both are equal # i.e. [1,5] → 0 (falsey) # i.e. [5,5] → 1 (truthy) ^ # After we've filtered, Bitwise-XOR each with the (implicit) input-integer # i.e. [16,25] and 22 → [6,15] b # Convert each to a binary string again # i.e. [6,15] → ['110','1111'] 1ö # Convert each to base-1, which effectively is a vectorized sum of their # digits, to get the amount of 1-bits in each binary string # i.e. ['110','1111'] → [2,4] ß # Pop and leave the minimum of this list # i.e. [2,4] → 2 # (which is output implicitly as result) ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 110 bytes ``` n->{int i=1,s=1,b,m=99,h=n.highestOneBit(n);for(;s<h*2;s=++i*i)m=(s^n)<h&&(b=n.bitCount(s^n))<m?b:m;return m;} ``` [Try it online!](https://tio.run/##ZZHfa4MwEMff@1eEQou2VhK1tlbt2AaDPYw9dG9jA62/0mkUcxZK6d/uou02dYEjuc9d7o7vHbyjtzgEXzXNirwEdBC@WgFN1Zk9@seiiu2B5qwJFpWf0j3apx7n6MWjDJ1HCN0oBw/EdcxpgDIRk3ZQUha/fyCvjLncpiL0lj8zeLrVdMQ7jMNyiyK3ZovtmTJA1CUKF@YrmWtZSuIyNaFxEnJ4ZeEDBYnJdpSXks2dZKbZ3J3P6YzKmSvxTyY7yXQq@eKPT@Exrxi0VHayO3@T2WUIVclQZl9qux1HNBQDgijOkXsb8e8YSh9o2hAMM3Q8ANYgY62TIegXJXi57AHTsPrAEqcLDIxNvQM0Y2WSTluCDUsnncFWukm01foHEIyxsTax2fqXqzCNws02Gmk2V4HkX312Jw5hpuYVqIXYMUTSeEJwsEGTYMLGSpuuoEj1iiI93XOxZalBsnytfRk1dqm/AQ "Java (JDK 10) – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 18 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md) Near-port of [my Jelly answer](https://codegolf.stackexchange.com/a/170373/59487). ``` s¦⟪,b¦l¦y⟫⁇⟪^bΣ⟫¦⌋ ``` [Try it online!](https://tio.run/##S0/MTPz/v/jQskfzV@kkHVqWc2hZ5aP5qx81tgMF4pLOLQZygJI93f//GxqYmgIA "Gaia – Try It Online") ### Breakdown ``` s¦⟪,b¦l¦y⟫⁇⟪^bΣ⟫¦⌋ – Full program. Let's call the input N. s¦ – Square each integer in the range [1 ... N]. ⟪ ⟫⁇ – Select those that fulfil a certain condition, when ran through a dyadic block. Using a dyadic block saves one byte because the input, N, is implicitly used as another argument. , – Pair the current element and N in a list. b¦ – Convert them to binary. l¦ – Get their lengths. y – Then check whether they are equal. ⟪ ⟫¦ – Run all the valid integers through a dyadic block. ^ – XOR each with N. bΣ – Convert to binary and sum (count the 1s in binary) ⌋ – Minimum. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes ``` Min@DigitCount[l=BitLength;#~BitXor~Pick[s=Range@#^2,l@s,l@#],2,1]& ``` [Try it online!](https://tio.run/##FYtfC4IwFMXf9ymEgRQs2uZciRijeiyQngIxGOKfkU7Q9RT51df1wu@cw733DNp19aCdqbRvso2/G6uupjXuMn6sK/rsbNyttq3rUrxAfo7TkpvqXczZQ9u2VvjFSa9mAJeEE1aGfpuifDLQxsHuFDRwCPfqiwRBnAPgESUoAT9GbBXYMhrHBEmRgCYwBAlKZbS@HyQT6Of/ "Wolfram Language (Mathematica) – Try It Online") Takes \$\{1, 2, \ldots, n\}\$ and squares them. Then, the numbers with same `BitLength` as the input are `Pick`ed, and `BitXor`ed with the input. Next, the `Min`imum `DigitCount` of `1`s in binary is returned. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 56 41 bytes It's not gonna break any length records but thought i'd post it anyway ``` ⟨⟨{⟦^₂ᵐḃᵐ}{h∋Q.l~t?∧}ᶠ{ḃl}⟩zḃᶠ⟩{z{∋≠}ᶜ}ᵐ⌋ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FUBU/Wj@srhHTU0Pt054uKMZSNZWZzzq6A7Uy6krsX/Usbz24bYF1UCZnNpH81dWgZRsWwBkVVdVA1U96lwAlJ9TC9T2qKf7/39DAyD4HwUA "Brachylog – Try It Online") [Answer] # x86-64 assembly, 37 bytes Bytecode: ``` 53 89 fb 89 f9 0f bd f7 89 c8 f7 e0 70 12 0f bd d0 39 f2 75 0b 31 f8 f3 0f b8 c0 39 d8 0f 42 d8 e2 e6 93 5b c3 ``` Nicely, this computes even the highest example in less than a second. Heart of the algorithm is xor/popcount as usual. ``` push %rbx /* we use ebx as our global accumulator, to see what the lowest bit * difference is */ /* it needs to be initialized to something big enough, fortunately the * answer will always be less than the initial argument */ mov %edi,%ebx mov %edi,%ecx bsr %edi,%esi .L1: mov %ecx,%eax mul %eax jo cont /* this square doesn't even fit into eax */ bsr %eax,%edx cmp %esi,%edx jnz cont /* can't invert bits higher than esi */ xor %edi,%eax popcnt %eax,%eax cmp %ebx,%eax /* if eax < ebx */ cmovb %eax,%ebx cont: loop .L1 xchg %ebx,%eax pop %rbx retq ``` [Answer] # PARI/GP 136 bytes ``` t(n)=b=#digits(n\2,2);for(j=0,b,v=concat(vector(b-j),vector(j,i,1));forperm(v,p,if(issquare(bitxor(n,fromdigits(Vec(p),2))),return(j)))) ``` ## Test ``` T=[4, 22, 24, 30, 94, 831, 832, 1055, 6495, 9999, 40063, 247614, 1049310, 7361278, 100048606]; for (i=1, #T, print(T[i]," | "t(T[i]))) 4 | 0 22 | 2 24 | 1 30 | 3 94 | 4 831 | 5 832 | 1 1055 | 4 6495 | 6 9999 | 4 40063 | 6 247614 | 7 1049310 | 7 7361278 | 8 100048606 | 8 > ## *** last result computed in 736 ms. Test with OEIS A358701(9): t(743300286) 9 ## last result computed in 3,813 ms. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` NθI⌊EΦEθ↨×ιι²⁼LιL↨θ²ΣE↨責⁼λ§ιμ ``` [Try it online!](https://tio.run/##RYxBCsIwFET3niLLH4ibbLtSUSjYUtALxBrshyRtkh/x9rEpEWcxDMObGScVxlmZnFu3JOqTfegAnje7IaAjOKlI0KFDmyx0aoELGlqJEr1gRxU13NHqCCgYcsEkX@3skzIRrtq9aIJS17jxfqMKd6un/1qwfiaoeyPYgVr31J/ybvlPTc5S5v3bfAE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ Input N θ N E Map over implicit range ιι Current value (twice) × Multiply ↨ ² Convert to base 2 Φ Filter over result ι Current value θ N ↨ ² Convert to base 2 L L Length ⁼ Equals E Map over result θ N ↨ ² Convert to base 2 E Map over digits λ Current base 2 digit of N ι Current base 2 value μ Inner index § Get digit of value ⁼ Equals ¬ Not (i.e. XOR) Σ Take the sum ⌊ Take the minimum I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` BL’Ø.ṗŻ€©Ḅ^⁸Ʋa§ɼ¹ƇṂ ``` [Try it online!](https://tio.run/##ATgAx/9qZWxsef//QkzigJnDmC7huZfFu@KCrMKp4biEXuKBuMOGwrJhwqfJvMK5xofhuYL///80MDA2Mw "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` lambda n:min(bin(i*i^n).count('1')for i in range(n)if len(bin(i*i^n))<len(bin(n))) ``` [Try it online!](https://tio.run/##bc7dCoIwFMDx@57iQBe6iDhnm1Oj3iQC@7AGdRSxi55@6UiwrQOD7cefw9p3f29Yunp/cI/qebpUwNun5fQ0HLuyRxabc/PiPk0oEXXTgQXL0FV8u6YsbA2P6zwWu@k93IVrO8s91Cl8RwtYAy4ClnJkGbGvKWSFI6uQS1/rgAtFI2cRyz@7CbPszxKjS8/ml8th4lojGhXVUueG/AfzGRPqUhGGnCtDMi9GLhbLyQkRdWHQeHcf "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-g`, 20 bytes *This can be golfed down.* ``` op f_¤Ê¥¢lî^U ¤¬xÃn ``` [Try it online!](https://tio.run/##ASsA1P9qYXB0//9vcCBmX8Kkw4rCpcKibMODwq5eVSDCpMKseMODbv//ODMxIC1n "Japt – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~93~~ 91 bytes ``` g(n){n=n?n%2+g(n/2):0;}m;i;d;f(n){m=99;for(i=0;++i*i<2*n;m=g(d=i*i^n)<m&d<n/2?g(d):m);n=m;} ``` [Try it online!](https://tio.run/##JY/basMwDIbv8xSikGE3DnMcx4nreH2QroUQk8wEq6OM3ZQ8e6Z0AiE@Sb8OYzmP47bNDPkTPZ4xVwXBu@In6dbkogtu2ovJW@um@4NFL11RxGPs1RFd8jMLnuiGvE9voSfpmVL8lLhDn9y6/d5jgC8W8QeQwzMDsu8H4cQOuQ1Qlh@Qh088CEAB@zLusjXLdkEaIjL@r9l5uFzBw1MLpYTSopbCatHVFbkSlWwaYbRthCUTWkpTU1drKk01betKirY2lWo7Yil1Z6RZ3Wv46zNasHgJDpa@aigUxcLp8uGyXPeTtj8 "C (gcc) – Try It Online") --- Edit: I think my original solution ([Try it online!](https://tio.run/##JU/haoQwDP7vU4QDpT0jq7VWu9rtQW53IBa9IvbGMfZHfHYXb4GQfEm@fMlQTMOw7xOLfI0ufsZU5gTeJH8XdlucMTZYb8ejPz6eLDhh8zycQyfP0U7MO8pvkXdLlvmOeFnGFkd1zrmNbrHb/vsIHu4sxB@IHNYEyL6fBEd2So2HoviA1H/FE0JEOJS4TbYkOQhLHyLj/5wD95crOFgVSolSYSXQKGyrklxiKeoatTI1GjJUQuiKphpdKuopU5UCm0qXsmkJC6FaLfRmX8tfv5HA7ARYmLuyppDnM4fFaYV31l/m63HX/gc)) is not valid, because one of the variables, `m`, global to save a few bytes by not specifying type, was initialized outside of `f(n)` and therefore had to be reinitialized between calls --- # Ungolfed and commented code : ``` g(n){n=n?n%2+g(n/2):0;} // returns the number of bits equal to 1 in n m; //miminum hamming distance between n and a square i; //counter to browse squares d; //bitwise difference between n and a square f(n){m=99; //initialize m to 99 > size of int (in bits) for( i=0; ++i*i<2*n; //get the next square number, stop if it's greater than 2*n g(d=i*i^n)<m&&d<n/2&&(m=g(d)) //calculate d and hamming distance // ^~~~~~~~~~~^ if the hamming distance is less than the minimum // ^~~~^ and the most significant bit of n did not change (the most significant bit contains at least half the value) // ^~~~~~~^ then update m ); n=m;} // output m ``` --- # Edits: * Saved 2 bytes thanks to ceilingcat [Answer] # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` x=>g=(i=z=x)=>i?g(i-1,t=i*i^x,u=(N=i=>i&&i%2+N(i>>1))(t),z=z<u|t>x&i*i>x?z:u):z ``` [Try it online!](https://tio.run/##JYpBCsIwEADv/sOwq4lYb1Z3@4M@QSi1DaulKSaVEHy7MeAcZ@bRvTvfv2QJZnb3IY@UI7ElEEoUkVgaC2IqHUh2cot6JWhJildKtqd9C8JcIUJAnShd10/gqMrKsUn1inXKl03vZu@m4TA5CyNUxwICYv66JUhp2fjQ9U/jJQ10/vMD "JavaScript (Node.js) – Try It Online") If `t` and `t^x` are both larger than `x` then `t` is longer than `x` ]
[Question] [ I think most people around here know what a 7-segment display for digits is: ``` _ _ _ _ _ _ _ _ | | | _| _| |_| |_ |_ | |_| |_| |_| | |_ _| | _| |_| | |_| _| ``` We can define the **7-segment difference** (7SD) between two *digits* to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between `1` and `2` is **5** (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is **1**. Furthermore, we can define the 7SD between two *numbers* to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between `12345` and `549`: ``` x: 1 2 3 4 5 y: 5 4 9 7SD: 2+5+2+0+1 = 10 ``` Your task is to **compute 7SD between *n* and *n+1*, given *n***. For convenience, here is the full table of 7SDs between individual digits. The row `_` represents an empty position. ``` _ 0 1 2 3 4 5 6 7 8 9 _ 0 6 2 5 5 4 5 6 3 7 6 0 6 0 4 3 3 4 3 2 3 1 2 1 2 4 0 5 3 2 5 6 1 5 4 2 5 3 5 0 2 5 4 3 4 2 3 3 5 3 3 2 0 3 2 3 2 2 1 4 4 4 2 5 3 0 3 4 3 3 2 5 5 3 5 4 2 3 0 1 4 2 1 6 6 2 6 3 3 4 1 0 5 1 2 7 3 3 1 4 2 3 4 5 0 4 3 8 7 1 5 2 2 3 2 1 4 0 1 9 6 2 4 3 1 2 1 2 3 1 0 ``` ## Input * Input is a single positive integer `n`. * You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. * You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127. ## Output * You should print a single integer, the 7SD between `n` and `n+1`. * You may output via STDOUT (or closest alternative), function return value or function (out) argument. ## Scoring Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, shortest code (in bytes) wins. ## Test Cases For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence [A123587](https://oeis.org/A123587). Here are the first 100 numbers (starting with `n = 1, 2, 3, ...`): ``` 5, 2, 3, 3, 1, 5, 4, 1, 4, 4, 5, 2, 3, 3, 1, 5, 4, 1, 7, 4, 5, 2, 3, 3, 1, 5, 4, 1, 4, 4, 5, 2, 3, 3, 1, 5, 4, 1, 5, 4, 5, 2, 3, 3, 1, 5, 4, 1, 5, 4, 5, 2, 3, 3, 1, 5, 4, 1, 3, 4, 5, 2, 3, 3, 1, 5, 4, 1, 7, 4, 5, 2, 3, 3, 1, 5, 4, 1, 6, 4, 5, 2, 3, 3, 1, 5, 4, 1, 3, 4, 5, 2, 3, 3, 1, 5, 4, 1, 6, 4 ``` The first input for which the 7SD is greater than 9 is `1999` which should yield 11. Here are some other larger examples: ``` n 7SD 1999 11 12345 1 999999 14 5699999 15 8765210248 1 ``` [Answer] ## JavaScript (ES6), ~~46~~ 40 bytes ``` f=n=>n?+"452331541"[n%10]||f(n/10|0)+2:2 ``` Alternative formulation, also ~~46~~ 40 bytes: ``` f=n=>n?26523308>>n%10*3&7||f(n/10|0)+2:2 ``` Edit: Saved 6 bytes thanks to @xsot. [Answer] # Python, 50 48 bytes ``` f=lambda n:26523308-0**n*2>>n%10*3&7or f(n/10)+2 ``` ## Explanation This function operates on the least significant digit of the number `n`, summing the 7SD of the digits when incremented by one until after the first non-`9` digit. `26523308` is a bitmask that encodes the mapping for the digits `0-8`. When `n=0`, which only occurs when `n` comprises only `9`s, the answer will be off by two. This is compensated by the expression `0**n*2`. As for the digit `9`, the bitmask evaluates to zero which will trigger the recursive call while adding `2` to the 7SD. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~25~~ ~~22~~ ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘DṁDḟ"DFị9979482ḃ5¤S ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCYROG5gUThuJ8iREbhu4s5OTc5NDgy4biDNcKkUw&input=&args=MTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCYROG5gUThuJ8iREbhu4s5OTc5NDgy4biDNcKkUwrCs1I7MTk5OSwxMjM0NSw5OTk5OTksNTY5OTk5OSw4NzY1MjEwMjQ4w4figqxH&input=). ### Background We first increment the input **n** and discard all digits of **n + 1** that haven't changed. For example, if **n** is **5699999**, we get the following. ``` n : 5700000 n + 1 : 5699999 Result: 700000 ``` All digits in this result have a fixed number of segments that have to get toggled. We can convert the list of toggles to [bijective base 5](https://en.wikipedia.org/wiki/Bijective_numeration) to save some bytes. ``` digit: 1 2 3 4 5 6 7 8 9 0 toggles: 4 5 2 3 3 1 5 4 1 2 ``` The output is simply the sum of the individual toggles. This works for most values of **n**, but special care must be taken if **n + 1** has more digits than **n**. In this case, all digits must be **9**'s, and we solve this problem by chopping off a trailing **0** from **n + 1**. For example, if **n** is **999999**, we get the following. ``` n : 999999 n + 1 : 1000000 Result: 100000 ``` This works because the leading **1** evaluates to **4** toggles (distance between **0** and **1**), while the actual amount of toggles is **2** (distance between **0** and **1**), and suppressing one trailing **0** removes its **2** toggles from the sum. ### How it works ``` ‘DṁDḟ"DFị9979482ḃ5¤S Main link. Argument: n ‘ Compute n+1. D Convert n+1 from integer to base 10. D Convert n from integer to base 10. ṁ Mold the left result as the right result. This chops of a 0 if n+1 has more digits than n. ḟ"D Vectorized filter-false with the base 10 digits of n. This removes the digits from n+1 that are identical to the corresponding digits of n. F Flatten the resulting list of lists. 9979482ḃ5¤ Convert 9979482 to bijective base 5. This yields [4, 5, 2, 3, 3, 1, 5, 4, 1, 2]. ị Retrieve the digits at the right that correspond to the indices at the left. S Compute the sum of the results. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~31~~ ~~30~~ ~~28~~ ~~27~~ 26 bytes Code: ``` 9Ü©T%•2X›ùì•sè¹g®g-·¹Ú9Q·O ``` **Explanation** (*outdated*): ``` 9Ü # Trim off trailing 9's © # Copy this into the register T% # Get the last non-9 digit žh # Short for 0123456789 •2X›ùì•§ # Compressed version of 4523315412 ‡ # Transliterate ``` We are changing the following to the last non-9 digit: ``` 0 -> 4 1 -> 5 2 -> 2 3 -> 3 4 -> 3 5 -> 1 6 -> 5 7 -> 4 8 -> 1 9 -> 2 ``` For the special cases: ``` ¹g # Get the length of the input ®g # Get the length of the input with all trailing 9 gone - # Substract, giving the number of 9's at the end of the input 2* # Multiply by two O # Sum everything up ¹Ú # Uniquify the input 9Qi # If this is equal to 9 (only 9's in the input) Ì # Increment by 2 (_ -> 1) ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=OcOcwqlUJeKAojJY4oC6w7nDrOKAonPDqMK5Z8KuZy3Ct8K5w5o5UcK3Tw&input=NTY5OTk5OQ). 28 byte alternative: `D[¤©•2X›ùì•sès®9Ê#¨]\rÚ9Q4*O`. [Answer] ## Java, 63 bytes [The world is righted as Python passes Java once more.](https://codegolf.stackexchange.com/a/82772/51825) [Cause, ya know, Java.](http://meta.codegolf.stackexchange.com/a/5829/51825) ``` int f(int n){return n>0?n%10<9?26523308>>n%10*3&7:2+f(n/10):2;} ``` [See it on ideone](http://ideone.com/nZBRJA) Maxes out at 2147483647, as that is Java's `Integer.MAX_VALUE`. This is a port of [my Python answer](https://codegolf.stackexchange.com/a/82765/51825) which is a port of [the ES6 answer](https://codegolf.stackexchange.com/a/82752/51825). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~61~~ ~~39~~ 36 bytes ``` tQvV15\'3dAsMh818RG5'6Y27WZaw)Z}Z~Bz ``` [**Try it online!**](http://matl.tryitonline.net/#code=dFF2VjE1XCczZEFzTWg4MThSRzUnNlkyN1daYXcpWn1afkJ6&input=NTY5OTk5OQ) ### Explanation ``` tQv % Implicit input. Duplicate, add 1, concatenate vertically V % Convert to 2D char array: each number in a row, possibly left-padded % with a space 15\ % Modulo 15. With modular indexing this corresponds to the order % '9', ' ', '0', '1', ..., '8' '3dAsMh818RG5' % This string encodes active segments for each of the 11 chars 6Y2 % Source alphabet printable ASCII chars (predefined literal) 7W % Target alphabet: [0 1 ... 127] Za % Base conversion: decode string into vector of 11 numbers, where each % number from 0 to 127 encodes the 7-segment representation of a digit, % in the order '9', ' ', '0', '1', ..., '8' w % Swap top two elements in stack ) % Use as index. Gives 2-row array, where each column is a digit Z} % Split into the two rows Z~ % Bitwise XOR, elementwise B % Convert to binary. Each number gives a row z % Number of nonzero elements. Implicitly display ``` [Answer] # Julia, 44 bytes ``` !x=x<1?2:(t=x%10÷1)<9?3045058÷6^t%6:2+!.1x ``` [Try it here.](http://julia.tryitonline.net/#code=IXg9eDwxPzI6KHQ9eCUxMCk8OT8zMDQ1MDU4w7c2XnQlNjoyKyEoeMO3MTApCgpwcmludCghMTk5OSk&input=) Dennis saved a byte! [Answer] ## Python, ~~71~~ 66 bytes [48 bytes by](https://codegolf.stackexchange.com/a/82772/51825) [xsot](https://codegolf.stackexchange.com/users/45268/xsot). Even more magic maths! ``` f=lambda n:(2+f(n/10)if n%10==9else 26523308>>n%10*3&7)if n else 2 ``` [See it on ideone](https://ideone.com/aCzCJu) Because the [prior Python answer](https://codegolf.stackexchange.com/a/82758/51825) doesn't work and is far from optimal. A simple port of [a previous ES6 version](https://codegolf.stackexchange.com/a/82752/51825). Now using bit twiddling (from the ES6 alternate formulation) to cut out a cast! Can be made to work with Python 3 by explicitly using floordiv for +1 byte. [Answer] # Jolf, 32 bytes ``` Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2 ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zo98PzzOsyVIdDlQLiI0NTIzMzE1NDEizrMrMs6PYy9IdDI&input=MTk5OQ) ## Explanation This is a transpilation of Neil's answer. ``` Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2 Ώ define a function Ώ of H ?H 2 (when H is zero, return is 2) %Ht H mod 10 γ γ = ^ ?< 9 is it less than 9? if so: ."452331541"γ get the γth element of that string P as a number else +2 add two to Ώ Ώ over c/Ht int(H / 10) ``` [Answer] # Pyth - ~~78~~ ~~30~~ 27 bytes That first one was embarrassing. ``` s@LjC" (J"ThC{I#.tjRThBQT ``` [Test Suite](http://pyth.herokuapp.com/?code=s%40LjC%22%0A%C2%88%1B%28J%22ThC%7BI%23.tjRThBQT&test_suite=1&test_suite_input=1999%0A12345%0A999999%0A5699999%0A8765210248&debug=0). [Answer] # J, 53 bytes ``` 2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.* ``` Originally based on @Neil's [solution](https://codegolf.stackexchange.com/a/82752/6710). Then improved by saving a byte using the same formula in @Lynn's [solution](https://codegolf.stackexchange.com/a/82757/6710). The 54 byte version based on the string is ``` 2:`((2+10$:@<.@%~[)`('452331541'".@{~])@.(9>])10&|)@.* ``` ## Usage ``` f =: 2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.* f 1999 11 f 1999 12345 999999 5699999 8765210248 11 1 14 15 1 ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 34 bytes ``` M!`.9*$ ^9 0 T`d`4523315412 . $* . ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApNIWAuOSokCl45CjAKVGBkYDQ1MjMzMTU0MTIKLgokKgou&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKMTEKMTIKMTMKMTk5OQoyOTk5CjY5OTkKMTIzNDUKOTk5OTk5CjU2OTk5OTkKODc2NTIxMDI0OA) (The first line just allows the processing of multiple test cases at once.) ### Explanation Like most answers have discovered by now, we don't need to use the full table, since only the least-significant non-`9` digit changes when incrementing. That's also how this answer works. ``` M!`.9*$ ``` This matches (`M`) the regex `.9*$` i.e. the first digit that is only separated by `9`s from the end. The `!` tells Retina to replace the input with this match, discarding everything that doesn't affect the 7SD. ``` ^9 0 ``` If the input now starts with a `9` that means, the input itself consisted *only* of `9`s, so the 7-segment display needs to prepend a `1` which costs `2`. The simplest way to handle this is to replace the leading `9` in this case with a `0`, since the cost of incrementing a `9` (to `0`) is `2` and the cost of incrementing `0` (to `1`) is `4`, so this raises the overall cost by `2` as required. ``` T`d`4523315412 ``` Now we have a transliteration stage which replaces each digit with its cost for incrementing it (since the `d` expands to `0123456789`). Note that this is the first subdiagonal of the 7SD table. ``` . $* ``` This replaces each digit `n` with `n` copies of `1`, i.e. it converts each digit to unary, and since there are no separators immediately adds them together. ``` . ``` Finally, we count the number of characters (i.e. number of matches of `.`) in the result, which converts the unary sum back to decimal. ]
[Question] [ Python string parsing has quite a few edge cases. This is a string: ``` "a" ``` Putting 2 strings immediately after each other implicitly concatenates them, so this is also a string: ``` "a""a" ``` However, if you put 3 quotes in a row, it will create a "triple quoted string" which can only be ended by another 3 quotes in a row. A triple quoted string can contain other quotes. These quotes will not end the string unless there are 3 of them. Thus this is valid: ``` """a"a""" ``` Of course, you can combine these together, so this is a valid string: ``` """a""""a" ``` And this: ``` """""aaa""""""""" ``` 3 quotes in a row outside a string always starts a triple quoted string, even if such a string would be invalid. There is no backtracking. A string is *not* valid if: 1. Any `a` appears outside of a string literal (would get `SyntaxError: invalid syntax` in python) OR 2. The end of the sequence is inside a string literal (would get `SyntaxError: unterminated string literal (detected at line 1)` in python) ## Your task Given a string containing 2 distinct characters, one representing a double quote and another representing the letter "a" (most letters except b, u, r, and f would work exactly the same, you don't need to concern yourself with that detail), determine if it would be a valid python string, or invalid syntax. You do not need to consider single quotes or how double and single quotes normally interact. An array of booleans or an array of bytes would also be a valid input method. Thus some valid representations for `"a"` include `$2$`, `[0,1,0]`, or `[False, True, False]`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins. ## Test Cases | Truthy | Falsy | | --- | --- | | `"a"` (1-1) | `"a` (1) | | `"a""a"` (1-2-1) | `"a"a"` (1-1-1) | | `"""a"a"""` (3-1-3) | `""a"a"""` (2-1-3) | | `"""a""""a"` (3-4-1) | `"""a"""a"` (3-3-1) | | `"""""aaa"""""""""` (5-9) | `"""""aaa""""""""` (5-8) | | `""""""""""""` (12) | `""""""aaa"""""""""` (6-8) | | `"a""a""a""a"` (1-2-2-2-1) | `""""` (4) | | `"a"""` (1-3) | `a` | | `""` (2) | `"""a"` (3-1) | | `""""""` (6) | `"""""""` (7) | | `""""""""` (8) | `a""""""` (6) | `eval` or `exec` or `ast.literal_eval` would be [valid](https://codegolf.meta.stackexchange.com/a/17718/91213) answers, though I hope to see more creative python answers as well. [Answer] # [Python](https://www.python.org), 57 bytes ``` lambda s:not re.sub(r'("""|"(?!"")).*?\1','',s) import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBLTsMwEIbFkpximE1mUBKRpPQRqequJ-iOsnBFIyKlsZW4CyRuwqYSgjvBaXD8iICsMt98-u3fb5_qRT_L7vJer_cfZ12ny69VK06HJwFD1UkN_TEbzgfqY0LEV6TNDSJzdrvZ53ESx8nAUXNSsh_NEFDLHlpoOpDq2NEdVxHski2soc0G1Taa-KGqiscIVN90mmracVLTltkFXL6vShQIlKc5wzUK88eRIR4WHgcnHbdoZzSkNKQchYkUljgHXUqZzlyKYw6VPsnMwpr2A7pPV079sxj50vsTyotg_suYW9d2-N2kCG2sNHOK3Y0VRGSvH-5pu4UTTeR0lBkW_vF-AA) # [Python 3.11](https://www.python.org), 53 bytes ``` lambda s:not re.sub(r'("("")?+).*?\1','',s) import re ``` This [requires Python 3.11](https://docs.python.org/3.11/whatsnew/3.11.html#re) which that scandalously outdated ato does not support ;-P [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~23~~ 22 bytes ``` ^(?>("(?>""|)).*?\1)+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP07D3k5DCUgoKdVoaupp2ccYamqr/P@vlKjEBcRgCkQCmVCWEkwQSCeCuWDApYQEoFphBkA1c6GpBEpwgY3mQrcBiwVQXRhWciVyIWkA8SE0AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ ``` Match must start at the beginning of the string. ``` (?>...)+$ ``` After each quoted segment is matched, it cannot be backtracked and reevaluated. Instead, further quoted segments must be matched until the end of the string is reached. ``` ("(?>""|)) ``` Three quotes must be matched if possible, otherwise one. This decision cannot be changed later. ``` .*?\1 ``` Match the closing quote(s) as early as possible. Edit: Saved 1 byte thanks to @Mukundan314. [Answer] # [C (GCC)](https://gcc.gnu.org), ~~132~~ ~~130~~ ~~109~~ 108 bytes *-12 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* *-9 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)* *-1 bytes thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)* ``` #define T bcmp(s,"\"\"\"",n) n;g(char*s){for(n=3;~n;n-=2)if(!T){for(s+=n;T**s;s++);return*s&&g(s+n);}n=!*s;} ``` [Try it online!](https://tio.run/##bU3LbsIwEDx7v2JxBbLzkCo4WvmL3KAH1yTGEmxRnIoDCp9e13ESCdGu5X3NzowprTEhvB2b1lGDNX6ay1X4gh/S4wVJIGWFOeku8/LefnWCqp16kKKy2krXilU9rX1ekaqzzCuf51J1Tf/dUeY3GxshkmqgahXBITjq8aIdCXkHNg6@7xzZ/fb9QwG7ndy5QWGb3osJkBLjIbvGvm8FXx8Rce3xQLxAu9wUs4qMEgzYAEPgmkP8qYw5tnPHl2WsOo0pgD/FTF0EZjK8XEYAkjS8OvxjMLP@WIKGJ8I4T/XHtGdtfShvvw "C (gcc) – Try It Online") Note: 3 bytes can be shaved by changing the quote char. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (no built-in); 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (built-in) ### Built-in The two-byte built-in `ŒV` (evaluate Python code) works as a full program when given the raw input enclosed in `'''` - the exit code identifies the result: \$0\$ [if valid](https://tio.run/##y0rNyan8///opLD///@rq6srKSklAjGQBQA "Jelly – Try It Online"), \$1\$ [if not](https://tio.run/##y0rNyan8///opLD///@rq6srKSklgjGQDQA "Jelly – Try It Online"). Aside: The zero-byte program, when given the raw input, will actually give the evaluated string if valid, or the input if not. However, this does not conform with [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") defaults. ### Non built-in ``` Ạ3ƤḢḤ‘ɓẠ⁹ƤḢ×TƊḟḶ}+Ḣ ḊÇ¡ÐL ``` A monadic Link that accepts a list of \$1\$s (`"`s) and \$0\$s (`a`s) and yields an empty list (falsey) if valid or a non-empty list (truthy) if not. **[Try it online!](https://tio.run/##y0rNyan8///hrgXGx5Y83LHo4Y4ljxpmnJwMFHjUuBMsdHh6yLGuhzvmP9yxrVYbyOd6uKPrcPuhhYcn@Pz//z/aUAcEDXTgdCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrgXGx5Y83LHo4Y4ljxpmnJwMFHjUuBMsdHh6yLGuhzvmP9yxrVYbyOd6uKPrcPuhhYcn@Px/uHvLoa22jxrmKhkYHm6318l61DBHwcZWASiiGfn/v7q6egyXUqISCIMpEAlkQllKMEEgnQjmggGXEhKAaoUZANXMhaYSKMEFNpoL3QYsFkB1YVjJlciFpAHEh9BAXwAA "Jelly – Try It Online"). ### How? ``` Ạ3ƤḢḤ‘ɓẠ⁹ƤḢ×TƊḟḶ}+Ḣ - Helper Link, prefix length that may be removed: list of 1s and 0s, L 3Ƥ - for overlapping infixes of length 3: Ạ - all? Ḣ - head -> 1 if L starts with three 1s, 0 otherwise Ḥ - double ‘ - increment -> 3 if L starts with three 1s, 1 otherwise ɓ - new dyadic Link - f(L, Y=that) ⁹Ƥ - for overlapping infixes of length Y: Ạ - all? Ɗ - last three links as a monad - f(Z=that): Ḣ - head (alters Z) and yield T - truthy indices (of the altered Z) × - multiply (vectorises) Ḷ} - lowered range (Y) -> [0] or [0,1,2]) ḟ - filter discard (these invalid locations) + - add Y (vectorises) Ḣ - head (the empty list yields 0) ḊÇ¡ÐL - Main Link: list of 1s and 0s, L ÐL - repeat while results are distinct applying: ¡ - repeat... Ç - ...number of times: call the helper Link - f(current L) Ḋ - ...action: dequeue ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` Wθ≔⎇⌕θ"""∧∧¬⌕θ"⊖№θ"✂θ⊕§⌕Aθ"¹Lθ¹∧⊖№θ"""✂θ⁺⁶⌕✂θ³Lθ¹"""Lθ¹θ⁼θω ``` [Try it online!](https://tio.run/##dU7LCsIwELz7FSGnBOpBBC89FR9QECnosZfSLm0gbsmjVr8@JlXbipglh53ZeZRNocu2kM71jZBAmOIkMUbUyC6gsdAPdhBYMRURmg9DeUQSj4R/au2cptxzOyg1XAEtVGzbdmgn0rNnKUoISIrTWWJTrOA@WCVSjoKIrILmCFjbxjcL@yv8X0j@aTHmZLIzbBORoeaIrn9c5@IvKgCKx4tMCx@zV10hTbDoOY@do@/nljf5BA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for valid quotes, nothing if not. Explanation: ``` Wθ ``` Repeat until the input becomes the empty string (because all quoted substrings were successfully parsed) or zero (because an error occurred). ``` ≔⎇⌕θ""" ``` If the input does not begin with `"""`, then... ``` ∧∧¬⌕θ"⊖№θ"✂θ⊕§⌕Aθ"¹Lθ¹ ``` ... it must begin with `"` and contain at least two `"`, in which case slice it after the second `"`, otherwise... ``` ∧⊖№θ"""✂θ⁺⁶⌕✂θ³Lθ¹"""Lθ¹θ ``` ... it must begin contain at leat two `"""`, in which case slice it after the second `"""`. ``` ⁼θω ``` Output whether the input was valid. [Answer] # Regex (Javascript/PCRE), ~~31~~ 28 bytes * -3 bytes thanks to Neil and Mukundan314 ``` ^(""$|"a+"|"""("?"?a)*""")+$ ``` [Try it on regexr](https://regexr.com/7199l) Basically: * Empty single-quoted string may appear only at the end * A single-quoted string outside the end must contain at least one element, this makes it unambiguous with a triple quoted string. Since "stock" regex has no way to prevent backtracking there must be no ambiguity. * A triple quoted string may contain up to 2 quotes in a row. These quotes may not be at the end. If they where at the end they would end the string early. Unlike single quoted strings tripple quoted ones may be empty without introducing ambiguity. [Answer] # x86-64 machine code, 24 bytes ``` E2 03 6A 06 59 B0 14 AE 7B F6 18 D2 D2 C0 24 01 83 C9 03 00 D0 78 EE C3 ``` [Try it online!](https://tio.run/##ZVJNb9swDD2Lv4JTEUBq0yHpRw5xvUvPvfQ0oOnBkeRYhSM5ltMpKPrX59FqHDSYYIiP71GPJGB1vVGq74uwRYHPXMBuyWrvG3RQLlmzDxUuMmyIaFUEt2Rb/45FPcVZnN8BC6oIa2BvjccdZes1atJ0Daz1dapThAunE54D8y0aFad4S6z@Yofqt0ANWWs6kBxlBqoqWiyF8i50mJLLIDN891bjTlABXFin6r02@BA6bf3P6tcZ1Vq3GTiwrsNtYZ2Q8AEsWYWXm/vFawbsT2Vrg4KWcKXgk8CnGCTmOc4lMNaQRzfwdtVNwsqRWooghxp6O6or91SoyjqDymuz5IM29IyY42yKB0q1x4@xHCezm9/kdMiF2LtgN87otOCl3MmXeHX1KrNPPA52wB9kEh9vvzdEMbG4PnQmyDRTJPGz73nkwCN9/Aulm6fIB3QCKZ7UEVGMSUjnPwb4t3NMzh@kvmP3keFAEx07wbnTyRGOLvBXlXWxCf31dnFHF/2SOW1s6n8 "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of a null-terminated byte string consisting of `"` and `x` in RDI, and returns 0 or 1 in AL. The starting point is after the first 2 bytes. --- This uses a single-pass algorithm: it processes each character of the string in order. The validity condition can be checked by a [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) like this: [![An incomplete DFA, with seven states S, N0, N1, N2, T0, T1, and T2, connected by quote transitions in that order. There is also a quote transition from T2 to N0, and x transitions from S and N1 to S and from T0, T1, and T2 to T0. The start state is N0. States N0 and N2 are accepting.](https://i.stack.imgur.com/RsUnx.png)](https://i.stack.imgur.com/RsUnx.png) (Technically, to satisfy the most common definition of a DFA, we would need to fill in the missing transitions, pointing them to a sink state. But the program can easily return before the end of the string, so this is not a problem.) We number the states 7, 6, 5, 4, 3, 2, 1 in the order shown, so that implementing the `"` transition is easy: subtract 1, and if the result is 0, change it to 6. The current state number is held in RCX. The `x` character and the null terminator can be handled together, as follows: | | N0/N2 | Other | | --- | --- | --- | | NUL | Success | Failure | | `x` | Failure | S/T | The "S/T" case is implemented by bitwise-ORing the state number with 3, which changes it to 3 or 7 as appropriate. In assembly: ``` q: loop n # (For ") Decrease RCX by 1, and jump if the result is not 0. f: push 6; pop rcx # (When it hits 0, or at the start) Set RCX to 6. n: mov al, 0x14 # Set AL to 0x14. scasb # Read a byte from the string, advancing the pointer, # and set flags based on AL minus that byte. jpo q # Jump if the sum of the bits is odd (true only for "). sbb dl, dl # Subtract DL+CF from DL, making it 0 for NUL or -1 for x. rol al, cl # Rotate AL left by the low byte of RCX, the state number... and al, 1 # ...and keep only the low bit, which is 1 only for state 4 or 6. or ecx, 3 # Bitwise-OR ECX with 3, changing 1–3 to 3 and 4–7 to 7. add al, dl # Add DL to AL, making 1 for success, 0 for failure, -1 for S/T. js n # Jump (to continue processing the string) if it's negative. ret # Return. ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~2~~ ~~1~~ 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` §g ``` -1 byte by changing an explicit evaluate as Python (`.E`) to an implicit one (`§`) +1 byte because apparently the default is truthy/falsey when it's unspecified. I was under the impression two distinguished values were the default, unless truthy/falsey was mentioned specifically. Input wrapped in a list (as-is, since 05AB1E uses `"`/`"""` for string-quotes as well). Outputs `1` for truthy or nothing for falsey. [Try it online](https://tio.run/##MzBNTDJM/f//0PL0//@jlUAgMTFRCQZiAQ) or [verify all test cases](https://tio.run/##bY5BDoIwEEX3PcWkYWcEiXFjwJ1uPYBhMcDENiEtkSaGE3kPL1ZLgWIIXXT@/Om83xI7YSs0cIFK1xTrDktJkGVwvd/s9/O0rjIm85S9hWwIXoQ1SMVqzQCoEhr2Cngkz8Cd0fZGaHWERLcmOZywTCkZkXHbrxIyiBwHoCEDXO7ylE9Ex1ZkHxx5wYZ7EkN1TdB8GTiF3vBn9v5aD1lQAROeenccTdB12GZW2N/IdwXn9eVLBfsB) **Explanation:** ``` § # Cast the (implicit) input to a string, which is implicitly evaluated as Python† # (if it was invalid Python, it will stop the program and output nothing) g # Pop and push the length, to make the truthy cases explicit 1 # (after which the truthy case is output implicitly with trailing newline) ``` † This only applies to the legacy version of 05AB1E, which is build in Python. In the new version of 05AB1E (build in Elixir), this wouldn't work. --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔU17SbεXr¡D¬õQ©sg3@*i¦¦yýëX}}®è}õQ ``` Less boring approach without Python eval. Uses `1` instead of `"` in the inputs. Not the shortest approach, but at least it works. 🤷 [Try it online](https://tio.run/##yy9OTMpM/f//3JRQQ/PgpHNbI4oPLXQ5tObw1sBDK4vTjR20Mg8tO7Ss8vDew6sjamsPrTu8ohYo9/@/IQgkJiYawsB/Xd28fN2cxKpKAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1NCDc2Dk85tjSg@tNDl0JrDWwMPrSxON3bQyjy07NCyysN7D6@OqK09tO7wilqg3H@d/9FKhomGSjogEsoA0UAOnG2IkACyEsECYAATQ@KCDUEYBTcGrhRJj5KOAlAFRBnUAnSLsdoLNwJTDEglwnQjbAKJQlmx/3V18/J1cxKrKgE). **Explanation:** ``` Δ # Continue until the result no longer changes # (using the implicit input-string in the first iteration): U # Pop the current string, and store it in variable `X` 17S # Push pair [1,7] b # Convert each to binary: [1,111] (these are the quotes to check) ε # Map over them: X # Push string `X` s # Swap so the current (binary) quote is at the top ¡ # Split string `X` on this single/triple (binary) quote D # Duplicate the split list ¬ # Push its first item (without popping) õQ # Check that the first item is an empty string # (which means string `X` starts with the current (binary) quote) © # Store this 0 or 1 in variable `®` (without popping) s # Swap so the split list is at the top again g # Pop and push its length 3@ # Check that this length is >=3 # (which means there is a matching closing quote) *i # If both checks are truthy: ¦ # Remove the empty first string ¦ # As well as the second string yý # Then join it with the (binary) quote again ë # Else: X # Simply keep `X` as is } # Close the if-else statement } # Close the map ® # Push the last `®` result for the triple-quote è # 0-based index this check into the pair } # After the loop: õQ # Check if what remains is an empty string # (after which the result is output implicitly) ``` [Answer] # [Whython](https://github.com/pxeger/whython), 20 bytes ``` lambda s:eval(s)+s?0 ``` Just getting the obvious out of the way. [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8HiNNuYpaUlaboWW3ISc5NSEhWKrVLLEnM0ijW1i-0NIFI3X6TlFymUpBaXJCcWpypk5imoq6tzKSUqgTCYApFAJpSlBBME0olgLhhwKSEBqFaYARDNiVxgc7jQjcNiGtQwdBEuoMv0ikuKMgs0NPWKC3IyS3Iy81KLNTStuBQUCooy80o0YP7QUVDStVPSUUiDi2hqQvy7YAGEBgA) ### Explanation Whython is mostly Python 3, but with a couple added features. Here, we use the rescue operator `?`, which returns its left operand unless it raises an exception, in which case it returns its right operand instead. So if the argument `s` represents a valid string, `eval(s)` returns that string. Since the string can be empty, we concatenate `s` to it to make sure the result is nonempty and therefore truthy. If `s` is not a valid string, `eval(s)` errors, so we return `0` (falsey) instead. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 18 bytes ``` '"""'/['"']+2%{~}% ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X11JSUldP1pdST1W20i1uq5W9f9/oFCiEgA "GolfScript – Try It Online") Split on ````` and eval each. Why 18 bytes though? :( [Answer] # Regex (Perl or PCRE), 21 bytes ``` ^(?>("("")?+).*?\1)+$ ``` [Test online on Regex101](https://regex101.com/r/bqab2U/1) The idea to use a backreference was inspired by @Neil's answer. I wrote the rest myself, but most of it ended up the same (probably because there's only one shortest way to express the algorithm, so two golfers will come to the same conclusions). The Regex101 link uses the `/gm` flags in order to test multiple inputs at once – the problem as stated takes only a single input, so those flags aren't required and aren't part of the submission. (The existence of Regex101 establishes "regex" as a valid programming language by itself for the purposes of this site, as Regex101 acts as an interpreter for the language.) ## Explanation ``` ^(?>("("")?+).*?\1)+$ ^ $ Only the input as a whole matches ( )+ The input must consist of one or more of: ( ) a group named \1, which consists of " one double quote, ("") followed by two more double quotes ?+ if they are present at that point in the input, .* followed by any number of any characters, ? the shortest number which leads to a match, \1 followed by another copy of \1, ?> but try only the first possibility for each block ``` Here, each block has its own `\1`, i.e. the delimiter is allowed to be different for each block. Normally, regexes can backtrack if one potential parse doesn't work, to try a different potential parse. This solution therefore has to contain a couple of backtracking-blockers in order to ensure that if Python would reject a parse, we also reject the input rather than backtracking: * The `+` on `"("")?+` means that if three double-quotes are present in a row at that point of the input, all three double-quotes must be included in `\1`, the variable that holds the delimeter; the regex engine isn't allowed to go back and try with just one. This ensures that `"""a"` is correctly rejected, by preventing it being parsed as `""``"a"`. * The `?>` means that once the first possibility for a string in the input has been discovered, that must be used as a section when matching for the string as a whole; the regex engine isn't allowed to go back and try a different section. Because of the `?` on `.*?`, sections are tested shortest to longest, so in this situation, the restriction imposed by `?>` can equivalently be stated as "if any prefix of the input is a valid string, that prefix must be interpreted as the string, don't look for any longer prefixes that might also be valid". This ensures that `"""a""""` is correctly rejected, by preventing it being viewed as `a"` within triple quotes (because `"""a"""` is a valid string that will be tested first). # Regex (Perl or PCRE, no backreferences), 25 bytes ``` ^(?>""".*?"""|"a+"|""$)+$ ``` [Test online on Regex101](https://regex101.com/r/1CiUt2/1) The thing that first inspired me to try answering this question with regex is that the set of allowed answers is a regular expression in the mathematical sense – you can solve it purely with a finite state automaton. Here's an answer that demonstrates that. It's pretty similar to the previous solution, except that there are separate cases for the `"` and `"""` delimiters. When using `"""`, the string can be empty; as in the previous answer, there's a backtracking-blocker (here `?>`) present to ensure that only the first `"""` is matched. When using `"`, then the regex needs to disallow possibilities that would start with `"""`. The only such possibility is an empty string followed by another string, so we ensure that either the string is nonempty (i.e. it contains `a+`, i.e. one or more `a`), or else that we have an empty string at the end of input (written in regex syntax as `""$`). As a side note, the fact that the set of answers is a regular expression in the mathematical sense implies that problem can also be solved without backtracking-blockers at all (meaning that no evaluation order hints are required either). However, the solution would likely be somewhat longer; the best I've found is `^("""("{0,2}a)*"""|"a+"|""$)+$` at 30 bytes. [Answer] # [Turing Machine Code](http://morphett.info/turing/turing.html), 147 bytes ``` 0 " _ r 1 0 _ _ * haltA 1 " _ r 2 1 a _ r S 2 " _ r T 2 _ _ * haltA S a _ r S S " _ r 0 T a _ r T T " _ r 3 3 " _ r 4 3 a _ r T 4 " _ r 0 4 a _ r T ``` [Try it online!](https://morphett.info/turing/turing.html?a7fc84e1a5bc55b05cc1923a3969573d) The input string is valid iff the machine halts on state `haltA`. Note that the machine is basically a DFA. [Answer] # [C (gcc)](https://gcc.gnu.org/), 84 bytes ``` n;S;g(char*s){n=bcmp(s,S="\"\"\"",3)?1:3;S=strstr(s+n,S+3-n);n=*s-34?!*s:S&&g(S+n);} ``` [Try it online!](https://tio.run/##bU3LbsIwEDx7v8K1BLITR2pxT1gRH@Fj6cF1wUQiFsKROKD8OmZjHAnRrh@zj5lZ13jnUgraaM/dwZ6rKK6h/XH9iUdpWrbNh0klNh9rpU0bhzNeHusgTa2aIHRoq9ioz81bFddmufTc1NgdUxcG2tsucHEFMhWo64L/Wr1/ayCXQ3fcUe53Q@SPgRAUieSE@bDnbPFLKV1Eug1MUj9zZHERaEGAjDAmZhngyzD9mJaMzU1Em8scwJ6iSGeDIoYXJg4gW8Prhn8WFNWflWDhSTDVD7y5/dH6mJpLanq1ugM "C (gcc) – Try It Online") Require 32-bit or +5 byte `long` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` † ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oCgIiwiIiwiW1wiYVwiXVxuW1wiYVwiXCJhXCJdXG5bXCJcIlwiXCJdXG5bXCJhXVxuW1wiXCJcIlwiXCJhYWFcIlwiXCJcIlwiXCJcIlwiXCJdXG5bYV0iXQ==) Python `eval` and inputs as a list. Returns a a list `[0]` if true and an empty list `[]` if false. [Answer] # Python (built-in), 4 bytes (built-in), JS (TODO) Because I'm evil and mousetail allowed me to. ``` exec ``` ~~I'll add a C answer later.~~ A C answer has already been added, so I'll add a JS answer by 19 November 2022. Note: there are other answers that deserve your upvote, rather than this one. ]
[Question] [ An analog clock has 2 hands\*: Hour and minute. These hands circle the clock's face as time goes by. Each full rotation of the minute hand results in 1/12th of a rotation of the hour hand. 2 full rotations of the hour hand signifies a full day. As these hands are fixed to the same central point, and rotate around that point, you can always calculate the angle between the hands. In fact there are 2 angles at any given time; A larger one, and a smaller one (sometimes they will both equal 180, but that's not important) *\*Our hypothetical clocks don't have second hands* ## Task Given a time in 24 hour format, output the smaller angle between the hands, in degrees. If the hands are directly opposite eachother (such as at `6:00`, `18:00` etc) output 180 ## Rules Input may be taken as: - A delimiter separated string: `6:32`, `14.26` - 2 separate values, strings or ints: `6, 32`, `14, 26` - An array of 2 values, strings or ints: `[6, 32]`, `[14, 26]` You may also optionally specify that your answer requires inputs be padded to 2 digits (assuming you take strings), ie: `06:32`, `06, 32`, `[06, 32]` You may also optionally reverse the order of the inputs, taking minute then hour, ie: `32:6`, `32, 6`, `[26, 14]` Hour will be an integer value between `0` and `23` (inclusive) Minute will be an integer value between `0` and `59` (inclusive) You can assume that the minute hand snaps to increments of 6 degrees along the face (one evenly-spaced position for each minute value) You can assume that the hour hand snaps to increments of 0.5 degrees along the face (one evenly-spaced position for each minute value per hour value) Output must be given in degrees, not radians. You may include a trailing `.0` for whole numbers ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes *in each language* wins! ## Testcases ``` Input: 06:32 Output: 4 Input: 06:30 Output: 15 Input: 18:32 Output: 4 Input: 06:01 Output: 174.5 Input: 00:00 Output: 0 Input: 00:01 Output: 5.5 Input: 12:30 Output: 165 Input: 6:00 Output: 180 Input: 23:59 Output: 5.5 ``` [Answer] # JavaScript (ES6), ~~41 40~~ 39 bytes Takes inputs as `(h)(m)`. ``` h=>m=>((x=4+h/3-m*.55/9)&2?12-x:x)%4*90 ``` [Try it online!](https://tio.run/##jc9LDoIwEIDhvafoRtPB9EmLYFLceQ/CQzBAjRDT29e4bbtwMbsv/8w8m0@zte/ptZPVdr0fjB9NvZgaY2fUeWQ5WTKqNavgJG9CEnd1cFRZxX1r183OPZ3tAw8YFYBzCXS398n1HRYAiDGkDgnGIyZ04ET5dw6JOHdRNCwiDr8JKU@xuKijnpDpTwqdujEBy3C1zAHrKrXafwE "JavaScript (Node.js) – Try It Online") ### How? Instead of working directly in the range \$[0..360]\$, we define a temporary variable \$x\$ in the range \$[0..4]\$: $$x=\left|\frac{4h}{12}+\frac{4m}{60\times12}-\frac{4m}{60}\right|\bmod 4$$ $$x=\left|\frac{4h}{12}-\frac{44m}{60\times12}\right|\bmod 4$$ $$x=\left|\frac{h}{3}-\frac{11m}{180}\right|\bmod 4$$ The angle in degrees is given by: $$\min(4-x,x)\times90$$ However, the formula is implemented a bit differently in the JS code, as we definitely want to avoid using the lengthy `Math.abs()` and `Math.min()`. Instead of computing the absolute value, we force a positive value in \$[0..12]\$ by computing: $$x'=4+\frac{h}{3}-\frac{11m}{180}$$ And instead of computing the minimum, we determine in which case we are by simply doing a bitwise AND with \$2\$ -- and this is why we chose an interval bounded by a power of \$2\$ in the first place. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes ``` ד<¿‘Iæ%ذAH ``` [Try it online!](https://tio.run/##AUwAs/9qZWxsef//w5figJw8wr/igJhJw6Ylw5jCsEFI/0RVK8OYMFVq4oCdOjvigJwgLT4g4oCdO8OHCjI0LDYw4bi2xZJww4figqxZ//// "Jelly – Try It Online") A monadic link which takes the time as a list of two integers: hour, minute. Thanks to @JonathanAllan for saving 2 bytes! ### Explanation ``` ד<¿‘ | Multiply hour by by 60 and minute by 11 I | Find difference æ%ذ | Symmetric mod 360 [equivalent to (x + 360) mod 720 - 360] A | Absolute H | Half ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~30~~ ~~29~~ 28 bytes ``` 5Abs@Mod[#.{6,-1.1},72,-36]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9/UManYwTc/JVpZr9pMR9dQz7BWx9xIR9fYLFbtf0BRZl6Jg1aagr6DQjVQWsHYqFZHAcwwADEMLZCEDEG0gY6CAZQG8w2NYGrNoDJGxjoKppa1tf8B "Wolfram Language (Mathematica) – Try It Online") ungolfed version: ``` Abs[Mod[#.{30,-5.5}, 360, -180]] & ``` The argument of the function is `# = {h,m}` containing the hour and the minute. This length-two list is interpreted as a vector and the dot-product with `{30,-5.5}` is calculated: `#.{30,-5.5} = 30*h-5.5*m`. Then we calculate the symmetric modulus of 360 with `Mod[#.{30,-5.5}, 360, -180]` giving an angle in the interval -180..+180. `Abs` takes the absolute value thereof. As all involved operators are linear, we can multiply and divide all appearing numbers however they are most convenient. By pulling a factor of `5` out of the expression and dividing all numbers in the expression by 5, the byte-count is minimized. [Answer] # MATL, 18 bytes ``` 30*i5.5*-t360-|hX< ``` Accepts two inputs of hours followed by minutes. Uses the same method as [this answer](https://codegolf.stackexchange.com/a/187248/51939) Try it at [MATL Online](https://matl.io/?code=30%2ai5.5%2a-t360-%7ChX%3C&inputs=12%0A30&version=20.11.0) **Explanation** ``` % Implicitly grab first input (hours) 30* % Multiply by 30 i % Explicitly grab second input (minutes) 5.5* % Multiply by 5.5 - % Take the difference t % Duplicate the result 360- % Subtract 360 | % Take the absolute value h % Horizontally concatenate X< % Determine the minimum value % Implicitly display the result ``` [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 134 bytes ``` _->In_h+In_m+720d+360a+f h->60d m+11d-> 0m+d+a+0r->b 0a+0x->r d+b+r->r+a r+0b-> b+0d+0h+0y->5y b+0d+5y->x 0b+0d+f->Out_x+Out_"."+Out_y ``` [Try it online!](https://tio.run/##JYw7DsIwEET7PUba0aJNooRueyqOYNmYyEiYwgTJPr1ZQjM/PY1/3tI9P95774718nIJJhnnSSLmVTw2SqyrRMoYx8hKkhHhIYU1kAFSWQtFBNhS4KlAgnEBdiEJ0liX9q@L5Upy5I31@tldxU@H03B4632aSeQL "Alchemist – Try It Online") ## Explanation ``` _->In_h+In_m+720d+360a+f ``` Initial setup. Inputs hours and minutes into `h` and `m`, sets current angle `d` to 360 degrees (720 half-degrees), sets up `a` to compute the principal angle, and sets the output flag. ``` h->60d m+11d-> ``` Each hour adds 30 degrees, and each minute subtracts 5.5 degrees. ``` 0m+d+a+0r->b 0a+0x->r ``` While the `r` (reverse) flag is not set, each `d` atom should move one `a` atom to `b`. This occurs after the minutes are all used up, to avoid a "race condition". When there are no `a` atoms remaining, set `r` to reverse this flow. Note that this second rule can trigger multiple times, and can even trigger before the initial setup rule. This does not harm anything, so there's no need to prevent this. The `0x` condition handles an edge case: when the input is 6:00, there are no `a` atoms when the program terminates, but there are `x` atoms if the final result is at least 1 degree. ``` d+b+r->r+a r+0b-> ``` The reverse: when the signed angle is greater than 180 degrees, move `b` atoms to `a` to decrease the angle to output. Stop reversing when the angle reaches "360". ``` b+0d+0h+0y->5y b+0d+5y->x ``` When all of the degree atoms are used up, divide by 2 to get the angle to output. ``` 0b+0d+f->Out_x+Out_"."+Out_y ``` After this is done, output exactly once using the `f` flag from the initial setup. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~45~~ 43 bytes -2 bytes thanks to [Erik](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). ``` lambda h,m:min(x:=abs(h%12*30-m*5.5),360-x) ``` [Try it online!](https://tio.run/##TY3dCoIwGIbPu4oPIdjkW@wHhw3sRqoDJcaENod5YIjXvpoYdPS8f/DG9@SGoOo4Jtvc0rP13aMFh974PpDZNG33Iu4oZKk482V1qigqzdlMkx3GPIQ@wJVoBCUpwiZ4FqL@i0QmR@A7Ny/kb6v3RiqE6kzv5gAQxz5MxBaLM1yuZvEZwC6wWPK9pWtB0wc "Python 3.8 (pre-release) – Try It Online") `h%12` - hour in 12-hour format `h%12*30` - angle of hour hand at the full hour `m/2` - angle the hour hand moved in `m` minutes `h%12*30+m/2` - current position of the hour hand as an angle `m*6` - angle of the minute hand (`360°/60 = 6°`) [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç╢e╛╦¡uøßmì♪║└├ ``` [Run and debug it](https://staxlang.xyz/#p=80b665becbad7500e16d8d0dbac0c3&i=[06,+32]%0A[06,+30]%0A[18,+32]%0A[06,+01]%0A[00,+00]%0A[00,+01]%0A[12,+30]%0A[06,+00]%0A[23,+59]&a=1&m=2) * `m =` number of minutes since midnight * `d = 5.5 * m` * The result is `min(d % 360, -d % 360)`. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~47~~ 45 bytes ``` h=>m=>(h=(360+h%12*30-m*5.5)%360)<180?h:360-h ``` [Try it online!](https://tio.run/##bY3BS8MwFMbP5q94FgbJtpakpWVmS70JA8GhBw@yQ@0yEmyz0SZ6EP/2uqRjqHh573vv99731X1c93q4c6Ze7Q7utZHzn3psZbkXgxJlK0qsBM4KOlMTlk4zGrfTPMnJ5LQiK7agt4qfZKyGJfpQupGA1ybZSPmGCVwLiBmBT3T1XnWgzdFZEPAoq929NhKT5Qj6Y6M9CAfJk59wxCOPtbGgDq7rA7bJpup6icPDC92SObTaOCv/w2zrDZ47bWVIi9benkMEszHpD35w9sL3OIQSfLYnv29P09dAC56lyFeK2OKsKUOUckpDZYilnhZ@kWY8v/kG "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` I↔⁻¹⁸⁰﹪⁻׳⁰⁺⁶N×⁵·⁵N³⁶⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzGpWMM3M6@0WMPQwkBHwTc/pTQnHyoSkpmbWqxhDBQOyAFyzXQUPPMKSkv8SnOTUos0NDU1dRQgSkz1TLHIGZsZaIKA9f//hhYKxkb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two integers. Explanation: ``` N First input ⁺⁶ Plus literal 6 ׳⁰ Multiplied by literal 30 ⁻ Minus N Second input ×⁵·⁵ Multiplied by literal 5.5 ﹪ ³⁶⁰ Modulo literal 360 ⁻¹⁸⁰ Subtracted from literal 180 ↔ Absolute value I Cast to string Implicitly print ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 28 bytes ``` ((*/3-*/9*.55+2)%4-2).abs*90 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0NL31hXS99SS8/UVNtIU9VE10hTLzGpWMvS4L81V3FipUKaRo1KvKZCWn4Rl4aCmY6CsZGmDpRlAGIZWiCLKRiCWQZAlgGcBRYzNILpAKsDs4yMdRRMLTV1/gMA "Perl 6 – Try It Online") Uses a few tricks stolen from other answers and calculates ``` r = abs((h/3 - m/9*0.55 + 2) % 4 - 2) * 90 = abs((h*30 - m*5.5 + 180) % 360 - 180) ``` [Answer] # [Python 3](https://docs.python.org/3/), 40 bytes ``` lambda h,m:180-abs(180-(h*30-m*5.5)%360) ``` [Try it online!](https://tio.run/##TY3dCsIgGIbPu4qPQaBD41OZLKFupDpwhDhIN7adhOzaLceCjp73D97xvfghquwu9/yyoXta8CwY0SK33UwKia8V8lA3p4YelUaa3TCVFfQRbkQzUJIy2AQWIdq/SBQiA9y5eSF/W703UjFozvRhDgDj1MeFuCp5g3I1KRQAv0Jy5HtL14rmDw "Python 3 – Try It Online") `h*30` - angle between noon and the hour `h` when the minute is `0`; if the hour is equal or greater than 12, this angle can be equal or greater than 360° `m*6` - angle between noon and the minute hand `m*.5` - angle the hour hand moved forward from the full hour after `m` minutes (e.g: if it's 4:24, the hour hand moved forward 12 degrees from the position it was in at 4 o'clock) `h*30-m*5.5` - one of the two angles between the hour hand and the minute hand; the coefficient for `m` is `5.5` because `m*6-m*.5=m*5.5`; this is still not the answer because it can be a value greater than 360° (e.g: if `h,m=13,0`) or less than 0° (e.g: if `h,m=12,30`) `(h*30-m*5.5)%360` - this modulo takes into account the cases where the computed value above is not between 0 and 360°; this is still not the answer because it could be the ampler of the two angles, while we want the most narrow `180-abs(180-(h*30-m*5.5)%360)` - this is the final result; the general rule is that `x-abs(x-y)` is equivalent to `min(y,x-y)`, which would give the correct result [Answer] # [Tcl](http://tcl.tk/), ~~71~~ ~~74~~ ~~59~~ 54 bytes ``` {{h m {x (60*$h-$m*11)%720}} {expr min($x,720-$x)/2.}} ``` [Try it online!](https://tio.run/##ZY1RC4IwFIX/ykEWqGTdXVHrt1QPEYqBi5ELJmO/fUVPbj5@537nXPOYwtwbDLgG50YoOIu8pVKMlVCllMWuY/Ierrf6DfV85cLuf1ElbHHkg/dBf8yM7HLXelogBrSo@YaIac3ytBFIrplAlHB05xrNOVrk5EWTCJvCX8jCFw "Tcl – Try It Online") saved 5 bytes by using a lambda expression [Answer] # Python 3, ~~58~~ 57 Bytes -1/-2 Thanks to @Shaggy ``` h,m=eval(input()) x=(30*h-5.5*m) print(abs(min(x,360-x))) ``` Naive implementation, takes input in the form of `[6,32]`. Some bytes can probably be shaved off the last line especially. # Python 2, ~~52~~ 50 Bytes ``` h,m=input() x=(30*h-5.5*m) print abs(min(x,360-x)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=min -p`, 37 bytes ``` $_=abs<>*5.5-$_%12*30;$_=min$_,360-$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYxqdjGTstUz1RXJV7V0EjL2MAaKJqbmacSr2NsZgAU/f/f0ILL2OhffkFJZn5e8X9dX5/M4hIrq9CSzByQwv@6BTkA "Perl 5 – Try It Online") Takes input as hours followed by minutes on a separate line because it saved a few bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 60*+5.5*D(‚360%ß ``` Takes hours as first input, minutes as second. [Try it online](https://tio.run/##yy9OTMpM/f/fzEBL21TPVMtF41HDLGMzA9XD84GCXMZGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaW61aGFCcX/zQy0tE31TLVcNB41zDI2M1A9PP@/zv9oJQMzK2MjJR0wbQCkDS3gfANDEG1gZWAApUF8QyOIOpA8iDYytjK1VIoFAA). **Explanation:** Basically implements the following formula: $$t = (60h+m)×5.5$$ $$r = min(t\bmod360,-t\bmod360)$$ ``` 60* # Multiply the (implicit) hours-input by 60 + # Add it to the (implicit) minutes-input 5.5* # Multiply it by 5.5 D(‚ # Pair it with it's negative 360% # Take modulo-360 on both ß # And then pop and push the minimum of the two # (which is output implicitly as result) ``` [Answer] # [R] , 45 bytes ``` function(h,m)min(t=(60*h+m)*5.5%%360,-t%%360) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` *FÑ aV*5½ mUa360 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KkbRIGFWKjW9Cm1VYTM2MA&input=NgozMg) ``` *FÑ aV*5½ :Implicit input of integers U=h and V=m *F :Multiply U by 15 Ñ :Multiply by 2 a :Absolute difference with V*5½ :V multiplied by 5.5 mUa360 :Reassign to U m :Minimum of U and Ua360 :Absolute difference of U and 360 ``` [Answer] ## [><>](https://esolangs.org/wiki/Fish), 17 bytes ``` b*$6a**-:0)12,-*n ``` [Try it online! (6:32)](https://tio.run/##S8sszvj/P0lLxSxRS0vXykDT0EhHVyvv////urpliTmlqf/N4CxjIwA "><> – Try It Online") Takes input as h, m on the stack. ### Explanation ``` b*$6a**-:0)12,-*n b* Multiplies m by 11 $ Swaps m & h 6a** Multiplies h by 60 - Subtracts m & h (v) :0) Checks if v > 0 (b=0/1) 12,- Subtracts .5 from b (-.5/.5) * Multiplies v by b (halve & abs) n Outputs result b* Errors ``` [Answer] ## Pyret, 59 bytes ``` {(h,m):x=(30 * h) - (m * 5.5) num-abs(num-min(x,360 - x))} ``` ]
[Question] [ Randomness is fun. Challenges with no point are fun. Write a function that, given integer input `n`, will output a **set** (unordered, unique) of exactly `n` random integers between `1` and `n^2` (inclusive) such that the sum of all integers is equal to `n^2`. Randomness does *not* have to be uniform, provided each valid set has a non-zero chance to occur. Shortest answer in bytes (per each language) wins. ## Examples ``` Input (n) = 1, Target (n^2) = 1 Sample of possible outputs: 1 Input = 2, Target = 4 Sample of possible outputs: 3, 1 1, 3 Input = 3, Target = 9 Sample of possible outputs: 6, 1, 2 3, 5, 1 4, 3, 2 Input = 4, Target = 16 Sample of possible outputs: 1, 3, 5, 7 2, 4, 1, 9 8, 3, 1, 4 Input = 5, Target = 25 Sample of possible outputs: 11, 4, 7, 1, 2 2, 3, 1, 11, 8 6, 1, 3, 7, 8 Input = 8, Target = 64 Sample of possible outputs: 10, 3, 9, 7, 6, 19, 8, 2 7, 16, 2, 3, 9, 4, 13, 10 7, 9, 21, 2, 5, 13, 6, 1 ``` **Bonus Task:** Is there a formula to calculate the number of valid permutations for a given `n`? [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 15 bytes (random) or 13 bytes (all possibilities) ## Random ``` ~lℕ₁ᵐA+√?∧A≜₁ᵐ≠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7nUcvUR02ND7dOcNR@1DHL/lHHcsdHnXMgQo86F/z/b/w/CgA "Brachylog – Try It Online") Function submission (seen in TIO with a wrapper making it into a full program). ### Explanation ``` ~lℕ₁ᵐA+√?∧A≜₁ᵐ≠ ~l Specify a property of a list: its length is equal to the input, ᵐ and it is composed entirely of ℕ₁ integers ≥ 1, √ for which the square root of the + sum of the list ? is the input. A ∧A Restricting yourself to lists with that property, ≜₁ pick random possible values ᵐ for each element in turn, ≠ until you find one whose elements are all distinct. ``` ## All possibilities ``` ~lℕ₁ᵐ<₁.+√?∧≜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1vb/9flPGqZCmZPsAFSetqPOmbZP@pY/qhzzv//xv@jAA "Brachylog – Try It Online") Function submission, which [generates](https://codegolf.meta.stackexchange.com/a/10753/76359) all possible outputs. ### Explanation ``` ~lℕ₁ᵐ<₁.+√?∧≜ ~l Specify a property of a list: its length is equal to the input, ᵐ it is composed entirely of ℕ₁ integers ≥ 1, <₁ it is strictly increasing, √ and the square root of the + sum of the list ? is the input. . ∧≜ Generate all specific lists with that property. ``` I'm fairly surprised that `∧≜` works (you'd normally have to write `∧~≜` in order to brute-force the output rather than the input), but it turns out that `≜` has an input=output assumption so it doesn't matter which way round you run it. ## Bonus task In order to get some insight into the sequence of the number of possibilities, I created [a different TIO wrapper](https://tio.run/##SypKTM6ozMlPN/r/aP6yR02N1Y/aNjxqanq4bU7tw60T/tflPGqZChQGsm2AlJ72o45Z9o86lj/qnPP/v6HB/ygA) which runs the program on successive integers to give the sequence of output counts: ``` 1,1,3,9,30,110,436,1801,7657,33401 ``` A trip to OEIS discovers that this is already a known sequence, [A107379](http://oeis.org/A107379), described pretty much as in the question (apparently you get the same sequence if you restrict it to odd numbers). The page lists several formulas for the sequence (although none is particularly simple; the second looks like a direct formula for the value but I don't understand the notation). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` nÅœʒDÙQ}sùΩ ``` [Try it online](https://tio.run/##ARwA4/9vc2FiaWX//27DhcWTypJEw5lRfXPDuc6p//82) or [verify all test cases](https://tio.run/##ASoA1f9vc2FiaWX/N0dOPyIg4oaSICI/TkT/bsOFxZPKkkTDmVF9c8O5zqn/LP8). **Explanation:** ``` n # Take the square of the (implicit) input # i.e. 3 → 9 Åœ # Get all integer-lists using integers in the range [1, val) that sum to val # i.e. 9 → [[1,1,1,1,1,1,1,1,1],...,[1,3,5],...,[9]] ʒ } # Filter the list to only keep lists with unique values: D # Duplicate the current value Ù # Uniquify it # i.e. [2,2,5] → [2,5] Q # Check if it's still the same # i.e. [2,2,5] and [2,5] → 0 (falsey) s # Swap to take the (implicit) input again ù # Only leave lists of that size # i.e. [[1,2,6],[1,3,5],[1,8],[2,3,4],[2,7],[3,6],[4,5],[9]] and 3 # → [[1,2,6],[1,3,5],[2,3,4]] Ω # Pick a random list from the list of lists (and output implicitly) ``` [Answer] # [Python](https://docs.python.org/) (2 or 3), 85 bytes ``` def f(n):r=sample(range(1,n*n+1),n);return(n*n==sum(r))*r or f(n) from random import* ``` **[Try it online!](https://tio.run/##NY2xDsIwDERn@hXeGpeAKANDUfmXiiYQiTiR7Q79@pAWYcmy7k73nFd9J7qWEHNiBVmlqXsWp@yeC0tI9AkxqOkv22CZnQdvCAceZYr54wxP9HKmt9TRsUdLeGenC5OpxjjKEg0jdgyJ92LjOUWopbme39uu@BqqE4VA8OfBDYfmkDmQ7pmF9vRobYVsCssX "Python 2 – Try It Online")** [Answer] # [R](https://www.r-project.org/), ~~68, 75~~ 48 bytes (random) and 70 bytes (deterministic) @Giuseppe's rejection sampling method: ``` function(n){while(sum(F)!=n^2)F=sample(n^2,n);F} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7O6PCMzJ1WjuDRXw01T0TYvzkjTzbY4MbcAKAjk6ORpWrvV/k/TMNTkStMwAhHGIMIERJiCCDMQYa75HwA "R – Try It Online") Golfed original: ``` function(n,m=combn(1:n^2,n))m[,sample(which(colSums(m)==n^2)*!!1:2,1)] ``` [Try it online!](https://tio.run/##Fcq9DkAwEADg3VOw3UkNrZ9B9CmMQkKjIXFXUeLxS5dv@q5g064I9mFz746BBWnjaGGQLU9KMCINws90Hiu82242MO7oH/JAqPVfMM8y2SohcQwWJCYWVKSMVJE60mD4AA "R – Try It Online") The `*!!1:2` business is to avoid the odd way `sample` act when the first argument has length 1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ²œcS=¥Ƈ²X ``` [Try it online!](https://tio.run/##y0rNyan8///QpqOTk4NtDy091n5oU8T///@NAQ "Jelly – Try It Online") Generate all n-combinations of the list [1..n²], filter to keep those with sum n², then pick a random one. [Answer] # Java 10, ~~250~~ ~~242~~ 222 bytes ``` import java.util.*;n->{for(;;){int i=n+1,r[]=new int[i],d[]=new int[n];for(r[n<2?0:1]=n*n;i-->2;r[i]=(int)(Math.random()*n*n));var S=new HashSet();for(Arrays.sort(r),i=n;i-->0;)S.add(d[i]=r[i+1]-r[i]);if(!S.contains(0)&S.size()==n)return S;}} ``` -20 bytes thanks to *@nwellnhof*. Watch out, Java coming through.. It's 'only' five times as long as the other four answers combined, so not too bad I guess.. rofl. It does run `n=1` through `n=25` (combined) in less than 2 seconds though, so I'll probably post a modified version to the speed version of this challenge (that's currently still in the Sandbox) as well. [Try it online.](https://tio.run/##LVDBUsIwEL3zFSsHJ6E2UGY8aKyONy@iMz0yPYQ2SLBsmWSLg0yvfoCf6I/gBsghO/uy723eW5udSdf159Fttq0nWHOvOnKNGmkAGI/h3TDcLoFWFhZ7smnVdkggkuxODqrGhACvxuFhAOCQrF@aysIstgCFJagEw4BSM9IP@ApkyFUwA4Qcjpg@HpatF1rLQxx0OSbZjZ@XOdqvqDh3pd4ZD8UJeDFhxapC6kjyc3yYPk3uM54eoXZp@jjVnhl5XCrFq6GV8gbrdiPkiEfkmffsvdkHFdix8PKGd564Ey0LZeqadV2SlWlUktotxVWhqhaJbQYxkdeFCu7bCpnnKL2lziMUuu@POtrbdouG7V1c7lpXw4aJoiDv8GNegpHncOJHzo4zDe4hn95ySZLLK8DbYm0rAm9D1xBHhYqjPMUYz6UU@0B2o9qO1Jb1qUHhkiH8/fzCMDkzLpT@lH9//Ac) **Explanation:** In pseudo-code we do the following: 1) Generate an array of size `n+1` containing: `0`, `n` squared, and `n-1` amount of random integers in the range `[0, n squared)` 2) Sort this array 3) Create a second array of size `n` containing the forward differences of pairs These first three steps will give us an array containing `n` random integers (in the range `[0, n squared)` that sum to `n` squared. 4a) If not all random values are unique, or any of them is 0: try again from step 1 4b) Else: return this differences array as result As for the actual code: ``` import java.util.*; // Required import for HashSet and Arrays n->{ // Method with int parameter and Set return-type for(;;){ // Loop indefinitely int i=n+1, // Set `i` to `n+1` r[]=new int[i]; // Create an array of size `n+1` var S=new HashSet(); // Result-set, starting empty for(r[n<2? // If `n` is 1: 0 // Set the first item in the first array to: : // Else: 1] // Set the second item in the first array to: =n*n; // `n` squared i-->2;) // Loop `i` in the range [`n`, 2]: r[i]= // Set the `i`'th value in the first array to: (int)(Math.random()*n*n); // A random value in the range [0, `n` squared) for(Arrays.sort(r), // Sort the first array i=n;i-->0;) // Loop `i` in the range (`n`, 0]: S.add( // Add to the Set: r[i+1]-r[i]); // The `i+1`'th and `i`'th difference of the first array if(!S.contains(0) // If the Set does not contain a 0 &S.size()==n) // and its size is equal to `n`: return S;}} // Return this Set as the result // (Implicit else: continue the infinite loop) ``` [Answer] # [Perl 6](http://perl6.org/), 41 bytes ``` {first *.sum==$_²,(1..$_²).pick($_)xx*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi2zqLhEQUuvuDTX1lYl/tAmHQ1DPT0QQ1OvIDM5W0MlXrOiQqv2f3FipYaSSryCrZ1CdZqCSnytkqZCRQWQoZCWX6QA1GP6HwA "Perl 6 – Try It Online") * `(1 .. $_²)` is the range of numbers from 1 to the square of the input number * `.pick($_)` randomly chooses a distinct subset of that range * `xx *` replicates the preceding expression infinitely * `first *.sum == $_²` selects the first of those number sets that sums to the square of the input number [Answer] # Pyth, ~~13~~ 12 bytes ``` Ofq*QQsT.cS* ``` Try it online [here](https://pyth.herokuapp.com/?code=Ofq%2AQQsT.cS%2A&input=3&debug=0). Note that the online interpreter runs into a MemoryError for inputs greater than 5. ``` Ofq*QQsT.cS*QQQ Implicit: Q=eval(input()) Trailing QQQ inferred S*QQQ [1-Q*Q] .c Q All combinations of the above of length Q, without repeats f Keep elements of the above, as T, where the following is truthy: sT Is the sum of T... q ... equal to... *QQ ... Q*Q? O Choose a random element of those remaining sets, implicit print ``` *Edit: saved a byte by taking an alternative approach. Previous version:* `Of&qQlT{IT./*` [Answer] # [Python 3](https://docs.python.org/3/), ~~136 134 127 121~~ 114 bytes ``` from random import* def f(n): s={randint(1,n*n)for _ in range(n)} return len(s)==n and sum(s)==n*n and s or f(n) ``` [Try it online!](https://tio.run/##RY1BCgMhDEXX4ymyGxUXle4GPEspjLaBGiU6i1J6dmtooavwyX/v12e/FzqPkbhk4Cvt82CuhbtVe0yQNJlNLS285InUtXdkyaTCcAEkYW5xlt5q4dgPJnhE0s2EQDAJaEf@JvvLMEmxDlHgX@GdP8lUZVlBt26rm0U0ZnwA "Python 3 – Try It Online") A commenter corrected me, and this now hits recursion max depth at f(5) instead of f(1). Much closer to being a real competing answer. I've seen it do f(5) *once*, and I'm working on trying to implement this with shuffle. I tried making some lambda expressions for `s=...`, but that didn't help on bytes. Maybe someone else can do something with this: `s=(lambda n:{randint(1,n*n)for _ in range(n)})(n)` Thanks to Kevin for shaving off another 7 bytes. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous prefix lambda. ``` {s=+/c←⍵?s←⍵*2:c⋄∇⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7rYVls/@VHbhEe9W@2LIbSWkVXyo@6WRx3tQE7t/zSwaN@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MUDLnSFIyA2BiITYDYFIgtAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; `⍵` is argument  `⍵*2` square the argument  `s←` assign to `s` (for **s**quare)  `⍵?` find `n` random indices from 1…`s` without replacement  `c←` assign to `c` (for **c**andidate)  `+/` sum them  `s=` compare to `s`  `:` if equal   `c` return the candidate  `⋄` else   `∇⍵` recurse on the argument [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 18 bytes ``` (≢?≢×≢)⍣(0=+.-∘≢)⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYb/04CkxqPORfZAfHg6kNB81LtYw8BWW0/3UccMCH/z//9pCoZcaQpGQGwMxCZAbArEFgA "APL (Dyalog Classic) – Try It Online") uses `⎕io←1` `⍳` generates the numbers `1 2 ... n` `(`...`)⍣(`...`)` keep applying the function on the left until the function on the right returns true `≢` length, i.e. `n` `≢?≢×≢` choose randomly `n` distinct integers between 1 and `n`2 `+.-∘≢` subtract the length from each number and sum `0=` if the sum is 0, stop looping, otherwise try again [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 13 bytes ``` `xGU:GZrtsGU- ``` [Try it online!](https://tio.run/##y00syfn/P6HCPdTKPaqopNg9VPf/f2MA "MATL – Try It Online") ``` ` # do..while: x # delete from stack. This implicitly reads input the first time # and removes it. It also deletes the previous invalid answer. GU: # paste input and push [1...n^2] GZr # select a single combination of n elements from [1..n^2] tsGU- # is the sum equal to N^2? if yes, terminate and print results, else goto top ``` [Answer] # Japt, 12 bytes ``` ²õ àU ö@²¥Xx ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=svUg4FUg9kCypVh4&input=NA==) ``` :Implicit input of integer U ² :U squared õ :Range [1,U²] àU :Combinations of length U ö@ :Return a random element that returns true when passed through the following function as X ² : U squared ¥ : Equals Xx : X reduced by addition ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 127 bytes ``` n->{for(int s;;){var r=new java.util.TreeSet();for(s=n*n;s>0;)r.add(s-(s-=Math.random()*n*n+1));if(r.size()==n&s==0)return r;}} ``` [Try it online!](https://tio.run/##ZU9Nb8IwDL3zK6xJTAkfEVwXwnESB07sNu2Q0ZSZtW4Vu0wM9bd3Bg1p0iRHz/F7L345xlOcH4vPAeu2yQJHvbtOsHJlR3vBhtzEj/6ROttXkRm2EQkuI4C2e69wDyxRFE4NFlArZ3aSkQ6vbxDzge1NCrAhef59frVLsoYyDDRfX8omGyQB9t5eTjFDDpS@/ux9ySmpwVh/lXKgCXleL7zNLhaF4blW2Eb5cDlS0dTGTlQyXVrrsTTZMX4nY0OgRw5hYXOSLhNk3/eDvyW7J0AIsPQKK8WFNtPpPTzA7sySatd04lr9nZTmYUNtJzDmJ6XHPKaHGc5KF9u2OhvU7TdnP7qefvgB "Java (JDK) – Try It Online") Infinite loop until a set with the criteria matches. I hope you have the time, because it's very sloooooow! It can't even go to 10 without timing out. [Answer] ## Batch, ~~182~~ 145 bytes ``` @set/an=%1,r=n*n,l=r+1 @for /l %%i in (%1,-1,1)do @set/at=n*(n-=1)/2,m=(r+t+n)/-~n,r-=l=m+%random%%%((l-=x=r+1-t)*(l^>^>31)+x-m)&call echo %%l%% ``` Explanation: Calculates the minimum and maximum allowable pick, given that the numbers are to be picked in descending order, and chooses a random value within the range. Example for an input of `4`: * We start with 16 left. We can't pick 11 or more because the remaining 3 picks must add to at least 6. We also need to pick at least 6, because if we only pick 5, the remaining 3 picks can only add to 9, which isn't enough for 16. We pick a random value from 6 to 10, say 6. * We have 10 left. We can't pick 8 or more because the remaining 2 picks must add to at least 3. As it happens, we can't pick 6 or more because we picked 6 last time. We also need to pick at least 5, because if we only pick 4, the remaining 2 picks can only add to 5, for a grand total of 15. We pick a random value from 5 to 5, say 5 (!). * We have 5 left. We can't pick 5 or more because the remaining pick must add to at least 1, and also because we picked 5 last time. We also need to pick at least 3, because if we only pick 2, the remaining pick can only be 1, for a grand total of 14. We pick a random value from 3 to 4, say 4. * We have 1 left. As it turns out, the algorithm chooses a range of 1 to 1, and we pick 1 as the final number. [Answer] ## JavaScript, ~~647~~ ~~291~~ ~~261~~ ~~260~~ ~~259~~ ~~251~~ 239 bytes *Thanks to @Veskah for -10 bytes at original version and "Oh yeah, you're outputting all the sets whereas the challenge asks for a random one to be returned"* ``` (n,g=m=n**2,r=[...Array(g||1)].map(_=>m--).sort(_=>.5-Math.random()).slice(-n),c=_=>eval(r.join`+`),i=_=>r.includes(_))=>[...{*0(){while(g>1&&c()!=g){for(z of r){y=c();r[m++%n]=y>g&&!(!(z-1)||i(z-1))?z-1:y<g&&!i(z+1)?z+1:z}}yield*r}}[0]()] ``` [Try it online!](https://tio.run/##HY1dboMwEISvEh6KdjFYEKkvSUzUA/QECCUWGMfB2JGhqfg7OzV9mdV8s5p58jfvK6deQ2JsLbaGbWBiyTpmougYO1ZQSr@c4yPIZcmwpB1/wY3lXZIg7a0bdkM/k28@PKjjprYdoE@0qgQkBuOK@Qfx5hocfVpl7uSOsdqho8pU@qcWPdwQWb5PzVEKOP8@lBYg8ywMK8CASZwb62A62ObgcB6Zp2dXdIR8mJKNuQzDAAKYkgyXRf1fvHo9jZc98oRkHpDsNK3rqISuI7euRVoCltve3LL03F6OXgjBypreakG1ldBAi7j9AQ) Create an array of `n^2` 1-based indexes, sort array randomly, slice `n` elements from array. While the sum of the random elements does not equal `n^2` loop array of random elements; if sum of array elements is greater than `n^2` and current element `-1` does not equal zero or current element `-1` is not in current array, subtract `1`; if sum of array is less than `n^2` and current element `+1` is not in array, add `1` to element. If array sum is equal to `n^2` break loop, output array. [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 bytes ``` ²õ ö¬oU íUõ+)Õæ@²¥Xx ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=svUg9qxvVSDtVfUrKdXmQLKlWHg=&input=MgotUQ==) Extremely heavily takes advantage of "Non-uniform" randomness, almost always outputs the first `n` odd numbers, which happens to sum to `n^2`. In theory it can output any other valid set, though I've only been able to confirm that for small `n`. Explanation: ``` ²õ :Generate the range [1...n^2] ö¬ :Order it randomly oU :Get the last n items í )Õ :Put it in an array with... Uõ+ : The first n odd numbers æ_ :Get the first one where... Xx : The sum ²¥ : equals n^2 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` ->n{z=0until(z=[*1..n*n].sample n).sum==n*n;z} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vusrWoDSvJDNHo8o2WstQTy9PKy9WrzgxtyAnVSFPU6@4NNfWFihmXVX731SvJDM3tbi6JrGmQCE6UdvWUCctOjE2tvY/AA "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~128~~ 125 bytes ``` p(_){printf("%d ",_);}f(n,x,y,i){x=n*n;y=1;for(i=0;++i<n;p(y),x-=y++)while(rand()&&(n-i)*(n-i+1)/2+(n-i)*(y+1)+y<x)y++;p(x);} ``` [Try it online!](https://tio.run/##LY3RCsIwDEXf9xVFUJK1w00f675EhpS6acDFUae2jH177YZ5CPcecnNtcbM2xgEuOA2OeOxgs72Kjbqgnjtg5VVQhJOvOWcd6kp3TwdUl1pKOrEeIKDyRR2kxO@dHi04w1fA3Q64IMyXLSvcH@Tfh@RkOHlMiZT2qSamWtEbYliEcTerhL0bJ/KkP@cGxZSJNK/19Uh9CyWizlbYgRmfBOtl1Sx4oa4d345FqbM5xuMP "C (gcc) – Try It Online") -3 bytes thanks to ceilingcat NOTE: The probability is very very far from uniform. See explanation for what I mean and a better means to test that it works (by making the distribution closer to uniform [but still a far cry from it]). ### How? The basic idea is to only choose increasing numbers so as to not worry about duplicates. Whenever we pick a number we have a non-zero chance of 'skipping' it if allowable. To decide if we can skip a number we need to know `x` the total left to be reached, `k` the number of elements we still have to use, and `y` the current candidate value. The smallest possible number that we could still pick would consist of $$y+(y+1)+(y+2)+...$$ added to the current value. In particular we require the above expression to be less than `x`. The formula will be $$\frac{k(k+1)}{2}+k(y+1)+y<x$$ Unfortunately we have to be a bit careful about rearranging this formula due to integer truncation in C, so I couldn't really find a way to golf it. Nonetheless the logic is to have a chance to discard any `y` that satisfies the above equation. ### The code ``` p(_){printf("%d ",_);} // Define print(int) f(n,x,y,i){ // Define f(n,...) as the function we want x=n*n; // Set x to n^2 y=1; // Set y to 1 for(i=0;++i<n;){ // n-1 times do... while(rand()&& // While rand() is non-zero [very very likely] AND (n-i)* // (n-i) is the 'k' in the formula (n-i+1)/2+ // This first half takes care of the increment (n-i)*(y+1) // This second half takes care of the y+1 starting point +y<x) // The +y takes care of the current value of y y++; // If rand() returned non-zero and we can skip y, do so p(y); // Print y x-=y++; // Subtract y from the total and increment it }p(x);} // Print what's left over. ``` The trick I mentioned to better test the code involves replacing `rand()&&` with `rand()%2&&` so that there is a 50-50 chance that any given y is skipped, rather than a 1 in `RAND_MAX` chance that any given y is used. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 172 bytes ``` import StdEnv,Math.Random,Data.List ? ::!Int->Int ?_=code{ ccall time "I:I" } $n=find(\s=length s==n&&sum s==n^2)(subsequences(nub(map(inc o\e=e rem n^2)(genRandInt(?0))))) ``` [Try it online!](https://tio.run/##JY5BSwMxFITv@RXPUkoKbRG9LaR7qYeFCmKvRXlN3m4DyUvdvAgi/nXjts5hmIGB@Wwg5BqTK4Egoufq4yWNAgdxT/y5ekY5b16RXYqrHQpu9j6LaqFp7jqW9XYy1b4bmxx9K2sxBBAfCWZd083Uj5qz6T07fcwmEA9yhmwMLxa5xFt6e1jqXE6ZPgqxpay5nHTEi/ZsIR3JEIwU4bYbiK8k06Vu75dX1YPgxGpgDo/11/YBh1zX3b7uvhijt//lJaD0aYx/ "Clean – Try It Online") [Answer] # [Python](https://docs.python.org/) (2 or 3), 84 bytes ``` from random import*;l=lambda n,s=[]:(sum(s)==n*n)*s or l(n,sample(range(1,n*n+1),n)) ``` **[Try it online!](https://tio.run/##NYuxDsIwDERn@ApvtdMsRWIJypdUDEFtIVLiRE4Y@PpgBqbT3btXP/1V@DLGISWDBN40Yq5Furkln0J@bAHYNr/eHbZ3xkbes2EyDYpAQmUh17Sjys8dF6twXsgy0Tj0ESEy/NmV3PlUJXLH1gUjwQyTg0nj15Muqn0B "Python 2 – Try It Online")** Hits max recursion depth at around l(5) [Answer] # [Kotlin](https://kotlinlang.org), 32 bytes ``` {(1..it*it).shuffled().take(it)} ``` [Try it online!](https://tio.run/##JYzBCoNADETvfkXwlBS66FWqPRf8iQV3aXAbi8ZexG9fo32nmXkw46SJJf98gtgAvkQJ7h30vOjDSgdt3rB2jvXGSm55rzGmMCA59WNA2/YcV4GPZ0GCrQDjfBNoAefgh54lmHk2UFYlXf7E6WT/@B@@M1uOKETFnuvqAA "Kotlin – Try It Online") [Answer] # Mathematica 40 bytes ``` RandomChoice[IntegerPartitions[n^2, {n}]] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes ``` (While[Tr[s=RandomSample[Range[#^2],#]]!=#^2];s)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@18jPCMzJzU6pCi62DYoMS8lPzc4MbcAKALkpKdGK8cZxeoox8Yq2oJY1sWaav9d8qMDijLzSqLTovNiY3Wq83QMdQwNamP/AwA "Wolfram Language (Mathematica) – Try It Online") Golfed version by @J42161217. --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes ``` Range[#-1,0,-1]+RandomChoice@IntegerPartitions[#*(#+1)/2,{#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8oMS89NVpZ11DHQEfXMFYbyE/Jz3XOyM9MTnXwzCtJTU8tCkgsKsksyczPK45W1tJQ1jbU1DfSqVaujVX775IfHVCUmVcSnRZtEhurU52nY6hjaFoby4UkkQeXMKiN/Q8A "Wolfram Language (Mathematica) – Try It Online") ### How it works Mainly based on [this Math.SE question](https://math.stackexchange.com/q/305988). In order to get partitions of \$n^2\$ into \$n\$ distinct parts, get partitions of \$n^2 - (n^2-n)/2 = (n^2+n)/2\$ instead and add \$0 \cdots n-1\$ to each element. Since Mathematica gives the partitions in decreasing order, \$n-1 \cdots 0\$ is added instead. --- # The answer to the Bonus Task > > **Bonus Task:** Is there a formula to calculate the number of valid permutations for a given `n`? > > > Yes. Define \$part(n,k)\$ as the number of partitions of \$n\$ into exactly \$k\$ parts. Then it satisfies the following recurrence relation: $$ part(n,k) = part(n-1,k-1) + part(n-k,k) $$ You can understand it as "If a partition contains a 1, remove it; otherwise, subtract 1 from every term". More explanation [here on another Math.SE question](https://math.stackexchange.com/q/1908701). Combined with the initial conditions \$ part(n,1) = 1 \$ and \$ n < k \Rightarrow part(n,k) = 0 \$, you can compute it with a program. The desired answer will be: $$ part(\frac{n^2+n}{2}, n) $$ which is, in Mathematica: ``` Length@IntegerPartitions[#*(#+1)/2,{#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98nNS@9JMPBM68kNT21KCCxqCSzJDM/rzhaWUtDWdtQU99Ip1q5Nlbtv0t@dEBRZl5JdFp0XmysTnWejqGOoUFt7H8A "Wolfram Language (Mathematica) – Try It Online") ]