text
stringlengths
180
608k
[Question] [ The esoteric programming language [evil](http://esolangs.org/wiki/Evil) has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric): * Bit 0 is moved to bit 2 * Bit 1 is moved to bit 0 * Bit 2 is moved to bit 4 * Bit 3 is moved to bit 1 * Bit 4 is moved to bit 6 * Bit 5 is moved to bit 3 * Bit 6 is moved to bit 7 * Bit 7 is moved to bit 5 For convenience, here are two other representations of the permutation. As a cycle: ``` (02467531) ``` And as a list of pairs of the mapping: ``` [[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]] ``` Your task is to visualise this permutation, using the box-drawing characters `โ”€`, `โ”‚`, `โ”Œ`, `โ”`, `โ””`, `โ”˜`, `โ”ผ` (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints: The first and last line are exactly: ``` 0 1 2 3 4 5 6 7 ``` Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via `โ”ผ` (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be: ``` 0 1 2 3 4 5 6 7 โ”‚ โ”‚ โ””โ”€โ”ผโ”โ”‚ โ”‚ โ””โ”โ”‚ โ””โ”€โ”ผโ”€โ” โ”‚โ”‚โ””โ”€โ”ผโ”€โ”โ”‚โ”‚ โ”Œโ”€โ”˜ โ”‚ โ”‚โ”‚ โ”‚ โ”‚โ”‚โ”‚ โ”‚ โ”Œโ”€โ”ผโ”€โ”˜โ”‚ โ”‚ โ”‚โ”‚โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”€โ”€โ”˜ โ”‚โ”‚โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”Œโ”€โ”ผโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” 0 1 2 3 4 5 6 7 ``` However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer. You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, so the shortest code (in bytes) wins. [Answer] ## PowerShell v2+, ~~172~~ ~~153~~ ~~148~~ ~~145~~ ~~142~~ ~~131~~ 123 bytes (81 chars) ``` ($a=""+0..7) $b='โ”Œโ”˜' "โ”‚$b$('โ”Œโ”ผโ”€โ”˜'*3) โ””โ”ผโ”$('โ”‚โ””โ”€โ”'*3) $b$('โ””โ”ผโ”€โ”'*3)โ”‚ โ”‚ $($b*6)โ”‚" $a ``` I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal. We start by setting `$a` equal to the range `0..7` that's been joined together with spaces. This is because the default `$ofs` (Output Field Separator) for an array is a space, so when the array is stringified with `""+` (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated. That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable `$b`, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by `$a` again. The four lines and `$a` are also placed on the pipeline, and output is implicit at the end. ``` PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1 0 1 2 3 4 5 6 7 โ”‚โ”Œโ”˜โ”Œโ”ผโ”€โ”˜โ”Œโ”ผโ”€โ”˜โ”Œโ”ผโ”€โ”˜ โ””โ”ผโ”โ”‚โ””โ”€โ”โ”‚โ””โ”€โ”โ”‚โ””โ”€โ” โ”Œโ”˜โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ”‚ โ”‚ โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”‚ 0 1 2 3 4 5 6 7 ``` [Answer] ## Actually, 69 bytes ``` "โ”‚ โ”Œโ”˜โ”‚ โ”‚โ””โ” โ”‚โ””โ”โ””โ”""โ”Œโ”˜โ””โ”ผโ”โ””โ”ผโ” โ””โ”ผโ”โ””โ”""โ””โ”ผโ”โ”‚โ””โ”โ”Œโ”˜โ””โ”โ”Œโ”˜โ”‚""โ”Œโ”ผโ”€โ”˜"3*"โ”‚โ”Œโ”˜"+8r' j;) ``` [Try it online!](http://actually.tryitonline.net/#code=IuKUgiDilIzilJjilIIg4pSC4pSU4pSQIOKUguKUlOKUkOKUlOKUkCIi4pSM4pSY4pSU4pS84pSQ4pSU4pS84pSQIOKUlOKUvOKUkOKUlOKUkCIi4pSU4pS84pSQ4pSC4pSU4pSQ4pSM4pSY4pSU4pSQ4pSM4pSY4pSCIiLilIzilLzilIDilJgiMyoi4pSC4pSM4pSYIis4cicgajsp&input=) (the alignment is a little messed up in the online interpreter) Actually has a **HUGE** advantage here - all of the box drawing characters are in CP437, so they're only a byte each. Though each character needed could theoretically be encoded in 4 bits (since there are only 9 unique characters), the 31 bytes saved by compressing the string would be lost due to Actually's very poor string processing capabilities. This also means that any 8x4 configuration would result in the same score. Since 8x4 appears to be the (vertically) shortest possible configuration, this is optimal. Thanks to Martin for 3 bytes! Thanks to TimmyD for 4 more bytes! Explanation: ``` "โ”‚ โ”Œโ”˜โ”‚ โ”‚โ””โ” โ”‚โ””โ”โ””โ”""โ”Œโ”˜โ””โ”ผโ”โ””โ”ผโ” โ””โ”ผโ”โ””โ”""โ””โ”ผโ”โ”‚โ””โ”โ”Œโ”˜โ””โ”โ”Œโ”˜โ”‚""โ”Œโ”ผโ”€โ”˜"3*"โ”‚โ”Œโ”˜"+8r' j;) "โ”‚ โ”Œโ”˜โ”‚ โ”‚โ””โ” โ”‚โ””โ”โ””โ”""โ”Œโ”˜โ””โ”ผโ”โ””โ”ผโ” โ””โ”ผโ”โ””โ”""โ””โ”ผโ”โ”‚โ””โ”โ”Œโ”˜โ””โ”โ”Œโ”˜โ”‚""โ”Œโ”ผโ”€โ”˜"3*"โ”‚โ”Œโ”˜"+ push the individual lines, using string multiplication to shorten repeated sections 8r' j push the string "0 1 2 3 4 5 6 7" (range(8), join on spaces) ;) make a copy and move it to the bottom of the stack ``` [Answer] # Javascript ES6, ~~168~~ 167 bytes Edit: Whoops, turned out I was using the pipe `|` char instead of U+2502 `โ”‚` in part of the function, updated byte count. ``` _=>((n=`0 1 2 3 4 5 6 7 `)+[...`6452301`].map(i=>`${(d=n=>`โ”‚ `.repeat(n))(i)}โ””โ”โ”‚ ${r=d(6)}โ”Œโ”ผโ”˜ ${r}โ”‚โ””โ” ${d(6-i)}`).join``+n).match(/.{16}/g).join` ` ``` Returns a string. Output: ``` 0 1 2 3 4 5 6 7 โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ””โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ 0 1 2 3 4 5 6 7 ``` --- Extra: Using @TimmyD's method, I have another 167 byte solution: ``` (n=`0 1 2 3 4 5 6 7 `,a=`โ”‚โ”Œโ”˜ `,b=`โ””โ”ผโ”€โ”`,d=`โ”Œโ”ผโ”€โ”˜`,f=` โ”‚โ””โ”`)=>[n,a,a,a,a,` `,b,b,b,`โ””โ”ผโ” โ”Œโ”˜`,d,d,d,`โ”‚ โ”‚`,f,f,f,` โ”‚ `,n].join`` ``` [Answer] ## JavaScript (ES6), ~~137~~ 134 bytes ``` f= _=>`0 โ”‚2525252 1 1 1 1 24242423525252 3 1 1 1 3 242424โ”‚ 0`.replace(/\d/g,d=>`0 1 2 3 4 5 6 7,โ””โ”ผโ”,โ”Œโ”˜,โ”‚ โ”‚,โ”‚ , โ”‚`.split`,`[d]) ; o.textContent=f(); ``` ``` <pre id=o></pre> ``` As a bell-ringer I immediately recognised this as the first two rows of [Plain Hunt Major](http://www.ringbell.co.uk/methods/img/ph8.gif) (note that the linked image uses 1-8 instead of 0-7). [Answer] # Pyth - ~~119~~ ~~104~~ ~~100~~ 81 bytes Extremely simple. (Its actually bytes this time). ``` js[KjdU8cX."szยจรบยจรฃร†hร†?\ร•รผร“ยผxFNรธa"_G"โ”‚โ”Œโ”˜โ””โ”ผโ”€โ” "15K ``` [Try it online here](http://pyth.herokuapp.com/?code=js%5BKjdU8cX.%22sz%0F%C2%A8%C3%BA%C2%8F%C2%A8%C3%A3%C3%86%C2%8Ch%C3%86%C2%8C%3F%5C%C3%95%10%C3%BC%C3%93%C2%BCxFN%C3%B8a%22_G%22%E2%94%82%E2%94%8C%E2%94%98%E2%94%94%E2%94%BC%E2%94%80%E2%94%90+%2215K&debug=0). I also stole @TimmyD's output: ``` 0 1 2 3 4 5 6 7 โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚ โ”‚ โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”โ”‚ โ”Œโ”˜โ”Œโ”ผโ”€โ”˜ โ””โ”โ”‚โ”Œโ”ผโ”€โ”ผโ”˜ โ”‚ โ”‚โ””โ” โ”Œโ”€โ”ผโ”˜โ”‚โ””โ”โ””โ” 0 1 2 3 4 5 6 7 ``` [Answer] ## MS-DOS Batch, 136 bytes ``` @echo 0 1 2 3 4 5 6 7 @echo ยณรšร™ ยณรšร™ ยณรšร™ ยณรšร™ @echo ร€ร…ร„ยฟร€ร…ร„ยฟร€ร…ร„ยฟร€ร…ยฟ @echo รšร™รšร…ร„ร™รšร…ร„ร™รšร…ร„ร™ยณ @echo ยณ ยณร€ยฟ ยณร€ยฟ ยณร€ยฟ ยณ @echo 0 1 2 3 4 5 6 7 ``` Using @TimmyD's output. This might work in Windows Batch too, but my code page there is CP850, not CP437. [Answer] ## MATLAB / Octave, ~~112~~ 109 bytes ``` a='0 1 2 3 4 5 6 7';d=['โ””โ”โ”‚ ';'โ”Œโ”ผโ”˜ ';'โ”‚โ””โ” '];e=repmat('โ”‚โ€ˆ',3,1);[a;d d d d;e d d d e;a] ``` Output: ``` 0 1 2 3 4 5 6 7 โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ 0 1 2 3 4 5 6 7 ``` My code is based on the ouputs of [@Dendrobium](https://codegolf.stackexchange.com/questions/83899/visualise-bit-weaving/83910#83910) and [@Neil](https://codegolf.stackexchange.com/questions/83899/visualise-bit-weaving/83922#83922). [Answer] # [///](https://esolangs.org/wiki////), 112 bytes (100 chars) ``` /8/0 1 2 3 4 5 6 7//9/โ”‚//A/โ””โ”//B/โ”Œโ”ผโ”˜/8/C/9 A9 A9 A9//D/9A 9A 9A 9/ AC B B B B DA C 9 9 B B B 9 9 D 8 ``` *Thanks @MartinEnder for -3 bytes!* *Thanks @MartinEnder for -9 bytes!* *Thanks @MartinEnder (OP) for pointing 15-char rule out* Uses ~~@TimmyD's~~ @Marco's output ``` 0 1 2 3 4 5 6 7 โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ 0 1 2 3 4 5 6 7 ``` [Answer] **Python3, 209 bytes** ``` lambda s="0 1 2 3 4 5 6 7\n":s+"โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚ โ”‚\nโ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”โ”‚\nโ”Œโ”˜โ”Œโ”ผโ”€โ”˜ โ””โ”โ”‚โ”Œโ”ผโ”€โ”ผโ”˜\nโ”‚ โ”‚โ””โ” โ”Œโ”€โ”ผโ”˜โ”‚โ””โ”โ””โ”\n"+s ``` Returns a string. Thanks to @Mego for saving 2 bytes! Credits of the character body go to @TimmyD ! [Answer] # [Sprects](https://dinod123.neocities.org/interpreter.html), 99 bytes (87 chars) ``` $8 AC BE DA C 9 9E 9 9 D 8$E B B B$D9A 9A 9A 9$C9 A9 A9 A9$Bโ”Œโ”ผโ”˜$Aโ””โ”$9โ”‚$80 1 2 3 4 5 6 7 ``` Uses @Marco's output (replace every 16th character with a newline (regex: `(.{15}).` -> `\1\n`)). ``` 0 1 2 3 4 5 6 7 โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ 0 1 2 3 4 5 6 7 ``` [Answer] ## Bash + GNU sed, 140 bytes ``` sed 'h s/$/nxxxacnb b b bnyyycanc xxxcnc b b b cnc yyyc/ : s/x/ac / s/y/ca / s/a/โ””โ”/ s/b/โ”Œโ”ผโ”˜/ t y/cn/โ”‚\n/ G'<<<'0 1 2 3 4 5 6 7' ``` Output: ``` 0 1 2 3 4 5 6 7 โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ””โ”โ”‚ โ”‚ โ”‚ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”Œโ”ผโ”˜ โ”‚ โ”‚ โ”‚โ””โ” โ”‚โ””โ” โ”‚โ””โ” โ”‚ 0 1 2 3 4 5 6 7 ``` Using [@TimmyD's](https://codegolf.stackexchange.com/questions/83899/visualise-bit-weaving/83906#83906) output: 142 bytes ``` sed 'h s/$/npbcccnsurdddnbeeepnp bbbbbbp/ : s/b/qt/ s/c/quot/ s/d/psor/ s/e/suor/ t y/nopqrstu/\nโ”€โ”‚โ”Œโ”โ””โ”˜โ”ผ/ G'<<<'0 1 2 3 4 5 6 7' ``` Output: ``` 0 1 2 3 4 5 6 7 โ”‚โ”Œโ”˜โ”Œโ”ผโ”€โ”˜โ”Œโ”ผโ”€โ”˜โ”Œโ”ผโ”€โ”˜ โ””โ”ผโ”โ”‚โ””โ”€โ”โ”‚โ””โ”€โ”โ”‚โ””โ”€โ” โ”Œโ”˜โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”โ”‚ โ”‚ โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โ”‚ 0 1 2 3 4 5 6 7 ``` [Answer] # [Tcl](http://tcl.tk/), 205 bytes ``` puts "[set B "0 1 2 3 4 5 6 7"] โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ””โ”โ”‚ โ””โ”ผโ” โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”€โ”โ”‚โ”‚ โ”Œโ”˜โ””โ”€โ”โ”‚ โ””โ”โ”‚โ”Œโ”€โ”ผโ”ผโ”˜ โ”‚ โ”Œโ”€โ”ผโ”˜โ”Œโ”€โ”ผโ”˜โ”‚ โ”‚โ””โ” $B" ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWEEpuji1RMFJQclAwVDBSMFYwUTBVMFMwVwpluvRlKZHU3oeTZmhgJ015dGUCUA@F5i1B8hRgLEawDJwNoTbBFEL0gyWg4oiDALLNYA1AdEMLogkXGwGKrsJ4haQXi4VJ6X//wE "Tcl โ€“ Try It Online") outputs ``` 0 1 2 3 4 5 6 7 โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ”‚โ”Œโ”˜ โ””โ”โ”‚ โ””โ”ผโ” โ””โ”ผโ”€โ”โ””โ”ผโ”€โ”€โ”โ”‚โ”‚ โ”Œโ”˜โ””โ”€โ”โ”‚ โ””โ”โ”‚โ”Œโ”€โ”ผโ”ผโ”˜ โ”‚ โ”Œโ”€โ”ผโ”˜โ”Œโ”€โ”ผโ”˜โ”‚ โ”‚โ””โ” 0 1 2 3 4 5 6 7 ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 64 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` โ””โ”ผโ”€โ”ยณ โ”˜โ”Œโ”ผโ”€โ”˜ยฒ โ”โ”‚โ””โ”€โ”ยน โ”Œโ”˜โ”Œโ”˜โ”Œโ”˜โฐ โ”‚โ”Œยฒโ”Œโ”ผโ”€ยฒยถโ””โ”ผยนโ”‚โ””โ”€ยนยถโ”Œโ”˜ยณยณยณโ”‚ยถโ”‚ โฐโฐโ”‚โ€8ฮด@โˆ‘Q;O ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTE0JXUyNTNDJXUyNTAwJXUyNTEwJUIzJTBBJXUyNTE4JXUyNTBDJXUyNTNDJXUyNTAwJXUyNTE4JUIyJTBBJXUyNTEwJXUyNTAyJXUyNTE0JXUyNTAwJXUyNTEwJUI5JTBBJXUyNTBDJXUyNTE4JXUyNTBDJXUyNTE4JXUyNTBDJXUyNTE4JXUyMDcwJTBBJXUyNTAyJXUyNTBDJUIyJXUyNTBDJXUyNTNDJXUyNTAwJUIyJUI2JXUyNTE0JXUyNTNDJUI5JXUyNTAyJXUyNTE0JXUyNTAwJUI5JUI2JXUyNTBDJXUyNTE4JUIzJUIzJUIzJXUyNTAyJUI2JXUyNTAyJTIwJXUyMDcwJXUyMDcwJXUyNTAyJXUyMDFEOCV1MDNCNEAldTIyMTFRJTNCTw__) Pattern stolen from [the powershell](https://codegolf.stackexchange.com/a/83906/59183) ]
[Question] [ ...at least for some definition of "self-modification". # The Task In this challenge, your task is to write three strings `A`, `B` and `C` that satisfy the following properties. * The string `B` has length at least 1. * For every `n โ‰ฅ 0`, the string `ABnC` is a valid program (meaning full runnable program or function definition) in your programming language of choice. The superscript denotes repetition, so this means the strings `AC`, `ABC`, `ABBC`, `ABBBC` etc. Each program takes one string as input, and returns one string as output. * For any `m, n โ‰ฅ 0`, if the program `ABmC` is run with input `ABnC`, it returns `ABm\*n+1C`. For inputs not of this form, the program may do anything, including crash. Some examples in the format `program(input) -> output`: ``` AC(AC) -> ABC ABC(AC) -> ABC ABBBBBC(AC) -> ABC AC(ABC) -> ABC AC(ABBBBC) -> ABC ABC(ABC) -> ABBC ABBC(ABC) -> ABBBC ABBBBC(ABBBC) -> ABBBBBBBBBBBBBC ABBBC(ABBBBBBC) -> ABBBBBBBBBBBBBBBBBBBC ``` # Rules and Scoring Your score is the **total length of `A` and `C`**, lower score being better. Note that while `B` is not counted toward the score, it must be produced by `A` and `C` as in the first example. Standard loopholes are disallowed. The programs are not allowed to directly or indirectly access their own source code (except when they are given it as input). You are required to identify the strings `A`, `B` and `C` in your answer in some way, and encouraged to explain your solution. [Answer] # CJam, ~~9~~ 8 bytes ``` A: 1 B: 0 C: r,(#0q ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=1%20r%2C(%230q&input=1%20r%2C(%230q). ### How it works ``` (ABcode) e# Push the integer 10 ** len(Bcode). <SP> e# Noop. Separates (AB) and C for input reading. r e# Read the first whitespace-separated token from STDIN (ABinput). ,( e# Push the string length minus 1: len(Binput) # e# Power operator: 10 ** len(Bcode) len(Binput) # -> e# (10 ** len(Bcode)) ** len(Binput) = 10 ** (len(Bcode) * len(Binput)) 0 e# Push an additional 0 to complete len(Bcode) * len(Binput) + 1 zeroes. q e# Read the remaining input (C). ``` [Answer] # CJam, ~~15~~ ~~13~~ 11 bytes ``` A: rl" B: <SP> C: <LF>",(*SNq ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=rl%22%0A%22%2C(*SNq&input=rl%22%0A%22%2C(*SNq). ### How it works ``` e# A r e# Read a whitespace-separated token from STDIN. e# This reads the input up to the first space, but does not consume it. l e# Read the rest of the first line from STDIN. e# This reads up to the first linefeed and consumes it. " e# Initiate a string. e# B <SP> e# Fill the string with as many spaces as there are copies of B. e# C <LF>" e# Terminate the string with a linefeed. e# This serves as a delimiter for the `l' command. ,( e# Compute the length of the string minus 1 (to account for the LF). * e# Repeat the string read by `l' that many times. SN e# Push a space and a linefeed. q e# Read the remaining input (i.e., the second line) from STDIN. ``` At the end, the stack contains the token read by `r`, the space produced by `*`, the space and linefeed pushed by `SN` and the line read by `q`. CJam prints all these automatically. [Answer] # Pyth, 10 ``` A: w*\0hl*w[<newline> B: 0 C: <empty> ``` We split the source in two lines. The first line is A, the second line are the Bs. Since A is on the first line, the first `w` just prints A - easy, done. In Pyth leading zeroes are seperate tokens, so `[00)` actually is `[0, 0]`. Note that the first line ends in `l[`, and the second line consists of `0000...`. So `l[` actually counts the number of Bs in this program. The second `w` reads in the second line of the input - this is the number of Bs of the input. From here it's a simple multiply, increment and outputting that many zeroes. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~25~~ 19 bytes ``` A: ]\]<LF> B: ]] C: <LF>m`^]*$<LF>]$0] <LF> stands for newline ``` Example `ABC` code: ``` ]\] ]] m`^]*$ ]$0] ``` The code has two substitute steps: * change the input `AB^mC` into `AB^(m*n)C` by changing every `B` to `B^n`: + `]\]` matches every `B` in the input and nothing else thanks to escaping in the pattern lines + `]]...]]` is `B^n` * change `B^(m*n)` to `B^(m*n+1)` by + `m`^]*$` taking the line with only `]`'s + `]$0]` adding an extra pair of `]]` to it in a way that this line doesn't match the first regex I've added 3 bytes to the score for the `-s` multi-line flag which is needed so the whole Retina code could be in one file. 2 bytes saved thanks to @MartinBรผttner. [Answer] # Python 3, 51 bytes ``` A: lambda s:s[:28]+"x"*(1+len(" B: x C: ")*(len(s)-51))+s[-23:] ``` Example usage: ``` >>> f=lambda s:s[:28]+"x"*(1+len("xx")*(len(s)-51))+s[-23:] >>> f('lambda s:s[:28]+"x"*(1+len("xxx")*(len(s)-51))+s[-23:]') 'lambda s:s[:28]+"x"*(1+len("xxxxxxx")*(len(s)-51))+s[-23:]' ``` The function computes `n*m+1` with `(1+len("xxx")*(len(s)-51))` where there are `m` `x`'s in the string (`xxx` part is the `B^m`). Multiplying the string `"x"` with this number gives `B^(n*m+1)` and the function takes `A` and `C` out of the input and concatenates all of these to get `AB^(n*m+1)C`. The same approach in J: # J, 35 bytes ``` A: (19{.]),('x'#~1+(#' B: x C: ')*35-~#),_16{.] ``` [Answer] # CJam, 22 ``` A:<empty> B:{])`\,q,K/(*))*"_~"} C:{])`\,q,K/(*))*"_~"}_~ ``` Example run: ``` ABBC(ABC) -> ABBBC ``` which translates to ``` {])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}_~ ``` with input as ``` {])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}_~ ``` which gives the following output: ``` {])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}_~ ``` **How it works**: Lets take a look at what programs `AC` and `ABC` look like: ``` AC :{])`\,q,K/(*))*"_~"}_~ ABC:{])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}_~ ``` We notice that `C` = `B_~` Lets look at what `B` is doing: ``` {])`\,q,K/(*))*"_~"} { } e# This is a code block. Alone, this does nothing except e# pushing this block to stack as is ] e# Wrap everything on stack in an array )` e# Take out the last part and convert it to its string representation \, e# Take length of remaining array q,K/ e# Read the input, take its length and int divide by K (i.e. 20) (* e# Decrement and multiply by the array length on stack )) e# Add two to the product * e# Repeat the string representation on stack that many times "_~" e# Put this string on stack ``` Now lets see what running `AC` without any input will do: ``` {])`\,q,K/(*))*"_~"}_~ e# Copy the block and run it {])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}~ e# Block is copied, run it { ... } ]) e# Wrapped array has the block in it. `\, e# Stringify it and take length of remaining = 0 q,K/ e# No input so 0 (*)) e# 0 * -1 = 0. 0 + 2 = 2 * e# Repeat the stringified block 2 times: e# "{])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}" "_~" e# Put this string. Program ends, so print stack: e# {])`\,q,K/(*))*"_~"}{])`\,q,K/(*))*"_~"}_~ ``` Wow, the output is `ABC`. We basically count how many `B` exist in the code. Then how many are in the input (using length). Multiply them, increment twice (since `C` also has `B`) and append `_~` to get `C` [Try it online here](http://cjam.aditsu.net/#code=%7B%5D)%60%5C%2Cq%2CK%2F(*))*%22_~%22%7D%7B%5D)%60%5C%2Cq%2CK%2F(*))*%22_~%22%7D%7B%5D)%60%5C%2Cq%2CK%2F(*))*%22_~%22%7D_~&input=%7B%5D)%60%5C%2Cq%2CK%2F(*))*%22_~%22%7D%7B%5D)%60%5C%2Cq%2CK%2F(*))*%22_~%22%7D_~) [Answer] # [Haskell](https://www.haskell.org/), 50 bytes `f` is a function taking and returning a `String`. The string B is just a single space, while C starts with one. ``` A:_:b=" B: C: ";f s|a:c<-words s=unwords$a:(drop 50s>>b):c ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P94qyVZJQck6TaG4JtEq2Ua3PL8opVih2LY0D8xSSbTSSCnKL1AwNSi2s0vStEr@n5uYmWebmVeSWpSYXKKQRoYRAA "Haskell โ€“ Try It Online") * `_:b=" "` assigns all but the first of the spaces in the string literal to `b`, making that equal to the program's *m* B copies. * `s` is the input string. `a:c<-words s` splits it into space-separated words, so that `a` becomes A and `c` becomes a list of the words comprising C. The B copies are ignored since `words` squeezes multiple spaces (which the rest of the program avoids). * `drop 50s` is a string with length equal to the number *n* of B copies in the input. `drop 50s>>b` concatenates that many copies of `b`, giving *mn* spaces. * `unwords$a:(drop 50s>>b):c` joins all the strings back together with spaces. Since there is an extra "word" `(drop 50s>>b)` inserted in the list, there is also an extra joining space, automatically adding the +1 to the multiplication. [Answer] # Matlab, 85 First time for me to do such an abstract challenge, so for me it was more of a coding challenge than a code-golf challenge! The three strings are, without the quotation marks: ``` A: "X=strsplit(input('','s'));m=0 " B: "+1 " C: ";[X{1},32,repmat(['+1',32],1,m*(length(X)-2)+1),X{end}]" ``` **How it works:** I split the input argument on whitespace, so `n` can be determined from the number of string parts. B works as a sort of counter to get `m`. For reconstructing the answer I use A and C from the split, repeat B m\*n+1 times and I insert the spaces by using their ASCII value, so that no unwanted splits occur in C. EDIT: whoops, accidentally counted A+B [Answer] # [C (gcc)](https://gcc.gnu.org/), 81 bytes The requirement to identify the strings seems at odds with our being allowed arbitrary behaviour for illegal input, unless we have rather lax standards of what identifying entails. Naturally, I took the interpretation that sheds the most bytes. [Try it online!](https://tio.run/##lc3LCsIwEIXhtXmKEihkchFUnE3wTbIpwdqCCTLTXemzx1kJdtez/g9fDq@cWytxNHkayDKs5cELUZ7IsEP0tysEDniPH5rrMhrdnxG5t6w9@2KlfT@r0Z1Mg7ugZ1fkB3Fr0ndlmKsBtaqTXA8w6eekPyiJlHaQhqi29gU "C (gcc) โ€“ Try It Online") ``` A: m;f(char*s){m=strrchr(s+66,32)-s-65;printf("%.66s%*s",s,m*strlen(" B: <SPACE> C: ")+16,s+m+66);} ``` [Answer] # TI-Basic (83 series), 65 bytes Segment A (33 bytes): ``` Input Str1:sub(Str1,1,27:For(I,0,(length(Str1)-55)(length(" ``` Segment B: ``` X ``` Segment C (32 bytes): ``` Y")-1:Ans+"X":End:Ans+sub(Str1,length(Str1)-27,28 ``` --- I am really excited about finding this quine-like challenge! Most quines don't work in TI-Basic without at least a little cheating, because there is no way to escape the `"` symbol. (In both senses of the word "escape".) But here, we get an input string via the `Input` command, and typing in a `"` there is perfectly fine. There is still some amount of TI-Basic silliness to work around here: an empty string is invalid, so the naive solution of inserting the string `"XXX...XX"` in a loop won't work when n=0. Instead, we manually compute the value of mn+1, and insert the string `"X"` that many times. The magic constants `27` and `28` in the program are slightly off from the byte counts 33 and 32, because `Str1`, `sub(`, and `length(` are two-byte tokens that only contribute 1 to the length of a string. If we use newlines instead of `:`, it looks like when can save a few bytes by leaving off ending quotes, but this doesn't actually work. First of all, you need a hex editor before you can add the newline character into a string: you can't just type it in, because if you press ENTER during an `Input` command, it submits the input. When I tried the hex editor approach, I ended up getting a weird buffer overflow error that modified the contents of my program, so don't try this at home with your expensive calculator. [Answer] # Java 11, ~~135~~ 65+26=91 bytes **A** ``` s->{var p=s.split("\\(\"|\"\\.");return p[0]+"(\"B"+p[1].repeat(" ``` **B** ``` B ``` **C** ``` ".length())+'"'+'.'+p[2];} ``` Try it online [here](https://tio.run/##zZNBb8IgFMfv@xQvXFpSS9yujSZj5512LD1gRYdDJEBNjPOzd2CYte6wm/EdIMCf936P/NnwPS83y6/edAslW2gVdw7eudRwfIIQUnthV7wV8Erf0l6MD2@lXsO2U14adcjTWmrTeVydZafzmBI7z32Y9ju5hG1Iny7UDXC7dvgqc6zDFy3MoHfl/LjnFszMEWeU9DmaMPTNEGME4coK31kNpp42RTygqLDCCO5zUz83E0QpRUQJvfafOcZFhrIiI1lh6pemOvW/9aqhp4PzYkt2nScmwHml8wBCLj2ivzws1GURiUWogMVuuJKAsjFbUI/Q2IgN4fCEd6WhD4bzcDz/A8Hg@RvTp7@RUqaVm8S/Bfra@hdlMD9CgzFhtbN5pctyPq3wsBvDQjEDdyVN/dgL0Kn/AQ) (TIO does not have Java 11 yet, so this relies on a helper method instead of `String::repeat()`). Ungolfed: ``` s -> { // lambda taking and returning a String var p = s.split("\\(\"|\"\\."); // split input into parts A, B^n, C (where n may be 0) at the "(\"" and "\"." return p[0] + "(\"B" + // put it back together: A plus the part the split shaved off, plus an extra B ... p[1].repeat("BBB".length()) + // ... plus B^(n*m) '"' + '.' + p[2]; // plus C, with the part the split shaved off reattached } ``` ]
[Question] [ Say you list the positive integers in a triangle, then flip it left-to-right. Given a number, output the number it's sent to. This is a self-inverse mapping. ``` 1 1 2 3 3 2 4 5 6 <---> 6 5 4 7 8 9 10 10 9 8 7 11 12 13 14 15 15 14 13 12 11 ``` This is the n'th element of [A038722](https://oeis.org/A038722), one-indexed: ``` 1, 3, 2, 6, 5, 4, 10, 9, 8, 7, 15, 14, 13, 12, 11, ... ``` This sequence reverses contiguous chunks of the positive integers with increasing lengths: ``` 1, 3, 2, 6, 5, 4, 10, 9, 8, 7, 15, 14, 13, 12, 11, ... <-><----><-------><-----------><------------------> ``` Test cases: ``` 1 -> 1 2 -> 3 3 -> 2 4 -> 6 14 -> 12 990 -> 947 991 -> 1035 1000 -> 1026 1035 -> 991 1036 -> 1081 12345 -> 12305 ``` --- **Leaderboard:** ``` var QUESTION_ID=117879,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/117879/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## JavaScript (ES7), 26 bytes ``` n=>((2*n)**.5+.5|0)**2-n+1 ``` An implementation of the following formula [from OEIS](https://oeis.org/A038722): [![formula](https://i.stack.imgur.com/FIbAc.png)](https://i.stack.imgur.com/FIbAc.png) ### Demo ``` let f = n=>((2*n)**.5+.5|0)**2-n+1 for(n = 1; n <= 50; n++) { console.log(n, '->', f(n)) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` RแนRโ‚ฌUFi ``` *Thanks to @ErikTheOutgolfer for saving 1 byte!* [Try it online!](https://tio.run/nexus/jelly#@x/0cGdj0KOmNaFumf@P7jncDmS6//9vqKNgpKNgrKNgoqNgCMSWlgYgAihsaGBgACKNTcGkGQA "Jelly โ€“ TIO Nexus") ### How it works ``` RแนRโ‚ฌUFi Main link. Argument: n R Range; yield [1, ..., n]. Rโ‚ฌ Range each; yield [[1], [1, 2], [1, 2, 3], ..., [1, ..., n]]. แน Mold the left argument like the right one, yielding [[1], [2, 3], [4, 5, 6], ...]. The elements of the left argument are repeated cyclically to fill all n(n+1)/2 positions in the right argument. U Upend; reverse each flat array, yielding [[1], [3, 2], [6, 5, 4], ...]. F Flatten, yielding [1, 3, 2, 6, 5, 4, ...]. i Index; find the first index of n in the result. ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 27 bytes *Thanks to Sp3000 for the `.C` idea.* ``` /o \i@/.2:e2,tE*Y~Z.H2*~.C+ ``` [Try it online!](https://tio.run/nexus/alice#@6@fzxWT6aCvZ2SVaqRT4qoVWRel52GkVafnrP3/v6GRsYkpAA "Alice โ€“ TIO Nexus") ### Explanation I think there may be a shorter way to compute this using triangular numbers, but I thought this is an interesting abuse of a built-in, so here's a different solution. The basic idea is to make use of Alice's "pack" and "unpack" built-ins. "Pack", or `Z`, takes two integers maps them bijectively to a single integer. "Unpack", or `Y`, inverts this bijection and turns one integer into two. Normally, this can be used to store a list or tree of integers in a single (large) integer and recover the individual values later. However, in this case we can use the functions in the opposite order, to let the nature of the bijection work for us. Unpacking one integer into two integers basically consists of three steps: 1. Map **โ„ค โ†’ โ„•** (including zero) with a simple "folding". That is, map negative integers to odd naturals, and non-negative integers to even naturals. 2. Map **โ„• โ†’ โ„•2**, using the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function). That is, the naturals are written along the diagonals of an infinite grid and we return the indices: ``` ... 3 9 ... 2 5 8 ... 1 2 4 7 ... 0 0 1 3 6 ... 0 1 2 3 ``` E.g. `8` would be mapped to the pair `(1, 2)`. 3. Map **โ„•2 โ†’ โ„ค2**, using the inverse of step 1 on each integer individually. That is, odd naturals get mapped to negative integers, and even naturals get mapped to non-negative integers. To pack two integers into one, we simply invert each of those steps. Now, we can see that the structure of the Cantor pairing function conveniently encodes the triangle we need (although the values are off-by-one). To reverse those diagonals, all we need to do is swap the **x** and **y** coordinates into the grid. Unfortunately, since all three of the above steps are combined into a single built-in `Y` (or `Z`), we need to undo the **โ„ค โ†’ โ„•** or **โ„• โ†’ โ„ค** mappings ourselves. However, while doing so we can save a couple of bytes by directly using **โ„•+ โ†’ โ„ค** or **โ„ค โ†’ โ„•+** mappings, to take care of the off-by-one error in the table. So here is the entire algorithm: 1. Map **โ„•+ โ†’ โ„ค** using **(n/2) \* (-1)n-1**. This mapping is chosen such that it cancels the implicit **โ„ค โ†’ โ„•** mapping during unpacking, except that it shifts the value down by 1. 2. Unpack the result into two integers. 3. Swap them. 4. Pack the swapped values into a single integer again. 5. Map **โ„ค โ†’ โ„•+** using **|2n| + (nโ‰ฅ0)**. Again, this mapping is chosen such that it cancels the implicit **โ„• โ†’ โ„ค** mapping during packing, except that it shifts the value up by 1. With that out of the way, we can look at the program: ``` /o \i@/... ``` This is simply a framework for linear arithmetic programs with integer input and output. ``` . Duplicate the input. 2: Halve it. e Push -1. 2, Pull up the other copy of the input. t Decrement. E Raise -1 to this power. * Multiply. We've now computed (n/2) * (-1)^(n-1). Y Unpack. ~ Swap. Z Pack. .H Duplicate the result and take its absolute value. 2* Double. ~ Swap with other copy. .C Compute k-choose-k. That's 1 for k โ‰ฅ 0 and 0 for k < 0. + Add. We've now computed |2n| + (nโ‰ฅ0). ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` แธคยฝ+.แธžยฒโ€˜_ ``` [Try it online!](https://tio.run/nexus/jelly#ARkA5v//4bikwr0rLuG4nsKy4oCYX////zEyMzQ1 "Jelly โ€“ TIO Nexus") Port of my MATL answer. [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` r=round f n=r(sqrt$2*n)^2-r n+1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8i2KL80L4UrTSHPtkijuLCoRMVIK08zzki3SCFP2/B/bmJmnm1BUWZeiUqagvF/AA "Haskell โ€“ Try It Online") This answer just uses the formula. It is the least interesting answer here, but it also happens to be the golfiest. # [Haskell](https://www.haskell.org/), ~~38~~ ~~36~~ 34 bytes ``` x!y|x<=y=1-x|v<-y+1=v+(x-y)!v (!0) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0KxsqbCxrbS1lC3oqbMRrdS29C2TFujQrdSU7GMK9FWQ9FA839uYmaebUFRZl6JSm5igUJitKGenqGBQex/AA "Haskell โ€“ Try It Online") `(!0)` is the point free function we are concerned with. ## Explanation Let me start out by saying I'm very happy with this answer. The basic idea here is that if we remove the largest triangular number smaller than our input we can reverse it and add the triangular number back. So we define an operator `!`, `!` takes our regular input, `x`, but it also takes an extra number `y`. `y` keeps track of the size of the growing triangular number. If `x>y` we want to recurse, we decrease `x` by `y` and increase `y` by one. So we calculate `(x-y)!(y+1)` and add `y+1` to it. If `x<=y` we have reached our base case, to reverse `x`'s placement in the row of the triangle we return `1-x`. # [Haskell](https://www.haskell.org/), 54 bytes ``` f x|u<-div(x^2-x)2=[u+x,u+x-1..u+1] (!!)$0:(>>=)[1..]f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoqbURjcls0yjIs5It0LTyDa6VLtCB4h1DfX0SrUNY7kSbTUUFTVVDKw07OxsNaOBwrFp/3MTM/NsC4oy80pUchMLFBJBwoYGBrH/AQ "Haskell โ€“ Try It Online") `(!!)$0:(>>=)[1..]f` is a point-free function ## Explanation The first thing we are concerned with is `f`, `f` is a function that takes `x` and returns the `x`th row of th triangle in reverse. It does this by first calculating the `x-1`nd triangular number and assigning it to `u`. `u<-div(x^2-x)2`. We then return the list `[u+x,u+x-1..u+1]`. `u+x` is the `x`th triangular number and the first number on the row, `u+x-1` is one less than that and the second number on the row `u+1` is one more than the last triangular number and thus the last number on the row. Once we have `f` we form a list `(>>=)[1..]f`, which is a flattening of the triangle. We add zero to the front with `0:` so that our answers will not be offset by one, and supply it to our indexing function `(!!)`. # [Haskell](https://www.haskell.org/), 56 bytes ``` f 0=[0] f x|u<-f(x-1)!!0=[u+x,u+x-1..u+1] (!!)$[0..]>>=f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDbaIJYrTaGiptRGN02jQtdQU1ERKFiqXaEDxLqGenql2oaxXIm2GoqKmirRBnp6sXZ2tmn/cxMz82wLijLzSlRyEwsUEqOBKg0NDGL/AwA "Haskell โ€“ Try It Online") This one is 2 bytes longer but a bit more elegant in my opinion. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 11 bytes ``` EX^.5+kUG-Q ``` [Try it online!](https://tio.run/nexus/matl#@@8aEadnqp0d6q4b@P@/oZGxiSkA "MATL โ€“ TIO Nexus") This uses the formula ``` a(n) = floor(sqrt(2*n)+1/2)^2 - n + 1. ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~71~~ 68 bytes *3 bytes saved thanks to [Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien).* ``` x=triu(ones(n=input('')));x(~~x)=1:nnz(x);disp(nonzeros(flip(x))(n)) ``` This doesn't work for large inputs due to memory limitations. [Try it online!](https://tio.run/nexus/octave#Dcg7CsAgEAXA4/hel5RGvE0MLIRV/MBi4dVNppxtsVcZyJoaNIqW0eEcyWBYyxjPS3XCGG5pBZp1ppobnlfKv4SSe3t/fA "Octave โ€“ TIO Nexus") ### Explanation Consider input `n = 4`. The code first builds the matrix ``` 1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1 ``` Then it replaces nonzero entries in column-major order (down, then across) by `1`, `2`, `3` ... : ``` 1 2 4 7 0 3 5 8 0 0 6 9 0 0 0 10 ``` Then it flips the matrix vertically: ``` 0 0 0 10 0 0 6 9 0 3 5 8 1 2 4 7 ``` Finally, it takes the `n`-th nonzero value in column-major order, which in this case is `6`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 48 bytes ``` k,j,l;f(n){for(k=j=0;k<n;)l=k,k+=++j;n=1+k-n+l;} ``` [Try it online!](https://tio.run/nexus/c-gcc#LY3RCoMwDEXf/YogCC2N0KgbSOx@ZPNhDxNqXTecb@K3u9TtQs4NSbjZA4448aCiXofXrIIbneXQRdaTCxiMM2bk6MiEMpqJt/1591HpNQORjwssj89yJerBwQqEUCHUCA0CSbWtTZAxWWsT69PBs7CqmxNsfCSl3ynNS4xlsQ6IxI3Rxz7pPcvFoPLCQ3mBwt9ijr/3vkcY1L/VmrNt/wI "C (gcc) โ€“ TIO Nexus") Probably suboptimal, but I'm pretty happy with this one. Uses the fact that NTF**N** = T**N** + [A057944](http://oeis.org/A057944)(**N**) - **N** + 1 (If I wrote the formula down correctly, that is.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` U1V[YLO>Xโ€บiYLOX-UY<LO>X+,q}Y>V ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9qGBYd6eNvF/GoYVcmkBGhGxppA@Jr6xTWRtqF/f8PAA) [Answer] ## Batch, 70 bytes ``` @set/ai=%2+1,j=%3+i @if %j% lss %1 %0 %1 %i% %j% @cmd/cset/ai*i+1-%1 ``` Uses a loop to find the index of the triangular number at least as large as `n`. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` !แนโ†”ยดCN ``` [Try it online!](https://tio.run/##yygtzv7/X/HhzsZHbVMObXH2@///v6GBgQEA "Husk โ€“ Try It Online") ### Explanation ``` !แนโ†”ยดCN -- implicit input N, for example: 4 ยด N -- duplicate the natural numbers: [1,2,3,โ€ฆ] [1,2,3,โ€ฆ] C -- cut the second argument into sizes of the first: [[1],[2,3],[4,5,6],[7,8,9,10],โ€ฆ] แนโ†” -- map reverse and flatten: [1,3,2,6,5,4,10,9,8,7,15,โ€ฆ ! -- index into that list: 6 ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 78 bytes ``` (d _(q((R N T)(i(l T N)(_(a R 1)N(a T R))(a 2(a T(s T(a N R (d f(q((N)(_ 2 N 1 ``` Defines a function `f` that performs the mapping. [Try it online!](https://tio.run/##FYs7CsAgEET7nGLK2dJArmEh9rIhBAQTzafJ6c1aDG8Y3rz5/Ep@Wu/ckHiRAR5RmFkQ4YWJigAn3hgRRIzz6HwsanaY7LuP79Ax2@Q6S9UNJa@33p9MPLRhB91b4RaR/gM "tinylisp โ€“ Try It Online") ### Ungolfed We find the smallest triangular number that is greater than or equal to the input number, as well as which row of the triangle our number is in. From these, we can calculate the flipped version of the number. * If the current triangular number is less than N, recurse to the next row of the triangle. (We treat the top row as row 2 to make the math simpler.) * Otherwise, the flipped version of N is (T-N)+(T-R)+2. The main function `flip` simply calls the helper function `_flip` starting from the top row. ``` (load library) (def _flip (lambda (Num Row Triangular) (if (less? Triangular Num) (_flip Num (inc Row) (+ Triangular Row)) (+ 2 (- Triangular Num) (- Triangular Row)))))) (def flip (lambda (Num) (_flip Num 2 1))) ``` [Answer] # [Julia 1.0](http://julialang.org/), ~~29~~ 23 bytes ``` !n=round((2n)^.5)^2-n+1 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPtii/NC9FQ8MoTzNOz1Qzzkg3T9vwf0FRZl5JTp6GooahpiYXEs8ElWtkbGKqqfkfAA "Julia 1.0 โ€“ Try It Online") Port of [Arnauld's JS](https://codegolf.stackexchange.com/a/117883/109916) answer. -6 thx to @steffan [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ยทLDยฃรญหœยน<รจ ``` [Try it online!](https://tio.run/nexus/05ab1e#ARUA6v//wrdMRMKjw63LnMK5PMOo//80MDA "05AB1E โ€“ TIO Nexus") **Explanation** ``` ยทL # push range [1 ... 2n] D # duplicate ยฃ # split the first list into pieces with size dependent on the second list รญ # reverse each sublist หœ # flatten ยน<รจ # get the element at index <input>-1 ``` Array flattening unfortunately doesn't handle larger lists very well. At the cost of 1 byte we could do [ยทt2z+รฏnยน->](https://tio.run/nexus/05ab1e#@39oe4lRlfbh9XmHdura/f9vaWkIAA) using the mathematical formula `floor(sqrt(2*n)+1/2)^2 - n + 1` found on [OEIS](https://oeis.org/A038722). [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~13~~ 12 bytes ``` โ†ฤ2*โˆšยฝ+โŒŠยฒ-~โบ ``` Port of [Arnauld's approach](https://codegolf.stackexchange.com/a/117883/15214) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` dษพ:แบ‡RfJi ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJkyb464bqHUmZKaSIsIiIsIjQwMCJd) [Answer] # [Python 3](https://docs.python.org/3/), ~~37~~ ~~35~~ 32 bytes ``` lambda n:round((2*n)**.5)**2-n+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqii/NC9FQ8NIK09TS0vPFEgY6eZpG/4vKMrMK9FI0zDU1OSCs02QOUbGJqaamv8B "Python 3 โ€“ Try It Online") Port of [Arnauld's JS](https://codegolf.stackexchange.com/a/117883/109916) answer. -3 thx to @Steffan [Answer] # PHP, 35 Bytes ``` <?=((2*$argn)**.5+.5^0)**2-$argn+1; ``` Same formula that is used in [Arnaulds Approach](https://codegolf.stackexchange.com/questions/117879/number-triangle-flip/117883#117883) [Answer] # C#, ~~46~~ 44 bytes ``` n=>Math.Pow((int)(Math.Sqrt(2*n)+.5),2)-n+1; ``` I port [@Arnauld's solution](https://codegolf.stackexchange.com/a/117883/15214). Thank you! * Pow of 0.5 is Sqrt. 2 bytes saved! [Answer] # APL (Dyalog), 27 bytes I've got two solutions at the same bytecount. A train: ``` โŠขโŠƒโŠƒโˆ˜(,/{โŒฝ(+/โณโต-1)+โณโต}ยจโˆ˜โณ) ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG3Co65Fj7qaQahjhoaOfvWjnr0a2vqPejc/6t2qa6ipDWHVHloBlAeyNf//dwSyezcbGgAA "APL (Dyalog Unicode) โ€“ TIO Nexus") And a dfn: ``` {โตโŠƒโŠƒ((โณโต),.{1+โต-โณโบ}+\โณโต)} ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG1C9aPerY@6moFIQ@NR72YgT1NHr9pQG8jQBfN31WrHQCVq//93PLQCyDE0AAA "APL (Dyalog Unicode) โ€“ TIO Nexus") Both of these solutions first create the flipped triangle and then extract element at the index stated by the argument (`1`-based). [Answer] # J, 25 bytes ``` 3 :'>:y-~*:>.-:<:%:>:8*y' ``` As an explanation, consider `f(n) = n(n+1)/2`. `f(r)`, given the row `r`, returns the leftmost number of the the `r`th row of the mirrored triangle. Now, consider `g(n) = ceiling[fโปยน(n)]`. `g(i)`, given the index `i`, returns the row on which index i is found. Then, `f(g(n))` returns the leftmost number of the row on which index n is found. So, `h(n) = f(g(n)) - (n - f(g(n)-1)) + 1` is the answer to the above problem. Simplifying, we get `h(n) = [g(n)]ยฒ - n + 1 = ceiling[(-1 + sqrt(1 + 8n))/2]ยฒ - n + 1`. From the looks of @Arnauld's formula, it appears that: `ceiling[(-1 + sqrt(1 + 8n))/2] = floor[1/2 + sqrt(2n)]`. [Answer] # [J](http://jsoftware.com/), 19 bytes ``` 1-]-0.5*:@<.@+%:@+: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuo2CgYAXEunoKzkE@bv8NdWN1DfRMtawcbPQctFWtHLSt/mtypSZn5CukKRjCGEYwhjGMYQJXA2dZWhogmHCthgYGBgi2sSkS2wzONjI2Mf0PAA "J โ€“ Try It Online") Uses the formula from [Arnauld's answer](https://codegolf.stackexchange.com/a/117883/31957). ``` 1-]-0.5*:@<.@+%:@+: +: 2n %:@ sqrt(^) 0.5 + 0.5 + ^ <.@ floor(^) *:@ square(^) ]- input - ^ 1- 1 - ^ (computes - input + 1 in a golfier way) ``` # [J](http://jsoftware.com/), 43 bytes ``` 1+;@((#{.[:;(1<@,#&0)"0)<@|.;.1>:)@i.@+:i.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuo2CgYAXEunoKzkE@bv8Nta0dNDSUq/Wiraw1DG0cdJTVDDSVDDRtHGr0rPUM7aw0HTL1HLStMvVi/2typSZn5CukKRjCGEYwhjGMYQJXA2dZWhogmHCthgYGBgi2sSkS2wzONjI2Mf0PAA "J โ€“ Try It Online") Shortest non-formula solution I could think of. The array form of `;.` is really unwieldly for code golf, and it doesn't help that ragged lists aren't that golfy either. ``` 1+;@((#{.[:;(1<@,#&0)"0)<@|.;.1>:)@i.@+:i.] @i.@+: range [0, 2n) ( ;.1>:) segment [1, 2n] according to ( ) the indices of triangular numbers: ( )"0 over each integer in [0, 2n): #&0 create that many 0s 1 , prepend a 1 (a cut location) <@ and box it [:; then raze that boxed list #{. and take 2n entries from that array <@|. box and reverse each segment ;@ raze this list i.] get the 0-based index of the input in it 1+ and add 1 ``` For generating the indices of triangular number, the invariance under inverse transform `(=(-:@*>:)@<.@%:@+:)` is 1 byte longer, but much faster. [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 0-indexed ``` gUรฒรฒ@Tยฑ1รƒcร” ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1Xy8kBUsTHDY9Q&input=MTE) ``` gUรฒรฒ@Tยฑ1รƒcร” :Implicit input of integer U g :Index into Uรฒ : Range [0,U] รฒ : Range [0,each] @ : Map each subrange Tยฑ1 : Increment T (initially 0) by 1 รƒ : End map c : Flat map ร” : Reverse ``` ]
[Question] [ Imagine you place a knight chess piece on a phone dial pad. This chess piece moves from keys to keys in an uppercase "L" shape: two steps horizontally followed by one vertically, or one step horizontally then two vertically: ``` +-+ |1| 2 3 +-+ `-------v | +-+ 4 | 5 |6| | +-+ | |+-+ 7 >|8| 9 +-+ 0 ``` Suppose you dial keys on the keypad using only hops a knight can make. Every time the knight lands on a key, we dial that key and make another hop. The starting position counts as hop 0. How many distinct numbers can you dial in N hops from a particular starting position? # Example **Starting key**: 6 **Number of hops**: 2 **Numbers that can be formed**: ``` 6 0 6 6 0 4 6 1 6 6 1 8 6 7 2 6 7 6 ``` So six different numbers can be formed from the key 6 and with 2 hops. # Constraints **Input:** You will receive two numbers as input. You can mix those input and use any format you wish. The starting key will be a number between 0 and 9, the number of hops will be a nonnegative integer with no upper limit. **Output:** You will output a single number in any format you want. # Test cases ``` (key,hops) result (6,0) 1 (6,1) 3 (6,2) 6 (6,10) 4608 (6,20) 18136064 (5,0) 1 (5,1) 0 ``` # Scoring This is code golf. To encourage participation in the future, no answer will be accepted. # Note This is strongly inspired by [*The Knight's Dialer*](https://alexgolec.dev/google-interview-questions-deconstructed-the-knights-dialer/), a former Google interview question. But be careful, it's not identical, so don't simply base your answer on the code you see there. [Answer] # JavaScript (ES6), ~~62 61~~ 60 bytes [My Python port](https://codegolf.stackexchange.com/a/213947/58563), ported back to JS. :-p ``` f=(n,k,o=k%2)=>n--?k-5&&(2-o)*f(n,!k*3-~o)+(k&5&&f(n,o*4)):1 ``` [Try it online!](https://tio.run/##dc5NCsIwFATgfU8RF4a8mtj8tKEI0bOU2oqm5IkVl149VhCDAbfzMcNcukc397fz9S4CHocYR8cC9xydX2tw@yDEwYuGUqYFQjkuuPKlEU@EDfN0gXeEZQ2wU7HHMOM0bCc8sZFJbgEIIVVFVPFLKpHJSCeyeeuzuFBtZZsXk6pWGSttXeSHmv@HviTjCw "JavaScript (Node.js) โ€“ Try It Online") Below is my original 62-byte version, which is easier to understand: ``` f=(n,k)=>n--?k&1?k-5&&f(n,2)+f(n,4):2*f(n,k?1:4)+(k&4&&f(n)):1 ``` [Try it online!](https://tio.run/##dc7BCoMwDAbgu0/RU2mmnU2tRQTXZxGnY6u0Msdev9MxVlbYKSFfEv5b/@zX4X5dHtz58xjC1DFXWOhOjnNjKRrLa0qnbSgh34uCVh72xhpsFeTMUvVeAGgxDN6tfh6Ps7@wiYlCAxBCypJg9ksYqUpIRtLp1efjRkqLJj2Mig1WWmiVpYHq/4G@JMIL "JavaScript (Node.js) โ€“ Try It Online") ### How? There are 4 groups of keys which are really connected together. All keys within a group have the exact same behavior. * Corners `1`, `3`, `7`, `9` (in green). Characterization: odd keys that are not equal to \$5\$. * Left/right sides `4`, `6` (in blue). Characterization: even keys for which we have \$k \operatorname{and}4 = 4\$. * Top/bottom sides `2`, `8` (in yellow). Characterization: non-zero even keys for which we have \$k \operatorname{and}4 = 0\$. * The `0` key (in red). The `5` key is secluded and processed separately. The figure on the right is a weighted directed graph showing which target groups can be reached from a given source group, and how many distinct keys are valid targets within each target group. [![keypad and graph](https://i.stack.imgur.com/HbxLz.png)](https://i.stack.imgur.com/HbxLz.png) This algorithm does one recursive call per target group from the current group, multiplies each result by the corresponding weight and sums them all. Only the first iteration is expecting \$k\in[0..9]\$. For the next ones, we just set \$k\$ to the leading key of each group (\$1\$, \$4\$, \$2\$ and \$0\$ respectively). --- # JavaScript (ES6), ~~86 74~~ 72 bytes ``` f=(p,n,k=10)=>n?k--&&(306>>(p*2149^k*2149)%71%35&1&&f(k,n-1))+f(p,n,k):1 ``` [Try it online!](https://tio.run/##dc7RCoIwFAbg@55iN46d2nLHzWWB9iaBmJOabJLR668wJFC6Ohff@X/@e/2qx@ZxG57Ch2sboy3ZwD13JUooK392QlDKlDRVxYZthvp4cdOB5ICJyilSapnjXiDAzn7DcMLYBD@Gvt33oWOWGS4BCCFpSnCzJJxJrSibyaxTU@OHtJHFOjgrFqiMNHrxkf8flP8GyfgG "JavaScript (Node.js) โ€“ Try It Online") ### 71 bytes Much, much slower. ``` f=(p,n,k=10)=>n?k--&&(306>>(p*2149^k*2149)%71%35&1)*f(k,n-1)+f(p,n,k):1 ``` [Try it online!](https://tio.run/##dczRCsIgGIbh867Ck4n/0uY/0yjQ7iQYa0Y5VFp0@wbFCBYdfQcP33vrnt3U36/5IWI6D6V4yzKPPFiUYF08BiEoZUoa51iuW9zuT@E9UO2wUpoi1J4FHgXC2n@@cMDSpzilcdiM6cI8M1wCEEKahuBqSTiT@qF2JrMg/T@ov0FZXg "JavaScript (Node.js) โ€“ Try It Online") ### Finding a hash function We are looking for a function \$h(p,k)\$ telling whether \$p\$ and \$k\$ are connected by a knight hop. Because this function is commutative and because the result is always the same when \$p=k\$, a bitwise XOR looks like a good candidate. We can't directly do \$p \operatorname{XOR} k\$ because, for instance, \$0 \operatorname{XOR} 4\$ and \$3 \operatorname{XOR} 7\$ are both equal to \$4\$ although \$(0,4)\$ are connected and \$(3,7)\$ are not. We need to get more entropy by applying some multiplier \$M\$ such that \$(M\times p)\operatorname{XOR}\:(M\times k)\$ is collision-free. The first few [valid multipliers](https://tio.run/##TZFLT4NAFIX3/IqznKFjC/RBK1a3bojuCRpSBoMQIBRITMNvxwsXsRvmznfOfQ3fURddL3VaNQ9FGethuJTFtcHr2zvOCAxgY8KCuUGAncIBoQKY2kwPCsc76jB1FU53dLtUuPfumFoKW7Yz3k/473ZYTLaCu5hcxg7PxOzIjHzbhZ0W3w6hEXqGkZS1yHUDnxa0PTqe4FgWBauVxI2yRrEl8dZ7dEsTEXBzZ5qTdtircWta8Uhjh2vd6fpHiErhUyGSOD9PZYBaN21dIJod2b/CTVJqInyYqCQ@OMqkQkeY3j@ownVaXPI21leRSW9OnIuKNkhDMvJxpqCIdZIWOsYLVXicBDkpHaf20hg/ch5h/M9lrtd5@SX8qXpv9MPwCw) are \$75\$, \$77\$, \$83\$, ... (We *could* apply two distinct multipliers to \$p\$ and \$k\$, but we would lose the benefit of the function being commutative. So it's unlikely to lead to a smaller expression.) For each valid multiplier, we then look for some modulo chain to reduce the size of the lookup table. By running a brute-force search with \$M<10000\$ and two modulos \$1<m\_0<m\_1<100\$ followed by a modulo \$32\$, the following expression arises: > > $$h(p,k)=((((p\times 2149)\operatorname{XOR}\:(k\times 2149))\bmod 71)\bmod 35)\bmod 32$$ > > > We have a valid hop iff \$h(p,k)\in\{1,4,5,8\}\$, which can be represented as the small bit-mask \$100110010\_2=306\_{10}\$. Hence the JS implementation: ``` 306 >> (p * 2149 ^ k * 2149) % 71 % 35 & 1 ``` Note that the final modulo \$32\$ is implicitly provided by the right-shift. ### Commented ``` f = ( // f is a recursive function taking: p, // p = current position n, // n = number of remaining hops k = 10 // k = key counter ) => // n ? // if n is not equal to 0: k-- && ( // decrement k; if it was not 0: 306 >> // right-shifted lookup bit-mask (p * 2149 ^ k * 2149) // apply the XOR % 71 % 35 // apply the modulo chain & 1 && // if the least significant bit is set: f(k, n - 1) // do a recursive call with p = k and n - 1 ) + // f(p, n, k) // add the result of a recursive call // with the updated k : // else: 1 // stop the recursion // and increment the final result ``` [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes *Saved 1 byte thanks to @Sisyphus* *Saved 5 more bytes thanks to @xnor* This is based on the logic used in [my 62-byte JS version](https://codegolf.stackexchange.com/a/213807/58563), with a different implementation to make it easier to golf in Python. I've since ported this back to JS, as it turned out to be shorter as well. ``` f=lambda n,k:n<1or k-5and(2-k%2)*f(n-1,4-k%-9%2)+9%~k%2*f(n-1,k%2*2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n2yrPxjC/SCFb1zQxL0XDSDdb1UhTK00jT9dQxwTI0bUE8rUtVeuA4lBhEMtI838aUFexQmaeQlFiXnqqhqGBphWXQkFRZl6JQrGOQrQ2ULFOsaYCSFkeirLY/wA "Python 2 โ€“ Try It Online") Below is a summary of the results returned by each expression, split by key groups: ``` expression | 1 3 7 9 | 2 8 | 4 6 | 0 | description ------------+---------+-----+-----+---+--------------------------------------- 2-k%2 | 1 1 1 1 | 2 2 | 2 2 | 2 | weight for the 1st recursive call 4-k%-9%2 | 4 4 4 4 | 3 3 | 3 3 | 4 | target key for the 1st recursive call 9%~k%2 | 1 1 1 1 | 1 1 | 0 0 | 0 | weight for the 2nd recursive call k%2*2 | 2 2 2 2 | 0 0 | - - | - | target key for the 2nd recursive call ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โตแน—โ€™;;แนขeโ€œยกยฟแน„\ศทแธณโ‚ฌยฐแป‹โ€™Ds2ยคส‹ฦPษ—โ‚ฌS ``` A dyadic Link accepting the number of hops on the left and the key on the right which yields the number of paths. **[Try it online!](https://tio.run/##AUgAt/9qZWxsef//4oG14bmX4oCZO0A74bmiZeKAnMKhwr/huYRcyLfhuLPigqzCsOG7i@KAmURzMsKkyovGnVDJl@KCrFP///8y/zY "Jelly โ€“ Try It Online")** ### How? Forms all length `hops` decimal numbers, prepends `key` to each and counts how many have all valid neighbours by lookup in a compressed list. (Note: when `hops` is zero the fact that the empty product is one means the Link yields 1, as desired.) --- ### [Here](https://tio.run/##AUEAvv9qZWxsef//4oG14bmX4oCZwrU74oG0KzMhUMadJeKBvVfigbYlMzFmxpHigJzCpMKu4oKsw5figJgpU////zL/Ng) is another 28 ``` โตแน—โ€™ยต;โด+3!Pฦ%โฝWโถ%31fฦ‘โ€œยคยฎโ‚ฌร—โ€˜)S ``` This one uses some funky arithmetic to decide whether each move is valid by adding three to each of the two digits, taking their factorials, multiplying these together, getting the remainder after division by \$22885\$, getting the remainder after division by \$31\$, and checking if the result is one of \$\{3,8,12,17\}\$. [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` f=lambda s,n:n<1or sum(f(i,n-1)for i in range(10)if`i`+`s`in`0x20cb0e9fd6fe45133e`) ``` [Try it online!](https://tio.run/##VY1BCoMwEADvfcUeE7SQqC1U2pcUYaNm24W6SmKhfX2MR48DM8zyX9@zVCnR4@OmfnQQS2nlbucA8TspUlzK2WrKzMACwcnLK2s0EzIWGJEFza8yQ2/8jcYr@eZi69qjTnsUD1F7giWwrPkCz4JUnmnYNTloXdoA "Python 2 โ€“ Try It Online") A recursive solution. Checks for pairs of digits that are a knight's move away by them being consecutive in the hardcoded string `604927618343816729406`, written one byte shorter in hex. This string is a palindrome because the adjacency relationship being symmetric, but I didn't see a shorter way to take advantage of that and remove the redundancy. **83 bytes** ``` f=lambda s,n:n<1or sum(f(i,n-1)for i in range(10)if 6030408>>(s*353^i*353)%62%29&1) ``` [Try it online!](https://tio.run/##VY3LCsIwEEX3fsVsKhOtkIcWLdofEYWITh2w05LUhV8fk2U3Fy6cw5l@83sUmxJdPn54PD3EWlo5mzFA/A5IyLXsjKL8GVggeOlfaLRigkY7vdfHrsO4cQd357KqamxlT2ujUpHiQmpXMAWWOVfguiXMMQUFkwV2S38 "Python 2 โ€“ Try It Online") **85 bytes** ``` def f(s,n):a=b=c=d=1;exec"a,b=b+c,2*a;c,d=b+d,2*c;"*n;print[d,a,b,a,c,n<1,c,a,b,a][s] ``` [Try it online!](https://tio.run/##VY07DsMgEET7nGLlyp8tjEsTToIoYIHEzdoCLCWnJ8SpUszojfSkOd7lufNSqw8RYp@Rh9Uqp0h5JWR4BeosOuUmwmW0ktA39o1JdiPLFMqZWHtsUgsh30XraxmdTY17ggwbQ7L8CL2Yh/UGR9q4QEbQ0@8Svhr/aaZ@AA "Python 2 โ€“ Try It Online") A different idea giving a fast, iterative solution. We take advantage of the knight-move adjacency graph of the phone keypad being symmetric: ``` 3--8--1 | | 4--0--6 | | 9--2--7 ``` Note that 0 doesn't break the top-bottom symmetry of the keypad because it connects just to 4 and 6 on the centerline. The number 5 is isn't drawn; it doesn't connect to anything. We use the symmetry to collapse down to four types of locations: ``` a--b--a | | c--d--c | | a--b--a a: 1379 b: 28 c: 46 d: 5 ``` We now have the transitions (some appearing multiple times): ``` a -> b, c b -> a, a c -> a, a, d d -> c, c ``` This corresponds to the update of counts at each step of `a,b,c,d=b+c,2*a,2*a+d,2*c`. This can be written shorter as `a,b=b+c,2*a;c,d=b+d,2*c`, as pointed out by ovs saving 2 bytes. So, we iterate `n` steps to produce the correspond values of `a,b,c,d`, and now we need to select the one corresponding to the start digit `s`. We need a mapping of each digit `0-9` to the corresponding entry `a,b,c,d`, with `5` going to `n<0`. The code just uses a direct array selector: `[d,a,b,a,c,n<1,c,a,b,a][s]`. There's probably a shorter way using the symmetry that `s` and `10-s` are in the same category, and so we can do something like `s*s%10` to collapse these, or even `s*s%10%8` to get a distinct fingerprint for each type. With optimizations, this method might take the lead. [Answer] # [Perl 5](https://www.perl.org/), (`-p`) 63 bytes ``` eval's/./(46,68,79,48,390,"",170,26,13,24)[$&]/ge;'x<>;$_=y///c ``` [Try it online!](https://tio.run/##NYvtCoIwFIb/7yqGShYc29nX2YbljUREiEQgKRlRN99ySX8eHt6Psbv3NuZcKs1ybizNdD7M5Bi757kvJ7EVa0NAHlwA40EHhCwD6RAUgdSgzOZQrI7i0tXla9fUxWn/FkK0MRJDXjVcMmIyiZ5FJaGU/DpD6FO6DL3UhGSY/R/tcsTPMD6uw22KVT9@AQ "Perl 5 โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ๏ผฆ๏ผฎโ‰”โญ†ฮทยงโชชโ€)โ€ดโ†˜๏ผณโ€ด๏ผฐeฯ…!&q]3โฐ4โ€ยถ๏ผฉฮบฮท๏ผฉ๏ผฌฮท ``` [Try it online!](https://tio.run/##HYzBCoMwEAXvfkXIaQMWtIpWPElPQlsKXnNJrSZSu0pcS/8@XXqa4Q283hnfL2YOYVy8gBbXnW77@zF4UEo02zZZhI78hPZqVnCxaKjF5/CFbp0nApkXGouTxrLSmDOzKtGoMS0ZR25pxsxlLKRGqWJxNhvBSylWp@rozs8E//EyoCUHjlsdQppERTh85h8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes the number of hops as the first input. Too slow for large numbers of hops. Explanation: ``` ๏ผฆ๏ผฎ ``` Input the number of hops and repeat that many times. ``` โ‰”โญ†ฮทยงโชชโ€)โ€ดโ†˜๏ผณโ€ด๏ผฐeฯ…!&q]3โฐ4โ€ยถ๏ผฉฮบฮท ``` Map over every character in the string and list its possible next hops. Example: `6` โ†’ `170` โ†’ `682646` โ†’ `1701379170390170` โ†’ ... ``` ๏ผฉ๏ผฌฮท ``` Count the total number of hops found. Faster 44-byte version: ``` โ‰”๏ผฅฯ‡โผฮน๏ผฉฮทฮท๏ผฆ๏ผฎโ‰”๏ผฅโชชโ€)โˆงโ†‘mG@โฐEBรผ)โ€ฝโ‚‚โ‰•โ†–โ€ฯ‡ฮฃ๏ผฅฮบร—๏ผฉฮผยงฮทฮฝฮทฮฃ๏ผฉฮท ``` [Try it online!](https://tio.run/##XU/LDsIgELz3K0hPS4IJePDSU2M89KAxqT@AtQoRaOVh/HvERmrj7GX2MbuzneC2G7iKsXZO3gzs@QiMErR7BK4cSIK23HkQGGOCBK6K62ARNGYM/hD0ubeAMVpo21FJDyVNYCkyFvxLWaaM5jQPLCrsR/4X0JIgRpOrNujp9J2gk9S9g8mxTp3aN@bSv0AQZDCeXzhaaTx8ZPNvVYxrWmzi6qne "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: Works by repeatedly multiplying a next hop transition matrix. [Answer] # [Python 3](https://docs.python.org/3/), 88 bytes ``` f=lambda s,n:n<1or sum(map(f,'46740 021268983 1634 9 7'[int(s)::10].strip(),[n-1]*3)) ``` [Try it online!](https://tio.run/##VcxBDsIgFATQvaf4u4Khhg9IW6InabrAGGIToQRw4emxrpTZvcxk4rs8tiBrdden9be7hcyCCRfcEuSXJ95G4lin9KA4cIFCj9MoAbVUsGeCoZvXUEimxiBfTrmkNRLK5tDjcpSU1pi@vSOacUoPP2Ej0XbtVPzzzFrtP/UD "Python 3 โ€“ Try It Online") -15 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) -2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~60~~ ~~53~~ ~~52~~ 49 bytes ``` #,//(4 6;6 8;7 9;4 8;0 3 9;!0;0 1 7;2 6;1 3;2 4)/ ``` [Try it online!](https://ngn.codeberg.page/k#eJxdT8tugzAQvPsrtmoPIBHWxuBQ/Bu9RUhBxDwEwSl2VFDVfnttqoiqe9l57Iy0TfEcIQYpCCkgl0d4lanbFLhDT9QBBkeZOJsBdzsNkZC34vPltH7PRQMxLPKsBxmcm6of5SJXOYfll7s5UR8qHWAOcA98jdgU76WC5iVBJ2+XOeOCirQENKP+2PLZI59JWhKCpLP2ZgrEWl9Uq8cmNraqB7XUXTW1Kq71Fd/vytheTwYTxnOaoe3UYZj6trPmcOmrUc2EBINao07fTAgAszL30TpRRNTz32Ges51zz5Odi83fA/6b7WSXHi+RIPvXnP1tpj8wBFqk) Takes input as two separate arguments; `hops` as the first, `keys` as the second. Uses a list to map keys to each other key a "hop" away. When combined with `/`, this functions as a [finite-state machine](https://code.kx.com/q/basics/glossary/#finite-state-machine), seeded with `key` and run for `hops` iterations. `,//` flattens the result into a one dimensional array and `#` takes its count. [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 108 bytes ``` Tr@MatrixPower[AdjacencyMatrix[4~KnightTourGraph~3~VertexDelete~{10,12}],#2,SparseArray[Mod[#,10,1]->1,10]]& ``` [Try it online!](https://tio.run/##JYnBCoJAFAA/Juj0BNeiW5IQdAhBULose3itz9zQVV4bKeL@uhmdZphp0dXUojMal@q4FHxK0bEZsu5DLJPyiZqsHv9R7v3Vmkftiu7NF8a@9jt/I3Y0nKkhR34SIYhoVrCJIO@RX5Qw4yjTrpQb@E0VxGIVpbZLrtHKjI11UOC9ITkdwM5BXMmVCiYLAqJwVmr5Ag "Wolfram Language (Mathematica) โ€“ Try It Online") You know, there's probably a shorter solution for this, but I enjoy the mathematics of this one. This gets the [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) for the graph, raises it to the power of the number of jumps, and multiplies it by a vector representing which key it starts from. The elements of the resulting vector give the number of paths to each key, so the total gives the total number of paths of a given length. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Fโ€ขลพNjฮตEรฟยถ^ยฒรจ+%โ€ข5ยกsรจS}g ``` Amount of hops as first input, and the starting digit as second input. [Try it online](https://tio.run/##yy9OTMpM/f/f7VHDoqP7/LLObXU9vP/QtrhDmw6v0FYFCpoeWlh8eEVwbfr//4YGXGYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8X@3Rw2Lju7zyzq31fXw/kPb4g5tOrxCWxUoaHpoYfHhFcG16f91/kdHG@iYxepEG4JJIwgbImSgYwqWMI2NBQA) (except for the one with 20 hops, which times out). **Explanation:** ``` F # Loop the first (implicit) input amount of times: โ€ขลพNjฮตEรฟยถ^ยฒรจ+%โ€ข # Push compressed integer 46568579548530955107526513524 5ยก # Split it on 5: [46,68,79,48,309,"",107,26,13,24] s # Swap to take the current list of digits, # or the second (implicit) input in the first iteration รจ # (0-based) index those into this list S # Convert it to a flattened list of digits # ("" becomes an empty list []) }g # After the loop: pop the list of digits, and take its length # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โ€ขลพNjฮตEรฟยถ^ยฒรจ+%โ€ข` is `46568579548530955107526513524`. [Answer] # T-SQL, 197 bytes Returns null for no solutions This can handle 25 hops in 10 seconds ``` WITH C as(SELECT 0i,1*translate(@n,'37986','11124')x,1q UNION ALL SELECT-~i,y,q*(2+1/~(y*~-a))FROM(values(1,4),(1,2),(4,0),(2,1),(4,1),(0,4))x(a,y),c WHERE a=x AND i<@) SELECT sum(q)FROM C WHERE i=@ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1312728/the-knights-dialer)** [Answer] # Java 8, ~~137~~ ~~129~~ ~~91~~ 89 bytes ``` int f(int n,int k){return--n<0?1:k%2>0?k==5?0:f(n,2)+f(n,4):2*f(n,k>0?1:4)+k/4%2*f(n,0);} ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/213807/52210), provided by *@OlivierGrรฉgoire*. -2 byte thanks to *@ceilingcat*. [Try it online.](https://tio.run/##XZBBboMwEEX3nGJkKZJdICWIZOE04QRdsWy7cIEEx8QgPESqIs5O7YCqhs3YzzP2/98XcRPhpVBjXgtj4F1IffcADAqU@Sg1wom6qgNXFbt3JfadDkP9FqUbrlbxMUrV4bBNI36iOoiZ75aE8fjFbdTRjSXMV6/JajqK2H4YPSvS9t@1zGctuDWygKvVpxl2Up8/vkAw5wUAS4N05y7@x80zxovuYjp@4m2wwOmxwfvLPvl5dF1y88hfzYayH4Pldd30uG6tV6w1JRmKDq1vKORZIgfiG5/soWpa46DyCf9EYn@nCgyb1YbxFw) **Old ~~137~~ 129 bytes answer:** ``` (s,h)->{for(;h-->0;){var t="";for(var c:s.getBytes())t+="46,68,79,48,309,,107,26,13,24".split(",")[c-48];s=t;}return s.length();} ``` Starting digit as a String input, amount of hops as an integer. [Try it online.](https://tio.run/##ZZBPj4IwEMXvfopJT20oBJTFPw0e9r5ePLoeuoBQFwuho4kxfHa2RXcT3cskv3mTzHvvKC/SP@bfQ1ZLY@BDKn2bACiNRXeQWQEbh@MCMrrFTukSDHdYMWGlfmKHQYkqgw1oSAdqeMX89e3QdFRUvr8OBbtdZAeYEiLc1kG2MkFZ4PsVC0MZQy8lccKTBZ8vebzgs3DJeRTO@TTh0YxPYxKYtlZICSdsl/nxYi9MiqLvCjx3GkxQF7rEijLRD8J5as9ftfX0sHZpVA4nm@6RYbcHye7RrAGkCQ/HOH8YPeP0RX26fuMvGP2rZvw/qq663wLvBrZXg8UpaM4YtNYb1pqSLcoOXde5KhWugHjGIwKqpjUOKo@sPpF4OsioFYht/PGyH34A) **Explanation:** ``` (s,h)->{ // Method with String & integer parameter & integer return for(;h-->0;){ // Loop the integer amount of times: var t=""; // Temp-String, starting empty for(var c:s.getBytes()) // Inner loop over the digit-codepoint of the String: t+= // Append to the temp-String: "46,68,79,48,309,,107,26,13,24".split(",")[c-48]); // The keys the current digit can knight-jump to s=t;} // After the inner loop, replace `s` with the temp-String return s.length();} // Return the length of the String as result ``` ]
[Question] [ Around the year 1637, Pierre de Fermat wrote in the margins of his copy of the Arithmetica: ``` It is impossible to separate a cube into two cubes, or a fourth power into two fourth powers, or in general, any power higher than the second, into two like powers. I have discovered a truly marvelous proof of this, which this margin is too narrow to contain. ``` Unfortunately for us, the margin is still too narrow to contain the proof. Today, we are going to write into the margins a simple program that confirms the proof for arbitrary inputs. # The Challenge We want a program for function that given a power, separates it into two pairs of two powers that are as close to the power as possible. We want the program that does this to be as small as possible so it can fit into the margins. --- # Input The power and the power number: `c`, `x` Constraints: `c > 2` and `x > 2` Input can be through program arguments, function arguments, or from the user. # Output This exact string: "`a^x + b^x < c^x`" with `a`, `b`, `c`, and `x` replaced with their literal integer values. `a` and `b` must be chosen so that `a^x + b^x < c^x` and no other values of `a` or `b` would make it closer to `c^x`. Also: `a>=b>0` Output can be through function return value, stdout, saved to a file, or displayed on screen. --- **Examples:** ``` > 3 3 2^3 + 2^3 < 3^3 > 4 3 3^3 + 3^3 < 4^3 > 5 3 4^3 + 3^3 < 5^3 > 6 3 5^3 + 4^3 < 6^3 > 7 3 6^3 + 5^3 < 7^3 > 8 3 7^3 + 5^3 < 8^3 ``` Due to Fermat's average writing skills, unprintable characters are not allowed. The program with the least number of characters wins. --- ## 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 characters ``` Alternatively, you can start with: ``` ## 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=57363,OVERRIDE_USER=32700;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Pyth, 38 bytes ``` Ls^Rvzbjd.imj\^,dz+eoyNf<yTy]Q^UQ2Q"+< ``` Takes input in this format: ``` x c ``` [Answer] # Matlab, ~~169~~ 153 bytes ~~The score can be +-1 depending on the unsolved problems in the comments=)~~ The score stays the same. This is just a bruteforce search for the best `(a,b)` pair. Pretty disappointing: I first tried experimented with some 'fancy' stuff and then realized two simple nested for loops are way shorter... ``` function f(c,x); m=0;p=@(x)int2str(x); X=['^' p(x)]; for b=1:c;for a=b:c; n=a^x+b^x; if n<c^x&n>m;m=n;s=[p(a) X ' + ' p(b) X ' < ' p(c) X];end;end;end; disp(s) ``` Old version: ``` function q=f(c,x); [b,a]=meshgrid(1:c); z=a.^x+b.^x; k=find(z==max(z(z(:)<c^x & a(:)>=b(:))),1); p=@(x)int2str(x);x=['^' p(x)]; disp([p(a(k)) x ' + ' p(b(k)) x ' < ' p(c) x]) ``` [Answer] # Mathematica, ~~79 95~~ 80 bytes This just might fit onto the margin. ``` c_~f~x_:=Inactivate[a^x+b^x<c^x]/.Last@Solve[a^x+b^x<c^x&&a>=b>0,{a,b},Integers] ``` --- **Testing** ``` f[3, 3] f[4, 3] f[5, 3] f[6, 3] f[7, 3] f[8, 3] ``` [![output](https://i.stack.imgur.com/rs6mq.png)](https://i.stack.imgur.com/rs6mq.png) [Answer] # CJam, ~~51~~ ~~46~~ 43 bytes ``` q~_2m*\f+{W$f#)\:+_@<*}$W='^@s+f+"+<".{S\S} ``` This full program reads the power, then the base from STDIN. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~_2m*%5Cf%2B%7BW%24f%23)%5C%3A%2B_%40%3C*%7D%24W%3D'%5E%40s%2Bf%2B%22%2B%3C%22.%7BS%5CS%7D&input=3%205). [Answer] ## Matlab, ~~141~~ 140 bytes This is coded as function that displays the result in stdout. ``` function f(c,x) b=(1:c).^x;d=bsxfun(@plus,b,b');d(d>c^x)=0;[~,r]=max(d(:));sprintf('%i^%i + %i^%i < %i^%i',[mod(r-1,c)+1 ceil(r/c) c;x x x]) ``` Example use: ``` >> f(8,3) ans = 7^3 + 5^3 < 8^3 ``` Or [try it online in Octave](http://ideone.com/pYkwkV). Thanks to @flawr for removing one byte. [Answer] # CJam, ~~53~~ 51 bytes ``` l~:C\:X#:U;C2m*{Xf#:+_U<*}$W=~"^"X+:T" + "@T" < "CT ``` [Try it online](http://cjam.aditsu.net/#code=l~%3AC%5C%3AX%23%3AU%3BC2m*%7BXf%23%3A%2B_U%3C*%7D%24W%3D~%22%5E%22X%2B%3AT%22%20%2B%20%22%40T%22%20%3C%20%22CT&input=3%205) The input format is `x c`, which is the reverse of the order used in the examples. Explanation: ``` l~ Read and interpret input. :C Store c in variable C. \ Swap x to top. :X Store it in variable X. # Calculate c^x. :U; Store it in variable U as the upper limit, and pop it from stack. C2m* Generate all pairs of values less than c. These are candidates for a/b. { Start of mapping function for sort. X Get value of x. f# Apply power to calculate [a^x b^x] for a/b candidates. :+ Sum them to get a^x+b^x. _U< Compare value to upper limit. * Multiply value and comparison result to get 0 for values above limit. }$ End of sort block. W= Last a/b pair in sorted list is the solution. ~ Unpack it. "^"X+ Build "^x" string with value of x. :T Store it in variable T, will use it 2 more times in output. " + " Constant part of output. @ Rotate b to top of stack. T "^x" again. " < " Constant part of output. C Value of c. T And "^x" one more time, to conclude the output. ``` [Answer] # R, 139 characters ``` function(c,x)with(expand.grid(a=1:c,b=1:c),{d=a^x+b^x-c^x d[d>0]=-Inf i=which.max(d) sprintf("%i^%4$i + %i^%4$i < %i^%4$i",a[i],b[i],c,x)}) ``` [Answer] # Python 2, ~~182~~ ~~161~~ 157 bytes I usually answer in MATLAB, but because there are already two solutions in that language, I'd figure I'd try another language :) ``` def f(c,x):print max([('%d^%d + %d^%d < %d^%d'%(a,x,b,x,c,x),a**x+b**x) for b in range(1,c+1) for a in range(b,c+1) if a**x+b**x<c**x],key=lambda x:x[1])[0] ``` # Ungolfed code with explanations ``` def f(c,x): # Function declaration - takes in c and x as inputs # This generates a list of tuples where the first element is # the a^x + b^x < c^x string and the second element is a^x + b^x # Only values that satisfy the theorem have their strings and their # corresponding values here # This is a brute force method for searching lst = [('%d^%d + %d^%d < %d^%d'%(a,x,b,x,c,x),a**x+b**x) for b in range(1,c+1) for a in range(b,c+1) if a**x+b**x<c**x] # Get the tuple that provides the largest a^x + b^x value i = max(lst, key=lambda x:x[1]) # Print out the string for this corresponding tuple print(i[0]) ``` # Example Runs I ran this in IPython: ``` In [46]: f(3,3) 2^3 + 2^3 < 3^3 In [47]: f(4,3) 3^3 + 3^3 < 4^3 In [48]: f(5,3) 4^3 + 3^3 < 5^3 In [49]: f(6,3) 5^3 + 4^3 < 6^3 In [50]: f(7,3) 6^3 + 5^3 < 7^3 In [51]: f(8,3) 7^3 + 5^3 < 8^3 ``` # Try it online! <http://ideone.com/tMjGdh> If you want to run the code, click on the *edit* link near the top, then modify the STDIN parameter with two integers separated by a space. The first integer is `c` and the next one is `x`. Right now, `c=3` and `x=3` and its result is currently displayed. [Answer] # Pyth, ~~53~~ ~~52~~ 50 bytes ``` Ls^ReQbs[j" + "+R+\^eQ_Sh.MyZf<yT^FQ^UhQ2" < "j\^Q ``` [Try it online.](https://pyth.herokuapp.com/?code=Ls%5EReQbs%5Bj%22+%2B+%22%2BR%2B%5C%5EeQ_Sh.MyZf%3CyT%5EFQ%5EUhQ2%22+%3C+%22j%5C%5EQ&input=7%2C3&debug=0) Takes as input `c,x` where `c` is the target number and `x` is the base. [Answer] # Pyth, 60 bytes Input is given as c,k ``` =k^ReQUKhQLfghTeT^tb2jd.i+R+\^[[emailย protected]](/cdn-cgi/l/email-protection)?>Z^KeQ0ZJK"+< ``` [Try it Online](https://pyth.herokuapp.com/?code=%3Dk%5EReQUKhQLfghTeT%5Etb2jd.i%2BR%2B%5C%5EeQa%40yUKxJsMykh.M%3F%3EZ%5EKeQ0ZJK%22%2B%3C&input=8%2C5&test_suite=1&test_suite_input=3%2C3%0A4%2C3%0A5%2C3%0A6%2C3%0A7%2C3%0A8%2C3%0A4%2C4&debug=0) [Answer] # C, 175 bytes ``` a,b,m,A,B,M;p( a,x){return--x ?a*p(a,x):a;}f (c,x){M=p(c,x) ;for(a=c,b=1;a >=b;)(m=p(c,x) -p(a,x)-p(b,x ))<0?--a:m<M? (M=m,B=b++,A= a):b++;printf ("%d^%d + %d" "^%d < %d^%d", A,x,B,x,c,x);} ``` To fit the code into the margin, I've inserted newlines and split a string literal above - the golfed code to be counted/compiled is ``` a,b,m,A,B,M;p(a,x){return--x?a*p(a,x):a;}f(c,x){M=p(c,x);for(a=c,b=1;a>=b;)(m=p(c,x)-p(a,x)-p(b,x))<0?--a:m<M?(M=m,B=b++,A=a):b++;printf("%d^%d + %d^%d < %d^%d",A,x,B,x,c,x);} ``` Function `f` takes `c` and `x` as arguments, and produces the result on `stdout`. ### Explanation This is an iterative solution that zigzags the line defined by `a^x + b^x = c^x`. We start with `a=c` and `b=1`. Obviously, that puts us on the wrong side of the line, because `c^x + 1 > c^x`. We decrement `a` until we cross the line. When we're below the line, we increment `b` until we cross it in the other direction. Repeat until `b` meets `a`, remembering the best solution in `A` and `B` as we go. Then print it. `p` is a simple recursive implementation of `a^x` (for `x>0`) since C provides no operator for exponentiation. In pseudo-code: ``` a=c b=1 M = c^x while a >= b do m = c^x - a^x - b^x if m < 0 a -= 1 else // (m > 0, by Fermat's Last Theorem) if m < M A,B,M = a,b,m b += 1 done return A,B ``` ### Limitations `c^x` must be representable within the range of `int`. If that limitation is too restrictive, the signature of `p` could be trivially modified to `long p(long,int)` or `double p(double,int)`, and `m` and `M` to `long` or `double` respectively, without any modification to `f()`. ### Test program This accepts `c` and `x` as command-line arguments, and prints the result. ``` #include<stdio.h> int main(int argc, char**argv) { if (argc <= 2) return 1; int c = atoi(argv[1]); int x = atoi(argv[2]); f(c,x); puts(""); return 0; } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~38~~ ~~33~~ ~~31~~ 30 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` pV รต รฏ ร”รฆ@>XxpVรƒรฏNร… iร„ p<N ร‹q^ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=cFYK9SDvINTmQD5YeHBWw%2b9OxSBpxCBwPE4gy3Fe&input=OCAz) ``` :Implicit input of integers U=c & V=x pV\nรต รฏ ร”รฆ@>XxpVรƒ >FINDING THE PAIR pV :Raise U to the power of V \n :Reassign to U รต :Range [1,U] รฏ :Cartesian product with itself ร” :Reverse รฆ :Find the first element that returns true @ :When passed through the following function as X > : U is greater than Xx : X reduced by addition pV : After raising each to the power of V รƒ :End find รฏNร… iร„ p<N ร‹q^ >FORMATTING THE OUTPUT รฏ :Cartesian product with N : Array of all inputs (i.e., the original [U,V]) ร… : Slice off the first element i :Insert ร„ : "+" at 0-based index 1 p<N :Push "<", and the array of all inputs ร‹ :Map q^ : Join arrays with (and split strings on) "^" :Implicit output joined with spaces ``` [Answer] # Haskell, 120 bytes I think I've golfed this as much as I can: ``` c%x=a&" + "++b&" < "++c&""where(_,a,b)=maximum[(a^x+b^x,a,b)|b<-[1..c],a<-[b..c],a^x+b^x<c^x];u&v=show u++"^"++show c++v ``` Ungolfed: ``` fn c x = format a " + " ++ format b " < " ++ format c "" where format :: Integer -> String -> String -- `format u v` converts `u`, appends an exponent string, and appends `v` format u v = show u ++ "^" ++ show c ++ v -- this defines the variables `a` and `b` above (_, a, b) = maximum [(a^x + b^x, a, b) | b <- [1..c], a <- [b..c], a^x + b^x < c^x] ``` Usage: ``` Prelude> 30 % 11 "28^30 + 28^30 < 30^30" ``` [Answer] # Haskell, ~~132~~ 128 bytes ``` x!y=x++show y c#x=(\[_,a,b]->""!a++"^"!x++" + "!b++"^"!x++" < "!c++"^"!x)$maximum[[a^x+b^x,a,b]|a<-[0..c],b<-[0..a],a^x+b^x<c^x] ``` Usage example: `7 # 3` returns the string `"6^3 + 5^3 < 7^3"`. [Answer] # Perl 5, 119 bytes A subroutine: ``` {for$b(1..($z=$_[0])){for(1..$b){@c=("$b^$o + $_^$o < $z^$o",$d)if($d=$b**($o=$_[1])+$_**$o)<$z**$o and$d>$c[1]}}$c[0]} ``` Use as e.g.: ``` print sub{...}->(8,3) ``` [Answer] # Ruby, 125 bytes Anonymous function. Builds a list of `a` values, uses it to construct `a,b` pairs, then finds the max for the ones that fit the criteria and returns a string from there. ``` ->c,x{r=[];(1..c).map{|a|r+=([a]*a).zip 1..a} a,b=r.max_by{|a,b|z=a**x+b**x;z<c**x ?z:0} "#{a}^#{x} + #{b}^#{x} < #{c}^#{x}"} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 114 bytes ``` c=>x=>{for(a=B=[];++a<c;)for(b=0;++b<c;)B[c**x-a**x-b**x]=`${a}^${x} + ${b}^${x} < ${c}^${x}`;return B.find(_=>_)} ``` [Try it online!](https://tio.run/##bchLCoMwGATgfU/hwkWiKIW@hPi7cOElxGoStVgkKdEWIXj2NLZdlcAwzHx3@qITV8NjjoRsO1OA4ZAtkOleKkQhh7IiYUhTTvAmDPb2su3mJQ@CJaJbMVsVNL6m69XXy@qFnq/Zb6d28@9uiOrmpxJeHveDaFENWY1XQ3ZcikmOXTzKGyrQAdvgPzy68OTCswsvLkw@aN4 "JavaScript (Node.js) โ€“ Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 117 bytes ``` c=>x=>[...B=Array(c)].map((_,a,P)=>P.map((_,b)=>B[c**x-a**x-b**x]=`${a}^${x} + ${b}^${x} < ${c}^${x}`))&&B.find(_=>_) ``` [Try it online!](https://tio.run/##lY9LC4JAGEX3/QoXIjOmU9ET6hvIhWv3YjrOWBjmiEYY5m83e0IhRHC53Ht2Z89OrOB5nB3NVIqosaHhQEugLiHEgnWeszPi2CMHliHkG8xwMFDndcP2WC7X9dJktwrb8iBQK1Zv1Kqslb6iVuFzr9rNHzvAWNMsso1TgXygPm6WPS7TQiYRSeQO2WiM2@AvOOmC0y4464LzLri4wx/Wd00Bb1EjBKHraDQo8WVoiD@8P7Wv "JavaScript (Node.js) โ€“ Try It Online") Brute-force all a,b<c ]
[Question] [ # Introduction Apparently, this question has been asked [here](https://codegolf.stackexchange.com/questions/117838/shortest-possible-xkcd-password-generator) and it unfortunately closed. I thought it was a good idea to try again with it, but done right. [XKCD](http://www.xkcd.com/936) looks at the how we are trained to use "hard to remember passwords", thinking it's secure, but instead, would take a computer 3 days to crack. On the flip side, remembering 4-5 words brings Kuan's Password Intropy up, and is easy to remember. Crazy how that works, huh? # Challenge The job today is to create 5 passwords using words. 4 words per password and a minimum of 4 letters per word, but no maximum. Kuan's Password Intropy will need to be calculated for every password, but a forced minimum will not be set. # What is Kuan's Password Intropy? Kuan's Password Intropy is a measurement of how unpredictable a password is, according to Kuan. There is a simple calculation: **E = log2(R) \* L**. E being Kuan's Password Intropy, R being range of available characters and L for password length. Range of available characters is self explanatory. It's the range of characters that a password can have, in this case is Upper and lower case. Since there is 26 characters in the alphabet, 26 x 2 = 52 characters in the whole range of the password. Password Length is also self explanatory. It's the total length of the password after creation. # Constraints * No input. * A word **cannot reappear** in the same password. * No symbols or numbers allowed in a password. * 4 words per password, but a forced minimum of 4 letters per word. * No spaces between words. * You cannot generate the same password over and over again. * Each word has to be capitalized in a password. * Output has to be human-readable, must be spaced out. Must also include Kuan's Password Intropy of the password with it using Kuan's Password Intropy equation above. * [Dictionary](https://hastebin.com/raw/itixigesam). You must use this, download it as a text file and integrate accordingly. This will be the list from which you grab words from. Your code should assume its available. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest bytes win. # Output ``` TriedScarProgressPopulation 153.9 TryingPastOnesPutting 119.7 YearnGasesDeerGiven 108.3 DoubtFeetSomebodyCreature 142.5 LiquidSureDreamCatch 114.0 ``` [Answer] # Python 2, ~~102~~ ~~101~~ ~~97~~ 91 bytes ``` from random import* exec"x=''.join(x.title()for x in sample(f,4));print(x,57*len(x)/10);"*5 ``` Assumes the dictionary as a list named `f`. Can be tested by saving the file as `dict.txt` and calling ``` f = open('dict.txt').readlines() ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) (3.0+), 77 bytes ``` 1..5|%{($p=-join($d|random -c 4|%{culture|% te*|% tot* $_}));57*$p.Length/10} ``` [Try it online!](https://tio.run/nexus/powershell#TZ3b7uu@c91fxRf/AkmApA3QoBdF3qDvUMgWbWtbpx9J2V/vJo/d63TWZ412ejNrRA4PongYDg/623j510u5PbfLMNTxPdTXZbgO67itJ7ZgprEEXbe6DHMw2zy1p7B20zIap/WRDOGDUei6DfJvZZV42@o1gWBiJNV6HW4IHFXuRysJDXDcgW/l5dvIyu1GpEADG8HM4BIRJIyJ6UyEYvq2BDPJe6uraLhNt2Dqtn6XExWsT@@hFzNl/orZqqm8D/mNw95NlaKQlMSEzDhOeksAfzFyf5ZaEsbEdHbwX4PfdfwVuUNEjESWiZDb7mIfj7mbyvPtQO9SVQ7CfLTv1Eo9MR22@hWz3XjTSF4F/VCKj7KOA9BNI8QjiuYyRAUZRcnqNIb7VG91uHcxO/XkNUXe5qEukhQiK6YJRK5l6oIDp9v23CLlmRzPj3KtkfY8DXzAeSqrKQ@P1ZS4Ax13MPi@4j3muTxOGBOb0cKRzkMffY4k1huikyWyJGZ973k7FHp/DqbXEplbwv@owt/FdDQ0gPiXqwp6uU4U3hIlaVoSLRSMwuxzxLMOjzoswnl7fMEv7w7ThfX2xCNqsDAqPdVxLbdxU5bXR5lNGyC/x0wcj4M2vE7RjvS8Hn7BdQsHsA6vBPn3KaPs01@H8GeKZhL4fW6fy7APXVnZdxXkKKYM/8k0cB0TyslMP8kgMA@01X3fJpWRMXzqbVD/E7ACT8igjxVIf2AcT0aByhqfqD6O4arCNBM5rFHTV4ASd3XMykhVrJsyUevwNZVTNMWegLgY3KM7mIXbY1iRUFmIyrdP7kZgcAjSbpQDUE5G7s@BrLRnvKZAL9HaQGOOvmzhNYKpPQHp5oaszu6EdHf/F9TylqKhAJZyCwlsPSHdm@U3p7adqblHD6kov6gd/VmmtiT2E0Oi06DpWIOoEALkUrfb1KNkex9uL8UJ00B1ED0q8FoQ0HAQHsc48eqBMUgdKuYjIqNJfgZ1GKKKSsh3FNMEdbR7HdO9qqg/94Oq/qMCimq8mPLQLtcY7grwDXJ7XbeodWKiFYKKRYwKYQhmfMj/fp9PGBObUUlfh8djQO4h11eBjFAcLDSrDY8nI49oTR3YDHKL9g9dhwQcR6hiWV/12DsMbitRBlTASa3yqgUy603rQx/gKg1AhDA181WJqG5q@VdV/9EwAxMRg80MgaLOqq8L5gkhEPVakDLTjccXb9ngmyW6ixmUQ78pmm5St/hqYvDpFH10zNcySKpEtxlkhTTROpqWRFIvjrlEGqY8wPdC4J5y9jmi4obO4rQLQctdpEL0HGMJxVyew5u0hM3ouILqOcaWe0I@vgk3zxDctvVBHPPmuGZlbeUF1xHiKPn0ZS0UDkVemjS2GJuihpQPn3lSLdHgORr8RAS0L9Hpppo13b43HEDJPVT5RAkcGBrCdZrn@zaPMNI7EhuMqMp8ooSnqpyJjoNCttsx9RPl357bHtCXAegqipl@IUBvIsqD@kjAT@Q/Ggv1Z3aFn/meopZtPaX4wPPQ1VXHK6u2ze4vjfls6fIJMqmcRdVCAl@ihNuuInRhoANtzvK2jaYKtX3S77NCJXCQ1hGK8HWjcm1XkQffO4AQgfoMAL6QQ3SaIUhP7mAC5aMPsqmibMsVgkyoHcgsJKOXolMLwjNxbrxLgEW3Fz1PoD8OlX7bGm5kOVpTFRAsKAKVGN0DSJm@biquTU1UeEizEoyD6pAYnBXrRy8Vw23oeeqIRHlQZ1ndT9aBQRMkiep@r9J11GhrQcswQlXngHLi6U5UfjqpYyu06oDfhIl@Rv1AnW4vU3lO44Pw04OaGfikvsKonjDdgfop0lPfIKWgJIyJ6ezED/WT9ehqg8eVNnko4YN0j/udmYEZOTykzxn0OF8hsDNE3w@Q2xLf8KDziDIn7vh@q8CEqKsHh8AGVQS1JU0vWhGzqCs5PhqchNxwA@gGji9PX7L33fWJbsP1qmEwcFojezeUM@hoQIYafYuxM3pLeRPiZSKB@XbMB4wmJFVMaO@CJchSYqJgkEy8uIhZQkUdnBPyUWFXeOVpn/qAD4H2ftRy4ngy8qnRdAS41kIslYFASAcTjN@l7rxujI1@G4@awq0nIA3pmyMWyqGRQhT2zT32TT3cLTs2IYXYiKGFHn/RhKWaErSXzEZ37nrMrEIpuw0E6Q5/NEIezCJvaksiMR7einNQGDYERFbc89wYrkSPWd8iZmTbCYQSI4FaFs0VpbnrrQIqML9EmR8Jd5J/Dpt058Adoi/25IM8NbF2yCpVUriYKrlnKvMwluqmjl8KbEA0RehosFuGQ95ivVuiu6ifZdjnL9hN8U5FAUbBSowLSqyUF9R8DbXTDDKFLJRFinMi7s20m64HzAfixD6Z1keC0SmV9UQcQq8IOo@a3t2e23Tj5bZJmdh2yE5EgY5po1hjojcD@FW1lKf6HygBDg9zMPiuL1MeqvJ7uU0aFW7RbpdohFPM2aA07EDGexjqSujtkBEqnz4lKKGA37zV9I4RDxpz88ttzi8/0yZmK5VCvqdQVceYHtP9m4wi9kzTIIFQEwkprCeeHvoUYhwyGNWAGc0yINQ2gmiMuM3M7g3yne53USYrwqspaU0elGGQXcm0QB9innbIbuH8VsEgK0X8ZnXjpnlJkLWY4qJZn4CuK@YOT9N8IMqtu9QCHbUsG1C5HuTpQOJYmt5YZqd6Yrhv0rWDziKyLgWorLbBRCIaxuqJcpBZS0UUU3uI6guM8hRAVjY6iE09/jZTUQS9nDiejKRmdReiX8GxEHS5konoEeS63DWPvTERhSKiCirqhyLNRMzUE@y@Ob7lWHnRZZeRUljmhGYke@B4MvaZ5nLieDL2mcncvjXKKJgYmmEqvYCYiXKNvJE62MyM6SH7B8ze04d3BbeTsc8Z2Xxk4EPphkq1rCc2M6slpdMBqx8P3h1E8O58rvfJAvf8jjD2mSeHiU9AXPe68f1jbtP@IKLNFQO0w0bJrU02kER7HEs5cTyZejKI9CGz2MuydzMUbmDL55@U2FwMvWZR2lZqxiLv8gXyXd6TI99eEPIQenNJsJdr8vbiaYZYcE4fPiTNOyi8PaLJKz9V36Tu5EQgidAaRg2uW3NVbq5srVOTpHcFHA81y9D1JlI4okDnE3HYnRFhPjvho6KbBKKbBEZZfc0g2Gi0USqW0wBUB/V71cYckLgqkzdbgINKBxO1zLKnDFpZHfBssDEHgFrwM6fgRxmvmtaLdr6TGJVFKBlMYGE6coQuRfFq5JTmrv4wXmuESmhSFRL1w0TzjmEFo44YFTAgAQ2clXGybh5lwHx2LrfPaFoS/zgjFtO/Wz1uE@nQAOtRZlMNZvWgeQJjYjM6IrR3gwVWj7hMHKB2bn9cHe6bsPuVvq2TBTAEj2sRkV@M61t0GceomUsM0dH9dKHJgYIAowQOW5Juxx5zWCkNh4rHOnJKWOk8KrHV6PhvZqB62ahYmuslEuRdTPVgG1Cu0BjkrJ5WpokRIA2hmrUxhL6atasWfxlWvx5VR9XHcYjuTiQiECgCYRPdg2gkGG2JG22HE1hsZbY1ovSLwturvlZ1h8HMdojPMtruNVpFGdPuNQ6HJ43j8FFWIrPxLKarWo4xg53Vo8J8BXcRDaWGJpTxayxXxkNjPpNEuXaR42H6sJAnjTASvmFWESqVm9YChC@RzAE4ngzC21gSxsR0dsIxOuAhbEZ74KoZdtCdbAQ0ZfM@0LUHI8XagPQdjVp46wl@XMeEcjK46zUedSCD4Hgy8pbSOJZ5@OIc6HzNMvIHFGY@wUws@IjhsxgR6YNodIQILkOmL0OnGbXhAK@Qxjg64bxOpL9uRCvgEdm1OVurVgmEPGTWQjeY5GiNQKi@L3E8GXxcHfaDyKoq6onjyUjA6w@JOEhfMCDpFQWQpMDxZPDR8oE@X3v16BgD95jLgX59TUz/4HgyCtqlMxrwgMGjsJIqBspa8Fik94tqqUlI9G96SGM6u7Te2xTuk9YkVZEnL6AlNjG4zlQmo123R@jTYnhcnIlJJqpxUmcQ4z01AlQ243sWxVUUUVpmzCgGVJsA7HijliP1USY1udD9pHiOFJBLZ6IwXUBWgEct6AZRJA0TSeJ4MhJtN/WOiXbYoLWQ16b5@on4PxhiYMggiM8TYimtl44ngwvdQoBMn6MWiEdy3KJ22kcq7InjySC7H84LKxKBfat/EIH80mKo4pPs/CO13FV8sjoG9oTTnSiolDE3pETfLr/3VvXdNleqzevzworYpjWbcXvoS8iuOkrTHJlr6GEpLNwFE2pBKKVm9CLb/wdjYjOSMIz6Bk0bRtlMRRDdFktoDBspL5eRDD9BHF/PaA5/bLAZTw/EP2tM8aPoUbCgEhciJqYJ4N35C9PzoRxWLUWN2FqhlskKaONrgEpIlPKITuQl@tEyGAyrGSMmV2hJlKkDxrEFY7HlfF78rBbm715tiTfms4XpQtHagvK6fvVpfaWALBABO2S3uCfMYvB7q7mihEGRCbRMMBLSWFkZGOuxQGB556BFYd0vy8Y2yjgyYgoZj5jnjzK7Bok3OpYFSlYOq7vCZkrvEtqUawpNMch18oNCYgUZv@sgNT@xXcqgwRsaqQRGpY0iXCGRlEBJCSVdRZSaJJQo@3xEJCxoAGE0hX5ErFi3pUmzlqPBWzU@cTyZ8Hk8RLYgWMCjdGCelzKPzqD615jtiWF5PHB/JvOWfIyrqO7BdFMNgQUDCXQ8mUglZnjRaA1jYjrzAlG1NIEsmsDHAEzhJkpsV58aMG/fBGKBqckg1yd78A2EX0d/YIEwRqdSVnfIIBIrdpcTx5NpYqQyGcbEdHbIkXZUZJhvwngJBOLdIreaO9/KiePJSIBFZcOYmM6O@KHuziD3J7pt4ngy8vnl8hA65C@KY40ekRTA8WTkExr7nMBjlG//wrjkYtI8x8RWTIxZRPIO/z1qdJBGiRhD@K9oURokYfyswhbwHf86onVD1aZgQqpqgIOOBrvxAvURVT2GRuTBZsS3bZroRU5aC9UXKu@GFSh6f1JXy4mGDpK5/lQQUZyfNMr@1AyjvIfZeY6arcqvfVfqJmQg/GrZM9SUkQoqnUYkwr63@V0SxsR0Jps/ob6IoCKICc@fmxRpwx/G7uw4M4MDrerHBlZjOjty74UrP1hIys9zUFeUKPfndFVb@klCJGfYCQls9OVnlyqrZzcyYExMZ4cK5iuY@frG8WSaGVID06GWE8eTwUeahKCVhDHRvi2TtBG0/LDsG4B1KdDbS2AMRbaA8pV6G1r/fdCKX4AaimgTVZx3tvt9QX3hwEMz@Hu0BCa@wazdND6bseFQ/VzPRyaMYgjdnxo271rpug@hi9zkuuhhmdiLdqcmBKzio@k1SahvuGuNX@SjHQR3rYXUBIm220SKMf3cCOs1ycBDmnVMv25F/n6PwuxWwOsykDAxEznsV9RvB8z0XMGIzPP2SdBjqI0lgcfQLZQL2hhTt5og39bZS3Uv0v/u7Ia4h7qt1n@fRq1YGsbEZiSHU6EMQjnQMCR8QuNdcnUWtCxTuQC/iNDu88LzvJyPkpodePZCmhm7PxX5qs5KwCsZcXCHbnPondZriyi0C5yKY6XSBP1s9SUm/cgB9gOBHV0uv39H6rMVOxDPWRrdfabKeItEwAdiuU@K6evMRV88yjGKSmsN91xruJ9rDXfWGu5sZoCWRHsGY98K7LtyJEtqUCcXkE8WydSpG/OhrjDgfle4Y1KAg7zYjmVsRgfUTOK@RY94326qtNrrIFISaoK9CBPIU@ZFOx/uMj@LyIN3kHX2buvsPa2zoHKDlTZo194rGObwMf5eZWQQKuuABOtt0i7DYAqLtGL@AAIPLawKp//E9WSQeIks7MaEcbgFnUpMKCDCztOh4qje2HaXKVK5POjAtgN@dQEdaxYJWy4EmN7uWHmVg5gPaKVCyL6tYKhCKP1QpV@1AfQmPCLW0OBfphLUuCRKOpUuIehn@J5oh98lIR8tfrZ11P27d1XwKEPGvW4PiIJIib@nEn8/lfi7lfgAog8qIW0zgsoHxeZ@aOp3l@VVuwBVKwT6RlpUuLN@cM9CO8vsiAasvkkmT0IICSJb5l1riXfbhO7aDSEi5055Hmqsj2HWnvEbzI@eI96H1rMfA9b0APWohjGxGSdktV1DDm0P0gukQVXCD7p0Qrpvf0S3DZFbduUPuvKHu96AAtEwB2ooEGPa0xkLeDCTfTdW7IKpUG0dACILxVOIwKVoi5jMIBp7H8@BFYrHU9uHHpMG4odmciIR6VSjkT1mbJ0Pdj4KmAY@tM5qqvc4l2EfXn59zNuVdhJMxUYkhkd9gYc2zpni84EQjzujB53RIzqjy2ONTF8eWs0UaaKRQXUQD3U0IlGlBOqMxdyDbOP1W0CNz0KG9Ad7vx7RqAu52pqWCx9qn/H1tIKyJig3MJKKiv2owxWiORBIRoNpoioazJtp0xRIBwm830M3O5lNzER0y6KKUIf9ibiqD6stQd/Sah/RfBtAikVLpo86iddegqCLyA5RsE1fRMseKvioNDvhAsnp4V2W4B@HCHaowUD1MNnKLgbhiZc5pgwS46vpV7CWQdD1HoeKPVos88bHoWI7iJG9R48j@pinF6OAmmBXRf5kZeqpyYt2oNyOfvFOlCdq2JM9tkE7hHjm7oAyUQeNOgXVw7KQxDpqoxyMVDhhzBF2mNkSfOVgYnD9g02J1BFrypMGnkCybvDCGAF3GOWvsosmMGrhczBps/LUOhHIhPAcnPVOLjP/vdpNTu/tFvS3LIgGOUZH9SzDKJssDOV2LkZo74tIjW7tawZfEsodMN4AE1RjmsGPvDOodw61ESI/lG2DHkML0@O8MxOOnkyRVy1D6iBMV1cZzAYpCGzRTwFK0XuPE@XdJuZyT@qZqNrjM1JTp5koB776hBVfQCyazDxR0Z6oaE9rZk@sl0p1Ulcbbe25Xa8Rm5WQZyohT9QOgbw0rDy1O6PzKMYI3aosYU/qkBeUn7mC/GQF@RkTaSpWoAtGNlhTHqbfMfg8tWb81CLxlUS0Wmy4K7cwdt@Uzcb4JFQUnI8C/ETix0N7w5/HopMXgHoMmCZQIwRw3BhBnsf60MscLswjC/OQxvUMZQNiJ2rQd4xxXdXluz8Dpttm0i6TFrsiapBHDzDRS2wLtJvG24GSiRxNDxVoDDLxVemOAz08T4sMI5GtZMIrukcGqUlbQBpoQ1IwbIkCu5lQBAJY7TAQ1U7/EaiVFUM5GbtzhiqYeYrJtxjNXQ2WxBo@5caPiX0fZHc/ZuVpVflP68025ImNG1AyICZCrZgXBD@4Cu3841BaVrghEdO9hDGxGVPwmB/lxPFkJBLVfRoCYyaqby2GNO@OWEAAL9QJlVFNd6LeTLkbZFqt4AbzHGRiSFSA3B8EM/1BfKYUnVI0hjs17Wn95cR/8RmBMbEZpz8MrxeMMtNcqM2hW@Y40PHYDBC4xTxauKfgfkpi7UgcTwafqN@W7fUwo0V0g0VZ75zYpgK8FFN3DRTiSuHJULUkbjh4P9m0vqUIGMbEZvR7vgdX@lW2KIJ6KQXsCQ7KUoqw4b6RnTc9kbEZibiSvCy7Imp8Oh95mVrobmNCu/zSqCYSHbpBbjHs/tKoOQKK7pesWr@GqkWJX8Pv35dfRafsmnAV9Tk84TdoTI9@KZe/dDhMLj4k9ou8/iKnv5zPXxshYoIjK15iMxPd7i/NBEZDAwh0aMHvl233v9J2/@tYPTsJRkb3AH0K6tEvzorKLUpZHerLi9svKXdzALtrX0Xm1aCKLuCjbZaJ7fLS5kERyUzWU15sN39N2MAFdhzXGIUN@OpNXhNxMJuJsFZBFYm2b70YCF8TTv2mLval9vNaS4GIne7iqfCzNM3QxTWUzSw4zEMMI7Nq6Kz9Efq6s7I/q/3MOi8UyjpynCHNgxfnuQtZzeMzzNryYIpnoH2DaYZOHOxyMVjQu1zm4T1gdZu1ZSLIF@nP10n66XxwzF/xvydKY05tJvCuffGJOGjtd9ZElrlGTjXOmYYnGrN0n5mjA5FOtH/6mGTkojmVALV0LhM2x1kbni9zntOZGQ2CPrRSb/wK2TM6F5LBjjrboV0n8tP00EPlvMzTwLgQ2m@ZoXVIjO41@lb6j8TxZCLCifVBATlh2sWmBlyz6EEldtrK5jzRwMZVb1P1ZpDZ5isdiJFCxvEfrEXamKrKErApxphsaD9OcSCYmkwDqZxa/fGLCPWNYbpi7s4ah61nrF@iyuU2UEU3vg8KmA7qqsmD7ZLndg1jYjqTfVaBQ6PYLto3S8Btf2opWIwkt2Zn1XZa6uxdX@yVFSEHx@gMHU2yb9JyhtH5oe3iaWhQp/1htg7@cZD3VwWhndYKf/jU4KzTGzMLiPOxshYb@IDISU3w4MiegOgOHdnTVt0gP@qn5q9UVmi7LIM7idCCaCFiWNRYooO@bj9gRCdQdAuLPAuLwkF/K4AmV1A5zeViM@@iY8t2W0cV/8KJ44QxsRkd9RoaRVD1XMLVUmt67pjuUDiD@JDyMmCqFFhql6fWARN4EzG46ziH0DmumeXATiSVoWnhSMaY6OevY28vkYaj9z4vOo2IcKCFeNVe2W4Po0JEs1yG76aEVWraxrugzQZd2e21yLIeA@J040MEo7WkYB7D9atYyyxjwqLjf0v0KM6d@ps8Pn6eHvfhcdnuCC5QWZX1gMgrprv1C0If5ZLLqbmaei6mBiLHkvziFfklF@RjgjZEK6kXb5OBylfvDmym4aZxcYmhK6Zai/oSgIadOJ6MhOcRojxP6pYlNb9E4nUmrYQvU66QLnRDCxr84s7IqwvKkBZfguiFQ1XRUcZEHDT3MegxRiwl17BAiNnn4WamOp7G5oZEgrSJKMF0iP6Pcxw@xLFMP/7wqwYA5VsmExFlevPAstBxLduV2LZQAJZtdK@3sBgG7YIDCYFceYihx64Ly1nGYwmGSwGEE3teggk1I4HHbdeMVPvaKS0jPv2Jx6ZM6o04fcQkSNo7zJyIe6F707RvNcWV2gfo0cbIcxle@PYrsonXgLs@y5ZZ7rJoK6Uek@tFpmpTWbRgKMecWcIolMywy/ameWhvxuJzK0seW1nYqrEcrCUZxsR0ttRDT3OftDt/8RR3YUPHolOLaqIH@58MxAFzuih4o9YBPBZ9GoBHd7VCjfCLbVcG4uv@IgfLiwZl5qsvZVSl@vYnxLF9pVWs0q9X991r9t0rfffKcfN1WGw/WH1VgSESX6Wt/cGodt7H1MD4UIZ4VGclEvkJ3VFFaWgnisE@HcBGu0S5a0Ph6l2ELIOtvk9hLVYVV4yDa4Gw2zigGz86zFHFJCX4R9mIXsbwgijC1KGFemWYiNRGpnXTN121BL3S0taNjYTr5l3g67nba1Ur0KU3IqrIemoFIvE@OKLOzRJCJgnBTHcNJckgenpQplFjIWLfMoMBXXG81WcawvnQOaN432Nq2EtX7TFaD52VU/w69TDMJzYzUTVWomaLNVQP8eLblVmIQKUjlGOoeSVhTExnS2mnaAHRepORCDtCK0xrCZbwkBFM9FSdwJ4Jbzfp2BsbzLc723gN5Q9Tk2lCGVCFURwVBx1sMsTj2ffKnFbme@CDzUzR@eEaQ8C2sx0joA6mcts3TDzBYHDZ2DixsUEeGoUqXE6M5rv5Gp9NWyu2/TDRO@oLbN5vq2XAborjQ@8qqniFEkfdNyA0ee@wGQTQW1TjtjFUse3oqvsnNpjoBgJGhtBg8rWPjqU2cTwZgswyLgbu1AQ1q0c5cTwZ@zAPDIayPvpHxtmL@nodqjWzJTMeRi3rwshcDDPHjAncTodNWYRRTt6sZwqqhl6YLRntWIVBQYLRCSQx0b1HQqz95cof637bz1c2xO235HYN4UHU@KqYF@@4e11gT1vEngsCOwsC@8BEW2DHUW4O9rDLtNK97WjBO3s8oMikzRhGvrPzMIvIDgCVh@rCPhDWkiznANqcCxNfXRj90nAySqPqVq5dN9s4oEbl3Vd17HlVx85VHUGlMu4@XbxzOA86GpBoKR/VnVzWvlJaoCQau7YS7TCRgcYdXELsmGKwZ@zSjoNaNzY2o9PCrqWbglhc3DnBEHRiR4gZ3uxwTg/n9Micvn2fyD58/38MiRJlLev4zjp0UB2aNfDYKG6jHMZhhuI6ekHbTDQrMxJTaXBYN7qQQb3z7nwWnay6pJV3T@Xbtt6gWq8SsuVfSDixG@etdu1VofzEkIV6y/eo0zaSFzE4cDHPTjerb1i6sqE1IG0O2n2AefcB5j0PMIduXtaYfexaXRgNDUjf0KmgcqwZQz3DfnV01hD@oZ6EcAwI@u7av@6zi7tU8p01k6CqYpOsNlBFN9lmAxKtbs7YaTZuHtNe6KnE6LETumvX04k4xztOv38PpuEyY6wxjInpTDqzGulXuNodZULYLZ@tdPYnxlRVT8ShF1M/cGhxt3lpT/tSfMUB884@e9e2sRod/aY8@NANaFeplkE1YOxbdkJbWaDUwY1lc4HcbABOxEG2H4MihpH7K/Ky6ZjsrsnB7q0rBuRmb@0X0@3Pmn4wKmXOnQq3SnLesSJUSWoH5@4T43seGN9lGwlyuI@DId76ErFWlEsbQE1ooKPwFYGJ9tCNW4l2EFWtZ2ufN/bltr5984VXgSwJgjPAoQgxJJvfNXBnZJCOtiUQ3VEhJOD1AaF83hjVdp3nk4ztNftpr9nrQHdNpisnioCa0MCU1PtUriYyIFx89CUYzvImjidjHzY17DrZGMpTIg53yj5QLR1wUDEIPDi5EMzifILNTKgzUnw4PZsMPhyRTcThrfmEUKPuLuPGCPi9JrLNdMGgMJPjmugqtWJBK/Z6loEyimngDfffxVSBtqvrTt3Y45qIzy2atnK9abFKEWz3yaJ3d0lieoIfOU0djBeOgkEDSURk0V6uxPFk7LOfLrtjQ2cP3O487jGECSnaCDTh2bfbpvKSdTCoFsEFNFDjeDIRS0wHx6iLR2ocx7xfvNwHDQFZ/XavROy5ErFjBNwxku9pI9/TRA5aaKUHACyQPYDmBbum0ztz5v3Y9X1F9SB7UFA@2FF1B2FAO04YE5vRKYlRdL9/Iy4YE5sRuZidxvf/6xiwUgS6P/jr0NYzKA/YtoRf0ahXQZUwgA/J/nVM3I8TiA3KiPj0O0g0b9N2YQdNT@AxVKnKpt7Kpt6gWpyt3tsraItBoWJOWb2E5RPNoZxFPytd7Uagcdpw1OYoNOo6EL9WZKoajwgXAlWm4aIybWhzzjVU5jx4c5678bEbHYxW49Wk4pIn@PL8nsCC6wuCE6LdUj29edldGVK3LsoLRb2w4a0OKRkdsOnKG3W/EcFZujKMiensoO8CGaHyedv99xYploG1YBDn4stSwXbJw0Ew82LKAxIe4sQw1NZyPWQfTGzJxAuVmy@cNCOP0K72btTkVJ2oigHA/4UaLyaqpMERvDQSBdLVBPqcmxjt4RfDhsJERLt2VARyY1rieDKSGAt3I6jnZvG9ns/eG2xsRpfSfS4/AqkehqEn4wBbpaDubPASag9voLo7gc7kCbuSeVjooYmUwF8ZRpE8auFFdC9kLfPwY0pCMxckgs7ZrIobihvmDjEW0y4xoBlUK4zjyeDzdSyLZyzabj8qmsUHtXVfJ3lcB7/nyvZT0AF5vVPWprea28drauGVgStoDFdQy/jKHBh8VZ65e8OMXPd0RycWY9UlWo@mtAbJtdsh77yRUwzhNFmGIqOh0eBHijev3TRj90YgToEkjieDgLUoMziEGuNc9CFdUiDbmM5T8sWbfQ/K1EP9OdKDFucQD@Cc@Rh@4ESr61lGnY0NYIbj1KYwv/dBmcWI90g8jEw6k2lmFE4KhT0mfxOO9tY82lvzaG89j/aaobm@N5q9wJLbzJtyK6eBx8ppFzEa5Ovzu0D7M1pVjB6KS6a2IE@IPvXki5eqFt3lz9fznsTzdjdZZ0ZRb3Zie/IIWIoeTRuT8iTieRCRvZO@e7b63fLNpkZrCDgf8XspKey/Bjm@eXrnA/V@o05uVyUoyoNW/apWFOrmoYt7grCuhPKjtDf3mQEkykQgdJ1hNVW5CDUpkcojQtTqSKXz1I1ddYYxsRkdY9pCq6ZGAu@oruc29Opt6FU3/4nYz3EcPixuBlHSVjVhdZTLM6qm2SIKeWTfeVB5D97t0G4IKE72h1TiQDPKyzLOuzIqxy/bEAWpsbxp@G@2GrW0FjXUgKAVRyqK4c@zvB9DkGhazbb4lrb4hhLQdOu1uksYJRgfRYXftO20cf3zmNiMDryOkI/qLLuX2mD3iWyvym29DaHAtIEW3HSwJ@ibetluXMkM@Ilob1qpncHV3txhCp4CiOuQjSEaghg/Okx1lPUOzXBVey2abphzhF7YkEE5RDYYjayg3OObaFlLzGIH5rWJclAVDOpEt0xnk/2g6SaZHfeqBeHmC2MMdubYceNSGGi6fhxLVU8UMEnlD4xWkWA5Wkn0/hGnlnGbL7gWEJ5V3ab1kcYu2Fa4SUkSOpGvIoPBp0NCG/K2M20640UL8j6AkSjfWTt5ZOKWXt9KNs2msZNi8bDYvNtDA9LkCP7SOYdWtGVY8B5wBdvF1nth9z6MxqHFJ8gsoLGDMKjGqYCD1/7xclQwQZ6yXkIbEDptwKuYrga83HwCCcXe2PbkeCaAzJ4yVYtvtFCR0a6aCQYtO7RCO058mIBuV42mBjl77wvoeNj9ogZfTEeD3VJkVfLuwcF03hGKEaw91b9CEckbYGEksxUILOnI5i2aeaA/DaidMgLTASAFswe7isV0Uyd4nDEdFuOdWcszyPHouing0rQ01nxToEFR5I2BjZ3RouyEbh7utPkRQmrnhqDmBbSAJfq36Nk0UoBdwNbdpmuAlQuw4fHmWd1YaMvB2GDUZCOoIEQm3OZkuKre0MDTmY7LlTWo28y58N9kZWx5K0DjUoA28Ybp3Q8nC44nI4EfjkAJn9ApXZXb34hySimG6ujQ9JIvjikaJMvuu1Eoz2mH7HbJ2vOi9ryoPS@t47V5eIisUDXsWTMqaEjOUdMJKIbnmNY07ekyHQ0NsOCE21hM8RnTx3u8gllEnDVQ3e955K@xiavNus1eoL7WR/uarLwieNNx5hmaxhkaXRGC2TEYveAymHcbXnz9EUiYRadUoc0QKSweKRfMOQJLTvoki0wo0NFQE5rR4ADRtJ7Ed8TTyhC@DrAaj1dt9IMqKiGhVpYOgAi66t7Gtm7XK8Wzqqvahviomy4pbZssBkqCPsA6VkuDbnMHoBuam8cunUUsf1B@GuHQw4LGICirVMMkhT1X16voQ@rcc9MZPhE5H5GBHcuFgGzv@k67x16tn6h/3mOmy7Puc1Kt1n5lnRNsfPS9FFfZPW89htEzPyBpuwNz53fACyd9rV1Ve58qaUxsyg5EKFkaldDRsvFRLhTGnhdVw0h@457YRBxC0RRFWJXINuAA9Xw71pCGwZXNOSqvHZWu7UeFYC1tfx0xXxNFSQDtam0hGNVNIAVcO2WG@l1OHE8mfDq1yD8qkMGZ3smIw1RNeVCJdS38ic6iy26qOHvefgeDPH2ozjaJmLVgddI1xStZqKfnH2cLdWfJZjUY56Biu0nGPu@SMCamc0aIZtFlnVEVF2Pw1@tWczqqVddBHtEdWk2Jt5TMYHGGCuILrHsfYYpQEBFwAyZyXmomGOOUMkCT7JT0lIUwnYXgknfL6zQv0VWwyOrOeR1eU0YVqB6YKRv86GEnmA9UyabOGEjr9iVFBvKQ19WIYUToOikH9Usy72u@WjKAfkyXomRKB3e8t87PLQLud0IF@s2CUXBvQ0ocTwafFbLaNRX2fqz2i3bTvwge1/j@Gs/EADJDGuR9s6UdMy823uYLxyvM9BMQowzzBJhysQVY5l/xbOkX2FFlFjM89Z60UF2iE8QXqgWz4sHtpoGpjB07yQW9CnbrEUdu0ghGNqPA6usYmgzWpFAxHTXZrA/cmV6KeRfeLir3m6w39pAlhs8nFVEjDgtkN9VLfc4m@3GT/Qx47um5n574yX4JtSMHbgXd9HTtuKrdfM5h/uNh/qNz@UE12H80Wn@mLNRg5G9e6@2iBRqv9FEP/12uXOwdjI/gBuM/84h56pSGGF2nmBgxfuM7aT9HMPzuKrFduo4C0Pflz1p6ToKFUR8NY6JF59OfR/Ulhih9M3bHBIvxSSTGAQORibGnqMb67m3G9KoiUa8NyM9MkvrgLMyKcpHc@rBg1BL8m8VbL35yTn9sqOgYO4NOIjsreZ0lOiVMJxB0j0Gx6xN3H6zu@aE731lKpOwGiZLS2S9AOeeeFShBF@8oglFgJovdU7meBs2ujQR4mhQoGWaqFt3kQihfet4Lh/@KmVC2hSpdtg/oxlvOqfrqW1HN6PpT/88YjVLCYYguZlgi9y6qXrZrYm7Kgw/kiYm2eaJ96HG1a27YkahaJANjnNfd0/Zuej1dXy5a7tB3ScBLPyAQdEUjs1tMTYI5IJLAQAtoNmUGdx3hNvB4EFHldpuuY4uXTrqhJOv1J85wB3whFMDEZ0zbH@clO/qpNibJQ59Fk8Wubh6Ti02mNphC1bTSbtq1ENS5Jbtv1@F22y4sQ3f/6qPrlx49Qa5M0DSUscZjpktOlVy/QNoSiEPpaLLZ2fARVHsl@BVDl1LVucuib7sboxbxu/oP/XBJhC3LXb/r6C5irY2LTGQXlJ@mmN0zzM7eq66borrX1LoX1Xoup/W8GLifFwN3djt138zZfYZdkH4PLQkI1W@wfga1rPXH7oU0jda6GhNczPjXWV2LUZZQXNSNmls2xHRcXyLraNoM8uAOSAGnFoK5JsWVbq2ikQTcLYE6mIi320T1oUdpAJbbN3x36BHdsfA9DQGyMUl023ZTyeTlf2IaKYBy0Jqw3vhYOeEihoxhvgzQvqque31FxEo9EIWnFKUyzAlylS0KqjlE/6ipfqjdHz7/x38GAwn/cW347ix8JLZLNKoa07nhcqz5s6HIY7z@sfou9YvswLqaC9SCkplJIpotBMVTVVqgxA5fQH6s3K4Xr6H7Co5V9yYFeK@tsYFfUwedSJTlrgAZxPDuDtMdpKdsx8@brUJbUXMVRCdhKOezQumUjuSpYqHEDHcFarIkCLooekigN8UEo1qojeujQna9anwvOR0tRQ6X2ke60bH7tofE8WQi@d3bNI@dtaYAT0COnYWQo16jKbCif3DAQ1TXL4M9YfZzE6UEMg@t@A9p3pj@HvSPlK/wCCXjLQ3qPVBjdelZRC5Q@DeXI7x9OcJ7YBeCAaHchfAeqv@waKafGD7FF3W@y5NNiYlyUJpl9s/j3mq4b4@X7xwohVGF37Rm7l6rCq9lKKgcQ60UiQpumL9mojOH0cqGEFl23MgOSvVKppkhnIWb3UKjvLBf9UbsTbfDvidK8x1uVdT9gRgNW7pDXukCftTxxlwYAyrA201ENOtA5okKs3Y7rF8lt2FWE2KYM9NBFd/EAakARn2QSOqRlKdG0wCdctNBkhNTAnAszdZg/S40Hv27Ee7h1cIcudNPGXBUN/1mq41oNZWHU9qOmEC9Y2SZLx9V@g81/kN1/3iI@Pg3ex/F@6EMPppvf7DmfLA0f2zR@fjPeZ8BdcqAjBeMaSQf/zLmk3@M@fDDmI8v0YTZIRbZU2THhwE58SsGV7Yrf7Sk87Fx4WPTwiftXh8pn9KwPv4Rz0f2vg87KD4Y/T7eQfGRkUqEQ3rBzKHqGb5C2UyElSfVNYMc2cb8SaP5R3O6mFG8dARLSPMQM@tZRt4obi6P@6j7/ngp4PJ5StWGhuOT6vR5RnX96PILvEB50od@nhy2DogRDBpuPozxmUbl3ie7PhOt9uMb0kAJamT6pMMDVitQBj3uBTJCcbAwnxRV62MNK3pNLZV8@K2taAxeH7aXBn2OWvkJxsU6aTPtRxPzD2dbPhPXoXw0RxdZg873IPxM5LNpmhRN5aMLxD46JfXh/jBd2kZDF@PsB8PYIYa/pwUzW3SBwHKry4cR4qOfIHxy/cpYT2xmeDsWtoKqQLVhxZQw/ucQaNGiUeqjH5h9sE0gpcGcpXGinbzu85E9Qh@nYoX8qhS@rKN/ddj6GxUtfL@lT5fvVObRNHwj79J9jBFzMJGz30WH/9iJ/xtV9Pe2Lf/xz//0T//yb//l//zd3/Z//Ued2f@7v43/pr@3xdf6x9vlv4dX/lrg3/5LzEz@QXTr/3D52//@97//@//5L//jH/62/9P/4sz0f/3n//bv//Ef/3fd/vGm6dn/Aw "PowerShell โ€“ TIO Nexus") Using [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s `57*len/10` trick. `$d` contains the dictionary as an array of words. If you're playing at home and want to fill `$d`: ``` $d=-split(irm pastebin.com/raw/eMRSQ4u2) ``` Using a golfed version of `(Get-Culture).TextInfo.ToTitleCase()` to capitalize the first letter; I don't think there's a shorter way to do that in PowerShell. The rest is pretty straightforward I think. The TIO link has the whole dictionary; disable the cache and go nuts! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แบŠแธฃ4ล’tFยตLร—57รทโตโธ,K รงรโ‚ฌ5Y ``` A monadic link taking a list of list of characters, the parsed dictionary (as [allowed in chat](http://chat.stackexchange.com/transcript/message/37656420#37656420)). **[Try it online!](https://tio.run/nexus/jelly#VZ0/Euu8kt1zL@PFM5mnvAMn9gZcLgeUCFG4Igl@AChd3WwmdORy4gU4cOJ0ylMO/coLmbcHx8/dfc4B70T9E9AAQRD/0YD@@s//@z//8z/993/9f/9r/7f/5x///Z//29/9mz//r7/8/T/@5e//6W/@3b/68//483/5yz/8z7/7D3/961//45@mqc7vqb7@9Dd/mm7TPpf9ohaY5xRyL3Wb1sCy5vYE1S6ZZlHel4GMzxCx1TJBr6UdQVuptwGMxBH6rdfpTsWzwvdsaUAj6JlGb6T325jc@52PCmikxkiAdLUIB8yDhicf4tjLFpihVuoOaT75HljL/t0uQiQ9v6eehGn9AkuVhNoJnXk6uiTS48RUOIb2PGfkUAD1HOH7TDUNmAcNT0X3Y1I@zT/sLajqCNUtM55y6LPO59olofRWFO9UkZdOw0lauaV60XAs9Qssd@aSJQ8fcUF6lrTPE6FLRvjFMtmlFdcZki@W5/DP9V6nRwceLLevHO@xTnVDKCeGc2wAiFvKHXDS416eJVK38h3XJd1qpG/NEwvOmtMuSYdll@RTjfRUQ2q9IgfWNS0XzIOaSAEtDQuK3moP3@8MlKU58nRFqVvLidiO5yR5S/Eam2meFfQrSc6CRuCTtxs@5nbL/CibfSXJNEjqhojhWCPufVrqtIHWsnxJX@ZfYAfV@5PeVv9AVn1ZffZ0nwtecV/SKtkI0FlWxrqcbMP2bO0E3PZTmbMXcyTV6TUAej2PB/X8xwn6ma3yB32f5eNwTB3JPQ7/PDMwTb9jI@3zgHRh/jmQiuvENuo4SkZug8K/3ie01gY74UkxoXAYsYUEzRciirRHcajLOd3wgYDxJtXq607g91TVGRWH1aYWJLTW6SsJD2t8@gAGdqSvNZErqCzTTk3kqEto9ayGNpCOIdqduRmQLoTvc2KC29MyCYBXb21ig2Y9wsaXN6x9AEM2NWXedVwwfNWjmFRY6bPyB0hfdd6o9QHDtylsUUrKlRL1rKZv3yRKan@m3LZB/aLQ7GzQ2IWZQEYawL2We@7xzXqf7i88KbCR0Gx2q3h7oqJ30@F9zplZZ1RC4iOe9gA2QZ8JTalLRO/E8uPYAHWWb52Hb8WH/DxOVtafyGyrgJskHVzcbAiTCN8Q99etRO1wtBaH5DEDPSunwHmB3uOxXjAPaiIk7jYty8QQC/xeiWKmpLMCrN6CzRfC21qLTigC@OxRN1zu0wB6zZSIeX/V8@hE@ux8lEElKCE7VGqiWJFXdcHHvmGM6IJx1PEOldHXgrbw5tV5FqyEzEcGNSGjsPqGvsPwScEoWDsdhna@0@nFfGr83aTb9TGD4NjviLpL1BIlxpEanZ85usZbmhAiRfdkYqdokHWWTIOYxqSnpikqYEg68HdPjK6PMNI4o/rZaFgpTIwsPSAqBVxtDMAPmp7Tm2lxaiI9wSTcbFzwGDCc3oxlXSnoU/aFsa5F8a94jZ1ZtM8UehSLY9oTM5wfODXMKGysESU4fVjoMsqxD5xmgVwYKVsWl/mOmpDv3zsdgxBiQbVxyciMYnR5y@v6KOtMxEiW1IiQ@LqZ3zFXvIXLeUJM7X7mfhH02rMcAX2bCB3ZurIFNUAOuKQD@qQAufCdrVlgKV9VkVeWKZcK1/rQZ0Fbp47u0zIN9WNVHwUabgqZPiEyvqVLtAJGL0jGU24Q7ByCFEnRS5YySyKW8hk6n50SqifTcsZU8FZYEcoNYmHpM2AMRvjoAdSiOCHzSsGwWY20ETRQCAoKctluFNS34Sz1NyYD2cKuwwRd@bzCvDBQwPJiO26kYsEKXUqjD1/V2pAKYDQmqVr5JLWWmGzeCj5G8UYLdGLU7zBPKO2O9MTzPsiWGIrZXAWNu0s6oMOq6qnqxCFUEBNQ1ddUNrx1eiNYmmZK1JaAdNHly@jlckk9I7HNM/jFGKzFRptZ8/0lCaU8L4wxL6xdRk/WvECUZS5AhJSLpQYtqQ8v04B50PBU4k70UvXsaIXOG1umEwk7ma7z8eCsGwjHBbMRAJzWGwV/rhQoPwHw2aIUnWx27evyuVZ@doAEH1vVxRs1SkRa25BDhW0HVz1ufM@z8RcCqEEzYKN5funy5Qt9DxSN@3S7YUhklPd4nTsnFiFnAbVZS@82qrLeCmoM/5KA6no/15PoywIVuCbCFmJLMSEHQDuy0IV@MharPeuA4YTYdv5G@o/cJ2owkqOfNV00Xwj/eouOxoB@NTHmym7ciQ21oXKhHswyGyspHzSWcip9AENS9KIHOsGx8dnxUe/qVe/oTe6jC3HiB2qMtZ0TsqbzyT3pRXoaie16k/4sa0wq7hMj6IrxbIzp5CrSHW2HixgZ3ZPSmTgAcOAjklrxOwcnLs8V3z7trVzAOByhWNOGNSKfCyNHDCphfUFyNcPpYAKfU8Fc0@igQEl58vM/fYFOMVVMnpw2SSTmOSbJgdLvknoypnQG0RiFnAXyGfEwtIL0Lt2uz/lM07F@SV2SamP4GYhIkvXrSEpKL0r9rjbtElI7MZlpw2STRN8m2SX3k/ihUFI@IyUfBLLmPe0X0TFGribXGUs492fJd2ZMyUhoOSgORm6k2As/WqkoigbUqWgJnmjFQzL4qQFOILX2lyQd6h392j2jN79bC7ZF85PrXZJNnRHHjIEswzkmyHdOi11Co@cBSIbBL@ZIfsdYJ2SOOcp9HaVwZW1fNZFyYnlyQsEGDe/8@A7E47TuBICiTYQYj1O96PLGR3dUPIYoiyvnUQY27WBw9Ov3lSuJAGjlxwOSiwhON0mmI2vQFshwO1/RAR98zQfFoYCjdBgyHCazdw1o71gpMLEnSbpjlceBnYDN2p@Sw4GPKl3fwUgPxVpsSPidTP1J3XNryDVfmq8XhW/BPNXkCoG1dwPkf5kkoO6DlXoRHH1TAJleYlDo4o6pmiNSb8AkFzahBb1yWVmAHXq6aL4Q@isaVZdfwLkxqu3GhFp7Cb/tgTWvOxepQlIZFculHBLGv465D5Bv0VO2c2dGbQc2l5zSOqCJ@CJB84Xyz2u6aL5Q/itf4iiN@W147tKsbBsdM7@YvQHTFtSE8/DG6m3g0Yc/cymoXCj/K/r1HFGdSJMN8Lf9oibcFQbzkIBdTifzLYhBHnqf/ZGl@BglJ1D@a1Z4@8CM/VELy9@@sOEAMVBT8QySY@E32BvWbknyPrd00XxhvZCqfRov0tN2dCE/l1Ebbj@HZlEm9jo@jPa@gFJ9py9hvPs765HlRcE02hwyDZCKal550WWlUKB1aLDgsHkzyd9SsIYP6a748vVgih2ga6PMGcOp0lT5mqpB6yzbPgMIOBc0QTYzyXz6aR9qvYiOh5LrNNyUsLNylGvEUa6R5f1XyCCNjZTlsEJg0FAn9CFVS9dBjL9yCUZ7gSYxG3Ap7e0Y2pwj1IlKjT9jFh1SgT7rCPTBq1YsG7rsLBuOyFMbnnIxK7AzBGNLCc/DCMlnuehhLEtmSgTIKN4u5ZDZuNkAgMvYjviAAVDEAKlyLFSLxgRBw03vVD6zZBr0mycDxLLOvZ73zDSwsalnWiUxLKknm6SAeVATKXLOdAFS3DXO4kQ8pDzbb36K5TvgUFZ8W2cigyLIeUsQ0LGRXonG9JyxVmDDNGuqO0ji5DAyEI8@ta5@P49bwTqxIfw4Mxm6mj6dlc@o1hHfhZTILCv@WLEhMYJ3koSDVr@HnQIAnujTfKl0JvD5TmjiQKH@9VVA1MMvB1JfjaNm1KF5iu7DRUTpgCidGuQRAv3zrD2PWTseDgqyc01k5lTZJX9Lpb52dDWGqxyjIMzaN5g13J3HvsE8nVoQmqcPkmyvZ27Ajso0p2le0X8FfgEPCAycAA2EzYM53TjaAQ03PjzdOsS5SC5S14JQIALeuTTshBTcM@xZjF4QI5VB84UMWOY0YB40PJUw68Hp7dRE8qYfVuNMHkyqQcMrPSZ2uIaYYAIY8sF5pdO9D5DTPg9IF9IXr77Uia8SNF8INUx15rROX3oaKf0rtp0NElccDDONIRxZAEBUja0Jk9bNMMg2jfT5VpUQrZiBbKJs3JTpuWemby98mAOdGG5vSvzeM/Nzp8N4BRs/ZnhpzOiEPoU0X0h/Fcvj5AOqV62L5guhqH1zEh0xsgQwjHa/g5iIoPlC@vsmN4pLe/XocoyOKdPtUPb50tNvNF@IiDpmOAB6B9I70YbKkZJ2Y3PC7NglDDSc@Ng3@x7Q8FS@v0uYd83ZrYtQ@bKMVUgNSL@VBRwkv7LETNKRTpuSmbFMP2c0jDYeZLkMwitZKUqIPyHysaYMRJwcMhtwj2R2oyJ8@oxGxWYmmDTNzGzldOZHUnZrkjfD5MsEom5cuCXNFyJYu6PfIcmxUNbEd2sJK1sk6i0cEgTyZYLo/6SQvltIzRfSlY2kATarZjcrm/l@zWqS/I@ipznNFzLUcSq13Ec36qX@RlQcJc2R1TNjr3lmHVUFzZoaBPUBly8jZQXKb32pt77Iu1SUlaIiX2Q36FQZoMByYS4Lvjh2x2bMluaYrcNhSzSkMbShY0yxgHj98i9gHtRETFgg2kpMtGfsdLlgsLJJF2ORmV9AeY4lbBN6Th@RnypuQU10eTPoZ3/m2DuZOcAPiaBODODYAPytzthpKC14nwpjjpm7ZSGlPaqKttAMkOMumbPWyL4gPzfMThy5Fz9z0yxkGoRl1kA9wVABtsttkxtaEpXAqr1e0HBTQHZSnEmYZHYp@/L@GqpY3zQ4KA4F1rKZI3XeaKw4GQhJbSNpG0Ido6HKYU89Nwr@ZL6ZTIhNfSL2I2Ys1M5ckp3PWCOcsX1mInLk3DZKJvvUBM@pSbJFttG8yjEbIRO3LAfExNXY@btPmBqT3DFNGMyFjBQYRbWzT7RTREIckBAnhK0QnhroIlnp/iwUCOrQCIzDl9TCejJxL9TnlbRq8AEd6jFpvjD8lwWihIid08jxQG/K0jrrdbxvq5FFhjTRMzqeA98IayMqTnINuySGOYmLtiHnC@P5W6rRfAHmQcOTr2zVAItCCQt@NgzjxyMhwIF@zGAt3wGMN7AOZIie5c1v7fTVY0@ucYKiGU67usQgau6xOnzRfGEDYpAOmAcNT8Uzs7VIvuHbQPbSVLQciffy1bR7umi@EIo0TwPMg4anHregGwHA98nZG2m@EP4/lKNOiucHM3S3/oZPDpovhL/NZtcBdLKv1r9EfYXdmpdyICYbqel13qF3RF000ZiroAj4h7UYGA4Fyg2f0YHl5o8zWrmQaC8CQ79i2BJyFsiHr1yXqKg2AGLooCaiViu@OBOpbS0meCGh1riObT0z0@etQTR4QXyN/kQELun5ZBPUn5irp/e06h2tTqL6uo0@mk/fePnCmMmGvTOrEsbLLiKud1nfacA8aHjylX7GsNgFh5OOofTzjkkk4DeUL083AOnI9uKntsJAw1MP1fmM9JNrtunnc0LDTYLvM9/QQvwcgtFecWXqcrc3/Tx8mgY3NSEB86DhqTgMv4CVZRA0X9iETEnQcKzpovlC@mP86dDSgHmQtNpIjrak0k8agxlw9dxIRruBgoS1xPT16VvMjR/TDYX1MaHiu2yQeNIjDq98SShdRidW@x5Wp7ncZbh3ySgmoEbHKrd6OXGxx5Gx9SeGRw/YhDwmG8/e4bfBYcs8@fCI8hiw47c1MQ26aCsfsD908YHl48N37OsABGv3zBS1J3uWxyTLIaMTs8vHdN4T9PT2iStZDswudvRcLnFxSiehxzRY2eYbQqxrmMED4GTTnTSATjYmRUrZjsTSSh0ArdZpZ/9ImKs8aP35sKkn2sJHnmFdBJgHNRHfJifmpA0iMWxwelJGHgxbrCCF44KLgV7fSb7rRrd1u5ygvyqyVYYoQPk@8dAdDb0DswJER3Wq2qR6sOXSTlXIDlAK9DQWZ5OfEqbRjzwSXplKrkU6yEt5/OtXpHDVxCOISivmG4@VhVlGoQYfCoX5jCAoD2tC2bNvFNmPne7H2Ol@XDvdD@50P2ioGTINkpKhtCrhOJB27H2ZVHIMhouURwpZYtcT3YzB44F4zozgJ9OstXxQEykizMsfJfqbR7mj2sGa00UaUAdIhXEY0WWkGdadD2xBuoAC3x57bQ/ttT3GXlsQ0s1dN5Pd7fWJXPuzMdgNi5hOeOEABKn3jBM2hokGWY6/ARUXmEs55d9pv5CaL4iNZ5oCFcvGsbyjDWFBnS4nMrbqqMXDN4LwPic7hHLy967sPveRuTQ5deB2xSP28JBGm01j39yJVv@GLOKcKodECqsfsrqDwkriYXPdlyQCYXzhkmmobDJNfqbvRXL8lQYMJwW92j9Okh@wJKUTFlEftSwUiADT3ceY7j6u6e5D010DPtgk1GFAHhIaHDo/TizgPLBz5mddUE4dUCqwtf3gDvZjfIrrS5zWnKGN9w0phndiBNhdesCy56G17gesPV3Au/N7nWi0lmn106t34k@4xRMX2MMtE/dkDdCbAeZBTZQZzs1X4diOED1RNEp8xyW6XMak3ndJYXuyqKNdRke7sKNd1AUaJAoMaYLQdTtK9uHJHVPDLK1CuxjDSgnzxoBIZtJk3GhLOHrgS7QYjS3PiTvoyxOG4EvG8GzBOoyLeFiu0agsK3eilpU92bLqtMuy4mDKMgyylsvgapGZ1bKWG1sCw8q1cEc64WsvfsBDkhofCsatJn1hk76ssby97CUK5AIrJBcNMl4IDemCZtpFVACHB9pPw0eIMt@@iYQxnBMHgQtPEyzW1CW@Q2kw3lm8nYrS41YB@wCkOxD6UVWXOt0osBIRxFczbJDIbG5AjT0nB4xyjR4Pm0NcWICZD9k2FM46HU8GRRGnNYHJN2Z0izVojcAUJRhCLTXjN2wfTW4QBwUiKigHvnGPD20F@2BMRny3U@eVgn5zjEhONA4h4ZC1b@vIgJnZcOYRQV675BewpwnQkQMnPrC1YFwVWk58kJNPol35ckY7/ZQBR0AdID88@EmLjicWENyi9x72pbLtfXLa8OQZOpOdgrGvXVFhG9Nk1IGQcNg2JmCfbzDWccQkxMlm4AdxlWaUuEAbcv1GDY@vM9eCnxNt9wFMlBpEJxv7HES8SaUls1HUneck0VakvHVGiSXL56SX7Xyj8c69ygce73IP@Qt7OQB4RfP/TNPsO29Efo9r09ytjSGqdRxfIbWYjGF1LKNjkxjDAOTEfAtCvqWo6i6gwykqAE42b4DTenCtzPoJPLbCkMivPejoogwLRaJqibY/ACnSOUUS1Frm6syTtcIlWqSnpQXdFQmOLH@Zu8cOjBeLC09OLp6cXDw1o3jGfhNSlb3TizbmWW5xoPWpoe5zDHWfhVNFA6hgkPB0m9VOJ0cRZanYRXiyjMsg7Tmsz560PnuWI7H4GymbfadNkg75VwwqnrA0e7pZ2Y0JqGjVAh54u0D5FrxU4/jDCZHydo4AuTB554KTq89zwwn4ALSvgQ2ABiiAXoWjgOe5L8iEUx/qHB/qxLzgecY6jAt5sIR/ZxsRoiB/j2dAvhcJV8luPBIPDaKThgvWnsa2mcsuGXkTBO1Ie178c8WgwUoWu0cjDePy5su58QLEULDuiIOQ7AazjaSFdEOaxQd14blDkXv3AEZ@sKU1ggUBIF0oX97mYbjme8bzuKYFUBjuruZhJJvDRpYvdpwr0r3jG@f9rr3FTLPWkEygY8Sxc4nT4Sf9nOT5U3H4xvedmuc9DZgHNdEIcq5Lumi@EKpWacMYL@@PaUNJc2R6HnqcAwPLSMYJr@TLEFGS87CgzftD9/Lk/TlhkZOEwMOuOzD/RvTPI1AegWxAg8Yt7z@UtB8sNgHzoCbKvyEzxRDJbfpQTbG18XZGilkLjkblMeGlbXCnIMcVhuuxpPlC@lu9VKheTyGM9gAKRNulHAbAhBfi7qofTvTjp/Dl@21QoaPOJuT9jQEjYB7URMqh96Tquvu6PCOSmUBQH6CIaCbg1OhbmOQ3W2xQE/FxlcnD7p0LNC0Vw4ncbHYxD/DQPzBGcRGdKgA@MeD64WOjmYDH/MC6/4@pYgP9x/Trl4vkd8400A6p@2mcviFj2eIH3uuHX2wCd11x8oPv94Nv90Pv9qMwhnJyr4TUhNHJ/fB59SxoBEZxwgznh3aKf4yd4h/nrlUBQ2znGuDDs5T/iLuf4GPfEp3WSwZzL5@IrAE8C/dK2DAziYcYfHAUieTJe@FIjAtoZ418Xzz8@srcP3WQ17zHKAxALeTAKzNerihYbJpcecQw9n9xmPPK9Oh3dGYvtBCvPSUK/MwP/GYFXjF/slkrhiYrN8XXKbr8FTVshV2ol7UVL76inVhx24RNcRmKt0SNA@/XeXffiY0Pv04wQQ9JJSNpGTZBZ6y0LQYoiGyL1@k9cU9jhbmoiS9Dfr5KkFwuBz3xi9@/MnN3HaNlowdO9pLoCDuxFctbnNWPSf01p9eUfsVIe43j1JEKax/ZNhPhuqBb9suiMO5ZU@a@0OqHIkNq1Whlf21ygQ0h6Aviyaw1MQncIVvl3G6Z6W5w6M@ojWue2H/b7C@tlHUaFB2b9Wpsc0nzhfGYTGseB6aXSyVhvkm/8YmDkJBr32Edp8F5hEyHxWRGu2q53y8@wDSBF0VwzdwPh6EgGxQ8KSb1bjedFElgHdhIrFpuEaHXd0JJC@x4YtdL8KK4lbsHLvFOZWL1KiwRnBL4ZV9oDoMaAfEW2X@AhidfmZZjNh4tIXY@vJTjCfMxR4QqTZ6ovWyzVp0h4Lk2F0znOSvpZ0PIN9Oil@SsOWQjUCqFH64ABv3mCLUvMtVPbCLGU7fyrDg9v9LsZz13WmgZLRTwQPNz8rIbBz7mxGU3K7aY1/Mn2v71i@lZSFfYJjWqNvaONgDIrfrNOs9b@UmKhzjgIRtNIDaalJn8heBYBgkJjzVR4Oc@LfLZZ3zubWJ3BZgHNZEeusf41OQLF4Bsui9oG9cEGR3cMOFUyoQuTdsmbjI5SP@AklvsDGAOONI3d7npDet4RaPOaCuHHlscgZ8Hye2rp8Y9WJsWSLdJJyU3vwOIAY2kzozqlceIA/FxOFfapm9BwvAlcEhv4/zN5M7TAxt2dG1IlO/86IbpTf1lun3xtLRiIXPDRTqbtcN6E7TW4/K86@48XZ3nuyaM0AG5n/aTAir1jqLpRLkkyVlA3UUPqAxD48FNtoPbMB3cUp@sJajANCS0OuqBQ5EMH4yMNhuixMLI5m0wgQ0eab4QAdeZAu@ZvaOEfpzZ32CxuGVY4m15WEhtbM43zn03NevYIUfSYY5gAtlmQ2RcJ0SiI9YiAHCyEQmS02I1FHis011YFXOjgSeJwVvmY4KGY/QyPEevQ/Rb/qliuHt3jffEYq8LvGTR8GBjZ7CVG59RYgi5lVl9y0YzlJAdcFLXAX50sKGE/DaajoBin9DSw0sGPWW0RDZ8xWATQKdyYDXKT@Iy90H07096F7wQ8oK3V8SyBGa/gesg@iZ2HL6Qs0vSj7UlAE7aOrrMBJ3eyh4e2APQF0WgjFfsvkOKVPRYkNsKbrrbro3PQH6fsYoUiDiw9baVN6s@7Fk33TuwjWsHNpq4bidtMgDzoOEp/QUua884h7xp0WujQezmtwShiTppIQ9grIGXK6JrrB0BdEooCAF0UjfnhPHgptV9AJ/R9fVPGg0BkOCvlw0RCv03rEpc6AlfjFF3zEZ39ab76E139qY7L@Hbp03rlbsulgRE8nafWfxGUT1g295IUTQA4YQm30Wk2@ZE@ESAdhGQe5sGPC5Cgi8O1Ow6Q0MDlF03Ze5JE5@dGzR7ouA5RIMu@vhR@gockhF@kFhrlwUvCjxozDOddpii7Jxy7lps3wvK1A5jt53tyl54nGYvOo@6X2cKdtTsHSe/TXhlhEtLFAjcJ0XfeQOpEyfihvmBYQCRgS5vfjOrbxT4@cbmQUBHrG/0T4DwPP2GisizMzfugO2wLN9PvyUGT/az5NN6URNGgd35SB7gDAmHyL5y4xqAA3LbCV42TUkD5kHDU/p@WiuROPsjQjXOY1ViawOkqS7e0Nr6zqi0albumIcWHoEtDx7ZA6TfsA5soOckTcvUSkdclgEIp6vf8y2JFJuEZV9o1m6dCv2igy4HzVgN4mKnkPA5ChexDblsXGhaWnjsN2R8LqftomjCii7XLjBDLccpgRzCly46SecGPF2SXgtyyyWe6ITAnDoDqJ51lhBIRY6MvWaUOaYJ5ex37K@TGjEaSIOZQyfDkXVn554cab6QwVds9BgdLJHeeCzpovlC@XONx5Df8uwf335ztJJ2R1sRWAbOp@iBrSnHJ0ZGjmusZQSVy7HgRQKR0jctlxwqBl6BZaCfKSNyUB6IuyscrbONBNBSZ9jp0Eqn/PxiB6f8QpgDgzoT3shU4It5c2iX@hgro8fYnD64OX1MXKJzkNcMH0WzyD3v7CoOzv8O2syGpPbYOwyE1qp0rhBYbwwJBZTIY2JsCkfjhgAcwQuMcudkrfl0IZ5f8U8Bh98XrWgwOjt0Rewxrog9eEWsSUx6Dt1cdvCqmpCzgLpthLZKy3eqfecXCIJm4zkAkhwzk9j4nwBO3G1y5Frr4bPDkJobgppIqeAegN/qTfOgg2e/TWba2gKZI6fe6dQ7neOd3rrx9pi@/5JCM9m3xP7qQSs3k7g4C0Cnxo8JguM8rZT0m2VCB4wmA4gAyFFe6GUN7IRe8dA7Jb/TA8BiPKak2t0z6RYfIB58dmI8@Fl448fh9sL8Jo5MZr2Pt6@5zEyxIx15PfYRHRrKTepIqttEwAT80HVph65LO8Z1aTZvTXvM7A/f9Z4FjTC0YjwfEl51xFmvuL64PAsQejbUjYDWTaPs4eSt7gQ6MFU9aAlgEpUgYx06JB6TtQodxAfiFtaDjYKqfT4SW3lHOHXG1x8TnxhEz8il/OvXJBnuK5efAfOg4clUrN5AfUG7fDkIdeoKO1qoVQUtlu/rRXTsSVIOvBTo0PL6MdbXrQRNXLo@Vp0UBVWRHluQSl20ECQ/TI9Moks/ymi8S9ooWWcKzfcc4KNtQBIdsboNwAMD4Rv7HTb/nRBu5U@YvgEYZtURZ8cuPVohGuIrxk1SoFKZGNkLO@EL4aTUoVvwjnEJ3oEVXBOneo1APi@WP72p5Ph7bM0H1AGNpEj1hy8keeMfAEhyhEQt5iEWHWEZB1iOogv2jWiwE7QSeODckcka5croYP/tc4YygI84KwUfrV1rJ2i8uSlx@K030NbK83GtPB91YqfJ16y8hSKgDmikEQo5UXnJOIABk642MOTdX6T5QvnTlPPwe4RiyE6i44Pf1wgtX4AicqTiwtPfhpveKKgJY5DsQ2vepUWkP6/KItHxjXm5E0Zdhy@yzgTlReYrcroNQAxZ8Wd2Rr7bzjZMFiEA5nV@sx@oWDUPiSjKTeW5Fp5JI9H/bo0b3rG4kQciLI@sQA815I59gJx4t5uhjCoMOYYlUXXDqQDSfKH8j8v1UPycxxqVB52OZ@Jj@MEsikylXu4FeY9dGJMwsXNggwSaL4x4WzrnqC/nGK2e6wGB57gMVeyoHNoxP8aO@cFNloObrMfYYz3GFmuQ1He2hQFSHG0h5tEHFtgOrp8d54HS5RIOWOM2ySJyVvzLjEE7L5gHNZHS4YiH/PrFoA7zoCZiiK9N0jxb/zgnrokaqXX848Sxh5B04Dq/0xcySr1JJCyAGkzWH2fmDdNGXHUHMWj@FaLExTUhPYKwaO4D6BRD@MqjfJVH@UzCOKvqTJ9D/I1IAGKJNaIqYxDdpmaThejXfP5wZyRzLvSC2TxnlXXi02GFUNE8uODF3JXLdS6xvOqm1LeYMo6LF657F3Ttgl/VhuarTvTgHTfjhhsHBdpfFPRgwK4QfSgy0w4kHl2tS2ZIlFltW9RphOvx1ye4S4A50pUjjJJmIIB50PBUVO9EMVNC4y3/X7Ew7X0GU@FEz6Q/FwtqAB17M4xLskPSgboawjhyuFXT7cReDKkNjKxId/3JERDeNs4/ugjLUN5lITsDqPfipNcxqhNAEb4wmjBiE22ke10c36hLhjxSQ2KgDqtSI/5bBGm@EJpz4t2V3ofSCLBebjopCGoi5fZjTT8BGMACpj5QgUtlhj94UMAJZ/aM0I044LYap44ELFJfsLThoBIWiGiXmvjq@L@hmtbppyQTsfKPc4L0BiuqnE0puODqqAA4fRDQBCidoPlC@n8V76ZVAT9ePCPiTVfL@X9O8W32SXm080hYkKJhxlzhtF1Rx9HWOuamlcMQkzH0CCltXTYdSC18p2HZCoTfMXyfvAXAUINhaxWwkAVAiHY/oTb@S8qRsWDhLCS1MQQCyImfbvxVFFC@jVHwfD5pvpCKGrsD6WhDY6WzT8N1KI72w283Yolr0jr5rTQMvEaBQQrKKx0ClH5dWmiU2ar0kdud5ptBIxberuQ0StvJL2DjmWXQKeJSErEJEYsPQ@Wd9eV5IVgdF4LVcSFYvS4EA7Jxehc2ew4KU1bmEf9LCkCnyvsLHDH8q8/vRtmf0V5YL4/4sR1h4kmBgpZ1kXp1oz9osrzoJM71Xxe@jjxDyrg9ji/OBOmzN4DB@bjd57rch@eL9N9vVTkz8iU31m2Dy4k6LySF@3sAeL3p8h4OrMGFdajckCSXdIDdTcWOdi0aiPCObq4C21AbKSzqkQyYME6gbVwdC/UhkddOmPL7ABuCj0V3hTF2LTz3AZgHNZGeNHaqqi9PAHRKs14HZqsOzFb8R4sL6SjWU1fhARmMqUMhpt0Tr1ytWIxzgbjO0UudrIIn8@aEHWhIekiTojJmjsvHFavXDauVVyO1yT4VRnoNg8Wm9fE2VsUbh40mK71YmAG/uUFtmUJEc9K0w9vGDm/jkLH5f3aiawpEgqwo4FM3HPxq8ceT86AmUmT7TPFB7aPtepvkn/mqO96v3qcYJreJbVqbcGagxRgt4r/zTx8D5MIH3t1WayXtUuM/egVdigyK6xYAUdUd5aQYqh5UH5Qjngrr0@b/y6HHaCvetxNNtRAxrgqCr5UBmIM4bnLkyhYJjqg2JpWkMlJQsELZ/Gblg74VxmJNFycD5MmLzhovRQ45/D6Kt6JFN8iYNhuVdR2gEGwFrI@OJ8Gcq@mvOR0YIy28Gvb4G0@rtRQ3pEPX7zXERwikf6eI0bcOO/hRB2ZUYmgdgSdBa4UVtm@GYlbc0micmo@bmMUaCDXZx/oAIyvCP3B2vKUKG1/fCJ7oF9SI/PCpyza1xSVBTxLn0o0nZUxi7GFwMuN@ymjDMMQTe0ohGyHmcAavJLkLqKIGwoix8Bxbe/I6pQBqH0O7wsSF7ZOLWX5Y2zEZV2o3/pOJy04PFgWDLj@MqADwlN1xkOKm5bE3gklyFshnKO9IovrXoOF5UD1GKe2J/i0klcc/rAVCuyQK/mQqsFPqcqSUPZlB7cz1oOFI4NP18@TJQscuqQSdV@ynAjDfaEsDgNfZZ5y7bjA0afpvFwAiHf/y0nim0iXPTzYNcBq2mtuw926XaXeTYYpBXMPoxnXo34M6gEfymv/tH1Ia1Oj9ppt3CjFvNNTiePN1yEqiwEZdUxL4Z8OARro82QGoqplUm3CZJTbs9bRxC2PjJYwtM3@GYj@VsKD5Qij@5MUbTk/KPPzwdr8YjHdg2HDOOghk0YvXAwEQLs6OzCAoxflkF4fcR9l@sWy/WLZfsKFpa1y96QeNKNHQrVjvCBnhVqu5jMqRbrGo0FYMk0POgkZQoEyfOUlSYx4aOi9guEHoRYLQBV5X5zQeA2hrgblH4510TZfjNOzsuaAiO6txe0Lj7Ql@YS23gQyRRduk32rRNl1nHsQYNtxWFbIJ4umbxkgbF6wdFCqjGGxYAg45C@qAJhIouDUlTz4lLu9sOwd6@8SfGKftOMYSEg9wYiw7N7UDIrId/@/T9nK7McN3NP0lLENawR9zteLrlEgAW0nNAtrYxGtqIvEvkE2jE78BKP1G0MFohnMGkzH0wap945I99/H8KmEUJ9zT1nAPjgt4n5HUg2urDnzhA@Xk0KjM7QTQdx7pzurotKGu@klH3MPTWBCPlFT9jvEviYFwe7JROhQZ/wPV4EUPlJYDVfbIlc/PPApqxADjJ5sTJz0wDgrBlZl7jL/WDETYwv9iI9ExplUuGRDFXbuBBuhlDq7hNm6phTE1vsPBSUk7zkrB/a/2xxlrMC454AySn8aehqhdAUNR9csX6mPfiDRfGP6dpV1/h@3bkmzvQXTMVZIO@AodxjkuV8jYQAmJZ/Xx/yOBDM0@DDdpuNBPBapKXh2BKxNaL6XfPKXelXhtWQQqlZVr00T5v9OAedDwHA/hiLX7mjOqrKNApaZrkN058O@45MHlQVkl@byUxqskJTsx8MafasOdhjIz1CIqhMx3TXUkyMYhSCQbpc6vmUdW5isr9YXV5nQ2KC53wIY93rjFgdmEBeKQcOA6G0BOGkoYfiiRsDEfMmKbp8vHAUznuPzZkT15x70xIZVFXONp@hsjA/YPftXvSMXJ/91tnX/ubvB4MA4j5YkhopPROWm@kP47xS6/Md3t5y6daBX6l4HOm5VEjFwcCdgsAkDtrp1dbvhxt6/hT1krMTbF22njBc7CAxMIKTlhh9FOHnV2kBe@wrnP6LPYOuHiahP6ewnDnQr8ry@jMXE4DybH5A1waGR6DmNWQ189D6q6grP5liefXbmM3nzX86Rv5a508/@HYc5YFX3zZRtPKpDC/zOmXSA6bhSHJDLjczVYHzVYn4lKx1A6LiXqYLcppLx4XZdDl7z8Ov3QKnyugeFHA8MP7j80iQHiB@O5Tx4fzBCa@g0rQJeJMrLjg973u934V6aGusjL0E3/hE@cnnfE3@2Q4jlfKxmwgjU0xe0i9@84KM1epWuxrI/FMqeoQYB5kIKtlx6d0OoC4isD5cuNNi7Pu4ieGsAHOEoJEmPDrqOH7MdcRO0EMPTKhYw@KZkrHrUhzL4okJVdajYFbj3JRW/2UwupnVtWJjPEQRubHiYzSBqbRpNHDIE6ClrX9XB9FLjO8uZTJKxakqC/HQPwtrxjOCSj2mQzHojIuDTUtTzTx5ZUd@NIKkkkSr4iF16sO9oYi/40tqe4PCcJY2rqhO9Hk0j/dzreUaU/qnOJlZr@9H@Tn0WYuAbyEc84128irqEzid6tP9HwdC35GejKGscafS9J/uzr/HTHdFCzwjwlKEaD/m@YUmvImidWCDr/6dXlOw2gCv682qEjat/iiIUBw5MCutycC8DqB5C@uKAOQKeTkVfeH939oiCXTJlNHZGJmTfUGXwpmJGZhWjsxvAWo84ZmZumQwEFActDHd0wF5K1NaaNsZBoTMYOWYfZROd/ffZym@7xjys0dOuFXXa3sXnqA@DH5RYfqtAKAtgRAtXWhi@9DGCsSAWWnDpNaE3ChpR/C94x0O@8GbWXQw0SzA872tyOJtf/UuWkA1oofVDY6rnIfMkg6GCpqWulqdOKv@Pm@S47ly5Dlz4MXPr4i8B@/UVgpzV81z9Ndd355zB0FmxiO6G1pSVLSIXTvKjLqMVHdPgrp6BN2J73mB92N@@QJuJn2a3D7NWx0@8Fsc@STQAF/uOQA0@BG96GpB87jspRr8FDupzakKimel91HZGPHhXiKNQ6KE/rIEHvOEbQYx0ewUr8JVRIaI@/d3FsfHYQHN3ODHl27rzPwJEvwE0oA9jld/yfnwv8xCDTJX/z@/jwcx0AP6zch8RMvX/QdH1YYz8sjC4R7yePPuuj8vk9uNlPckdrTGpa49rdc79l2pbbG0Umnjv@rTZw5h8KBME4A5ihirm4SSqhejogIaf@tPXc@X8o9vK4ZfLcH5ilWjbwHB2okb6SiiozUTQzMfAtBqp1xdAVQR/hOnVktm/jYjRbDtGkAtLlhjj8FgeEZUWwQfP0QBQN65oOHZIjXSMZLhui1vjh2xkxdWSVlRJ4nG0on/oSH4zRz0M3f5LmCyOBhw5DnQctOAw06T8PmgGc9RbVm9aJJw/gu8QfPQb1AavcGiTzcaSz@dEQKHH/7j1ZAxJRGZ0xdH1jXP@eWNv8ryDisQ6I8c2LLt@66PI90QoTQPVhhfmevCG5p4H9ovBP@iuqd3ryyA4JjkhRsu@LIvFG0/XWiOk9BkpOUQHfbNXiXysqYoSpR0h4xaTJRVRUwPoV9pgEOGIH34nhaDHte1ysAsQmZCwK2OTTToIG2W@faQdkfqe3@VRItZSOGJb4f/8iXQFywoVDw0gloBKYM5mRryuGrCTEsHc57l8kpnDjwolbIcBOwkfJvKLDgGPFIEZbzyHp0ljhg5SyltFqkoYmQfE27Ra@C/OucN2e/7jnhjR8D/97cHqhu3zTYNpllYSC0lHOWOh425jAY/@gCn9Yfz@svB9155/pgQ7vg2d@mJsfrNl9uH794T7lR6vYPjmOpuczcaAPoLYM0tgIfCYO6B0UARZ/PvgjKOJBIeVjKB/U4FCN9AXSj0cePzB/@GiJ86MFzs/YP/j4VAszgM/UldZ3opgp6cwwWNR3wettDNeYsAC@oAM9xIf/Svbxv/lbB8CLRyI/Y7P2g9Uam8O/cEmIE6u/4wo3bP/Zp@Ufd3zQqX6SFqk/T0xOQ4bXkwX/84wq9/ELVakSBCX2XJ8nr5IziPFJyPDR4fhPnvHOupXkk9mCfbJaMCcEwmjjM5wX/oSFBwBOsYnkYqaks4KyaHE68NEcwHorGAx4t1UpY3Dy4VEwk88ZlhOG@nQZh@c@WPL78D6DT@bVvx@sALrYQ8bR7E/ZbjFj@hRf2oiG4YO/Tfjg5o4P/zXB/xiDTaGjXtyQvb9jeyKPS10VaKPgT95@/GHv/sGfcX@G5QioXtSEzB0alpjER6v4B92QjCHxhukgBUsYhRjsEDog@uE8JEz6@Lgs24mPr5eiUFTuHn2Rn1/aAn5xndzXKkfofVNcH/7NKcyrQ4aevTHG36B4pmG8xa@Ei3V4RvkXp2C//F8X/9P/28vf3n1B5P8D)** (Click "Arguments" to hide the dictionary and reduce the need to scroll.) ### How? Since the dictionary only contains valid words (`4`characters or more, only `[a-z]`), there is no need to check this condition. Since all the words in the dictionary have lengths in `[4-8]` the possible password lengths are in `[16,32]`, and the possible entropies will never round differently to one decimal place than by replacing `log(52,2)` with `5.7`. The only problem is that using a floating point value of `5.7` will give floating point rounding errors for lengths `18`, `26`, and `31`. However multiplying by `57` and *then* dividing by `10` using `ร—57รทโต` avoids this (while still being a byte shorter than printing the full floating point precision value using `ร—52l2ยค`). ``` รงรโ‚ฌ5Y - Main link: list of list of characters (the parsed dictionary) 5 - literal 5 รโ‚ฌ - map across the implicit range [1,2,3,4,5]: รง - last link (1) as a dyad Y - join with newlines - implicit print แบŠแธฃ4ล’tFยตLร—57รทโตโธ,K - Link 1, get password and entropy: list of lists of characters, number แบŠ - shuffle the list of lists (shuffle all the words) แธฃ4 - head to 4 (the first four words) ล’t - title case (make the first letter of each uppercase) F - flatten into one list of characters ยต - monadic chain separation, call that p L - length of p 57 - 57 ร— - multiply โต - 10 รท - divide -> entropy to 1 decimal place โธ - link's left argument, p , - pair -> [p, entropy] K - join with (a) space(s) ``` [Answer] # Ruby, ~~89~~ 83 bytes ``` d.select!{|w|w[3]} 5.times{p w=d.sample(4).map(&:capitalize)*'',5.700439718*w.size} ``` Assumes that the passwords are stored in the variable `d`. You can add this line before the code: ``` d=$<.map(&:chomp) ``` and call the script for instance like this: ``` $ ruby generate_passwords.rb < dictionary_file.txt ``` Sample output: ``` "MarginStarvedOnusInsulted" 142.51099295 "KitchenMiseryLurkJoints" 131.110113514 "InducesNotablePitfallsPrecede" 165.312751822 "FarmersAbortFutileWrapper" 142.51099295 "RoutesBishopGlowFaithful" 136.81055323200002 ``` *KitchenMiseryLurkJoints*... wow. --- -6 bytes from Ajedi32 [Answer] ## Mathematica, 178 bytes ``` t=1;l=Length;While[t<6,s=RandomChoice[Import["https://pastebin.com/raw/eMRSQ4u2"],4];c=Capitalize/@s;f=Flatten@Characters[c];Print[StringJoin[c]," ",Log[2,l@Union@f]*l@f//N];t++] ``` [Try it online](https://sandbox.open.wolframcloud.com/app/objects/) copy and paste using ctrl-v and press shift+enter to run --- ## Mathematica, 136 bytes assuming that m is the dictionary the code is ``` m=ImportString[Import["C:\a.txt"]] ``` . ``` t=1;l=Length;While[t<6,s=RandomChoice[m,4];c=Capitalize/@s;f=Flatten@Characters[c];Print[StringJoin[c]," ",Log[2,l@Union@f]*l@f//N];t++] ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~66~~ 65 bytes ``` for w in `shuf -n4 -`;{((l+=${#w}));printf ${w^};};bc<<<$l*5.7004 ``` [Try it online!](https://tio.run/nexus/bash#TZ3JsuQ8kp339ynKTLXolqxkvWiZFlV6FVkzgogI5uX0A2AwI8vqsbUu@fmOM7s3fpyAYyCIweEY@M/HVv90/mla//Qf7XU8/vSX9d//9Jf/@Ovf/@Vf5v/xf/789/92/uNf//Wve53W/vjTn/9@/t9//PUff73d//a3v/15/u//63/@73/7t3//5z@HoY7voX5/DbdhHbf1whbMNJag61aXYQ5mm6f2EtZuWkbjtD6TIXwwCl23Qf6trBJvW70lEEyMpFqvwx2Bo8r9aCWhAY478K28fBpZud@JFGhgI5gZXCKChDExnYlQTN@WYCZ5b3UVDbfpHkzd1s9yoYL16T30YqbMHzFbNZX3Ib9x2LupUhSSkpiQGcdJbwngL0bur1JLwpiYzg7@Y/C7jj8id4iIkcgyEXLbXezjMXdTeb4d6F2qykGYj/adWqkXpsNWP2K2O28ayaugn0rxWdZxALpphHhG0XwNUUFGUbI6jeE@1XsdHl3MTj35niJv81AXSQqRFdMEIrcydcGB0317bZHyTI7nZ7nVSHueBj7gPJXVlIfnakrcgY47GHy/4z3muTwvGBOb0cKRzlMffY4k1juikyWyJGZ973k7FHp/Daa3Eplbwv@owl/FdDQ0gPiXmwp6uU0U3hIlaVoSLRSMwuxzxLMOzzoswnl7fsAP7w7ThfX@wiNqsDAqPdVxLfdxU5bXZ5lNGyC/50wcz4M2vE7RjvS8Hn7BdQsHsA7fCfLvU0bZpz8O4c8pmkng57WdX8M@dGVl31WQo5gy/CfTwHVMKBcz/UwGgXmgre77NqmMjOFT74P6n4AVeEEGfaxA@gPjeDEKVNb4RPV5DDcVppnIYY2avgKUuKtjVkaqYt2UiVqHj6mcoin2BMTF4B7dwSzcnsOKhMpCVL59cjcCg0OQdqccgHIxcn8NZKW94jUFeonWBhpz9GULrxFM7QlINzdkdXYXpLv7v6CWtxQNBbCUW0hg6wnp3iy/ObXtSs09ekhF@UXt6K8ytSWxXxgSnQZNxxpEhRAgl7rdpx4l2/tw/1acMA1UB9GjAq8FAQ0H4XGME68euAVVMR8RGU3yHNRhiCoqId9RTBPU0e51TPeqoj4fB1X9pwooqvFiykP7usVwV4BPkPv3bYtaJyZaIahYxKgQhmDGp/wfj/mCMbEZlfRteD4H5J5y/S6QEYqDhWa14fFi5BGtqQObQW7R/qHrkIDjCFUs63c99g6D20qUARVwUqu8aoHMetP61Ae4SQMQIUzNfFUiqpta/k3VfzTMwETEYDNDoKiz6uuCeUEIRL0WpMx05/Gbt2zwzRLdxQzKod8VTTepW3w1Mfh0ij465lsZJFWi2wyyQppoHU1LIqkXx1wiDVMe4HshcE85@xxRcUNncdqFoOUhUiF6jrGEYi6v4U1awmZ0XEH1HGPLIyEf34SbZwhu2/okjnlzXLOytvKC6whxlHz6shYKhyIvTRpbjE1RQ8rJZ55USzR4jgY/EQHtS3S6q2ZN988dB1ByT1U@UQIHhoZwm@b5sc0jjPSOxAYjqjKfKOGpKmei46CQ7X5M/UL5t9e2B/RlALqKYqZfCNCbiPKgPhLwE/mPxkL9mV3hZ76nqGVbTyk@8Dx0ddXxyqpts/tLYz5bupxBJpWzqFpI4Lco4babCF0Y6ECbs7xto6lCbWf6nStUAgdpHaEI3zYq13YTefK9AwgRqM8A4As5RKcZgvTkDiZQPvogmyrKttwgyITagcxCMnopOrUgPBPnxrsEWHT7pucJ9Meh0m9bw40sR2uqAoIFRaASo3sAKdO3TcW1qYkKD2lWgnFQHRKDs2I99VIx3Iaep45IlAd1ltX9ZB0YNEGSqO73Kl1HjbYWtAwjVHUOKBde7kTlp4s6tkKrDvhFmOhn1A/U6f5tKs9pfBJ@elIzA1/UVxjVE6Y7UD9FeuobpBSUhDExnZ34oX6yHl1t8LjRJg8lfJDu8XgwMzAjh6f0OYMe5xsEdobo@wFyW@IbHnQeUebEHd9vFZgQdfXgENigiqC2pOlFK2IWdSPHR4OTkBtuAN3A8eHpQ/Y@uz7RfbjdNAwGTmtk745yBh0NyFCj7zF2Rm8pb0J8m0hgvh/zAaMJSRUT2rtgCbKUmCgYJBMvLmKWUFEH54R8VNgVXnnapz7gQ6C9H7VcOF6MfGo0HQGutRBLZSAQ0sEE43epO68bY6PfxqOmcOsJSEP65oiFcmikEIV9d499Vw93z45NSCE2Ymihx39pwlJNCdpLZqM7dz1mVqGU3QeCdIc/GiEPZpF3tSWRGA/vxTkoDBsCIivuee4MV6LHrG8RM7LtAkKJkUAti@aK0tz1VgEVmL9FmR8Jd5J/DZt058Adoi/24oO8NLF2yCpVUriYKrlXKvMwluqmjl8KbEA0RehosFuGQ95ivVuiu6hfZdjnD9hN8U5FAUbBSowLSqyUb6j5GmqnGWQKWSiLFOdE3JtpN10PmBPixM5M65RgdEplvRCH0CuCzqOmd/fXNt15uW1SJrYdshNRoGPaKNaY6M0AflUt5aX@B0qAw8McDL7rtykPVfn9uk8aFe7RbpdohFPM2aA07EDGexjqSujtkBEqnz4lKKGAX7zV9I4RDxpz86/7nF9@pk3MViqFfE@hqo4xPabHJxlF7JmmQQKhJhJSWC@8PPQpxDhkMKoBM5plQKhtBNEYcZ@Z3RvkOz0eokxWhDdT0po8KMMgu5JpgT7EPO2Q3cL5rYJBVor43erGXfOSIGsxxUWzPgFdV8wdXqb5QJRbd6kFOmpZNqByPcjTgcSxNL2xzE71wnDfpGsHnUVkXQpQWW2DiUQ0jNUL5SCzlooopvYQ1RcY5SmArGx0EJt6/G2mogh6uXC8GEnN6i5EP4JjIehyIxPRI8h1eWgee2ciCkVEFVTUD0WaiZipJ9h9c3zLsfKiyy4jpbDMCc1I9sDxYuwzzeXC8WLsM5O5fWuUUTAxNMNUegExE@UaeSN1sJkZ00P2D5i9pw/vCm4XY58rsvnIwIfSDZVqWS9sZlZLSqcDVj8evDuI4MP5XB@TBR75HWHsM08OE5@AuB514/vH3Kb9RkSbKwZoh42SW5tsIIn2OJZy4Xgx9WIQ6UNmsZdl72Yo3MCWzz9TYnMx9JpFaVupGYu8ywfId3lPjnz7hpCH0JtLgr1ck7dvnmaIBef04UPSvIPC2yOavPJT9U3qTk4EkgitYdTgujVX5ebK1jo1SXpXwPFUswxdbyKFIwp0vhCH3RkR5rMTPiq6SSC6SWCU1ccMgo1GG6ViOQ1AdVC/V23MAYmrMnmzBTiodDBRyyx7yqCV1QHPBhtzAKgFzzkFT2W8alov2vlOYlQWoWQwgYXpyBG6FMWrkVOau/rDeK0RKqFJVUjUDxPNO4YVjDpiVMCABDRwVsbJunmUAfPZudzO0bQk/nZGLKZ/93rcJ9KhAdajzKYazOpB8wTGxGZ0RGjvBgusHnGZOEDt3H67OtwnYfcrfVonC2AIHrciIr8Y17foMo5RM5cYoqP76UKTAwUBRgkctiTdjz3msFIaDhWPdeSUsNJ5VGKr0fHfzUD1slGxNNdLJMi7mOrBNqBcoTHIWT2tTBMjQBpCNWtjCH00a1ct/jCsfjyqjqqP4xDdnUhEIFAEwia6B9FIMNoSN9oOJ7DYymxrROkXhbdX/V7VHQYz2yE@y2i712gVZUy71zgcnjSOw6msRGbjWUxXtRxjBjurR4X5CB4iGkoNTSjj11hujIfGfCaJcusix9P0aSFPGmEkfMesIlQqd60FCL9FMgfgeDEIb2NJGBPT2QnH6ICHsBntgatm2EF3shHQlM3HQNcejBRrA9IPNGrhvSf4cR0TysXgrtd41oEMguPFyFtK41jm4YNzoPM1y8gfUJj5BDOx4COGz2JEpA@i0REiuAyZvgydZtSGA7xCGuPohPM6kf66Ea2AR2TX5mytWiUQ8pBZC91gkqM1AqH6vsTxYvBxddgPIquqqBeOFyMBrz8k4iB9wYCkVxRAkgLHi8FHywf6fO27R8cYuMdcDvTra2L6G8eLUdAundGABwwehZVUMVDWgscivV9US01Con/TQxrT2aX13qZwn7QmqYo8eQEtsYnBdaYyGe26PUOfFsPj4kxMMlGNkzqDGO@pEaCyGd@zKK6iiNIyY0YxoNoEYMcbtRypjzKpyYXuJ8VzpIBcOhOF6QKyAjxqQTeIImmYSBLHi5Fou6t3TLTDBq2FvDbN1y/E/8kQA0MGQXxeEEtpvXS8GFzoFgJk@hy1QDyS4xa10z5SYS8cLwbZ/XBeWJEI7Fv9jQjklxZDFZ9k5x@p5a7ik9UxsCdc7kRBpYy5ISX6dvm9t6rvtrlSbV6fF1bENq3ZjNtTX0J21VGa5shcQw9LYeEumFALQik1oxfZ/guMic1IwjDqGzRtGGUzFUF0WyyhMWykvFxGMvwEcXw9ozn8scFmvDwQP9eY4kfRo2BBJS5ETEwTwLvzF6bnUzmsWooasbVCLZMV0MbXAJWQKOURnci36KllMBhWM0ZMrtCSKFMHjGMLxmLL9bz4WS3M373aEm/MZwvThaK1BeV1/erT@p0CskAE7JDd4p4wi8HvreaKEgZFJtAywUhIY2VlYKzHAoHlnYMWhXW/LBvbKOPIiClkPGKeP8rsGiTe6FgWKFk5rO4Kmym9S2hTrik0xSC3yQ8KiRVk/KyD1PzE9lUGDd7QSCUwKm0U4QqJpARKSijpKqLUJKFEy/21QSQsaABhNIV@RqxYt6VJs5ajwVs1PnG8mPB5PkW2IFjAo3RgXl9lHp1B9a8x2xPD8njg/krmLfkYV1Hdg@mmGgILBhLoeDGRSszwotEaxsR05gWiamkCWTSBjwGYwk2U2K4@NWDePgnEAlOTQa5P9uAbCD@O/sACYYxOpazukEEkVuwuF44X08RIZTKMienskCPtqMgw34TxEgjEu0VuNXe@lwvHi5EAi8qGMTGdHfFT3Z1B7i9028TxYuTzw@UhdMgfFMcaPSIpgOPFyCc09jmBxyjf/oFxycWkeY6JrZgYs4jkHf571OggjRIxhvAf0aI0SML4WYUt4Dv@cUTrhqpNwYRU1QAHHQ124wXqM6p6DI3Ig82Ib9s00YuctBaqL1TeDStQ9P6krpYTDR0kc/2lIKI4v2iU/aUZRnkPs/McNVuVX/uu1E3IQPjRsmeoKSMVVDqNSIR9b/O7JIyJ6Uw2f4b6IoKKICY8f96lSBt@M3Znx5kZHGhVP21gNaazI/deuPITC0n5@RrUFSXK/TXd1JZ@JiGSK@yEBDb68nOXKqtnNzJgTExnhwrmI5j5@sbxYpoZUgPToZYLx4vBR5qEoJWEMdG@LZO0EbT8ZNk3AOtSoLeXwBiKbAHlI/U2tP7HoBW/ADUU0SaqOB9s9/uA@sKBh2bwj2gJTHyDWbtpfDZjw6H6uV6PTBjFELq/NGw@tNL1GEIXuct10cMysRftQU0IWMVH02uSUN/w0Bq/yKkdBA@thdQEibb7RIox/dwI6zXJwEOadUy/7kX@fo/C7FbA6zKQMDETOexX1G8HzPRcwYjM83Ym6DHUxpLAY@gWygVtjKlbTZBv6@ylehTpfw92QzxC3Vbrf0yjViwNY2IzksOpUAahHGgYEr6g8S65OgtalqlcgF9EaPd54XlerkdJzQ48eyHNjN1finxVZyXglYw4uEO3OfRB67VFFNoFTsWxUmmCnlv9FpN@5AD7gcCOLpdfvyL12YodiOcsje4xU2W8RSLghFjuTDF9nbnoi0c5RlFpreGRaw2Pa63hwVrDg80M0JJoz2DsW4F9V45kSQ3q5ALyySKZOnVjPtQVBjweCndMCnCQF9uxjM3ogJpJPLboER/bXZVWex1ESkJNsBdhAnnKvGjnw0PmZxF58A6yzj5snX2kdRZUbrDSBu3aewXDHD7G35uMDEJlHZBgvU/aZRhMYZFWzG9A4KmFVeH0n7heDBLfIgu7MWEcbkGnEhMKiLDzdKg4qje2PWSKVC4POrDtgF9dQMeaRcKWCwGmtwdWXuUg5gNaqRCybysYqhBKP1TpV20AvQuPiDU0@G9TCWpcEiWdSpcQ9Bw@F9rhV0nIR4tfbR11/@FdFTzKkPGo2xOiIFLiH6nEPy4l/mElPoDog0pI24yg8kGxeRya@j1kedUuQNUKgb6RFhUerB88stCuMjuiAatvksmTEEKCyJb50Friwzahh3ZDiMi5U56HGutzmLVn/A7zU88R71Pr2c8Ba3qAelTDmNiME7LariGHtgfpBdKgKuEnXToh3bc/o9uGyC278idd@dNdb0CBaJgDNRSIMe3pjAU8mMm@Gyt2wVSotg4AkYXiKUTgUrRFTGYQjb3P18AKxfOl7UPPSQPxUzM5kYh0qtHInjO2zic7HwVMA59aZzXVe1zLsE8vvz7n7UY7CaZiIxLDo77AUxvnTPE5IcTjzuhJZ/SMzujruUamv55azRRpopFBdRBPdTQiUaUE6ozFPIJs4@1TQI3PQob0J3u/ntGoC7nampYLn2qf8fW0grImKDcwkoqK/azDDaI5EEhGg2miKhrMm2nTFEgHCXw8Qje7mE3MRHTLoopQh/2FuKoPqy1B39Jqn9F8G0CKRUumzzqJ116CoIvIDlGwTV9Eyx4q@Kg0O@ECyenhXZbgb4cIdqjBQPUw2couBuGJlzmmDBLjq@lHsJZB0PUeh4o9WizzxuehYjuIkb1HzyP6mJcXo4CaYFdF/mJl6qXJi3ag3I/@5Z0oL9SwF3tsg3YI8czdAWWiDhp1CqqHZSGJddRGORipcMKYI@wwsyX4ysHE4PobmxKpI9aUFw08gWTd4IUxAu4wyl9lF01g1MLXYNJm5al1IpAJ4TU4651cZv57tZuc3ts96C9ZEA1yjI7qVYZRNlkYyu1ajNDeF5Ea3drHDL4klDtgvAEmqMY0gx95Z1DvHGojRH4o2wY9hhamx3lnJhw9mSKvWobUQZiurjKYDVIQ2KKfApSi9x4nyrtNzOVe1DNRtcdXpKZOM1EOfPUJK76AWDSZeaGivVDRXtbMXlgvleqkrjba2mu73SI2KyGvVEJeqB0CeWlYeWl3RudRjBG6VVnCXtQhLyi/cgX5xQryKybSVKxAF4xssKY8TL9i8HlpzfilReIbiWi12PBQbmHsvimbjfFJqCg4HwX4icSPp/aGv45FJy8A9RgwTaBGCOC4MYK8jvWplzlcmEcW5iGN6xXKBsRO1KDPGOO6qstnfwVM982kfU1a7IqoQR49wEQvsS3QbhpvB0omcjQ9VaAxyMRXpTsO9PA8LTKMRLaSCa/oHhmkJm0BaaANScGwJQrsZkIRCGC1w0BUO/1HoFZWDOVi7M4ZqmDmKSbfYjR3NVgSa/iUGz8m9n2Q3f2YladV5T@td9uQJzZuQMmAmAi1Yl4Q/MRVaOefDqVlhTsSMd1LGBObMQWP@VkuHC9GIlHdpyEwZqL61mJI8@GIBQTwQp1QGdV0J@rNlLtBptUKbjCvQSaGRAXI/UEw02/EZ0rRKUVjuFPTntYfTvwHnxEYE5tx@s3wesEoM82F2hy6ZY4DHY/NAIFbzKOFewrulyTWjsTxYvCJ@m3ZXg8zWkQ3WJT1zoltKsC3YuqugUJcKTwZqpbEDQfvJ5vWtxQBw5jYjH7P9@BKv8oWRVAvpYA9wUFZShE23Dey86YnMjYjEVeSl2VXRI1P5yO/pha625jQvn5oVBOJDt0gtxh2f2jUHAFF90NWrR9D1aLEj@HXr68fRafsmnAV9Tk84SdoTI9@KJc/dDhMLj4k9oO8/iCnP5zPHxshYoIjK15iMxPd7g/NBEZDAwh0aMHvh233P9J2/@NYPTsJRkb3AH0K6tEPzorKLUpZHeq3F7e/pdzNAeyu/S4yrwZVdAGntlkmtq9vbR4UkcxkPeWb7ebfEzZwgR3HNUZhA756k@@JOJjNRFiroIpE27e@GQi/J5z6XV3st9rP91oKROz0EE@Fn6Vphi6uoWxmwWEeYhiZVUNn7Y/Q152V/VntZ9Z5oVDWkeMMaR68uM5dyGoen2HWlgdTPAPtG0wzdOJgl4vBgt7lMg/vAavbrC0TQT5Inx8n6afrwTF/xP@aKI05tZnAh/bFJ@Kgtd9ZE1nmGjnVuGYanmjM0n1mjg5EOtH@6WOSkYvmVALU0rlM2BxnbXj@mvOczsxoEPSplXrjR8ie0bmQDHbU2Q7tNpGfpoceKufXPA2MC6H9lhlah8ToXqNvpf9IHC8mIpxYHxSQE6ZdbGrANYseVGKXrWzOEw1sXPU2VW8GmW2@0oEYKWQc/8FapI2pqiwBm2KMyYb24xQHgqnJNJDKqdUfv4hQ3ximK@burHHYesb6JapcbgNVdOP7oIDpoK6aPNi@8tyuYUxMZ7LPKnBoFNuX9s0ScNtfWgoWI8mt2Vm1nZY6e9cXe2VFyMExOkNHk@ybtJxhdH5o@/I0NKjTPpmtg78d5P1RQWintcIfPjU46/TGzALifKysxQY@IXJSEzw4sicgukNH9rRVN8hP9VPzRyortH0tgzuJ0IJoIWJY1Fiig75tP8GITqDoFhZ5FhaFg/5SAE2uoHKay5fNvIuOLdttHVX8CyeOE8bEZnTUa2gUQdVzCVdLrem5Y7pD4QziQ8rLgKlSYKldnloHTOBNxOCu4xxC57hmlgM7kVSGpoUjGWOinz@OvX2LNBy993nRaUSEAy3Eq/bKdnsYFSKa5TJ8NiWsUtM23gVtNujKbq9FlvUYEKc7HyIYrSUF8xxuH8VaZhkTFh3/W6JHce7U3@Tx8ev0uA@Py3ZHcIHKqqwHRF4x3a0fEPosX7mcmqup12JqIHIsyS9ekV9yQT4maEO0kvrlbTJQ@erdgc003DQuLjF0xVRrUV8C0LATx4uR8DxClOdJ3bKk5m@ReJ1JK@HLlCukC93Qgga/uDPy6oIypMWXIHrhUFV0lDERB819DHqMEUvJNSwQYvZ5uJupjqexuSGRIG0iSjAdov/jHIcPcSzTT3/4VQOA8i2TiYgyvXlgWei4lu1GbFsoAMs2utdbWAyDdsGBhECuPMTQY9eF5SzjsQTDpQDCiT0vwYSakcDjtmtGqn3tlJYRn/7CY1Mm9UacPmISJO0dZk7EvdC9adq3muJK7QP0aGPktQwvfPsV2cRrwF2fZcssd1m0lVKPyfUiU7WpLFowlGPOLGEUSmbYZXvTPLQ3Y/G5lSWPrSxs1VgO1pIMY2I6W@qpp7lP2p2/eIq7sKFj0alFNdGD/U8G4oC5XBS8UesAHos@DcCju1qhRvjFtisD8XV/kYPlRYMy89GXMqpSffoL4tg@0ipW6der@@41@@6VvnvluPk6LLYfrL6qwBCJr9LWfmNUO@9jamB8KEM8qrMSifyE7qiiNLQLxWCfDmCjXaLctaFw9S5ClsFW36ewFquKK8bBtUDYbRzQjacOc1QxSQl@KhvRyxi@IYowdWihXhkmIrWRad30TVctQa@0tHVjI@G6eRf4eu32WtUKdOmNiCqynlqBSLwPjqhzs4SQSUIw00NDSTKIXh6UadRYiNi3zGBAVxxv9ZmGcD50zije95ga9tJVe4zWQ2flFL9OPQzzhc1MVI2VqNliDdVDvPh2YxYiUOkI5RhqXkkYE9PZUtopWkC03mQkwo7QCtNagiU8ZAQTPVUnsGfC21069sYG8@3BNl5D@c3UZJpQBlRhFEfFQQebDPF49b0yp5X5EfhkM1N0frjGELDtbMcIqIOp3PYNE08wGFw2Nk5sbJCHRqEKlwuj@W6@xmfT1optP0z0jvoCm/fbahmwm@L41LuKKl6hxFH3DQhN3jtsBgH0FtW4bQxVbDu66v6FDSa6gYCRITSYfO2jY6lNHC@GILOMi4E7NUHN6lkuHC/GPswDg6Gsj37KOPulvl6Has1syYyHUcu6MDIXw8wxYwK3y2FTFmGUkzfrmYKqoRdmS0Y7VmFQkGB0AklMdO@REGt/ufLHut/28yMb4vZLcruG8CBqfFXMN@@4e11gT1vEngsCOwsC@8BEW2DHUW4O9rTLtNK97WjBO3s8oMikzRhGvrPzMIvIDgCVh@rCPhDWkiznANqcCxNfXRj90nAxSqPqVq5dN9s4oEbl3Vd17HlVx85VHUGlMu4@XbxzOA86GpBoKR/VnVzWvlJaoCQau7YS7TCRgcYdXELsmGKwZ@zSjoNaNzY2o9PCrqWbglhc3DnBEHRiR4gZ3uxwTg/n9Micvn2fyD58/iuGRImylnV8Zx06qA7NGnhsFLdRDuMwQ3EdvaBtJpqVGYmpNDisG13IoN55dz6LTlZ9pZV3T@Xbtt6gWq8SsuVfSDixG@etdu1VofzEkIV6z/eo0zaSFzE4cDHPTjerb1i6sqE1IG0O2n2AefcB5j0PMIduXtaYfexaXRgNDUjf0KmgcqwZQ73CfnR01hD@oZ6EcAwI@u7av@6zi7tU8p01k6CqYpOsNlBFN9lmAxKtbs7YaTZuHtNe6KnE6LETumvX04U4xztOv34NpuEyY6wxjInpTDqzGulHuNodZULYLZ@tdPYnxlRVL8ShF1M/cGhxt3lpT/tSfMUB884@e9e2sRod/aY8@NANaFeplkE1YOxbdkJbWaDUwY1lc4HcbABOxEG2H4MihpH7d@Rl0zHZXZOD3VtXDMjN3tovptufNf1gVMqcOxVuleS8Y0WoktQOzt0nxvc8ML7LNhLkcB8HQ7z1W8RaUS5tADWhgY7CVwQm2kM3biXaQVS1nq193tiX2/r2zRdeBbIkCM4AhyLEkGx@18CdkUE62pZAdEeFkIDXB4TyeWNU23WeTzK21@yXvWavA901ma6cKAJqQgNTUu9TuZrIgHDx0ZdgOMubOF6MfdjUsOtkYyhPiTg8KPtAtXTAQcUg8OTkQjCL8wk2M6HOSPHh9Gwy@HBENhGHt@YTQo26u4wbI@D3msg20wWDwkyOa6Kr1IoFrdjrWQbKKKaBd9x/FVMF2m6uO3Vjj2siPvdo2sr1psUqRbA9Jos@3CWJ6Ql@5DR1MF44CgYNJBGRRXu5EseLsc9@ueyODZ09cHvwuMcQJqRoI9CEZ9/um8pL1sGgWgQX0ECN48VELDEdHKMuHqlxHPP@5eU@aAjI6rd7JWLPlYgdI@COkXxPG/meJnLQQis9AGCB7AE0L9g1nd6ZM@/Hru8rqgfZg4LywY6qOwgD2nHBmNiMTkmMovv1C3HBmNiMyMXsNL7/H8eAlSLQ/cEfh7aeQXnAtiX8iEa9CqqEAXxI9o9j4n6cQGxQRsSnX0GieZu2L3bQ9AQeQ5WqbOqtbOoNqsXZ6r29grYYFCrmlNVLWD7RHMpZ9LPS1e4EGqcNR22OQqOuA/FrRaaq8YhwIVBlGi4q04Y259xCZc6DN9e5Gx@70cFoNV5NKr7yBF@e3xNYcP2G4IRot1RPb152V4bUrYvyQlEvbHirQ0pGB2y68kbdb0Rwlq4MY2I6O@i7QEaofN52/7VFimVgLRjEufiyVLB95eEgmHkx5QEJD3FiGGpruR2yDya2ZOKFyt0XTpqRR2hXezdqcqpOVMUA4P@NGi8mqqTBEXxrJAqkqwn0OTcx2sMvhg2FiYh27agI5Ma0xPFiJDEW7kZQz83ie72evTfY2IwupcdcfgqkehiGnowDbJWCerDBS6g9vIHq7gQ6kyfsSuZpoacmUgJ/ZRhF8qyFF9G9kLXMw09TEpq5IBF0zmZV3FDcMHeIsZh2iQHNoFphHC8Gn49jWTxj0Xb7UdEsPqit@zrJ4zr4PVe2n4IOyOtdsja91dw@XlMLrwxcQWO4glrGV@bA4KvyzN0bZuS6pzs6sRirLtF6NKU1SK7dD3nnjZxiCKfJMhQZDY0GP1K8ee2mGbs3AnEKJHG8GASsRZnBIdQY56IP6ZIC2cZ0npIv3ux7UKYe6q@RHrQ4h3gA58zH8AMnWl3PMupsbAAzHKc2hfm9D8osRrxn4mFk0plMM6NwUijsMfmbcLS35tHemkd763W01wzN9b3R7AWW3GbelFs5DTxWTruI0SBfX58F2l/RqmL0UFwytQV5QfSpJ1@8VLXoLn@@nvckXre7yTozinqzE9uTR8BS9GjamJQnEa@DiOyd9N2z1e@WbzY1WkPA9Yjft5LC/muQ45undz5Q7zfq5HZTgqI8aNWvakWhbh66uCcI60ooP0p7c58ZQKJMBELXGVZTlYtQkxKpPCJErY5UOk/d2FVnGBOb0TGmLbRqaiTwjup6bUOv3oZedfOfiP0cx@HD4mYQJW1VE1ZHuTyjapotopBH9p0Hlffg3Q7thoDiZH9IJQ40o7ws47oro3L8sg1RkBrLm4b/ZqtRS2tRQw0IWnGkohh@P8v7OQSJptVsi29pi28oAU23Xqu7hFGC8VFU@E3bThvXP4@JzejA6wg5VWfZvdQGu09ke1Vu630IBaYNtOCmgz1B39TLdudKZsBPRHvXSu0MrvbmDlPwEkBch2wM0RDE@NFhqqOsD2iGq9pr0XTDnCP0woYMyiGywWhkBeUe30TLWmIWOzCvTZSDqmBQJ7plOpvsB003yey4Vy0IN18YY7Azx44bl8JA0/V0LFU9UcAklT8wWkWC5Wgl0ftHnFrGbb7gWkB4VnWb1kcau2Bb4SYlSehEvooMBp8OCW3I28606YwXLcj7AEaifGft5JGJW3p9K9k0m8ZOisXDYvNuDw1IkyP4Q@ccWtGWYcF7wBVsX7beC7v3YTQOLb5AZgGNHYRBNU4FHLz2Ty9HBRPkJesltAGh0wZ8F9PVgJebTyCh2BvbXhzPBJDZU6Zq8Y0WKjLaVTPBoGWHVmjHiQ8T0O2q0dQgZ@99AR0Pu1/U4IvpaLBbiqxK3j04mM47QjGCtZf6VygieQMsjGS2AoElHdm8RTMP9KcBtVNGYDoApGD2YFexmG7qBI8rpsNivDNreQY5Hl03BXw1LY013xRoUBR5Y2BjZ7QoO6GbhzttfoSQ2rUhqHkBLWCJ/i16No0UYBewdbfpGmDlAmx4vHlWNxbacjA2GDXZCCoIkQm3ORmuqjc08HKm43JlDeo2cy38N1kZW94K0LgUoE28YXr3w8mC48VI4CdHoIQv6JSuyu0vRDmlFEN1dGh6yW@OKRoky@67USjPaYfsdsna803t@ab2fGsdr83DU2SFqmHPmlFBQ3KOmk5AMTzHtKZpT5fpaGiABSfcxmKKz5g@3uMVzCLirIHqfq8jf41NXG3WbfYC9bU@2tdk5RXBm44zz9A0ztDoihDMjsHoBZfBvNvw4uuPQMIsOqUKbYZIYfFIuWDOEVhy0idZZEKBjoaa0IwGB4im9SK@I55WhvB1gNV4vGqjH1RRCQm1snQARNBV9za2dbvdKJ5VXdU2xEfddElp22QxUBL0AdaxWhp0mzsA3dDcPHbpLGL5jfLTCIceFjQGQVmlGiYp7Lm6XkUfUueem87wicj5iAzsWC4EZHvXd9o99mr9RP3zHjNdnnWfk2q19ivrnGDjo@@luMrueesxjJ75AUnbHZg7vwO@cdLX2lW196mSxsSm7ECEkqVRCR0tGx/lQmHseVE1jOQ37olNxCEUTVGEVYlsAw5Qz7djDWkYXNmco/LaUenaflQI1tL2xxHzNVGUBNCu1haCUd0EUsC1U2aoX@XC8WLCp1OL/KMCGZzpnYw4TNWUB5VY18Kf6Cy67KaKs@ftdzDI04fqbJOIWQtWJ11TvJKFenn@drZQd5ZsVoNxDiq2m2Ts8y4JY2I6Z4RoFl3WGVVxMQZ/vW41p6NadR3kEd2h1ZR4S8kMFmeoIL7AuvcRpggFEQE3YCLnpWaCMU4pAzTJTklPWQjTVQguebe8TvMSXQWLrO6c1@E1ZVSB6oGZssGPHnaCOaFKNnXGQFq3LykykIe8rkYMI0LXSTmoX5J5X/PVkgH0Y7oUJVM6uOO9dX5uEfB4ECrQbxaMgnsbUuJ4MfiskNWuqbD3Y7VftJv@QfC4xffXeCYGkBnSIO@7Le2YebHxNl84XmGmnwExyjBPgClftgDL/CueLf0CO6rMYoan3pMWqkt0gvhCtWBWPLjdNDCVsWMnuaA3wW494shNGsHIZhRYfR1Dk8GaFCqmoyab9YE700sx78LbReV@k/XGHrLE8DlTETXisEB2U73UeTXZ0032HPDc03O/PPGT/RJqRw7cCrrp5dpxVbs5r2H@9DB/6lx@UA32p0brc8pCDUb@5rXeLlqg8UqnevjPcuNi72B8BDcY/5lHzEunNMToOsXEiPET30n7OYLhd1eJ7avrKAB9X/6speckWBj10TAmWnS@/HlUX2KI0jdjd0ywGJ9EYhwwEJkYe4pqrO/eZkyvKhL12oD8zCSpD87CrCgXya1PC0Ytwb9ZvPXiJ@f0pw0VHWNn0ElkZyWvs0SnhOkEgu4xKHZ94u6D1T0/dOc7S4mU3SBRUjr7BSjn3LMCJejiHUUwCsxksXsq19Og2bWRAE@TAiXDTNWim1wI5UvPe@HwXzETyrZQpcv2Ad14yzlVX30rqhldf@n/GaNRSjgM0cUMS@TRRdXLdk3MTXnwgTwx0TYvtA89rnbNDTsSVYtkYIzzunva3k2vp@vLRcsD@i4JeOkHBIKuaGR2i6lJMAdEEhhoAc2mzOCuI9wGHg8iqtxu03Vs8auTbijJev2JM9wBHwgFMPEZ0/bHecmOfqqNSfLQZ9Fksaubx@Rik6kNplA1rbSbdi0EdW7J7tttuN@3L5ahu3/10fVLj54gVyZoGspY4zHTJadKrl8gbQnEoXQ02exs@AiqvRL8iqFLqercZdG33Y1Ri/hd/Yd@uCTCluWu33V0F7HWxkUmsgvKT1PM7hlmZ@9V101R3Wtq3YtqPZfTel4M3K@LgTu7nbpv5uw@wy5Iv6eWBITqN1g/g1rW@mP3QppGa12NCS5m/OusrsUoSygu6kbNLRtiOq7fIuto2gzy4A5IAacWgrklxZVuraKRBDwsgTqYiLfbRPWhR2kAlts3fHfoEd2x8D0NAbIxSXTbdlPJ5OV/YhopgHLQmrDe@Fg54SKGjGG@DNC@qq57fUXESj0QhacUpTLMCXKVLQqqOUQ/1VRPavfJ5z/9ZzCQ8Kdrw2dn4SOxfUWjqjGdG76ONX82FHmM1z9W36X@JTuwruYCtaBkZpKIZgtB8VSVFiixwxeQHyu368Vr6L6CY9W9SQHea2ts4MfUQScSZbkrQAYxvLvDdAfpKdvx82ar0FbUXAXRSRjK9axQOqUjeapYKDHDQ4GaLAmCLooeEuhNMcGoFmrj@qiQXa8a30tOR0uRw6V2Sjc6dt/2kDheTCS/e5vmsbPWFOAJyLGzEHLUWzQFVvQPDniI6vplsCfMfm6ilEDmoRX/Ic0b09@D/pHyER6hZLylQb0HaqwuPYvIBQr/5nKEty9HeA/sQjAglLsQ3kP1HxbN9AvDp/iiznd5sSkxUQ5Ks8z@edxbDfft8fKdA6UwqvCb1szda1XhtQwFlWOolSJRwQ3zx0x05jBa2RAiy44b2UGpXsk0M4SzcLNbaJRf7Fe9E3vT7bDvidJ8h1sVdX8gRsOW7pBXuoAfdbwxF8aACvB2ExHNOpB5ocKs3Q7rR8ltmNWEGObMdFDFN3FAKoBRHySSeiTlqdE0QKfcdJDkwpQAHEuzNVi/C41H/26Ee3i1MEfu9FMGHNVNv9lqI1pN5eGUtiMmUO8YWeavU5X@pMafVPfTQ8Tp3@ydivekDE7Nt0@sOSeW5tMWndN/zjsH1CkDMl4wppGc/mXMmX@MOflhzOlLNGF2iEX2FNnxYUBO/IjBle3Kp5Z0ThsXTpsWzrR7nVI@pWGd/hHPKXvfyQ6KE6Pf6R0Up4xUIhzSC2YOVc/wEcpmIqw8qa4Z5Mg25jON5qfmdDGj@NYRLCHNQ8ysZxl5o7i5PO5U9316KeDrfEnVhobji@p0vqK6nrr8Ai9QnvSh54vD1gExgkHDzYcxzmlU7n2y65xotadvSAMlqJHpTIcnrFagDHrcC2SE4mBhPimq1mkNK3pNLZWc/NZWNAavk@2lQV@jVn6CcbFO2kx7amJ@crblnLgO5dQcXWQNOj@C8DORc9M0KZrKqQvETp2SOrk/TJe20dDFOPvBMHaI4e9pwcwWXSCw3OpyMkKc@gnCmetXxnphM8PbsbAVVAWqDSumhPE/h0CLFo1Sp35gdmKbQEqDOUvjRDt53eeUPUIfp2KF/KgUPqyjf3TY@hMVLXw/pU9fn6nMo2n4Rt6l@xgj5mAiZ7@KDv@xE/8XquivbVv@37r95a7p1P8H "Bash โ€“ TIO Nexus") Dictionary is recived by STDIN. Shuffles all words in dictionary and outputs first 4. For each word, adds up its length in var l, and echoes the word capitalized. In the end calls bc to do the math. Awk solution, 112 bytes, four passwords: ``` shuf -n16 -|xargs -n4|awk '{for(i=1;i<5;i++)printf toupper(substr($i,1,1))substr($i,2);print(length($0)-3)*5.7}' ``` [Answer] (This is an adaptation of Martmists' answer, but I don't have the rep to comment) # Python, ~~88~~ 86 bytes ``` g={*f} exec('x="".join(g.pop().title()for i in "a"*4);print(x,len(x)*5.700439718);'*5) ``` By exploiting how `set` is nondeterministic, you can avoid having to import any randomness libraries. [Answer] # [Japt](https://github.com/ETHproductions/japt), 30 bytes ``` 5ร‡[V=Uรถ4 ยฎg u +Zt1รƒยฌMm52 *Vl]ยธ ``` [Try it online!](https://tio.run/nexus/japt#VZ270us8k51v5a8JfQjs8oS@BId24KkJKBGisEUS/ABQerVTB74Zl0OX45lrcjzu7rUWuCfqR0ADBEGc0YD@5e//@X/@w3/7z//1n//Pf/rbP/3v5W/n3/7tf@//4Z//xz/9r/@y/f1//Nu/@W/rP/7T//2Xf/mHv5umOr@n@vq7f/d3023a57Jf1ALznELupW7TGljW3J6g2iXTLMr7MpDxGSK2WibotbQjaCv1NoCROEK/9TrdqXhW@J4tDWgEPdPojfR@G5N7v/NRAY3UGAmQrhbhgHnQ8ORDHHvZAjPUSt0hzSffA2vZv9tFiKTn99STMK1fYKmSUDuhM09Hl0R6nJgKx9Ce54wcCqCeI3yfqaYB86Dhqeh@Tcqn@Ze9BVUdobplxlMOfdb5XLsklN6K4p0q8tJpOEkrt1QvGo6lfoHlzlyy5OEjLkjPkvZ5InTJCL9YJru04jpD8sXyHP653uv06MCD5faV4z3WqW4I5cRwjg0AcUu5A0563MuzROpWvuO6pFuN9K15YsFZc9ol6bDsknyqkZ5qSK1X5MC6puWCeVATKaClYUHRW@3h@52BsjRHnq4odWs5EdvxnCRvKV5jM82zgn4nyVnQCHzydsPH3G6ZH2WzrySZBkndEDEca8S9T0udNtBali/py/wL7KB6f9Lb6h/Iqi@rz57uc8Er7ktaJRsBOsvKWJeTbdierZ2A234qc/ZijqQ6vQZAr@fxoJ7/OkE/2Sp/0PdZPg7H1JHc4/DPMwPT9Cc20j4PSBfmn4FUXCe2UcdRMnIbFP71PqG1NtgJT4oJhcOILSRovhBRpD2KQ13O6YYPBIw3qVZfdwK/p6rOqDisNrUgobVOX0l4WOPTBzCwI32tiVxBZZl2aiJHXUKrZzW0gXQM0e7MzYB0IXyfExPcnpZJALx6axMbNOsRNr68Ye0DGLKpKfOu44Lhqx7FpMJKn5U/QPqq80atDxi@TWGLUlKulKhnNX37JlFS@zPltg3qF4VmZ4PGLswEMtIA7rXcc49v1vt0f@FJgY2EZrNbxdsTFb2bDu9zzsw6oxISH/G0B7AJ@kxoSl0ieieWH8cGqLN86zx8Kz7k53Gysv4gs60CbpJ0cHGzIUwifEPcX7cStcPRWhySxwz0rJwC5wV6j8d6wTyoiZC427QsE0Ms8HslipmSzgqwegs2Xwhvay06oQjgs0fdcLlPA@g1UyLm/VXPoxPps/NRBpWghOxQqYliRV7VBR/7hjGiC8ZRxztURl8L2sKbV@dZsBIyHxnUhIzC6hv6DsMnBaNg7XQY2vlOpxfzqfF3k27XxwyCY78j6i5RS5QYR2p0fuboGm9pQogU3ZOJnaJB1lkyDWIak56apqiAIenA3z0xuj7CSOOM6mejYaUwMbL0gKgUcLUxAD9oek5vpsWpifQEk3CzccFjwHB6M5Z1paBP2RfGuhbFv@I1dmbRPlPoUSyOaU/McH7g1DCjsLFGlOD0YaHLKMc@cJoFcmGkbFlc5jtqQr5/73QMQogF1cYlIzOK0eUtr@ujrDMRI1lSI0Li62Z@x1zxFi7nCTG1@5n7RdBrz3IE9G0idGTryhbUADngkg7okwLkwne2ZoGlfFVFXlmmXCpc60OfBW2dOrpPyzTUj1V9FGi4KWT6hMj4li7RChi9IBlPuUGwcwhSJEUvWcosiVjKZ@h8dkqonkzLGVPBW2FFKDeIhaXPgDEY4aMHUIvihMwrBcNmNdJG0EAhKCjIZbtRUN@Gs9TfmAxkC7sOE3Tl8wrzwkABy4vtuJGKBSt0KY0@fFVrQyqA0ZikauWT1Fpisnkr@BjFGy3QiVG/wzyhtDvSE8/7IFtiKGZzFTTuLumADquqp6oTh1BBTEBVX1PZ8NbpjWBpmilRWwLSRZcvo5fLJfWMxDbP4DdjsBYbbWbN95cklPK8MMa8sHYZPVnzAlGWuQARUi6WGrSkPrxMA@ZBw1OJO9FL1bOjFTpvbJlOJOxkus7Hg7NuIBwXzEYAcFpvFPy5UqD8BMBni1J0stm1r8vnWvnZARJ8bFUXb9QoEWltQw4Vth1c9bjxPc/GXwigBs2Ajeb5pcuXL/Q9UDTu0@2GIZFR3uN17pxYhJwF1GYtvduoynorqDH8SwKq6/1cT6IvC1TgmghbiC3FhBwA7chCF/rJWKz2rAOGE2Lb@RvpP3KfqMFIjn7WdNF8IfzrLToaA/rVxJgru3EnNtSGyoV6MMtsrKR80FjKqfQBDEnRix7oBMfGZ8dHvatXvaM3uY8uxIkfqDHWdk7Ims4n96QX6WkktutN@rOsMam4T4ygK8azMaaTq0h3tB0uYmR0T0pn4gDAgY9IasXvHJy4PFd8@7S3cgHjcIRiTRvWiHwujBwxqIT1BcnVDKeDCXxOBXNNo4MCJeXJz//0BTrFVDF5ctokkZjnmCQHSr9L6smY0hlEYxRyFshnxMPQCtK7dLs@5zNNx/oldUmqjeFnICJJ1q8jKSm9KPW72rRLSO3EZKYNk00SfZtkl9xP4odCSfmMlHwQyJr3tF9Exxi5mlxnLOHcnyXfmTElI6HloDgYuZFiL/xopaIoGlCnoiV4ohUPyeCnBjiB1NpfknSod/Rr94ze/G4t2BbNT653STZ1RhwzBrIM55gg3zktdgmNngcgGQa/mSP5HWOdkDnmKPd1lMKVtX3VRMqJ5ckJBRs0vPPjOxCP07oTAIo2EWI8TvWiyxsf3VHxGKIsrpxHGdi0g8HRr99XriQCoJUfD0guIjjdJJmOrEFbIMPtfEUHfPA1HxSHAo7SYchwmMzeNaC9Y6XAxJ4k6Y5VHgd2AjZrf0oOBz6qdH0HIz0Ua7Eh4Xcy9Sd1z60h13xpvl4UvgXzVJMrBNbeDZD/ZZKAug9W6kVw9E0BZHqJQaGLO6Zqjki9AZNc2IQW9MplZQF26Omi@ULor2hUXX4B58aothsTau0l/LYH1rzuXKQKSWVULJdySBj/OuY@QL5FT9nOnRm1HdhcckrrgCbiiwTNF8o/r@mi@UL5r3yJozTmt@G5S7OybXTM/GL2BkxbUBPOwxurt4FHH/7MpaByofyv6NdzRHUiTTbA3/aLmnBXGMxDAnY5ncy3IAZ56H32R5biY5ScQPmvWeHtAzP2Ry0sf/vChgPEQE3FM0iOhd9gb1i7Jcn73NJF84X1Qqr2abxIT9vRhfxcRm24/QzNokzsdXwY7X0BpfpOX8J493fWI8uLgmm0OWQaIBXVvPKiy0qhQOvQYMFh82aSv6VgDR/SXfHl68EUO0DXRpkzhlOlqfI1VYPWWbZ9BhBwLmiCbGaS@fTTPtR6ER0PJddpuClhZ@Uo14ijXCPL@6@QQRobKcthhcCgoU7oQ6qWroMYf@USjPYCTWI24FLa2zG0OUeoE5Uaf8YsOqQCfdYR6INXrVg2dNlZNhyRpzY85WJWYGcIxpYSnocRks9y0cNYlsyUCJBRvF3KIbNxswEAl7Ed8QEDoIgBUuVYqBaNCYKGm96pfGbJNOgPTwaIZZ17Pe@ZaWBjU8@0SmJYUk82SQHzoCZS5JzpAqS4a5zFiXhIebY//BTLd8ChrPi2zkQGRZDzliCgYyO9Eo3pOWOtwIZp1lR3kMTJYWQgHn1qXf1@HreCdWJD@HFmMnQ1fTorn1GtI74LKZFZVvyxYkNiBO8kCQetfg87BQA80af5UulM4POd0MSBQv3rq4Coh18OpL4aR82oQ/MU3YeLiNIBUTo1yCME@udZex6zdjwcFGTnmsjMqbJL/pZKfe3oagxXOUZBmLVvMGu4O499g3k6tSA0Tx8k2V7P3IAdlWlO07yi/wr8Ah4QGDgBGgibB3O6cbQDGm58eLp1iHORXKSuBaFABLxzadgJKbhn2LMYvSBGKoPmCxmwzGnAPGh4KmHWg9PbqYnkTT@sxpk8mFSDhld6TOxwDTHBBDDkg/NKp3sfIKd9HpAupC9efakTXyVovhBqmOrMaZ2@9DRS@ldsOxskrjgYZhpDOLIAgKgaWxMmrZthkG0a6fOtKiFaMQPZRNm4KdNzz0zfXvgwBzox3N6U@L1n5udOh/EKNn7M8NKY0Ql9Cmm@kP4qlsfJB1SvWhfNF0JR@@YkOmJkCWAY7X4HMRFB84X0901uFJf26tHlGB1Tptuh7POlpz9ovhARdcxwAPQOpHeiDZUjJe3G5oTZsUsYaDjxsW/2PaDhqXx/lzDvmrNbF6HyZRmrkBqQfisLOEh@ZYmZpCOdNiUzY5l@zmgYbTzIchmEV7JSlBB/QuRjTRmIODlkNuAeyexGRfj0GY2KzUwwaZqZ2crpzI@k7NYkb4bJlwlE3bhwS5ovRLB2R79DkmOhrInv1hJWtkjUWzgkCOTLBNH/SSF9t5CaL6QrG0kDbFbNblY28/2a1ST5H0VPc5ovZKjjVGq5j27US/2DqDhKmiOrZ8Ze88w6qgqaNTUI6gMuX0bKCpTf@lJvfZF3qSgrRUW@yG7QqTJAgeXCXBZ8ceyOzZgtzTFbh8OWaEhjaEPHmGIB8frlX8E8qImYsEC0lZhoz9jpcsFgZZMuxiIzv4DyHEvYJvScPiI/VdyCmujyZtDP/syxdzJzgB8SQZ0YwLEB@FudsdNQWvA@FcYcM3fLQkp7VBVtoRkgx10yZ62RfUF@bpidOHIvfuamWcg0CMusgXqCoQJsl9smN7QkKoFVe72g4aaA7KQ4kzDJ7FL25f01VLG@aXBQHAqsZTNH6rzRWHEyEJLaRtI2hDpGQ5XDnnpuFPzJfDOZEJv6ROxHzFionbkkO5@xRjhj@8xE5Mi5bZRM9qkJnlOTZItso3mVYzZCJm5ZDoiJq7Hzd58wNSa5Y5owmAsZKTCKamefaKeIhDggIU4IWyE8NdBFstL9WSgQ1KERGIcvqYX1ZOJeqM8radXgAzrUY9J8YfgvC0QJETunkeOB3pSlddbreN9WI4sMaaJndDwHvhHWRlSc5Bp2SQxzEhdtQ84XxvO3VKP5AsyDhidf2aoBFoUSFvxsGMaPR0KAA/2YwVq@AxhvYB3IED3Lm9/a6avHnlzjBEUznHZ1iUHU3GN1@KL5wgbEIB0wDxqeimdma5F8w7eB7KWpaDkS7@Wrafd00XwhFGmeBpgHDU89bkE3AoDvk7M30nwh/H8pR50Uzy9m6G79DZ8cNF8If5vNrgPoZF@tf4n6Crs1L@VATDZS0@u8Q@@IumiiMVdBEfAvazEwHAqUGz6jA8vNX2e0ciHRXgSGfsWwJeQskA9fuS5RUW0AxNBBTUStVnxxJlLbWkzwQkKtcR3bemamz1uDaPCC@Br9iQhc0vPJJqg/MVdP72nVO1qdRPV1G300n77x8oUxkw17Z1YljJddRFzvsr7TgHnQ8OQr/cSw2AWHk46h9HPHJBLwB8qXpxuAdGR78aOtMNDw1EN1PiP9cM02/TwnNNwk@D7zDS3EzxCM9oorU5e7venn8Gka3NSEBMyDhqfiMPwCVpZB0HxhEzIlQcOxpovmC@mP8adDSwPmQdJqIznakko/NAYz4Oq5kYx2AwUJa4np69O3mBs/phsK62NCxXfZIPGkRxxe@ZJQuoxOrPY9rE5zuctw75JRTECNjlVu9XLiYo8jY@tPDI8esAl5TDaevcNvg8OWefLhEeUxYMdva2IadNFWPmB/6OIDy8eH79jXAQjW7pkpak/2LI9JlkNGJ2aXj@m8J@jp7RNXshyYXezouVzi4pROQo9psLLNN4RY1zCDB8DJpjtpAJ1sTIqUsh2JpZU6AFqt087@kTBXedD682FTT7SFjzzDuggwD2oivk1OzEkbRGLY4PSkjDwYtlhBCscFFwO9vpN8141u63Y5QX9VZKsMUYDyfeKhOxp6B2YFiI7qVLVJ9WDLpZ2qkB2gFOhpLM4mPyVMox95JLwylVyLdJCX8vj370jhqolHEJVWzDceKwuzjEINPhQK8xlBUB7WhLJn3yiyHzvdj7HT/bh2uh/c6X7QUDNkGiQlQ2lVwnEg7dj7MqnkGAwXKY8UssSuJ7oZg8cD8ZwZwU@mWWv5oCZSRJiXP0r0N49yR7WDNaeLNKAOkArjMKLLSDOsOx/YgnQBBb499toe2mt7jL22IKSbu24mu9vrE7n2Z2OwGxYxnfDCAQhS7xknbAwTDbIc/wAqLjCXcsp/0n4hNV8QG880BSqWjWN5RxvCgjpdTmRs1VGLh28E4X1Odgjl5O9d2X3uI3NpcurA7YpH7OEhjTabxr65E63@DVnEOVUOiRRWP2R1B4WVxMPmui9JBML4wiXTUNlkmvxM34vk@DsNGE4KerV/nCQ/YElKJyyiPmpZKBABpruPMd19XNPdh6a7BnywSajDgDwkNDh0fpxYwHlg58zPuqCcOqBUYGv7wR3sx/gU15c4rTlDG@8bUgzvxAiwu/SAZc9Da90PWHu6gHfn9zrRaC3T6qdX78QfuMUTF9jDLRP3ZA3QmwHmQU2UGc7NV@HYjhA9UTRKfMclulzGpN53SWF7sqijXUZHu7CjXdQFGiQKDGmC0HU7SvbhyR1TwyytQrsYw0oJ88aASGbSZNxoSzh64Eu0GI0tz4k76MsThuBLxvBswTqMi3hYrtGoLCt3opaVPdmy6rTLsuJgyjIMspbL4GqRmdWylhtbAsPKtXBHOuFrL37AQ5IaHwrGrSZ9YZO@rLG8vewlCuQCKyQXDTJeCA3pgmbaRVQAhwfaT8NHiDLfvomEMZwTB4ELTxMs1tQlvkNpMN5ZvJ2K0uNWAfsApDsQ@lFVlzrdKLASEcRXM2yQyGxuQI09JweMco0eD5tDXFiAmQ/ZNhTOOh1PBkURpzWByTdmdIs1aI3AFCUYQi014zdsH01uEAcFIiooB75xjw9tBftgTEZ8t1PnlYL@cIxITjQOIeGQtW/ryICZ2XDmEUFeu@QXsKcJ0JEDJz6wtWBcFVpOfJCTT6Jd@XJGO/2UAUdAHSA/PPhJi44nFhDcovce9qWy7X1y2vDkGTqTnYKxr11RYRvTZNSBkHDYNiZgn28w1nHEJMTJZuAHcZVmlLhAG3L9QQ2PrzPXgp8TbfcBTJQaRCcb@xxEvEmlJbNR1J3nJNFWpLx1Rokly@ekl@18o/HOvcoHHu9yD/kbezkAeEXz/0zT7DtvRH6Pa9PcrY0hqnUcXyG1mIxhdSyjY5MYwwDkxHwLQr6lqOouoMMpKgBONm@A03pwrcz6CTy2wpDIrz3o6KIMC0Wiaom2PwAp0jlFEtRa5urMk7XCJVqkp6UF3RUJjix/mbvHDowXiwtPTi6enFw8NaN4xn4TUpW904s25llucaD1qaHucwx1n4VTRQOoYJDwdJvVTidHEWWp2EV4sozLIO05rM@etD57liOx@Bspm32nTZIO@XcMKp6wNHu6WdmNCaho1QIeeLtA@Ra8VOP4wwmR8naOALkweeeCk6vPc8MJ@AC0r4ENgAYogF6Fo4DnuS/IhFMf6hwf6sS84HnGOowLebCEf2cbEaIgf49nQL4XCVfJbjwSDw2ik4YL1p7GtpnLLhl5EwTtSHte/HPFoMFKFrtHIw3j8ubLufECxFCw7oiDkOwGs42khXRDmsUHdeG5Q5F79wBGfrClNYIFASBdKF/e5mG45nvG87imBVAY7q7mYSSbw0aWL3acK9K94xvn/a69xUyz1pBMoGPEsXOJ0@GHfk7y/FEcvvF9p@Z5TwPmQU00gpzrki6aL4SqVdowxsv7Y9pQ0hyZnoce58DAMpJxwiv5MkSU5DwsaPP@0L08eX9OWOQkIfCw6w7MfxD98wiURyAb0KBxy/svJe0Xi03APKiJ8h/ITDFEcps@VFNsbbydkWLWgqNReUx4aRvcKchxheF6LGm@kP5WLxWq11MIoz2AAtF2KYcBMOGFuLvqhxP9@Cl8@X4bVOioswl5f2PACJgHNZFy6D2puu6@Ls@IZCYQ1AcoIpoJODX6Fib5zRYb1ER8XGXysHvnAk1LxXAiN5tdzAM89C@MUVxEpwqATwy4fvnYaCbgMb@w7v9rqthA/zX9/u0i@Z0zDbRD6n4ap2/IWLb4hff65RebwF1XnPzi@/3i2/3Su/0qjKGc3CshNWF0cr98Xj0LGoFRnDDD@aWd4l9jp/jXuWtVwBDbuQb48Czlv@LuJ/jYt0Sn9ZLB3MsnImsAz8K9EjbMTOIhBh8cRSJ58l44EuMC2lkj3xcPv74y908d5DXvMQoDUAs58MqMlysKFpsmVx4xjP1fHOa8Mj36HZ3ZCy3Ea0@JAj/zA79ZgVfMn2zWiqHJyk3xdYouf0UNW2EX6mVtxYuvaCdW3DZhU1yG4i1R48D7dd7dd2Ljw68TTNBDUslIWoZN0BkrbYsBCiLb4nV6T9zTWGEuauLLkJ@vEiSXy0FP/OL378zcXcdo2eiBk70kOsJObMXyFmf1Y1J/zek1pV8x0l7jOHWkwtpHts1EuC7olv2yKIx71pS5L7T6ociQWjVa2V@bXGBDCPqCeDJrTUwCd8hWObdbZrobHPozauOaJ/bfNvtLK2WdBkXHZr0a21zSfGE8JtOax4Hp5VJJmG/Sb3ziICTk2ndYx2lwHiHTYTGZ0a5a7veLDzBN4EURXDP3w2EoyAYFT4pJvdtNJ0USWAc2EquWW0To9Z1Q0gI7ntj1ErwobuXugUu8U5lYvQpLBKcEftkXmsOgRkC8RfYfoOHJV6blmI1HS4idDy/leMJ8zBGhSpMnai/brFVnCHiuzQXTec5K@tkQ8s206CU5aw7ZCJRK4YcrgEF/OELti0z1E5uI8dStPCtOz680@1nPnRZaRgsFPND8nLzsxoGPOXHZzYot5vX8Qdu/fjE9C@kK26RG1cbe0QYAuVW/Wed5Kz@keIgDHrLRBGKjSZnJ3wiOZZCQ8FgTBX7u0yKffcbn3iZ2V4B5UBPpoXuMT02@cAHIpvuCtnFNkNHBDRNOpUzo0rRt4iaTg/QPKLnFzgDmgCN9c5eb3rCOVzTqjLZy6LHFEfh5kNy@emrcg7VpgXSbdFJy8zuAGNBI6syoXnmMOBAfh3OlbfoWJAxfAof0Ns7fTO48PbBhR9eGRPnOj26Y3tRfptsXT0srFjI3XKSzWTusN0FrPS7Pu@7O09V5vmvCCB2Q@2k/KaBS7yiaTpRLkpwF1F30gMowNB7cZDu4DdPBLfXJWoIKTENCq6MeOBTJ8MHIaLMhSiyMbN4GE9jgkeYLEXCdKfCe2TtK6MeZ/Q0Wi1uGJd6Wh4XUxuZ849x3U7OOHXIkHeYIJpBtNkTGdUIkOmItAgAnG5EgOS1WQ4HHOt2FVTE3GniSGLxlPiZoOEYvw3P0OkS/5R8Vw927a7wnFntd4CWLhgcbO4Ot3PiMEkPIrczqWzaaoYTsgJO6DvCjgw0l5LfRdAQU@4SWHl4y6CmjJbLhKwabADqVA6tRfhKXuQ@if3/Su@CFkBe8vSKWJTD7DVwH0Tex4/CFnF2SfqwtAXDS1tFlJuj0VvbwwB6AvigCZbxi9x1SpKLHgtxWcNPddm18BvL7jFWkQMSBrbetvFn1Yc@66d6BbVw7sNHEdTtpkwGYBw1P6S9wWXvGOeRNi14bDWI3vyUITdRJC3kAYw28XBFdY@0IoFNCQQigk7o5J4wHN63uA/iMrq9/0mgIgAR/vWyIUOi/YVXiQk/4Yoy6Yza6qzfdR2@6szfdeQnfPm1ar9x1sSQgkrf7zOIPiuoB2/ZGiqIBCCc0@S4i3TYnwicCtIuA3Ns04HEREnxxoGbXGRoaoOy6KXNPmvjs3KDZEwXPIRp00ceP0lfgkIzwg8Rauyx4UeBBY57ptMMUZeeUc9di@15QpnYYu@1sV/bC4zR70XnU/TpTsKNm7zj5bcIrI1xaokDgPin6zhtInTgRN8wPDAOIDHR585tZfaPAzzc2DwI6Yn2jfwKE5@k3VESenblxB2yHZfl@@i0xeLKfJZ/Wi5owCuzOR/IAZ0g4RPaVG9cAHJDbTvCyaUoaMA8antL301qJxNkfEapxHqsSWxsgTXXxhtbWd0alVbNyxzy08AhsefDIHiD9gXVgAz0naVqmVjrisgxAOF39nm9JpNgkLPtCs3brVOgXHXQ5aMZqEBc7hYTPUbiIbchl40LT0sJjvyHjczltF0UTVnS5doEZajlOCeQQvnTRSTo34OmS9FqQWy7xRCcE5tQZQPWss4RAKnJk7DWjzDFNKGe/Y3@d1IjRQBrMHDoZjqw7O/fkSPOFDL5io8foYIn0xmNJF80Xyp9rPIb8lmf/@Pabo5W0O9qKwDJwPkUPbE05PjEyclxjLSOoXI4FLxKIlL5pueRQMfAKLAP9TBmRg/JA3F3haJ1tJICWOsNOh1Y65eeLHZzyG2EODOpMeCNTgS/mzaFd6mOsjB5jc/rg5vQxcYnOQV4zfBTNIve8s6s4OP87aDMbktpj7zAQWqvSuUJgvTEkFFAij4mxKRyNGwJwBC8wyp2TtebThXh@xT8FHH5ftKLB6OzQFbHHuCL24BWxJjHpOXRz2cGrakLOAuq2EdoqLd@p9p1fIAiajecASHLMTGLjfwI4cbfJkWuth88OQ2puCGoipYJ7AH6rN82DDp79Nplpawtkjpx6p1PvdI53euvG22P6/msKzWTfEvurB63cTOLiLACdGj8mCI7ztFLSb5YJHTCaDCACIEd5oZc1sBN6xUPvlPxODwCL8ZiSanfPpFt8gHjw2Ynx4GfhjR@H2wvzmzgymfU@3r7mMjPFjnTk9dhHdGgoN6kjqW4TARPwQ9elHbou7RjXpdm8Ne0xsz9813sWNMLQivF8SHjVEWe94vri8ixA6NlQNwJaN42yh5O3uhPowFT1oCWASVSCjHXokHhM1ip0EB@IW1gPNgqq9vlIbOUd4dQZX39MfGIQPSOX8u/fk2S4r1x@BsyDhidTsXoD9QXt8uUg1Kkr7GihVhW0WL6vF9GxJ0k58FKgQ8vrx1hftxI0cen6WHVSFFRFemxBKnXRQpD8MD0yiS79KKPxLmmjZJ0pNN9zgI@2AUl0xOo2AA8MhG/sd9j8d0K4lT9h@gZgmFVHnB279GiFaIivGDdJgUplYmQv7IQvhJNSh27BO8YleAdWcE2c6jUC@bxY/vSmkuPvsTUfUAc0kiLVH76Q5I1/ACDJERK1mIdYdIRlHGA5ii7YN6LBTtBK4IFzRyZrlCujg/23zxnKAD7irBR8tHatnaDx5qbE4bfeQFsrz8e18nzUiZ0mX7PyFoqAOqCRRijkROUl4wAGTLrawJB3f5HmC@VPU87D7xGKITuJjg9@XyO0fAGKyJGKC09/G256o6AmjEGyD615lxaR/rwqi0THN@blThh1Hb7IOhOUF5mvyOk2ADFkxZ/ZGfluO9swWYQAmNf5zX6gYtU8JKIoN5XnWngmjUT/uzVueMfiRh6IsDyyAj3UkDv2AXLi3W6GMqow5BiWRNUNpwJI84XyPy7XQ/FzHmtUHnQ6nomP4QezKDKVerkX5D12YUzCxM6BDRJovjDibemco76cY7R6rgcEnuMyVLGjcmjH/Bg75gc3WQ5ush5jj/UYW6xBUt/ZFgZIcbSFmEcfWGA7uH52nAdKl0s4YI3bJIvIWfEvMwbtvGAe1ERKhyMe8vs3gzrMg5qIIb42SfNs/eucuCZqpNbxrxPHHkLSgev8Tl/IKPUmkbAAajBZf52ZN0wbcdUdxKD5d4gSF9eE9AjCorkPoFMM4SuP8lUe5TMJ46yqM30O8TciAYgl1oiqjEF0m5pNFqJf8/nDnZHMudALZvOcVdaJT4cVQkXz4IIXc1cu17nE8qqbUt9iyjguXrjuXdC1C35VG5qvOtGDd9yMG24cFGh/UdCDAbtC9KHITDuQeHS1LpkhUWa1bVGnEa7HX5/gLgHmSFeOMEqagQDmQcNTUb0TxUwJjbf8f8fCtPcZTIUTPZP@XCyoAXTszTAuyQ5JB@pqCOPI4VZNtxN7MaQ2MLIi3fUnR0B42zj/6CIsQ3mXhewMoN6Lk17HqE4ARfjCaMKITbSR7nVxfKMuGfJIDYmBOqxKjfhvEaT5QmjOiXdXeh9KI8B6uemkIKiJlNuPNf0AMIAFTH2gApfKDH/woIATzuwZoRtxwG01Th0JWKS@YGnDQSUsENEuNfHV8X9DNa3TjyQTsfKPc4L0BiuqnE0puODqqAA4fRDQBCidoPlC@n8V76ZVAT9ePCPiTVfL@X9O8W32SXm080hYkKJhxlzhtF1Rx9HWOuamlcMQkzH0CCltXTYdSC18p2HZCoTfMXyfvAXAUINhaxWwkAVAiHY/oTb@S8qRsWDhLCS1MQQCyImfbvxVFFC@jVHwfD5pvpCKGrsD6WhDY6WzT8N1KI72w283Yolr0jr5rTQMvEaBQQrKKx0ClH5dWmiU2ar0kdud5ptBIxberuQ0StvJL2DjmWXQKeJSErEJEYsPQ@Wd9eV5IVgdF4LVcSFYvS4EA7Jxehc2ew4KU1bmEf9LCkCnyvsLHDH8q8/vRtmf0V5YL4/4sR1h4kmBgpZ1kXp1oz9osrzoJM71Xxe@jjxDyrg9ji/OBOmzN4DB@bjd57rch@eL9N9vVTkz8iU31m2Dy4k6LySF@3sAeL3p8h4OrMGFdajckCSXdIDdTcWOdi0aiPCObq4C21AbKSzqkQyYME6gbVwdC/UhkddOmPL7ABuCj0V3hTF2LTz3AZgHNZGeNHaqqi9PAHRKs14HZqsOzFb8R4sL6SjWU1fhARmMqUMhpt0Tr1ytWIxzgbjO0UudrIIn8@aEHWhIekiTojJmjsvHFavXDauVVyO1yT4VRnoNg8Wm9fE2VsUbh40mK71YmAF/uEFtmUJEc9K0w9vGDm/jkLH5f3aiawpEgqwo4FM3HPxq8ceT86AmUmT7TPFB7aPtepvkn/mqO96v3qcYJreJbVqbcGagxRgt4r/zTx8D5MIH3t1WayXtUuM/egVdigyK6xYAUdUd5aQYqh5UH5Qjngrr0@b/y6HHaCvetxNNtRAxrgqCr5UBmIM4bnLkyhYJjqg2JpWkMlJQsELZ/Gblg74VxmJNFycD5MmLzhovRQ45/D6Kt6JFN8iYNhuVdR2gEGwFrI@OJ8Gcq@mvOR0YIy28Gvb4G0@rtRQ3pEPX7zXERwikf6eI0bcOO/hRB2ZUYmgdgSdBa4UVtm@GYlbc0micmo@bmMUaCDXZx/oAIyvCv3B2vKUKG1/fCJ7oF9SI/PCpyza1xSVBTxLn0o0nZUxi7GFwMuN@ZLRhGOKJPaWQjRBzOINXktwFVFEDYcRYeI6tPXmdUgC1j6FdYeLC9snFLD@s7ZiMK7Ub/8nEZacHi4JBlx9GVAB4yu44SHHT8tgbwSQ5C@QzlHckUf1r0PA8qB6jlPZE/xaSyuMf1gKhXRIFfzIV2Cl1OVLKnsygduZ60HAk8On6efJkoWOXVILOK/ZTAZhvtKUBwOvsM85dNxiaNP23CwCRjn95aTxT6ZLnJ5sGOA1bzW3Ye7fLtLvJMMUgrmF04zr070EdwCN5zf/2DykNavR@0807hZg3GmpxvPk6ZCVRYKOuKQn8s2FAI12e7ABU1UyqTbjMEhv2etq4hbHxEsaWmT9DsZ9KWNB8IRR/ePGG05MyDz@83W8G4x0YNpyzDgJZ9OL1QACEi7MjMwhKcT7ZxSH3UbZfLNsvlu0XbGjaGldv@kEjSjR0K9Y7Qka41Wouo3KkWywqtBXD5JCzoBEUKNNnTpLUmIeGzgsYbhB6kSB0gdfVOY3HANpaYO7ReCdd0@U4DTt7LqjIzmrcntB4e4JfWMttIENk0Tbpt1q0TdeZBzGGDbdVhWyCePqmMdLGBWsHhcooBhuWgEPOgjqgiQQKbk3Jk0@JyzvbzoHePvEnxmk7jrGExAOcGMvOTe2AiGzH//u0vdxuzPAdTX8Jy5BW8Mdcrfg6JRLAVlKzgDY28ZqaSPwLZNPoxG8ASn8QdDCa4ZzBZAx9sGrfuGTPfTy/ShjFCfe0NdyD4wLeZyT14NqqA1/4QDk5NCpzOwH0nUe6szo6bairftIR9/A0FsQjJVW/Y/xLYiDcnmyUDkXG/0A1eNEDpeVAlT1y5fMzj4IaMcD4yebESQ@Mg0JwZeYe4681AxG28L/YSHSMaZVLBkRx126gAXqZg2u4jVtqYUyN73BwUtKOs1Jw/6v9dcYajEsOOIPkp7GnIWpXwFBU/fKF@tg3Is0Xhn9nadffYfu2JNt7EB1zlaQDvkKHcY7LFTI2UELiWX38/0ggQ7MPw00aLvRTgaqSV0fgyoTWS@kPT6l3JV5bFoFKZeXaNFH@7zRgHjQ8x0M4Yu2@5owq6yhQqekaZHcO/DsueXB5UFZJPi@l8SpJyU4MvPGn2nCnocwMtYgKIfNdUx0JsnEIEslGqfNr5pGV@cpKfWG1OZ0NissdsGGPN25xYDZhgTgkHLjOBpCThhKGH0okbMyHjNjm6fJxANM5Ln92ZE/ecW9MSGUR13ia/sbIgP2DX/U7UnHyf3db55@7GzwejMNIeWKI6GR0TpovpP9OsctvTHf7uUsnWoX@ZaDzZiURIxdHAjaLAFC7a2eXG37c7Wv4U9ZKjE3xdtp4gbPwwARCSk7YYbSTR50d5IWvcO4z@iy2Tri42oT@XsJwpwL/68toTBzOg8kxeQMcGpmew5jV0FfPg6qu4Gy@5clnVy6jN9/1POlbuSvd/P9hmDNWRd982caTCqTw/4xpF4iOG8Uhicz4XA3WRw3WZ6LSMZSOS4k62G0KKS9e1@XQJS@/Tj@0Cp9rYPjRwPCD@w9NYoD4wXjuk8cHM4SmfsMK0GWijOz4oPf9bjf@lamhLvIydNM/4ROn5x3xdzukeM7XSgasYA1NcbvI/TsOSrNX6Vos62OxzClqEGAepGDrpUcntLqA@MpA@XKjjcvzLqKnBvABjlKCxNiw6@gh@zEXUTsBDL1yIaNPSuaKR20Isy8KZGWXmk2BW09y0Zv9aCG1c8vKZIY4aGPTw2QGSWPTaPKIIVBHQeu6Hq6PAtdZ3nyKhFVLEvS3YwDelncMh2RUm2zGAxEZl4a6lmf62JLqbhxJJYlEyVfkwot1Rxtj0Z/G9hSX5yRhTE2d8P1oEun/Tsc7qvRHdS6xUtOf/m/yswgT10A@4hnn@k3ENXQm0bv1JxqeriU/A11Z41ij7yXJn32dn@6YDmpWmKcExWjQ/w1Tag1Z88QKQec/vbp8pwFUwZ9XO3RE7VscsTBgeFJAl5tzAVj9ANIXF9QB6HQy8sr7o7tfFOSSKbOpIzIx84Y6gy8FMzKzEI3dGN5i1Dkjc9N0KKAgYHmooxvmQrK2xrQxFhKNydgh6zCb6Pyvz15u0z3@cYWGbr2wy@42Nk99APy43OJDFVpBADtCoNra8KWXAYwVqcCSU6cJrUnYkPJvwTsG@p03o/ZyqEGC@WFHm9vR5Ppfqpx0QAulDwpbPReZLxkEHSw1da00dVrxd9w832Xn0mXo0oeBSx9/EdivvwjstIbv@qeprjv/HIbOgk1sJ7S2tGQJqXCaF3UZtfiIDn/lFLQJ2/Me88Pu5h3SRPwsu3WYvTp2@r0g9lmyCaDAfxxy4Clww9uQ9GPHUTnqNXhIl1MbEtVU76uuI/LRo0IchVoH5WkdJOgdxwh6rMMjWIm/hAoJ7fH3Lo6Nzw6Co9uZIc/OnfcZOPIFuAllALv8jv/zc4GfGGS65G9@Hx9@rgPgh5X7kJip9w@arg9r7IeF0SXi/eTRZ31UPr8HN/tJ7miNSU1rXLt77rdM23J7o8jEc8e/1QbO/EOBIBhnADNUMRc3SSVUTwck5NSftp47/w/FXh63TJ77A7NUywaeowM10ldSUWUmimYmBr7FQLWuGLoi6CNcp47M9m1cjGbLIZpUQLrcEIff4oCwrAg2aJ4eiKJhXdOhQ3KkayTDZUPUGj98OyOmjqyyUgKPsw3lU1/igzH6eejmT9J8YSTw0GGo86AFh4Em/edBM4Cz3qJ60zrx5AF8l/ijx6A@YJVbg2Q@jnQ2PxoCJe7fvSdrQCIqozOGrm@M698Ta5v/FUQ81gExvnnR5VsXXb4nWmECqD6sMN@TNyT3NLBfFP5Jf0X1Tk8e2SHBESlK9n1RJN5out4aMb3HQMkpKuCbrVr8a0VFjDD1CAmvmDS5iIoKWL/CHpMAR@zgOzEcLaZ9j4tVgNiEjEUBm3zaSdAg@@0z7YDM7/Q2nwqpltIRwxL/71@kK0BOuHBoGKkEVAJzJjPydcWQlYQY9i7H/YvEFG5cOHErBNhJ@CiZV3QYcKwYxGjrOSRdGit8kFLWMlpN0tAkKN6m3cJ3Yd4VrtvzH/fckIbv4X8PTi90l28aTLusklBQOsoZCx1vGxN47B9U4Q/r74eV96Pu/DM90OF98MwPc/ODNbsP168/3Kf8aBXbJ8fR9HwmDvQB1JZBGhuBz8QBvYMiwOLPB38ERTwopHwM5YMaHKqRvkD68cjjB@YPHy1xfrTA@Rn7Bx@famEG8Jm60vpOFDMlnRkGi/oueL2N4RoTFsAXdKCH@PBfyT7@N3/rAHjxSORnbNZ@sFpjc/gXLglxYvV3XOGG7T/7tPzjjg861U/SIvXniclpyPB6suB/nlHlPn6hKlWCoMSe6/PkVXIGMT4JGT46HP/JM95Zt5J8MluwT1YL5oRAGG18hvPCn7DwAMApNpFczJR0VlAWLU4HPpoDWG8FgwHvtiplDE4@PApm8jnDcsJQny7j8NwHS34f3mfwybz694MVQBd7yDia/SnbLWZMn@JLG9EwfPC3CR/c3PHhvyb4H2OwKXTUixuy93dsT@RxqasCbRT8yduPP@zdP/gz7s@wHAHVi5qQuUPDEpP4aBX/oBuSMSTeMB2kYAmjEIMdQgdEP5yHhEkfH5dlO/Hx9VIUisrdoy/y80tbwC@uk/ta5Qi9b4rrw785hXl1yNCzN8b4GxTPNIy3@J1wsQ7PKP/mFOy3/@viP/6/vfz7uy@I/H8 "Japt โ€“ TIO Nexus") [Answer] # JavaScript (ES6), 164 bytes ``` d=>{for(i=5;i--;)console.log(p="....".replace(/./g,_=>(w=d.splice(Math.random()*d.length|0,1)[0])[0].toUpperCase()+w.slice(1)),(Math.log2(52)*p.length).toFixed(1))} ``` Assumes the dictionary is passed to the function as an array. ## [Test Snippet](https://codepen.io/justinm53/pen/WjmBQv) [Answer] ## Mathematica, 71 Bytes Assuming the dictionary is already loaded into an array called `d`. ``` Table[{#,Log[2,52]StringLength[#]}&[""<>Capitalize@d~RandomSample~4],5] ``` Explaination: ``` Capitalize@d - Capitalize all the dictionary ~RandomSample~4 - make an array with 4 values. By default values can not repeat. ""<> - Concatenate with empty string to turn array into single string. {#,Log[2,52]StringLength[#]}&[ ] - Put current string next to log(2,52) times length of current string Table[ ,5] - Repeat this 5 times. ``` [Answer] # ColdFusion 216 bytes ``` p={};z=arrayLen(c);for(x=0;x<5;x++){pw="";r={};while(structCount(r)<4){n=RandRange(1,z);r.append({"#c[n]#":true});}for(w in structKeyList(r)){pw&=REReplace(w,"\b(\w)","\u\1","All");};p.append({"#pw#":57*len(pw)/10})} ``` This works in ColdFusion 11+ and Lucee 4.5+ To run it: <https://trycf.com/gist/ff14e2b27d66f28ff69ab90365361b12/acf11?theme=monokai> The TryCF link has less-golf-ish but the same code. I didn't really expect to have a competitive golfing answer; I just wanted to see what it would take to complete this challenge in ColdFusion. Especially since there isn't much CF in these answers. :-) After the setup, it was surprisingly shorter than I expected. My first attempt was a little shorter until I remembered that the same word can't be used more than once. Even though it's highly unlikely that the randomizer would pick the same index more than once, I dump the indexes into the keys of a structure, which will prevent duplication. Then I use that list of keys to build my final password string. I also used the math trick to find entropy. [Answer] # [PHP](https://php.net/), 136 129 bytes -7 bytes, thanks Jรถrg ``` for(shuffle($a);$i++<5;){for($s='',$c=0;$c<4;)strlen($w=$a[$k++])<4?:$s.=ucfirst($w).!++$c;echo$s.' '.log(52, 2)*strlen($s)." ";} ``` [Try it online!](https://tio.run/nexus/php#VZ3PzuQ6cuX3fgpP4wLdd7qnMTDsjW83/CCGF8oUM8X6JFGXpDIrazCPPeueiDjnUOVV/JIMUhTF/wwy//Yfx3L80y/T3//zD9NU59dUv/7wlz9Mt2mfy35RC8xzCrmXuk1rYFlzW0C1S6ZZlPfnQMZniNhqmaDX0o6grdTbAEbiCP3W63Sn4lnhe7Y0oBH0TKMX0vtpTO79zkcFNFJjJEC6WoQD5kHDkw9x7GULzFArdYc0n3wPrGX/bBchkp5fU0/CtH6ApUpC7YTOPB1dEulxYiocQ3ueM3IogHqO8F1STQPmQcNT0X2blE/zN3sLqjpCdcuMpxz6rPO5dkkovRTFK1XkpdNwklZuqV40HEv9AMuduWTJw0d8Ij3PtM8ToUtG@KdlsksrrjMkXyzP4Z/rvU6PDjxYbr9yvMc61Q2hnBjOsQEgbil3wEmPe1lKpG7lO67PdKuRvjVPLDhrTrskHZ67JJ9qpKcaUusrcmBd0/OCeVATKaCl4Ymit9rD9zsDZWmOPF1R6tZyIrZjmSRvKV5jM82zgn4kyVnQCHzydsPH3G6ZH2WzrySZBkndEDEca8S9T886baC1PD@kD/MvsIPqfaG31T@QVV9Wnz3d54JX3J9plWwE6DxXxvo82Ybt2doJuO2nMmcv5kiq09cA6PU8HtTz7yfoe7bKH/RZytvhmDqSexz@eWZgmn7GRtrnAenC/H0gFdeJbdRxlIzcBoV/vU9orQ12wkIxoXAYsYUEzRciirRHcajPc7rhAwHjTarV153A76mqMyoOq00tSGit00cSHtb49AEM7EhfayJXUHlOOzWRoy6h1bMa2kA6hmh35mZAuhC@y8QEt8UyCYBXb21ig2Y9wsaXN6x9AEM2NWXedVwwfNWjmFRY6bPyB0hfdd6o9QHDtylsUUrKlRL1rKZv3yRKal9SbtugflFodjZo7MJMICMN4F7LPff4Zr1P9y88KbCR0Gx2q3h7oqJ30@F9zplZZ1RC4iOe9gA2Qe8JTalLRO/E8uPYAHWWb52Hb8WHfD9OVtbvyGyrgJskHVzcbAiTCJ8Q969bidrhaC0OyWMGelZOgfMTeo/HesE8qImQuNv0fE4M8YTfV6KYKemsAKu3YPOF8LbWohOKAD571A2X@zSAXjMlYt6/6nl0In12PsqgEpSQHSo1UazIq/rEx75hjOiCcdTxDpXR14K28ObVeRashMxHBjUho7D6hr7DcKFgFKydDkM73@n0xXxq/N2k2/Uxg@DY74i6S9QSJcaRGp2fObrGW5oQIkX3ZGKnaJB1lkyDmMakp6YpKmBIOvB3T4yujzDSOKP62WhYKUyMLD0gKgVcbQzAD5qW6cW0ODWRnmASbjYueAwYTi/Gsq4U9Cn7k7GuRfGveI2dWbTPFHoUi2PaEzOcHzg1zChsrBElOL1Z6DLKsQ@cZoFcGClbFpf5jpqQ7587HYMQ4olq45KRGcXo8pbX9VHWmYiRLKkRIfF1M79jrngLl/OEmNr9zP0i6LWlHAF9mwgd2bqyBTVADrikA/qkALnwna1ZYClfVZFXlimXCtf60GdBW6eO7tMyDfVjVR8FGm4Kmd4hMr6lS7QCRl@QjKfcINg5BCmSopcsZZZELOU9dN47JVRPpuWMqeCtsCKUG8STpc@AMRjhowdQi@KEzCsFw2Y10kbQQCEoKMhlu1FQ34az1N@YDGQLuw4TdOXzCvPCQAHLF9txIxULVuhSGn34qtaGVACjMUnVyieptcRk81bwMYo3WqATo36HeUJpd6QnnvdGtsRQzOYqaNxd0gEdVlVPVScOoYKYgKq@prLhrdMLwdI0U6K2BKSLLl9GL5dL6hmJbZ7BD8ZgLTbazJrvX5JQyvOTMeYna5fRwpoXiLLMBYiQcrHUoCX14WUaMA8ankrciV6qnh2t0Hljy3QiYSfTdT4enHUD4fjEbAQAp/VGwZ8rBcpPAHy2KEUnm137unyulZ8dIMHHVnXxRo0SkdY25FBh28FVjxvf82z8hQBq0AzYaJ4funz4Qp8DReM@3W4YEhnlPV7nzolFyFlAbdbSu42qrLeCGsN/SUB1vZ/rSfRlgQpcE2ELsaWYkAOgHVnoQj8Zi9WedcBwQmw7fyP9R@4TNRjJ0c@aLpovhH@9RUdjQL@aGHNlN@7EhtpQuVAPZpmNlZQPGks5lT6AISl60QOd4Nj47Piod/Wqd/Qm99GFOPEDNcbazglZ0/nknvQiPY3Edr1JX8oak4r7xAi6YjwbYzq5inRH2@EiRkb3pHQmDgAc@IikVvzOwYnLc8W3T3srFzAORyjWtGGNyOfCyBGDSli/ILma4XQwgctUMNc0OihQUhZ@/sUX6BRTxeTJaZNEYpYxSQ6UfpfUkzGlM4jGKOQskM@Ih6EVpHfpdn3OJU3H@iF1SaqN4WcgIknWryMpKX1R6ne1aZeQ2onJTBsmmyT6NskuuZ/EN4WS8h4peSOQNe9pv4iOMXI1uc5YwrkvJd@ZMSUjoeWgOBi5kWIv/GiloigaUKeiJVjQiodk8FMDnEBq7V@SdKh39Gv3jN78bi3YFs1PrndJNnVGHDMGsgznmCDfOS12CY2eByAZBj@YI/kVY52QOeYo93WUwpW1fdVEyonlyQkFGzS88@MzEI/TuhMAijYRYjxO9aLLGx/dUfEYoiyunEcZ2LSDwdGv31euJAKglR8PSC4iON0kmY6sQVsgw@18RQd88DUfFIcCjtJhyHCYzN41oL1jpcDEniTpjlUeB3YCNmtfJIcDH1W6voORHoq12JDwO5n6k7rn1pBrvjRfLwrfgnmqyRUCa@8GyP8ySUDdByv1Ijj6pgAyvcSg0MUdUzVHpN6ASS5sQgt65bKyADv0dNF8IfRXNKouP4BzY1TbjQm19hJ@2wNrXncuUoWkMiqWSzkkjH8dcx8g36KnbOfOjNoObC45pXVAE/FFguYL5Z/XdNF8ofxXvsRRGvPb8NylWdk2OmZ@MXsDpi2oCefhjdXbwKMPf@ZSULlQ/lf06zmiOpEmG@Bv@0VNuCsM5iEBu5xO5lsQgzz0PvsjS/ExSk6g/Nes8PaBGfujFpa//cmGA8RATcUzSI6F32BvWLslyfvc0kXzhfVCqvZpvEhP29GF/FxGbbh9H5pFmdjr@DDa@wJK9ZU@hPHur6xHli8KptHmkGmAVFTzyhddVgoFWocGCw6bN5P8LQVr@JDuii9fD6bYAbo2ypwxnCpNla@pGrTOsu0zgIDziSbIZiaZTz/tQ60X0fFQcp2GmxJ2Vo5yjTjKNbK8/wgZpLGRshxWCAwa6oQ@pGrpOojxVy7BaC/QJGYDLqW9HUObc4Q6UanxZ8yiQyrQex2B3njVimVDl51lwxF5asNTLmYFdoZgbCnheRgh@SwXPYxlyUyJABnF26UcMhs3GwBwGdsRHzAAihggVY6FatGYIGi46Z3Ke5ZMg37yZIBY1rnX856ZBjY29UyrJIYl9WSTFDAPaiJFzpkuQIq7xlmciIeUZ/vJT7F8BhzKik/rTGRQBDlvCQI6NtIr0ZieM9YKbJhmTXUHSZwcRgbi0afW1e/ncStYJzaEH2cmQ1fTp7PyGdU64ruQEpllxR8rNiRG8EqScNDq97BTAMATfZovlc4EPt8JTRwo1D@@Coh6@OFA6qNx1Iw6NE/RfbiIKB0QpVODPEKgf5615zFrx8NBQXauicycKrvkb6nUrx1djeEqxygIs/YNZg1357FvME@nFoTm6Y0k2@uZG7CjMs1pmlf0X4EfwAMCAydAA2HzYE43jnZAw40PT7cOcT4ln1LXglAgAt65NOyEFNwz7FmMviBGKoPmCxmwzGnAPGh4KmHWg9PbqYnkTT@sxpk8mFSDhld6TOxwDTHBBDDkg/NKp3sfIKd9HpAupC9e/VknvkrQfCHUMNWZ0zp96Gmk9K/YdjZIXHEwzDSGcGQBAFE1tiZMWjfDINs00udbVUK0YgayibJxU6bnnpm@vfBhDnRiuL0p8XvPzM@dDuMVbPyY4aUxoxP6FNJ8If1VLI@TD6hetS6aL4Si9s1JdMTIEsAw2v0OYiKC5gvp75vcKC7tq0eXY3RMmW6Hss@Xnn6i@UJE1DHDAdA7kN6JNlSOlLQbmxNmxy5hoOHEx77Y94CGp/L9VcK8a85uXYTKl2WsQmpA@q0s4CD5lWfMJB3ptCmZGcv0c0bDaONBlssgvJKVooT4EyIfa8pAxMkhswH3SGY3KsKnz2hUbGaCSdPMzFZOZ34kZbcmeTNMvkwg6saFW9J8IYK1O/odkhwLZU18t5awskWi3pNDgkC@TBD9Fwrpu4XUfCFd2UgaYLNqdrOyme/XrCbJ/yh6mtN8IUMdp1LLfXSjXupPRMVR0hxZPTP2mmfWUVXQrKlBUB9w@TJSVqD80pd66Yu8SkVZKSryRXaDTpUBCiwX5vLEF8fu2IzZ0hyzdThsiYY0hjZ0jCkWEK9f/hvMg5qICQtEW4mJ9oydLhcMVjbpYiwy8wsoz7GEbULP6SPyU8UtqIkubwZ970uOvZOZA/yQCOrEAI4NwN/qjJ2G0hPvU2HMMXO3LKS0R1XRFpoBctwlc9Ya2S/I9w2zE0fuxc/cNAuZBmGZNVBPMFSA7XLb5IaWRCWwaq8XNNwUkJ0UZxImmV3Kvrx/DVWsbxocFIcCa9nMkTovNFacDISktpG0DaGO0VDlsKeeGwV/Mt9MJsSmPhH7ETMWamcuyc5nrBHO2D4zETlybhslk31qgufUJNki22he5ZiNkIlblgNi4mrs/NknTI1J7pgmDOZCRgqMotrZJ9opIiEOSIgTwlYITw10kax0XwoFgjo0AuPwJbWwnkzcC/V5Ja0afECHekyaLwz/5xOihIid08jxQG/K0jrrdbxvq5FFhjTRMzqWgS@EtREVJ7mGXRLDnMRF25DzhfH8LdVovgDzoOHJV7ZqgEWhhAU/G4bx45EQ4EA/ZrCWzwDGG1gHMkTP8ua3dvrosSfXOEHRDKddXWIQNfdYHb5ovrABMUgHzIOGp@KZ2Vok3/BtIHtpKlqOxHv5ato9XTRfCEWapwHmQcNTj3uiGwHAd@HsjTRfCP9vylEnxfONGbpbf8MnB80Xwt9ms@sAOtlX6x@ivsJuzUs5EJON1PQ6r9A7oi6aaMxVUAT83VoMDIcC5YbP6MBy8/sZrVxItBeBoV8xbAk5C@TDV67PqKg2AGLooCaiViu@OBOpbS0meCGh1riObT0z0@etQTR4QXyNviACl/Rc2AT1BXP19JpWvaPVSVRft9FH8@kbLx8YM9mwd2ZVwnjZRcT1KusrDZgHDU@@0vcYFrvgcNIxlL7fMYkE/ITy5ekGIB3ZXnzXVhhoeOqhOp@RvnPNNn1fJjTcJPgu@YYW4vsQjPaKK1OXu73p@@HTNLipCQmYBw1PxWH4Aawsg6D5wiZkSoKGY00XzRfSH@NPh5YGzIOk1UZytCWVvtMYzICr50Yy2g0UJKwlpo9P32Ju/JhuKKyPCRXfZYPEkx5xeOVDQukyOrHa97A6zeUuw71LRjEBNTpWudXLiYs9joytLxgePWAT8phsPHuH3waHLfPkwyPKY8CO39bENOiirXzA/tDFG5aPD9@xrwMQrN0zU9QW9iyPSZZDRidml4/pvCfo6e0TV7IcmF3s6Llc4uKUTkKPabCyzTeEWNcwgwfAyaY7aQCdbEyKlLIdiaWVOgBardPO/pEwV3nQ@vNhU0@0hY88w7oIMA9qIr5NTsxJG0Ri2OC0UEYeDFusIIXjgouBXt9JvutGt3W7nKC/KrJVhihA@S546I6G3oFZAaKjOlVtUj3YcmmnKmQHKAV6GouzyXcJ0@hHHgmvTCXXIh3kpTz@8SNSuGriEUSlFfONx8rCLKNQgzeFwrxHEJSHNaHs2TeK7MdO92PsdD@une4Hd7ofNNQMmQZJyVBalXAcSDv2vkwqOQbDRcojhSyx64luxuDxQDxnRvCTadZaPqiJFBHm5Y8S/c2j3FHtYM3pIg2oA6TCOIzoMtIM684HtiBdQIFvj722h/baHmOvLQjp5q6bye72@kSu/dkY7IZFTCe8cACC1HvGCRvDRIMsx5@Aik@YSznln2m/kJpfEBvPNAUqlo1jeUcbwoI6XU5kbNVRi4dvBOF9TnYI5eTvXdl97iNzaXLqwO2KR@zhIY02m8a@uROt/g1ZxDlVDokUVj9kdQeFlcTD5rpfkgiE8YVLpqGyyTT5nj4XyfFHGjCcFPRq/zhJfsCSlE5YRH3U8qRABJjuPsZ093FNdx@a7hrwwSahDgPykNDg0PlxYgHngZ0zP@uCcuqAUoGt7Qd3sB/jU1xf4rTmDG28b0gxvBMjwO7SA5Y9D611P2Dt6QLend/rRKP1nFY/vXonfodbPPEJe7jnxD1ZA/RmgHlQE2WGc/NVOLYjRE8UjRLf8RldLmNS7/tMYXvyVEf7HB3tkx3tU12gQaLAkCYIXbejZB@e3DE1zNIqtIsxrJQwbwyIZCZNxo22hKMHvkSL0dhzmbiD/lxgCP7MGJ49sQ7jIh6WazQqz5U7Uc@VPdlz1WmX54qDKc9hkPW8DK6eMrN6ruXGlsCwci3ckU742k8/4CFJjTcF41aT/mST/lxjefu5lyiQT1ghuWiQ8UJoSJ9opl1EBXB4oP00fIQo8@2TSBjDOXEQ@ORpgqc1dYnvUBqMd57eTkXpcauAfQDSHQj9qKrPOt0osBIRxFczbJDIbG5AjT0nB4xyjR4Pm0NcWICZD9k2FM46HQuDoojTmsDkCzO6pzVojcAUJRhCPWvGb9g@mtwgDgpEVFAOfOMeH9oK9sGYjPhup84rBf3kGJGcaBxCwiFr39aRATOz4cwjgrx2yQ9gTxOgIwdOfGBrwbgq9DzxQU4@iXblzzPa6UUGHAF1gPzw4IUWHQsWENyi9x72pbLtXThtWHiGzmSnYOxrV1TYxjQZdSAkHLaNCdjnG4x1HDEJcbIZ@EFcpRklLtCGXD9Rw@PrzLXgZaLtPoCJUoPoZGOfg4g3qbRkNoq6s0wSbUXKW2eUWLJcJr1s5xuNd@5VPvB4lXvIH9jLAcArmv8lTbPvvBH5Pa5Nc7c2hqjWcXyE1GIyhtWxjI5NYgwDkBPzLQj5lqKqu4AOp6gAONm8AU7rwbUy6yfw2ApDIr/2oKOLMiwUiaol2v4ApEjnFElQa5mrMwtrhUu0SIulBd0VCY4sf5m7xw6MF4sLCycXCycXi2YUS@w3IVXZO71oY5ZyiwOti4a6yxjqLoVTRQOoYJCwuM1qp5OjiLJU7CIsLOMySFuG9dlC67OlHInF30jZ7DttknTIP2JQscDSbHGzshsTUNGqBTzwdoHyLXipxvGHEyLl7RwBcmHyzidOri7nhhPwAWhfAxsADVAAvQpHAcu5P5EJpz7UOT7UiXnBcsY6jAt5sIR/ZhsRoiB/jiUg34uEq2Q3HomHBtFJwwVrT2PbzGWXjLwJgnakPT/9c8WgwUoWu0cjDePy5su58QLEULDuiIOQ7AazjaSFdEOaxQd14blDkXv3AEZ@sKU1ggUBIF0oX97mYbjme8bzuKYFUBjuruZhJJvDRpYvdpwr0r3jG@f9rr3FTLPWkEygY8Sxc4nT4Tv9nOT5XXH4xvedmuc9DZgHNdEIcq7PdNF8IVSt0oYxXt4f04aS5sj0PPQ4BwaWkYwTXsmXIaIk52FBm/eH7uXJ@zJhkZOEwMOuOzD/RPTPI1AegWxAg8Yt79@UtG8sNgHzoCbKPyEzxRDJbfpQTbG18XZGilkLjkblMeGlbXCnIMcVhuuxpPlC@lu9VKheTyGM9gAKRNulHAbAhC/E3VU/nOjHT@HL99ugQkedTcj7CwNGwDyoiZRDr0nVdfd1eUYkM4GgPkAR0UzAqdG3MMkvttigJuLjKpOH3TsXaFoqhhO52exiHuChv2GM4iI6VQB8YsD1zcdGMwGP@YZ1/29TxQb6t@nHDxfJ75xpoB1S99M4fULGssU3vNc3v9gE7rri5Bvf7xvf7pve7VthDOXkXgmpCaOT@@bz6lnQCIzihBnON@0Ufxs7xd/OXasChtjONcCHZyn/Fnc/wce@JTqtLxnMfflEZA3gWbivhA0zk3iIwRtHkUievC8ciXEB7ayR7xcPv35l7p86yGveYxQGoBZy4CszXq4oWGyaXHnEMPb/4jDnK9Oj39GZfaGF@NpTosDP/MBvVuAV8yebtWJosnJTfJ2iy19Rw1bYhXpZW/HiK9qJFbdN2BSXoXhL1Djwfp13953Y@PDrBBP0kFQykpZhE3TGSttigILItnidXhP3NFaYi5r4MOT7owTJ5XLQEz/4/SMzd9cxWjZ64GQviY6wE1uxvMVZ/ZjUX3N6TelXjLTXOE4dqbD2kW0zEa5PdMt@WRTGPWvK3Bda/VBkSK0areyvTT5hQwj6gHgya01MAnfIVjm3W2a6Gxz6ErVxzRP7b5v9pZWyToOiY7NejW0uab4wHpNpzePA9HKpJMw36Tc@cRAScu07rOM0OI@Q6bCYzGhXLff7xQeYJvCiCK6Z@@EwFGSDgifFpN7tppMiCawDG4lVyy0i9PpOKGmBHU/segleFLdy98Al3qlMrF6FJYJTAr/sC81hUCMg3iL7D9Dw5CvTcszGoyXEzoeXciwwH3NEqNLkidrLNmvVGQKea3PBdJ6zkn42hHwxLXpJzppDNgKlUvjmCmDQT45Q@yBT/cQmYjx1K8@K0/MrzX7Wc6eFltGTAh5ofk5eduPAx5y47GbFFvN6fkfbv34wPQvpCtukRtXG3tEGALlVv1nneSvfSfEQBzxkownERpMykz8QHMsgIeGxJgr83KenfPYZn3ub2F0B5kFNpIfuMT41@YULQDbdF7SNa4KMDm6YcCplQpembRM3mRykf0DJLXYGMAcc6Zu73PSGdbyiUWe0lUOPLY7Az4Pk9tFT4x6sTQuk26STkpvfAcSARlJnRvXKY8SB@DicK23TpyBh@BI4pLdx/mZy5@mBDTu6NiTKd350w/Si/nO6ffC0tGIhc8NFOpu1w3oTtNbj8rzr7jxdnee7JozQAbmf9pMCKvWOoulE@UySs4C6Tz2gMgyNBzfZDm7DdHBLfbKWoALTkNDqqAcORTJ8MDLabIgSCyObt8EENnik@UIEXGcKvGf2jhL6cWZ/g8XilmGJt@VhIbWxOd84993UrGOHHEmHOYIJZJsNkXGdEImOWIsAwMlGJEhOi9VQ4LFOd2FVzI0GniQGb5mPCRqO0cvwHL0O0W/5u4rh7t013hOLvS7wkkXDg42dwVZufEaJIeRWZvUtG81QQnbASV0H@NHBhhLy22g6Aop9QksPLxn0lNES2fArBpsAOpUDq1F@Epe5D6J/X@hd8ELIC95eEcsSmP0GroPom9hx@ELOLkk/1pYAOGnr6DITdHope3hgD0BfFIEyXrH7DilS0WNBbiu46W67Nj4D@X3GKlIg4sDW21ZerPqwZ91078A2rh3YaOK6nbTJAMyDhqf0n3BZe8Y55E2LXhsNYje/JQhN1EkLeQBjDbxcEV1j7QigU0JBCKCTujknjAc3re4D@Iyur3/SaAiABH@8bIhQ6D9hVeJCT/hgjLpjNrqrN91Hb7qzN915Cd8@bVqv3HWxJCCSt/vM4ieK6gHb9kaKogEIJzT5LiLdNifCJwK0i4Dc2zTgcRESfHGgZtcZGhqg7Lopc0@a@OzcoNkTBc8hGnTR24/SV@CQjPCNxFq7LPiiwIPGPNNphynKzinnrsX2vaBM7TB229mu7IXHafai86j7daZgR83ecfLbhFdGuLREgcB9UvSdN5A6cSJumB8YBhAZ6PLmN7P6RoGfL2weBHTE@kL/BAjP02@oiDw7c@MO2A7L8v30W2LwZD9LPq0XNWEU2J2P5AHOkHCI7Cs3rgE4ILed4GXTlDRgHjQ8pe@ntRKJsz8iVOM8ViW2NkCa6uINra3vjEqrZuWOeWjhEdjy4JE9QPoJ68AGWiZpWqZWOuKyDEA4Xf2eb0mk2CQs@5Nm7dap0C866HLQjNUgLnYKCZ@jcBHbkMvGhaalhcd@Q8bnctouiias6HLtAjPUcpwSyCF86aKTdG7A0yXp9URuucQTnRCYU2cA1bPOEgKpyJGx14wyxzShnP2O/XVSI0YDaTBz6GQ4su7s3JMjzRcy@IqNHqODJdIbj2e6aL5Q/lzjMeS3PPvbt98craTd0VYEloHzKXpga8pxwcjIcY21jKByORa8SCBS@qLlkkPFwCuwDPQzZUQOygNxd4WjdbaRAFrqDDsdWumU7x/s4JQfCHNgUGfCG5kK/GLeHNqlPsbK6DE2pw9uTh8Tl@gc5DXDR9E85Z53dhUH538HbWZDUnvsHQZCa1U6VwisN4aEAkrkMTE2haNxQwCO4AVGuXOy1ny6EM@v@KeAw@@LVjQYnR26IvYYV8QevCLWJCY9h24uO3hVTchZQN02Qlul5TvVvvMLBEGz8RwASY6ZSWz8TwAn7jY5cq318NlhSM0NQU2kVHAPwG/1pnnQwbPfJjNtbYHMkVPvdOqdzvFOL914e0yf/06hmexbYn/1oJWbSVycBaBT48cEwXGeVkr6zTKhA0aTAUQA5Cgv9LIGdkKveOidkt/pAWAxHlNS7e6ZdIsPEA8@OzEe/Cy88eNwe2F@E0cms97H29dcZqbYkY68HvuIDg3lJnUk1W0iYAJ@6Lq0Q9elHeO6NJu3pj1m9ofves@CRhhaMZ4PCa864qxXXB9cngUIPRvqRkDrplH2cPJWdwIdmKoetAQwiUqQsQ4dEo/JWoUO4gNxC@vBRkHVPh@JrbwjnDrj64@JTwyiZ@RS/vFjkgz3lcvPgHnQ8GQqVm@gPqBdvhyEOnWFHS3UqoIWy/f1Ijr2JCkHXgp0aHn9GOvrVoImLl0fq06KgqpIjy1IpS5aCJIfpkcm0aUfZTTeJW2UrDOF5nsO8NE2IImOWN0G4IGB8I39Dpv/Tgi38idM3wAMs@qIs2OXHq0QDfEV4yYpUKlMjOyFnfCFcFLq0C14x7gE78AKrolTvUYgnxfLn95Ucvw9tuYD6oBGUqT6wxeSvPEPACQ5QqIW8xCLjrCMAyxH0QX7RjTYCVoJPHDuyGSNcmV0sP/2OUMZwEeclYKP1q61EzRe3JQ4/NYbaGvl@bhWno86sdPka1beQhFQBzTSCIWcqLxkHMCASVcbGPLuL9J8ofxpynn4PUIxZCfR8cHva4SWL0AROVLxydPfhpveKKgJY5DsQ2vepUWkP6/KItHxhXm5E0Zdhy@yzgTlReYrcroNQAxZ8Wd2Rr7bzjZMFiEA5nV@sR@oWDUPiSjKTeW5Fp5JI9H/bo0b3rG4kQciLI@sQA815I59gJx4t5uhjCoMOYYlUXXDqQDSfKH8j8v1UPycxxqVB52OJfEx/GAWRaZSL/eCvMcujEmY2DmwQQLNF0a8LZ1z1JdzjFbP9YDAc1yGKnZUDu2YH2PH/OAmy8FN1mPssR5jizVI6jvbwgApjrYQ8@gDC2wH18@O80DpcgkHrHGbZBE5K/5lxqCdF8yDmkjpcMRDfvxgUId5UBMxxMcmaZ6tv58T10SN1Dr@fuLYQ0g6cJ3f6QMZpd4kEhZADSbr9zPzhmkjrrqDGDT/CFHi4pqQHkFYNPcBdIohfOVRvsqjfCZhnFV1ps8h/kYkALHEGlGVMYhuU7PJQvRrPn@4M5I5F3rBbJ6zyjrx6bBCqGgeXPBi7srlOpdYXnVT6ltMGcfFC9e9C7p2wa9qQ/NVJ3rwjptxw42DAu1fFPRgwK4QfSgy0w4kHl2tS2ZIlFltW9RphOvx1ye4S4A50pUjjJJmIIB50PBUVK9EMVNC4yX/H7Ew7X0GU@FEz6Q/FwtqAB17M4xLskPSgboawjhyuFXT7cReDKkNjKxId/3JERDeNs4/ugjLUN5lITsDqPfFSa9jVCeAIvzCaMKITbSR7nVxfKEuGfJIDYmBOqxKjfhvEaT5QmjOiXdXeh9KI8B6uemkIKiJlNuPNX0HYAALmPpABS6VGf7gQQEnnNkzQjfigNtqnDoS8JT6E0sbDiphgYj2WRNfHf83VNM6fZdkIlb@cU6Q3mBFlbMpBRdcHRUApw8CmgClEzRfSP@P4t20KuDHi2dEvOlqOf/PKb7NPimPdh4JC1I0zJgrnLYr6jjaWsfctHIYYjKGHiGlrcumA6mF7zQsW4HwO4bvwlsADDUYtlYBC1kAhGj3E2rjv6QcGQsWzkJSG0MggJz46cZfRQHl2xgFz@eT5gupqLE7kI42NFY6@zRch@JoP/x2I5a4Jq2T30rDwGsUGKSgvNIhQOnXpYVGma1KH7ndab4ZNGLh7UpOo7Sd/AI2nnkOOkVcSiI2IWLxYai8s748LwSr40KwOi4Eq9eFYEA2Tq/CZs9BYcrKPOJ/SQHoVHl/gSOGf3X5bJR9ifbCennEj@0IEwsFClrWRerVjf6gyfKikzjXf134OvIMKeP2OL44E6TP3gAG5@N2n@tyH54v0n@/VeXMyJfcWLcNLifqfCEp3N8DwOtFl9dwYA0urEPlhiS5pAPsbip2tGvRQIR3dHMV2IbaSGFRj2TAhHECbePqWKgPibx2wpTfB9gQfCy6K4yxa@G5D8A8qIn0pLFTVX15AqBTmvU6MFt1YLbiP1pcSEexnroKD8hgTB0KMe2eeOVqxWKcC8R1jl7qZBU8mTcn7EBD0kOaFJUxc1w@rli9blitvBqpTfapMNJrGCw2rY@3sSreOGw0WenFwgz4yQ1qzylENCdNO7xt7PA2Dhmb/2cnuqZAJMiKAj51w8GvFn88OQ9qIkW2zxRv1D7arrdJ/pmvuuP96n2KYXKb2Ka1CWcGWozRIv47//QxQC584N1ttVbSLjX@o1fQpciguG4BEFXdUU6KoepB9UE54qmwPm3@vxx6jLbifTvRVAsR46og@FoZgDmI4yZHrmyR4IhqY1JJKiMFBSuUzW9WPuhbYSzWdHEyQJ686KzxUuSQw@@teCtadIOMabNRWdcBCsFWwProeBLMuZr@mtOBMdLCq2GPv/G0WktxQzp0/V5DfIRA@neKGH3rsIMfdWBGJYbWEXgStFZYYftmKGbFLY3Gqfm4iVmsgVCTfawPMLIi/B1nx1uqsPH1jeCJfkGNyA@fumxTW1wStJA4l248KWMSYw@Dkxn3XUYbhiEW7CmFbISYwxl8JcldQBU1EEaMhefY2sLrlAKofQztChMXtk8uZvlhbcdkXKnd@E8mLjs9WBQMuvwwogLAU3bHQYqblsfeCCbJWSCfobwjiepfg4bnQfUYpbQF/VtIKo9/WAuEdkkU/MlUYKfU5UgpezKD2pnrQcORwKfr58mThY5dUgk6r9hPBWC@0ZYGAK@zzzh33WBo0vTfLgBEOv7lpfFMpUuen2wa4DRsNbdh790u0@4mwxSDuIbRjevQvwd1AI/kNf/bP6Q0qNH7RTfvFGLeaKjF8ebrkJVEgY26piTwz4YBjXR5sgNQVTOpNuEyS2zY62njFsbGSxhbZv4MxX4qYUHzhVD8zos3nBbKPPzwdj8YjHdg2HDOOghk0RevBwIgXJwdmUFQivPJLg65j7L9xbL9xbL9BRuatsbVm37QiBIN3Yr1jpARbrWay6gc6RaLCm3FMDnkLGgEBcr0mZMkNeahofMChhuEXiQIXeB1dU7jMYC2Fph7NN5J13Q5TsPOngsqsrMatyc03p7gF9ZyG8gQWbRN@q0WbdN15kGMYcNtVSGbIJ6@aYy0ccHaQaEyisGGJeCQs6AOaCKBgltTsvApcXln2znQ2yf@xDhtxzGWkHiAE2PZuakdEJHt@H@ftpfbjRm@o@kvYRnSCv6YqxVfp0QC2EpqFtDGJl5TE4l/gWwanfgNQOkngg5GM5wzmIyhD1btG5fsuY/nVwmjOOGetoZ7cFzA@4ykHlxbdeALHygnh0ZlbieAvvNId1ZHpw111U864h6exoJ4pKTqd4x/SQyE28JG6VBk/A9Ugy96oLQcqLJHrnx@5lFQIwYYP9mcOOmBcVAIrszcY/y1ZiDCFv4XG4mOMa1yyYAo7toNNEAvc3ANt3FLLYyp8R0OTkracVYK7n@1389Yg3HJAWeQ/DT2NETtChiKql@@UB/7RqT5wvDvLO36O2zflmR7D6JjrpJ0wFfoMM5xuULGBkpIPKuP/x8JZGj2YbhJw4V@KlBV8uoIXJnQein95Cn1rsRryyJQqaxcmybK/5UGzIOG53gIR6zd15xRZR0FKjVdg@zOgX/HJQ8uD8oqyeelNF4lKdmJgTf@VBvuNJSZoRZRIWS@a6ojQTYOQSLZKHV@zTyyMl9ZqS@sNqezQXG5Azbs8cYtDswmLBCHhAPX2QBy0lDC8E2JhI35kBHbPF0@DmA6x@XPjuzJO@6NCaks4hpP098YGbB/8Kt@RypO/u9u6/xzd4PHg3EYKU8MEZ2MzknzhfTfKXb5jeluP3fpRKvQPwx03qwkYuTiSMBmEQBqd@3scsOPu30Nf8paibEp3k4bL3AWHphASMkJO4x28qizg7zwFc59Rp/F1gkXV5vQ30sY7lTgf30ZjYnDeTA5Jm@AQyPTcxizGvrqeVDVFZzNtzz57Mpl9Oa7nid9K3elm/8/DHPGquiLL9t4UoEU/u8x7QLRcaM4JJEZ76vBeqvBek9UOobScSlRB7tNIeXF67ocuuTl1@mHVuF9DQzfGhi@cf@hSQwQ3xjPvfP4YIbQ1G9YAbpMlJEdb/S@n@3GvzI11EVehm76J1xwet4Rf7dDiud8rGTACtbQFLeL3L/joDR7la7Fsj4Wy5yiBgHmQQq2Xnp0QqsLiK8MlC832rg87yJ6agAf4CglSIwNu44esh9zEbUTwNArFzL6pGSueNSGMPtTgazsUrMpcOtJLnqz71pI7dyyMpkhDtrY9DCZQdLYNJo8YgjUUdC6rofro8B1ljefImHVkgT97RiAt@UdwyEZ1Sab8UBExqWhruWZPrakuhtHUkkiUfIVufBi3dHGWPSnsT3F5TlJGFNTJ3w/mkT6v9Pxjir9UZ1LrNT0xf9NfhZh4hrIRyxxrt9EXENnEr1bX9DwdC35GejKGscafS9J/uzr/HTHdFCzwjwlKEaD/m@YUmvImgUrBJ3/9OrylQZQBX9e7dARtW9xxMKA4UkBXW7OBWD1A0hfXFAHoNPJyCvvj@5@UZBLpsymjsjEzBvqDD4UzMjMQjR2Y3iLUeeMzE3ToYCCgOWhjm6YC8naGtPGWEg0JmOHrMNsovO/Pnu5Tff4xxUauvXCLrvb2Dz1AfDjcosPVWgFAewIgWprw5deBjBWpAJLTp0mtCZhQ8q/Be8Y6HfejNrLoQYJ5ocdbW5Hk@t/qXLSAS2UPihs9VxkvmQQdLDU1LXS1GnF33HzfJedS5ehSx8GLn38RWC//iKw0xq@65@muu78cxg6T2xiO6G1pSVLSIXTvKjLqMVHdPgrp6BN2JZ7zA@7m3dIE/Gz7NZh9urY6fcFsc@STQAF/uOQA0@BG96GpB87jspRr8FDupzakKimel91HZGPHhXiKNQ6KE/rIEGvOEbQYx0ewUr8JVRIaI@/d3FsfHYQHN3ODHl27rzPwJEvwE0oA9jld/yfnwv8xCDTJX/z@/jwcx0AP6zch8RMvb/RdL1ZY98sjC4R7zuPPuut8vk5uNlPckdrTGpa49rdc79l2pbbG0Umnjv@rTZw5h8KBME4A5ihirm4SSqhejogIaf@tPXc@X8o9vK4ZfLcH5ilWjbwHB2okT6SiiozUTQzMfAtBqp1xdAVQR/hOnVktm/jYjRbDtGkAtLlhjj8FgeEZUWwQfP0QBQN65oOHZIjXSMZLhui1vjh2xkxdWSVlRJ4nG0on/oSb4zRz0M3f5LmCyOBhw5DnQctOAw06T8PmgGc9RbVm9aJJw/gu8QfPQb1AavcGiTzcaSz@dEQKHH/7jVZAxJRGZ0xdH1hXP@aWNv8ryDisQ6I8cWLLl@66PI10QoTQPVhhfmavCG5p4H9ovBP@iuqV1p4ZIcER6Qo2fdFkXih6XppxPQaAyWnqIAvtmrxrxUVMcLUIyS8YtLkIioqYP0Ie0wCHLGD78RwtJj2PS5WAWITMhYFbPJpJ0GD7JfPtAMyv9PLfCqkWkpHDEv8v3@RrgA54cKhYaQSUAnMmczI1xVDVhJi2Lsc9w8SU7hx4cStEGAn4aNkXtFhwLFiEKOt55B0aazwQUpZy2g1SUOToHibdgtfhXlXuG7Pf9xzQxq@h/89OL3QXb5oMO2ySkJB6ShnLHS8bEzgsb9Rhd@sv29W3re68/f0QIf3xjPfzM031uzeXL9@c5/yrVVsnxxH0/OeONAHUFsGaWwE3hMH9A6KAIs/b/wRFPGgkPIxlA9qcKhG@gDpxyOPb5g/vLXE@dYC53vsH7x9qoUZwHvqSusrUcyUdGYYLOq74PU2hmtMWAAf0IEe4s1/JXv73/ytA@DFI5HvsVn7xmqNzeG/cEmIE6u/4wo3bP/Zp@Ufd7zRqb6TFqnfCyanIcNrYcF/L1Hl3n6hKlWCoMSe673wKjmDGJ@EDB8djn/nGe@sW0nemS3YO6sFc0IgjDbew/nJn7DwAMApNpFczJR0VlAWLU4H3poDWG8FgwHvtiplDE7ePApmcplhOWGoT5dxeO6NJb837zN4Z179@8YKoIs9ZBzNfpftFjOmd/GljWgY3vjbhDdu7njzXxP8jzHYFDrqxQ3Z@zu2BXlc6qpAGwV/8vbjN3v3N/6M@z0sR0D1oiZk7tCwxCQ@WsU/6IZkDIk3TAcpWMIoxGCH0AHRN@chYdLHx2XZTrx9vRSFonL36IP8/NAW8IPr5D5WOULvk@L68E9OYV4dMvTsjTH@BsUzDeMtfiRcrMMzyj84Bfvh/7r4X7/941Hqn9pyesP2p1@mX3/7Jf/5z3/7t99@/T/u8Uv7@x//@Jdf7n//37/9cv/bv/72a@vVOoQ//fL@@y/Tf/7y9ec//9evf/vX//j3X9pf/37eHz7XNr9f//o//vznX@6/@V/Omc8f//mPf7WZwJ/@7V/@8s//8uv/VBTt17/@4Z/@8Nv//cc//t9e/tfdV2X@Pw "PHP โ€“ TIO Nexus") [Answer] # Python 3, 252 bytes This is my first ever code golf challenge I've done! I know there are other Python answers on here (that are probably better than mine) but this looked fun, and so I wanted to try it anyways. Here's the golfed version: ``` import random, math with open("d") as f: d=f.read() l=d.split() for a in range(5): u=[] p="" for b in range(4): w=random.choice([w for w in l if not w in u and len(w)>=4]) u.append(w) w=w.title() p+=w print("%s %s"%(p,math.log2(52)*len(p))) ``` I would post a Try it Online! link, but that doesn't support multiple files. So here's a repl.it link: <https://repl.it/InIl/0> Also, here's the ungolfed version: ``` import random import math with open("d") as f: dictionary = f.read() #this is the dictionary text file, simply saved as "d" as to use as few bytes as possible words = dictionary.split() #here we turn that dictionary string into a list for a in range(5): #here we iterate through 5 passwords used_words = [] password = "" for b in range(4): #here we iterate through the 4 words in each password word = "" word = random.choice([word for word in words if not word in used_words and len(word) >= 4]) #Thanks to blackadder1337 from #python on freenode IRC for helping me with this. used_words.append(word) word = word.title() password = password + word print("%s %s"%(password, math.log2(52) * len(password))) ``` Like I said, this is my first time code gofling, so I'm sure this could be improved a lot. [Answer] # tcl, 137 Not a winner for sure, but I think it can be a golfed a little more. ``` time {set p "";time {set p [string totitle [lindex $d [expr int(rand()*[llength $d])]]]$p} 4;puts $p\ [expr 5.7004*[string length $p]]} 5 ``` [demo](http://rextester.com/VFKR74832) โ€” The line 1 purpose is only to put the dictionary contents into the variable `d` [Answer] # Vim, 87 keystrokes ``` qq:r!echo "$RANDOM"l<CR>D:w o|e w<CR>@"ev4bd:w|bp<CR>p0~wX~wX~wX~Y:.!wc -c<CR>A*5.7003<Esc>:.!bc<CR>PJq4@q ``` Assumes that the dictionary is in a file named `w`. Will always use 4 consecutive words Explanation: ``` qq Start recording a macro named 'q' :r!echo "$RANDOM"l<CR> Append the result of the shell command `echo "$RANDOM"l` D Delete what you just appended :w o| Save the buffer to the file 'o' and .. e w<CR> Open the file 'w' @" Execute the text we deleted as a normal-mode command This will move the cursor a random number of characters to the right e Go to the end of the next word v4bd Delete 4 words backwards :w| Save the file and .. bp<CR> Open the last buffer (the 'o' file) p Paste the 4 words we deleted 0 Move the cursor to the beginning of the line ~wX~wX~wX~ Remove the spaces between the words and capitalize Y Copy current line :.!wc -c<CR> Pipe the current line through 'wc -c' A*5.7003<Esc> Append "*5.7003" to the end of the line :.!bc<CR> Pipe the current line through 'bc' P Paste the password above the current line J Join with line bellow q Stop recording the 'q' macro 4@q Run the 'q' macro 4 times ``` [Answer] # q/kdb+, ~~76~~ ~~74~~ ~~65~~ 56 bytes **Solution:** ``` {(x;5.70044*(#)x)}(,/)@[;0;upper]each -4?" "vs(*)(0:)`:w ``` **Example:** ``` q){(x;5.70044*(#)x)}(,/)@[;0;upper]each -4?" "vs(*)(0:)`:w "RulingOverheadSaddensPriest" 153.9119 ``` **Explanation:** Read in the word list, break apart on " ", pick 4 random words from this list, uppercase first letter of each word, then join together. Feed this into a lambda function which returns the password and the calculated 'entropy': ``` `:w / the wordlist is a file called 'w' (0:) / read in the file list (\n separated list) (*) / take first (and only) item in the list " "vs / split this on " " -4? / take 4 random items from this list, neg means 'dont put back' @[; ; ] / apply a function to variable at indices (variable is implicit) upper / uppercase (the function being applied) 0 / index 0, the first character each / each of the 4 random items (,/) / 'raze' (flatten lists) { } / anonymous lambda function (x; ) / a 2-item list, x is first item (#)x / count x, return the length of the list 5.70044* / multiply by 5.70044 ``` **Notes:** I caved in and used 5.70044 instead of `2 xlog 52 xexp`... ]
[Question] [ Sometimes, when I'm really bored I like to take the sum of an array of non-negative integers. I only take the sum of arrays of lengths that are powers of two. Unfortunately I often make mistakes. Fortunately I keep track of my work as I go along in the following way: I add pairs of adjacent numbers until there's only one left. For example: ``` 6 + 18 + 9 + 6 + 6 + 3 + 8 + 10 = 24 + 15 + 9 + 18 = 39 + 27 = 66 ``` You're job is to determine if I've made a mistake somewhere. You may either get input passed to your function or read from standard in. Output can be printed or returned. Input: An array/list/etc. of non-negative integers, and possibly also the length of that array if your language requires it. That array will be all the numbers read left to right then top to bottom. For example the array above would become: `[[6, 18, 9, 6, 6, 3, 8, 10], [24, 15, 9, 18], [39, 27], [66]]` or `[6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66]` if you prefer. Output: a single boolean representing whether or not a mistake was made. The boolean can be represented using *any* mapping provided that all inputs where a mistake is made return/print an identical result and all input which contain no mistakes return/print an identical result. This should go without saying, but those two outputs cannot be the same. Some Examples of Correct Summations: ``` 6 5+6 =11 3 + 2 + 4 + 5 = 5 + 9 = 14 [0, 1, 2, 3, 1, 5, 6] [[1, 2, 4, 8], [3, 12], [15]] ``` Some Examples of Incorrect Summation: ``` 5+4 =8 4 + 4 + 4 + 4 = 9 + 7 = 16 [[1, 2, 3, 4], [7, 3], [10]] [3, 4, 5, 6, 7, 8, 9] ``` Keep in mind that I can make mistakes and still get the right answer. If I do make a mistake it'll never result in an extra number or a missing number in the final array, only a wrong number. Standard loopholes are forbidden. Shortest answer in each language is a winner. The older answer will win in the case of a tie. I retain the right to decide what the "same language" is, but I'll say upfront a point can't be earned in both Python 2, and Python 3. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` แน–+2/โ‚ฌแบ‡ ``` [Try it online!](https://tio.run/nexus/jelly#XU49DoIwGN05xbfbKIVS4AROnoB0INpEFyTQmLgZF27g5BHc/Vk9CVwEXwtdbJr09f1939i/b4toNVwf/acbvx0A7pr613O43GlT1nQ86YbMXpPRraFt2eqWympHdaONOeM5VGY5jgWOZMQzRjkj6W7MCF8eKkZFJIASJ/LMEjFQlFokpVIsIEKBBzBKK3HumRA5BFDqeEaJi3p50jBj6oY5cr5EWUcAh@0Ulst8RriAmGms47bhf53xrKd@dOj12IX9quk8O8dE9QM "Jelly โ€“ TIO Nexus") ### How it works ``` แน–+2/โ‚ฌแบ‡ Main link. Argument: A (2D array) แน– Pop; yield A without its last element. Let's call the result B. 2/ Pairwise reduce... โ‚ฌ each array in B... + by addition. แบ‡ Window exists; test if the result appears in A as a contiguous subarray. ``` [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` lambda l:map(sum,zip(*[iter(l)]*2))==l[len(l)/2+1:] ``` [Try it online!](https://tio.run/nexus/python2#nU/LboMwELzzFXsD1EXBgHlJfIlrRTQNiiVDEDGH9r97puslrThWlSzvrGdnZzx0r5vtx7f3Hmw79nP0WEf8NHNkVdtmGq0SvsZx11llr1Nk41P2Ilq9ubNDGM6uM9O8uigO5sVMDkK3rO72EQbDfQEDZgIabAMwHW2ODCodB7CPGgwhgRCHyPyqh94@juLhL@JNKVUiiBqhQSj55AjUilQjqKwgJJkUtX/ICWWVR2WpNZKab4klFSG4yTGpsUBJOJHYUCn4PaUlpCYHrycoeQ9zO0FuuwtNZjwkNdP/CFkfQkosqNSMC7bxhzoarHzwY4icKVDVT9D0@SsvIpvySbJBQ/m2r@meXPrL7foN "Python 2 โ€“ TIO Nexus") Thanks to Rod for the test cases. Takes the whole list flat as input. Groups elements into adjacent pairs using the [zip/iter trick](https://stackoverflow.com/questions/2233204/how-does-zipitersn-work-in-python), takes the sum of the pairs, and checks if the result equals the second half of the list. A [recursive method](https://tio.run/nexus/python2#nU/LboMwELzzFXsDmkXFgM1D5UssK6JprFhySETMoR/eM12WtOJYVbLY2Z2dnWGxvR@u7x8D@M6fx8Snb8VtAq9zc/BamL73epu/FgdhXmziddGZdAnHgGCPoXfjfQ5JGt0nNwaIwzSHy2ccWbriwI1Ai10Ern/M18ShNmkE26rDGDKI0SbuV20H/9iL7V/Ei9ZaIYgGoUVQ/EoEakVuEHRREZJMimYdlISKekVKGYOk5q9ERUUIbkrMGqxQEs4ktlQqnud0hNTksOoJSr7D3EaQ2@ZCmwUvScP0P0I2u5ASKyoN44pt1kcdLdZr8H2IkinQ9U/Q/PlXq4hs1JNkg5byLV/jLTsNp8v5Gw) came close at 55 bytes: ``` f=lambda l:len(l)<2or l[0]+l[1]==l[len(l)/2+1]*f(l[2:]) ``` This used that input integers are positive, which has since changed in the spec. [Answer] # [Rรถda](https://github.com/fergusq/roda), 40 bytes ``` {[0]if{|x|[[x()|[_+_]]=y]if tryPeek y}_} ``` [Try it online!](https://tio.run/nexus/roda#nZDBC4IwFMbP6694dCraoZktCzx06BARBXVbQyQnSKWhHhT1b7fnKtGOwTbe@36Pb9v3cIMQCvDtS12IqQz8osxKIbLRuBTOxJHSzlGENM6PSt0gr5yqJqlKUufqJiqBlQ1iQIgQnAKzKCwpcL1mFLBlU0lBGCZWcw2Z1QgzrIxFU3EuJf3TgPcNGEqa/QpmV9DGpp6joJ@AV/S4@eHGlzMpBwSXH8XQfh0wt04OXoQOTVAtL8HH/QlulI3fI@QZB2EKw8NuiJ26J6oj7ren83q3aYgXhUj0WdUv "Rรถda โ€“ TIO Nexus") It's an anonymous function that returns `0` if there are no mistakes and nothing if there are mistakes. Explanation: ``` {[0]if{|x|[[x()|[_+_]]=y]if tryPeek y}_} { } /* Anonymous function */ {|x| }_ /* Loop over lists in the stream */ if tryPeek y /* If there are lists left after this */ x() /* Push values in list x to the stream */ |[_+_] /* Sum every pair of numbers in x */ [ ] /* Create a list of sums */ =y /* If the list equals to the next list */ [ ] /* Push the result */ if /* If all results are TRUE */ [0] /* Return 0 */ /* Otherwise return nothing */ ``` Here's a version that is shorter (35 bytes) but against the rules (I think): ``` {{|x|[[x()|[_+_]]=y]if tryPeek y}_} ``` [Try it online!](https://tio.run/nexus/roda#nZBPC4JAEMXP66cYPBXtoTXb/oCHDh0ioqBu2yKRK0iloR4U9bPbuJVox2BYZt5vebP7HpcghAJ851wXRZmVQmSDYSnckSulk8vAhzTOD0rdIK/cqiapSlL3eklUAksHhEGIEJwCm1NYUOC6JhRwZGNJQVg2dlMN2bwRJthZs6bjXEr6pwHvGzCUNPsV7K6gjW19j4J@Aq7ocfvDrS9nUhoEy49iaL8OGFknBy9Chyaolpfgv1XyjIMwBXO/NXFS90R1xN3meFpt1w3xohCJPqv6BQ "Rรถda โ€“ TIO Nexus") It's an anonymous function that reads values from the stream and pushes `TRUE` or `FALSE` for each correct line. I'm not sure if this (multiple return values) is accepted in the rules. Here's my defence: in Rรถda, conditions of `if` and `while` blocks are not boolean values, but streams. A "truthy" stream is either empty or contains only `TRUE`s, and a "falsy" stream contains one or more `FALSE`s. In this way, this function returns a "boolean" value. And can be used as a condition of an `if` statement without any reduce-operations, etc. [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ 65 bytes ``` lambda x:reduce(lambda a,b:(b==map(sum,zip(a[::2],a[1::2])))*b,x) ``` [Try it online!](https://tio.run/nexus/python2#nU/LaoRAELz7FX1TQwu@xhf4JRNZRlfZgdUVd4RN/jtn09Oa4CWXwGBXT1VNlUP9vt3V2F4VvKqlv65d7x27wrby2roe1ew91xE/9ewpWVVxg0pGdvq@/9biy9/MxSAMF1PraV6N5zvzoicDrllWc/twneGxgAY9AQkrB3ZWowsBuDh4@tcwqPvzrB/@0G9SygwhKhBKhIxPgkBrFDYIMk4JCSajwl4khOLcoixrGiQ3fwVmNKKIlwSDAlMUhAOBJY2U70N6hNyUYP0EBb/D3E5Q2p5CyphFomH6HyWLU0mBKY2Cccox9tBGwtwWP5dImAKZ/xQNj7@yJorJDpIDSuq3fU2PoFPdrf8G "Python 2 โ€“ TIO Nexus") Returns : Empty List as `Falsy` Total sum as `Truthy` [Answer] # Mathematica, 36 bytes ``` Most[Tr/@#~Partition~2&/@#]==Rest@#& ``` Pure function taking a nested list as input and returning `True` or `False`. The function `Tr/@#~Partition~2&` takes the pairwise sums of a list, which is then applied (`/@#`) to each sublist of the input list. The first, second, ... sublists in the resulting list are supposed to equal the second, third, ... sublists in the original input; `Most[...]==Rest@#` tests for this property. [Answer] # [Python 2](https://docs.python.org/2/), 80 bytes ``` lambda l:all(l[i+1]==map(sum,zip(l[i][::2],l[i][1::2]))for i in range(len(l)-1)) ``` [Try it online!](https://tio.run/nexus/python2#HcnBDsIgDMbxV@mxxJoIU5wkexLkgHEzTTpGcLv48hOW9PDr/5uG5y5xfr0jiIsiKJ5POgzDHDN@t5l@nFsL3jkT6JBuVGpaCjBwghLTZ0QZE4o6a6X2XDitOCGnvK2oavHeEuie4EFgj@sI6qsvgcCba9XtGHXfQldl7k3WhvAH "Python 2 โ€“ TIO Nexus") Not quite as good as the other python answer, but I felt like posting it anyway. This just goes to show why I'm not as good at golfing in *regular* languages. [Answer] ## JavaScript (ES6), 54 bytes ``` a=>!a.slice(-a.length/2).some((n,i)=>a[i+=i]+a[i+1]-n) ``` Takes a flattened array. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 12 bytes ``` ยฌsvyQy2รดO}\P ``` [Try it online!](https://tio.run/nexus/05ab1e#@39oTXFZZWCl0eEt/rUxAf//R0eb6SgYWugoWOoomIGRsY4CkGtoEKujEG1kAmSZgiUNLUACxkCWkTmIZWYWGwsA "05AB1E โ€“ TIO Nexus") **Explanation** ``` ยฌ # get the first element from input without popping sv } # for each element y in input yQ # compare y to the top of the stack # leaves 1 on the stack if equal and otherwise 0 y2รด # split y in pieces of 2 O # sum each pair in the list \ # discard the top of the stack (the left over final element of the list) P # product of stack (all the 1's and/or 0's from the comparisons) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~82~~ ~~79~~ 65 bytes -14 bytes thanks to nimi! ``` p(x:y:z)=x+y:p z f x=and.zipWith(==)(drop(length x`div`2+1)x)$p x ``` Works by comparing the sum each pair of elements to the corresponding element on the next line down. Some bytes can probably be golfed from `f`, but I can't figure out where. [Answer] ## [Python 3](https://docs.python.org/3.5/), 69 68 bytes ``` lambda v:any(x+v[i-1]-v[(len(v)+i)//2]for i,x in enumerate(v)if i%2) ``` I know there are already two other python answers... but this one's in python 3, so it's exotic. This works on a flattened input. **Output**: `False` if there is no mistake, `True` if there is a mistake. [Answer] # Ruby, 50 bytes ``` ->x{a=b=0;b&&=x[a/2]==x[a]+x[a-1]while x[-a-=2];b} ``` Reversing the array, any element of the first half (position n) must be the sum of the elements in position n\*2 and n\*2+1. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~16~~ 13 bytes ``` sโ‚‚แต˜{{ฤกโ‚‚+แต}แตˆ}แต ``` [Try it online!](https://tio.run/##RU47DoJAEL3KhtaJYb/AWTZboEEtSExQYwzSUBhKSlttbG24gZ2ngIvg7EBi9jNv35v3ZldFut5d8v1WjOVwew91PTSv4FicsmB59XCT5ocsqL7P83hAte/uZfl5IFr0XVv1XYOnHUdrrQHGY2AJMENbAsMnDx0wKxQiTSKPPSERicgjY5wDdNOtwWDhnB4SBCjQCDUknlZEh8BRkJ4gcXJyasZstHHhRT0nKiwxYQW0ECYQ@Za/VRIdTbHhPB6H038iyk2ccz8 "Brachylog โ€“ Try It Online") This is just dreadfully long! There has to be some way to not nest inline predicates here. The predicate succeeds (printing `true.` as a program) if no mistakes were made and fails (printing `false.` as a program) otherwise. ``` sโ‚‚แต˜ Every length 2 substring of the input { }แต for every element satisfies the following: {ฤกโ‚‚ the pairs of elements of the input +แต when each pair is summed is the output }แตˆ where the input is the first item and the output is the second. ``` [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` lambda a:[map(int.__add__,x[::2],x[1::2])for x in a[:-1]]==a[1:] ``` **[Try it online!](https://tio.run/nexus/python2#bVDRCsIwDHy2X5HHCVHs2jlX2JfEMCpzILgpcw/@/Uwq@LDZPoTmLtfLdfV5vsf@0kaIgfr4zG7DtG@a2LZNg28KIWcpVuu2e4zwhtsAkcLOMtd1FITn6fqaXlADAdGRGQ38DlGBR0aydtl3mKPHQrACK2X4JeOAVjhOscRbSdskcRLIoc2VV6x/99I/Ldse0xWowlIH/2q7xCi/Fg7rBcR@Wq5MHipmYGM0JA1Ec0rBBLN5jpJqeiF0mdbtPH8A "Python 2 โ€“ TIO Nexus")** An unnamed function that takes a list of lists (one per line of working as it were), and returns True if no mistakes were made and False otherwise. It works by using the input without the last entry, `a[:-1]`, to form what the input without the first entry should be and checking that is what was input, `==a[1:]`. This formation is achieved by mapping the integer type's addition function, `int.__add__`, over the pairs of numbers as yielded by two "slices", one slice being every other item starting at the 0th index, `x[::2]`, the other slice being every other item starting at the 1st index, `x[1::2]`. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~20~~ 19 bytes ``` $*{{b=$+*Ya<>2}MPa} ``` This is an anonymous function that takes one argument, a list of lists (e.g. `[[1 2 3 4] [3 7] [10]]`). Verify all test cases: [Try it online!](https://tio.run/nexus/pip#XY47DsIwEER7TjFFCgiN17/YCCjpkNIiK0WQkktEObuzXhCOsCV/5u3uzHzJTbss71tzbl/j9a7XZz@u@YEJ6YCyUvKggAjP2yCA1ICkLcixSIE/JkJ3fHs/DL@m@nTwDImqYqBh4VjlGYXZyhSIqSmqVOwGkbSJI0iXCsew2liWQi23kM1iRIlHf6OMsO7jpfbpOJtk7sQsfhGfPY4zplPeAA "Pip โ€“ TIO Nexus") ### Explanation In a Pip function, the first two arguments are assigned to `a` and `b`. ``` { } Anonymous function: { }MPa To each pair of sublists from a, map this helper function: a<>2 Group the 1st member of the pair into 2-item sublists Y Yank that value (no-op used to override precedence order) $+* Map (*) the fold ($) on addition (+) operator b= If the 2nd member of the pair is = to the result, 1; else 0 $* Modify the outside function by folding its return value on * (makes a list containing all 1's into 1 and any 0's into 0) ``` For example: ``` a [[1 2 3 4] [7 3] [10]] {...}MP a:[1 2 3 4] b:[7 3] a:[7 3] b:[10] a<>2 [[1 2] [3 4]] [[7 3]] $+* [3 7] [10] b= 0 1 Final result of {...}MPa [0 1] $* 0 ``` [Answer] # PHP, ~~96~~ 95 bytes: using builtins: ``` function f($a){return!$a[1]||array_pop($a)==array_map(array_sum,array_chunk(end($a),2))&f($a);} // or function f($a){return!$a[1]||array_map(array_sum,array_chunk(array_shift($a),2))==$a[0]&f($a);} ``` recursive functions return `true` or `false`. **breakdown** for first function: ``` function f($a){ return!$a[1]|| // true if array has no two rows ... or array_pop($a)== // remove last row, true if equal to array_map(array_sum, // 3. sum up every chunk array_chunk( // 2. split to chunks of 2 end($a) // 1. new last row ,2)) &f($a); // and recursion returns true } ``` **older solutions** (96 bytes each) using loops: ``` function f($a){foreach($a[0]as$k=>$v)$b[$k/2]+=$v;return$b==$a[1]&&!$a[2]|f(array_slice($a,1));} //or function f($a,$y=0){foreach($a[$y]as$k=>$v)$b[$k/2]+=$v;return$b==$a[++$y]&&!$a[$y+1]|f($a,$y);} ``` **breakdown** for last function: ``` function f($a,$y=0){ foreach($a[$y]as$k=>$v)$b[$k/2]+=$v; // build $b with correct sums from current row return$b==$a[++$y] // true if $b equals next row &&!$a[$y+1] // and (finished |f($a,$y); // or recursion returns true) } ``` **iterative snippets, 81 bytes** ``` for(;$a[1];)if(array_pop($a)!=array_map(array_sum,array_chunk(end($a),2)))die(1); for(;$a[1];)if(array_map(array_sum,array_chunk(array_shift($a),2))!=$a[0])die(1); for(;$a[++$y];$b=[]){foreach($a[$y-1]as$k=>$v)$b[$k/2]+=$v;if($a[$y]!=$b)die(1);} ``` assume array predefined in `$a`; exits with error if it is incorrect. [Answer] # C, 54 bytes: ``` f(int*s,int*e){return e-s>1?*s+s[1]-*e||f(s+2,e+1):0;} ``` Ungolfed: ``` int f(int*s,int*e) { if(e-s>1) { return *s+s[1] != *e || f(s+2,e+1); } else { return 0; } } ``` Test with ``` #include <assert.h> int main() { int input1[15] = {6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66}; assert(!f(input1, input1+8)); int input2[7] = {3, 4, 5, 6, 7, 8, 9}; assert(f(input2, input2+4)); } ``` As you see, `f()` returns true for invalid inputs and false (= 0) for valid ones. As always, recursion is less bytes than iteration, so `f()` is recursive, even though it takes two iterators as arguments. It works by repeatedly comparing the sum of two integers at `s` to one integer at `e`, ignoring the level boundaries, and carrying on until the two iterators meet. I have also used some boolean zen together with the fact that any non-zero integer value is considered true in C to further shorten the code. [Answer] # R, ~~92~~ 77 bytes Anonymous function which takes a flat sequence of numbers as input. Returns `TRUE` or `FALSE` as appropriate. Uses the same approach conceptually as xnor's python answer. ``` function(x,l=sum(1|x)/2)all(rowSums(cbind(x[1:l*2-1],x[1:l*2]))==tail(x,l-1)) ``` Previous solution, using the `rollapply` function from the `zoo` package, and taking input as a list, e.g. `list(c(6, 18, 9, 6, 6, 3, 8, 10), c(24, 15, 9, 18), c(39, 27), c(66))`: ``` function(l,T=1){for(i in 2:length(l))T=T&all(zoo::rollapply(l[[i-1]],2,sum,by=2)==l[[i]]);T} ``` [Answer] ## JavaScript (ES6), ~~46~~ 44 bytes Takes input as a flattened array. Returns `NaN` for valid or `0` for invalid. ``` f=([a,b,...c])=>a+b==c[c.length>>1]?f(c):b-b ``` ### Test ``` f=([a,b,...c])=>a+b==c[c.length>>1]?f(c):b-b console.log(f([6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66])) // NaN console.log(f([0, 1, 2, 3, 1, 5, 6])) // NaN console.log(f([1, 2, 4, 8, 3, 12, 15])) // NaN console.log(f([1, 2, 3, 4, 7, 3, 10])) // 0 console.log(f([3, 4, 5, 6, 7, 8, 9])) // 0 ``` [Answer] # PHP, 102 Bytes input als url parameter in this format `?0=[1,2,3]&1=[3,3]&2=[6]` use this input `[[int,int],[int]]` ``` <?$r=[$_GET[0]];for(;count(end($r))>1;)$r[]=array_map(array_sum,array_chunk(end($r),2));echo$r==$_GET; ``` ## Breakdown ``` $r=[$_GET[0]]; # Set the first item of the input in the result array for(;count(end($r))>1;) # till the last item in the result array has only one int $r[]=array_map(array_sum,array_chunk(end($r),2));# add the next item to the result array echo$r==$_GET; # compare the input array with the result array ``` [Answer] # Japt, 10 bytes Takes input as a 2-D array. ``` รครeXรฒ mxรƒe ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=5M9lWPIgbXjDZQ==&input=W1sxLCAyLCAzLCA0XSwgWzcsIDNdLCBbMTBdXQ==) ``` รครeXรฒ mxรƒe :Implicit input of 2-D array รค :Reduce each consecutive pair of sub-arrays ร :By passing them through the following function as X & Y, respectively e : Test Y for equality with Xรฒ : Split X on every 2nd element m : Map x : Reduce by addition รƒ :End function e :All true? ``` ]
[Question] [ The task at hand is, given a number `n`, find the smallest prime that starts with ***AT LEAST*** `n` of the number `2` at the beginning of the number. This is a sequence I found on OEIS ([A068103](http://oeis.org/A068103)). The first 17 numbers in the sequence are given below, if you want more I'll have to actually go implement the sequence, which I don't mind doing. ``` 0 = 2 1 = 2 2 = 223 3 = 2221 4 = 22229 5 = 2222203 6 = 22222223 # Notice how 6 and 7 are the same! 7 = 22222223 # It must be **AT LEAST** 6, but no more than necessary. 8 = 222222227 9 = 22222222223 # Notice how 9 and 10 are the same! 10 = 22222222223 # It must be **AT LEAST** 9, but no more than necessary. 11 = 2222222222243 12 = 22222222222201 13 = 22222222222229 14 = 222222222222227 15 = 222222222222222043 16 = 222222222222222221 ``` Just thought this would be a cool combination of string manipulation, prime detection and sequences. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count will be declared the winner probably at the end of the month. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~164~~ 110 bytes ``` a->{int i=0;for(;!(i+"").matches("2{"+a+"}.*")|new String(new char[i]).matches(".?|(..+)\\1+");i++);return i;} ``` Thanks to @FryAmTheEggman for a bunch of bytes! [Try it online!](https://tio.run/nexus/java-openjdk#TVDBTsMwDD2nX2FySoiIGOIWOn4ATjtuO3hdullq0ypJQajrtxd3Q2g@@FmW33u2@@HQUAVVgynBJ1IYC0Eh@1hj5eED28MRYQRuQRyCWhC1g6kQ/Y2ZMmaGr46O0DJfbXKkcNruMZ6SBpYTfyp1OePTelwkqHx2dReVe1BkpNS2xVydfVLyZZQGjZzso9SX4L/hJqeWsjpj3NL@btq@X5S1Ru92KyO1I2O0iz4PMQC5aRbCsT0bwXVxghJWjuENXhl4mNeDuxBi85Oyb203ZNuzb274ZDAgoVxzMlDb6xe0dv9Ewb@Yimn@BQ "Java (OpenJDK 8) โ€“ TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 11 bytes ``` :2rj:Acb#p= ``` [Try it online!](https://tio.run/nexus/brachylog#@29lVJRl5ZicpFxg@/@/xf8oAA "Brachylog โ€“ TIO Nexus") This translates into Brachylog surprisingly directly. This is a function, not a full program (although giving the interpreter `Z` as a command-line argument causes it to add the appropriate wrapper to make the function into a program; that's what I did to make the TIO link work). It's also fairly unfortunate that `j` appears to be -1-indexed and needs a correction to allow for that. You can make a reasonable argument that the `=` isn't necessary, but I think that given the way the problem's worded, it is; without, the function's describing the set of all prime numbers that start with the given number of `2`s, and without some explicit statement that the program should *do* something with this description (in this case, generating the first value), it probably doesn't comply with the spec. ## Explanation ``` :2rjbAcb#p= :2rj 2 repeated a number of times equal to the input plus one :Ac with something appended to it b minus the first element #p is prime; = figure out what the resulting values are and return them ``` When used as a function returning an integer, nothing ever requests values past the first, so the first is all we have to worry about. One subtlety (pointed out in the comments): `:Acb` and `b:Ac` are mathematically equivalent (as one removes from the start and the other adds to the end, with the region in between never overlapping); I previously had `b:Ac`, which is more natural, but it breaks on input 0 (which I'm guessing is because `c` refuses to concatenate an empty list to anything; many Brachylog builtins tend to break on empty lists for some reason). `:Acb` ensures that `c` never has to see an empty list, meaning that the case of input 0 can now work too. [Answer] ## Pyth, 12 bytes ``` f&!x`T*Q\2P_ ``` In pseudocode: ``` f key_of_first_truthy_value( lambda T: ! not ( x`T*Q\2 repr(T).index(input()*'2') ) & and P_T is_prime(T) ) ``` Loops the `lambda` starting from `T=1`, incrementing by 1 until the condition is satisfied. The string of `2`s must be a substring from the beginning of the string, i.e. the index method needs to return `0`. If the substring is not found it returns `-1` which conveniently is also truthy, so no exceptional case exists. You can try it online [here](http://pyth.herokuapp.com/?code=f%26%21x%60T%2aQ%5C2P_&input=4&debug=0), but the server only allows up to an input of `4`. [Answer] ## Perl, 50 bytes 49 bytes of code + `-p` flag. ``` ++$\=~/^2{$_}/&&(1x$\)!~/^1?$|^(11+)\1+$/||redo}{ ``` Supply the input without final newline. For instance: ``` echo -n 4 | perl -pE '++$\=~/^2{$_}/&&(1x$\)!~/^1?$|^(11+)\1+$/||redo}{' ``` This take a while to run a numbers greater than 4 as it test every number (there are 2 test: the first one `/^2{$_}/` checks if there is enough 2 at the beginning, and the second one `(1x$\)!~/^1?$|^(11+)\1+$/` tests for primality (with very poor performances)). [Answer] ## Haskell, 73 bytes ``` f n=[x|x<-[2..],all((>0).mod x)[3..x-1],take n(show x)==([1..n]>>"2")]!!0 ``` Usage example: `f 3` -> `2221`. Brute force. `[1..n]>>"2"` creates a list of `n` `2`s which is compared to the first `n` chars in the string representation of the current prime. [Answer] # Mathematica, 103 bytes ``` ReplaceRepeated[0,i_/;!IntegerDigits@i~MatchQ~{2~Repeated~{#},___}||!PrimeQ@i:>i+1,MaxIterations->โˆž]& ``` Unnamed function taking a nonnegative integer argument `#` and returning an integer. It literally tests all positive integers in turn until it finds one that both starts with `#` 2s and is prime. Horribly slow for inputs above 5. previous result: **Mathematica, 155 bytes** Mathematica would be better for golfing if it weren't so strongly typed; we have to explicitly switch back and forth between integer/list/string types. ``` (d=FromDigits)[2&~Array~#~Join~{1}//.{j___,k_}/;!PrimeQ@d@{j,k}:>({j,k+1}//.{a__,b_,10,c___}->{a,b+1,0,c}/.{a:Repeated[2,#-1],3,b:0..}->{a,2,0,b})]/. 23->2& ``` This algorithm operates on *lists of digits*, strangely, starting with `{2,...,2,1}`. As long as those aren't the digits of a prime number it adds one to the last digit, using the rule `{j___,k_}/;!PrimeQ@d@{j,k}:>({j,k+1}` ... and then manually implements carrying-the-one-to-the-next-digit as long as any of the digits equal 10, using the rule `{a__,b_,10,c___}->{a,b+1,0,c}` ... and then, if we've gone so far that the last of the leading `2`s has turned into a `3`, starts over with another digit on the end, using the rule `{a,b+1,0,c}/.{a:Repeated[2,#-1],3,b:0..}->{a,2,0,b}`. The `/. 23->2` at the end just fixes the special case where the input is `1`: most primes can't end in `2`, but `2` can. (A few errors are spat out on the inputs `0` and `1`, but the function finds its way to the right answer.) This algorithm is quite fast: for example, on my laptop it takes less than 3 seconds to compute that the first prime starting with 1,000 `2`s is `22...220521`. [Answer] # Pyth, 17 bytes ``` f&q\2{<`T|Q1}TPTh ``` Can't seem to solve over `n = 4` online, but it's correct in theory. ### Explanation ``` Th Starting from (input)+1, f find the first T so that < the first Q (input) characters | 1 or 1 character, if (input) == 0 `T of T's string representation { with duplicates removed q\2 equal "2", & and }T T is found in PT the list of T's prime factors. ``` [Answer] # [Perlย 6](https://perl6.org), 53 bytes ``` {($/=2 x$^n-1)~first {+($/~$_) .is-prime&&/^2/},0..*} ``` [Try it](https://tio.run/nexus/perl6#dVBNC8IwDL33VzykjFX3GUURmfgjPHnQw@ygB3WsnShj/vVZnR9jYg/Jy0vy0qTUEudpkC5YadFaarNg7HCFk572EklTuTxMCBe@PfqxuGWq0AbVyLI3vhMIlPbzQh2k44RbCmsvCoJh3ViBlbFaSOAygLyPoXHrKH55mr8BReMP/Nb1Mc26QS/3E9KkT1AU95nOF@jPlLbzV@z5Yibs0bJTgcf22Lx295dwwdUxL40HLi@5TI3cQ6CyIkrjcWG3zYtOgYdBSyJZftkBq5s7 "Perl 6 โ€“ TIO Nexus") ## Expanded: ``` { ( $/ = 2 x $^n-1 ) # add n-1 '2's to the front (cache in ๏ฝข$/๏ฝฃ) ~ first { +( $/ ~ $_ ) .is-prime # find the first that when combined with ๏ฝข$/๏ฝฃ is prime && /^2/ # that starts with a 2 (the rest are in ๏ฝข$/๏ฝฃ) }, 0..* } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` D=2ร—\S:ยณaร†Pยต1# ``` *Very* inefficient. [Try it online!](https://tio.run/nexus/jelly#@@9ia3R4ekyw1aHNiYfbAg5tNVT@//@/CQA "Jelly โ€“ TIO Nexus") [Answer] ## Pyke, 14 bytes ``` .fj`Q\2*.^j_P& ``` [Try it here!](http://pyke.catbus.co.uk/?code=.fj%60Q%5C2%2a.%5Ej_P%26&input=2&warnings=0) ``` .fj - first number (asj) ` .^ - str(i).startswith(V) Q\2* - input*"2" & - ^ & V j_P - is_prime(j) ``` ### 12 bytes after bugfix and a new feature ``` ~p#`Q\2*.^)h ``` [Try it here!](http://pyke.catbus.co.uk/?code=~p%23%60Q%5C2%2a.%5E%29h&input=2&warnings=0) ``` ~p - all the primes # )h - get the first where... ` .^ - str(i).startswith(V) Q\2* - input*"2" ``` [Answer] ## Sage, ~~69~~ 68 bytes ``` lambda n:(x for x in Primes()if '2'*len(`x`)=>'2'*n==`x`[:n]).next() ``` Uses a generator to find the first (hence smallest) of infinitely many terms. [Answer] # Japt, 20 bytes ``` Lยฒo@'2pU +Xs s1)nรƒรฆj ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.2&code=TLJvQCcycFUgK1hzIHMxKW7D5mo=&input=MTI=) It finishes within two seconds on my machine for all inputs up to 14, and after that it naturally loses precision (JavaScript only has integer precision up to 253). Many thanks to @obarakon for working on this :-) ### Explanation ``` // Implicit: U = input integer, L = 100 Lยฒo // Generate the range [0...100ยฒ). @ รƒ // Map each item X through the following function: '2pU // Take a string of U "2"s. +Xs s1)n // Append all but the first digit of X, and cast to a number. // If U = 3, we now have the list [222, 222, ..., 2220, 2221, ..., 222999]. รฆ // Take the first item that returns a truthy value when: j // it is checked for primality. // This returns the first prime in the forementioned list. // Implicit: output result of last expression ``` --- In the latest version of Japt, this can be 12 bytes: ``` _n j}b!+'2pU // Implicit: U = input integer _ }b // Return the first non-negative bijective base-10 integer that returns // a truthy value when run through this function, but first, !+ // prepend to each integer '2pU // a string of U '2's. // Now back to the filter function: n j // Cast to a number and check for primality. // Implicit: output result of last expression ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.2&code=X24gan1iISsnMnBV&input=MTQ=) It finishes within half a second on my machine for all inputs up to 14. [Answer] # PHP, 76 bytes ``` for($h=str_pad(2,$i=$argv[1],2);$i>1;)for($i=$p=$h.++$n;$p%--$i;);echo$p?:2; ``` takes input from command line argument. Run with `-r`. **breakdown** ``` for($h=str_pad(2,$i=$argv[1],2) # init $h to required head ;$i>1; # start loop if $p>2; continue while $p is not prime ) for($i=$p=$h.++$n # 1. $p = next number starting with $h # (first iteration: $p is even and >2 => no prime) ;$p%--$i;); # 2. loop until $i<$p and $p%$i==0 ($i=1 for primes) echo$p?:2; # print result; `2` if $p is unset (= loop not started) ``` [Answer] # Bash (+coreutils), 53 bytes Works up to *2^63-1 (9223372036854775807)*, takes considerable time to finish for N > 8. **Golfed** ``` seq $[2**63-1]|factor|grep -Pom1 "^2{$1}.*(?=: \S*$)" ``` **Test** ``` >seq 0 7|xargs -L1 ./twist 2 2 223 2221 22229 2222203 22222223 22222223 ``` [Answer] ## Python 3, 406 bytes ``` w=2,3,5,7,11,13,17,19,23,29,31,37,41 def p(n): for q in w: if n%q<1:return n==q if q*q>n:return 1 m=n-1;s,d=-1,m while d%2==0:s,d=s+1,d//2 for a in w: x=pow(a,d,n) if x in(1,m):continue for _ in range(s): x=x*x%n if x==1:return 0 if x==m:break else:return 0 return 1 def f(i): if i<2:return 2 k=1 while k: k*=10;l=int('2'*i)*k for n in range(l+1,l+k,2): if p(n):return n ``` ### test code ``` for i in range(31): print('{:2} = {}'.format(i, f(i))) ``` ### test output ``` 0 = 2 1 = 2 2 = 223 3 = 2221 4 = 22229 5 = 2222203 6 = 22222223 7 = 22222223 8 = 222222227 9 = 22222222223 10 = 22222222223 11 = 2222222222243 12 = 22222222222201 13 = 22222222222229 14 = 222222222222227 15 = 222222222222222043 16 = 222222222222222221 17 = 222222222222222221 18 = 22222222222222222253 19 = 222222222222222222277 20 = 2222222222222222222239 21 = 22222222222222222222201 22 = 222222222222222222222283 23 = 2222222222222222222222237 24 = 22222222222222222222222219 25 = 222222222222222222222222239 26 = 2222222222222222222222222209 27 = 2222222222222222222222222227 28 = 222222222222222222222222222269 29 = 2222222222222222222222222222201 30 = 222222222222222222222222222222053 ``` --- I decided to go for speed over a fairly large range, rather than byte size. :) I use a deterministic Miller-Rabin primality test which is guaranteed up to 3317044064679887385961981 with this set of witnesses. Larger primes will always successfully pass the test, but some composites may also pass, although the probability is *extremely* low. However, I also tested the output numbers for i > 22 using [pyecm](https://github.com/martingkelly/pyecm) an Elliptic Curve factorization program, and they appear to be prime. [Answer] ## Python 3, 132 bytes ``` def f(x): k=10;p=2*(k**x//9) while x>1: for n in range(p*k,p*k+k): if all(n%q for q in range(2,n)):return n k*=10 return 2 ``` Any hope of performance has been sacrificed for a smaller byte count. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` แธŸo`โ‚ฌRโฐ2dฤฐp ``` [Try it online!](https://tio.run/##yygtzv7//@GO@fkJj5rWBD1q3GCUcmRDwf///40B "Husk โ€“ Try It Online") A bit slow due to uusing the infinite list of primes. [Answer] **Java, 163 bytes** ``` BigInteger f(int a){for(int x=1;x>0;x+=2){BigInteger b=new BigInteger(new String(new char[a]).replace("\0","2")+x);if(b.isProbablePrime(99))return b;}return null;} ``` test code ``` public static void main(String[] args) { for(int i = 2; i < 65; i++) System.out.println(i + " " + new Test20170105().f(i)); } ``` output: ``` 2 223 3 2221 4 22229 5 2222219 6 22222223 7 22222223 8 222222227 9 22222222223 10 22222222223 11 2222222222243 12 22222222222229 13 22222222222229 14 222222222222227 15 222222222222222143 16 222222222222222221 17 222222222222222221 18 22222222222222222253 19 222222222222222222277 20 2222222222222222222239 21 22222222222222222222261 22 222222222222222222222283 23 2222222222222222222222237 24 22222222222222222222222219 25 222222222222222222222222239 26 2222222222222222222222222213 27 2222222222222222222222222227 28 222222222222222222222222222269 29 22222222222222222222222222222133 30 222222222222222222222222222222113 31 222222222222222222222222222222257 32 2222222222222222222222222222222243 33 22222222222222222222222222222222261 34 222222222222222222222222222222222223 35 222222222222222222222222222222222223 36 22222222222222222222222222222222222273 37 222222222222222222222222222222222222241 38 2222222222222222222222222222222222222287 39 22222222222222222222222222222222222222271 40 2222222222222222222222222222222222222222357 41 22222222222222222222222222222222222222222339 42 222222222222222222222222222222222222222222109 43 222222222222222222222222222222222222222222281 44 2222222222222222222222222222222222222222222297 45 22222222222222222222222222222222222222222222273 46 222222222222222222222222222222222222222222222253 47 2222222222222222222222222222222222222222222222219 48 22222222222222222222222222222222222222222222222219 49 2222222222222222222222222222222222222222222222222113 50 2222222222222222222222222222222222222222222222222279 51 22222222222222222222222222222222222222222222222222289 52 2222222222222222222222222222222222222222222222222222449 53 22222222222222222222222222222222222222222222222222222169 54 222222222222222222222222222222222222222222222222222222251 55 222222222222222222222222222222222222222222222222222222251 56 2222222222222222222222222222222222222222222222222222222213 57 222222222222222222222222222222222222222222222222222222222449 58 2222222222222222222222222222222222222222222222222222222222137 59 22222222222222222222222222222222222222222222222222222222222373 60 222222222222222222222222222222222222222222222222222222222222563 61 2222222222222222222222222222222222222222222222222222222222222129 62 2222222222222222222222222222222222222222222222222222222222222227 63 2222222222222222222222222222222222222222222222222222222222222227 64 2222222222222222222222222222222222222222222222222222222222222222203 ``` 582.5858 milliseconds Explanation: loops over integers and adds them as strings to the root string, which is the given "2's" string, and verifies if it's prime or not. ]
[Question] [ The [Cornu Spiral](https://en.wikipedia.org/wiki/Euler_spiral) can be calculated using Feynman's method for path integrals of light propagation. We will approximate this integral using the following discretisation. Consider a mirror as in this image, where `S` is the light source and `P` the point where we collect light. We assume the light bounces in a straight ray from `S` to each point in the mirror and then to point `P`. We divide the mirror into `N` segments, in this example 13, labelled `A` to `M`, so that the path length of the light is `R=SN+NP`, where `SN` is the distance from `S` to mirror segment `N`, and similar for `P`. (*Note that in the image the distance of points `S` and `P` to the mirror has been shortened a lot, for visual purposes. The block `Q` is rather irrelevant, and placed purely to ensure reflection via the mirror, and avoid direct light from `S` to `P`.*) [![Reflecting mirror](https://i.stack.imgur.com/t7cqV.png)](https://i.stack.imgur.com/t7cqV.png) For a given wave number `k` the [phasor](https://en.wikipedia.org/wiki/Phasor) of a ray of light can be calculated as `exp(i k R)`, where `i` is the imaginary unit. Plotting all these phasors head to tail from the left mirror segment to the right leads to the Cornu spiral. For 13 elements and the values described below this gives: [![enter image description here](https://i.stack.imgur.com/HoLM9.png)](https://i.stack.imgur.com/HoLM9.png) For large `N`, i.e. a lot of mirror segments, the spiral approaches the "true" Cornu spiral. See this image using various values for `N`: [![enter image description here](https://i.stack.imgur.com/93nxM.png)](https://i.stack.imgur.com/93nxM.png) **Challenge** For a given `N` let `x(n)` be the *x*-coordinate centre of the *n*-th mirror segment (`n = 0,1,2,...,N`): ``` x(n) := n/N-0.5 ``` Let `SN(n)` be the distance of `S = (-1/2, 1000)` to the n-th mirror segment: ``` SN(n) := sqrt((x(n)-(-1/2))^2 + 1000^2) ``` and similarly ``` NP(n) := sqrt((x(n)-1/2)^2 + 1000^2) ``` So the total distance travelled by the *n*-th light ray is ``` R(n) := SN(n) + NP(n) ``` Then we define the phasor (a complex number) of the light ray going through the *n*-th mirror segment as ``` P(n) = exp(i * 1e6 * R(n)) ``` We now consider the cumulative sums (as an approximation to an integral) ``` C(n) = P(0)+P(1)+...+P(n) ``` The goal is now plotting a piecewise linear curve through the points `(C(0), C(1), ..., C(n))`, where the imaginary part of `C(n)` should be plotted against its real part. The **input** should be the number of elements `N`, which has a minimum of 100 and a maximum of at least 1 million elements (more is of course allowed). The **output** should be a plot or image in any format of at least 400ร—400 pixels, or using vector graphics. The colour of the line, axes scale etc are unimportant, as long as the shape is visible. Since this is code-golf, the shortest code in bytes wins. *Please note that this is not an actual Cornu spiral, but an approximation to it. The initial path integral has been approximated using the Fresnel approximation, and the mirror is both not of infinite length and not containing an infinite number of segments, as well as mentioned it is not normalised by the amplitudes of the individual rays.* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~29~~ ~~26~~ 25 bytes *Thanks to @Adriaan for 3 bytes off!* ``` Q:qG/q1e3YytP+1e6j*ZeYsXG ``` Here's an example with input ~~`365`~~ `366`... because today is MATL's first birthday! (and 2016 is a leap year; thanks to @MadPhysicist for the correction). Or try it in [**MATL online!**](https://matl.io/?code=Q%3AqG%2Fq1e3YytP%2B1e6j%2aZeYsXG&inputs=366&version=19.6.0) (experimental compiler; refresh the page if it doesn't work). [![enter image description here](https://i.stack.imgur.com/bin9q.png)](https://i.stack.imgur.com/bin9q.png) ### Explanation ``` Q:q % Input N implicitly. Push range [0 1 ... N] (row vector) G/ % Divide by N, element-wise q % Subtract 1. This gives NP projected onto the x axis for each mirror element 1e3 % Push 1000. This is NP projected onto the y axis Yy % Hypotenuse function: computes distance NP tP % Duplicate, reverse. By symmetry, this is the distance SN + % Add. This is distance SNP for each mirror element (row vector) 1e6j % Push 1e6*1i * % Multiply Ze % Exponential Ys % Cumulative sum XG % Plot in the complex plane ``` [Answer] # MATLAB, ~~88 84~~ 81 79 bytes ``` g=@(x)hypot(1e3,x);h=@(x)plot(cumsum(exp(1e6i*(g(x)+g(1-x)))));f=@(N)h(0:1/N:1) ``` Thanks @LuisMendo for -3 bytes, and @Adriaan for -2 bytes! The function `g` is the distance function we use in `SN` and `NP`, and `h` does the rest of the calculation plus plotting. `f` the actual function we want and it produces the vector we need. This is the output for `N=1111` ![output for N=1111](https://i.stack.imgur.com/W7hQX.jpg) [Answer] # [GeoGebra](https://www.geogebra.org/), 107 bytes ``` 1 1E6 InputBox[a] Polyline[Sequence[Sum[Sequence[e^(i*b(((k/a)^2+b)^.5+((k/a-1)^2+b)^.5)),k,0,a],l],l,1,a]] ``` Each line is entered separately into the input bar. Input is taken from an input box. Here is a gif of the execution: [![Cornu spiral](https://i.stack.imgur.com/SNfPI.gif)](https://i.stack.imgur.com/SNfPI.gif) **How it works** Entering `1` and `1E6` implicitly assigns the values to `a` and `b` respectively. Next, the `InputBox[a]` command creates an input box and associates it with `a`. The inner `Sequence` command iterates over integer values of `k` from `0` to `a` inclusive. For each value of `k`, the required distance is calculated using the expression `((k/a)^2+b)^.5+((k/a-1)^2+b)^.5)`. This is then multiplied by `i*b`, where `i` is the imaginary unit, and `e` is raised to the result. This yields a list of complex numbers. After this, the outer `Sequence` performs the cumlative summation by iterating over integer values of `l` from `1` to `a` inclusive. For each value of `l`, the first `l` elements of the list are summed using the `Sum` command, again yielding a list of complex numbers. GeoGebra treats the complex number `a + bi` as the point `(a, b)`. Hence, the complex numbers can be plotted using the `Polyline` command, which joins all the points in the complex number list with straight line segments. [Answer] ## R, 102 82 80 bytes Edit: scrapped the function for calculating the distance Edit2: Noticed a nearly identical answer by @Plannapus (oh well) Edit3: Saved 2 bytes thanks to @Plannapus as well ``` N=scan();x=1:N/N;plot(cumsum(exp((sqrt(x^2+1e6)+sqrt((x-1)^2+1e6))*1e6i)),t="l") ``` For `N=1000` we get: [![enter image description here](https://i.stack.imgur.com/OJgiP.jpg)](https://i.stack.imgur.com/OJgiP.jpg) [Answer] # R, ~~86~~ ~~83~~ 81 bytes ``` plot(cumsum(exp(1e6i*((1e6+(0:(N<-scan())/N)^2)^.5+(1e6+(0:N/N-1)^2)^.5))),t="l") ``` Thanks @JarkoDubbeldam for the extra 3 bytes. For N=1000: [![N=1e3](https://i.stack.imgur.com/QhJVK.png)](https://i.stack.imgur.com/QhJVK.png) [Answer] ## Mathematica 89 Bytes (87 chars) ``` Graphics[Line[ReIm/@Tr/@Table[E^(I*10^6*Tr[โˆš(10^6+(-{0,1}+j/#)^2)]),{i,0,#},{j,0,i}]]]& ``` Usage: ``` %@100 ``` yields [![enter image description here](https://i.stack.imgur.com/bXwPX.png)](https://i.stack.imgur.com/bXwPX.png) ]
[Question] [ Pythagoras had his leg blown up in the war. It had to be amputated, and though he nearly died, he pulled through and made a full recovery. Now, after a year of walking with crutches, he gets the privilege of getting a prosthetic leg! Thing is, though, there are several that fit, but which ones? ## The Task Given a positive integer as input that is the length of one leg of a Pythagorean triple, output all possibilities for the other leg. For example, the smallest Pythagorean triple is (3,4,5), which forms a triangle with two legs of length 3 and 4, and a hypotenuse of length 5. ## Examples ``` Leg:5 12 Leg:28 21 45 96 195 Leg:101 5100 Leg:1001 168 468 660 2880 3432 4080 5460 6468 10200 38532 45540 71568 501000 ``` ## The Rules * Input will be a single positive integer `n`. * Output may be in any order, with any delimiter, in any base (though this base must be consistent), and with optional opening and closing braces, and optional trailing whitespace. That is, `1 2 3`, `[1,2,3]`, and `1,11,111` all fit this output specification. * You may assume that `n` will never be larger than one fourth of the fourth root of your language's limit (without using libraries). In practice, you may assume the input will be less than either this or 10,000, whichever is less. Pythagoras is waiting on you, so better write your code quick and short! [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes ``` ยฒRยฒ+ยฒร†ยฒO ``` *This answer is non-competing, since it uses features that have been implemented after the challenge was posted.* [Try it online!](http://jelly.tryitonline.net/#code=wrJSwrIrwrLDhsKyTw&input=&args=MTAwMQ) This approach does not use floating point math, so it will give the correct answer as long as the intervening lists can fit into memory. ### Idea If **(a, b, c)** is a Pythagorean triple, there are strictly positive integers **k, m, n** such that the set equality **{a, b} = {km2 - kn2, 2kmn}** holds. In particular, this means that **a < b2** and **b < a2**, so for input **a** we can simply check if **a2 + b2** is a perfect square for each **b** in **{1, โ€ฆ a2}**. ### Code ``` Input: x ยฒ Compute xยฒ. R Get get range 1 ... xยฒ. ยฒ Square each integer in that range. +ยฒ Add xยฒ to each resulting square. ร†ยฒ Check if the resulting sums are perfect squares. O Get all indices of ones. ``` [Answer] # Julia, 35 bytes ``` n->filter(i->hypot(i,n)%1==0,1:n^2) ``` This is an anonymous function that accepts an integer and returns an array. For each `i` from 1 to the input squared, we compute the hypotenuse using Julia's built-in `hypot` function, and determine whether the fractional portion is 0. If so, we keep it, otherwise it's excluded. [Answer] # CJam, 17 bytes ``` {:A2#{Amh1%!},1>} ``` This is an anonymous function that pops an integer from the stack and leaves an array in return. [Try it online!](http://cjam.tryitonline.net/#code=MTAwMQogICAgezpBMiN7QW1oMSUhfSwxPn0KfnA&input=) ### Idea If **(a, b, c)** is a Pythagorean triple, there are strictly positive integers **k, m, n** such that the set equality **{a, b} = {km2 - kn2, 2kmn}** holds. In particular, this means that **a < b2** and **b < a2**, so for input **a** we can simply check if **a2 + b2** is a perfect square for each **b** in **{1, โ€ฆ a2}**. ### Code ``` :A Save the input in A. 2# Square it. { }, Filter; for each B in {0, ..., A**2}: Amh Calculate the hypotenuse of (A, B). 1%! Apply logical NOT to its fractional part. Keep B if ! pushed 1. 1> Discard the first kept B (0). ``` [Answer] # Pyth - 13 bytes Brute forces all possible ones up till `n^2+1`. ``` f!%.a,TQ1S*QQ ``` [Test Suite](http://pyth.herokuapp.com/?code=f%21%25.a%2CTQ1S%2aQQ&input=5&test_suite=1&test_suite_input=3%0A4%0A5%0A28%0A101&debug=0). [Answer] # JavaScript ES6, 60 ~~62~~ Same as the other answers, checking from 1 to a\*a-1 ``` a=>[...Array(a*a).keys()].filter(b=>b&&!(Math.hypot(a,b)%1)) ``` Thx to @Mwr247 [the shortest way to build a range in ES6](https://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6#comment148127_61489) 2 bytes saved thx @ETHproductions [Answer] ## C, 96 bytes Alternately increment `y` (the other leg) and `z` (the hypotenuse) until their difference drops to 1. Output every exact match (`c==0`) you encounter on the way. ``` int x,y,z;main(int c,char**a){for(x=z=atoi(a[1]);++y<z;c=x*x+y*y-z*z,c?z+=c>0:printf("%d ",y));} ``` Call the compiled program with *n* as parameter; it will output a space-separated list of decimal numbers. Obviously not the shortest; I may find comfort in having the fastest. ``` $ time ./pyth 9999 200 2020 13332 13668 16968 44440 45360 54540 55660 137532 164832 168168 413080 494900 504900 617120 1514832 1851468 4544540 5554440 16663332 49990000 real 0m0.846s user 0m0.800s sys 0m0.000s ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` b/.Solve[#^2+b^2==c^2,PositiveIntegers]& ``` I'm using an undocumented form of `Solve`: when the list of variables is omitted, then `Solve` defaults to solving for all symbols in the expression. We thus save 6 bytes over the more regular `Solve[#^2+b^2==c^2,{b,c},PositiveIntegers]`. [`PositiveIntegers`](https://reference.wolfram.com/language/ref/PositiveIntegers.html) is new in version 12 of Mathematica and thus not available in [TIO](https://tio.run/#mathematica). In desktop Mathematica, we get ``` F = b/.Solve[#^2+b^2==c^2,PositiveIntegers]& ; F[5] (* {12} *) F[28] (* {21, 45, 96, 195} *) F[101] (* {5100} *) F[1001] (* {168, 468, 660, 2880, 3432, 4080, 5460, 6468, 10200, 38532, 45540, 71568, 501000} *) ``` [Answer] ## Python 2, 53 bytes ``` lambda n:[i for i in range(1,n*n)if abs(i+n*1j)%1==0] ``` A straightforward solution using complex `abs` to compute the length of the hypotenuse. It's safe to use `n*n` as an upper bound for the other leg because `(n*n)^2 + n^2 < (n*n+1)^2`. I tried using recursion instead but didn't get anything shorter. [Answer] ## Seriously, 20 bytes ``` ,;โ•—ยชDR;`โ•œ@ร‡A1@%Y`M@โ–‘ ``` Same strategy as xnor's Python answer: check `i in range(1,n*n)` for values where `abs(i+nj) % 1 == 0`, and output the list. [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3bbba644523b60bd40804131402559604d40b0&input=28) Explanation: ``` ,;โ•— get input and save a copy in register 0 ยชDR; push two copies of range(1,n*n) `โ•œ@ร‡A1@%Y`M map the function across one of the ranges: โ•œ@ร‡A compute abs(i+nj) 1@%Y push 1 if result % 1 is 0, else 0 M@โ–‘ swap the two lists, take values in the original range where the corresponding values in the second range are truthy ``` [Answer] # PARI/GP, 36 bytes ``` x->[y|y<-[1..x^2],issquare(x^2+y^2)] ``` [Answer] # APL(NARS), 373 chars, 746 bytes ``` Cโ†{hโ†{0=kโ†โบ-1:,ยจโตโ‹„(k<0)โˆจkโ‰ฅiโ†โ‰ขwโ†โต:โฌโ‹„โ†‘,/{w[โต],ยจk h w[(โณi)โˆผโณโต]}ยจโณi-k}โ‹„1โ‰ฅโ‰กโต:โบhโตโ‹„โบhโŠ‚ยจโต}โ‹„Pโ†{1โ‰ฅkโ†โ‰ขwโ†,โต:โŠ‚wโ‹„โ†‘,/{w[โต],ยจP w[aโˆผโต]}ยจaโ†โณk}โ‹„dโ†{โˆชร—/ยจ{kโ†โ‰ขbโ†1,ฯ€โตโ‹„โˆช{b[โต]}ยจโ†‘โˆช/101 1โ€ผk k}โต}โ‹„tโ†{(-/k),(ร—/2,โต),+/kโ†โต*2}โ‹„bโ†{โฌโ‰กaโ†3 C d wโ†โต:(โŠ‚1,โต,1)โ‹„(โŠ‚1,โต,1),a/โจ{โต[2]>โต[3]}ยจaโ†โ†‘โˆช/Pยจ,a/โจ{w=ร—/โต}ยจa}โ‹„uโ†{(โ†‘โต),2รทโจ(+/a),-/aโ†1โ†“โต}โ‹„t1โ†{(โ†‘ยจโต)ร—tยจ1โ†“ยจโต}โ‹„f1โ†{0=2โˆฃโต:โ†‘ยจt1 bโตรท2โ‹„{2โŠƒโต}ยจt1 uยจbโต}โ‹„fโ†{mโ†โŽ•ctโ‹„โŽ•ctโ†0โ‹„rโ†f1โตโ‹„โŽ•ctโ†mโ‹„r} ``` comment: ``` C: โบ combination in โต list P: permutations in โต list d: divisors of โต unsigned t: Pythagorian triple from โต list 2 unsigned b: if argument โต is one unsigned it would return the list of (k,i,j) where k,i,j are all divisors of โต, and โต=kร—iร—j and i>j u: from one triple (k,i,j) return (k,(i+j)/2,(i-j)/2) t1: apply (k,i,j) to t in the way kร—t i,j f: the function of this exercise ``` The idea would be factor the input for to know the possible m,n that generate using t all Pythagorian triple that has the input as leg. Test: ``` f 18298292829831839x 167413760243137645229428509060960 15219432749376149566311682641900 99808869980900940 1383584795397831778755607512840 f 5 12 f 28 195 96 21 45 f 101 5100 f 1001 501000 6468 38532 2880 468 660 168 5460 45540 4080 71568 3432 10200 โ‰ขf 1001 13 f 1663481166348349x 1383584795397831778755607512900 f 198820182831x 19764732550476133587280 346749693868002343608 5664631173992 6083327962596530720 613900915408 115583231289334114460 18249983887789596492 1883559626820 1040249081604007030900 54749951663368790920 6588244183492044529092 265093577108 2196081394497348176360 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~15~~ 14 [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 tacit prefix function. ``` (โธโŠข(+โˆŠโŠข)โณร—โณ)ร—โจ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NR745HXYs0tB91dAFpzUe9mw9PBxKaIHLF/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwZQrTcHIAkgYGhiCSQNDAA "APL (Dyalog Extended) โ€“ Try It Online") `ร—โจ`โ€ƒsquare (lit. multiplication selfie of) the argument `(`โ€ฆ`)`โ€ƒapply the following anonymous tacit function: โ€ƒ`โณ`โ€ƒ**ษฉ**ntegers 1 through the argument โ€ƒ`โณ`โ€ƒmultiply by **ษฉ**ntegers 1 through the argument (i.e. square) โ€ƒ`โŠข(`โ€ฆ`)`โ€ƒapply the following anonymous tacit function with the argument as left argument: โ€ƒโ€ƒ`+`โ€ƒis the sum โ€ƒโ€ƒ`โˆŠ`โ€ƒa member of โ€ƒโ€ƒ`โŠข`โ€ƒit? โ€ƒ`โธ`โ€ƒ**ษฉ**ndices of truths [Answer] # Perl 5, 43 bytes ``` $i=<>;{sqrt(++$_**2+$i**2)!~/\./&&say;redo} ``` If you want the script to terminate, we can inspect other legs up to nยฒ only, as [explained](/a/65894) by [xnor](/u/20260), so we have 48 bytes: ``` map{sqrt(++$_**2+$i**2)!~/\./&&say}1..($i=<>)**2 ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), 16 bytes ``` 1oUยฒ f@!(MhXU %1 ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=MW9VsiBmQCEoTWhYVSAlMQ==&input=MTAwMQ==) ### How it works ``` // Implicit: U = input integer 1oUยฒ // Generate a range of integers from 1 to U squared. f@!( // Keep only items X that return falsily to: MhXU %1 // Math.hypot(X,U) % 1. // This keeps only the items where sqrt(X*X+U*U) = 0. // Implicit: output last expression ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` รฎโ†โ– โ†‘ยปโŒโ•šรข ``` [Run and debug it](https://staxlang.xyz/#p=8c1bfe18afa9c883&i=5%0A28%0A101%0A1001&m=2) In pseudo-code: ``` (1..nยฒ).filter(d -> is-square(nยฒ + dยฒ)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` nDLn+ร…ยฒฦถ0K ``` [Try it online](https://tio.run/##yy9OTMpM/f8/z8UnT/tw66FNx7YZeP//b2QBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2//NcfPK0D7ce2nRsm4H3f53/0aY6RhY6hgaGQGxgGAsA). ``` nDLส’nIn+ร…ยฒ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/z8Xn1KQ8zzztw62HNv3/b2QBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2SwqO2SQpK9v/zXHxOTcqLyNM@3Hpo0/9anf/RpjpGFjqGBoZAbGAYCwA). **Explanation:** ``` n # Take the square of the (implicit) input-integer D # Duplicate it L # Create a list in the range [1, input^2] n # Square each value in this list + # Add the input^2 we duplicated to each ร…ยฒ # Check for each of these if it's a square (1 if truthy; 0 if falsey) ฦถ # Multiply each value by its 1-based index 0K # Remove all 0s from the list # (after which the result is output implicitly) nDL # Same as above ส’ # Filter this list by: n # Get the square of the current number In+ # Add the squared input to it ร…ยฒ # And check if it's a square # (after the filter, implicitly output the result) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 9 bytes ``` ยฒโ•’gร†ยฒkยฒ+ยฐ ``` [Try it online!](https://tio.run/##ASAA3/9tYXRoZ29sZv//wrLilZJnw4bCsmvCsivCsP//NQoyOA "MathGolf โ€“ Try It Online") Couldn't find a nice way to remove any of the `ยฒ`s, which take up 3/9 bytes. Otherwise it is quite straight-forward ## Explanation ``` ยฒ square input โ•’ range(1,n+1) gร† filter list using next 5 operators ยฒ square list element kยฒ push input squared + pop a, b : push(a+b) ยฐ is perfect square ``` [Answer] # Java 8, 72 bytes ``` n->{for(int i=0;++i<n*n;)if(Math.hypot(i,n)%1==0)System.out.println(i);} ``` [Try it online.](https://tio.run/##jY5BC4JAEIXv/oq5BLuVokEQbNs/0EvH6LCtmmM6iq5CiL/dVvPYocvAvPnmvZerXrl5/Jp0odoWQoU0OABIJmlSpROI5hWgrzAGzawOxIWVRseO1iiDGiIgkBO5lyGtmoVB6YvdDs@0JcExZaEymZe968ow3BPfBFL6/PpuTVJ6VWe8urFfBTHkYpzEbF13j8JarwlLfGnLsaux6PN2B8W/zcjT7LhUAvjhuF5m6nD6Cwv84E9uBUdnnD4) **Explanation:** ``` n->{ // Method with integer as parameter and no return-type for(int i=0;++i<n*n;) // Loop `i` in the range (0, nยฒ)): if(Math.hypot(i,n) // If sqrt(iยฒ + nยฒ) %1==0) // has no decimal digits after the comma (so is an integer) System.out.println(i);} // Output `i` with trailing newline ``` ]
[Question] [ The problem with the Caesar cipher is the resulting words are often unpronounceable. The problem with Pig Latin is that it is easy to decode. Why not combine them? **Input** A word consisting of the 26 english letters. **Output** First, change every consonant in the word to the next consonant in the alphabet. So, b goes to c, d goes to f, and z goes to b. Then, change every vowel to the next vowel in the alphabet (u goes to a). Last, only if the first letter of the word is a consonant, move that letter to the end of the word and add "ay" to the end of the word. Examples: ``` cat -> evday dog -> uhfay eel -> iim ``` * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. * Case does not matter. * Vowels that will be used are A, E, I, O, and U [Answer] # [Ruby](https://www.ruby-lang.org/), ~~96~~ 69 bytes ``` ->s{/^[^aeiou]/=~(r=s.tr'zb-yadehinotu','b-zefijopuva')?$'+$&+'ay':r} ``` [Try it online!](https://tio.run/##DcrdDoIgGADQe5/CC9dXE/W@jXoQhttHgtFKGEIDf3p18uZcHRdEyorm5javXc96lNoE3tHf2dG59Q4W0SQc5FNPxgcgIJpFKv0yNnwRLvcK6upUAya4uj0zeKA/0mDGQynfQEoQYQTeftCuW9wKW7JIFIuc70X@Aw "Ruby โ€“ Try It Online") Fun fact of the day: tr() matches strings right-to-left. I always assumed it was left-to-right. [Answer] # [R](https://www.r-project.org/), ~~86~~ 85 bytes Simple way. `chartr` has the charming and useful property that it can specify letter *ranges*, which save a few bytes. -1 bytes by stealing @GB's [Ruby solution's](https://codegolf.stackexchange.com/a/172313/81549) translation strings - upvote it! ``` function(s)sub("^([^aeiou])(.*)","\\2\\1ay",chartr('zb-yadehinotu','b-zefijopuva',s)) ``` [Try it online!](https://tio.run/##JcZLDsIgEADQvceYDTMGTOram4hNBgotxjCGj0l7eTTxrV4Z8WZG7Nm3JBkr1e4QZrzPHJL0B@HlTKDB2qu1E@@g/calFVSHMzsvYUtZWldaOXOEmJ7y7h9WuhKNiOC5AZ1@WWT9J4QX0PgC "R โ€“ Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 167 bytes ``` s->{String r="",a="aeiouabcdfghjklmnpqrstvwxyzb",c=s.split("")[0];s=a.indexOf(c)>5?s.substring(1)+c+"ux":s;for(var d:s.split(""))r+=a.charAt(a.indexOf(d)+1);return r;} ``` [Try it online!](https://tio.run/##TY9Lb8IwEITv/IqVJSS7CVY59EIaql56q3rgiHpwnAcOiZN6NykU5beneVDowVqPZvbTTq5atcrjY2/KunIE@aBlQ6aQaWM1mcrKh2ChC4UI78pYuCwA6iYqjAYkRcNoKxNDOXh8R87YbP8JymUopijA25XzPLv@PLaQQtjjanuZNbiQMV@FTCWmalSk4zQ75MeitPWXQ2q/T@efiPk6RIl1YYgzJvaPnwGGShobJ6ePlGuxfXoZ/CbCicnXwtMea05sg0FaOd4qB/HmH0E4b9jXB@Veid9BsfDWInAJNc6CC7o@mJrc6lGChBBeCwIwrYj5fyKusrtIkoJN/25mjGdcG4@UzcwSN9TujJSUsmpI1kOKUs6WuIElLi3zp7APqVR1XZz5qISYud1ifF3/Cw "Java (JDK) โ€“ Try It Online") ## Credits * -7 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), using better types. * -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` ลพMDร€โ€กลพNDร€โ€กยฌลพNsรฅiร€โ€ฆรฟay ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVvn/6D5fl8MNjxoWHt3nB2EcWgNkFh9emgniLTu8P7Hyf22l0uH9Crp2Cof3K@n8T04s4UrJT@dKTc0BAA "05AB1E โ€“ Try It Online") **Explanation** ``` ลพMDร€โ€ก # replace each vowel with the next vowel in the alphabet ลพNDร€โ€ก # replace each consonant with the next consonant in the alphabet ยฌลพNsรฅi # if the first letter is a consonant ร€โ€ฆรฟay # rotate the word left and add "ay" ``` [Answer] # T-SQL, 169 bytes ``` SELECT IIF(CHARINDEX(LEFT(a,1),'aeiou')=0,SUBSTRING(a,2,99)+LEFT(a,1)+'ay',a)FROM (SELECT TRANSLATE(v,'aeioubcdfghjklmnpqrstvwxyz','eiouacdfghjklmnpqrstvwxyzb')a FROM t)s ``` Input is via a pre-existing table, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Performs the characters substitution first, using the ([new to SQL 2017](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017)) `TRANSLATE` function, then checks the first character. Annoying long mostly due to SQL keyword length. [Answer] # [Node.js 10.9.0](https://nodejs.org), ~~121~~ 116 bytes Expects the input string in lower case. ``` s=>(v=n=>2130466>>n&1)((a=Buffer(s).map(n=>(g=i=>v(n=n%61?n+1:97)^i?g(i):n)(v(n))))[0],a+='')?a:a.slice(1)+a[0]+'ay' ``` [Try it online!](https://tio.run/##bYpRC8IgFEbf@xmD8l6sMSsWDXTQ34iCy1IxTMdcg369@Rx9T4dzvictlIbJjfMuxIfORuYkFSwySLUXh@bYtkqFjUAAkpe3MXqChPWLRigPsNJJtRQM61b0gYvufMK76y047AJCSVh2bW5b4pIx7KmjOnk3aBDIqQTO6MPyEEOKXtc@WjBQDTRXiKsf@4j2j9XaF5u/ "JavaScript (Node.js) โ€“ Try It Online") ### Identifying vowels To identify vowels, the helper function \$v\$ uses the following bitmask: ``` 2130466 = 000001000001000001000100010 ^ ^ ^ ^ ^ zyxwvutsrqponmlkjihgfedcba- ``` And does: ``` (2130466 >> n) & 1 ``` We don't need to mask out the relevant bits of \$n\$, because it is done implicitly. Below is the relevant quote from [the ECMAScript specification](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-signed-right-shift-operator): > > Let *shiftCount* be the result of masking out all but the least significant 5 bits of *rnum*, that is, compute *rnum* & 0x1F. > > > ### Commented ``` s => // s = input string ( v = n => // v = helper function taking n = ASCII code in [97..122] 2130466 >> n & 1 // and returning 1 if the corresponding character is a vowel ) // or 0 otherwise (see the previous paragraph) ( // this statement will ultimately invoke v on a[0] ( a = Buffer(s) // convert s to a Buffer, holding ASCII codes .map(n => // for each ASCII code n in there: ( g = i => // g = recursive function taking i = vowel flag v( // update n and invoke v on the new value: n = n % 61 ? // if n is less than 122 (meaning less than 'z'): n + 1 // increment n : // else: 97 // wrap around by setting n to 97 (meaning 'a') ) ^ i ? // if v(n) is not equal to i: g(i) // do recursive calls until it is : // else: n // stop recursion and return the new n )(v(n)) // initial call to g with i = v(n) ) // end of map() )[0], // invoke v on a[0] a += '' // coerce the updated Buffer back to a string ) ? // if a[0] is a vowel: a // return the string as-is : // else: a.slice(1) + a[0] // move the leading consonant to the end + 'ay' // and append the 'ay' suffix ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~153~~ ~~121~~ ~~110~~ ~~99~~ 91 bytes ``` lambda s:[s[1:]+s[0]+"ux",s][s[0]in'aeiou'].translate(8*".ecdfighjoklmnpuqrstvawxyzb.....") ``` [Try it online!](https://tio.run/##HcdBDoIwEEDRtZyi6WZAGqKuDAlepHYxQIFqaZEpClwexb94yR@W0Hl32ZrivlnsyxoZ5ZLkOVcpyZNK@TRzQUruYxygNn4ClYURHVkMOr4eeaarujFt9/BP27theo0U3viZl7XM9niyNX5kxIxjEioMIKD27U@tLQgG6x/cnWZQeXQYRuMCIwHFDUQTUxJtXw "Python 2 โ€“ Try It Online") 8 bytes shaved off due to a suggestion by [Matthew Jensen](https://codegolf.stackexchange.com/users/87728/matthew-jensen) [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` รนโ‰ฅยฑโ•˜โ”œ*Lรขโ– 8Oยฑรขฮ“โ•‘ฮ˜รฆ%ยบโ€ข ``` [Run and debug it](https://staxlang.xyz/#p=97f2f1d4c32a4c83fe384ff183e2bae99125a707&i=cat%0Adog%0Aeel%0Az%0Athe&m=2) **Explanation** ``` Vc:tVv:tBcVc#{sL"ay"+}ML #Full program, unpacked, implicit input Vc:t #Push consonants and ring translate input Vv:t #Push vowels and ring translate input BCvc# #Push first letter and tail of word, find number #of occurrences to consonants {sL"ay"+}M #If truthy (word starts with consonant) #swap stack, listify, add "ay" L #Listify stack (combines words that start with vowel) ``` I went through a few iterations and finally got it down to 20. My original solution was 53 bytes. [Answer] # Shell script, 70 bytes ``` tr a-z b-{|tr eiou{bfjpv fjpvbeioua|sed -E 's/^([^aeiou])(.*)/\2\1ay/' ``` [Try it online!](https://tio.run/##S0oszvj/v6RIIVG3SiFJt7oGyEzNzC@tTkrLKihTABFJIH5iTXFqioKuq4J6sX6cRnRcIkgwVlNDT0tTP8YoxjCxUl/9//@M1JycfIXy/KKcFAA "Bash โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 102 97 bytes ``` h(c:r)|elem c"aeiou"=c:r|True=r++c:"ay" f s=h["ecdfighjoklmnpuqrstvawxyzb"!!(fromEnum y-97)|y<-s] ``` [Try it online!](https://tio.run/##Ncw7D4IwFAXgnV9RbxwgDbORWDc3N92MQy0XivSBfagQ/jt2kO3LyTlHct@jUssic1G5YkaFmgjg2NkILEXz1UVkjlJRAR8ha4hn8gYo6qZr5dP2SpshvpwPb/75jtMDNpu8cVafTNRkLPe7Yh4Ppb8vLpq0HWK4BHc2W08pkPJIgNL0mWneGVbbjJDUA8ED/FnbdiWiWhkkrpxg@QE "Haskell โ€“ Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` T`uo`aei\oub-df-hj-np-tv-zb ^([^aeiou])(.*) $2$1ay ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyShND8hMTUzJr80STclTTcjSzevQLekTLcqiStOIzoOKJVfGqupoaelyaVipGKYWPn/f3JiCVdKfjpXamoOAA "Retina 0.8.2 โ€“ Try It Online") Link includes test cases. Similar approach to the R answer. Explanation: ``` T`uo`aei\oub-df-hj-np-tv-zb ``` `o` refers to the other set, i.e. `aei\oub-df-hj-np-tv-zb`, which expands to `aeioubcdfghjlkmnpqrstvwxyzb`, so `uo` expands to `uaeioubcdfghjlkmnpqrstvwxyzb`. This results in the following transliteration: ``` uaeioubcdfghjlkmnpqrstvwxyzb aeioubcdfghjlkmnpqrstvwxyzb ``` The second `u` and `b` are ignored as they can never be matched, so this provides the desired cipher. (Note that in Retina 1 you can of course use `v` instead of `aei\ou` for a 5 byte saving.) ``` ^([^aeiou])(.*) $2$1ay ``` If the first letter is not a vowel, rotate it to the end and suffix `ay`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ,แน™ยฅ1y ร˜แบนรงร˜แธ„รงแน™แธขeยฉร˜แธ„ฦŠยฎโพayx ``` [Try it online!](https://tio.run/##y0rNyan8/1/n4c6Zh5YaVnIdnvFw187Dy4HUjpbDy4GiD3csSj20Esw/1nVo3aPGfYmVFf///0/JTwcA "Jelly โ€“ Try It Online") Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) (use the two-char syntax rather than quotes). [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~94~~ 92 bytes ``` i:0(?v"a"% 2%?!v\~r:5g a2r}<vr+ad* ol?!;>4g ecdfighjoklmnpuqrstvawxyzb 1 1 1 1 1 ``` [Try it online!](https://tio.run/##S8sszvj/P9PKQMO@TClRSZXLSNVesSymrsjKNJ0r0aio1qasSDsxRYsrP8de0drOJJ0rNTklLTM9Iys/Oyc3r6C0sKi4pCyxvKKyKonLUEFBAYbh5P//qak5AA "><> โ€“ Try It Online") *Edit: Saved 2 bytes by taking input mod 97 rather than 32, so the dictionary could start at the beginning of the line. Previous version:* ``` i:0(?v84*% 2%?!v\~r:5g 37r}<vr*46* ol?!;>4g ecdfighjoklmnpuqrstvawxyzb 1 1 1 1 1 ``` [Answer] # [Red](http://www.red-lang.org), 149 bytes ``` func[s][c:"aeioua.bcdfghjklmnpqrstvwxyzb"t: copy""foreach p s[append t c/(1 + index? find c p)]if 7 < index? find c t/1[move t tail t append t"ay"]t] ``` [Try it online!](https://tio.run/##XYxBCsIwEEX3PcUwK0WwdCUUwTu4DVmkk0kbbZOYprX18rEbRVw93of3I@t8ZS1kYepsJkdilIJqVGz9pI4NadN2t3s/uPCIY5qfy/pqMNVAPqyIxkdW1EGAUagQ2GlIQOWuKg5gneblAmYjEIS9tAZOcP7bU1mJwc@8dUnZfsPnB9WKMskconUJDCCphMXXtG9/jLnHIr8B "Red โ€“ Try It Online") As (almost) always, the longest entry [Answer] # [F# (Mono)](http://www.mono-project.com/), 197 bytes ``` let f(s:string)= let a="aeiouabcdfghjklmnpqrstvwxyzb" new string(s|>Seq.map(fun c->a.[a.IndexOf(c)+1])|>Seq.toArray)|>(fun x->if a.IndexOf(x.[0])>5 then x.Substring(1)+(string x.[0])+"ay"else x) ``` [Try it online!](https://tio.run/##RY3NaoQwFIX3PsUlMJAghs6imxYDXRYKXcxSXES9cTLVxEliJ5Z5d5vRQjf373z3HOWL0Rq7rgMGUNS/@OC06VmZweMiSyJR21k2baf68@VrGM10dT583@Ly05AMDN5g/6H@Lk545aOcqJoNtIWQvJL83XQYPxVtWX6s2c4E@@acXNK2obEQWsE/Gnn1VDPxDOGMSeWnufnLOLKc7iPsUE7kQnDwCJFla0VaGcgr6WyfKuJAargL@NA@cB3QwRaXDKAQMCWboAyQg4dSwMGTTaHq0RhbfwE "F# (Mono) โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 56 bytes ``` y/a-z/ecdfighjok-npuq-tvaw-zb/;s/^([^aeiou])(.*)/$2$1ay/ ``` [Try it online!](https://tio.run/##BcFBDkBADADAu3c4IKmGxMlThKQoFtFlF@HxasbysRaqDxK8yF0/mHGaZYHNnjv4i254WywdNlHVEBs56zhKkxjDPMzoQdWOfNDLGDCvn1hvZHMK9gc "Perl 5 โ€“ Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 107 bytes ``` x=>x.replace(/./g,y=>(z='aeiouabcdfghjklmnpqrstvwxyzb')[z.search(y)+1]).replace(/^([^aeiou])(.+)/,'$2$1ay') ``` [Try it online!](https://tio.run/##bcxLCoMwFEDReZchQvLQRuxcNyIKMT7jJ5o0sda4@bR0UiidHrh34jt3wo5muzozdmgXvc7oQ1@EoygPZtEoLpBmLJOpL0p6FoTjqB@8FV0vh2lWy2ru1m378/BnS6A6mUNuxUA9JHkN30VDq@bT1kBZAllK4lucc08gCL06rZApLWlPI8G3CODyo52WfxRRvTW8AA "JavaScript (SpiderMonkey) โ€“ Try It Online") Expects input in lowercase. Replaces each character of the string with a the one after it in the string `'aeiouabcdfghjklmnpqrstvwxyzb'`, and then piglatinifies anything with an initial consonant. [Answer] # PHP, 112 bytes ``` <?=strtr(($s=strstr(aeiou,($s=$argn)[0])?$s:substr($s,1).$s[0].ux),join(range(a,z)),ecdfighjoklmnpuqrstvawxyzb); ``` or ``` <?=strtr(($s=strstr(aeiou,($argn)[0])?$argn:substr($s,1).$s[0].ux),join(range(a,z)),ecdfighjoklmnpuqrstvawxyzb); ``` assume lower case input. Run as pipe with `-nR` or [try them online](http://sandbox.onlinephpfunctions.com/code/d0f21a36cfe3f98e069799d069c4183eb4d1b2ca). --- You could as well use `strtr($s,uzbcadfgehjklminpqrsotvwxy,range(a,z))` instead of `strtr($s,range(a,z),ecdfighjoklmnpuqrstvawxyzb)`. [Answer] # Dyalog APL (SBCS), 57 bytes ``` {aโ†โŽ•A{(โบ~โต)โต}'AEIOU'โ‹„('AY',โจ1โŒฝโŠข)โฃ(โˆŠ/โŠƒยจโตa)โŠข(โŠ‚โตโณโจโˆŠa)โŒทโˆŠ1โŒฝยจa} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///303hUdsEhepEIPmob6pjtcaj3l11j3q3agJxrbqjq6d/qLrCo@4WBQ11x0h1nUe9Kwwf9ex91LUIqGCxxqOOLv1HXc2HVgBVKyRqAoU1HnU1ATmPejcDlQKlgYI924E0SNehFYm1XEBbwFa6HVqhoO7sGKKuoO7i7w4kXV19gGSIh6v6//8A "APL (Dyalog Unicode) โ€“ Try It Online") Takes input in uppercase only! (Because `โŽ•A` is uppercase alphabet) * `โŽ•A{(โบ~โต)โต}'AEIOU'`: Vector of consonants and vowels * `(โŠ‚โตโณโจโˆŠa)โŒทโˆŠ1โŒฝยจa`: Uses indices of each letter of the word in the normal alphabet (`โŠ‚โตโณโจโˆŠa`) to index (`โŒท`) into the cipher `โˆŠ1โŒฝยจa`. * `('AY',โจ1โŒฝโŠข)โฃ(โˆŠ/โŠƒยจโตa)`: Moves first letter to the end and appends 'AY', if the first letter is a consonant. Thanks for the cool challenge! [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 202 bytes ``` class C {b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z} class V {a,e,i,o,u} c: {@C,@V}=>{{c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z,b},{e,i,o,u,a}} p: ([]+)$1 *=>$1/$ @V _ (@C+)$1 ([]*)$2=>$2 $1 ay/$ _ ``` ]
[Question] [ Platforms are stretches of `-` characters separated by one or more characters. For example: ``` ------ -- ------ - ``` The above has 4 platforms sizes 6, 2, 6 and 1. Platforms that are not supported will fall. To be supported platforms need Jimmies. Jimmies look like this: ``` \o/ ``` They are three units wide. Don't ask me what supports Jimmies. Jimmies go under platforms to support them: ``` ------------------ \o/ \o/ \o/ \o/ ``` Each platform has a "center" of mass which is the average position of all its `-`s. (Or the average of the start and end.) A platform is supported by Jimmies if its center of mass is between two points of the platform above a Jimmy or exactly above part of a Jimmy. For example: ``` ----- \o/ ``` The above platform is supported because the center of mass is in a place the Jimmy is touching. ``` ---------------- \o/ \o/ ``` The above platform is also supported because its center of mass is between the two Jimmies. ``` ---- \o/ ``` In the above example the center of mass is between the Jimmy's hand and the Jimmy's head and thus the platform is supported by that Jimmy. The following platform is not supported: ``` ---- \o/ ``` This is because its center of mass is not directly above any part of the Jimmy and there is no Jimmy to the left. A Jimmy can help support multiple platforms: ``` ------- ------------- \o/ \o/ \o/ ``` Your task is to take as input platforms (consisting only of `-`s and s). And output the minimum number of Jimmies required to support all the platforms given. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. ## Test cases Each line has the input, `>` and then the output. Below I have added one way to place the Jimmies to support the platforms. This is neither part of the input nor output, it's just there for your convenience. ``` -------------------------------- > 1 \o/ --------------- ---------------- > 2 \o/ \o/ - ---------------------------- - > 2 \o/ \o/ - --------------------------- - > 3 \o/\o/ \o/ --- - ------------------------ - > 3 \o/ \o/ \o/ - ------------- -------------- - > 3 \o/ \o/ \o/ --------------- - -------------- > 3 \o/ \o/ \o/ - - - ------------------------- > 3 \o/ \o/ \o/ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18 13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แธฒแบˆแนฃ0Hยซ1ยงฤŠS ``` A monadic Link that accepts a list of characters and yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///hjk0Pd3U83LnYwOPQasNDy490Bf9/uHvL4fZHTWv@/9clALjQ@AqYChTw6VcAKVAgoABEKuA1AZ8bFLA4UgHTkQr43AFVoAsA "Jelly โ€“ Try It Online")** ### How? Jimmies can't help if the gap is greater than one, so the result is the sum of Jimmies required for each section after partitioning at such gaps. In each section, we need one Jimmy per platform minus one Jimmy for every two length-one platforms, since then Jimmies can share the load of these and any intermediate platforms. ``` แธฒแบˆแนฃ0Hยซ1ยงฤŠS - Link: list of characters, P แธฒ - split at spaces แบˆ - length of each -> lengths of platforms with zeros between sections แนฃ0 - split at zeros -> list of section platform lengths (potentially including phantom empty sections) H - halve (vectorises) ยซ1 - minimum with one (vectorises) ยง - sums ฤŠ - ceiling (vectorises) S - sum ``` [Answer] # ARM T32 machine code, 32 bytes ``` 0003 2000 2102 1e4a bf58 07d1 0fc9 3905 3102 f150 0000 cb04 2a20 d0f4 d8f8 4770 ``` Following the [AAPCS](https://github.com/ARM-software/abi-aa/blob/2bcab1e3b22d55170c563c3c7940134089176746/aapcs32/aapcs32.rst), this takes in r0 the address of the input as a null-terminated string *in UTF-32* (if this is not allowed, +2 bytes for `LDMIA` โ†’ `LDRB` with writeback or 2 instructions), and returns the number of Jimmies needed in r0. The problem can be solved by a greedy algorithm, reading the string one character at a time while maintaining some values: \$L\$, the length so far of the current platform or 0 if none; \$Z\$, a flag that is 1 if the current platform is supported at its left end, and 0 otherwise; and \$T\$, the number of Jimmies used so far. When reading a platform character (`-`), if \$Z\$ is 0, we need to add a Jimmy (incrementing \$T\$) the first time (when \$L\$ is 0); if \$Z\$ is 1 (left-supported), we only need to add a Jimmy if the platform is longer than 1, so increment \$T\$ on the second platform character (when \$L\$ is 1). These cases can be combined: increment \$T\$ if \$L = Z\$. Afterwards, \$L\$ is incremented. When reading a non-platform character (), the way \$Z\$ is modified is more complicated. For a long platform (\$L \ge 2\$), if the platform is not left-supported, its Jimmy supports only that platform, whereas if it is left-supported, its second Jimmy can be placed at its right end to potentially support a later platform; this means that \$Z\$ remains unchanged. For a short platform (\$L\$ is 1), an existing left-support is enough for it, while if it was not left-supported, then it gets a new Jimmy that can also support a later platform; this means that \$Z\$ is inverted. Finally, if there is no platform between two consecutive non-platform characters (\$L\$ is 0), then any out-hanging Jimmy runs out; \$Z\$ is set to 0. Afterwards, \$L\$ is set to 0. Here is a summary of the way \$Z\$ is changed: $$ \begin{array}{c|ccccc} & 0 & 1 & 2 & 3 & \cdots \\ \hline 0 & 0 & 1 & 0 & 0 & \cdots \\ 1 & 0 & 0 & 1 & 1 & \cdots \end{array} $$ In my program, \$L\$ and \$Z\$ are combined into a single value \$K = 2L - Z - 2\$. Then, when reading a platform character (`-`), \$K\$ is increased by 2, and \$T\$ is incremented if \$K\$ changes from -2 to 0 or from -1 to 1, or equivalently, if \$K\$ changes from negative to nonnegative. When reading a non-platform character (), \$K\$ changes as follows: $$ \begin{array}{c|cccc|ccccc} \textrm{Before} & -3 & -2 & -1 & 0 & 1 & 2 & 3 & 4 & \cdots \\ \hline \textrm{After} & -2 & -2 & -2 & -3 & -3 & -2 & -3 & -2 & \cdots \end{array} $$ Assembly: ``` .code 16 .section .text .syntax unified .global njimmies .thumb_func njimmies: movs r3, r0 @ Transfer string address to r3 movs r0, #0 @ Total number of Jimmies = 0 movs r1, #2 @ K = 2 (will be changed by the following code before reading the string) space: subs r2, r1, #1 @ Calculate K-1 it pl @ If the result is nonnegative... lslpl r1, r2, #31 @ shift the low bit of the result into the high bit of r1 lsrs r1, r1, #31 @ Shift the high bit of r1 into the low bit; all other bits become 0 subs r1, #5 @ Make the value -4 or -5, and fall through platform: adds r1, #2 @ Add 2 to K adcs.w r0, #0 @ Count up one Jimmy if K went from negative to nonnegative ldmia r3!, {r2} @ Load the next character cmp r2, #32 beq space @ Jump on ' ' bhi platform @ Jump on '-' bx lr @ Return on the null terminator ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~20~~ 19 bytes ``` Oแธ‚ล’rยต=1Eฦ‡แนฃร˜0แบˆ:2SแบกSแธข ``` [Try it online!](https://tio.run/##y0rNyan8/9//4Y6mo5OKDm21NXQ91v5w5@LDMwwe7uqwMgp@uGth8MMdi/4/3L3lcPujpjX//@sSAFxofAVMBQr49CuAFCgQUAAiFfCagM8NClgcqYDpSAV87gAA "Jelly โ€“ Try It Online") This may or may not be an incredibly stupid way to do it. Based on the following observation: the best way is to use one Jimmy per platform, unless there are two platforms of length 1 such that all spaces between them are also length 1, in which case they can be connected by Jimmies, saving one Jimmy. [Answer] # [C (clang)](http://clang.llvm.org/), 73 bytes ``` c;o;f(*s){for(c=o=1;*s;o=*s++)c=o-*s?*s%5?s[1]%5>0|c:s[1]%2-~c:c;*s=c/2;} ``` [Try it online!](https://tio.run/##lZJdboMwDMffewoLCSlQUEunvjRjvcBu0PHQuUmFxABhqm7r2NHHHKAtQxrdoigf9u9vHGz0Mdmm@7pGmUktXHJOOisEhlkYSJdkFro0nTp8911au2Qv17QJInv5MP/AVXNc@J@4QoZDnC1kVcdpCS/bOBXO5DQBHmxwoVRU0iaCEFqjGY@Wf2NY3u8wjMMwFheGMPwDNhb4c@SxnOHGA2H8gTCWdwdX8lwDUK@5wlLt2ipA4MGimXf92RdgduA1BIrfVabFWe/A7Gxiyml57howV4hZMJe83bd6PnIDNcy18peWYLjtjDiSfS8kKmXfEYkPwiDOT//zQW8MM4Wgp2Qe8zfBTg8GIm2sgyCFokNicuii9SLlBQNaWHZC7Ld3zfKUWt4lX6@Te9cfG0fdB6pJVX@hTrZ7qv3jNw "C (clang) โ€“ Try It Online") -7 byte thanks to ceilingcat!! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 bytes ``` {+/โŒˆ+/ยจ1โŒŠ2รทโจ0(โ‰ โŠ†โŠข)โ‰ขยจโตโŠ†โจ' 'โ‰ โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pb/1FPh7b@oRWGj3q6jA5vf9S7wkDjUeeCR11tj7oWaT7qXHRoxaPerSBu7wp1BXWQVO/W2v9pj9omkKuZ61HfVKD2NAV1XVSgAIQoQP0/AA "APL (Dyalog Unicode) โ€“ Try It Online") [Answer] # [R](https://www.r-project.org/), ~~109~~ ~~93~~ 92 bytes Or **[R](https://www.r-project.org/)>=4.1, 78 bytes** by replacing two `function` appearances with `\`s. ``` function(x,`+`=strsplit,`?`=sum)?sapply(el(x+" ")+" ",function(a)pmin(nchar(a)/2,1)?.5)%/%1 ``` [Try it online!](https://tio.run/##jY5BCsMgEEX3PcUwEHCIbUihy@BVlFCpYKyogeT01m6yKZrOYpgPbz4vZD1lvbo5mbdjG5e9nGIK0VuTuBQlrAuJqLy3O3tatvUIgFQ28uNNkV@MY25@qVDCcOcjiduDuqEbs2Z4PRmkyy8FFQpaTXBQ8A/1PeG8q@UFNXuo2EPLDSl/AA "R โ€“ Try It Online") Port of [@Jonathan Allan's solution](https://codegolf.stackexchange.com/a/235264/55372). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` รฐยกโ‚ฌg0ยก<ฤ€>;OรฎO ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/235264/52210). [Try it online](https://tio.run/##yy9OTMpM/f//8IZDCx81rUk3OLTQ5kiDnbX/4XX@///rKoCggi4uAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8MbDi181LQm3eDQQpsjDXbW/ofX@f/X@a9LAHCh8RUwFSjg068AUqBAQAGIVMBrAj43KGBxpAKmIxXwuQOqQBcA). **Explanation:** ``` รฐยก # Split the (implicit) input-string on spaces # (`#` doesn't work here if the input lacks any spaces) โ‚ฌg # Get the length of each part 0ยก # Split this list of integers on 0s < # Decrease each length by 1 ฤ€ # Check which values are NOT 0 (0 if 0; 1 if >= 1) > # Increase each by 1 (1 if 0; 2 if >= 1) ; # Halve each (0.5 if 0; 1 if >= 1) O # Sum each inner list รฎ # Ceil each sum O # And sum those together again # (after which the result is output implicitly) ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~86~~ 78 bytes Thanks Johan du Toit for -8 ``` x=>(a=.5,x.split` `.map(p=>p.split` `.map(i=>a+=i?i[1]?1:.5:0,a=~~a+.5)),~~a) ``` [Try it online!](https://tio.run/##hZHRioMwFETf/YqhT4amQXcRlkrsh4jQ4MYli63BBBGW7a9bG7EotnpfDHNPJiPzKxph8lppe2i@uoJ3LU98wVlEW2Z0qewZOLOL0L7miR6lQVE8EXuuTioNs1N4ZNExoILfbmLPIkJofyBdI2pYaawBR@qhnxS7w8bsKMKMvqHxgv6Y0FhzxoLGFv05S4L3/gsaa7lfeM/XWPzl3Btr2ec0NqangyntAsxeGDUMuaOezmKvqGr4rmGo61AzwZ/zGXvva3d6arM0yGI8l7LVMrfyewqEI5BXV1OVkpXVj//YUhTuS@jzHom9/@4O "JavaScript (V8) โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~88~~ ~~81~~ ~~79~~ 77 bytes ``` lambda x:-sum(-sum(min(len(j),2)for j in i.split())//2for i in x.split(' ')) ``` [Try it online!](https://tio.run/##hY5BDoIwEEXXcIq/o01EIu40LnHrBdyAljBYSlNKhNNXa1yJKbP4yfy8mTw926ZXe1efrk6WXXUvMR3SYezYJzpSTArFWr7Jed0btCAF2g5akmWcZ1nuW/Lt9G0TIOHcPRuSArtDHFkzvzPShpRlNSOlR3/L40hMN6Etisu5MKY3nqqMKB9Hl65M/LNjCSB0Dw9gBfCJ4IeQA/5IYimJkMcL "Python 3 โ€“ Try It Online") -7 bytes thanks to [EnderShadow8](https://codegolf.stackexchange.com/users/103324/endershadow8) and [movatica](https://codegolf.stackexchange.com/users/86751/movatica). -2 bytes thanks to [movatica](https://codegolf.stackexchange.com/users/86751/movatica). -2 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard). Based on [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s answer. Outputs an integer. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes ``` --+ -- - ?-? ``` [Try it online!](https://tio.run/##K0otycxLNPz/X1dXm0tXl0tXwV7XHsRTAEMgDaYUwDQY6QIA "Retina โ€“ Try It Online") Reduce all long platforms to length 2, which doesn't change the result. Now each Jimmy can support up to two `-`s close together. Count such pairs of `-`s and excess single `-`s. [Answer] # [///](https://esolangs.org/wiki////), 31 bytes ``` /---/--//- -/--//--/1//-/1// // ``` Input should be appended to the program, as permitted [here](https://codegolf.meta.stackexchange.com/a/10553/104752). Output is in unary. [Try it online!](https://tio.run/##K85JLM5ILf7/X19XVxeI9fV1FaC0rr4hkAQRCiCeAhgCaTClAKbBCAj@/wcA "/// โ€“ Try It Online") This uses the same idea as one of my other answers โ€“ reduce all long platforms to length 2, which doesn't change the result, and then each Jimmy can support up to two `-`s close together โ€“ but does it in a somewhat more complicated way. ``` Example string: "- --- - ---- -" /---/--/ Reduce long platforms to length 2 "- -- - -- -" /- -/--/ Close short gaps "---- ---" /--/1/ Count pairs of -s "11 1-" /-/1/ Count leftover single -s "11 11" / // Remove spaces "1111" ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 19 bytes ``` ๏ผฉฮฃ๏ผฅโชช๏ผณ โŒˆโŠ˜ฮฃ๏ผฅโชชฮน โŒŠโŸฆยฒ๏ผฌฮป ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUAjuCAns0TDM6@gtCS4BCidrqGpo6CkoKAEpJxTM3NAIh6JOWWpKWhaMkHKQKp8M/Myc4FS0UY6Cj6peeklGRo5mrGaMGD9/7@ugoKCLlagAIZc/3XLcgA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: Now a port of @Yousername's answer. ``` ๏ผณ Input string โชช Split on pairs of spaces ๏ผฅ Map over runs โชชฮน Split run on spaces ๏ผฅ Map over each platform ๏ผฌฮป Length of platform โŒŠโŸฆยฒ Minimum of that and 2 ฮฃ Take the sum โŠ˜ Halved โŒˆ Ceiling ฮฃ Take the sum ๏ผฉ Cast to string Implicitly print ``` ]
[Question] [ The challenge is simple: write a program or function that, when given a finite non-negative integer, outputs a nested array. ## The rules * Your code must produce a **unique** valid nested array for *every* integer 0 โ€Œโ‰ค n โ€Œ< 231. * **Every** possible nested array with up to 16 open brackets must be outputted within this range. (This does not mean that your code can never output a nested array with more than 16 open brackets.) * Your code may output a string representation of the nested array instead of an actual array (with or without commas). One possible mapping: ``` 0 -> [] 1 -> [[]] 2 -> [[[]]] 3 -> [[], []] 4 -> [[[[]]]] 5 -> [[[], []]] 6 -> [[[]], []] 7 -> [[], [[]]] 8 -> [[], [], []] 9 -> [[[[[]]]]] etc. ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.** [Answer] # Python, 153 128 bytes ``` s=l=0;r="";n=input() for d in bin(n)[2:]*(n>0):c=d<"1";l=[l,s>1][c];r+="]"*c+(1-l*c)*"[";s+=1-c-l*c print"["+r+"["*l+"]"*(s+l+1) ``` We map a number *n* to a nested list by looking at its binary digits left-to-right. This algorithm works for any number, not just under 232. 1. If the current binary digit is an 1, output `[`. 2. Otherwise, if the sequence of brackets we've output so far would get balanced by a single closing bracket, output `][`. 3. Otherwise, if this is the last 0 in the binary number, output `][`. 4. Otherwise output `]`. Finally, we close any opened brackets. [Answer] # Python 2.7, ~~172 149 124~~ 118 bytes ``` x=input();y="";z=0 for b in bin(x)[2+(x<1):]:y+="[]"[b<"1"];z+=b>"0"or-1;z+=99*(z<0) print"["+(y,"[]"*(x+16))[z>0]+"]" ``` ### Explanation: Define a bijection by `[`โ†”`1` and `]`โ†”`0`. Any arrangement of brackets can then be written as a binary number and vice versa, for instance `[][]`โ†”`1010`(10) and `[[][]]`โ†”`110100`(52). All valid arrangements of up to 15 open brackets (30 brackets in total) are covered by numbers with up to 30 bits (ignoring leading zeros), which are precisely the numbers less than 231. The first for-loop gives the inverse of this bijection, converting a number to an arrangement of brackets, while checking that the arrangement is valid. Invalid arrangements are replaced within the print statement by long sequences of brackets to avoid collisions. For instance `11`(3)โ†”`[[` is not valid so we concatenate 3+16 brackets instead. This ensures all arrangements are unique. The resultant arrangement is placed within a pair of brackets to make a nested array, so that `1010`(10) becomes `[[][]]` and `110100`(52) becomes `[[[][]]]`. The extra open bracket means we've now covered all arrays with 16 open brackets. --- *The following program can be used to figure out the number for a given array with up to 16 brackets.* ``` s=raw_input();o=""; for c in s[1:-1]: if c=="[":o+="1" if c=="]":o+="0" print int(o,2) ``` [Answer] # [Spoon](http://progopedia.com/dialect/spoon/), 63 bytes (501 bits) ``` 000001001001001011001101001010011011111001010001000000101010 101101100110100101101001000101100010001000000100011000010000 000000000000001110111110010000001110110110010100100100100100 000110011010001000000110110000010000001010110011011011011001 000000011010010010010001000000111011011011101001001001000110 110110010100100101011001000100000011010001000000111011011001 010010010010010001101101101001000110110010110001101101101101 100100010001010010001010011011001000000011001101001001010010 000001100101001000111 ``` This is the following brainfuck program converted to spoon: ``` -[+[+<]>>+]<+++.[->+>+<<]>>++>>,[>-[<->-----]+<+++[-<+<<.>>>>-<]>[-<<-[->+<]<<<[-]>>>>[-<+<<<+>>>>]<<.>>+<[>-]>[-<+<<.>>>>]<<>>]<,]<<<<[>.>.<<[-]]>>>+[-<.>]+ ``` Reads an integer in binary on stdin, and outputs the nested list on stdin. Requires 0 to be input as the empty string (no digits), and requires a brainfuck interpreter with 8-bit cells. Same algorithm as my Python answer. Readable version: ``` -[+[+<]>>+]<+++. push open bracket and print it [->+>+<<] dup >>++ increment to close bracket >>,[ read input loop >-[<->-----]+<+++ subtract 48 and set up if/else [- if c == 1 <+ increment s <<.>>> output open bracket >-<]>[-< else <-[->+<] decrement and move s <<<[-] zero l >>>>[-<+<<<+>>>>] l = s and restore s <<.> output close bracket >+<[>-]>[- if s == 0 <+ undo s decrement <<. output open bracket >>>>]<< >>]< ,] <<<<[ if l >.>. output pair <<[-]] >>>+[-<.>] output close bracket s+1 times ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แธƒ2-*ยตSN;+\>-แบ  1ร‡#แนชแธƒ2แนญ2;1แป‹โพ][ ``` This iterates over all strings of the characters `[` and `]` that start with a `[` and end with a `]`, verifies if the brackets match, and prints the **n**th match. [Try it online!](http://jelly.tryitonline.net/#code=4biDMi0qwrVTTjsrXD4t4bqgCjHDhyPhuarhuIMy4bmtMjsx4buL4oG-XVs&input=&args=OA) [Answer] # Perl, ~~80~~ 79 bytes Again uses [orlp](https://codegolf.stackexchange.com/users/4162/orlp)'s algorithm, but this time I first checked if it works... Includes +1 for `-p` Give input number on STDIN ``` nest.pl <<< 8 ``` `nest.pl`: ``` #!/usr/bin/perl -p ($_=sprintf"%b",$_).=2x(s^.^$&or++$n-pos&&/.0/g?++$n%1:$`&&21^eg-$n);y;102;(); ``` [Linus](https://codegolf.stackexchange.com/users/46756/linus)'s solution is 64 bytes in perl: ``` #!/usr/bin/perl -p $_=sprintf"%b",/.+/g;$_=10x($&&&$&+16)if!/^(1(?1)*0)+$/;y;10;() ``` [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s solution is 59 bytes in perl (increasingly slower for large numbers): ``` #!/usr/bin/perl -p 1while$_-=(sprintf"%b",$n++)=~/^(1(?1)*0)+$/;$_=$&;y;10;() ``` [Answer] # Python 3, ~~120~~ 114 bytes ``` def f(n,k=0): while~n: k+=1 try:r=eval(bin(k).translate({48:'],',49:'['})[3:-1])+[];n-=1 except:0 print(r) ``` Test it on [Ideone](http://ideone.com/sQhCyA). ### How it works The defined function **f** takes input **n** and initializes **k** to **0**. We'll keep incrementing **k** until **n + 1** values of **k** result in a valid output. Every time we find such a value of **k**, **n** is decremented once it reaches **-1**, `~n` yields **0**, and the list **r** that corresponds to the last value of **k** is printed. The partial mapping from the positive integers to nested lists (i.e., **k โ†ฆ r**) has to be bijective, but there are no other constraints. The one used in this answer operates as follows. 1. Convert **k** to a binary string representation, staring with **0b**. For example, **44 โ†ฆ "0b101100"**. 2. Replace all **0**'s (code point **48**) in the string representation with the string **"],"** and all **1**'s (code point **49**) with **[**. For example, **"0b101100" โ†ฆ "],b[],[[],],"**. 3. Remove the first three characters (they correspond to **"0b"**) and the trailing character (hopefully a comma). For example, **"],b[],[[],]," โ†ฆ "[],[[],]"**. 4. Try evaluating the generated code. If this results in an error, **k** isn't mapped to any list. For example, **"[],[[],]" โ†ฆ ([], [[]])**. 5. Concatenate the result (if any) with the empty list. If this results in an error, **k** isn't mapped to any list. For example, **([], [[]]) + []** errors since **+** cannot concatenate lists and tuples. [Answer] ## Haskell, 71 bytes ``` p 1=["[]"] p n=['[':h++t|k<-[1..n-1],h<-p k,_:t<-p$n-k] ((p=<<[1..])!!) ``` The main function on the last line indexes into a list of all nested arrays, sorted by size (number of open brackets). So, all the arrays of size at most 16 are listed first. Let's first look at code that's nicer and shorter, but Haskell's typechecker refuses to accept. ``` p 1=[[]] p n=[h:t|k<-[1..n-1],h<-p k,t<-p$n-k] ((p=<<[1..])!!) ``` The function `p` on input `n` gives a list of all nested arrays of size `n` (open brackets). This is done recursively. Each such array consists of some head `h` (first member) of size `k` and some tail `t` (other members) of size `n-k`, both sizes nonzero. Or, it's the empty array for size `n==1`. The expression `p=<<[1..]` then flattens `p(1), p(2), ...` into a single infinite list of all arrays sorted by size ``` [ [], [[]], [[],[]], [[[]]], [[],[],[]], [[],[[]]], [[[]],[]], [[[],[]]], ... ``` and the main function indexes into it. ... Or, it would, if Haskell didn't whine about "construct[ing] the infinite type: t ~ [t]". Haskell cannot represent the infinite list above whose elements are arbitrarily nested arrays. All its elements must have the same type, but a type t cannot be the same as a list of t's. In fact, the function `p` itself cannot be assigned a consistent type without dependent typing, which Haskell lacks. So, instead we work on strings of brackets, simulating the cons operation by acting on `[` and `]` characters. This takes an extra 9 bytes. The perils of golfing in a type-safe language. [Answer] ## Haskell, ~~87~~ 82 bytes ``` 0#0=[""] n#m=['[':x|n>0,x<-(n-1)#m]++[']':x|n<m,x<-n#(m-1)] (([0..]>>= \y->y#y)!!) ``` Outputs the array elements. Usage example: `(([0..]>>= \y->y#y)!!) 3` -> `"[][]"`. Function `#` builds all nested arrays as strings for `n` open and `m` close brackets, by keeping track of how many of each are left over. Always starts with `n == m`. The main function calls `y # y` for every `y <- [0,1,...]` and picks the element at the index given by the input. [Answer] # [MATL](http://github.com/lmendo/MATL), 31 bytes ``` O`@BEqXJYs0&)0>w~hA+tG>~]x92J-c ``` [Try it online!](http://matl.tryitonline.net/#code=T2BAQkVxWEpZczAmKTA-d35oQSt0Rz5-XXg5MkotYw&input=NA) Or [verify the first few test cases](http://matl.tryitonline.net/#code=IkBYSwpPYEBRQkVxWEpZczAmKTA-d35oQSt0Sz5-XXg5MkotYw&input=MDo1) (takes a few seconds). The produced mapping is: ``` 0 -> [] 1 -> [[]] 2 -> [[][]] 3 -> [[[]]] 4 -> [[][][]] 5 -> [[][[]]] 6 -> [[[]][]] 7 -> [[[][]]] ... ``` ## Explanation The code keeps testing increasing binary numbers, with digit `0` replaced by `-1`; that is, using `1` and `-1` as digits. Digit `1` will represent `'['` and `-1` will represent `']'`. The program counts until *n*+1 *valid* numbers have been obtained. A number is valid if the following two conditions hold: 1. The sum of digits is zero (that is, there is an equal number of `1` and `-1`) 2. The cumulative sum of digits is always positive (that is, the accumulated number of `1` digits always exceeds that of `-1`) except at the end (where it is zero by condition 1). Once *n*+1 valid numbers have been obtained, the last one is transliterated by changing `1` into `[` and `-1` into `]`, and then it is displayed. Code: ``` O % Push 0: initial count of valid numbers ` % Do...while @ % Push iteretation index k, starting at 1 B % Convert to binary. For example, k=6 gives [1 1 0 0] Eq % Multiply by 2, subtract 1: transforms [1 1 0 0] into [1 1 -1 -1] XJ % Copy that to clipboard J, without popping it Ys % Cumulative sum: gives [1 2 1 0] 0&) % Split array into its final element and the rest. Gives 0, [1 2 1] 0> % Yields 1 for positive entries (condition 2). So in this case it % gives [1 1 1] w % Swap: moves second-top element in the stack (0 in this case) to top ~ % Negate: yields 1 if input is 0 (condition 1). Gives 1 in this case h % Concatenate horizontally. Gives [1 1 1 1] A % All: gives 1 if all elements are 1. Gives 1 in this case, meaning % that this k is valid + % Add the result (0 or 1) to the count of valid numbers t % Duplicate G % Push input n >~ % Loop condition: false (exit loop) if count exceeds input n ] % End loop. At this point the result is in clipboard J, in 1/-1 format x % Delete count 92 % Push 92. Will be used to convert 1, -1 to '[', ']' (ASCII 91, 93) J % Push result in 1/-1 format - % Subtract: converts 1 to 91, -1 to 93 c % Convert to char. Implicitly display ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 85 bytes ``` x=>eval("g=i=>i>1?(h-=i*2%4-1)&&']['[i%2]+g(i>>1):']';for(i=0;~x;~h||--x)h=0,g(i++)") ``` [Try it online!](https://tio.run/##ZcrdCoIwFADg@x5D0O1ki02toHHWg8guxPw5IS40xAvx1VfX7fbje1VLNdcTvT9idM/Gt@hXNM1SDTzqkNCQUQ/eC6RjFhdCQZIwW7KS4symHSdjFNyZZbp1EyeUel/13m@bECv0KE@/kqYQgdeH2o2zG5rz4DrecgnwJyqQLJA8kCKQSyDXQG4A/gs "JavaScript (Node.js) โ€“ Try It Online") Work for all positive integers assuming infinite bit width. But may fail when n is large and bit is broken. Slow. # [JavaScript (Node.js)](https://nodejs.org), 90 bytes ``` x=>eval("g=i=>i>1?(h-=[i]*2%4-1)&&']['[i%2n]+g(i>>1n):']';for(i=0n;~x;~h||--x)h=0,g(i++)") ``` [Try it online!](https://tio.run/##bc3dCoIwGIDh8y5D0O3LFptaQWPrQmQHYv4sZAsN8UC89eVxX6cPL7yvaq6merTvD3P@2YRWhUXpZq4GGnXKKm21eNCeqdKaYxYXTECSEFOS0saZM2lHrdbCwZ0YIls/Uqu4k9sit35dGVugV/y0R2kKEQR5qL2b/NCcB9/RlnKAHxFIMiQ5kgLJBckVyQ3fOf9nO4Yv "JavaScript (Node.js) โ€“ Try It Online") Should be enough and theoretically all. Slow. # [JavaScript (Node.js)](https://nodejs.org), ~~97~~ 96 bytes ``` x=>(h=x.toString(2).replace(/./g,c=>']['[i+=c-.5,i-=!i,c],i=0),i-.5?'['+'[]'.repeat(x+20):h)+']' ``` [Try it online!](https://tio.run/##ZctBDoIwEEDRvbdwNZ20FETRRDN4CJdNF00tUEMogcZw@6pbu/wv@S/zNqtd/ByLKTxd6iht1LKBNhnDIy5@6lmNcnHzaKxjpSx7YakFrUB5TraQjfAF7b2wWniq8FuyuYMCDkrDb3Qmso3XFV4H5KAh3XY2TGsYnRxDzzpWIf7JIZM6k2Mmp0yaTM6ZXBDTBw "JavaScript (Node.js) โ€“ Try It Online") Only fit the range. Fast for short output ]
[Question] [ You place a standard die at the origin of a 2D grid that stretches infinitely in every direction. You place the die such that the 1 is facing upwards, the 2 is facing in the negative y direction, and the 3 is facing in the positive x direction, as shown in the figure below: ![](https://i.stack.imgur.com/iMrcp.png) You then proceed to execute a series of moves with the die by rotating it 90 degrees in the direction of motion. For example, if you were to first rotate the die in the negative x direction, a 3 would be upwards, the 2 would be facing in the negative y direction, and a 6 would be facing in the positive x direction. The series of moves `+y, +y, +x, +x, -y` is shown in the figure below, along with the net of the die for clarification (sometimes the net is called a 'right-handed die'). ![](https://i.stack.imgur.com/FeOzU.png) We then proceed to read off the top face of the die after every move. In this case it would read `2, 6, 4, 1, 2`, which we call a *dice path*. Note we do not include the top face of the die in its initial position, but it is always 1. If the path of the die is such that it returns to the square it started on at the end of its movement, we call this a *dice path that returns to the origin*. ## Challenge Given a nonempty dice path as input (in a list or any other reasonable format), print a truthy value if the dice path returns to the origin, and a falsy value otherwise. Note that: * The truthy values and falsy values you output do not have to be consistent, but you can't swap them (eg. output a falsy value for a path that returns to the origin and a truthy value otherwise) * The input will be well formed and represent a valid dice path. * There is no limit to how far the die can stray from the origin. ## Test Cases ``` Path -> Output 2,1 -> true 3,1 -> true 5,4,1,5 -> true 2,4,1,2 -> true 4,2,4,1 -> true 2,4,6,2,4,6,5,4 -> true 2,4,5,1,4,5,3,6,5,1 -> true 5,6,2,3,5,4,6,3,1,5,6,2 -> true 2,4,1,3,5,1,3,5,6,3,5,6,4,5,6,2 -> true 2 -> false 4,5 -> false 5,1,2 -> false 5,6,2,1 -> false 5,4,6,5,4,6 -> false 5,6,4,1,5,4,2,6,5,4 -> false 5,1,2,1,5,6,5,1,2,6,4 -> false 4,6,3,1,5,6,2,1,3,6,4,1 -> false ``` ## Scoring Shortest code in bytes wins. [Answer] # JavaScript (ES6), ~~142 ... 122~~ 121 bytes Expects an array of characters, e.g. `['5','1','2']`. Returns **0** or **1**. ``` a=>a.map(n=>D=D.map((_,i)=>D['504405076067'[d*6+i>>1]^i],p+=[w=a.length,-w,1,-1][d=D.indexOf(n)]),p=0,D=[...'254316'])|!p ``` [Try it online!](https://tio.run/##lZLBbsIwDIbvewp2cjNCaZo4nNIT2nWX3bJsimgLnbq0gjI2ae/ehQEaIFBpZEVJ9H@x7N/v9tOuZsuibkauSrM2V61ViQ0/bB04lUzV9O8YvNGC@KsGjISIMJrISE5Apw9yWCQJM6@FofVQ6Y2yYZm5ebOgow1ldMSMTv0nhUuzr6c8cMQQWquITpUOwxBiFJxJMOTnvm5nlVtVZRaW1TwA/bxcN4tvA@Tu@D0PdhyDwckyhAzG40GzXGeX9LynHgVD6KGPBYv76IUH@v0vfaCAm/XIBHKJhyxd9cqYo5Cc@QPcVi9HH9KH2DLH@hMAXpx@tOXqqpNnxhwy55653DqEfgCeWdMNyPiiOdeBrTUS@mTw8yXif0NvqMFb43e5Jzq7tPOScbkftGOg/QU "JavaScript (Node.js) โ€“ Try It Online") ### How? The array `D[]` holds the face values in the following order: ``` index | 0 | 1 | 2 | 3 | 4 | 5 -------+--------+--------+--------+--------+--------+-------- face | front | behind | left | right | top | bottom ``` We start with `D = ['2','5','4','3','1','6']`, which is the initial orientation of the die as described in the challenge, using this encoding. The direction `d` of the next move is the 0-indexed position of the new top face in `D[]`: ``` index (d) | 0 | 1 | 2 | 3 -----------+-------+-------+-------+------- direction | up | down | right | left ``` When moving towards direction `d`, the `i`-th face in the updated die is the face at the following position in the previous die: ``` i = | 0 | 1 | 2 | 3 | 4 | 5 -------+---+---+---+---+---+--- d = 0 | 5 | 4 | 2 | 3 | 0 | 1 d = 1 | 4 | 5 | 2 | 3 | 1 | 0 d = 2 | 0 | 1 | 5 | 4 | 2 | 3 d = 3 | 0 | 1 | 4 | 5 | 3 | 2 ``` This table is encoded with the following expression: ``` '504405076067'[d * 6 + i >> 1] ^ i ``` [Try it online!](https://tio.run/##dY/LDoIwEEX3fMVdmBRESFHABcqPEAwN9VFiqBF1o3w7XjQmurDJySzmTO9Mo26qq8/mdAlaq7fDUNu2s8dteLR7VwAwWOMBSSIyJwsSk0R4mfOjB@/n/2H0nZ09u5p/ygwaK8Qsvu/h7gBjS7FVlLNXLBVDJWX5KIAKT9fu4IpExrFM5DKV6VIUGlOk8OnnOaISGxiGAT35XrHCmD25654HVBxQYWNNy0sfEB5H@mF4Ag "JavaScript (Node.js) โ€“ Try It Online") At each iteration, we update `D[]` and the position `p`. We add \$\pm 1\$ to \$p\$ when moving horizontally, or \$\pm w\$ when moving vertically, where \$w\$ is the length of the input array (an upper bound of the distance that can be traveled in a single direction). We test whether we're back to our starting point at the end of the process. [Answer] # [J](http://jsoftware.com/), 79 bytes Takes in the dice path as a reversed list of boxed 0 to 5. ``` 0 0-:[:+/(0,(,-@|.)=i.2){~]i.~&>[:}.(]A.~0 224 283 389 489{~i.~)&.>/\.@,&(<i.6) ``` [Try it online!](https://tio.run/##ldHNbsIwDAfwO09h7VAa0RrXSVFJADFN2mmnXRknBKJc9gBsffUudboPpBFKpbpS9ZPj/H1qH3B8gKWFMWRAYP2bIzy9vjy3BJTbjZ1MU8rSLF9/oFrWyOrcbGtsktXGfmK6fcSGgNkAVxp0NQdTzc@NByrB1fQN11mSLmqcqVaN9rvjOxSQWzhA7CFXwB2Yh2HjyGlnhuFC8MAxhDodx/5oVwos451JIPuqHUm9grtO3aVYOhr/lT@XOCAtlftKff3tTLdzhsUd2PykcRN3SZthmC4uGMEhj/LPuv/BgRRCKSR0DWuBYTEdjswcOrHrZ/1eD4zaLw "J โ€“ Try It Online") ### How it works We have the starting dice as the list `0 1 2 3 4 5`. Looking for the next top digit, we have either `1 2 3 4` as its index (`0` and `5` would be illegal moves). Taking the anagram indices `224 283 389 489` we permute the list, executing a dice move. We do this for the whole path and gather the intermediate results: `0 1 2 3 4 5โ”‚4 0 2 3 5 1โ”‚3 0 4 1 5 2`. Again, after looking for the indices, we map them to coordination changes `_1 0, 0 _1, 1 0, 0 1`, sum them up and check if they end up at `0 0`. There should be a byte saving by remapping the dice numbers 6 to 4, 5 to 3, โ€ฆ, 1 to 5 to save the two dummy zeros (`0,` and `0` ) by shifting the possible indices to `0 1 2 3`. But this feels so wrong that I'll try to think of another solution first. :-) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~55~~ 48 bytes ``` โ‰”324516ฮธ๏ผฆ๏ผณยซโ‰”โŒ•ฮธฮนฮน๏ผญโœณโŠ—ฮนโ‰”โญ†ยงโชชโ€)โŠŸ๏ผŸ2p}รžโ†”๏ฝž>โ€โถฮนยงฮธ๏ผฉฮบฮธยปยฌโˆจโ…ˆโ…‰ ``` [Try it online!](https://tio.run/##NY7NC4JAEMXP@leIp1kocL@8eJIi8NAHdKmjqdWS7Oq6RRD97duIBm8uM/N@71X30lambL3Ph0HdNMScCUnTeBH1JAuvxkZQ6O7pjs4qfQNCok8YzL8bpWvoF5Ei42RhsDWvBtbKNpVTRsPaPC9tU4MiZLzOrom0LTvIXaHr5g3HrlUOYkkFT1gimaBcUMlZkggmOcUuKZlS/g4MXZWDgweSp6bf8IBYBzvjYG/hBLg/Y11M9n4kSlSKEjJlfvlqfw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as a string of digits and outputs a Charcoal boolean, i.e. `-` for back at the origin, whitespace if not (+2 bytes to remove the whitespace). Explanation: ``` โ‰”324516ฮธ ``` The digits on the die, in the order right, up, left, down, top, bottom. ``` ๏ผฆ๏ผณยซ ``` Loop through the input digits. ``` โ‰”โŒ•ฮธฮนฮน ``` Find in which direction the die was rolled. ``` ๏ผญโœณโŠ—ฮน ``` Move in that direction. ``` โ‰”โญ†ยงโชชโ€)โŠŸ๏ผŸ2p}รžโ†”๏ฝž>โ€โถฮนยงฮธ๏ผฉฮบฮธยปยฌโˆจโ…ˆโ…‰ ``` Permute the digits to their new positions using a lookup table `514302` `052413` `415320` `042531` depending on the direction. ``` ยปยฌโˆจโ…ˆโ…‰ ``` Did we end up back at the origin? [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` a=b=1 t=0 for c in input():t=1+t*1j**(a*c*(a*a-c*c)*b**5%7*2/3+2*(a==c));a,b=b,c print t==0 ``` [Try it online!](https://tio.run/##bU9hC4IwFPzurxhCoM9FbXMGxvsl0QcdRkaYxKL69TZ72yoIRO/e@e7ujU97vAxyuh/7c8dE3T06k6bp1GCLIrG4Tg6XKzOsH9wz3myW1xZFYUGcALIGzPxqlgZMDi2AXmxArlQh3RjR5Pm24S223CTjtR8ss4jrafbfSc7EPtkp@mjOSoc4047IQKQjDnkelSqMHJgXo6DfWwRUkL09LSnaeFNFgSR9x6rgpIIcQfmzQPU0Bfi@MepzVhVDo16GbDrvc4g3@qoWJxX98ad8KOuN9y8 "Python 2 โ€“ Try It Online") The idea is to translate each triplet of consecutive die faces shown into the corresponding turn made by the die's path. The possible turn directions are left, right, straight, or reversing, all taken relative to the die's previous move. From the sequence of turns, we track the die's current coordinate and check whether it returns to the origin. Instead of tracking the die's facing direction, we simply rotate the whole coordinate system around it when it turns, and then move it. Doing it this way means we don't have to track the state of the die itself -- just looking at local snippets of the input sequence suffices. We also don't use any hardcoded values or magic numbers. The tricky bit is extracting the turn direction from the three consecutive die faces. You can think of these as a bug crawling on the from the first face to the second face, and then from the second face to the third face -- which direction does it need to turn on the second face to do this? We can detect that it doubles back if the first and third faces are equal, and that it goes straight forward when the first and third faces are opposite, so they add to 7. In the remaining cases, it remains to detect whether the bug turns left of right, that is the triple of faces is left-handed or right-handed. For this, we borrow an algebraic trick from [my CW solution to Determine dice value from side view](https://codegolf.stackexchange.com/a/44370/20260). The expression `3*a*c*(a*a-c*c)` will equal either `b` or `-b` modulo 7 depending on whether the triple is right-handed or left-handed. From there, some massaging takes the four cases of turn directions to numbers that equal `0,1,2,3` modulo 4, so that we can get the right complex rotation using the complex exponent `1j**`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 6RW;โธล“?@\แธŠแธขโ‚ฌโผ โ€œยงแนซยฒGโ€˜ร—J$แน—Lรงฦ‡:19แธขฤฑ*Sยฌ ``` A monadic Link accepting the dice-path as a list of the faces in \$[1,6]\$ which yields `1` (truthy) if it ends back at the start, or `0` (falsey) otherwise. **[Try it online!](https://tio.run/##AVAAr/9qZWxsef//NlJXO@KBuMWTP0Bc4biK4bii4oKs4oG8CuKAnMKn4bmrwrJH4oCYw5dKJOG5l0zDp8aHOjE54biixLEqU8Ks////NCwyLDQsMQ "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/98sKNz6UeOOo5PtHWIe7uh6uGPRo6Y1jxr3cD1qmHNo@cOdqw9tcn/UMOPwdC@Vhzun@xxefqzdytASqOzIRq3gQ2v@H24Hqv//PzraSMcwlksn2hhCmeqY6BjqmIKYRmCmEYhpogPmwETNdCAkUDFYCKLEFKIfqsUUrApuJlixjlksVywA "Jelly โ€“ Try It Online") (6 longest removed since the method is inefficient). ### How? Forms all the possible paths of the given dice-path's length formed from the four possible directions as the permutations-indices of the next state. Filters these to find the one that matches the face-up numbers in the given dice-path. Translates the permutation indices to the four Cartesian directions as complex numbers. Checks if the sum of these is zero. ``` โ€œยงแนซยฒGโ€˜ร—J$แน—Lรงฦ‡:19แธขฤฑ*Sยฌ - Main Link: dice-path โ€œยงแนซยฒGโ€˜ - list of code-page indices = [225,245,130,71] ร—J$ - multiply by their indices = [225,490,390,284] (these correspond to [up, down, right, left]) L - length (of the dice-path) แน— - Cartesian power (all lists of that length using {225,490,390,284}) ฦ‡ - filter keep those for which: รง - call Link 1 as a dyad - f(potential-path, dice-path) :19 - integer divide by 19 (225,490,390,284 -> 11,25,20,14) แธข - head (get the single path that filering found) (having แธข here rather than before the :19 saves a byte) ฤฑ* - i exponentiate (that) (11,25,20,14 -> -i,i,1,-1) (yep we've mirrored but it makes no difference) S - sum ยฌ - logical NOT 6RW;โธล“?@\แธŠแธขโ‚ฌโผ - Link 1: potential-path (as permutation indices), dice-path 6 - six R - range -> [1,2,3,4,5,6] W - wrap -> [[1,2,3,4,5,6]] ;โธ - concatenate with the permutation indices -> [[1,2,3,4,5,6],a,b,c,...] \ - cumulative reduce (current-state, permuation index) by: @ - with swapped arguments: ล“? - permuation (of the current state) at index (permutation index) แธŠ - dequeue (remove the leading [1,2,3,4,5,6]) แธขโ‚ฌ - head of each (get the list of face-up pips) โผ - equals (the dice-path)? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~96...74~~ 72 bytes ``` <<Quaternions` 0==Tr[a={-1,-K,J,-J,K,1};#&[t=a[[#]],a=++t**a**t/2]&/@#]& ``` [Try it online!](https://tio.run/##VU4xDoJAEOz5BgkFLlE4oNEz1thotLuQuDEaKcAEz4rg1/F2FzA2e7NzM7NTo33carTVFYdhszm@0d7apno2r4t31yutz61B3UUxRHsoICpgD3G/9gNjNRrjlyWgXixsGGIY2mVSBsudXwbDoa0aa/xoe6f1c7pi8@m8LnFm8DolTwYpxJARTBgmBFPgZWJzkOnEE5U5KU3F9BhFOkUqhxTFEvOLVuxSTMtMZ4nTyOFMosYikjk3zSV8@uHqQGXnbuwcTwvO5eOvE9dgf@/1wxc "Wolfram Language (Mathematica) โ€“ Try It Online") `Quaternions`` must be loaded prior to the function definition. ``` <<Quaternions` (* load the Quaternions` package *) a={-1,-K,J,-J,K,1}; (* (a die roll of i moves the die in direction a[[i]]) *) a=++t**a**t/2 (* rotate `a` in a direction *) #&[t=a[[#]], ]& (* and return the direction, *) % /@# (* taking directions one at a time from input. *) 0==Tr[ % ]& (* check if the sum of directions returns to the origin. *) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~174~~ \$\cdots\$ ~~130~~ 129 bytes Saved a whopping ~~15~~ ~~30~~ 35 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved another whopping ~~3~~ ~~9~~ 10 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` def f(l,p=[3,2,4,5,1,6],v=0): for d in l:n=p.index(d);v+=1j**n;p=[p[int(i)]for i in'%06d'%ord('๑ฝฃพ์ฒฝ๑ฅ™˜๊˜ฃ'[n])] return v==0 ``` [Try it online!](https://tio.run/##dVJBTsMwELznFXupbJcF1XESpFbmyAu4hRwQSURQ5UaOW4Gq/qOcKz7AvTwIcekLQuykErQmh9V6PLvemWz9ap4WSrRtXpRQ0jnWMhUYYoQxckwyXMkJmwZQLjTkUCmYT5WsryqVFy80Z7PVheTP47GadXV1WilDK5ZZctWRyWiS5GS00Dklh/3u8/tjf3h/235tdyRVGcsC0IVZagUrKSetKRrTgAQaQPdRGiJnCHd6WTAcIHEOxd2oHONTOHRweApHThr3sRPsY9fQd23tsFE4imcMWy9sdZcJO5JF/GMJ1004Sh@j/@gdcvswb34riM@weJB6itqRuAcfZGLirXF@onXqaIbntUFgnyce1h8bnNpkcP7IY4G2f5vcL8Pr6JEguIwLwgK7QAYLu29uK6auqV2OkhrmDrW2y1aStdnA5Q2smw2sddpIWWQbwtof "Python 3 โ€“ Try It Online") Returns `True` if we end up back at the origin or `False` otherwise. Port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [Charcoal answer](https://codegolf.stackexchange.com/a/211541/9481) using complex arithmetic to find out if we're back where we started. [Answer] # [R](https://www.r-project.org/), ~~143 ... 116~~ 102 bytes *Edits: -13 bytes by switching to linear instead of matrix list of transitions, then -4 bytes by halving the list of transitions & calculating the left, back & bottom die values as 7 minus the right, front & top values at each roll, then -3 bytes by switching to a base-7-encoded number to generate the list of transitions, then -14 bytes by rearranging the transition list to up, right, down, left to make calculating the new position easier using powers of i, and -6 bytes by various other minor golfs that didn't alter the approach* ``` p=a=1:4;m=5032105982%/%7^(11:0)%%7;for(i in scan()){p[6:4]=7-p;p=p[m[q<-(p[m[a]]==i)]];F=F+1i^a[q]};!F ``` [Try it online!](https://tio.run/##LcWxCsIwEADQ3a84h0CCFHNp2mjirfmJcIUgCBla0zqK3x5Rury3tVYpE3obZhp0b1AP14sRZ@Emiei1EsKFx3OTBcoCr3tepFLvmkZvmVxXQ6Wa5rTeOvk7MxMVxRwixROWKaeVP@EYmwELCD0Mu@Ou/WsO7Qs "R โ€“ Try It Online") **How?** (commented code before golfing) ``` is_dice_loop= function(s, # s = vector of top die values along path p=1:6, # p = positions of current die values # (top,front,right,left,back,bot) m=matrix( # m = matrix of transitions at each roll utf8ToInt( # created from ASCII values of "bedcfabbccafddfaafeeebcd") # this string -96, # -96, 4) # matrix has 4 rows. ){ for(i in s){ # Now, for each die value i along the path r=match(i,p[m[,1]]); # calculate the roll direction r # (1:4 -> up,down,right,left), p=p[m[r,]]; # then calculate the new positions of die values, F=F+(-.5+r%%2)*1i^(r>2) # and calculate the new location of the die # as a complex number (real=left->right, imaginary=down->up) # (F is initialized as 0+0i by default). } !F # If we end up back at 0+0i, then we've done a loop, } # so NOT F is true. ``` [Answer] # [Perl 5](https://www.perl.org/) `-pF`, ~~130~~, 121 bytes ``` @A=(2,4,-1,1,-@F,@F+!s/^/1/);s/.(?=.(.))/$x+=$A[$&==$1||$&+$1!=7&&($P[$|--]=$&)&&$1==$P[$|]?$A[$|]^=1:$A[$|]]/ge;$_=$x==1 ``` [Try it online!](https://tio.run/##LYxBa8MwDIXv/hcFYRLixJMtubAgml5y7r2kO5Ux6NbQ7JCBf/s8ZRs8xCfpvTdfHzcu718VrG441T1keerLcJQqOHItOnTtMLphbHaLv3j0db/4rjpIV3V17WFtBI5nsCKAOYNtAHeyt7aC0xly204CtrYWUA3bZTps9jxdBJ//aPKv1x5eBFYRLCWgiWiYkE0gDIZ0KiUVkwIjcUyslhQiU4qosFkjq5KKfg@G2LDmddnqNJyUtZbCVqQvDepMZP5LMOr7@z5/vt0/ltLe5vEH "Perl 5 โ€“ Try It Online") A different solution, the straightforward one was [173 bytes](https://tio.run/##RY3BCsIwEETv@Qshh0pTdZPdHCzFHkp/ohRPCoLaUj3UnzdOY1BYwuzOm8l4mq4Sbi89l6Fuqow2G78ut7rpqN8esrrpdoaMGO4r6KjMzug5z/v1fsE4YcmKWIoAK4qE2V@bheUiFlVsK6q6BZj9j6nnu@G7CJyHqW5LfaxWeg7BknKkhEmUZbKK8UJ5jDCEEIvzAsRbJ@wdQSyoE4zHcDwoFiXIY1nqEPbQqGW7FMFCEK9nlUrIwX4P4/My3B@huI7tBw "Perl 5 โ€“ Try It Online"), which could be golfed to [165 bytes](https://tio.run/##LU7RasMwEHv3XwxMm9Cm7tl3flgwzYPJTyxhDNqNQdaEdozs5@fJ3uCQddJJeLncJkkf33ptUxdDRYeDr1v9HLYm0mhOVTyS8Bgi8LjX62431o8mcrGyBitfwGqaYtm/lBUHC5hTTeh6mFXZcwJvLivy63zr@m17N9EMXXwyb6DDuTqF4VwbvdlDuHy9TPlTD3pNyZJypIRJlGWyioFgHiMMIsTivODEWyfsHYHkUycYj@EiKBYlyGPJdQh7cNSyzUWwEAR6Vv8l5GD/zMvn@3y9p2Za@l8 "Perl 5 โ€“ Try It Online"). EDIT : I realized after that the straightforward could be golfed to [136 bytes](https://tio.run/##LYzBCsJADETv@xdCD4pbNZtkDy3FHkp/QoonBaHaUj3Un3edWCFkZ@dlZrxMvab7O5vLVDfVmna7uCmh9nVzom5/tMerD579wYvP5u22KwzKAgW2QfUEmOcLDAsM3rKWY4NV3XYFbIZ9ABAkUWj2dZjqtszO1SqbUwrkmJwKqQtCwQk2VMSoQCiJclScxMAqkQnCTlkxESM/w4k6RR4fq0M4QqNWghUBIYgdxf1LiIE/w/i6DY9nyvux/QI) But to golf more I though differently. Using the fact that the sum of opposite side is 7. And that keeping a track of some previous number could be sufficent to get the directions. * array A : + `[0]`={2|3} and `[1]`={4|5} : to store the direction on (+/-)x or (+/-)y, where x and y depend on the firsts move's direction on these axes + the next `[2..5]` : to store numbers to add to `$x` corresponding to direction * `s/^/1/` : prepend `1` the initial face * regex `.(?=.(.))` : consumes one die face `$&` and capture the next next `$1` * `$&==$1` the direction is changing backward * `$&+$1==7` the direction doesn't change, the test is inverted because nothing to do * otherwise the direction has changed to rigth or left compared to the previous direction * array P : stores the last die face [0] x, [1] y, where x and y are depends on the firsts moves + `$P[$|--]=$&` : - `$P[$|]=$&` to store the die face when turning left or right - `$|--` switches axis index 0/1 for x/y * `$1==$P[$|]` the next next face is compared to the last when moving on the same axis if is equal the direction is changing backward compared to the previous direction * `^=1` : to switch using bytwise xor (2<->3) or (4<->5) * `$_=$x==1` : the initial position when `$x==1` because first move (direction 2 : -1) was not added. ]
[Question] [ Today's Google doodle is about [Celebrating 50 years of Kids Coding](https://www.google.com/doodles/celebrating-50-years-of-kids-coding): The goal is program the path of a little bunny so that it can eat all the carrots. There are 4 types of blocks (see pictures below): [![block description](https://i.stack.imgur.com/aIjhc.png)](https://i.stack.imgur.com/aIjhc.png) From left to right: * `O("...", k)` = orange piece: these are `for` loops which executes k times the program `"..."`. * `G` = green piece: go one step forward if you can, otherwise do nothing * `Bl` = blue piece: turn right and stay on the same block * `Br` = blue piece: turn left and stay on the same block [![big program](https://i.stack.imgur.com/WeKGs.png)](https://i.stack.imgur.com/WeKGs.png) The code above can be written as ``` O(O(G G Br, 4) Bl Bl, 23) ``` Each block (`G, Bl, Br, O(...,k)`) counts as 1 unit, so this program is of length 7. Note than the value of `k` is included inside the 1 unit of `O`. There are 6 levels. To finish a level you need to eat all the carrots. It is not a problem if your program is not fully executed, the level finishes directly when you eat the last carrot. We assume that all the 4 types of blocks are available in every level. > > **Your task is to find a single program which solves every level of the game. > > Shortest program in blocks wins.** > > > Screen shots of each level: Level 1: [![level 1 screenshot](https://i.stack.imgur.com/BCmoY.png)](https://i.stack.imgur.com/BCmoY.png) Level 2: [![level 2 screenshot](https://i.stack.imgur.com/8GqzY.png)](https://i.stack.imgur.com/8GqzY.png) Level 3: [![level 3 screenshot](https://i.stack.imgur.com/TX5Mt.png)](https://i.stack.imgur.com/TX5Mt.png) Level 4: [![level 4 screenshot](https://i.stack.imgur.com/J4NVl.png)](https://i.stack.imgur.com/J4NVl.png) Level 5: [![level 5 screenshot](https://i.stack.imgur.com/aSi1d.png)](https://i.stack.imgur.com/aSi1d.png) Level 6: [![level 6 screenshot](https://i.stack.imgur.com/ebjGV.png)](https://i.stack.imgur.com/ebjGV.png) [Answer] # Not my answer 6 blocks The user [Alex](https://codegolf.stackexchange.com/users/86858/alex) found a shorter solution, of length 6. I can confirm that their solution works: ``` O(O(Br G G, 6) Br, 5) ``` [![6 blocks](https://i.stack.imgur.com/YpoxP.png)](https://i.stack.imgur.com/YpoxP.png) They attempted to edit this question to add this answer, so I'm assuming they want it to be displayed here. I don't like how the reputation system works around here. The message they left: > > The editor doesn't have 10 rep, but does have a solution of length 6. O(O(RGG,6)R,5) > > > After a few days they responded again via editing the post with: *"Thanks for doing this. Editing this was the only way I saw to get a message. I am happy it exists at all. Feel free to bring it into a new post if you want though."* # Old answer 7 Blocks ``` O(O(G G Br, 4) G Br, 100) ``` Patience required. Edit: The image was wrong. [![7 blocks](https://i.stack.imgur.com/xvXFM.png)](https://i.stack.imgur.com/xvXFM.png) [Answer] Actually, I found a solution with 8 blocks ``` O(O(O(G,4)R,4)GGR,4) ``` [Answer] ## Manually found, 9 blocks `O(O(GRGLGR,4)L,4)` I started with the obvious `O(O(GGR,4)L,4)` that solves levels 1-5 then tried a few variations adding effectively-null moves on those levels to find one that would complete level 6. The shortest was a simple right-forward-left in the middle of each "bridge" so the forward move had no effect. ]
[Question] [ Write a program or function that draws a mountain range, where each subsequent larger mountain peak is "behind" the ones in front, and alternates which side is visible. This is a mountain range of size `1` ``` /\ ``` This is a mountain range of size `2` ``` /\ /\ \ ``` This is a mountain range of size `3` ``` /\ / /\ / /\ \ ``` This is a mountain range of size `4` ``` /\ /\ \ / /\ \ / /\ \ \ ``` This is a mountain range of size `5` ``` /\ / /\ / /\ \ / / /\ \ / / /\ \ \ ``` And so on. ### Input A single positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `n > 0`. ### Output An ASCII-art representation of the mountain range, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the peaks line up appropriately. ### Rules * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] ## [Charcoal](http://github.com/somebody1234/Charcoal), 16 bytes ``` ๏ผฎฮป๏ผฆฮปยซ๏ผฐโ†˜โปฮปฮนโ†โ†™ยนโ€–๏ผดโ†’ ``` [Try it online!](http://charcoal.tryitonline.net/#code=77yuzrvvvKbOu8Kr77yw4oaY4oG7zrvOueKGkOKGmcK54oCW77y04oaS&input=NQ) ### How? `๏ผฎฮป` inputs the size of the largest mountain into `ฮป`. `๏ผฆฮปยซ` runs a loop over values of `ฮน` from `0` through `ฮป-1`. (The closing `ยป` is implied at the end of the program.) Inside the loop, `๏ผฐโ†˜โปฮปฮน` calculates `ฮป-ฮน` and draws, without moving the cursor afterward, a line of that length going southeast. Based on its direction, this line will consist of `\` characters. `โ†` moves one step to the west, and `โ†™ยน` draws a line of length 1 going southwest (made of `/`). Finally, `โ€–๏ผดโ†’` horizontally reflects the drawing, transforming characters as appropriate: `\` becomes `/` and `/` becomes `\`. Adding the dump instruction `๏ผค` at the beginning of the loop ([try it](http://charcoal.tryitonline.net/#code=77yuzrvvvKbOu8Kr77yk77yw4oaY4oG7zrvOueKGkOKGmcK54oCW77y04oaS&input=NQ)) allows us to see the progression: ``` /\ / / / / /\ /\ \ / \ / \ / \ /\ / /\ / /\ \ / / \ / / \ /\ /\ \ / /\ \ / /\ \ \ / / \ \ /\ / /\ / /\ \ / / /\ \ / / /\ \ \ ``` [Answer] # JavaScript (ES6), 75 bytes ``` for(n=prompt(s="/\\");n--;s=n%2?s+' \\':'/ '+s)console.log(" ".repeat(n)+s) ``` The full program is currently slightly shorter than the recursive function: ``` f=n=>n?" ".repeat(--n)+`/\\ `+f(n).replace(/\S.+/g,x=>n%2?x+" \\":"/ "+x):"" ``` [Answer] ## Python 2, 67 bytes ``` n=input() s='/\\' while n:n-=1;print' '*n+s;s=['/ '+s,s+' \\'][n%2] ``` Prints line by line, accumulating the string `s` by alternately adding a slash to the left or right based on the current parity of `n`. Prefixes with `n` spaces. An alternative way to update was the same length: ``` s=n%2*'/ '+s+~n%2*' \\' s=['/ '+s,s+' \\'][n%2] ``` A recursive method was longer (70 bytes). ``` f=lambda n,s='/\\':n*'_'and' '*~-n+s+'\n'+f(n-1,[s+' \\','/ '+s][n%2]) ``` [Answer] ## Haskell, 77 bytes ``` 0%_="" n%s=(' '<$[2..n])++s++'\n':(n-1)%(cycle[s++" \\","/ "++s]!!n) (%"/\\") ``` Usage: ``` putStrLn $ f 5 /\ / /\ / /\ \ / / /\ \ / / /\ \ \ ``` Prints line by line, accumulating the string s by alternately adding a slash to the left or right based on the current parity of n. Prefixes with n-1 spaces. [Answer] ## Batch, 202 bytes ``` @echo off set/af=%1^&1 set m=/\ set s= for /l %%i in (2,1,%1)do call set s= %%s%% for /l %%i in (2,1,%1)do call:l :l echo %s%%m% set s=%s:~1% set/af^^=1 if %f%==1 (set m=%m% \)else set m=/ %m% ``` Takes input as a command-line parameter. Falls through to execute the last loop. [Answer] # Ruby, 61 bytes A pretty straightforward port of [ETHproductions' JavaScript answer](https://codegolf.stackexchange.com/a/98595/11261). ``` ->n{s="/\\" (puts" "*n+s s=n%2>0?s+" \\":"/ "+s)until 0>n-=1} ``` See it on repl.it: <https://repl.it/EPU5/1> ## Ungolfed ``` ->n{ s = "/\\" ( puts " "*n+s s = n%2 > 0 ? s+" \\" : "/ "+s ) until 0 > n -= 1 } ``` [Answer] # Haskell, ~~117 107 105 97~~ 90 bytes ``` b!1=["/\\"] b!n|m<-(1-b)!(n-1)=map(' ':)m++[[("/ "++),(++" \\")]!!b$last m] (unlines.(1!)) ``` [Try it on Ideone.](http://ideone.com/oGrdB4) Edit: Saved 8 bytes with an idea from Neil. Ungolfed version: ``` p b 1 = ["/\\"] p b n = let m = p (1-b) (n-1) k = last m r = map (' ':) m in if b == 1 then r ++ [k ++ " \\"] else r ++ ["/ " ++ k] f n = unlines(p 1 n) ``` Recursive approach. The shape for `n` is generated by adding a space in front of each line of the `n-1` shape and taking the last line of `n-1` and add `"/ "` before if `n` is odd or `" \"` after if `n` is even ... or so I thought before noticing that this last step is reversed for all recursive steps when the final `n` is odd. Therefore a flag `b` is passed which alternates each recursive call and determines if the next mountain part is added left or right. [Answer] # Java 7,130 bytes ``` String f(int n,String s){String l="";for(int i=1;i++<n;l+=" ");return n>1?n%2<1?l+s+"\n"+f(--n,s+" \\"):l+s+"\n"+f(--n,"/ "+s):s;} ``` # Ungolfed ``` class Mountain { public static void main(String[] args) { System.out.println(f( 5 , "/\\" ) ); } static String f(int n,String s){ String l = ""; for (int i = 1; i++ < n; l += " ") ; return n > 1? n % 2 < 1?l + s + "\n" + f(--n , s + " \\") :l + s + "\n" + f(--n , "/ " + s) :s; } } ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ๏ผจ๏ผผโ•‘๏ฝŽโ†”๏ฝโ†• ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjNDJXUyNTUxJXVGRjRFJXUyMTk0JXVGRjVEJXUyMTk1,i=NQ__,v=8) I guess Canvas is now the ideal language for this challenge. [Answer] # C++ 138(function) Function :- ``` #define c(X) cout<<X; #define L(X,Y) for(X=0;X<Y;X++) void M(int h){int l=1,r=1,j,H=h,i;L(i,h){for(j=H;j>0;j--)c(" ")L(j,l)c(" /")L(j, r)c("\\ ")c("\ n")(h%2)?(i%2)?r++:l++:(i%2)?l++:r++;H--;} ``` Full program :- ``` #include<conio.h> #include<iostream> using namespace std; #define c(X) cout<<X; #define L(X,Y) for(X=0;X<Y;X++) void M(int h) { int l=1,r=1,j,H=h,i; L(i, h) { for (j = H;j > 0;j--) c(" ") L(j, l) c(" /") L(j, r) c("\\ ") c("\n") (h % 2) ? (i % 2) ? r++ : l++ :(i % 2) ? l++ : r++; H--; } } int main() { int h; cin >> h; M(h); _getch(); return 0; } ``` **NOTE :** the function `_getch()` may have different prototype names across different compilers. ]
[Question] [ [We're getting markdown tables!](https://meta.stackexchange.com/questions/356997/feature-preview-table-support?cb=1) I assume this is what they look like: ``` data data data data --------------------- | | | | | | | | ``` Your task is to make a program or function to generate one of these tables. You'll be given input (string, list of lines, list of characters, etc.) containing data, which looks like this: ``` datadata data data data data data data ``` The data consists of spaces and non-overlapping `data`s. The data will not necessarily form neat stacks (it can float in midair). There is guaranteed to be data on the top and bottom lines, as well as some touching the left side. You can choose if the data is right padded with spaces or not. The table will always be six characters wider than the data, padded three spaces on the left. The table top is directly below the bottom row of data, and is made up of a line of `-`s. As for the legs, everyone knows taller tables can support more weight, so they'll need to be one unit tall for every `data` in the input. They will be made up of `|`s, one space in from the sides. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins! ## Test cases Input: ``` data ``` Output: ``` data ---------- | | ``` Input: ``` data data data data data data ``` Output: ``` data data data data data data --------------------- | | | | | | | | | | | | ``` Input: ``` data data ``` Output: ``` data data ---------- | | | | ``` [Answer] # [Perl 5](https://www.perl.org/) `-lpF`, ~~88~~ ~~74~~ 66 bytes *Because we're allowed to require the input to be padded on the right side, @DomHastings was able to shave 8 bytes off my method while eliminating the need for `List::Util`.* ``` END{printf'-'x(@F+6)." |%@{[@F+3]}s"x$q,("|")x$q}s// /;$q+=y;d; ``` [Try it online!](https://tio.run/##K0gtyjH9/9/Vz6W6oCgzryRNXVe9QsPBTdtMU0@JS6FG1aE6Gsgzjq0tVqpQKdTRUKpR0gQyaov19RUUFPStVQq1bSutU6z//09JLEkEYQVkwKWADSBEkTVwoXKhslxgMYgEQvpffkFJZn5e8X9dX5/M4hIrq9CSzBzb3MQKoICpnoGhwX/dghw3AA "Perl 5 โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~30~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ยฌg6+ยฉ'-ร—ยชรฐยฎร—'|1ยฎรโ€šวIJ'dยขะธยซ.c ``` -1 byte thanks to *@ovs*. Input as a list of lines, right-padded with spaces to an equal length. [Try it online](https://tio.run/##yy9OTMpM/f//0Jp0M@1DK9V1D08/tOrwhkPrDk9XrzEEUr2PGmYdn@vppZ5yaNGFHYdW6yX//x@tlJJYkgjCCshASUdBSQEbQJFA1gaRQDMIxAVJgIUhcggVSrEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@P7Qm3Uz70Ep13cPTD606vOHQusPT1WsMgVTvo4ZZx@dWeqmnHFp0Yceh1XrJ/3UObbP/Hx2tpKCQkliSqAADSjpKYD5EEEQqxeooRIMFURRCFCsoKWADKBLI2iASaAaBbQFKoFkM1RGrA7EdzlBAEEDXKqAKIZTrKCH5Ryk2FgA). **Explanation:** ``` ยฌ # Get the first line of the (implicit) input-list (without popping) g # Pop and push its length 6+ # Add 6 ยฉ # Store this value in variable `ยฎ` (without popping) '-ร— '# Pop and create a string of that many "-" ยช # Append it to the list of lines รฐยฎร— # Create a string consisting of `ยฎ` amount of spaces 1 # Push 1 ยฎร # Push value `ยฎ` and decrease it by 2 โ€š # Pair them together: [1,ยฎ-2] '| ว '# Insert a "|" at those (0-based) indices in the spaces-string IJ # Push the input-list, and join it to a single string 'dยข '# Count the amount of "d"s in it ะธ # Repeat the legs-string that many times as list ยซ # And merge the two lists together .c # And finally centralize this list, which adds leading spaces where # necessary, and implicitly joins the list by newlines # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~60 57 56 55~~ 41 bytes ``` {3โŒฝโ†‘(โ†“'-'โชโจ' 'โˆ˜,โฃ6โŠขโต),โ†“(+/โˆŠ'd'โทโต)6โด' | '} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9r4Uc/eR20TNR61TVbXVX/Uu@pR7wp1BfVHHTN0HvUuNnvUtehR71ZNHaC0hrb@o44u9RSgou0gMbNHvVvUFWoU1Gv/pz1qm/Cot@9RV/Oj3jVA4UPrjYFmPuqbGhzkDCRDPDyD/6cpGCqYgLSkJJYkqnMBhYGa1NW50hSASsGCCnAC6AAFNBFsGoDKgAjMAgA "APL (Dyalog Unicode) โ€“ Try It Online") Input as a character matrix. -1 byte from ovs. -14 bytes, following xash's answer. ## Explanation(old) ``` {โ†‘(' 'โˆ˜,ยจโ†“โต),(โŠ‚a/'-'),(+/โˆŠ'd'โทโต)/โŠ‚2โŒฝ'| |'โ†‘โจaโ†6+โŠƒโŒฝโดโต} '| |' a set of table legs โ†‘โจ pad to length aโ†6+โŠƒโŒฝโดโต 6 + row size aโ† store in var a โŠ‚2โŒฝ rotate 2 steps and wrap ( )/ replicate that by: 'd'โทโต boolean matrix of occurrences of 'data' +/โˆŠ sum all the occurrences , concatenate with (โŠ‚a/'-') '-' repeated a times (' 'โˆ˜,ยจโ†“โต), and the input padded with 3 spaces on the left โ†‘ convert to matrix(join with newlines) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~30~~ ~~28~~ 27 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Hmm ... thought this would work out much shorter. Takes input as an array of lines, right-padded with spaces and outputs an array of lines. ``` cUยฌรจd รด@S+i|i|รบUรŽรŠ+3รƒvรˆรง- รป ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1Ws6GQg9EBTK2l8aXz6Vc7KKzPDdsjnLQr7&footer=VnFS&input=WyJkYXRhICAgICAgICAgICAiLCJkYXRhIGRhdGEgIGRhdGEiXQ) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1Ws6GQg9EBTK2l8aXz6Vc7KKzPDdsjnLQr7&footer=UrJpVrc&input=WwpbImRhdGEgICAgICAgICAgICIsImRhdGEgZGF0YSAgZGF0YSJdClsiZGF0YWRhdGEgICAgICAgICAgICAgIiwiICAgICAgICAgICAgICAgICAgICAgIiwiICAgICAgICAgZGF0YSAgICAgICAgIiwiICBkYXRhICAgICAgICAgICBkYXRhIiwiZGF0YSBkYXRhICBkYXRhICAgICAgIl0KWyJkYXRhIl0KWyJkYXRhIGRhdGEgZGF0YSAiLCIgZGF0YSBkYXRhIGRhdGEiXQpbImRhdGEiLCIgICAgIiwiZGF0YSJdCl0tbVI) ``` cUยฌรจd รด@S+i|i|รบUรŽรŠ+3รƒvรˆรง-\nรป :Implicit input of array U c :Concatenate Uยฌ : Join U รจd : Count the "d"s รด : Range [0,count] @ : Map S : Space + : Append i : A space prepended with |i : A "|" prepended with |รบ : A "|" right padded with spaces to length UรŽรŠ+3 : Length of first element of U plus 3 รƒ :End map v :Modify first element รˆ :By passing it through the following function รง- : Fill with "-" \n :Reassign to U (saves a byte over having to close all the nested methods) รป :Centre pad each element with spaces to the length of the longest ``` [Answer] # [J](http://jsoftware.com/), 41 bytes ``` 0 3|.(' | '$~6,~1#.'d'=,),~'-',~' '&,.^:6 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRSMa/Q01BVqFNRV6sx06gyV9dRT1G11NHXq1HXVgYSCupqOXpyV2X9NLq7U5Ix8BQ3rNE2FaGu9eCMFDbBZmlwKCimJJYlcIALMgvLx6IDJ41ehACe4FND4mgS0ckGt@A8A "J โ€“ Try It Online") ### How it works * `' '&,.^:6` prepend a space to each row 6 times. * `'-',~` append a new row filled with `-`. * `1#.'d'=,` count the `d`s in the input. * `' | '$~6,~` shape `|` into dimensions `count 6`, so `count` rows of `| |` * `,~` append the leg rows to the tables, filling possible empty space on the right with . * `0 3|.` shift every row 3 characters to the left. Or in pictures: ``` data data data ---------- data ---------- | | data ----------- | | ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), ~~112~~ ~~98~~ ~~77~~ 74 bytes *Saved 6 bytes using* `String#count` *method, thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)!* *Saved 3 bytes using literal newline, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!* ``` ->m{m.map{" "*3+_1}<<?-*(6+c=m[0].size)+" | #{" "*c} |"*(m*"").count(?d)} ``` [Try it online!](https://tio.run/##dY69DoIwFIX3PsXNcYHyExMTJ5AHAQYESRyKhJZBKc9eA0isBE9yp@/83K6/Pk0dm@AiBhGKoh201CDwkyfHKEoC7py9MhbpMQ/l/XVzPTDSdBgmTzmSBncEB9ywfPSNcpLKHU3bK0l1mqIqVIE89wlZkzVgbCVsRtORLfgMtKcfYMcWsCmaZ/1l48O@DrD9hzYtO/l/yXXOjtle8wY "Ruby โ€“ Try It Online") * TIO uses an older version of Ruby, while in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~113~~ ~~107~~ 95 bytes Saved ~~6~~ a whopping 18 bytes thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)!!! ``` lambda l:[' '+a for a in l]+[(r:=6+len(l[0]))*'-']+''.join(l).count('d')*[' |'+(r-4)*' '+'|'] ``` [Try it online!](https://tio.run/##3VTBToQwEL3zFZNepl3KRqNRQ8LRHzDekENduorBQko3UcO/IwWEssDRmDgJBN6bN9OZtlN@mtdCXd2VujlGT00u3p9TAXkYIwCgL@BYaBCQKcgTP6Y6jG78XCqaxxcJYzsMMPER929F1mJsfyhOylBMke3aCDX6VAfXrVsbCmtMGiMrU0XUi0kqjLAPuEY4EFizGeHKeuIskP21RAf33ORBeMKH/GT8gulFOIE5NLlZrgsxypknP0p5MDK1VeGQfFEYckDYsHPOFY/cSoUDt1qk5YJt66T1xnrqf8h2O@icjKkVdksHXU1cN2f/@11fgKutdeK5K/gLeF40GW@Mg2304awnzLNTwHBp58BXVtLuGnP4Ofos9KxvqbP28pPHljyISoaEdfA4QUzYe4ge19GRGuYqH6Q5aSXThVLPlRbPOlyoF0ntPDJ2Hvk3bHCsjKYZi4PLhEuVRohunlnO@6GGRU75azkxwp0T4Jax5hs "Python 3.8 (pre-release) โ€“ Try It Online") Inputs a list of right-space-padded strings and returns a list of strings. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` แปดโถx3ยค;แน„ฦŠโ‚ฌแบˆแน€+ยฉ3โ€-xแน„แน›ฤ‹โ€dยฎeยฎโ€™,2ยคยฅรพแป‹โพ| Y ``` [Try it online!](https://tio.run/##y0rNyan8///h7i2PGrdVGB9aYv1wZ8uxrkdNax7u6ni4s0H70ErjRw1zdSuAwg93zj7SDeSkHFqXemjdo4aZOkaHlhxaenjfw93djxr31ShE/v//PyWxJBGEFZABlwI2gBBF1sCFyoXKcoHFIBIIaQA "Jelly โ€“ Try It Online") Takes input as a single string. This is disgustingly hacked together, but Jelly's never been particularly good at strings. ## How it works ``` แปดโถx3ยค;แน„ฦŠโ‚ฌแบˆแน€+ยฉ3โ€-xแน„แน›ฤ‹โ€dยฎeยฎโ€™,2ยคยฅรพแป‹โพ| Y - Main link. Takes s on the left แปด - Split into a list of lines ฦŠโ‚ฌ - Over each line l: ยค - Group together as a nilad: โถ - " " x3 - [" ", " ", " "] ; - Prepend to l แน„ - Print แบˆ - Get the lengths of each line แน€ - Take the maximum + 3 - Add 3 ยฉ - Save it to the register, r โ€- - "-" x - Repeat that many times แน„ - Print แน› - Discard everything and use s ฤ‹โ€d - Count occurrences of "d", d ยฎ - Yield the register, r ยฅรพ - Create an dร—r grid and to each cell (i, j): ยค - Group into a nilad: ยฎ - r โ€™ - r-1 2 - 2 , - [r-1, 2] e - Is i in [r-1, 2]? แป‹โพ| - Index each cell into "| " Y - Join by newlines ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 25 bytes ``` ๏ผท๏ผณโŠžฯ…ฮนโ†‘โ„–ฮฃฯ…d๏ผญโ†ยณ๏ผฌฮธโ†๏ผฆฯ…โ†‘โ€–๏ผฏ๏ผฏ๏ผฌฮธฯ… ``` [Try it online!](https://tio.run/##bYxNDoIwEIX3PcWEVZvgyh0sXZlgJBIO0EChJJXWOq3Hr1UIP9FJJjPzvTevkdw2mqsQXnJQAuh5NA4rtMPYU8agdE9JXQoDy0kZIdKsNimctItr5e7UsRSSNmFRv2gvaFaIDhfzcdkKMfYo6ePH2GkLMQUmWJuIbqJTosGrF1ZxM49dwpTpWB5Cy5F/GrZF4F@tdPtA9ueski@bhFUm4eDVGw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes newline-terminated rectangular input. Explanation: ``` ๏ผท๏ผณโŠžฯ…ฮน ``` Input the data. ``` โ†‘โ„–ฮฃฯ…d๏ผญโ†ยณ ``` Print the left leg and the `---` at the top of the left leg. ``` ๏ผฌฮธ ``` Print the middle part of the table. ``` โ†๏ผฆฯ…โ†‘ ``` Move the cursor to the top right of the data. The following reflection will then move it to the top left. (Moving here avoids confusion between the use of the arrows as movement and as modifiers for reflection or printing direction.) ``` โ€–๏ผฏ๏ผฏ๏ผฌฮธ ``` Reflect to complete the right of the table. ``` ฯ… ``` Print the data. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~204~~ ~~194~~ ~~187~~ ~~181~~ 174 bytes *174-byte solution thanks to @ceilingcat.* ``` z,s,i;main(c,v)char**v;{for(;++z<c;)printf(" %s\n",v[z]);for(;c--;)for(s=0;z=v[c][s++];)i+=z=='d';for(;z++<strlen(v[1])+6;putchar(45));for(;i--;)printf("\n |%*c",z-4,'|');} ``` [Try it online!](https://tio.run/##VY3LCsIwFER/JRRKk94EFKqb23xJ20W4tRrQWJqaRazfHqkPxM0wDIczpI5EKUXppcWLsY6TDIJOZirLgPfhOnEEiDWhGCfr5oFnjLHcty6ToYmdwBdCSqFYm9cbjDo01DUeoENhQUeti754gxGg9vN0Pjgemm0nYI/jbV7/eLUTH5tdbd@71rElLymTUVWyWAqBj5RSb2bDfpHY//AE "C (gcc) โ€“ Try It Online") Takes each line of input as a right-padded command line argument. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes ``` \`.+ $& L$`d $%= T`p`- *\0G` T`-` %,T1,,-2` `| ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyZBT5tLQUFBRQ1IcPmoJKRwqajacoUkFCTocmnFGLgnANm6CQpcqjohhjo6ukYJCgk1//@nJJYkgrACMuBSwAYQosgauFC5UFkusBhEAiENAA "Retina โ€“ Try It Online") Takes rectangular input. Explanation: ``` \`.+ $& ``` Pad the input by 3 spaces on each side and print the result. ``` L$`d $%= ``` Repeat each line by the count of its `d`s. ``` T`p`- ``` Change all the characters to `-`s. ``` *\0G` ``` Print the first line. ``` T`-` ``` Change all the characters to spaces. ``` %,T1,,-2` `| ``` Change the (0-indexed) second and second last characters to `|`s and implicitly print the resulting legs. [Answer] # JavaScript (ES6), ~~105~~ 103 bytes Expects a single string with right-padded lines. ``` s=>s[R='replace'](/^|t/g,c=>o+=` `+(p=c?' | ':'---')+q[R](/./g,p[0])+p,o=s[R](/.+/g,s=>' '+(q=s)))&&o ``` [Try it online!](https://tio.run/##jYxBCoMwEEX3OcXgwkmI0a4LsXdwqxZD1NIiSTTSlXdPU1oqhS46i4F58/6/qbvyerm6VRjbD2GUwcvS15XEZXCT0gO2tDhva3HJtCwtlx3pOHVSnxA2wCMKIZDxua6il0fL1YeWcZdZ6V@MRxg7EQCQ01l6xlia2qCt8XYa8sle6EgJQNKrVSWEAQdsDDJCfiuwr8YkwJ8cvh9/tOzROJ/jHWbhAQ "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` s => // s = input string s[R = 'replace']( // replace in s: /^|t/g, // match the beginning of the string // and each 't' (of 'data') c => // for each matching character c: o += // append to o: `\n` + ( // a line-feed p = // followed by p defined as: c ? // if c is not empty: ' | ' // ' | ' : // else: '---' // '---' ) // + q[R](/./g, // followed by each character in q ... p[0]) // ... replaced with the 1st character of p + p, // followed by p o = // initialize the output string o: s[R]( // replace in s: /.+/g, s => // each line s ' ' // with 3 leading spaces + (q = s) // followed by s, which is copied in q ) // end of replace() ) && o // end of replace(); return o ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes ``` แปดโถx3ยค;โฑฎยฉแบˆแน€+3ยตโถแบ‹โ€|2,-ยฆWแบ‹ยณฤ‹โ€dยค;@โ€-xWฦŠยฎ;Y ``` [Try it online!](https://tio.run/##y0rNyan8///h7i2PGrdVGB9aYv1o47pDKx/u6ni4s0Hb@NBWoPDDXd2PGubWGOnoHloWDuQc2nwEJJACVOwApHUrwo91HVpnHfn///@UxJJEEObiUoABMBdCKSigioLFIBIgEgA "Jelly โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-pl055F`, 53 bytes A different approach to [@Xcali's answer](https://codegolf.stackexchange.com/a/215961/9365). Requires lines to be padded with spaces. ``` $;+=y/d//;say" $_"}{$\=$\x(6+($#x=@F))." | @x |"x$ ``` [Try it online!](https://tio.run/##K0gtyjH9/1/FWtu2Uj9FX9@6OLFSSUFBQSVeqbZaJcZWJaZCw0xbQ0W5wtbBTVNTT4lLoUbBoUKhRqlC5f//lMSSRBBWQAZcCtgAQhRZAxcqFyrLBRaDSCCk/@UXlGTm5xX/1y3IMTA1dfuv62uqZ2igZwAA "Perl 5 โ€“ Try It Online") ## Explanation Firstly, `-l055` sets `$\` to `'-'`, `-p` implicitly wraps wraps the code in `while(<STDIN>){...;print;}` and `-F` splits each line of input into chars in `@F`. In the code, due to the implicit code added by `-p`, for each line of text increment `$;` with the number of `d` in the code then `say` the line with three leading spaces. The `}{` breaks out of the implicit `while` and `$\` is then set to `$\` repeated 6+`@F` (whilst also setting `$#x` to `@F`'s scalar value) times concatenated with a string consisting of: a leading newline, space, pipe (`|`), space, `@x` interpolated, space, pipe, which itself it repeated `$;` times. `@F`, when used in a scalar context like this, returns the number of elements in `@F` - which is the number of chars in the line, since each line is space-padded this works fine. `$#x` is a 'magic' variable which contains the last index of `@x` and means that `@x` now contains `@F`+1 empty values. When an array is interpolated into a double-quoted string, its values are printed out with a space between each, so an empty array with `@F`+1 elements interpolated, results in a string consisting of `@F` spaces. This code ends with just `$` because of the `-p`-added code which contains `;` saving another byte. [Answer] # [Pip](https://github.com/dloscutoff/pip), 36 bytes ``` P'-M@P*gWRsX3LXW*4N JgPsX#a+2WR'|WRs ``` Takes lines of input as command-line arguments; or, with the -r flag, as lines of stdin. Lines must be padded with spaces to the same length. [Try it online!](https://tio.run/##K8gs@P8/QF3X1yFAKz08qDjC2CciXMvET8ErPaA4QjlR2yg8SL0GKPH/f0piSSIIKyADLgVsACGKrIELlQuV5QKLQSQQ0v91iwA "Pip โ€“ Try It Online") ### Explanation Let's break this into two halves: the data + tabletop, and the legs. ``` P'-M@P*gWRsX3 g List of input lines WR Wrap each line in sX3 Three spaces P* Print each line @ Take the first one '-M List containing one hyphen for each character in that line P Print (concatenated together by default) LXW*4N JgPsX#a+2WR'|WRs Jg Join the lines of input into one string N Count occurrences in that string of XW Regex matching [a-zA-Z0-9] *4 repeated 4 times L Loop that many times: a First line of input # Length +2 Plus 2 sX String of that many spaces WR'| Wrap in pipe characters WRs Wrap in spaces P Print ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ao`, 34 bytes ``` ฦ›3Ipโ€ฆL;G:3+\-*,โ€นโ€›ฦ›โ†“โ–กโ‹แบŽL$Iโ€› |pโ€›| +* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJhbyIsIiIsIsabM0lw4oCmTDtHOjMrXFwtKizigLnigJvGm+KGk+KWoeKBi+G6jkwkSeKAmyB8cOKAm3xcbisqIiwiIiwiZGF0YVxuICAgZGF0YSJd) Probably not optimal, but beats Jelly :P `a` flag is for multiline input; `o` forces implicit output even though there are print statements in the code. ``` ฦ›3Ipโ€ฆL;G:3+\-*,โ€นโ€›ฦ›โ†“โ–กโ‹แบŽL$Iโ€› |pโ€›| +* # Full program ฦ› ; # For each line in input (`a` flag): 3Ip # Prepend 3 spaces โ€ฆ # Print ^ L # and return its length G: # Take the maximum length from ^ and duplicate 3+ # Add 3 to one copy \-*, # Print that many `-`s โ€น # Decrement the other maximum length copy for later โ–กโ‹ # From inputs... แบŽL # ...find the number of โ€›ฦ›โ†“ # ...`data`s (dictionary-compressed) $ # Swap number of "data"s for (maximum length - 1) I # Push that many spaces โ€› |p # Prepend " |" to ^ โ€›|\n+ # Append "|\n" to ^ (\n is an actual newline) * # Repeat as many times as the number of datas to make the legs # `o` flag - implicitly output the legs of the table ``` ]
[Question] [ Tonight, 31 January 2020, Brexit will happen and the United Kingdom will leave the European Union, the first time that the number of EU member states will decrease. Your job is to take a date and output the number of EU1 members on that date, according to the following table: ``` | Start | End | Number of members | 0 | 1957-12-31 | 0 | 1958-01-01 | 1972-12-31 | 6 | 1973-01-01 | 1980-12-31 | 9 | 1981-01-01 | 1985-12-31 | 10 | 1986-01-01 | 1994-12-31 | 12 | 1995-01-01 | 2004-04-30 | 15 | 2004-05-01 | 2006-12-31 | 25 | 2007-01-01 | 2013-06-30 | 27 | 2013-07-01 | 2020-01-31 | 28 | 2020-02-01 | Inf | 27 ``` Input may take one of the following forms: * your language's date format * any ordering of integers for year, month and day with any separator (e.g. YYYYMMDD or DD/MM/YYYY) * number of days lapsed since some epoch. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! 1. or [EEC](https://en.wikipedia.org/wiki/European_Economic_Community) before 1993 [Answer] # Javascript, ~~85~~ 83 Bytes ``` a=d=>d<0?0:d<180?6:d<276?9:d<336?10:d<444?12:d<556?15:d<588?25:d<666?27:d<745?28:27 ``` It takes an input as a float as the *months / fractions of months passed* since `1958-01-01` (`0` for `1958-01-01T00:00:00` and a negative number for any previous date) (Since number of days from some epoch is allowed, I assume that also a number of months is valid, as well) [Try it Online](https://tio.run/##bcvBDoIwDMbxu08CB8lW2m4SZp9lYWA0hBExvv7sjkZP3z@/po/4jsf0vO@v85bTXJZQYkjhmkYjZkij9UZYFxzLRbfvWWw9IKJY0CBSoRreC9RgZgGn4ZAE/ACuTHk78jp3a741S0NgOt@2p2/Vtx9ziH@M1Er5AA) --- # 80 Bytes (credits: [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)) ``` a=d=>d<0?0:d<180?6:d<276?9:d<336?10:d<444?12:d<556?15:d<588?25:27+(d>=666&d<745) ``` --- Sad to see you go, UK [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ ~~27~~ ~~26~~ ~~25~~ 33 bytes ``` ยฌยฎ12ล’โ‰คโ‰ˆฮฉโ€šร‡ร–b-โ€šร„รฒยฌยฅ`<lpโ€šร‡ยจยฌโˆโ€šร„รฒโˆšรก.ยฌโ€ข@โ€šร„ยขยฌรธโ€šร„รบ0pโ€šร„ยข12โ€“โ‰ค<*O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0ApDo3Obju591NSapPuoYcahLQk2OQWPmtYc2gHkHW7XO7TU4VHDokP7HzXMMSgAsgyNLmyy0fL//z/a0NLUUkfBwBCEYwE "05AB1E โ€šร„รฌ Try It Online") Input is in the form `[yyyy, mm, dd]`. [Answer] # [Python 2](https://docs.python.org/2/), ~~110~~ 97 bytes ``` lambda d:ord('069:<?IKLK'[sum(d>i for i in(0,5479,8401,10227,13514,16922,17897,20270,22676))])-48 ``` [Try it online!](https://tio.run/##VZGxboMwEIZ3P8VJHbAjO7IPjAGVdmiWKNnaLc1AS1CRQkCEDnl6ahOSuJIX3/fd79O5uww/7QnHKv8cj0XzVRZQZm1f0kDGafb8ut5sN8Hu/NvQ8qWGqu2hhvpEJdeRSXkSScWVRDRchVpFXMUpIlcmSQ1HiUZyxNjEjO2ZiJJxu37/yHckUKmUQip7Ag72po1QKEJ3ewLpuE58btDjseMm9HkiPZ46nqh/XHtcTQ8ksS@kkS@gE1L9EFDKSNgTyqugyVzSDyH2EvAqGD9B2YnjWwIaMpfMXcBpJbeEhMwlvAt6mkHqAK4Je1L1bQNlMRyGujlA3XRtP8CCuG8q7TeB23dGrC0EvBXHb@tezjB1uaXbMoFVfgugi6boaH0aeLk8d8d6oIEIGGPk2pYDXYm76/q5Qh4qxpaOz88Q6HobAaulUynjQWanr6hT2PgH "Python 2 โ€šร„รฌ Try It Online") -13 bytes, thanks to Jonathan Allan Takes input as number of days since `1957-12-31` (so `1958-01-01` is day `1`) --- # [Python 3](https://docs.python.org/3/), 93 bytes ``` lambda d:b'069:<?IKLK'[sum(d>i for i in(0,5479,8401,10227,13514,16922,17897,20270,22676))]-48 ``` [Try it online!](https://tio.run/##VZGxbsMgEIZ3ngKpg6GCCM4GjFW3Q7NEydZuaQanjlVLcWw57pCnd8FxEiqxcN93P6ejuww/7Skeq/xrPBbNvixwme0joW328rZab9bR9vzbkPK1xlXb4xrXJyKYSoxlaSIkkwLAMBkrmTCpLQCTJrWGgQAjGIA2mtIdT9Jxs/r4zLcoklYILqQ7EcPupgyXwGN/e8LCc5WG3EDAtecmDnkqAm49T@U/rgIupwdSHQo2CQXwglUPAYRIuDuxuAoKzSX1EHSQAFfBhAnSTaxvCWDQXDJ3AaaV3BJSNJfgLqhpBqEifE3YoapvG1wWw2GomwOum67tB/yM/C@V7pew33eGnM05fi@O3869nPHU5Zfuyggv81sAeW6KjtSngZWLc3esBxLxiFKKrm05Jkt@d30/k8BiSenC8/kZhLveRTh34V1CWZS58SviHUrHPw "Python 3 โ€šร„รฌ Try It Online") -4 bytes, thanks to mypetlion [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~42~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โ€šร„ยขAโˆšร‡ย รญโˆšยด.โ‰ˆยฐยฌยฐล’ยต%โ‰ˆรฆยฌโˆ‘7โˆšโ‰ โ€šร„ยขโ‰ˆฮฉL}โ€“โ‰ค.ยฌโ€ขโ€šร„โˆซOโ€šร„ยข=ล’โ‰ฅ1sโˆšยถล’รฎโ€šร„ยขโ€šร‡รœโ€“โ‰คsโˆšยฎ< ``` Input as number of days since 1957-12-31 (so 1957-12-30 is day `-1`; 1957-12-31 is day `0`; 1958-01-01 is day `1`; etc.) [Try it online](https://tio.run/##yy9OTMpM/f//UcMix8NNpyYdXq13dOGhhee2qh7dd2i7@eG1QImje31qL2zSO7T0UcMufyDf9txmw@LDy85NAbIfNbVd2FR8eIXN//@GxqaGJgA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw2LHA83nZp0eLXe0YWHFp7bqnp036Ht5ofXAiWO7vWpvbBJ79DSRw27/IF823ObDYsPLzs3Bch@1NR2YVPx4RU2/3X@R@sa6hjoGOqYmphbAgkLAx0LEwNDEGGkY2hgZGQOJi10DI1NDU3ApKmOoZmlkRGYNNYxNLewNAeTFjpGBkbmBmDSUMfIyMzcDEya6xgZGxgYxAIA). **Old 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer taking input in the format `yyyyMMdd`:** ``` ยฌยฎยฌยฎโ€šร„ยขa3|}\ยฌรŸล’ยชโ€šร„รดIโ‰ˆรฌgยฌฮฉโˆšรฆโ€šร„ยขโ‰ˆฮฉOล’ยฉโ€“โ‰คโ€šร„ยข32โˆšรฒโ€šร„ยข+@Oโ€šร„ยข=ล’โ‰ฅ1sโˆšยถล’รฎโ€šร„ยขโ€šร‡รœโ€“โ‰คsโˆšยฎ< ``` [Try it online](https://tio.run/##yy9OTMpM/f//0IpDKx41LEo0rqmNObT83O5HDTM9j05OP7T38D6g8NG9/udWXtgEZBkbHZ4BpLQd/IGk7bnNhsWHl52bAmQ/amq7sKn48Aqb//8NLS1NDI2MDQE) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/QysOrXjUsCjRuKY25tDyc7sfNcz0PDo5/dDew/uAwkf3@p9beWETkGVsdHgGkNJ28AeStuc2GxYfXnZuCpD9qKntwqbiwyts/uv8jzY0AAJDA0MdQ0tTc0MjYzDDAipibgQVMTeGigBlICIWhjARU5iIGVTE0gQqYmkKFjEyMDAxMDE2gDBMISJmYDVAhjlUjaGxgRlYDZBhDhYBShoaQxlGIBFDiFNjAQ). `โ€šร„ยขa3|}\ยฌรŸล’ยชโ€šร„รดIโ‰ˆรฌgยฌฮฉโˆšรฆโ€šร„ยขโ‰ˆฮฉOล’ยฉโ€“โ‰คโ€šร„ยข32โˆšรฒโ€šร„ยข+` can alternatively be `โ€šร„ยขMe1ล’ยตโˆšยง~.=ล’รฎล’ยฉยฌยชโ€šร„ยขโ‰ˆฮฉ5โˆšยฃโ€“โ‰ค.ยฌโ€ขโ€šร„ยข32โˆšรดโ€šร„ยข+` for the same byte-count: [Try it online](https://tio.run/##yy9OTMpM/f//0IpDKx41LPJNNTy39fCSOj3bc1POrTy0Gyh0dK/p4cUXNukdWgrkGBsdngmktB38gaTtuc2GxYeXnZsCZD9qaruwqfjwCpv//w0tLU0MjYwNAQ) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/QysOrXjUsMg31fDc1sNL6vRsz005t/LQbqDQ0b2mhxdf2KR3aCmQY2x0eCaQ0nbwB5K25zYbFh9edm4KkP2oqe3CpuLDK2z@6/yPNjQAAkMDQx1DS1NzQyNjMMMCKmJuBBUxN4aKAGUgIhaGMBFTmIgZVMTSBCpiaQoWMTIwMDEwMTaAMEwhImZgNUCGOVSNobGBGVgNkGEOFgFKGhpDGUYgEUOIU2MB). **Explanation:** ``` โ€šร„ยขAโˆšร‡ย รญโˆšยด.โ‰ˆยฐยฌยฐล’ยต%โ‰ˆรฆยฌโˆ‘7โˆšโ‰ โ€šร„ยข # Push compressed integer 813218926689775697373196902446 โ‰ˆฮฉL} # Push compressed integer 5480 โ€“โ‰ค # Convert the larger integer to base-5480 as list: # [5479,2922,1826,3287,3408,975,2373,2406] .ยฌโ€ข # Undelta it with leading 0: # [0,5479,8401,10227,13514,16922,17897,20270,22676] โ€šร„โˆซ # Check for each if it's larger than the (implicit) input-integer O # Take the sum to get the amount of truthy values โ€šร„ยข=ล’โ‰ฅ1sโˆšยถล’รฎโ€šร„ยข # Push compressed integer 122116126451824 โ€šร‡รœโ€“โ‰ค # Convert it to base-36 as list: # [1,7,10,11,13,16,26,28,29,28] sโˆšยฎ # Swap to get the sum, and use it to index into this list < # And decrease it by 1 # (since a compressed integer/list cannot contain a leading 0) # (after which the result is output implicitly) ยฌยฎยฌยฎ # Remove the last two digits from the (implicit) input (the "dd") โ€šร„ยขa3|}\ยฌรŸล’ยชโ€šร„รดIโ‰ˆรฌgยฌฮฉโˆšรฆโ€šร„ยข # Push compressed integer 2722385715080006519908031109868 โ‰ˆฮฉOล’ยฉ # Push compressed integer 6203 โ€“โ‰ค # Convert the larger integer to base-6203 as list: # [1,1501,2301,2801,3701,4605,4901,5507,6202] โ€šร„ยข32โˆšรฒโ€šร„ยข # Push compressed integer 195800 + # Add it to each value in the list: # [195801,197301,198101,198601,199501,200405,200701,201307,202002] @ # Check for each if it's larger than or equal to the input minus "dd" Oโ€šร„ยข=ล’โ‰ฅ1sโˆšยถล’รฎโ€šร„ยขโ€šร‡รœโ€“โ‰คsโˆšยฎ< # Same as above ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression works. [Answer] # [Turing Machine Code](http://morphett.info/turing/turing.html), ~~972~~ 1009 bytes My input is the date in the format specified in the test cases `YYYY-MM-DD`. ``` 0 0 0 * halt * 1 _ r โ€šร‡ยจ โ€šร‡ยจ 9 _ r % * 2 _ r $ $ 0 _ r ยฌยฃ * I 2 r ยฌยข % 5 _ r ^ % 6 6 r c % 7 _ r x % 8 _ r B % 9 _ r i % * _ r c ^ * 0 r c ^ 8 6 r c ^ 9 6 r c B 0 9 r c B 1 1 r r B 2 1 r r B 3 1 r r B 4 1 r r B 5 1 r r B * 1 r e r * 0 r c e * 2 r c x 0 6 r c x 1 6 r c x 2 6 r c x * 9 r c i 0 1 r ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ i 1 1 r ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ i 2 1 r ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ i 3 1 r ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ i 4 1 r ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ i * 1 r t t * 5 r c ๏ฃฟรผรกโ„ข๏ฃฟรผรกโˆซ * 2 r c ยฌยฃ 0 _ r ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ ยฌยฃ 1 _ r โ€šรฒร– ยฌยฃ 2 _ r ๏ฃฟรผรซรซ ๏ฃฟรผรซรซ 0 _ r ! ๏ฃฟรผรซรซ * 2 r ยฌยข ! - _ r ~ ~ 0 _ r 1 1 1 2 r โ€šรฒรœ 1 * 2 r ยฌยข โ€šรฒร– 0 2 r ยฌยข โ€šรฒร– 1 2 r ยฌยข โ€šรฒร– 2 2 r ยฌยข โ€šรฒร– 3 _ r & โ€šรฒร– * 2 r โ€šรฒรœ & - _ r @ @ 0 _ r 6 6 0 2 r ยฌยข 6 1 2 r ยฌยข 6 2 2 r ยฌยข 6 3 2 r ยฌยข 6 4 2 r ยฌยข 6 5 2 r ยฌยข 6 6 2 r ยฌยข 6 * 2 r โ€šรฒรœ โ€šรฒรœ * 8 r c ๏ฃฟรผรกโˆซ๏ฃฟรผรกโˆž * 5 r c ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 1 1 r ๏ฃฟรผรกโˆซ๏ฃฟรผรกโˆž ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 2 1 r ๏ฃฟรผรกโˆซ๏ฃฟรผรกโˆž ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 3 1 r ๏ฃฟรผรกโˆซ๏ฃฟรผรกโˆž ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 4 _ r + ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 5 2 r t ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ 6 2 r t ๏ฃฟรผรกยจ๏ฃฟรผรกรŸ * 2 r ยฌยข ยฌยข * 7 r c + - _ r ยฌยจ ยฌยจ 0 _ r 4 ยฌยจ * 2 r t 4 0 1 r t 4 1 1 r t 4 2 1 r t 4 3 1 r t 4 4 1 r t 4 * 2 r t 6 _ 6 l c c * _ r c c _ _ * halt ``` [Try it online!](http://morphett.info/turing/turing.html?ede7a51c0dff0419b383aae1fb089ce0) *Added a few bytes thanks to [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy) being a bit more thorough in testing my code than I was.* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` ร”ยบยฉโ€šรฅรฏล’โ‰ฅยฌรŸ &)*,/9;<;ร”ยบยจล’ยถโ€šโ„ขโ„ขโ€šร„รน)ยฌโˆ‚โ€šรœโˆ‚โ€šรฅรฏล’โ‰คล’โ‰ฅโ€šยถร‘Jโ€šรขยถล“ร‰ล’ฮฉ{:Xล’ยฅpโ€šร…ยฅEโ€šรครดโ€šรขรฏโ€šรงรฒร”ยบยฎโ€šรครดล’โ‰คgโ€šร„รนโ€šร…โˆ‚โ€šร„ฯ€ล’ฯ€ล’โˆ ``` [Try it online!](https://tio.run/##JYxBCsIwFET3niJ0IT8S8Se1TUPciCAILgRPUNrSBkKqTRBvHxM7i8cMPKab2qWbWxvjYzEuwKX1Aa7G9TAycg431w9fKMiW7thB6ZMuGLkPbgxTkmwYFni@rAlQcFU1yLmSZWbD/6wzVYVcIB6xSpS58xKlwLREeqtpfvQeDCNvukZvYlwFFHH/sT8 "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Takes input as YYYYMMDD. Explanation: ``` โ€šร„รน...โ€šร„รน Compressed string of YYYYMM values โ€šโ„ขโ„ข โ€šร…โˆ‚ Split into substrings of length 6 ร”ยบยจล’ยถ โ€šร„ฯ€ล’ฯ€ล’โˆ Count those that appear before the input ยฌรŸ &)*,/9;<; Look the count up in a translation table ร”ยบยฉโ€šรฅรฏล’โ‰ฅ Subtract 32 from the ASCII code ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~158~~ 150 bytes ``` i=int(input()[:6]);print((((((((27,28)[202002>i>201306],25)[i<200701],15)[i<200405],12)[i<199501],10)[i<198601],9)[i<198101],6)[i<197301],0)[i<195801] ``` [Try it online!](https://tio.run/##NY@7DoMwDEV3vgKxQCoG2yGvtvAjiIkiNQugikrt16dOSDOdc@1EN/v3eG4rhXl7LGVf1nUdfO/Xo/Hr/j4aMV71JG77K0b5kGnJipGAAGjwAwFK0FNLSoz@zqEBnFr8WweKjaKhcyrN4DSro7ksGEWfYmSUvKYsS@BqxfJZ5iZWFReEUPGIkK9VBaPuGFVCo8GiSWj5obzgOiQZkUtBThkVEHYJEUCSPVGDA0oYf8m7Pw "Python 2 โ€šร„รฌ Try It Online") Takes input as a string in `YYYYMMDD` format Alternative Python 2 approach without imports. Simply uses nested list indexing to create the equivalent of a big `if/elif` structure. **NB:** Posted by a British guy who is sorry to see us leave. I'm still all for the Community and working together (whether EU or here). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 37 bytes ``` โ€šร„รบโ€šร‡ยจโ€ฆรฌโ€šร…ยฅ5O/ยทฯ€รฑยทฯ€โ„ขOยทฯ€ร…ยทฯ€โ„ขยทโˆรฃgโ€šร„รดยทโˆร‰โ€šร…ฮฉโˆšรณยทยชยตโˆšร‘โ‰ˆยช>โ€šร…โˆSยทยชรฃโ€šร„รบโˆšโˆ‘โˆšยฑฦ’ยฑโˆšรชโ€šร‡ยจยฌฮฉยฌยตยฌยฉยฌยฐโˆšยฑโ€šร„รฒ ``` [Try it online!](https://tio.run/##FYwxCsIwFEAv9MHkt2nSxSt08AwiSC/g1qjg0EUQtIKLo@JSsNhSuuTr4DHyLxLr9Jb33nKe56sQuLjw@vE9sH2qbOK7o@/ume/sCN@WCy7Ovt2wHejk@4a2n37Ktp35vhxDelH9rmk/DtzgGndzV6q5qALtQkBMdBIkqNgIMLFAkALRgIyUVCCTFCOQ2qQGUKCW8Pf1Dw "Jelly โ€šร„รฌ Try It Online") A monadic link taking the zero-indexed count of days since 1958-01-01 as a integer argument and returning an integer. Thanks to @JonathanAllan for saving a byte! [Answer] # AWK, 98 bytes ``` {m=$1*12+$2-23496}1,$0=m<1?0:m<181?6:m<277?9:m<337?10:m<445?12:m<557?15:m<589?25:27+(m>666&&m<746) ``` [Try it online!](https://tio.run/##RZDBDsIgDIbvPgWHZVGnCS20pcsmz@LZ7OzB@OzYbchIQ798/EmB5/tVymeZO7gCDh3eMUTlL9w6Py8TZD/aniCzdRTJaj0EybAexEgZ0IDIDK2QNCONKMN5eTBz3y@TRL6U4m05D1YnUBIH6MKGqVnBZiU0m3yzCQ5Lh@VmNTarVC16H51V8BWpWq5ZQ2lZsMG8Z1eU3eJ29fBHrNNUjxntddsHVv4B "AWK โ€šร„รฌ Try It Online") Input format: `YYYY MM DD` [Answer] # JavaScript (ES6), 95 bytes Expects a number of days since `1957-12-31`. ``` n=>[x=0,5479,2922,1826,3287,3408,975,2373,2406].map((d,i)=>x-=(n-=d)>0&&~('52012910'[i]||~1))|x ``` [Try it online!](https://tio.run/##ZYyxbsMgFEX3fAVTAAnSxwMMDHjqX0QZrEAqRymOaqv1YOXXXTlDItnSW@65575r89v055/2PsjSpTxf4lxifRwjCGtcEBgQhfJYCY3eCW3Ai@CsQO20QAPV6fDd3BlLouWxHmVkRcbEa9jvH4xaBIVBAT22p2l6KM6ncR5yP5BIEok1OXel7275cOu@2IWxkv/IZzNkljiR5JWoCtZJhVIryjn5IL4y2XK@2y2/lhqUfB7lL/RevJHfWA43ltMrCwGMBLtCbmMhLEivET6t@R8 "JavaScript (Node.js) โ€šร„รฌ Try It Online") This is however a bit longer than [@FabrizioCalderan's answer](https://codegolf.stackexchange.com/a/198700/58563), even if it is [fixed to use days](https://tio.run/##ZYzBbsMgDEDv/QpugQOb7QAGtNDLfiRq6LSqIlMTdZf9exZ6aKVEsvTkxzOX/t5Pp9v3z6zLOOTl3C2lSyXBsSRrOKzwBnAFAhFXthZNpQtElewDH8lrWT4IiPGvJCLHTkWyEdehiBBDdBGWOU@z6MQguiROY5nGa367jl/yLGXJv@Kzn7MclNDiuTUYLGsk3WKjlHgX3plslToc6l/1GVA/plFP9bp4Kb@rmHYVt5uKAIwGu1G8qwiqareKHtXyDw) instead of months. [Answer] # x86 (32-bit) assembly, 43 bytes (13 bytes code + 30 bytes data) This routine expects input in `ax` as a signed short giving number of days since 1950-01-01, and returns output in `al` (clobbering `edi` along the way). ``` .text .globl eu_members eu_members: mov $.Ltbl-1, %edi .Lloop: inc %edi scas (%edi), %ax jg .Lloop mov (%edi), %al ret .section .rodata .Ltbl: .short 2921 .byte 0 .short 8400 .byte 6 .short 11322 .byte 9 .short 13148 .byte 10 .short 16435 .byte 12 .short 19843 .byte 15 .short 20818 .byte 25 .short 23191 .byte 27 .short 25597 .byte 28 .short 32767 .byte 27 ``` Exact opcodes of the code part (in a linked context so that the relocation of .Ltbl doesn't confuse things): ``` 0804930b <eu_members>: 804930b: bf 49 a0 04 08 mov $0x804a049,%edi 8049310: 47 inc %edi 8049311: 66 af scas %es:(%edi),%ax 8049313: 7f fb jg 8049310 <eu_members+0x5> 8049315: 8a 07 mov (%edi),%al 8049317: c3 ret ``` And here's the test harness I used (note that the assembly code is not PIC safe, so on Debian or Ubuntu systems you will need to pass `-no-pie` to gcc): ``` #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> unsigned char eu_members_wrap(short days_since_1950_01_01) { unsigned char res; __asm__("call eu_members" : "=a"(res) : "0"(days_since_1950_01_01) : "edi", "cc"); return res; } int main(int argc, char* argv[]) { struct tm tm; time_t epoch, req; short days_since_epoch; memset(&tm, 0, sizeof(tm)); tm.tm_year = 50; tm.tm_mon = 0; tm.tm_mday = 1; epoch = mktime(&tm); memset(&tm, 0, sizeof(tm)); tm.tm_year = atoi(argv[1]) - 1900; tm.tm_mon = atoi(argv[2]) - 1; tm.tm_mday = atoi(argv[3]); req = mktime(&tm); days_since_epoch = (((unsigned int) (req - epoch)) / (24 * 60 * 60)); /* printf("epoch = %ld, req = %ld\n", epoch, req); printf("Raw number of days: %hd\n", days_since_epoch); */ printf("EU members: %hhu\n", eu_members_wrap(days_since_epoch)); return 0; } ``` [Answer] # [Perl 5](https://www.perl.org/), 46 bytes ``` ($q,%d)=split;$q--while!exists$d{$q};say$d{$q} ``` [Try it online!](https://tio.run/##PcprCsIwEATgq0SIoGDK7tY0CcUjeAihAQOlrwRUxKsbtynI/vlmZie/9Drng5xP@@54iVMfUitnpR730Pudf4aYouzecv608fbalDM6UwMCCuBDp20Jjfj3jmmxENcP22wmttObtSCAM3ASVGxKT4aN9ZoEWTYvVPrvOKUwDjGr4aorhAp@ "Perl 5 โ€šร„รฌ Try It Online") ...or try like this on some decent command line: ``` query=19730101 data="0 0 19580101 6 19730101 9 19810101 10 19860101 12 19950101 15 20040501 25 20070101 27 20130701 28 20200201 27" echo "$query $data" | perl -nE '($q,%d)=split;$q--while!exists$d{$q};say$d{$q}' ``` ]
[Question] [ Your task is to model the effects of batter on pieces of food. Please add three layers of crust. ``` [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0], // in [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0], [0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] | V [[0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,1,2], [0,0,2,1,2,2,0,0,0,0,0,0,0,2,2,0,2,0], [0,0,2,1,1,1,2,0,0,0,0,0,2,1,1,2,0,0], [0,0,0,2,1,2,0,0,0,0,0,2,1,1,2,1,2,0], [0,0,0,0,2,0,0,0,0,0,0,0,2,1,1,1,2,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0]] | V [[0,0,3,2,3,3,0,0,0,0,0,0,0,3,3,2,1,2], [0,3,2,1,2,2,3,0,0,0,0,0,3,2,2,3,2,3], [0,3,2,1,1,1,2,3,0,0,0,3,2,1,1,2,3,0], [0,0,3,2,1,2,3,0,0,0,3,2,1,1,2,1,2,3], [0,0,0,3,2,3,0,0,0,0,0,3,2,1,1,1,2,3], [0,0,0,0,3,0,0,0,0,0,0,0,3,2,2,2,3,0]] | V [[0,4,3,2,3,3,4,0,0,0,0,0,4,3,3,2,1,2], // out [4,3,2,1,2,2,3,4,0,0,0,4,3,2,2,3,2,3], [4,3,2,1,1,1,2,3,4,0,4,3,2,1,1,2,3,4], [0,4,3,2,1,2,3,4,0,4,3,2,1,1,2,1,2,3], [0,0,4,3,2,3,4,0,0,0,4,3,2,1,1,1,2,3], [0,0,0,4,3,4,0,0,0,0,0,4,3,2,2,2,3,4]] ``` A little visual aid: ``` body { background-color:#222; color:lightgray; } ``` ``` <pre> [[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>], // in [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>]] | V [[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>]] | V [[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], [<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>]] | V [[<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], // out [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>], [<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>]] </pre> ``` The input is a boolean matrix representing the fryer: 0 for the oil, 1 for the food. Your function or program should add the three layers as 2s, 3s, and 4s around the 1s, thus overwriting some of the 0s. Batter sticks horizontally and vertically (but not diagonally) to food of any shape or size, including donuts (food with holes) and crumbles (isolated food "pixels"), and is restricted to the boundaries of the fryer. Earlier layers of batter turn into crust and are not affected by later ones. In other words, first you should replace all 0s that are in the von-Neumann neighbourhoods of 1s with 2s, then replace all 0s in the von-Neumann neighbourhoods of 2s with 3s, and finally replace all 0s in the von-Neumann neighbourhoods of 3s with 4s. Thus, the numbers 2,3,4 represent a quantity one greater than the Manhattan distance to the nearest 1-cell. The fryer will be of size at least 3-by-3 and it will contain at least one piece of food. I/O is flexible - use a matrix format suitable for your language. Extra whitespace is allowed, shorter code desirable, loopholes forbidden. More tests: ``` [[0,0,1], // in [0,0,0], [0,1,0]] [[3,2,1], // out [3,2,2], [2,1,2]] - [[0,0,0,0,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], // in [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0], [0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [0,0,1,0,1,1,1,1,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,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,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]] [[3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,3,3,4,3,3,3,4,4,4,3,2,1], // out [2,3,4,0,0,0,0,0,0,0,0,0,0,0,0,4,3,2,2,3,2,2,2,3,3,4,4,3,2], [1,2,3,4,0,0,0,0,0,0,0,0,0,0,4,3,2,1,1,2,1,1,1,2,2,3,4,4,3], [1,1,2,3,4,4,4,4,0,0,0,0,0,4,3,2,1,1,1,1,1,1,1,1,1,2,3,4,4], [2,2,3,4,4,3,3,3,4,0,0,0,4,3,2,1,1,2,1,1,1,1,1,2,2,1,2,3,4], [3,3,4,4,3,2,2,2,3,4,0,0,4,3,2,1,2,2,1,1,2,2,1,2,3,2,3,4,4], [4,4,4,3,2,1,1,1,2,3,4,0,4,3,2,1,1,2,1,2,3,3,2,2,2,3,4,3,3], [0,4,3,2,1,1,2,1,2,3,4,0,0,4,3,2,2,2,1,2,3,3,2,1,1,2,3,2,2], [4,3,2,1,1,2,2,1,2,3,4,0,0,0,4,3,3,3,2,3,4,4,3,2,2,3,2,1,1], [3,2,1,2,1,1,1,1,2,3,4,0,0,0,0,4,4,3,3,3,4,3,3,3,3,3,2,1,2], [4,3,2,1,2,2,1,2,3,4,0,0,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3], [0,4,3,2,1,1,2,3,2,3,4,0,0,0,4,3,2,1,1,1,2,1,1,2,3,4,4,3,4], [0,0,4,3,2,2,3,2,1,2,3,4,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3], [0,0,0,4,3,3,4,3,2,3,4,0,0,0,0,0,4,3,3,3,4,3,3,4,4,3,2,1,2], ``` A little visual aid: ``` body { background-color: #222; color:lightgray; } ``` ``` <pre>[[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>], // in [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>]] [[<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>], // out [<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>], [<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>]] - [[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>], // in [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>]] [[<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>], // out [<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>], [<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>], [<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>], [<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>], [<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>], [<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>], [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>], [<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>], [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], </pre> ``` --- Thanks @Tschallacka for the visualizations. [Answer] # Java 8, ~~271~~ ~~269~~ ~~247~~ ~~210~~ ~~202~~ ~~198~~ ~~193~~ ~~186~~ ~~179~~ ~~177~~ 176 bytes ``` a->{for(int l=a[0].length,i,t,I,J,n=0;++n<4;)for(i=a.length*l;i-->0;)for(t=4;a[I=i/l][J=i%l]==n&t-->0;)try{a[I-=t-t%3*t>>1][J-=t<2?1-2*t:0]-=a[I][J]<1?~n:0;}finally{continue;}} ``` Java and index-dependent matrices.. Not a good combination for an already verbose language to begin with.. Modifies the input-matrix instead of returning a new one. -8 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##tVdbb5swFH7fr3CROiWNodyeQklVTZuUSuvD@hjx4CVuR@c6GZiuEaJ/PTPggLmYXKSJlmBz/J3vfD4@Ni/oDenrDaYvq9@7JUFxDL6jkKafAAgpw9ETWmLwkDcBeFuHK7Ac8f5FsAgAGnu8O@P//C9miIVL8AAo8MEO6bP0aR3lpoD4aGEGBsH0mf2CIWRwDu8h9U1vMqE3rjcuDH0kLK6IF@r6zCz7me96aDH3w2sSLO798JIEvk8/s9KCRduUv9V9prNL54rNZha34s0b@9bS7Ss2NQOdu5/z3uDGuv2gU9PLnkKKCNmmyzVlIU2wl2U7r4xik/wkPAoRTBHvK1dj9MiikD4XMZdSMByzEcV/gRAjBdfXYE43CZsW7wFITWhCK4Ny05SbFm8WLdHZRvv6vsFLhlcgwnFCalwH2jJu3rTrJn/HmyXu2Mt/TuF7ztWO8ZyrhrAO@8uVK@6WCsI6CNC8OhDHM9gPt06FqIFMVSBtyv0sBuU8wljqHdCil@qwRk0IWbJjIXpYnMJhUAt1Zpjq1FJLdzKLExfZ2cXCHcR1oQMdcc9/3eK5UWBsOARSmtviblcwjlyULKgGEf7ysiX0t4U1f9Nc1HZF0e0FaF7CWg6kwhU0VQz2LASIXGyr6CqaMoRdAe0Hd1hIGks02yxKIWsnjqxFn7HbmA0ZwqqY2DILp0PVbeSEI6m1n2CrvfHIkjWnWJbZqa5yd@qw6HJoBuPIOZE/qbRwOoHUMssZ1JjUdhpbPSAHWTQXU18otRZ1AvyfnVpZOI8sTurdRlFPlRvTMWWv8nZSjTyrGprV5PRNz0BydtOhlQCHVnQr4dxWonXWc192qhK7Nw9VC8mtMq5zdi@Ou0X67U/4eQPulQVYqPqjEFUchKmxHOVmBR4A5UEZMBj5mgYxv5X94mNgEbxPC@tUMH7cxgy/GuuEGRs@khHKj/wv/JvESFhIjLsoQtvYYOsSd/Q@NiK8IfybZKQBDWraWPgFIJr4rHzO2h5bxMUAPDnK0R0he18ixC7lyMB/EkTiER7fal/WUcTdXWhT7RsKCV5dDIwU05Dt/gE) **Explanation:** ``` a->{ // Method with integer-matrix parameter and no return-type for(int l=a[0].length, // Amount of columns i,t,I,J, // Temp integers n=0;++n<4;) // Loop `n` in range [1, 4): for(i=a.length*l;i-->0;) // Inner loop over the cells: for(t=4;a[I=i/l][J=i%l] // Set I,J to the current cell ==n& // If the value of the current cell is the current `n`: t-->0;) // Loop `t` downwards in the range (4, 0]: try{a // Get the cell at a location relative to the current [I-=t-t%3*t>>1] // If `t` is 3: // Take the cell above // Else if `t` is 2: // Take the cell below [J-=t<2?1-2*t:0] // Else if `t` is 0: // Take the cell left // Else if `t` is 1: // Take the cell right -=a[I][J]<1? // And if this cell contains a 0: ~n:0; // Fill it with `n+1` }finally{continue;} // catch and ignore ArrayIndexOutOfBoundsExceptions // (saves bytes in comparison to manual checking) ``` [Answer] # [Stencil](https://github.com/abrudz/Stencil): 1 + 14 = 15 bytes Command-line argument: `3` Code: `s<ร—โŒˆ/N:1+โŒˆ/Nโ‹„S` [Try it online!](https://tio.run/##jVBLCsIwEN17iuxMUWgmrbURz@DGI4iLgqjQ7sSVUkStCCJewqWewJvkIMb82qauSiCZeXkz896k2Xw5SxZCpOPPg58P/mQEPf3y034qxIby4w7zy53n1y7Pb13PJrx41@HT20YIYl68MEQ@8frQx6F9YagCHPggb4gURyOAQP@XCSJIsQc1W3botJ4foEC2JqoLIvZA@3IIEWVKG42tbspKA1GlsLRRIvJT28TMuGMOc6AgYl2ZpkaUFahgcFbzt4ewmZLGVlFzb4bCGoCSELqqqlrLp44JR4cWWM2XRWbOd7XOktUyFcEP "Stencil โ€“ Try It Online") `3`โ€ƒrepeat the following transformation thrice: โ€ƒ`s`โ€ƒif whether the **s**elf is non-empty โ€ƒ`<`โ€ƒis less than โ€ƒ`ร—`โ€ƒthe signum of โ€ƒ`โŒˆ/N`โ€ƒthe maximum of the von neuman**N** neighborhood โ€ƒ`:`โ€ƒthen the new value becomes โ€ƒโ€ƒ`1+`โ€ƒone plus โ€ƒโ€ƒ`โŒˆ/N`โ€ƒthe maximum of the von neuman**N** neighborhood โ€ƒ`โ‹„`โ€ƒelse โ€ƒโ€ƒ`S`โ€ƒthe value stays unmodified (**S**elf) [Answer] # [Stencil](https://github.com/abrudz/Stencil) *+CLA: `3`*, 11 bytes ``` s:Sโ‹„+โˆ˜ร—โจโŒˆ/N ``` [Try it online!](https://tio.run/##Ky5JzUvOzPn/v9gq@FF3i/ajjhmHpz/qXfGop0Pf7///R20TNQwUyIOGmmRrNdDUMCRsvoIhlDRE12pIUCMqhGsl3kaYNkNitSIMMEB3MLrTsNuKNZiIUIQkisWvWJ2EPwwgWpGDglitSLaSYidWv@KOWQPMJIE7SIi2lcTED9T6L7@gJDM/r/i/MQA "Stencil โ€“ Try It Online") -1 thanks to [Adรกm](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m). -2 thanks to a suggestion on another answer by [ngn](https://codegolf.stackexchange.com/users/24908/ngn), which led me to convert this from **Stencil** to **Stencil *+CLA: `3`***. [Answer] # JavaScript (ES6), ~~107~~ 105 bytes ``` f=(m,k=1)=>k<4?f(m.map((r,y)=>r.map((v,x)=>v|[-1,0,1,2].every(d=>(m[y+d%2]||0)[x+~-d%2]^k)?v:k+1)),k+1):m ``` ### Test cases ``` f=(m,k=1)=>k<4?f(m.map((r,y)=>r.map((v,x)=>v|[-1,0,1,2].every(d=>(m[y+d%2]||0)[x+~-d%2]^k)?v:k+1)),k+1):m draw = a => O.innerText += a.map(r => r.join(',')).join('\n')+'\n\n' draw(f( [[0,0,1], [0,0,0], [0,1,0]] )) draw(f( [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0], [0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [0,0,1,0,1,1,1,1,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,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,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]] )) ``` ``` <pre id=O></pre> ``` ### Commented ``` f = (m, k = 1) => // given the input matrix m[] and starting with k = 1 k < 4 ? // if this is not the 4th iteration: f( // do a recursive call: m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each cell v at position x in r[]: v | // if v is non-zero [-1, 0, 1, 2].every(d => // or each neighbor cell at (x+dx, y+dy), with: (m[y + d % 2] || 0) // dy = d % 2 --> [-1, 0, 1, 0] [x + ~-d % 2] // dx = (d - 1) % 2 --> [0, -1, 0, 1] ^ k // is different from k ) ? // then: v // let the cell unchanged : // else: k + 1 // set the cell to k + 1 ) // end of inner map() ), // end of outer map() k + 1 // increment k for the next iteration ) // end of recursive call : // else: m // stop recursion and return m[] ``` [Answer] # [Python 3](https://docs.python.org/3/), 176 bytes ``` f=lambda a,i=-2,e=enumerate:a*i or f([[E or int((6*max(len(a)>i>-1<j<len(a[i])and a[i][j]for i,j in((r+1,c),(r-1,c),(r,c+1),(r,c-1))))**.5)for c,E in e(R)]for r,R in e(a)],i+1) ``` [Try it online!](https://tio.run/##hY/BboMwDIbvPIWPDg2o2bQdqtJbX4Ar4uBBqhlBQEkq0adnCZ3QpnVbfPDv6Pv/ONPNv4/meVkuRU/DW0tAkovsSepCm@ugLXl9oJRhtHDBqjpHwcYjvqYDzdhrgyROfMrUsTuuU8W1INNCFFVXX6JBdsGEaHdKNkKizT67bHbq3jMlwknT/EVERyPPwQEaS7EmWFneZxK15GBaeJhG68HdXGKhiMv17DwONGHYT8Kcu6lnjyEVYsIc/YHOnW/Z5FZT27PRDkUtkgisD9gDTDb@L92CSiGWPfxdCvbJpn6vjVE/uO0m@ZL5gFDfmEebqH@ZrT4A "Python 3 โ€“ Try It Online") -18 bytes thanks to Mr. Xcoder -20 bytes thanks to ovs [Answer] # [Python 2](https://docs.python.org/2/), ~~146~~ 143 bytes ``` e=enumerate;l=input() for y,f in e(l): for g,h in e(f):x=1+min(abs(y-a)+abs(g-c)for a,b in e(l)for c,d in e(b)if d==1);l[y][g]=x*(x<5) print l ``` [Try it online!](https://tio.run/##nVPLboMwELzzFRYn3DgSW6kXiI/ptZfeEKqAmIdKDHKNAl9PeZcSXon24PUyo50d1mkhw4S/ll5yYVRV1ZJRxrMrE45kZkwjnmZSw4qfCFQQH0UcMS3GhoLqSkDCtuJjI6dwuEZcc9wfrTg6@FAnwdHDNdAhbk@trx65tFcXRz66UArYjK3CtgKb5i9afnrDSioiLlFcVpqUWxjFDH2KjFWNEcuZh2q9VS5FYQjn9tXpNBtWg/FYKtH54/0sRCIMVzDnu7QsnawHEN0m1pAvxwgFd8ihMqD0BQxMUHOKYAfqT5etKO2Y0BOaE8afngnY13/RLdju0Dky8bPhwibzf@h3/m/37Hmwmzv@1zC7HesbAqubtYoaVefmnVW17kPHHfuxlzt9M/DgbsxMsvAKYMVn/bHeT@9z85R@AQ "Python 2 โ€“ Try It Online") [Answer] # Fortran 95, ~~309~~ ~~299~~ ~~294~~ ~~287~~ 269 bytes ``` subroutine f(a) integer::a(:,:),s(2) integer,allocatable::b(:,:) s=shape(a) allocate(b(0:s(1)+1,0:s(2)+1)) do1 k=0,3 do1 i=1,s(1) do1 j=1,s(2) b(i,j)=a(i,j) if(any((/b(i+1,j)==k,b(i-1,j)==k,b(i,j+1)==k,b(i,j-1)==k/)).and.b(i,j)<1.and.k>0)b(i,j)=k+1 1 a(i,j)=b(i,j) end ``` Fortran is not a golfing language. * **Edit:** Saved 10 bytes by using weird old-fashioned do loops. * **Edit 2:** Saved 5 bytes with `any()` * **Edit 3:** Saved 7 bytes by removing an unnecessary `if` * **Edit 4:** Saved 18 bytes by shrinking declaration of `s` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes ``` Mod[-MorphologicalTransform[#,#[[;;,2]]~Max~#[[2]]&,i]~Sum~{i,0,3},5]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfNz8lWtc3v6ggIz8nPx0onBNSlJhXnJZflButrKMcHW1trWMUG1vnm1hRB@QBmWo6mbF1waW5ddWZOgY6xrU6prFq/wOKMvNKotOiq6sNdPBDQx2DWp1qOBs3RFJliKESLgJXZYBDjSGaKmwuMiRCFcJdtbGx/wE "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~34~~ ~~30~~ 23 bytes ([abrudz/SBCS](https://github.com/abrudz/SBCS)) ``` 5|{5โŠƒ,โต+ร—โŒŠ.โŒŠโจโต}โŒบ3 3โฃ3โˆ˜- ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///37Sm2vRRV7POo96t2oenP@rp0gPiR70rgPzaRz27jBWMH/UuNn7UMUP3//9HvXMVfBMz8xTSSvOSSzLz8xQ0ikuTcjOLi4FsTS6uNIVHbRMUiDeRiwtkYkhqcYlCcmJxajHQhEdtEzUMFMiDhppkazXQ1DAkbL6CIZQ0RNdqSFAjKoRrJd5GmDZDYrUiDDBAdzC607DbijWYiFCEJIrFr1idhD8MIFqRg4JYrUi2kmInVr/ijlkDzCSBO0iItpXExA/UCgA "APL (Dyalog Unicode) โ€“ Try It Online") -4 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn). [Answer] # [Clean](https://clean.cs.ru.nl), 157 bytes ``` import StdEnv,StdLib t=transpose z=zipWith ?n=n+sign n f[0,h:l]=[?h:f[h:l]] f[h,0:l]=[h,?h:f l] f[h:l]=[h:f l] f l=l $l=z(z max)(t(map f(t l)))(map f l) ``` # ``` $o$o$ ``` [Try it online!](https://tio.run/##nVSxbsMgEN35CqRmsFUqwRoJZWmGStkydLA8UMfESIAtm1SpP770EhLVTW3Hjk8y3BO8ezxxZDoX1ptyd9A5NkJZr0xV1g5v3W5tPwkMG/WBHHe1sE1VNjlqeauqd@UKtLLcPjdqb7FFMqGkWOqUJ6tiKZPTNAWwIPQMFuQEY33GAnJJseYaLTRvoxYEHOPIRUZUWEYO6ziOQwJTv3WidugJFrlaHTHHCZR8LFhKEIbvYQJ6JWD3axF2@bN@AnZ3@9@4IZhe/bqZzSP4paH9R7gV269gxMQJSzvooAe9Ise96RJ0jZpK8E/BnPojHgzfBDp0kYYNm6lgZisBQQpdKQ82g55clBCIhzR0qv/OpBb7xr@8bfzrlxVGZSEJj8sP "Clean โ€“ Try It Online") As a function literal. [Answer] # Perl, 63 bytes Includes +3 for `0ap` ``` perl -0ape 's/0(?=$a|.{@{-}}$a)/$a+1/seg,$_=reverse while($a+=$|-=/ /)<4' ``` Give the input matrix as a block of digits **without** final newline., e.g. ``` 001 000 010 ``` for the 3x3 example. The output format is the same, a block of digits without final newline. You can use a small script like ``` perl -i -0pe 's/\n*$//' <file> ``` to conveniently remove the final newlines from a file if that is hard to do in your favorite editor [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~93~~ ~~87~~ 84 bytes ``` 1 4 3{m`(?<=^(.)*)0(?=4|.*ยถ(?>(?<-1>.)*)4|(?<=40|^(?(1)_)(?<-1>.)*4.*ยถ.*)) 5 T`1-5`d ``` [Try it online!](https://tio.run/##fZFBDsIgFET3/ySfJiVMpDtbLuG6YqILF7ow7uRcHsCLYanQ0Bb7w2rezGcIj8vzej/Be5Cm3etm2ezbnqWohGLTaierz5tNN8g1uiBrFyxauZ4NQxzFhHTwykoIauhgUTf27L3aGNAWVYRVAMNBoljCOCMtJgNDiY4GlTandVk2a7WWEKVIs1WLDhQAgCL9ZcvR7N7ZgyeBZl2K2X@foL4 "Retina โ€“ Try It Online") Based on my answer to [Kill it With Fire](https://codegolf.stackexchange.com/questions/138068). Edit: Saved ~~6~~ 9 bytes thanks to @MartinEnder. Explanation: ``` 1 4 ``` Turn all the 1s into 4s. ``` 3{ ``` Repeat the rest of the program (at most) 3 times. ``` m`(?<=^(.)*)0(?=4|.*ยถ(?>(?<-1>.)*)4|(?<=40|^(?(1)_)(?<-1>.)*4.*ยถ.*)) 5 ``` Change all 0s adjacent to 4s into 5s. ``` T`1-5`d ``` Decrement all digits. # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~100~~ 94 bytes ``` 1 3 {m`(?<=^(.)*)0(?=3|.*ยถ(?>(?<-1>.)*)3|(?<=30|^(?(1)_)(?<-1>.)*3.*ยถ.*)) 4 T`1-4`d`^[^1]+$ ``` [Try it online!](https://tio.run/##fZFBDsIgFET3/xwuoKYNE7q05RLujIiJLlzowriTc/UAXgxLhYa22B9W82Y@Q3heX7fH2TmQpPfdMLVrNKt4wQVTjbRV8emYanu5ROtlab1FCquZYuAnPiLpvVXBOdW0NyhrczH6oHHcbpwTKwNao4KwCKA/iBRzGGag2aRnyNHBIOLmuC7JJq2WEoIUaLJq1oE8AJClv2w@mtw7efAo0KRLNvvvE8QX "Retina 0.8.2 โ€“ Try It Online") Explanation: ``` 1 3 ``` Turn all the 1s into 3s. ``` { ``` Repeat until the output does not change. ``` m`(?<=^(.)*)0(?=3|.*ยถ(?>(?<-1>.)*)3|(?<=30|^(?(1)_)(?<-1>.)*3.*ยถ.*)) 4 ``` Change all 0s adjacent to 3s into 4s. ``` T`1-4`d`^[^1]+$ ``` If there are no 1s, decrement all digits. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~183~~ ~~158~~ 146 bytes ``` ->a{3.times{|n|a.size.times{|i|r=a[i];r.size.times{|j|(r[j]<1&&[i>0?a[i-1][j]:0,a[i+1]&.at(j),j>0?r[j-1]:0,r[j+1]].include?(n+1))?r[j]=n+2:0}}};a} ``` [Try it online!](https://tio.run/##jZDdisIwEEbv@xShF6WhMWT0Tq0@SDYX0a2Q0EZJW8Rt8uzdWfxZRVeWgfDlO@diGN9vTuOuHCcrPcx4Z5qqHYILmrfmq7r@TfCllkYt/ENtQ@6lVUvIMmlWYo3KBBQ2c8EwF6AyrrvcUmaRoooUEQZEihu3rfvPap27Aij94ap0xXQuYowLHUdftX3dkZLs@FbXNZEJkYK9H2BCsZsH79wHD57cW3PniT8sePJebQb/8n73U0ly6LuWnO/AG30Ygt8fA8GH271xeUpSGi/xw6V0/AY "Ruby โ€“ Try It Online") Uses the obvious three-loop algorithm. ~~The fact that Ruby allows negative indexing into arrays means that there is no way (that I can see) around making the bounds checks.~~ Reaching beyond the boundary of an array returns `nil`, so only the negative bound checks are necessary. The check for `a[i+1][j]` just needs to use the safe access operator. I also shaved off a few bytes by using a variable for `a[0]`. -12 more bytes: Use `.times` instead of `(0...x).map` (in three places). ``` ->a{ 3.times{|n| # For n from 0 to 2 a.size.times{|i| # For each row r=a[i]; r.size.times{|j| # For each column (r[j]<1 && [ # If the current cell is 0, and any of i>0 ? a[i-1][j] : 0, # the cell to the north, a[i+1]&.at(j), # the cell to the south, j>0 ? r[j-1] : 0, # the cell to the west, r[j+1] # or the cell to the east ].include?(n+1) # are set to the previous value, ) ? r[j]=n+2 : 0 # Set this cell to the next value (or 0) } } }; a # Return the modified array } ``` [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` f=lambda a,n=2,e=enumerate:n//5*a or f([[r[j]or n*any([0,*r][j:j+3]+[0,*c][i:i+3])for j,c in e(zip(*a))]for i,r in e(a)],n+1) ``` [Try it online!](https://tio.run/##pVbLbqMwFN3zFV7ixFK5xt1E4kuQF0yHaIhaJ6JEVfvzGT/wC4yTqLFQ8OXcp6@Pffme/p1Ffbsdm/fu48/fDnVENJT0TS@uH/3YTf1BvLy87jp0HtGxbNuxPXH5Knad@C7biuxG3p4Op33N92r2xtvhMMgZPkrUibyhQaC@/Bku5a7DmCvpQEYj7TAnYg/4pqXiQtD5OqlPZVEWqJX28gNIxUmBUOum2yMGwgrsJCGw2oDBGpiKDh4D@hgVUqXNSE2ofGr55r8zLaHSKDUmmZ1qMAtgRiKfGAgabKBepiU2SG9zDQNv0TtaOnZewrRZIhVq4@a8wMSvOASK9hVccbQLI9YmzKspirGDHmmdzUV7eLFybQb3/cx9tGhEqw53leNRpXr3vmerCs@oh7sFtrZYfpvBvR2aBQbSjdyT4eVr4tXD8jyqnuAheL5tElltcArkK189F8Fvej7cmSyLZDOh1fM/s4Rht3DOQEhq1HGjlto9s20g5jAIGJNZmvLMaEZKOR4z2gbv7EW0vfZsvUe0G2QTkXlI8LFi5D2o5SbFw1w076D2FL0GsgVNe3VwEdDl4UIX6pWrB40SnPGexcPyxMsYlrR2Y@MMXPdAWFIaRZHMPXeehR0SnJfVIqvUSZzxHm8Mmjzxa4dwyaqjrsAHaQOhsf@8vk@okdczeYfCWqYuVOP5C6nLlPlusOp3GQcxlfKrgeopKq2VRt3B8O0/ "Python 3 โ€“ Try It Online") Adaptation of my answer to [Calculate COVID spread](https://codegolf.stackexchange.com/questions/214463/calculate-covid-spread) [Answer] # [C (gcc)](https://gcc.gnu.org/), 217 bytes ``` for(w=2;w<=4;w++)for(y=0;y<H;y++)for(x=0;x<W;x++){if(o[y][x].v[w%2])continue;if(o[y][x].v[!(w%2)]){o[y][x].v[w%2]=o[y][x].v[!(w%2)];continue;}for(z=0;z<8;z++)if(o[y][x].a[z]&&o[y][x].a[z]->v[!(w%2)])o[y][x].v[w%2]=w;} ``` [Try it online!](https://tio.run/##pVRtU6MwEP6c/Io9nVawqIC9OzWgX/sP@gGZmw5tlbkedSpKaeW39zYJbymg7V2ZacjuPs@zWXYTXDwFwe40jILF23QGzms8DZeXz/eUnk5n8zCawZjYt@VmRKwhpXH6MkMDvMartyCGYLZY/HqFLSWq4Xzi3fiMEkrCKIZ3z8ZNJp0xo5Qb/0zCSOMvk9VTYEDwPFkhbPX07vk6J@SuhMl1na9pvm6QQ7yEnjX0PfvWB5djyNY0/u2xMuN/4KaEW1/rGFb@b7XBrS/B6qPAD1cuoNYx8IrEbEt@P8129c7SHRBYs3acvTW9z2tSwevlORS@p36MdufZu7@82d423WU6Sv3IgUE4JZmYcTnXsPRGvjcWo4g/M8OfcM@XKy1Fq8kgBQdGuAwGYsaFay1da3SNcSlcYr4XYfQb3Rp3amO4AEuHB7DgDkwdPkDjfNqosNvCzu8GRM81Ae5zl@AjSy/1vbV/OfGGPMm@3MMALH5VlQHCgEHXtSAZkO0x203mHwVIsBRAUjNgkPUFs@vCdZP65x61mnjdiMFmQ4K0JGIfUofvrUfKaE5ZJPguNautOGVYZcDbZcc/eOLaLHHcIUvwW4vmcE2WOiOW5vs17tfOmPFe2GJRKs6kZ/t6sIziMHqbMcX1TUOn7utbNdptRLASn3GxDYptnBu2QbEa4cTb@P1@fXdxX4nsaSQs25Grc9nqCR7bZpCA48IQV@TNO10ZglTaPx0B0jw8lNk3A4rscjBRocrHKWohA1XOrGoXUSCZ3AaTu8ElT1uR5uWBfh@6yiUBzXySopXOryhtL5E4y8sKL4O5dvIY9wLvxED3A5zhcwdn3pnOSTrvEi5QwHvTXoBopWMf1O2d0sAGv3kG/Aa5d2HMRX0hapSiJXXwGCG1lpbho/3wjGa7vw "C (gcc) โ€“ Try It Online") ]
[Question] [ I've compiled a mosaic of 2025 headshots from the avatars of the [top Stack Overflow users](https://stackoverflow.com/users?page=1&tab=reputation&filter=all). *(Click the image to view it full-size.)* [![StackOverflow headshots mosaic](https://i.stack.imgur.com/GY1es.jpg)](http://www.pictureshack.us/images/25745_avatars.png) Your task is to write an algorithm that will create an accurate photomosaic of another image using the 48ร—48 pixel avatars from this 45ร—45 grid of them. ## Test Images Here are the test images. The first is, of course, a light bulb! *(They are not full-sized here. Click an image to view it at full-size. Half-sized versions are available for [The Kiss](http://www.pictureshack.us/images/65020_kiss_half.jpg), [A Sunday Afternoon...](http://www.pictureshack.us/images/75361_sunday_half.jpg), [Steve Jobs](http://www.pictureshack.us/images/73806_steve_half.jpg), and [the spheres](http://www.pictureshack.us/images/99408_spheres_half.png).)* [![lightbulb](https://i.stack.imgur.com/GysVo.png)](http://www.pictureshack.us/images/77388_lightbulb.png) [![The Kiss](https://i.stack.imgur.com/Ts649.jpg)](http://www.pictureshack.us/images/61555_kiss.jpg) [![A Sunday Afternoon on the Island of La Grande Jatte](https://i.stack.imgur.com/11PKc.jpg)](http://www.pictureshack.us/images/45148_sunday.jpg) [![Steve Jobs](https://i.stack.imgur.com/LsL3f.jpg)](http://www.pictureshack.us/images/47824_steve.jpg) [![spheres](https://i.stack.imgur.com/wLzFs.png)](http://www.pictureshack.us/images/21104_spheres.png) Thanks to Wikipedia for all but the raytraced spheres. At full-size these images all have dimensions divisible by 48. The larger ones had to be JPEGs so they could be compressed enough to upload. ## Scoring This is a popularity contest. The submission with mosaics that most accurately depict the original images should be voted up. I will accept the highest voted answer in a week or two. ## Rules * Your photomosaics must be entirely composed of **unaltered** 48ร—48 pixel avatars taken from the mosaic above, arranged in a grid. * You may reuse an avatar in a mosaic. (Indeed for the larger test images you'll have to.) * Show your output, but keep in mind that the test images are very large, and **StackExchange only allows posting of images up to 2MB**. So compress your images or host them somewhere else and put smaller versions here. * To be confirmed the winner you must provide PNG versions of your light bulb or spheres mosaics. This is so I can validate them (see below) to ensure you are not adding extra colors to the avatars to make the mosaics look better. ## Validator This Python script can be used to check whether a completed mosaic really uses unaltered avatars. Just set `toValidate` and `allTiles`. It is unlikely to work for JPEGs or other lossy formats since it compares things exactly, pixel-for-pixel. ``` from PIL import Image, ImageChops toValidate = 'test.png' #test.png is the mosaic to validate allTiles = 'avatars.png' #avatars.png is the grid of 2025 48x48 avatars def equal(img1, img2): return ImageChops.difference(img1, img2).getbbox() is None def getTiles(mosaic, (w, h)): tiles = {} for i in range(mosaic.size[0] / w): for j in range(mosaic.size[1] / h): x, y = i * w, j * h tiles[(i, j)] = mosaic.crop((x, y, x + w, y + h)) return tiles def validateMosaic(mosaic, allTiles, tileSize): w, h = tileSize if mosaic.size[0] % w != 0 or mosaic.size[1] % h != 0: print 'Tiles do not fit mosaic.' elif allTiles.size[0] % w != 0 or allTiles.size[1] % h != 0: print 'Tiles do not fit allTiles.' else: pool = getTiles(allTiles, tileSize) tiles = getTiles(mosaic, tileSize) matches = lambda tile: equal(tiles[pos], tile) success = True for pos in tiles: if not any(map(matches, pool.values())): print 'Tile in row %s, column %s was not found in allTiles.' % (pos[1] + 1, pos[0] + 1) success = False if success: print 'Mosaic is valid.' return print 'MOSAIC IS INVALID!' validateMosaic(Image.open(toValidate).convert('RGB'), Image.open(allTiles).convert('RGB'), (48, 48)) ``` Good luck everyone! I cant wait to see the results. **Note:** I know photomosaic algorithms are easy to find online, but they aren't yet on this site. I'm really hoping we see something more interesting than the usual *"average each tile and each grid space and match them up"* algorithm. [Answer] # Mathematica, with control for granularity This uses the 48 x 48 pixel photos, as required. By default, it will swap those pixels for a corresponding 48x48 pixel square from the image to be approximated. However, the size of the destination squares can be set to be smaller than 48 x 48, allowing for greater fidelity to detail. (see the examples below). ## Preprocessing the palette `collage` is the image containing the photos to serve as the palette. `picsColors`is a list of individual photos paired with their mean red, mean green, and mean blue values. targetColorToPhoto[]` takes the average color of the target swath and finds the photo from the palette that best matches it. ``` parts=Flatten[ImagePartition[collage,48],1]; picsColors={#,c=Mean[Flatten[ImageData[#],1]]}&/@parts; nf=Nearest[picsColors[[All,2]]]; targetColorToPhoto[p_]:=Cases[picsColors,{pic_,nf[p,1][[1]]}:>pic][[1]] ``` **Example** Let's find the photo that best matches RGBColor[0.640, 0.134, 0.249]: ![example1](https://i.stack.imgur.com/QSap7.png) --- ## photoMosaic ``` photoMosaic[rawPic_, targetSwathSize_: 48] := Module[{targetPic, data, dims, tiles, tileReplacements, gallery}, targetPic = Image[data = ImageData[rawPic] /. {r_, g_, b_, _} :> {r, g, b}]; dims = Dimensions[data]; tiles = ImagePartition[targetPic, targetSwathSize]; tileReplacements = targetColorToPhoto /@ (Mean[Flatten[ImageData[#], 1]] & /@Flatten[tiles, 1]); gallery = ArrayReshape[tileReplacements, {dims[[1]]/targetSwathSize,dims[[2]]/targetSwathSize}]; ImageAssemble[gallery]] ``` `photoMosaic takes as input the raw picture we will make a photo mosaic of. `targetPic` will remove a fourth parameter (of PNGs and some JPGs), leaving only R, G, B. `dims` are the dimensions of `targetPic`. `tiles` are the little squares that together comprise the target picture. `targetSwathSize is the granularity parameter; it defaults at 48 (x48).` `tileReplacements` are the photos that match each tile, in proper order. `gallery` is the set of tile-replacements (photos) with the proper dimensionality (i.e. the number of rows and columns that match the tiles). `ImageAssembly` joins up the mosaic into a continuous output image. --- **Examples** This replaces each 12x12 square from the image, Sunday, with a corresponding 48 x 48 pixel photograph that best matches it for average color. ``` photoMosaic[sunday, 12] ``` ![sunday2](https://i.stack.imgur.com/a2fn8.jpg) --- Sunday (detail) ![top hat](https://i.stack.imgur.com/GOW6T.jpg) --- ``` photoMosaic[lightbulb, 6] ``` ![lightbulb 6](https://i.stack.imgur.com/k3K4t.jpg) --- ``` photoMosaic[stevejobs, 24] ``` ![steve jobs 24](https://i.stack.imgur.com/eweC7.jpg) --- Detail, stevejobs. ![jobs detail](https://i.stack.imgur.com/U7Uf7.jpg) --- ``` photoMosaic[kiss, 24] ``` ![kiss](https://i.stack.imgur.com/acPZS.jpg) --- Detail of the Kiss: ![detail kiss](https://i.stack.imgur.com/GaSBA.png) --- ``` photoMosaic[spheres, 24] ``` ![spheres](https://i.stack.imgur.com/9v8FN.jpg) [Answer] ### Java, average distance ``` package photomosaic; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; public class MainClass { static final String FILE_IMAGE = "45148_sunday.jpg"; static final String FILE_AVATARS = "25745_avatars.png"; static final String FILE_RESULT = "mosaic.png"; static final int BLOCKSIZE = 48; static final int SCALING = 4; static final int RADIUS = 3; public static void main(String[] args) throws IOException { BufferedImage imageAvatars = ImageIO.read(new File(FILE_AVATARS)); int[] avatars = deBlock(imageAvatars, BLOCKSIZE); BufferedImage image = ImageIO.read(new File(FILE_IMAGE)); int[] data = deBlock(image, BLOCKSIZE); // perform the mosaic search on a downscaled version int[] avatarsScaled = scaleDown(avatars, BLOCKSIZE, SCALING); int[] dataScaled = scaleDown(data, BLOCKSIZE, SCALING); int[] bests = mosaicize(dataScaled, avatarsScaled, (BLOCKSIZE / SCALING) * (BLOCKSIZE / SCALING), image.getWidth() / BLOCKSIZE); // rebuild the image from the mosaic tiles reBuild(bests, data, avatars, BLOCKSIZE); reBlock(image, data, BLOCKSIZE); ImageIO.write(image, "png", new File(FILE_RESULT)); } // a simple downscale function using simple averaging private static int[] scaleDown(int[] data, int size, int scale) { int newsize = size / scale; int newpixels = newsize * newsize; int[] result = new int[data.length / scale / scale]; for (int r = 0; r < result.length; r += newpixels) { for (int y = 0; y < newsize; y++) { for (int x = 0; x < newsize; x++) { int avgR = 0; int avgG = 0; int avgB = 0; for (int sy = 0; sy < scale; sy++) { for (int sx = 0; sx < scale; sx++) { int dt = data[r * scale * scale + (y * scale + sy) * size + (x * scale + sx)]; avgR += (dt & 0xFF0000) >> 16; avgG += (dt & 0xFF00) >> 8; avgB += (dt & 0xFF) >> 0; } } avgR /= scale * scale; avgG /= scale * scale; avgB /= scale * scale; result[r + y * newsize + x] = 0xFF000000 + (avgR << 16) + (avgG << 8) + (avgB << 0); } } } return result; } // the mosaicize algorithm: take the avatar with least pixel-wise distance private static int[] mosaicize(int[] data, int[] avatars, int pixels, int tilesPerLine) { int tiles = data.length / pixels; // use random order for tile search List<Integer> ts = new ArrayList<Integer>(); for (int t = 0; t < tiles; t++) { ts.add(t); } Collections.shuffle(ts); // result array int[] bests = new int[tiles]; Arrays.fill(bests, -1); // make list of offsets to be ignored List<Integer> ignores = new ArrayList<Integer>(); for (int sy = -RADIUS; sy <= RADIUS; sy++) { for (int sx = -RADIUS; sx <= RADIUS; sx++) { if (sx * sx + sy * sy <= RADIUS * RADIUS) { ignores.add(sy * tilesPerLine + sx); } } } for (int t : ts) { int b = t * pixels; int bestsum = Integer.MAX_VALUE; for (int at = 0; at < avatars.length / pixels; at++) { int a = at * pixels; int sum = 0; for (int i = 0; i < pixels; i++) { int r1 = (avatars[a + i] & 0xFF0000) >> 16; int g1 = (avatars[a + i] & 0xFF00) >> 8; int b1 = (avatars[a + i] & 0xFF) >> 0; int r2 = (data[b + i] & 0xFF0000) >> 16; int g2 = (data[b + i] & 0xFF00) >> 8; int b2 = (data[b + i] & 0xFF) >> 0; int dr = (r1 - r2) * 30; int dg = (g1 - g2) * 59; int db = (b1 - b2) * 11; sum += Math.sqrt(dr * dr + dg * dg + db * db); } if (sum < bestsum) { boolean ignore = false; for (int io : ignores) { if (t + io >= 0 && t + io < bests.length && bests[t + io] == at) { ignore = true; break; } } if (!ignore) { bestsum = sum; bests[t] = at; } } } } return bests; } // build image from avatar tiles private static void reBuild(int[] bests, int[] data, int[] avatars, int size) { for (int r = 0; r < bests.length; r++) { System.arraycopy(avatars, bests[r] * size * size, data, r * size * size, size * size); } } // splits the image into blocks and concatenates all the blocks private static int[] deBlock(BufferedImage image, int size) { int[] result = new int[image.getWidth() * image.getHeight()]; int r = 0; for (int fy = 0; fy < image.getHeight(); fy += size) { for (int fx = 0; fx < image.getWidth(); fx += size) { for (int l = 0; l < size; l++) { image.getRGB(fx, fy + l, size, 1, result, r * size * size + l * size, size); } r++; } } return result; } // unsplits the block version into the original image format private static void reBlock(BufferedImage image, int[] data, int size) { int r = 0; for (int fy = 0; fy < image.getHeight(); fy += size) { for (int fx = 0; fx < image.getWidth(); fx += size) { for (int l = 0; l < size; l++) { image.setRGB(fx, fy + l, size, 1, data, r * size * size + l * size, size); } r++; } } } } ``` The algorithm performs a search through all avatar tiles for each grid space separately. Due to the small sizes I didn't implement any sophisticated data structurs or search algorithms but simply brute-force the whole space. This code does not do any modifications to the tiles (e.g. no adaption to destination colors). ### Results *Click for full-size image.* [![light buld](https://i.stack.imgur.com/xwoxk.png)](http://www.pictureshack.us/images/42778_mosaic_04_lightbulb.png) [![spheres](https://i.stack.imgur.com/b4Psv.png)](http://www.pictureshack.us/images/57865_mosaic_04_spheres.png) [![sunday](https://i.stack.imgur.com/ftTVx.png)](http://www.pictureshack.us/images/48448_mosaic_04_sunday.png) ### Effect of radius Using `radius` you can reduce the repetitiveness of the tiles in the result. Setting `radius=0` there is no effect. E.g. `radius=3` supresses the same tile within a radius of 3 tiles. [![light buld](https://i.stack.imgur.com/xwoxk.png)](http://www.pictureshack.us/images/42778_mosaic_04_lightbulb.png) [![sunday](https://i.stack.imgur.com/ftTVx.png)](http://www.pictureshack.us/images/48448_mosaic_04_sunday.png) radius=0 [![light buld](https://i.stack.imgur.com/sNhls.png)](http://www.pictureshack.us/images/82587_mosaic_04_r03_lightbulb.png) [![light buld](https://i.stack.imgur.com/WxxH2.png)](http://www.pictureshack.us/images/22259_mosaic_04_r03_sunday.png) ### Effect of scaling factor Using the `scaling` factor we can determine how the matching tile is searched. `scaling=1` means searching for a pixel-perfect match while `scaling=48` does a average-tile search. [![scaling 48](https://i.stack.imgur.com/UtHKr.png)](http://www.pictureshack.us/images/45469_mosaic_48_sunday.png) scaling=48 [![scaling 16](https://i.stack.imgur.com/7ao0C.png)](http://www.pictureshack.us/images/72507_mosaic_16_sunday.png) scaling=16 [![scaling 4](https://i.stack.imgur.com/kk4oP.png)](http://www.pictureshack.us/images/48448_mosaic_04_sunday.png) scaling=4 [![scaling 1](https://i.stack.imgur.com/5bN7t.png)](http://www.pictureshack.us/images/10567_mosaic_01_sunday.png) scaling=1 [Answer] **JS** Same as in previous golf: <http://jsfiddle.net/eithe/J7jEk/> :D (this time called with `unique: false, {pixel_2: {width: 48, height: 48}, pixel_1: {width: 48, height: 48}}`) (don't treat palette to use one pixel once, palette pixels are 48x48 swatches, shape pixels are 48x48 swatches). Currently it searches through the avatars list to find the nearest matching by weight of selected algorithm, however it doesn't perform any color uniformity matching (something I need to take a look at. * [![balanced](https://i.stack.imgur.com/1RFS0.png)](https://i.stack.imgur.com/Mt8dZ.png) * [![lab](https://i.stack.imgur.com/Rr3Tp.png)](https://i.stack.imgur.com/B4J1z.jpg) Unfortunately I'm not able to play around with larger images, because my RAM runs out :D If possible I'd appreciate smaller output images. If using 1/2 of image size provided, here's Sunday Afternoon: * ![balanced](https://i.stack.imgur.com/V1R9w.png) * ![lab](https://i.stack.imgur.com/594iG.png) [Answer] ## GLSL The difference between this challenge and the one at [American Gothic in the palette of Mona Lisa: Rearrange the pixels](https://codegolf.stackexchange.com/questions/33172/american-gothic-in-the-palette-of-mona-lisa-rearrange-the-pixels) interested me, because the mosaic tiles can be re-used, whereas the pixels couldn't. This means that it is possible to easily parallelize the algorithm, so I decided to attempt a massively parallel version. By "massively" I mean using the 1344 shader cores on my desktop's GTX670 all simultaneously, via GLSL. ## Method The actual tile-matching is simple: I calculate the RGB distance between each pixel in a target area and the mosaic tile area, and choose the tile with the lowest difference (weighted by brightness values). The tile index is written out in the red and green color attributes of the fragment, then after all the fragments have been rendered I read the values back out of the framebuffer and build the output image from those indices. The actual implementation is quite a hack; instead of creating an FBO I just opened a window and rendered into it, but GLFW can't open windows at arbitrarily small resolutions, so I create the window bigger than required, then draw a small rectangle that is the correct size so that it has one fragment per tile that maps to the source image. The entire MSVC2013 solution is available at <https://bitbucket.org/Gibgezr/mosaicmaker> It requires GLFW/FreeImage/GLEW/GLM to compile, and OpenGL 3.3 or better drivers/video card to run. ## Fragment Shader Source ``` #version 330 core uniform sampler2D sourceTexture; uniform sampler2D mosaicTexture; in vec2 v_texcoord; out vec4 out_Color; void main(void) { ivec2 sourceSize = textureSize(sourceTexture, 0); ivec2 mosaicSize = textureSize(mosaicTexture, 0); float num_pixels = mosaicSize.x/45.f; vec4 myTexel; float difference = 0.f; //initialize smallest difference to a large value float smallest_difference = 255.0f*255.0f*255.0f; int closest_x = 0, closest_y = 0; vec2 pixel_size_src = vec2( 1.0f/sourceSize.x, 1.0f/sourceSize.y); vec2 pixel_size_mosaic = vec2( 1.0f/mosaicSize.x , 1.0f/mosaicSize.y); vec2 incoming_texcoord; //adjust incoming uv to bottom corner of the tile space incoming_texcoord.x = v_texcoord.x - 1.0f/(sourceSize.x / num_pixels * 2.0f); incoming_texcoord.y = v_texcoord.y - 1.0f/(sourceSize.y / num_pixels * 2.0f); vec2 texcoord_mosaic; vec2 pixelcoord_src, pixelcoord_mosaic; vec4 pixel_src, pixel_mosaic; //loop over all of the mosaic tiles for(int i = 0; i < 45; ++i) { for(int j = 0; j < 45; ++j) { difference = 0.f; texcoord_mosaic = vec2(j * pixel_size_mosaic.x * num_pixels, i * pixel_size_mosaic.y * num_pixels); //loop over all of the pixels in the images, adding to the difference for(int y = 0; y < num_pixels; ++y) { for(int x = 0; x < num_pixels; ++x) { pixelcoord_src = vec2(incoming_texcoord.x + x * pixel_size_src.x, incoming_texcoord.y + y * pixel_size_src.y); pixelcoord_mosaic = vec2(texcoord_mosaic.x + x * pixel_size_mosaic.x, texcoord_mosaic.y + y * pixel_size_mosaic.y); pixel_src = texture(sourceTexture, pixelcoord_src); pixel_mosaic = texture(mosaicTexture, pixelcoord_mosaic); pixel_src *= 255.0f; pixel_mosaic *= 255.0f; difference += (pixel_src.x - pixel_mosaic.x) * (pixel_src.x - pixel_mosaic.x) * 0.5f+ (pixel_src.y - pixel_mosaic.y) * (pixel_src.y - pixel_mosaic.y) + (pixel_src.z - pixel_mosaic.z) * (pixel_src.z - pixel_mosaic.z) * 0.17f; } } if(difference < smallest_difference) { smallest_difference = difference; closest_x = j; closest_y = i; } } } myTexel.x = float(closest_x)/255.f; myTexel.y = float(closest_y)/255.f; myTexel.z = 0.f; myTexel.w = 0.f; out_Color = myTexel; } ``` ## Results The images render almost instantly, so the parallelization was a success. The downside is that I can't make the individual fragments rely on the output of any other fragments, so there is no way to get the significant quality increase you can get by not picking the same tile twice within a certain range. So, fast results, but limited quality due to massive repetitions of tiles. All in all, it was fun. <https://i.stack.imgur.com/MO7NU.jpg> for full-size versions. ![enter image description here](https://i.stack.imgur.com/9tVlw.jpg) [Answer] # Python Here goes for the first Python solution, using a mean approach. We can evolve from here. The rest of the images are [here](https://i.stack.imgur.com/6pDtQ.jpg). ![sunday](https://i.stack.imgur.com/wsVf2.jpg) ![steve](https://i.stack.imgur.com/Qx85w.jpg) ``` from PIL import Image import numpy as np def calcmean(b): meansum = 0 for k in range(len(b)): meansum = meansum + (k+1)*b[k] return meansum/sum(b) def gettiles(imageh,w,h): k = 0 tiles = {} for x in range(0,imageh.size[0],w): for y in range(0,imageh.size[1],h): a=imageh.crop((x, y, x + w, y + h)) b=a.resize([1,1], Image.ANTIALIAS) tiles[k] = [a,x,y,calcmean(b.histogram()[0:256]) \ ,calcmean(b.histogram()[256:256*2]) \ ,calcmean(b.histogram()[256*2:256*3])] k = k + 1 return tiles w = 48 h = 48 srch = Image.open('25745_avatars.png').convert('RGB') files = ['21104_spheres.png', '45148_sunday.jpg', '47824_steve.jpg', '61555_kiss.jpg', '77388_lightbulb.png'] for f in range(len(files)): desh = Image.open(files[f]).convert('RGB') srctiles = gettiles(srch,w,h) destiles = gettiles(desh,w,h) #build proximity matrix pm = np.zeros((len(destiles),len(srctiles))) for d in range(len(destiles)): for s in range(len(srctiles)): pm[d,s] = (srctiles[s][3]-destiles[d][3])**2 + \ (srctiles[s][4]-destiles[d][4])**2 + \ (srctiles[s][5]-destiles[d][5])**2 for k in range(len(destiles)): j = list(pm[k,:]).index(min(pm[k,:])) desh.paste(srctiles[j][0], (destiles[k][1], destiles[k][2])) desh.save(files[f].replace('.','_m'+'.')) ``` [Answer] # Yet Another Python Solution - Average Based (RGB vs L*a*b\*) ## Results (There are some slightly differences) **Bulb - RGB** [full view](http://www.pictureshack.us/images/3669_bulb_photomosaic.png) ![bulb_rgb](https://i.stack.imgur.com/OH0V4.png) **Bulb - Lab** [full view](http://www.pictureshack.us/images/62570_bulb_photomosaic.png) ![bulb_lab](https://i.stack.imgur.com/HUoC5.png) **Steve - RGB** [full view](http://www.pictureshack.us/images/3496_steve_photomosaic.png) ![steve_rgb](https://i.stack.imgur.com/vDlj4.png) **Steve - Lab** [full view](http://www.pictureshack.us/images/95937_steve_photomosaic.png) ![steve_lab](https://i.stack.imgur.com/c6fgU.png) **Spheres - RGB** [full view](http://www.pictureshack.us/images/9886_spheres_photomosaic.png) ![spheres_rgb](https://i.stack.imgur.com/sFZa6.png) **Spheres - Lab** [full view](http://www.pictureshack.us/images/2992_spheres_photomosaic.png) ![spheres_lab](https://i.stack.imgur.com/EvCM6.png) **Sunday - RGB** [full view](http://www.pictureshack.us/images/83218_sunday_photomosaic.png) ![sunday_rgb](https://i.stack.imgur.com/y3I6w.png) **Sunday - Lab** [full view](http://www.pictureshack.us/images/14201_sunday_photomosaic.png) ![sunday_lab](https://i.stack.imgur.com/rMmGC.png) **Kiss - RGB** [full view](https://i.stack.imgur.com/ULEpd.jpg) ![kiss_rgb](https://i.stack.imgur.com/jf9VA.jpg) **Kiss - Lab** [full view](https://i.stack.imgur.com/b0wfK.jpg) ![kiss_lab](https://i.stack.imgur.com/QqA8B.jpg) ## Code requires [python-colormath](http://python-colormath.readthedocs.org/en/latest/index.html) for Lab ``` #!/usr/bin/env python # -*- coding: utf-8 -*- from PIL import Image from colormath.color_objects import LabColor,sRGBColor from colormath.color_conversions import convert_color from colormath.color_diff import delta_e_cie1976 def build_photomosaic_ils(mosaic_im,target_im,block_width,block_height,colordiff,new_filename): mosaic_width=mosaic_im.size[0] #dimensions of the target image mosaic_height=mosaic_im.size[1] target_width=target_im.size[0] #dimensions of the target image target_height=target_im.size[1] target_grid_width,target_grid_height=get_grid_dimensions(target_width,target_height,block_width,block_height) #dimensions of the target grid mosaic_grid_width,mosaic_grid_height=get_grid_dimensions(mosaic_width,mosaic_height,block_width,block_height) #dimensions of the mosaic grid target_nboxes=target_grid_width*target_grid_height mosaic_nboxes=mosaic_grid_width*mosaic_grid_height print "Computing the average color of each photo in the mosaic..." mosaic_color_averages=compute_block_avg(mosaic_im,block_width,block_height) print "Computing the average color of each block in the target photo ..." target_color_averages=compute_block_avg(target_im,block_width,block_height) print "Computing photomosaic ..." photomosaic=[0]*target_nboxes for n in xrange(target_nboxes): print "%.2f " % (n/float(target_nboxes)*100)+"%" for z in xrange(mosaic_nboxes): current_diff=colordiff(target_color_averages[n],mosaic_color_averages[photomosaic[n]]) candidate_diff=colordiff(target_color_averages[n],mosaic_color_averages[z]) if(candidate_diff<current_diff): photomosaic[n]=z print "Building final image ..." build_final_solution(photomosaic,mosaic_im,target_nboxes,target_im,target_grid_width,block_height,block_width,new_filename) def build_initial_solution(target_nboxes,mosaic_nboxes): candidate=[0]*target_nboxes for n in xrange(target_nboxes): candidate[n]=random.randint(0,mosaic_nboxes-1) return candidate def build_final_solution(best,mosaic_im,target_nboxes,target_im,target_grid_width,block_height,block_width,new_filename): for n in xrange(target_nboxes): i=(n%target_grid_width)*block_width #i,j -> upper left point of the target image j=(n/target_grid_width)*block_height box = (i,j,i+block_width,j+block_height) #get the best photo from the mosaic best_photo_im=get_block(mosaic_im,best[n],block_width,block_height) #paste the best photo found back into the image target_im.paste(best_photo_im,box) target_im.save(new_filename); #get dimensions of the image grid def get_grid_dimensions(im_width,im_height,block_width,block_height): grid_width=im_width/block_width #dimensions of the target image grid grid_height=im_height/block_height return grid_width,grid_height #compute the fitness of given candidate solution def fitness(candidate,mosaic_color_averages,mosaic_nboxes,target_color_averages,target_nboxes): error=0.0 for i in xrange(target_nboxes): error+=colordiff_rgb(mosaic_color_averages[candidate[i]],target_color_averages[i]) return error #get a list of color averages, i.e, the average color of each block in the given image def compute_block_avg(im,block_height,block_width): width=im.size[0] height=im.size[1] grid_width_dim=width/block_width #dimension of the grid grid_height_dim=height/block_height nblocks=grid_width_dim*grid_height_dim #number of blocks avg_colors=[] for i in xrange(nblocks): avg_colors+=[avg_color(get_block(im,i,block_width,block_height))] return avg_colors #returns the average RGB color of a given image def avg_color(im): avg_r=avg_g=avg_b=0.0 pixels=im.getdata() size=len(pixels) for p in pixels: avg_r+=p[0]/float(size) avg_g+=p[1]/float(size) avg_b+=p[2]/float(size) return (avg_r,avg_g,avg_b) #get the nth block of the image def get_block(im,n,block_width,block_height): width=im.size[0] grid_width_dim=width/block_width #dimension of the grid i=(n%grid_width_dim)*block_width #i,j -> upper left point of the target block j=(n/grid_width_dim)*block_height box = (i,j,i+block_width,j+block_height) block_im = im.crop(box) return block_im #calculate color difference of two pixels in the RGB space #less is better def colordiff_rgb(pixel1,pixel2): delta_red=pixel1[0]-pixel2[0] delta_green=pixel1[1]-pixel2[1] delta_blue=pixel1[2]-pixel2[2] fit=delta_red**2+delta_green**2+delta_blue**2 return fit #http://python-colormath.readthedocs.org/en/latest/index.html #calculate color difference of two pixels in the L*ab space #less is better def colordiff_lab(pixel1,pixel2): #convert rgb values to L*ab values rgb_pixel_1=sRGBColor(pixel1[0],pixel1[1],pixel1[2],True) lab_1= convert_color(rgb_pixel_1, LabColor) rgb_pixel_2=sRGBColor(pixel2[0],pixel2[1],pixel2[2],True) lab_2= convert_color(rgb_pixel_2, LabColor) #calculate delta e delta_e = delta_e_cie1976(lab_1, lab_2) return delta_e if __name__ == '__main__': mosaic="images/25745_avatars.png" targets=["images/lightbulb.png","images/steve.jpg","images/sunday.jpg","images/spheres.png","images/kiss.jpg"] target=targets[0] mosaic_im=Image.open(mosaic) target_im=Image.open(target) new_filename=target.split(".")[0]+"_photomosaic.png" colordiff=colordiff_rgb build_photomosaic_ils(mosaic_im,target_im,48,48,colordiff,new_filename) ``` ]
[Question] [ # Introduction We -- especially the geeks among us, who tend to be fans -- all remember this old *Far Side* cartoon: [![Hey! Hey! Hey!](https://i.stack.imgur.com/L3GcY.jpg)](https://i.stack.imgur.com/L3GcY.jpg) Clearly, Professor Schwartzman could have brushed up on his programming skills just a wee bit more before he put his invention to use. But can you replicate it yourself... using as few bytes as possible? # Input Specs You must create a script that translates dog sounds into appropriately intonated "Hey"s. This is pure code golf; the lowest number of bytes wins. Your input will consist of some combination of the following tokens: * `Bark`, `Baark`, `Baaark`, `Baaaark`, ... (that is, `B*rk` with at least 1 `a` replacing the asterisk) * `Woof`, `Wooof`, `Woooof`, ... (`W*f` with at least **2** `o`s replacing the asterisk) * `Grr`, `Grrr`, `Grrrr`, ..., (`G` followed by at least **2** `r`s) * Any number of `.` (period), `!` (exclamation mark) and/or `?` (question mark) characters, which may occur anywhere in the input Note, again, that the `Woof`-based and `Grr`-based tokens always require at least **two** `o`s and `r`s respectively; `Wof` and `Gr` are *not* valid tokens. There is no limit on how long a token can be (e.g., how many repeated `a`s there can be in a `Bark` token); however, your decoder only needs to work correctly for input tokens with **up to 10** total `a`s, `o`s, or `r`s to pass this challenge. # Output Specs Faithful to Schwartzman's design, your canine decoder program must process it into output text as follows: * `Bark`, `Woof`, and `Grr` become `Hey`; * `Baark`, `Wooof`, and `Grrr` become `Heyy`; * `Baaark`, `Woooof`, and `Grrrr` become `Heyyy`; etc. * For all `Bark`-based tokens, the number of `y`s in the output `Hey`-based token must be equal to the number of `a`s; * For all `Woof`-based tokens, the number of `y`s in the output `Hey`-based token must be **one less than** the number of `o`s; * For all `Grr`-based tokens, the number of `y`s in the output `Hey`-based token must be **one less than** the number of `r`s; * All punctuation (`.`, `!`, and `?`) is left unchanged. Remember to drop one `y` from the output for `Woof`s and `Grr`s only! The input `Baaaaaaaark?`, with 8 `a`s, will become `Heyyyyyyyy?`, with a matching set of 8 `y`s. However, `Woooooooof?` becomes only `Heyyyyyyy?`, with 7 `y`s. Again, if you can get your program to work for input tokens of unlimited size, that's great, but for purposes of this challenge, your program will only be checked to ensure that it works properly for input tokens that have no more than 10 repeated letters. All `Bark`-, `Woof`-, and `Grr`-based tokens in your input are assumed to begin with capital letters. Therefore, there is *no need* to handle turning `Bark grrr` into `Hey heyy` or anything similar. # Example Inputs and Outputs 1. * Input: `Bark. Bark! Bark!!` * Output: `Hey. Hey! Hey!!` 2. * Input: `Baaaaaark?` (six `a`s) * Output: `Heyyyyyy?` (six `y`s) 3. * Input: `Grrrrrrrr...` (eight `r`s) * Output: `Heyyyyyyy...` (**seven** `y`s) 4. * Input: `?...!` * Output: `?...!` 5. * Input: `Wooof Woof? Grrrr. Baaaark Grr!` * Output: `Heyy Hey? Heyyy. Heyyyy Hey!` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~24~~ ~~18~~ ~~17~~ 16 bytes *1 byte saved based on an idea in MT0's answer.* ``` \wf?k? y \byy He ``` [Try it online!](http://retina.tryitonline.net/#code=XHdmP2s_CnkKXGJ5eQpIZQ&input=QmFyay4gQmFyayEgQmFyayEhCkJhYWFhYWFyaz8KR3JycnJycnJyLi4uCj8uLi4hCldvb29mIFdvb2Y_IEdycnJyLiBCYWFhYXJrIEdyciE) ### Explanation ``` \wf?k? y ``` This simply turns all letters into `y`, but if they are followed by an `f` or `k` we immediately replace that as well. By removing `f` and `k` we "normalise" the lengths of the words so that they now all have two more `y`s than they need. ``` \byy He ``` This turns the first two `y` of every word into `He`, completing the transformation. [Answer] ## Perl, 51 41 39 bytes ``` s/(G.|[BW]..)(\w+)/He."y"x length$2/ge ``` ### Usage ``` perl -pE 's/(G.|[BW]..)(\w+)/He."y"x length$2/ge' ``` ### Input ``` Bark. Bark! Bark!! Baaaaaark? Grrrrrrrr... ?...! Wooof Woof? Grrrr. Baaaark Grr! ``` ### Output ``` Hey. Hey! Hey!! Heyyyyyy? Heyyyyyyy... ?...! Heyy Hey? Heyyy. Heyyyy Hey! ``` ### How it works Simple regexp substitution using the auto-printing `-p` adding 1 byte to the count. `/ge` executes the substitution for every pattern, and runs the replacement as code. --- An older version used a three-way detection, but [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) noticed that I was not aggressive enough, which saved me 10 bytes. [msh210](https://codegolf.stackexchange.com/users/1976/msh210) informed me that you don't need quotes around the string `He`, saving two bytes. [Answer] # Python, 106 bytes ``` f=lambda s,a="B,He,Gr,He,Wo,He,a,y,r,y,o,y,f,,yk,".split(","):s if a==[]else f(s.replace(a[0],a[1]),a[2:]) ``` **Demo** <https://repl.it/C6Rr> [Answer] # Vimscript, ~~51~~ ~~39~~ ~~37~~ ~~33~~ ~~32~~ ~~29~~ 28 bytes, ``` %s/\hk\?f\?/y/g|%s/\<yy/He/g ``` Regex credits for shaving 9 more bytes: MT0, Martin Ender, msh210 [![asciicast](https://asciinema.org/a/50280.png)](https://asciinema.org/a/50280) *Demo* Explanation: ``` 1. Normalize words to same length & replace letters with ys %s Regex search and replace / Regex search begin \hk\?f\? Find any letter (\h) optionally followed by k or f / Regex search end and replace start y Replace with y / Replace end g Replace globally | New command 2. Overwrite first two y of every word with He %s Regex search and replace / Regex search begin \<yy Find yy at a word's beginning / Regex search end and replace start He replace with He / Replace end g Replace globally ``` [Answer] # JavaScript (ES6) - ~~57~~ ~~55~~ ~~52~~ 51 Bytes ``` f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He') ``` Test: ``` f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He'); [ 'Bark. Bark! Bark!!', 'Baaaaaark?', 'Grrrrrrrr...', '?...!', 'Wooof Woof? Grrrr. Baaaark Grr!' ].forEach( s=>{console.log( f(s) );} ); ``` Thanks to @MartinEnder for bytes 56 & 51 and the inspiration for some of the other shavings. [Answer] # Perl 5, 25 bytes A Perl copy of [Martin Ender's Retina answer](/a/83871). 24 bytes, plus 1 for `-pe` instead of `-e`. ``` s;\wf?k?;y;g;s;\byy;He;g ``` [Answer] # Javascript, ~~72~~ ~~66~~ 64 Bytes ``` f= t=>t.replace(/k|f/g,'').replace(/\w/g,'y').replace(/\byy/g,'He') ``` Edit: separated `f=` and function + reduced byte count [Answer] ## Pyke, 35 bytes ``` .cFDlR\G.^+3-\y*"He"R+)Rdc~lL-],AsJ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.cFDlR%5CG.%5E%2B3-%5Cy%2a%22He%22R%2B%29Rdc%7ElL-%5D%2CAsJ&input=Wooof+Woof%3F+Grrrr.+Baaaark+Grr%21) Generates Heys, Generates punctuation, zips together, joins [Answer] # Python 3, ~~140~~ ~~135~~ 134 bytes ``` from re import* f=lambda s:''.join('He'+'y'*len(x)+y for x,y in[(a+b+c,d)for a,b,c,d in findall('(?:Wo(o+)f|Gr(r+)|B(a+)rk)(\W+)',s)]) ``` Using regex to find occurences of replacable characters. **Edit:** Golfed 1 byte whitespace and 4 bytes on getting the values from findall result. **Edit2:** Golfed 1 byte (Bark's "a" was not counted properly) ]
[Question] [ [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) is a popular computer game that you have probably wasted time playing where you try to reveal the cells that are mines in a rectangular grid based on hints of how many neighboring mines each non-mine cell has. And in case you haven't played it, do so [here](http://minesweeperonline.com/). A nifty mathematical fact about a Minesweeper grid (a.k.a. board) is that: > > A board and its complement have the same *mine total number*. ([Proof](http://www.cut-the-knot.org/arithmetic/combinatorics/Minesweeper.shtml)) > > > That is to say that if you have a completely revealed Minesweeper grid, the sum all the numbers on that grid, i.e. the *mine total*, will equal the mine total of the complement of the grid, which is the grid where every mine has been replaced with a non-mine and every non-mine replaced with a mine. For example, for the Minesweeper grid ``` **1.. 34321 *2**1 ``` the mine total is 1 + 3 + 4 + 3 + 2 + 1 + 2 + 1 = 17. The grid's complement is ``` 24*** ***** 3*44* ``` which has mine total 2 + 4 + 3 + 4 + 4 = 17 again. Write a program that takes in an arbitrary Minesweeper grid in text form where `*` represents a mine and `1` through `8` represent the number of mines adjacent to a non-mine cell. You can use `.` or `0` or (space) to represent cells with no mine neighbors, your choice. You can assume that the input grid will be correctly marked, i.e. each non-mine cell will accurately denote the total number of mines immediately adjacent to it orthogonally or diagonally. Your program needs to print the complement of the grid in the same format (using the same `.`, `0`, or as you expected in the input). **The shortest code in bytes wins.** * Instead of a program you may write a function that takes the input grid as a string and prints or returns the complement grid. * A trailing newline in the input or output is fine, but there should be no other characters besides those that form the grid. * You can assume a 1ร—1 grid will be the smallest input. # Test Cases All inputs and outputs could be swapped as the complement of the complement is the original grid. The grids can be rotated as well for further test cases. Input: ``` 111 1*1 111 ``` Output: ``` *** *8* *** ``` --- Input: ``` . ``` Output: ``` * ``` --- Input: ``` *11*1.1**1...1***1.....1*****1.......... ``` Output: ``` 1**2***11*****1.1*******1...1*********** ``` --- Input: ([Cut The Knot example](http://www.cut-the-knot.org/arithmetic/combinatorics/Minesweeper.shtml)) ``` **212*32 333*33** 1*22*333 222222*1 *33*2232 2**22*2* ``` Output: ``` 24***4** ***7**64 *8**7*** ******8* 4**7**** *33**5*3 ``` [Answer] # CJam, ~~58~~ 57 bytes ``` 0WX]2m*qN/{'*f+z}2*f{\~@m<fm<W<}:..+{W<{_'*#'*@'*-,?}/N}/ ``` Input should not end with a linefeed. Output contains `0` for cells without nearby mines. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0WX%5D2m*qN%2F%7B'*f%2Bz%7D2*f%7B%5C~%40m%3Cfm%3CW%3C%7D%3A..%2B%7BW%3C%7B_'*%23'*%40'*-%2C%3F%7D%2FN%7D%2F&input=**212*32%0A333*33**%0A1*22*333%0A222222*1%0A*33*2232%0A2**22*2*). ### Idea We start by padding the input matrix with one row and one column of asterisks. For input ``` *4* **2 ``` this results in ``` *4** **2* **** ``` Now we generate all possible modifications that result of rotating the rows and columns 0, -1 or 1 units up/left: ``` *4** **** **2* **4* **** ***2 4*** **** *2** **2* *4** **** ***2 **4* **** *2** 4*** **** **** **2* *4** **** ***2 **4* **** *2** 4*** ``` We discard the "padding locations" from each rotation, i.e., ``` *4* *** **2 **4 *** *** 4** *** *2* **2 *4* *** *** **4 *** *2* 4** *** ``` and form a single matrix by concatenating the corresponding characters of each rotation: ``` ******4** 4*******2 **24***** *******4* *4****2** 2***4**** ``` The first character of each position is its original character. * If it is a non-asterisk, it has to be replaced with an asterisk. * If it is an asterisk, the number of non-asterisks in that string is the number of neighboring mines. ### How it works ``` 0WX]2m* e# Push the array of all vectors of {0,-1,1}^2. qN/ e# Read all input from STDIN and split at linefeeds. {'*f+z}2* e# Append a '*' to each row and transpose rows with columns. Repeat. f{ e# For each vector [A B], push the modified input Q; then: \~ e# Swap Q with [A B] and dump A and B on the stack. @m< e# Rotate the rows of Q B units up. fm< e# Rotate each row of the result A units left. W< e# Discard the last row. } e# This pushes all nine rotations with Manhattan distance 1. :..+ e# Concatenate the corresponding characters for each position. { e# For each row: W< e# Discard the character corresponding to the last column. { e# For each remaining string: _'*# e# Find the first index of '*' in a copy. '* e# Push '*'. @'*-, e# Count the non-asterisks in the string. ? e# Select '*' if the index is non-zero, the count otherwise. }/ e# N e# Push a linefeed. }/ e# ``` [Answer] # Pyth, ~~39~~ 38 bytes ``` j.es.eh-+K\*l-s:RtWYY+Y2:+K.zk+k3KZb.z ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=j.es.eh-%2BK%5C*l-s%3ARtWYY%2BY2%3A%2BK.zk%2Bk3KZb.z&input=**212*32%0A333*33**%0A1*22*333%0A222222*1%0A*33*2232%0A2**22*2*&debug=0) The main algorithm is really straightforward. I simply iterate over each cell, take the surrounding 3x3 box (or smaller when the cell is at the border) and print a star or the number of non-stars in that box. ### Explanation: ``` j.es.eh-+K\*l-s:RtWYY+Y2:+K.zk+k3KZb.z implicit: .z = list of input strings .e .z map each index k, line b of .z to: .e b map each index Y, char Z of b to: K\* assign "*" to K +K.z insert K at the front of .z : k+k3 slice from k to k+3 :RtWYY+Y2 take the slice from Y-1 or 0 to Y+2 for each line s join, this gives the 3x3 rectangle (or smaller on the border) - K remove all "*"s l take the length +K "*" + ^ - Z remove Z from this string h and take the first char (if cell=mine take the number, otherwise take the number) s join the chars of one line j join by newlines ``` [Answer] # Ruby, 119 ``` ->s{w=1+s.index(' ') s.size.times{|c|t=0;9.times{|i|(s+?**w*2)[c+i/3*w-w+i%3-1]<?0||t+=1} print [t,?*,' '][s[c]<=>?*]}} ``` Ungolfed in test program: ``` f=->s{ w=1+s.index("\n") #width of board s.size.times{|c| #iterate through input t=0; #number of digits surrounding current cell 9.times{|i| #iterate through 3x3 box (centre must be * if this ever gets printed.) (s+"*"*w*2)[c+i/3*w-w+i%3-1]<"0"||t+=1 #copy of s has plenty of * appended to avoid index errors } #add 1 every time a number is found. print [t,"*","\n"][s[c]<=>"*"] #if * print t. if after * in ACSII it's a number, print *. if before, it's \n, print \n } } f['**212*32 333*33** 1*22*333 222222*1 *33*2232 2**22*2*'] ``` [Answer] # Octave, 76 ``` m=@(s)char(conv2(b=(cell2mat(strsplit(s)'))~='*',ones(3),'same').*~b-6*b+48) ``` ### Explanation * Convert input string to matrix of strings using `strsplit` and `cell2mat`. * Get the logical matrix containing `1` where there is no `*` in the original matrix. * Take its convolution with a 3x3 matrix of 1's. * Mask it with the inverse logical matrix and put `*` in place of the mask. * Note: Cells with no mine neighbors are represented as `0`. ### Execution ``` >> m(['**100' 10 '34321' 10 '*2**1']) %// `10` is newline ans = 24*** ***** 3*44* >> m(['24***' 10 '*****' 10 '3*44*']) ans = **100 34321 *2**1 ``` ]
[Question] [ [![](https://i.stack.imgur.com/BN6hG.png "colors.rgb(\"blue\") yields \"#0000FF\". colors.rgb(\"yellowish blue\") yields NaN. colors.sort() yields \"rainbow\"")](https://xkcd.com/1537/) > > colors.rgb("blue") yields "#0000FF". colors.rgb("yellowish blue") yields NaN. colors.sort() yields "rainbow" > > > Using the rules set out in the image and its title text (quoted here), create a program that accepts all the given input and displays the appropriate output. * Input can be taken with stdin or nearest equivalent. There should be a line like `[n]>` on which to type it, and `n` increases by 1 each command. It should start at 1. * The result should be displayed using stdout or nearest equivalent. There should be a `=>` on each line of output. All 13 conditions, plus the 3 in the title (quoted) must work. This is code golf, so shortest answer wins. [Answer] # Python 3, 700 698 697 689 683 639 611 Tabs as indentation. ``` from ast import* E=literal_eval O='=>%s\n' P=print I=int def Q(a):P(O%a) def W(a):Q('"%s"'%str(a)) def gb(a):W(_ if'y'in a else'#0000FF') def t():W('rainbow') def FLOOR(n):P(O%'|'*3+(O%'|{:_^10}').format(n)) def RANGE(*a):Q([('"','!',' ','!','"'),(1,4,3,4,5)][len(a)]) c=0 while 1: try: c+=1;A,*B=input('[%d]>'%c).split('+') if not A:W(c+I(B[0])) elif A=='""':Q("'\"+\"'") elif B: A=E(A);B=E(B[0]) if A==B:Q('DONE') elif type(A)==list:Q(A[-1]==B-1) elif type(B)==list:W([I(A)]) else:W(A+I(B)) else:eval(A.lstrip('colrs.')) except:Q('Na'+['N','P','N.%s13'%('0'*13)][('-'in A)+len(B)]) ``` *Since this uses a bare Except you can't Ctrl-C it. Ctrl-Z and kill %% work though* Some of the conditions are generalized and others will only work with exact input. 1. `A+"B"` will work with any A and B not just when `A == B` 2. `"A"+[]` will work for any A that can be converted to an int (Includes hex and binary strings e.g 0xff and 0b01010) 3. `(A/0)` will work for any A, Eval Causes `DivideByZeroError` which is handled in the except 4. `(A/0)+B` will work with any A or B. `literal_eval` (E) raises an error. 5. `""+""` only works for the + sign. Anything else will print NaN, NaP or NaN.00... 6. `[A, B, C]+D` works by checking that `D == C+1` so will work for any length of list and any numbers. 7. ^^ 8. `2/(2-(3/2+1/2))`, Anything that fails to parse that has `-` with a `+` somewhere after it will output NaN.000...13 9. `RANGE(" ")` Hardcoded 10. `+A` will work for any A. Ouputs `"current_line_number+A"` 11. `A+A` works for any A as long as they are the same and are bulitin python types 12. `RANGE(1,5)` Hardcoded. 13. `FLOOR(A)` works for any A. 14. `colors.rgb("blue")` The lstrip in eval turns this in `gb("blue")` which has a hardcoded response. 15. `colors.rgb("yellowish blue")` The lstrip in eval turns this in `gb("yellowish blue")` which attempts to use a non existent variable if `y` is present in the arguement causing an error which the except turns into NaN 16. `colors.sort()` The lstrip turns this into `t()` which has a hardcoded response. ![](https://i.stack.imgur.com/eq4Zp.png) ![](https://i.stack.imgur.com/c3Vk8.png) *Brainsteel pointed out an error in my assumption for rule 10.* ![](https://i.stack.imgur.com/eSW72.png) [Answer] # Python, 1110 bytes Operator overloading isn't evil, right?? ``` from re import* class V(str): def __add__(s,r):return s[:-1]+chr(ord(s[-1])+r) class S(str): def __str__(s):return "'"+s+"'"if '"'in s else'"'+s+'"' def __repr__(s):return str(s) def __add__(s,r):s=str(s)[1:-1];return S('['+s+']'if type(r)==L else '"+"' if(s,r)==('','')else s+r) class I(int): def __add__(s,r):return type(r)(int(s)+int(r))if s!=r else V('DONE') def __div__(s,r):return N if r==0 else int(s)/int(r) def __pos__(s):return s+c*10 def __mul__(s,r):return V('NaN.'+'0'*13+'13')if r==1 else int(s)*int(r) class L(list): def __add__(s,r):return V(str(r==s[-1]+1).upper()) def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b]) def FLOOR(n):return V('|\n|\n|\n|___%s___'%n) def colorsrgb(c): m={'blue':V('#0000FF')} return m.get(c,N) def colorssort():return V('rainbow') N=V('NaN') c=1 while True: try:l=raw_input('[%d] >'%c) except:break l=sub(r'(?<!"|\.)(\d+)(?!\.|\d)',r'I(\1)',l) l=sub(r'"(.*?)"',r'S("\1")',l) l=sub(r'\[(.*?)\]',r'L([\1])',l) l=sub(r'/\(','*(',l) l=sub('s\.','s',l) for x in str(eval(l)).split('\n'):print ' =',x c+=1 ``` My goal wasn't as much winning (obviously) as it is making it as generic as possible. Very little is hardcoded. Try stuff like `RANGE(10)`, `9*1`, and `RANGE("A")`, `(2/0)+14`, and `"123"` for fun results! Here's a sample session: ``` ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >1+1 = DONE [2] >2+"2" = "4" [3] >"2"+2 Traceback (most recent call last): File "xktp.py", line 31, in <module> for x in str(eval(l)).split('\n'):print ' =',x File "<string>", line 1, in <module> File "xktp.py", line 7, in __add__ def __add__(s,r):s=str(s)[1:-1];return S('['+s+']'if type(r)==L else '"+"' if(s,r)==('','')else s+r) TypeError: cannot concatenate 'str' and 'I' objects ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >ryan@DevPC-LX:~/golf/xktp$ ryan@DevPC-LX:~/golf/xktp$ ryan@DevPC-LX:~/golf/xktp$ ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >2+"2" = "4" [2] >"2"+[] = "[2]" [3] >"2"+[1, 2, 3] = "[2]" [4] >(2/0) = NaN [5] >(2/0)+2 = NaP [6] >(2/0)+14 = Na\ [7] >""+"" = '"+"' [8] >[1,2,3]+2 = FALSE [9] >[1,2,3]+4 = TRUE [10] >[1,2,3,4,5,6,7]+9 = FALSE [11] >[1,2,3,4,5,6,7]+8 = TRUE [12] >2/(2-(3/2+1/2)) = NaN.000000000000013 [13] >9*1 = NaN.000000000000013 [14] >RANGE(" ") = (" ", "!", " ", "!") [15] >RANGE("2") = ("2", "3", "2", "3") [16] >RANGE(2) Traceback (most recent call last): File "xktp.py", line 31, in <module> for x in str(eval(l)).split('\n'):print ' =',x File "<string>", line 1, in <module> File "xktp.py", line 15, in RANGE def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b]) TypeError: ord() expected string of length 1, but I found ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >ryan@DevPC-LX:~/golf/xktp$ # oops ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >RANGE("2") = ("2", "3", "2", "3") [2] >RANGE(2*1) Traceback (most recent call last): File "xktp.py", line 31, in <module> for x in str(eval(l)).split('\n'):print ' =',x File "<string>", line 1, in <module> File "xktp.py", line 15, in RANGE def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b]) TypeError: ord() expected a character, but string of length 19 found ryan@DevPC-LX:~/golf/xktp$ python xktp.py # oops again [1] >RANGE(1,20) = (1, 19, 3, 19, 3, 19, 3, 19, 3, 19, 20) [2] >RANGE(1,5) = (1, 4, 3, 4, 5) [3] >RANGE(10,20) = (10, 19, 12, 19, 12, 19, 20) [4] >RANGE(10,200) = (10, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 200) [5] >+2 = 52 [6] >+"99" Traceback (most recent call last): File "xktp.py", line 31, in <module> for x in str(eval(l)).split('\n'):print ' =',x File "<string>", line 1, in <module> TypeError: bad operand type for unary +: 'S' ryan@DevPC-LX:~/golf/xktp$ python xktp.py # oops again and again! [1] >FLOOR(200) = | = | = | = |___200___ [2] >2+2 = DONE [3] >3+# Traceback (most recent call last): File "xktp.py", line 31, in <module> for x in str(eval(l)).split('\n'):print ' =',x File "<string>", line 1 I(3)+# ^ SyntaxError: unexpected EOF while parsing ryan@DevPC-LX:~/golf/xktp$ python xktp.py [1] >3+3 = DONE [2] >ryan@DevPC-LX:~/golf/xktp$ ``` [Answer] # C, 412 bytes This is basically hardcoded, but all the other answers so far were missing something... ``` i;char b[99];main(){for(;;){printf("[%d]>",abs(++i));gets(b);i-=b[2]==50?26:0;printf("=>");puts(*b==82?b[6]==34?"('\"',\"!\",\" \",\"!\",'\"')":"(1,4,3,4,5)":*b==70?"|\n=>|\n=>|\n=>|___10.5___":*b==43?"12":*b==91?b[8]==50?"FALSE":"TRUE":*b==34?b[1]==34?"'\"+\"'":"\"[2]\"":*b==40?b[5]==43?"NaP":"NaN":*b==99?b[7]=='s'?"rainbow":b[12]==98?"#0000FF":"NaN":b[1]==43?b[2]==34?"\"4\"":"DONE":"NaN.000000000000013");}} ``` Output: ``` [1]>2+"2" =>"4" [2]>"2"+[] =>"[2]" [3]>(2/0) =>NaN [4]>(2/0)+2 =>NaP [5]>""+"" =>'"+"' [6]>[1,2,3]+2 =>FALSE [7]>[1,2,3]+4 =>TRUE [8]>2/(2-(3/2+1/2)) =>NaN.000000000000013 [9]>RANGE(" ") =>('"',"!"," ","!",'"') [10]>+2 =>12 [11]>2+2 =>DONE [14]>RANGE(1,5) =>(1,4,3,4,5) [13]>FLOOR(10.5) =>| =>| =>| =>|___10.5___ ``` [Answer] ## Python 3, 298 Everything is hardcoded, but the input is turned into a number that is then converted to a string and looked up in a large string that contains all these numbers followed by their answers. ``` B="""53"#0000FF"~62DONE~43NaN.000000000000013~25(1,4,3,4,5)~26"rainbow"~49"4"~21"[2]"~29FALSE~15|*|*|*|___10.5___~17'"+"'~1212~60('"',"!"," ","!",'"')~24NaN~31TRUE~64NaN~76NaP""" i=0 while 1:i+=1;s=input("[%s]>"%i);print("=>"+B[B.find(str(sum(map(ord,s))%81))+2:].split("~")[0].replace("*","\n=>")) ``` [Answer] # Python 3, 542 484 bytes Since there was no mention of absolute hardcoding here's my solution. ``` a={'2+"2"':'"4"','"2"+[]':'"[2]"',"(2/0)":"NaN","(2/0)+2":"NaP",'""+""':"'\"+\"'","[1,2,3]+2":"FALSE","[1,2,3]+4":"TRUE","2/(2-(3/2+1/2))":"NaN.000000000000013",'RANGE(" ")':'(\'"\',"!"," ","!",\'"\')',"+2":"12","2+2":"DONE","RANGE(1,5)":"(1,4,3,4,5)","FLOOR(10.5)":"|\n|\n|\n|___10.5___",'colors.rgb("blue")':'"#0000FF"','colors.rgb("yellowish blue")':"NaN","colors.sort()":'"rainbow"'} i=1 while 1:b=a[input("[%i]>"%i).replace("\t","")].split("\n");print("=> "+"\n=> ".join(b));i+=1 ``` ]
[Question] [ It is ancient knowledge that every non-negative integer can be rewritten as the sum of four squared integers. For example the number 1 can be expressed as \$0^2+0^2+0^2+1^2\$. Or, in general, for any non-negative integer \$n\$, there exist integers \$a,b,c,d\$ such that $$n = a^2+b^2+c^2+d^2$$ [Joseph-Louis Lagrange](https://pg-astro.fr/grands-astronomes/le-grand-siecle/joseph-louis-lagrange.html) proved this in the 1700s and so it is often called [Lagrange's Theorem](https://www.britannica.com/science/Lagranges-four-square-theorem). This is sometimes discussed in relation to quaternions โ€“ a type of number discovered by [William Hamilton](https://www.maths.tcd.ie/pub/HistMath/People/Hamilton/) in the 1800s, represented as $$w+x\textbf{i}+y\textbf{j}+z\textbf{k}$$ where \$w,x,y,z\$ are real numbers, and \$\textbf{i}, \textbf{j}\$ and \$\textbf{k}\$ are distinct imaginary units that don't multiply commutatively. Specifically, it is discussed in relation to squaring each component of the quaternion $$w^2+x^2+y^2+z^2$$This quantity is sometimes called the [norm, or squared norm](https://math.stackexchange.com/questions/3174308/norm-of-quaternion), or also [quadrance](https://www.youtube.com/watch?v=g22jAtg3QAk). Some [modern proofs](https://www2.gwu.edu/~spwm/erin_alissa.pdf) of Lagrange's Theorem use quaternions. [Rudolf Lipschitz](http://www-history.mcs.st-andrews.ac.uk/Biographies/Lipschitz.html) studied quaternions with only integer components, called Lipschitz quaternions. Using quadrance, we can imagine that every Lipschitz quaternion can be thought of having a friend in the integers. For example quaternion \$0+0\textbf{i}+0\textbf{j}+1\textbf{k}\$ can be thought of as associated with the integer \$1=0^2+0^2+0^2+1^2\$. Also, if we go backwards, then every integer can be thought of as having a friend in the Lipschitz quaternions. But there is an interesting detail of Lagrange's theorem โ€“ the summation is not unique. Each integer may have several different sets of four squares that can be summed to create it. For example, the number 1 can be expressed in 4 ways using non-negative integers (let us only consider non-negatives for this challenge): $$1=0^2+0^2+0^2+1^2$$ $$1=0^2+0^2+1^2+0^2$$ $$1=0^2+1^2+0^2+0^2$$ $$1=1^2+0^2+0^2+0^2$$ The summands are always squares of 0, or 1, but they can be in different positions in the expression. For this challenge, let us also "sort" our summands lowest to highest, to eliminate duplicates, so that we could consider, for this exercise, that 1 only has one way of being represented as the sum of four squares: $$1=0^2+0^2+0^2+1^2$$ Another example is the number 42, which can be expressed in four ways (again, only considering non-negative a,b,c,d, and eliminating duplicate component arrangements) $$42=0^2+1^2+4^2+5^2$$ $$42=1^2+1^2+2^2+6^2$$ $$42=1^2+3^2+4^2+4^2$$ $$42=2^2+2^2+3^2+5^2$$ What if we imagine each of these different ways of expressing an integer as being associated to a specific quaternion? Then we could say the number 42 is associated with these four quaternions: $$0+1\textbf{i}+4\textbf{j}+5\textbf{k}$$ $$1+1\textbf{i}+2\textbf{j}+6\textbf{k}$$ $$1+3\textbf{i}+4\textbf{j}+4\textbf{k}$$ $$2+2\textbf{i}+3\textbf{j}+5\textbf{k}$$ If we imagine the standard computer graphics interpretation of a quaternion, where \$\textbf{i}\$, \$\textbf{j}\$ and \$\textbf{k}\$ are vectors in three dimensional [Euclidean](https://play.google.com/books/reader?id=5lN1sy51SwYC&hl=en&pg=GBS.PA6) space, and so the \$x\$, \$y\$ and \$z\$ components of the quaternion are 3 dimensional [Cartesian](https://mathinsight.org/cartesian_coordinates) coordinates, then we can imagine that each integer, through this thought process, can be associated with a set of 3 dimensional coordinates in space. For example, the number 42 is associated with the following four \$(x,y,z)\$ coordinates: $$(1,4,5),(1,2,6),(3,4,4),(2,3,5)$$ This can be thought of as a point cloud, or a set of points in space. Now, one interesting thing about a set of finite points in space is that you can always draw a minimal bounding box around them โ€“ a box that is big enough to fit all the points, but no bigger. If you imagine the box as being an ordinary box aligned with the \$x,y,z\$ axes, it is called an [axis-aligned bounding box](https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection). The bounding box also has a volume, calculable by determining its width, length, and height, and multiplying them together. We can then imagine the volume of a bounding box for the points formed by our quaternions. For the integer 1, we have, using the criteria of this exercise, one quaternion whose quadrance is 1, \$0+0\textbf{i}+0\textbf{j}+1\textbf{k}\$. This is a very simple point cloud, it only has one point, so it's bounding box has volume 0. For the integer 42, however, we have four quaternions, and so four points, around which we can draw a bounding box. The minimum point of the box is \$(1,2,4)\$ and the maximum is \$(3,4,6)\$ resulting in a width, length, and height of 2, 2, and 2, giving a volume of 8. Let's say that for an integer \$n\$, the qvolume is the volume of the axis-aligned bounding box of all the 3D points formed by quaternions that have a quadrance equal to \$n\$, where the components of the quaternion \$w+x\textbf{i}+y\textbf{j}+z\textbf{k}\$ are non-negative and \$w<=x<=y<=z\$. Create a program or function that, given a single non-negative integer \$n\$, will output \$n\$'s qvolume. Examples: ``` input -> output 0 -> 0 1 -> 0 31 -> 4 32 -> 0 42 -> 8 137 -> 96 1729 -> 10032 ``` This is code-golf, smallest number of bytes wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~67~~ 58 bytes ``` Volume@BoundingRegion[Rest/@PowersRepresentations[#,4,2]]& ``` [Try it online!](https://tio.run/##HYuxCsMgFAD3fMWDQiYhjRFCh4LkC4JDFusg7cMK9VnU0KH0263tcMctF2y5Y7DFX211cIZL3eJjDyiXuNPNk1PofCStMJdBrvGFKSt8JsxIpW2Rsj4wwbgxfV2TpyKdFLzr/q3dIOF9ZDAymH5wBqIxTnPTzE8fU78 "Wolfram Language (Mathematica) โ€“ Try It Online") ``` ...& Pure function: PowersRepresentations[#,4,2] Get the sorted reprs. of # as sums of 4 2nd powers Rest/@ Drop the first coordinate of each BoundingRegion[...] Find the bounding region, a Cuboid[] or Point[]. By default Mathematica finds an axis-aligned cuboid. Volume Find volume; volume of a Point[] is 0. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ลปล“ฤ‹4ยฒSโผษ—ฦ‡โธZแธŠแนขโ‚ฌIยงP ``` **[Try it online!](https://tio.run/##AS4A0f9qZWxsef//xbvFk8SLNMKyU@KBvMmXxofigbha4biK4bmi4oKsScKnUP///zQy "Jelly โ€“ Try It Online")** (pretty slow - make it fast enough for all the test cases [with a leading `ยฝ`](https://tio.run/##y0rNyan8///Q3qO7j04@0m1yaFPwo8Y9J6cfa3/UuCPq4Y6uhzsXPWpa43loecD/w@1A1v//0YY6CsYgbKSjYALEhsbmQMLcyDIWAA "Jelly โ€“ Try It Online")) ### How? ``` ลปล“ฤ‹4ยฒSโผษ—ฦ‡โธZแธŠแนขโ‚ฌIยงP - Link: non-negative integer, n e.g. 27 ลป - zero-range [0,1,2,...,27] 4 - literal four 4 ล“ฤ‹ - combinations with replacement [[0,0,0,0],[0,0,0,1],...,[0,0,0,27],[0,0,1,1],[0,0,1,2],...,[27,27,27,27]] ฦ‡ - filter keep those for which: e.g.: [0,1,1,5] ษ— - last three links as a dyad: ยฒ - square (vectorises) [0,1,1,25] S - sum 27 โผ โธ - equal to? chain's left argument, n 1 - -> [[0,1,1,5],[0,3,3,3],[1,1,3,4]] Z - transpose [[0,0,1],[1,3,1],[1,3,3],[5,3,4]] แธŠ - dequeue [[1,3,1],[1,3,3],[5,3,4]] แนขโ‚ฌ - sort each [[1,1,3],[1,3,3],[3,4,5]] I - incremental differences (vectorises) [[ 0,2 ],[ 2,0 ],[ 1,1 ]] ยง - sum each [2,2,2] P - product 8 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~132~~ 123 bytes ``` z=zipWith (!)=foldr1.z h n=[0..n] f n|p<-[[c,b,a]|a<-h n,b<-h a,c<-h b,d<-h c,a^2+b^2+c^2+d^2==n]=product$z(-)(max!p)$min!p ``` [Try it online!](https://tio.run/##ZYrRCoIwFIbvfYojeKG0iVoghXuArroRuhCFuSWOdBvTKIbvbhoEYQd@Pv7vPy0d7reum2dLrNBXMbaO7wakUR03cWidFiQpojCUpdOAnHSGi4KhGtFyohleVlSvoIitqBFfwRCtkl29hC3hVUKILIk2ij/Y6FkfB35PX64OvF5IV889FZJw5cBy2gg5ggcNRJseb/r@TyQbcdiKeJ9@DMaQKwVDp57QKAP5@QIn/zv9/KfJcX4D "Haskell โ€“ Try It Online") Pretty straightforward solution. Brute force all the possible solutions by iterating over all the values from 0 to n (way overkill but shorter bytecount). I output the point as a list so we can use @Lynn's magic `(!)` operator. That operator collapses each dimension with the function on the left side so `max!p` returns a list of size 3 which consists of the maximums along each dimension and `min!p` does the same for minimum. Then we just find the minimum size in each dimension (by subtracting the min value from the max with `z(-)`) and multiply them together. Thanks a lot to @Lynn for taking off 9 bytes with some folding zip magic! [Answer] # [Sledgehammer](https://github.com/tkwa/Sledgehammer) 0.2, 12 bytes ``` โกŒโขŽโฃŸโกŠโข˜โฃšโกโกจโ โ โก‡โ จ ``` Use with Mathematica 11.2 and [this version](https://github.com/tkwa/Sledgehammer/tree/137f71a5e3f4ddd8d008f0811e3d1d3bea7ebb5e) of Sledgehammer, which predates the challenge. See edit history for a version that works in version 0.3, which has a GUI and generates a Mathematica expression. This pushes the input to the stack and calls the sequence of commands ``` {intLiteral[4], intLiteral[2], call["PowersRepresentations", 3], call["Thread", 1], call["Rest", 1], call["Thread", 1], call["BoundingRegion", 1], call["Volume", 1]} ``` which is equivalent to evaluating the following Wolfram code derived from my [Wolfram Language answer](https://codegolf.stackexchange.com/a/186161/39328): ``` Volume[BoundingRegion[Thread@Rest@Thread@PowersRepresentations[#, 4, 2]]]& ``` [Try it online!](https://tio.run/##LY29CoMwFEZ3n@JCoVOgVQvSghB8ArE/S5oh6CUGNJHkSofSZ09j6XAOZ/jgmxWNOCsyvYp3u3hH2BO/To6yTULCpYZf5TLTUMMzPty0zigat9rBWN2hNs6K2@hRDbzDQPzfrXuhDx0uHgNaSifOBrFjcGJQSCn3sfXGktAHDu8jg5xBuVGkRSIvq6SqOH9k/AI "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 138 bytes ``` q=lambda n,x=0,*t:[t]*(n==0)if t[3:]else q(n-x*x,x,x,*t)+q(n,x+1,*t+(0,)*(x>n)) p=1 for l in zip(*q(input()))[:3]:p*=max(l)-min(l) print p ``` [Try it online!](https://tio.run/##FY5BCoMwFET3OUVw9X@MkGihEEgvIi5sGzEQv9GmNO3lbWQG3rzdxG@aV2qPz@yD49q47B5VVR2bDeNyf46cZLZKimT6NAggaxX6iae@M4MLL8c3oCaLLM@IhHVxmWtddg1KooB8I0QWrWbTuvPAPfGfjyA28BTfCRCxN91gorDLmCFgs3gqYHH3lHg8zjuKadaVtuzSMt1d/w "Python 2 โ€“ Try It Online") Recursively generates the reverse-sorted quaternions with the given norm, then takes the product between the max and min of all possible values in the first three indices. `itertools` might have had a shot if it didn't use ridiculously long names like `itertools.combinations_with_replacement` **[Python 2](https://docs.python.org/2/), 161 bytes** ``` from itertools import* n=input();p=1 for l in zip(*[t[1:]for t in combinations_with_replacement(range(n+1),4)if sum(x*x for x in t)==n]):p*=max(l)-min(l) print p ``` [Try it online!](https://tio.run/##FY5RCsIwEAX/c4qlX0lVMFUQKjmJiNSS2oVks6RbjF6@GngwMDDw@CNzom57zxg82N4XPzZNs005RUDxWVIKC2DklKVV5JB4FW2u7KyaUoYASPBF1u1Nbra/VyfVjSk@kQbBRMvjjTI/sucwjD56Ep0HenlNO2v2Z4MTLGvUpS1Q81JzMc7R3fTcujgUHcwhIv2hOCMJ8FZfHpVVp/86de6UPV1@ "Python 2 โ€“ Try It Online") This is why [`itertools` is never the answer](https://codegolf.meta.stackexchange.com/a/5603/20260). [Answer] # JavaScript (ES6), ~~148~~ 143 bytes ``` n=>(r=[[],[],[]]).map(a=>p*=a.length+~a.indexOf(1),(g=(s,k=0,a=[])=>a[3]?s||r.map(r=>r[a.pop()]=p=1):g(s-k*k,k,[...a,++k],k>s||g(s,k,a)))(n))|p ``` [Try it online!](https://tio.run/##fcxBbsIwEIXhfU/hpYc4Jk5QKUjjHqEHsLwYQWKoU9uyEeoi6tXTlgVIICG93af/fdKZyi4f06kOcd/PA84BNc9ojBWXWZBflDihTgskOfbBnQ7VD8lj2PffHwNXILhDXoTHRhAaC6jJdPa9TFO@tBl1NiRTTBwsJlSwdbzUfuGFF0ZKSaKqvBVe/yXu/0kQAPAAMKV5F0OJYy/H6PjAGWMNAFsuWa1Z8/KA6gl2N1w9YvukXN3w7R5Vt77i5vVO1brdXFU1TdfOvw "JavaScript (Node.js) โ€“ Try It Online") ## Commented We initialize an array \$r\$ with 3 empty arrays. ``` r = [ [], [], [] ] ``` For each valid value of \$x\$, we will set to \$1\$ the value at \$x+1\$ in the first array. Ditto for \$y\$ and \$z\$ with the 2nd and 3rd arrays respectively. The dimensions of the bounding box will be deduced from the distance between the first and the last entry set to \$1\$ in these arrays. ### Step 1 To fill \$r\$, we use the recursive function \$g\$. ``` g = ( // g is a recursive function taking: s, // s = current sum, initially set to the input n k = 0, // k = next value to be squared a = [] // a[] = list of selected values ) => // a[3] ? // if we have 4 values in a[]: s || // if s is equal to zero (we've found a valid sum of 4 squares): r.map(r => // for each array r[] in r[]: r[a.pop()] // pop the last value from a[] = p = 1 // and set the corresponding value in r[] to 1 // (also initialize p to 1 for later use in step 2) ) // end of map() : // else: g( // do a recursive call: s - k * k, // subtract kยฒ from s k, // pass k unchanged [...a, ++k], // increment k and append it to a[] k > s || // if k is less than or equal to s: g(s, k, a) // do another recursive call with s and a[] unchanged ) // end of outer recursive call ``` ### Step 2 We can now compute the product \$p\$ of the dimensions. ``` r.map(a => // for each array a[] in r[]: p *= // multiply p by: a.length + // the length of a[] ~a.indexOf(1) // minus 1, minus the index of the first 1 in a[] ) | p // end of map(); return p ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 229 bytes ``` a=>{uint b=0,c=~0U,d,e,f=0,g=0,h=0,i=c,j=c,k=c;for(;b*b<=a;b++)for(c=b;c*c<=a;c++)for(d=c;d*d<=a;d++)for(e=d;e*e<=a;e++)if(b*b+c*c+d*d+e*e==a){f=c>f?c:f;g=d>g?d:g;h=e>h?e:h;i=c<i?c:i;j=d<j?d:j;k=e<k?e:k;}return(f-i)*(g-j)*(h-k);} ``` [Try it online!](https://tio.run/##Zc49b4QwDAbgvb@iYwJBuo9Kp2Ictk5dq87gOCRE4iQOptP1r1NHuqVlsBU/rxOFbhXd4vaxTtSscVpMbtbj1qG95/NrjwdD@HP4Ms6w8TINUkEqIplRKiGBv84K@qJvsIO@LHWeCXuggjLRk5ysusJlck9idMAFZ2Kh6JU8U8q9UhZLSRA7ffdI1rdUexjQ2aF19QAB2YaW6wDykyZKGmFE14ySjpCQmyRpgsfMyzpPyldRF2qoRumhShoeG7x8z3Hhzzix8uqo9V847@X0X952cjxfdnQ5vYttvw "C# (Visual C# Interactive Compiler) โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` ร4รฃส’nOQ}โ‚ฌ{ฮถยฆฮต{ยฅO}P ``` [Try it online!](https://tio.run/##ASgA1/9vc2FiaWX//3TDnTTDo8qSbk9RfeKCrHvOtsKmzrV7wqVPfVD//zQy "05AB1E โ€“ Try It Online") Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/186153/6484). [Answer] # [Haskell](https://www.haskell.org/), 104 bytes ``` n%i=(-).maximum<*>minimum$[t!!i|t<-mapM(:[0..n])[0..3],sum(map(^2)t)==n,scanr1 max t==t] f n=n%0*n%1*n%2 ``` [Try it online!](https://tio.run/##FYxBCoMwFET3PcUXFBKJYlQoFNMb9ASSQhBtg/5PMBG66NmbxsXjDcMwb@PXedtipMIqVvEazcfigUN5R0tnyseQZfYbhgqNe7Db2NQ1aX6q08IfyFLPni0PXCkSfjK0S0g3EJQK@rIAKSqakgqZaCMaS6DA7ZYC5GnoYEkOZp2hT2FsBEgB3UkroE/I7qrjb1o28/Kxmpz7Aw "Haskell โ€“ Try It Online") *Thanks to Delfad0r for -1 byte and Lynn for 3 bytes* To multiply the three dimensions, it turns out shortest to just write the product `f n=n%0*n%1*n%2` than to use any sort of loop. Here, `n%i` is the difference between the min and max of the `i`'th coordinate values, which are extracted with indexing `!!i`. To generate the valid four-tuples, we take lists of four numbers from `[0..n]` whose squares sum to `n` and are in decreasing order. We check the reverse-sortedness of `t` with `scanr1 max t==t`, which sees if the running maximum of the reverse is itself, as Haskell doesn't have a built-in sort without a costly import. I tried various ways to recursively generate the four-tuples like in my Python answers, but they were all longer than this brute-force generate-and-filter way. [Answer] # [jq](https://stedolan.github.io/jq/), 164 bytes ``` . as$i|[range(.)]|[combinations(4)|select(map(.*.)|add==$i)|sort]|unique|[transpose[1:][]|sort|[.[:-1],.[1:]]|transpose|map(.[1]-.[0])|add//0]|reduce.[]as$j(1;.*$j) ``` [Try it online!](https://tio.run/##PY5BCoMwEEWv0oWLROpoSqFg8STDLFIdSqQmmsTd3D21Lrr97/N481YKXGyqnGC0/s0KNAmOYXk5b7MLPqm7lsQfHrNa7KqgBi12moahcgcIMZPs3m07C@ZDkdaQGE1PSCcVBOwbQ1f4jST/j5w2NNQAdnQ627YjiTztIwPSUTUr84S6mnUpt8cX "jq โ€“ Try It Online") The pairwise reduction can probably be better. For lower numbers, null is substituted with `0` for consistent output. Idea from Jonathan Allan's answer. -1 from ovs. ]
[Question] [ # Mรถlkky [Mรถlkky](https://en.wikipedia.org/wiki/M%C3%B6lkky) is a Finnish throwing game. The players use a wooden pin (also called "mรถlkky") to try to knock over wooden pins of almost similar dimensions with the throwing pin, marked with numbers from 1 to 12. The initial position of the pins is as follows: ``` (07)(09)(08) (05)(11)(12)(06) (03)(10)(04) (01)(02) ``` *This description and the rules below are based on [Wikipedia](https://en.wikipedia.org/wiki/M%C3%B6lkky).* # Simplified Mรถlkky rules 1. Knocking over **one pin** scores the number of points marked on the pin. 2. Knocking **2 or more pins** scores the number of pins knocked over (e.g., knocking over 3 pins scores 3 points). 3. The aim of the game is to reach exactly **50** points. Scoring more than 50 is penalized by setting the score back to **25** points. 4. For the purpose of this challenge, we will make the assumption that the pins are *always* in the exact order described above. (In a real game, the pins are stood up again after each throw in the location where they landed.) All other Mรถlkky rules are ignored and only a single player is considered. # Input A non-empty list of lists of 12 booleans. Each list of booleans describes the outcome of a throw: **1** if the pin was knocked over and **0** otherwise. The booleans are given in the exact order of the pins, from top left to bottom right: **7**, **9**, **8**, **5**, **11**, **12**, **6**, **3**, **10**, **4**, **1**, **2**. # Output The score after all throws described in the input, calculated by applying rules **1**, **2** and **3**. # Detailed example Let's consider the following input: ``` // 07 09 08 05 11 12 06 03 10 04 01 02 [ [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ], // scores 5 (rule #1) [ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ], // scores 2 (rule #2), total: 7 [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ], // scores 7, total: 14 [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], // scores 12, total: 26 [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], // scores 12, total: 38 [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ], // scores 11, total: 49 [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], // scores 7, total: 56 -> 25 (rule #3) [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ] // scores 2, total: 27 ``` The expected output is **27**. # Challenge rules * You may take input in any reasonable format. Instead of lists of booleans, you can use integers where the most significant bit is the pin #7 and the least significant bit is the pin #2. In this format, the above example would be passed as `[ 256, 2304, 127, 64, 64, 128, 2048, 3072 ]`. * The input list may contain throws where no pin at all is knocked over, in which case the score is let unchanged. * You don't have anything special to do when the score reaches *exactly* 50 points. But you can assume that no other throw will follow when it happens. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. # Test cases Using lists of integers as input: ``` [ 0 ] --> 0 [ 528 ] --> 2 [ 4095 ] --> 12 [ 64, 0, 3208 ] --> 16 [ 16, 1907, 2048 ] --> 18 [ 2023, 2010, 1, 8 ] --> 29 [ 1726, 128, 35, 3136, 1024 ] --> 34 [ 32, 32, 2924, 2, 256, 16 ] --> 28 [ 64, 64, 2434, 1904, 3251, 32, 256 ] --> 25 [ 3659, 2777, 2211, 3957, 64, 2208, 492, 2815 ] --> 25 [ 2047, 1402, 2, 2599, 4, 1024, 2048, 3266 ] --> 50 [ 256, 2304, 127, 64, 64, 128, 2048, 3072 ] --> 27 [ 16, 8, 128, 1, 2048, 1, 2048, 513, 8, 3206 ] --> 30 ``` You can [follow this link](https://pastebin.com/LjjhDESQ) to get these test cases in Boolean format. [Answer] # [Python 2](https://docs.python.org/2/), ~~126 111 108~~ 104 bytes *-3 bytes thanks to Jonathan Allan* *-4 bytes thanks to Kaya!* ``` f=lambda A,t=0:t>50and f(A,25)or A and f(A[1:],t-~(sum(A[0])-1or 762447093078/12**A[0].index(1)%12))or t ``` [Try it online!](https://tio.run/##TVLBboMwDD3DV1idppIqbLGTEEBqpX4H40DVoVEVWrWZ1F326yyhoevBke33/J4TOP/Yr9NA49iuj02/2zew5XYtSrvRohn20CZbTpqdLrCFUFdY1tymv8n1u3eVqFmKDjcZKWVEIYXJ35FWKw@9dcP@85Yge0ViXsWOrTs76AaoKhBQ8ziqQFMeMiUKHdJMcRAcJIkZxIwDFsJwIKHmJgmSvoGOixweXEOeTblT0C5Q@lKQCrgkPgUV5Hx8oj0hezL3QUqqyVR5usYwpGeezHThamP8UoQeL7QJs25zDqrwAznqx77K4agEBdvCCaj7bveLeY9sNpjWIun9kYJwpsLNAlsYenqhPIA4449Eo5xg96ROPo7qMo4OsIZjd7VJ35yT8Avcyv9WN1gO7pv1jU1ufPkiUO2WrKKyZoxDx1gcnS@OBB2HxYdN082Ct8mBQRyPfw "Python 2 โ€“ Try It Online") Defines a recursive function that takes a 2D array of 1s and 0s and returns an integer value. Nothing too special in the construction, and I'm sure there's a simpler solution. ### Explanation: ``` f=lambda A,t=0: #Define the function, initialising t to 0 on the first iteration t>50and f(A,25) #If t>50 then iterate again with t=25 or #Else A and #If A exists f(A[1:], #Iterate again without the first list of A t-~ #And add to t, either (sum(A[0])-1 #The sum of all elements if that's not 1 or 762447093078/12**A[0].index(1)%12 #Else the appropriate pin value (black magic!) or t #Finally, if A is finished, just return t ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€œรฑโ‚ฌbแธทโ€™ล“?TLแธขแน–?ยตโ‚ฌ+25ยน>?50ษ—/ ``` A monadic link accepting a list of lists of ones and zeros (each of length 12) which returns an integer. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5zDGx81rUl6uGP7o4aZRyfbh/g83LHo4c5p9oe2AsW1jUwP7bSzNzU4OV3/////0dEGOiBoqGOACmN1uBSiDfHIIfiGyBBDDp8@XHKGON1igMOdWGVjYwE "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##LU@xTsNADP2V7nWF7bPvckuDmBlZUJQFiaXqD7BFLEiMILUglYWZhQGRSEytMvAZyY8E3wXpZPue3733bnO73d5N09gcTp/j/cfN0H6PzWv/XF5dDu370O3K45fhS9Zjty4Vf/dn01Iw@ouhfbSFndODlf7nvH8auhcbNwluDovVar0Ym7fraaoqrKFSLqzaW7XmBRAcY4LIA0UMwCjpysjOZkIgyOvARuACnIIjZzOyGO7YBIAjC1hTw/0sbIfFSRIVoyhlnqat8xqBQzAzJsOjhky3ICDRWAVpjiABSJCzcowg2TQnNDGfpJIjO3MgzhpecsiZgoHnjxUZpBn@b0oOkgz6uv4D "Jelly โ€“ Try It Online") (using the integer values given in the OP) ### How? This solution makes use of, `ล“?`, which given a number, n, and a list finds the nth lexicographical permutation of the list where the list defines the sort order. First we need to work out this `n`: ``` index: 1 2 3 4 5 6 7 8 9 10 11 12 value: 7 9 8 5 11 12 6 3 10 4 1 2 (as defined by the question) P: 11 12 8 10 4 7 1 3 2 9 5 6 (our permutation lookup array) ``` ...that is, `P` at index `i` is set to the original index of the value `i`. This `P` has a lexicographical index of **438,337,469** (that is, if you took all **12!** permutations of the numbers **1** to **12** and sorted them lexicographically, the **438,337,469th** would be `P`). This may be found [using Jelly's `ล’ยฟ` atom](https://tio.run/##y0rNyan8///opEP7////H21oqKNgaKSjYAGkDHQUTHQUzIEsHQVjHQWgqKWOgqmOglksAA "Jelly โ€“ Try It Online"). Both steps may be performed in one go [using the Jelly program `ฤ ล’ยฟ`](https://tio.run/##y0rNyan8///IgqOTDu3///9/tLmOgqWOgoWOgqmOgqEhEBvpKJjpKBgDWQY6CiZASkfBKBYA "Jelly โ€“ Try It Online") ``` โ€œรฑโ‚ฌbแธทโ€™ล“?TLแธขแน–?ยตโ‚ฌ+25ยน>?50ษ—/ - Link: list of lists of zeros and ones ยตโ‚ฌ - perform the monadic chain to the left for โ‚ฌach list: โ€œรฑโ‚ฌbแธทโ€™ - base 250 number = 438337469 ล“? - nth permutation (reorder the 1s and 0s to their pin values) T - truthy indices (get the pin values of the 1s) ? - if... แน– - ...condition: pop (length greater than 1 ?) L - ...then: length (the number of pins) แธข - ...else: head (the first (& only) pin value) / - reduce the resulting list of integers with: ษ— - last three links as a dyad: + - addition (add the two values together) 50 - literal fifty ? - if... > - ...condition: greater than (sum greater than 50 ?) 25 - ...then: literal twenty-five ยน - ...else: identity (do nothing - just yield the sum) ``` [Answer] # [Python 2](https://docs.python.org/2/), 90 bytes Heavily inspired by [Jo King's Python 2 answer](https://codegolf.stackexchange.com/a/164279/53748) and utilising [Kaya's base-12 representation comment](https://codegolf.stackexchange.com/questions/164270/lets-play-m%c3%b6lkky/164309#comment397640_164279) ``` t=0 for v in input():t+=sum(v)-1or 762447093078/12**v.index(1)%12;t=[t+1,25][t>49] print t ``` **[Try it online!](https://tio.run/##dY7LDsIgFET3/Qo2JtCichHFavBHCDs1sigl9bbRr8e68hHImc3kZJKJT7z1QaaERlTXfiAT8WFOHJGyAzbmPnZ0YkuYld5JpbRoN0Lv1yDrelr5cL48KLAFyCMaiw1wuXUWT6p1VRx8QIIpWSv4G@DiF8ctFM2nwTd/przJGyg8ENlvWefcCw "Python 2 โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##TVLbboMwDH3nK/IyAa3ZYichpBP9ir0hHnrJNqQWqjatuq/vnDBNRRFOjo/OceycfsL3NNJjN@19m@f5I7Qy@5zO4iaGkdfpGopyFZbt5XosbmWFnLI1aW2lU9I2b0iLxe11GPf@XmD5gvQe2i4sEcj0XVhr12en8zAGER4snyXF9rA5bveb1XaaDn4zfvhLyJIp8/yXP0cg2ned7KEz1PBfS2c41BokKJIRwhrQSQskdTySJMV7lICQ0paYQA0oAwoV7yVpxhWxAJAjDRwM4/UszIu00lFUM8Vg4pmYVbVxQNayGSHjzthE50JAO2Y1aFIJ2gJqSUnZOdDJNFXIYnWUio6k2AEpadQ6FTlTpKX5Yk0CcYb/gkEFUUbWfb/KBH9PDRSt6I6bU8EtBFHkMl8gLbfDyEPraNWXXYUxiKfZ/ve6T2LzmJ5gELmoqrXIIeX93e@K@E7Kxy8 "Python 2 โ€“ Try It Online") [Answer] # Pyth, ~~51~~ ~~48~~ 38 bytes ``` VQI>[[emailย protected]](/cdn-cgi/l/email-protection)"รฎO&"S12xN1J50=Z25;Z ``` Saved 10 bytes thanks to Jonathan Allan Takes input as a list of lists of booleans. [Try it here](https://pyth.herokuapp.com/?code=VQI%3E%3D%2BZ%3FqJsN1%40.PC%22%0F%C3%AEO%26%22S12xN1J50%3DZ25%3BZ&input=%5B+%5B+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1+%5D%2C+%5B+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D%2C+%5B+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0+%5D+%5D&debug=0) ### Explanation ``` VQI>[[emailย protected]](/cdn-cgi/l/email-protection)"รฎO&"S12xN1J50=Z25;Z VQ ; For each input... =+Z ... add to the total... ?q sN1 ... if one pin is down... @.PC"รฎO&"S12xN1 ... the score of that pin. J J ... otherwise, the count. I> 50 If we pass 50... =Z25 ... reset to 25. Z Output the total. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 28 bytes ``` vโ€ขCรžลธฮฑLฤ‡โ€ข13ะฒyOฮ˜myรOO25โ€šยฌ50โ€บรจ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7FHDIufD847uOLfR50g7kGNofGFTpf@5GbmVh/v9/Y1MHzXMOrTG1OBRw67DK/7/j4420FHARIbI3FgdBeyqUBSiqzLEqgOfWQitIFWGhFTRyCxDAmYRFxKGSAKGGApBIrGxAA "05AB1E โ€“ Try It Online") **Explanation** ``` v # for each boolean list in input โ€ขCรžลธฮฑLฤ‡โ€ข # push 13875514324986 13ะฒ # convert to a list of base-13 numbers yO # push the sum of y ฮ˜m # truthify and raise the pin-list to this number (0 or 1) yร # keep those which are true in the current list OO # sum the list and the stack 25โ€š # pair with 25 ยฌ50โ€บ # check if the first number is larger than 50 รจ # index into the pair with this result ``` [Answer] # [Perl 5](https://www.perl.org/), ~~74~~ 70 bytes ``` $\+=y/1//-1||/1/g&&(0,6,8,7,4,10,11,5,2,9,3,0,1)[pos];$\=25if++$\>50}{ ``` [Try it online!](https://tio.run/##TYtdDoIwEITfOUUDlWhYZIvWnxi8gScQQzQp2MRAQ8sDUa9uLfiAk0km386sEu2D20Bfe1pkWrWyNqU/Q5befKDFIei0IOYuNTENMUIbIkvSaVlXxC1FJdqxkbXqjKV5lPUJS5KYvV4uqzCcI2xgB1tYA0NgDDiksIcVOFicVaMvB5pnKZdlFNH8yPH9tBbZKBzS@wEORg8nsX@YGveFn0YZ2dTaxie@dBcbqy8 "Perl 5 โ€“ Try It Online") Takes input as a series of newline separated bitstrings. [Answer] # [Haskell](https://www.haskell.org/), 96 bytes ``` foldl(\s a->([s..50]++e)!!sum(last$zipWith(*)[7,9,8,5,11,12,6,3,10,4,1,2]a:[a|sum a>1]))0 e=25:e ``` [Try it online!](https://tio.run/##hY/NDoIwEITvfYol4QCykBbFHxJ4DQ/QQ4NFiOUntl6Mz27Fi8FoNDuHzeabyWwj9EkqZeustPWgDsorNYgw9wodRQnlQSB9x9GXzlNCG/fajvvWNN7CLza4wy0myBiyGNe4REZxhQxjLtJC3CYPiJxx36dEZnGSSmukNpBBMQ1FYB@iOLsDRwJfSfq@0Bn5W@wf@eowZQInpBNtPxU@DATGc9sbcKGG5xfE3qtaiaO2YTWODw "Haskell โ€“ Try It Online") The wrapping is clever: I essentially index at position `s+sum(โ€ฆ)` into the list `([0..50]++cycle[25])`. However, a shorter way to write that is indexing at position `sum(โ€ฆ)` and beginning the list at `s`. [Answer] # Java 10, ~~131~~ ~~130~~ 129 bytes ``` m->{int r=0,i,s,t;for(var a:m){for(i=s=t=0;i<12;s+=a[i++])t=a[i]>0?" \n".charAt(i):t;r+=s<2?t:s;r=r>50?25:r;}return r;} ``` Contains 10 unprintables. Input as integer-matrix of zeros and ones. -1 byte thanks to *@JonathanFrech*, changing `\t` into an actual tab (works in TIO, doesn't work in my local IDE). [Try it online.](https://tio.run/##7VdNb9swDMW@t3Y/QujJRtxADNBLXCfYD1gvPWY5aK7bqouVQlIyDIZ/eyo7xmzXWUxm2bDDonzYBqXwkXxP1INYi/OHm2@beCGMYZ@FVNkJY1LZRN@KOGFXxW35gMWe@57NZ3OW@qF7mruPexsrrIzZFVMsYpv0fJIVxjrigQxMYMPbpfbWQjMxTv2suJGRiWzEQ3kJo9AMIjGTg8Hct8XFfMKnZ@8@vH9z@vHtqy/q9YuXZ8P4XuhP1pP@2IZ6EJnL0dSOTagjPbng09HFWIe5TuxKK@auNuHWrcfV14Vzq/JuvZQ3LHXovGurpbpzIIS/hWYTYz2VfGcVuizjQTEg4O2RB6V955UB0b62geZA2VPXp9gDCS8nxGfnjDwvy@jXGaDOgC7uPTMg2DlQXlHzQIsTtP8FHSdAeLRFWf/yvZUHB@ShGc2fNd7rUe1ViYMYU0DbAxIBb0QJUB4Bmf3NTAOCPdiq@x22wYEI@vSinV8g86Y/A4foL1Yr/rQC10zBIu7yGKssGN4fVhFAqLmmPjQ866mhZxWEUC4gsKwdUUDqCpD2TCBGFJCc6SpW/262e//bryvwzKvjsRg6Ox@ga7Qxi6yLx@5yoN2H9KrK/z7zX@kzgdzRwZERU7sbaoT@xvpwhO4M2yFXbKsy3D6Qlke@MuX1sXV74rv@YWySDpcrO3x0h0G7UJ4axl7qV6vkmyc) **Explanation:** ``` m->{ // Method with integer-matrix parameter and integer return-type int r=0, // Result-integer, starting at 0 i,s,t; // Temp integers for(var a:m){ // Loop over the integer-arrays of the input for(i=s=t=0; // Reset `i`, `s` and `t` to 0 i<12; // Loop `i` in the range [0,12) s+=a[i++]) // Increase `s` by the current value (0 or 1) t=a[i]>0? // If the current value is 1: " \n".charAt(i) // Set `t` to the score at this position :t; // Else: Leave `t` the same r+=s<2? // If only a single pin was hit: t // Add its score `t` to the result : // Else: s; // Add the amount of pins `s` to the result r=r>50? // If the result is now above 50 25 // Penalize it back to 25 :r;} // If not, it stays the same return r;} // Return the result ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` โ‰”โฐฮท๏ผฆฮธยซโ‰งโบโŽ‡โŠ–ฮฃฮนฮฃฮนโŒ•ฮฑยงโ€$๏ฝœ#zโธ๏ผตgโŠ—โ€โŒ•ฮนยนฮทยฟโ€บฮทโตโฐโ‰”ยฒโตฮทยป๏ผฉฮท ``` [Try it online!](https://tio.run/##jY9PawJBDMXPzqcInhJIYafgyZN/qrVVkLa3ZQ/D7ugMrGM7O0pL8bOPygrFiuzCO4S8X5KX3Cifb1UZ46Cq7NphwmCoL1ZbD/hF8Cs6C/VZe292bQIuy13F8KG9U/4Hxzr3eqNd0AW@7zZoiRjqgmFiXYGKYRBmrtDf2H1@mU3mi@n49Wk46l58yyDpPHU@27ErwKnXKmiPhqGXEMEl2WOvZg5i6a0LOFJVQEPUjzFNRQqn5LUk/9VXgoxPnGzJ/evKW93j2u5r5mSbP5LGf2UTJ7IsPuzLIw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as a boolean array. Explanation: ``` โ‰”โฐฮท ``` Set the score to 0. ``` ๏ผฆฮธยซ ``` Loop over the throws. ``` โŽ‡โŠ–ฮฃฮน ``` Is the number of pins 1? ``` ฮฃฮน ``` If not, then take the number of pins. ``` โŒ•ฮฑยงโ€$๏ฝœ#zโธ๏ผตgโŠ—โ€โŒ•ฮนยน ``` Otherwise, translate the position of the pin to a value. ``` โ‰งโบ...ฮท ``` Add it to the score. ``` ยฟโ€บฮทโตโฐโ‰”ยฒโตฮท ``` If the score exceeds 50 then set it back to 25. ``` ยป๏ผฉฮท ``` Print the final result after all the throws. [Answer] # [Haskell](https://www.haskell.org/), 110 bytes ``` m s|sum s==1=sum$zipWith(*)[7,9,8,5,11,12,6,3,10,4,1,2]s|1>0=sum s f l=foldl(\b->c.(b+).m)0l c a|a>50=25|1>0=a ``` Same length: `f l=foldl(\b a->last$b+m a:[25|b+m a>50])0l` instead of `f` and `c` [Try it online!](https://tio.run/##jY/PboMwDMbvPIUPHKA1VczG2lUKr7ED42C6UKIlrGrSHSbenYVqUvdHE0ifrE/Wz/bnjt2rMmY8gpHtm3kxyXMDnJWGnY@btQXeV3kxXF1ZiDoVBrLMsVVgVH/0HbDx6tyz1@9qtOAGdwlVSpLBxB/69KR9l6zSaouPuMMCiZByfMA7JIH3SJjXbqBSyOtg1H4LkpWHTdKs040NZ6MD8DBlkCHPxPNoWfcg4XTWvYcYWvDK@SiaqqygAoFfIrz5H4IaA0cLuV9d@qv/uKX75jla8oeY/ZfmOKjHTw "Haskell โ€“ Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~47~~ 35 bytes -12 bytes thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz?tab=profile) (better way of generating the list encoding points)! ``` Fโ‚…0 S?25>50+?โ†Lฮต`f`+Nm+3d4652893071 ``` [Try it online!](https://tio.run/##yygtzv7/3@1RU6sBV7C9kamdqYG2/aO2CT7ntiakJWj75Wobp5iYmRpZWBobmBv@//8/OtpABwQNdQxQYaxOtCFOGQTPEBmiyeDWg13GEIcLDLC6DatcbCwA "Husk โ€“ Try It Online") ### Explanation ``` Fโ‚…0 -- input is a list of boolean lists F -- left fold by โ‚… -- | the function flipped (overflowing label) on line 1 0 -- | with initial value 0 S?25>50+?โ†Lฮต`f`+Nm+3d4652893071 -- example inputs: [0,0,0,1,0,0,0,0,0,0,0,0] 0 4652893071 -- integer literal: 4652893071 d -- digits: [4,6,5,2,8,9,3,0,7,1] m+3 -- map (+3): [7,9,8,5,11,12,6,3,10,4] `+N -- append natural numbers: [7,9,8,5,11,12,6,3,10,4,1,2,3,... `f -- filter this list by argument: [5] ? ฮต -- if it's of length 1 โ† -- | take first L -- | else the length -- : 5 + -- add to argument: 5 ? >50 -- if the value is > 50 25 -- | then 25 S -- | else the value -- : 5 ``` [Answer] # [Red](http://www.red-lang.org), 189 172 bytes ``` func[b][s: 0 foreach c b[d: 0 foreach e c[if e = 1[d: d + 1]]i: find c 1 n: either i[pick[7 9 8 5 11 12 6 3 10 4 1 2]index? i][0]if 50 < s: s + either 1 < d[d][n][s: 25]]s] ``` [Try it online!](https://tio.run/##fVJBboMwELzzirn3sktL0tJW@UOvqz002FasSiSCVMrvqQkBDDLVSrbsmR3PDjTWdF/WiGau7NxvXclRpS1BcOfGflcnVDiKiS8sKvEubJ/gHjF4Aqv6Es7XJvA5q0tYfz3ZBl4uvvqRPd7wigLM4Bw7PIMJL2DkGnrs7QCvQhpkC8IHgoE2qD40ONwYMSr13VpeqLbaXRpfX@EgQuiLQctS4S1gPnBcS2CzIwmsXxlfp5StJKSKd@T7bD1YihiYlCRu2t7wwMu@uwfeRdJDNDOFh9CG8R6HaaURmJlTzCpjzhTt9G/qKalorqXg1MHr79r/nn22RfcH "Red โ€“ Try It Online") ## Explanation of the ungolfed code: ``` f: func[b][ ; a block of blocks of booleans s: 0 ; sets sum to 0 foreach c b[ ; for each row of booleans d: 0 foreach e c[if e = 1[d: d + 1] ; count the number of 1s i: find c 1 ; the index of the first 1 n: either i[pick [7 9 8 5 11 12 6 3 10 4 1 2] ; if there is 1, pick the number index? i][0] ; at the index of 1 ; otherwise 0 if 50 < s: s + either 1 < d[d][n][s: 25] ; if there is only one 1, add ; the number to the sum, otherwise ; the number of 1s ; if the sum > 50, reset it to 25 ] s ; return the sum ] ``` [Answer] # JavaScript (ES6), 98 bytes ``` a=>a.map(b=>b.map((m,i)=>(c+=m,d+=m*('0x'+'7985bc63a412'[i])),c=d=0)|(t+=c>1?c:d)>50?t=25:0,t=0)|t ``` **Test cases:** ``` f= a=>a.map(b=>b.map((m,i)=>(c+=m,d+=m*('0x'+'7985bc63a412'[i])),c=d=0)|(t+=c>1?c:d)>50?t=25:0,t=0)|t console.log(f([ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ])) // 0 console.log(f([ [ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 ] ])) // 2 console.log(f([ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ])) // 12 console.log(f( [ [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ] ] )); // 16 console.log(f( [ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ], [ 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ])); // 18 console.log(f( [ [ 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ], [ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ] ] )); // 29 console.log(f( [ [ 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ], [ 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ] )) // 34 console.log(f( [ [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 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, 1, 0, 0, 0, 0 ] ] )) // 28 console.log(f( [ [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0 ], [ 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ] ] )) // 25 console.log(f( [ [ 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1 ], [ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1 ], [ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1 ], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 ], [ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ] ] )) // 25 console.log(f( [ [ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ], [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 ] ] )) // 50 console.log(f( [ [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ] )) // 27 console.log(f( [ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 ] ] )) // 30 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 37 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` โ”œT<โ†“"โ™ฅโ†~;โ–Œ6ยปโ‰ฅรธFโ†รฎ5โ–‘Uโ•š_ฯ€โ—‹Qโ–’<โ”‚โˆŸโ””รนโ•‘pฮตโ™€โ–€รฆ ``` [Run and debug it](http://stax.tomtheisen.com/#p=c3543c1922031b7e3bdd36aff200461b8c35b055c85fe30951b13cb31cc097ba70ee0cdf91&i=[[+0,+0,+0,+1,+0,+0,+0,+0,+0,+0,+0,+0+],[+1,+0,+0,+1,+0,+0,+0,+0,+0,+0,+0,+0+],[+0,+0,+0,+0,+0,+1,+1,+1,+1,+1,+1,+1+],[+0,+0,+0,+0,+0,+1,+0,+0,+0,+0,+0,+0+],[+0,+0,+0,+0,+0,+1,+0,+0,+0,+0,+0,+0+],[+0,+0,+0,+0,+1,+0,+0,+0,+0,+0,+0,+0+],[+1,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0+],[+1,+1,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0+]]%0A) [Try It online!](https://tio.run/##Ky5JrPj//9GUOSE2j9omKz2aufRR24Q660fTeswO7X7UufTwDjegwOF1po@mTQx9NHVW/PmGR9O7Ax9Nm2TzaErTo475j6ZMObzz0dSJBee2PprZ8Ghaw@Fl//9HRysY6ECRoQ6CjYIUYnWiEbL4laEJGmIiHMqINI2gMkMivGBAyKeGhJTFcgEA) **Explanation** ``` F:1"=EA5MQ9-I1%)"!s@c%1={h+}{%+}?c50>{d25}{}? # Full program, unpacked F # Loop through every element :1 # Get indices of truthy elements "=EA5MQ9-I1%)"! # Push encoded [7,9,8,5,11,12,6,3,10,4,1,2] s@ # Swap the top 2 elements of stack and get elements at indexes c%1= # Copy the top element, get length of array, compare to length of 1 {h+}{%+}? # If it has length of 1, add the element, otherwise add the length of the array to total c50> # Compare total to 50, {d25}{}? # If it is greater, pop it off and push 25 to reset counter, otherwise do nothing ``` Not my best work, but it works. I'm sure there is somehting I'm missing to make it a bit shorter. [Answer] # [Python 2](https://docs.python.org/2/), ~~109~~ ~~105~~ 103 bytes ``` c=0 for l in input():a=sum(l);c+=int('7985bc63a412'[l.index(1)],16)if a==1else a;c=(25,c)[c<51] print c ``` [Try it online!](https://tio.run/##jY/LCsIwEEX3/YrZNcEgnWrro@ZLQhZxbDEQ09IH6NfHLoSioi2cxTD3cOE2j/5a@zQEkklU1S04sH6kGXrGj0Z2w405XtBKWt@zeHfYZ2fKN2aLaazc2vpLeWfItcCc2wqMlFi6rgRTkGRpJogrOmWoo6YdC4BCUKAgES9QTPcboIWa0v/axxO/@aEtbJvVcMGEZG4pzmmgnw "Python 2 โ€“ Try It Online") Alternative without a recursive function. -2 with thanks to @Jo King ]
[Question] [ ## Problem The goal is as the title says to find the \$n\$th prime such that \$\text{the prime}-1\$ is divisible by \$n\$. ## Explanation Here is an example so you understand the question, *this is not necessarily the way it ought to be solved. It merely as a way to explain the question* given \$3\$ as an input we would first look at all the primes ``` 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 ... ``` Then we select the primes such that \$\text{the prime}-1\$ is divisible by \$n\$ (3 in this case) ``` 7 13 19 31 37 43 61 67 73 79 97 103 107 109 127 ... ``` We then select the \$n\$th term in this sequence We would output \$19\$ for an input of \$3\$ ## Note We can also think of this as the \$n\$th prime in the sequence \$\{1, n + 1, 2n + 1, 3n + 1 ...kn + 1\}\$ where \$k\$ is any natural number ## Test Cases ``` 1 --> 2 2 --> 5 3 --> 19 4 --> 29 100 --> 39301 123 --> 102337 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes 05AB1E uses [CP-1252](http://www.cp1252.com) encoding. Saved a byte thanks to *Osable* ``` ยตNยน*>Dpยฝ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOwrkqPkRwwr0&input=MTIz) **Explanation** ``` ยต # for N in [1 ...] loop until counter == input Nยน*> # N*input+1 (generate multiples of input and increment) D # duplicate pยฝ # if prime, increase counter # implicitly output last prime ``` [Answer] # Python 2, 58 bytes ``` n=N=input();m=k=1 while N:m*=k*k;k+=1;N-=m%k>~-k%n print k ``` [Answer] # Mathematica, 48 bytes ``` Select[Array[Prime,(n=#)^3],Mod[#-1,n]==0&][[n]]& ``` Unnamed function taking a single argument, which it names `n`. Generates a list of the first `n^3` primes, selects the ones that are congruent to 1 modulo `n`, then takes the `n`th element of the result. It runs in several seconds on the input 123. It's not currently known if there's always even a single prime, among the first `n^3` primes, that is congruent to 1 modulo `n`, much less `n` of them. However, the algorithm can be proved correct (at least for large `n`) under the assumption of the [generalized Riemann hypothesis](https://en.wikipedia.org/wiki/Generalized_Riemann_hypothesis)! [Answer] ## Haskell, ~~59~~ 47 bytes ``` f n=[p|p<-[1,n+1..],all((<2).gcd p)[2..p-1]]!!n ``` Usage example: `f 4` -> `29`. How it works: ``` [p|p<-[1,n+1..] ] -- make a list of all multiples of n+1 -- (including 1, as indexing is 0-based) ,all((<2).gcd p)[2..p-1] -- and keep the primes !!n -- take the nth element ``` Edit: Thanks @Damien for 12 bytes by removing the divisibility test and only looking at multiples in the first place. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€˜ร†P>%รฐ#แนชโ€˜ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCYw4ZQPiXDsCPhuarigJg&input=&args=MTIz) ### How it works ``` โ€˜ร†P>%รฐ#แนชโ€˜ Main link. Argument: n รฐ# Call the dyadic chain to the left with right argument n and left argument k = n, n+1, n+2, ... until n of them return 1. โ€˜ Increment; yield k+1. ร†P Test k+1 for primality, yielding 1 or 0. % Compute k%n. > Compare the results to both sides, yielding 1 if and only if k+1 is prime and k is divisible by n. แนช Tail; extract the last k. โ€˜ Increment; yield k+1. ``` [Answer] # Java 7, 106 bytes ``` int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}} ``` **Ungolfed:** ``` int c(int n){ for(int z = 1, i = 2, j, x; ; i++){ x = i; for(j = 2; j < x; x = x % j++ < 1 ? 0 : x); if(x > 1 & (i-1) % n < 1 && z++ == n){ return i; } } } ``` **Test code:** [Try it here](https://ideone.com/m4ilQc) (last test case results in a *Time limit exceeded* on ideone) ``` class M{ static int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}} public static void main(String[] a){ System.out.println(c(1)); System.out.println(c(2)); System.out.println(c(3)); System.out.println(c(4)); System.out.println(c(100)); System.out.println(c(123)); } } ``` **Output:** ``` 2 5 19 29 39301 102337 ``` [Answer] **Nasm 679 bytes (Instruction Intel 386 cpu 120 bytes)** ``` isPrime1: push ebp mov ebp,dword[esp+ 8] mov ecx,2 mov eax,ebp cmp ebp,1 ja .1 .n: xor eax,eax jmp short .z .1: xor edx,edx cmp ecx,eax jae .3 div ecx or edx,edx jz .n mov ecx,3 mov eax,ebp .2: xor edx,edx cmp ecx,eax jae .3 mov eax,ebp div ecx or edx,edx jz .n inc ecx inc ecx jmp short .2 .3: xor eax,eax inc eax .z: pop ebp ret 4 Np: push esi push edi mov esi,dword[esp+ 12] xor edi,edi or esi,esi ja .0 .e: xor eax,eax jmp short .z .0: inc esi jz .e push esi call isPrime1 add edi,eax dec esi cmp edi,dword[esp+ 12] jae .1 add esi,dword[esp+ 12] jc .e jmp short .0 .1: mov eax,esi inc eax .z: pop edi pop esi ret 4 ``` this is ungolfed one and the results ``` ;0k,4ra,8Pp isPrime1: push ebp mov ebp, dword[esp+ 8] mov ecx, 2 mov eax, ebp cmp ebp, 1 ja .1 .n: xor eax, eax jmp short .z .1: xor edx, edx cmp ecx, eax jae .3 div ecx or edx, edx jz .n mov ecx, 3 mov eax, ebp .2: xor edx, edx cmp ecx, eax jae .3 mov eax, ebp div ecx or edx, edx jz .n inc ecx inc ecx jmp short .2 .3: xor eax, eax inc eax .z: pop ebp ret 4 ; {1, n+1, 2n+1, 3n+1 } ; argomento w, return il w-esimo primo nella successione di sopra ;0j,4i,8ra,12P Np: push esi push edi mov esi, dword[esp+ 12] xor edi, edi or esi, esi ja .0 .e: xor eax, eax jmp short .z .0: inc esi jz .e push esi call isPrime1 add edi, eax dec esi cmp edi, dword[esp+ 12] jae .1 add esi, dword[esp+ 12] jc .e jmp short .0 .1: mov eax, esi inc eax .z: pop edi pop esi ret 4 00000975 55 push ebp 00000976 8B6C2408 mov ebp,[esp+0x8] 0000097A B902000000 mov ecx,0x2 0000097F 89E8 mov eax,ebp 00000981 81FD01000000 cmp ebp,0x1 00000987 7704 ja 0x98d 00000989 31C0 xor eax,eax 0000098B EB28 jmp short 0x9b5 0000098D 31D2 xor edx,edx 0000098F 39C1 cmp ecx,eax 00000991 731F jnc 0x9b2 00000993 F7F1 div ecx 00000995 09D2 or edx,edx 00000997 74F0 jz 0x989 00000999 B903000000 mov ecx,0x3 0000099E 89E8 mov eax,ebp 000009A0 31D2 xor edx,edx 000009A2 39C1 cmp ecx,eax 000009A4 730C jnc 0x9b2 000009A6 89E8 mov eax,ebp 000009A8 F7F1 div ecx 000009AA 09D2 or edx,edx 000009AC 74DB jz 0x989 000009AE 41 inc ecx 000009AF 41 inc ecx 000009B0 EBEE jmp short 0x9a0 000009B2 31C0 xor eax,eax 000009B4 40 inc eax 000009B5 5D pop ebp 000009B6 C20400 ret 0x4 68 000009B9 56 push esi 000009BA 57 push edi 000009BB 8B74240C mov esi,[esp+0xc] 000009BF 31FF xor edi,edi 000009C1 09F6 or esi,esi 000009C3 7704 ja 0x9c9 000009C5 31C0 xor eax,eax 000009C7 EB1D jmp short 0x9e6 000009C9 46 inc esi 000009CA 74F9 jz 0x9c5 000009CC 56 push esi 000009CD E8A3FFFFFF call 0x975 000009D2 01C7 add edi,eax 000009D4 4E dec esi 000009D5 3B7C240C cmp edi,[esp+0xc] 000009D9 7308 jnc 0x9e3 000009DB 0374240C add esi,[esp+0xc] 000009DF 72E4 jc 0x9c5 000009E1 EBE6 jmp short 0x9c9 000009E3 89F0 mov eax,esi 000009E5 40 inc eax 000009E6 5F pop edi 000009E7 5E pop esi 000009E8 C20400 ret 0x4 000009EB 90 nop 120 [0, 0] [1, 2] [2, 5] [3, 19] [4, 29] [5, 71] [6, 43] [7, 211] [8, 193] [9, 271] [1 0, 191] [11, 661] [12, 277] [13, 937] [14, 463] [15, 691] [16, 769] [17, 1531] [18 , 613] [19, 2357] [20, 1021] [21, 1723] [22, 1409] [23, 3313] [24, 1609] [25, 3701 ] [26, 2029] [27, 3187] [28, 2437] [29, 6961] [30, 1741] [31, 7193] [32, 3617] [33 , 4951] [34, 3877] [35, 7001] [36, 3169] [37, 10657] [38, 6271] [39, 7879] [40, 55 21] [41, 13613] [42, 3823] [43, 15137] [44, 7349] [45, 9091] [46, 7499] [47, 18049 ] [48, 6529] [49, 18229] [50, 7151] [51, 13159] [52, 10141] [53, 26501] [54, 7669] [55, 19801] [56, 11593] [57, 18127] [58, 13109] [59, 32569] [60, 8221] [61, 34649 ] [62, 17981] [63, 21799] [64, 16001] [65, 28081] [66, 10429] [67, 39799] [68, 193 81] [69, 29947] [70, 14771] [71, 47713] [72, 16417] [73, 51539] [74, 25013] [75, 2 9101] [76, 26449] [77, 50051] [78, 16927] [79, 54037] [80, 23761] [81, 41149] [82, 31489] [83, 68891] [84, 19237] [85, 51341] [86, 33713] [87, 45589] [88, 34057] [8 9, 84551] [90, 19531] [91, 64793] [92, 42689] [93, 54499] [94, 41737] [95, 76001] [96, 27457] [97, 97583] [98, 40867] [99, 66529] [100, 39301] [101, 110899] [102, 2 9989] [103, 116803] [104, 49297] [105, 51871] [106, 56711] [107, 126047] [108, 385 57] [109, 133853] [110, 42901] [111, 76369] [112, 53089] [113, 142607] [114, 40129 ] [115, 109481] [116, 63337] [117, 83071] [118, 67733] [119, 112337] [120, 41281] [121, 152219] [122, 70639] [123, 102337] ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 13 bytes Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O-KVl2BQROKVnEAlWWDilZNOUA&input=MTIz) ``` ;โ•—`PDโ•œ@%Y`โ•“NP ``` **Ungolfing** ``` Implicit input n. ;โ•— Save a copy of n to register 0. `...`โ•“ Push first n values where f(x) is truthy, starting with f(0). PD Get the x-th prime - 1. โ•œ@% Push (x_p - 1) % n. Y If x_p-1 is divisible by n, return 1. Else, return 0. NP Get the n-th prime where n_p-1 is divisible by n. Implicit return. ``` [Answer] # Common Lisp, 162 bytes ``` (defun s(n)(do((b 2(loop for a from(1+ b)when(loop for f from 2 to(1- a)never(=(mod a f)0))return a))(a 0)(d))((= a n)d)(when(=(mod(1- b)n)0)(incf a)(setf d b)))) ``` Usage: ``` * (s 100) 39301 ``` Ungolfed: ``` (defun prime-search (n) (do ((prime 2 (loop for next from (1+ prime) when (loop for factor from 2 to (1- next) never (= (mod next factor) 0)) return next)) (count 0) (works)) ((= count n) works) (when (= (mod (1- prime) n) 0) (incf count) (setf works prime)))) ``` Some of those `loop` constructs can probably be shortened into `do` loops, but this is what I've got for now. [Answer] # [MATL](http://github.com/lmendo/MATL), 12 bytes ``` 1i:"`_YqtqG\ ``` [Try it online!](http://matl.tryitonline.net/#code=MWk6ImBfWXF0cUdc&input=NA) (For input `123` it times out in the online compiler, but it works offline.) ### Explanation ``` 1 % Push 1 i: % Input n and push [1 2 ... n] " % For each (that is, do the following n times) ` % Do...while _Yq % Next prime tq % Duplicate, subtract 1 G % Push n again \ % Modulo % End (implicit). Exit loop if top of stack is 0; else next iteration % End (implicit) % Display (implicit) ``` [Answer] # Perl, ~~77~~ 76 + 1 = 77 bytes ``` for($p=2;@a<$_;$p++){push@a,$p if(1 x$p)!~/^(11+?)\1+$/&&($p%$_<2)}say$a[-1] ``` Uses the prime-testing regex to determine if `$p` is prime, and makes sure that it's congruent to 1 mod the input (the only nonnegative integers below 2 are 0 and 1, but it can't be 0 if it's prime, so it has to be 1. saves 1 byte over `==1`). [Answer] **Mathematica 44 Bytes** ``` Pick[x=Table[i #+1,{i,# #}],PrimeQ/@x][[#]]& ``` Very fast. Uses the idea from the "Note" ``` % /@ {1, 2, 3, 4, 100, 123} // Timing ``` Output ``` {0.0156001, {2, 5, 19, 29, 39301, 102337}} ``` [Answer] # [Perl 6](https://perl6.org), ~~46 39~~ 37 bytes ``` ->\n{(2..*).grep({.is-prime&&($_-1)%%n})[n-1]} ``` ``` ->\n{(1,n+1...*).grep(*.is-prime)[n-1]} ``` ``` {(1,$_+1...*).grep(*.is-prime)[$_-1]} ``` [Answer] # Java 8, 84 bytes ### Golfed ``` (n)->{for(int s=n,i=1;;i+=n)for(int j=2;i%j>0&j<i;)if(++j==i&&--s<1)return n>1?i:2;} ``` ### Ungolfed ``` (n) -> { for (int s = n, // Counting down to find our nth prime. i = 1; // Counting up for each multiple of n, plus 1. ; // No end condition specified for outer for loop. i += n) // Add n to i every iteration. for (int j = 2; // Inner for loop for naive primality check. i % j > 0) // Keep looping while i is not divisible by j // (and implicitly while j is less than i). if(++j==i // Increment j. If j has reached i, we've found a prime && // Short-circutting logical AND, so that we only decrement s if a prime is found --s < 1) // If we've found our nth prime... return n>1?i:2; // Return it. Or 2 if n=1, because otherwise it returns 3. } ``` ## Explanation Solution inspired by several other answers. Function is a lambda that expects a single int. The `n>1?i:2` is a cheap hack because I couldn't figure out a better way to consider the case of n=1. Also, this solution times out on Ideone, but has been tested for all test cases. It times out because in order to shave a couple bytes off, I took out the explicit `j<i` check in the inner loop. It's mostly implied by `i%j>0`... except in the case of `i=1` and `j=2` (the very first iteration), in which case the loop runs until j overflows (I'm assuming). Then it works fine for all iterations afterwards. For a version that doesn't time out that's a couple bytes longer, [see here!](http://ideone.com/whXnHl) [Answer] ## Racket 109 bytes ``` (let p((j 2)(k 0))(cond[(= 0(modulo(- j 1)n))(if(= k(- n 1))j(p(next-prime j)(+ 1 k)))][(p(next-prime j)k)])) ``` Ungolfed: ``` (define (f n) (let loop ((j 2) (k 0)) (cond [(= 0 (modulo (sub1 j) n)) (if (= k (sub1 n)) j (loop (next-prime j) (add1 k)))] [else (loop (next-prime j) k)] ))) ``` Testing: ``` (f 1) (f 2) (f 3) (f 4) (f 100) (f 123) ``` Output: ``` 2 5 19 29 39301 102337 ``` [Answer] ## Ruby 64 bytes ``` require'prime';f=->(n){t=n;Prime.find{|x|(x-1)%n==0&&(t-=1)==0}} ``` Called like this: ``` f.call(100) # 39301 ``` Also, this command-line app works: ``` n=t=ARGV[0].to_i;p Prime.find{|x|(x-1)%n==0&&(t-=1)==0} ``` called like this ``` ruby -rprime find_golf_prime.rb 100 ``` but I am not so sure how to count the characters. I think I can ignore the language name, but have to include the `-rprime` and space before the script name, so that is slightly shorter, at 63 . . . [Answer] ## R, 72 bytes ``` n=scan();q=j=0;while(q<n){j=j+1;q=q+1*(numbers::isPrime(j)&!(j-1)%%n)};j ``` Terribly inefficient and slow but it works. It reads input from stdin and then uses the `isPrime` function from the `numbers` package to find the primes. The rest is just checking whether `prime - 1` is divisible by `n`. [Answer] ## JavaScript (ES6), 65 bytes ``` f=(n,i=n,j=1)=>i?f(n,i-!/^(..+?)\1+$/.test('.'.repeat(j+=n)),j):j ``` Uses the regexp primality tester, since it's a) 8 bytes shorter and b) less recursive than my pure recursive approach. [Answer] **Axiom 64 bytes** ``` f(n)==(n<0 or n>150=>0;[i*n+1 for i in 0..2000|prime?(i*n+1)].n) ``` does someone know how to write above using Axiom streams?... some example ``` -> f(i) for i in 1..150 Compiling function f with type PositiveInteger -> NonNegativeInteger [2, 5, 19, 29, 71, 43, 211, 193, 271, 191, 661, 277, 937, 463, 691, 769, 1531, 613, 2357, 1021, 1723, 1409, 3313, 1609, 3701, 2029, 3187, 2437, 6961, 1741, 7193, 3617, 4951, 3877, 7001, 3169, 10657, 6271, 7879, 5521, 13613, 3823, 15137, 7349, 9091, 7499, 18049, 6529, 18229, 7151, 13159, 10141, 26501, 7669, 19801, 11593, 18127, 13109, 32569, 8221, 34649, 17981, 21799, 16001, 28081, 10429, 39799, 19381, 29947, 14771, 47713, 16417, 51539, 25013, 29101, 26449, 50051, 16927, 54037, 23761, 41149, 31489, 68891, 19237, 51341, 33713, 45589, 34057, 84551, 19531, 64793, 42689, 54499, 41737, 76001, 27457, 97583, 40867, 66529, 39301, 110899, 29989, 116803, 49297, 51871, 56711, 126047, 38557, 133853, 42901, 76369, 53089, 142607, 40129, 109481, 63337, 83071, 67733, 112337, 41281, 152219, 70639, 102337, 75641, 126001, 42589, 176531, 85121, 107071, 62791, 187069, 55837, 152419, 94873, 104761, 92753, 203857, 62929, 226571, 72661, 144103, 99401, 193051, 69697, 168781, 112859, 133183, 111149, 250619, 60601] ``` ## Type: Tuple NonNegativeInteger [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes ``` !โฐfแน—ยก+โฐ1 ``` [Try it online!](https://tio.run/##yygtzv7/X/FR44a0hzunH1qoDWQZ/v//39DAAAA "Husk โ€“ Try It Online") ``` !โฐ # get the input-th element of fแน— # the elements that are primes among ยก # the list formed by repeatedly +โฐ # adding the input to the last result 1 # starting with 1. ``` ]
[Question] [ # The task Given any array of integers, e.g.: ``` [-1,476,578,27,0,1,-1,1,2] ``` and an index of that array (this example uses **0 based indexing**, though you can use **1 based indexing** as well.): ``` index = 5 v [-1,476,578,27,0,1,-1,1,2] ``` Then **return the nearest number greater than the element at that index**. In the example, the closest number greater than 1 is 27 (at 2 indices away). ``` index = 5 v [-1,476,578,27,0,1,-1,1,2] ^ Nearest greater number Output = 27 ``` # Assumptions * Nearest does not include wrapping. * The program will never be given an array of length 1 (e.g; `[55]`). * You are to assume there is **always** a number greater than the given element. * If there are 2 numbers greater than the element at equal distances, you can return **either one**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins # I/O pairs ``` Input: Index = 45 Array = [69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129] Output = 199 Input: Index = 2 Array = [4,-2,1,-3,5] Output = 4 OR 5 Input: Index = 0 Array = [2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545] Output = 4545 Input: Index = 0 Array = [1,0,2,3] Output = 2 Input: Index = 2 Array = [3,-1,-3,-2,5] Output = -1 OR -2 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` yt&y)>fYk) ``` This uses 1-based indexing. [**Try it online!**](https://tio.run/nexus/matl#@19ZolapaZcWma35/3@0rqGOibmZjqm5hY6RuY6BjqEOUMRQxyiWy4wLCAA) ### Explanation Consider inputs `[4,-2,1,-3,5]`, `3` as an example. ``` y % Take two inputs implicitly. Duplicate 2nd-top element in the stack % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5] t % Duplicate top of the stack % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5] &y % Duplicate 3rd-top element in the stack % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5], 3 ) % Index: select elements from first input as indicated by second input % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], 1 > % Greater than, element-wise % STACK: [4,-2,1,-3,5], 3, [1,0,0,0,1] f % Find: gives indices of non-zero entries % STACK: [4,-2,1,-3,5], 3, [1,5] Yk % Closest element: gives closest element of each entry in second input % ([1,5]) to each entry in the first input (3). In case of a tie it % gives the left-most one % STACK: [4,-2,1,-3,5], 1 ) % Index: select elements from first input as indicated by second input % STACK: 4 % Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` แป‹<แน›Tแบกโธ$รžแธขแป‹ ``` [Try it online!](https://tio.run/nexus/jelly#bVJLat1AENz7FMJ4KcH0fDWQY3hjHu8wXucIgUCyyRWcePlO8nIRuaq6lYUJSPPpT01XdR/3969f7r@/Pd///Pj7@vZ0@35/@wnbcfv1@HIcta9LWRfDd1wufa5LxXXHPrH3vC65wQY3QwznfeAwYOkJF@xtRxD@DsdgVMOh4oetEHsCxZjmqcAotJTm4FZg9hhGN0IwncHMJxptiJg9fJM@VjWH158Y3WGZiVb4s3k5YzgPkyfnKCozYW9evl5PAM/8yQn7mA7Ae5YCXIaTNsLbTto0jtPd5rkkYDY@WbrLIdJRHPUzZ0UVWJDtTkulIG8ypPcgzkdmkLeq6@5kJTmh6ombTgmsizIXaUWxhT96qNUBQhKWsAy6xHSoEQznfBhHoQBFPerBrbazF2c11IUtnMouMTOqT1ktRGDVTfLD1cLh8ic3iDtfdCW8x5oe65Gb/yUSTpNTQ5GqRoiiZsgCh522MmPQWOC0GLjeoqWdQhIw@U6BqIZELC0mzlXSQFE4donJmil1iM3U3OcZ@slHSSWmJnBe14flAqTNJ2NjVbJlPbCpD9unRmz/6UT1NGC4r1yvHw "Jelly โ€“ TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +1 byte - No wrapping allowed. ``` JแบกลผโธแนขZแนชยป\Q2แป‹ ``` 1-indexed. **[Try it online!](https://tio.run/nexus/jelly#AScA2P//SuG6ocW84oG44bmiWuG5qsK7XFEy4buL////WzEsMCwyLDNd/zE)** --- Previous 11 byter (wrapping indexing), 0-indexed: ``` แน™ลผU$Fยต>แธขTแธขแป‹ ``` [Answer] ## JavaScript (ES6), ~~57~~ 55 bytes Takes the array `a` and the index `i` in currying syntax `(a)(i)`. ``` a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p) ``` ### Test cases ``` let f = a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p) console.log(f([-1, 476, 578, 27, 0, 1, -1, 1, 2])(5)) console.log(f([69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129])(45)) console.log(f([4, -2, 1, -3, 5])(2)) console.log(f([2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545])(0)) ``` [Answer] # PHP, 106 Bytes ``` <?for($y=($a=$_GET[0])[$x=$_GET[1]];$y>=$a[$x-++$i]&&$y>=$a[$x+$i];);echo$y<$a[$x+$i]?$a[$x+$i]:$a[$x-$i]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/93ffeb6d2cbd58870cbaf8e08d695ad88eaaa9cf) [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` i%l=minimum[[j*j,x]|(j,x)<-zip[-i..]l,x>l!!i]!!1 ``` [Try it online!](https://tio.run/nexus/haskell#bVLLbtswELz3K2SgAaSCErh8ikGTe845Cj4YqdEysNRAsdG0yL87O0uqh6IHvvYx3Jnd@ZCXu7ycj@vh6fz5spzycnwd5sNL277@@Pnr9vZhOff3j@c1L9@74bI8Xdb1d3vTDevx8K0bJPyab053c17yfJmn6fnLs3rbv7e8d1/7P/ll6vMw7E/q7f602@X9bkfXa@u8aqaQVOOsakY@E5/BqMaww6mGCIvvY@RLZEvQ/ODTjxzEK7AjIsrzxfFim2UQSoxCSCupjGFhsb6Ak2VziUG0BwTSEYx8oMHGESlUX4IPVSV@IEsjOrAlaVjZb6iUE2PhQeIxphZlkDD6Ur78rhncYIETnzEVALyNKIAtFtIEeBpBG8a4uX3aNs2YHl/aUOQQ0rU46EeFFVRAQTQWWlIK5yWEhFCJ45NUyZOT51jIiuSAchuu3iSgIJSxiVYQW/BjqGoFBgEJ0rxFuIRplEYg3CESo2AZRXoUKjfnt15s1UAXtDBJtq0zI/VJlq8ioGov8rPLV0eRXxeDcMePRYnSY5keCjXX/E0EnEyOq4o4aYRQlBmiioNOk0110FBgojpwwdeWBggJQF1OCAQ1RETr68QVlWSgIBy6hGSZKekQmilzb1LVT3yQVMSUCUz77lPLMZNTvVGkeqs8TAw7Gfmil070/7Si/08vHDI/AA "Haskell โ€“ TIO Nexus") Test framework from ร˜rjan Johansen. [Answer] # [Python](https://docs.python.org/), 62 bytes ``` lambda a,i:min((v<=a[i],abs(j-i),v)for j,v in enumerate(a))[2] ``` **[Try it online!](https://tio.run/nexus/python3#bVPLjtswDDy3X6HLYu2FDIh6WkH30GNP/YA0By/WAbxo3IXjBO3XpxxKDtqiB0kWhxyRQ/r4/O32fTi9vA5q0NPuNM1Nc/30POyngx5ezs1bN7X62h5/LOpNX9U0q3G@nMZlWMdmaNu9PdyAreN5Bdg0@5i18k6rns/MZ7Ra2cA2rYiw@LtP/JHYEg1f@Aw9O/GKDCR4Bf7wvNjmmIQysxDCSihzOFhcKOTk2Fx84B1AgXA4Ix5ssLFHjhXLwJBV5guiDLwjW7KBlXFLJZ2USh0kiLU1KYuAPpT05XXD5BYLNfGZciHA3YoC2FIpmkBPPcqGMW1wyNtmmDPgSReLHFJ0TQ76UakKKiAh6ktZkgrHZbjEWAvHI7kWT16ufSlWJAeV33jNJgFFKRmbaAWxhT/FqlZkEhRBhrcESCpN0gi4e3hiFByzSI9irc2HrRdbNtAFLcwS7erMSH4SFaoIyDqI/AyFChT5TTFI7XixKFF6LNNDscbaeyDoZHJ8VcRLI6REmSGqPOg0uVwHDQlmqgMXQ21phJAgNOWEQFBDRHShTlxRSQYKwqFLCJaZkg6hmTL3Nlf9BIOkIqZMYD5AxVarZu91ZzXpzunARis2K6900ozun250/2mHR6iRUNJGW@3k3u4@fnhfpnltHr/Mr@PPnXo4P6oH@e33dGjv6OdlGX79hZo/0K@X9f2ybvCxeYJHe8fb2@03)** [Answer] # x86-64 Assembly, 40 bytes Inspired by analyzing [Johan du Toit](https://codegolf.stackexchange.com/a/118802/58518) and [2501](https://codegolf.stackexchange.com/a/118844/58518)'s C solutions, the following is a function that can be assembled with MASM for x86-64 platforms. It follows the [Microsoft x64 calling convention](https://msdn.microsoft.com/en-us/library/ms235286.aspx) for passing parameters, so the total length of the array is passed in `ECX`, the position of interest is passed in `EDX`, and the pointer to the integer array is passed in `R8` (it's a 64-bit platform, so it's a 64-bit pointer). It returns the result (the "nearest greater number") in `EAX`. ``` FindNearestGreater PROC 8B F2 \ mov esi, edx ; move pos parameter to preferred register 8B D9 | mov ebx, ecx ; make copy of count (ecx == i; ebx == count) | MainLoop: 8B C6 | mov eax, esi ; temp = pos 2B C1 | sub eax, ecx ; temp -= i 99 | cdq 33 C2 | xor eax, edx 2B C2 | sub eax, edx ; temp = AbsValue(temp) | 41 8B 14 B0 | mov edx, DWORD PTR [r8+rsi*4] 41 39 14 88 | cmp DWORD PTR [r8+rcx*4], edx 7E 04 | jle KeepGoing ; jump if (pValues[i] <= pValues[pos]) 3B D8 | cmp ebx, eax 77 02 | ja Next ; jump if (count > temp) | KeepGoing: 8B C3 | mov eax, ebx ; temp = count | Next: 8B D8 | mov ebx, eax ; count = temp E2 E3 | loop MainLoop ; equivalent to dec ecx + jnz, but smaller (and slower) | | ; Return pValues[temp + pos] 03 C6 | add eax, esi 41 8B 04 80 | mov eax, DWORD PTR [r8+rax*4] C3 / ret FindNearestGreater ENDP ``` If you wanted to call it from C code, the prototype would be: ``` extern int FindNearestGreater(unsigned int count, unsigned int pos, const int *pValues); ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->a,i{a[(0...a.size).select{|j|a[j]>a[i]}.min_by{|j|(i-j).abs}]} ``` [Try it online!](https://tio.run/nexus/ruby#FYhLCsMgFACv8pYJ6EON9rNoLmKlvAQDii0Fu2kTz251M8zMdrtXPhMLO9lBICJhDj8/YvbJr5/9iAfZ6GaywRV8htdj@fY5BB5HpCUXV@obNlwpJbBKKs2Ay/PUaQwDqU8N196TYKBaXPoRzbTRxjEQ9Q8 "Ruby โ€“ TIO Nexus") [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 20 bytes Basically a translation of [this Ruby answer](https://codegolf.stackexchange.com/a/118757/65298). ``` Dl#)โ–‘โ”ผ_ยชโ”ผโ”˜ยช>;โ•ฅโ”˜_-A;ยช ``` [Try it online!](https://tio.run/nexus/ohm#PVJLSkRBDNx7igeuhBE6/Um/MCAI3kJkLuBlhFG8gJs5g6s5yrvIWJXkuehfPtWpSm4v7/cP29fHdv49XS/Yt/P39fJ03D5/cDs9Ph@vl9vtVe2w9HZYVpyGU@thqQO2wyLChfs6cZmwaMED51gRhKVwTEYNXDoWbA0gYkARpkUqMBotbQS4NJgjhtGDEExnMPOJRhsiTNNn9LEqw4NZhdEKixVa4a8S5cwZPMQ9tWZRlQnriPL99wLwykVOOKcFAN/VFeA2g7QQXlbSpnHu7mH7VoA5@GXTkMNJZ3HUT4IVVWBBsgYtLwV5xhDVJM5PLMlL9@caZF1yQvUdt@wSiDplbq4VxXb8qamWAoQkpGCbdDnT6Y1geGckR6EBxXukya2PvRd7NdSFLTTPbjkzXp9njRSBVQ@XH66RjpC/hMG588dQInrs0yOaufU/kXA@OT0V6d4Ip@gzJInDTkuzHDQWaJIDpyNbqhSSgCVOCkQ1XMQ2cuJCJR8oCscuMdlnyjvEZvrcV0v93EdJXUyfQHu76@MP "Ohm โ€“ TIO Nexus") Explanation will come later when I'm not doing homework. [Answer] # [Haskell](https://www.haskell.org/), 53 bytes `(#)` takes an `Int` and a list of `Int`s or `Integer`s (actually any `Ord` type), and returns an element of the list. ``` n#l=[x|i<-[1..],x:_<-(`drop`l)<$>[n-i,n+i],x>l!!n]!!0 ``` # How it works * `n` is the given index and `l` is the given list/"array". * `i`, taking on values from 1 upwards, is the distance from `n` currently being tested. * For each `i`, we check indices `n-i` and `n+i`. * `x` is the element of `l` being tested. If it passes the tests it will be an element of the resulting list comprehension. + Indexing arbitrary indices with `!!` could give an out of bounds error, while `drop` instead returns either the whole list or an empty list in that case. The pattern match with `x:_` checks that the result is not empty. + `x>l!!n` tests that our element is greater than the element at index `n` (which is guaranteed to exist). + `!!0` at the end returns the first match/element of the list comprehension. [Try it online!](https://tio.run/nexus/haskell#bVLLbtswELz3K2QkBxmhBC6fouH43nOPgtEYiZEIcJhAsZEU6L@7O0uqh6IHvvYx3Jnd18OU76d8Ps6Hx/PtJZ@mfPzoXw/vbfvx8va52Xxn3/Nx7nY/zvOUn9f9JT9e5vlXe7Pu5@Phad1LyjXfnO7Hr9/Tthup7/fqa/Nz27UPT/Pb@8Npvb3djbmbVL6b2LU7rVZ5v1rp67V1XjVjSKpxVjUDn4nPYFRj2OFUQ4TF9yHyJbIlaH7w6QcO4hXYERHl@eJ4sc0yCCVGIaSVVMawsFhfwMmyucQg2gMC6QhGPtBg44gUqi/Bh6oSP5ClER3YkjSs7DdUyomx8CDxGFOLMkgYfClfftcMbrDAic@YCgDeRhTAFgtpAjwNoA1jXNw@LZtmTI8vbShyCOlaHPSjwgoqoCAaCi0phfMSQkKoxPFJquTJyXMoZEVyQLkFVy8SUBDK2EQriC34MVS1AoOABGneIlzCNEojEO4QiVGwjCI9CpWb80svlmqgC1qYJNvWmZH6JMtXEVC1F/nZ5aujyK@LQbjjx6JE6bFMD4Waa/4mAk4mx1VFnDRCKMoMUcVBp8mmOmgoMFEduOBrSwOEBKAuJwSCGiKi9XXiikoyUBAOXUKyzJR0CM2UuTep6ic@SCpiygSm/fpbyzGjU51RpDqrPEwMOxr5opNOdP@0ovtPLxwy/wA "Haskell โ€“ TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` hH&โˆ‹โ‚Ž<.&t:Iโ‰œ+:Hโˆ‹โ‚ ``` [Try it online!](https://tio.run/nexus/brachylog2#@5/hofaoo/tRU5@NnlqJleejzjnaVh5gkd7//6Oj4w11TMzNdEzNLXSMzHUMdAx1gCKGOkaxOqax/6MA "Brachylog โ€“ TIO Nexus") ### Explanation ``` hH Call the list H &โˆ‹โ‚Ž<. Output is greater than the number at the specified index &t:Iโ‰œ Label I (0, then 1, then -1, then 2, then -2, โ€ฆ) + Sum I with the input Index :Hโˆ‹โ‚ Output is the element of H at index <the sum> ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 98 bytes ``` int f(int n,int[]a){for(int s=1,i=1,x=a[n];;n+=i++*s,s=-s)if(0<=n&n<a.length&&a[n]>x)return a[n];} ``` [Try it online!](https://tio.run/nexus/java-openjdk#nVNNj9owED13f0VOKCkO8ndisfQf9LRHxCHdAo3EGkRCuxXit9N5Y6daVSu16sF2PDPveebN5HT5cuifi@dDNwzF566P13sfx2JXYo@C9vWmq66745ktw0qJntbrqlvHzXIZ56t@Pv84iGFVD1W/K@XjKs7iY7c4bON@/DabIe7Ta3XejpdzLBh1u5/Sq8PYjXR8P/Zfixd6u3waz33crzdFd94P1fXhw9PPYdy@LI6XcXEi13iIZdz@4ETLarErrRMFDJzn1QdRWCOKls5Ap9ei0BRhRaEUFn23DX00ZPGSLnS6loJoeXI0iHL0YWmRzRCJCsSiAEtQ4jCwGJfIlSFzikG0AwXgCAYebLBRRPDZF@BDVoEuQElEe7IECSv5tUrpNE2qQ7FH65yUBqB1KX1@XRK5xkJNdDYhEeCuWQFsTSpagV61KBvGZnK7MG2SOB2eND7JwUXn5KCfSlVBBSSk2lQWp0K4gBDvc@F4JOTileVrm4plyUFlJ145SaA8l4yNtYLYzN/4rJYnEhShJG0NXFxpw41AuEUkRsEQC/fI59qsm3oxZQNd0MLAaJNnhvNjlMsiIGvH8pPLZUeSXyYD144XkxKpxzw9ymes/g0EHU@OzYpYbgSXyDOkMg86rUzIg4YEg8oD511uqYeQIJTphEBQg0U0Lk9cUokHCsKhSwDzTHGH0Eyeex2yfuyDpCwmT2C4VdXy77@ofvuHWlFroURthPs3tHyL1px4zf2t/2hw/U6H7f88ooQUWhhG3h5u918 "Java (OpenJDK 8) โ€“ TIO Nexus") Checks the indices in the order specified by the partial sums of the following sum: ``` initial value + 1 - 2 + 3 - 4 + 5 - 6 + ... ``` [Answer] ## C, 69 bytes ``` t;b;f(*d,c,p){for(b=c;c--;)d[c]>d[p]&(t=abs(p-c))<b?b=t:0;*d=d[p+b];} ``` First argument is an in/out argument. Output is stored in its first element. See it [work online](https://tio.run/nexus/c-clang#fVXbjpswEH3PV1grtcqN1gZscNm0H5JGVTC7Eg@bRAnpQ6N8@9ZzBpuQdBspg5k5PjM@M8B7V9XV63TeLN3yMLu87o/TeuUqlyTVrFm7zfdmfdh8nnarbX2aHhI3mz3XP@pV901W82blg4t6U13fJ5N214m3bbubit/7thGzyWUi/I/c2/VGrMRFGCuWIs@8KWllaWVSb1JNAf9XCoZuy4KWBXmNpHta6ZLQZAyFC8A1LXMyFMiIVVmiVeDoiYgzgzfTIaXKKNZjsU@DEWTYBjbwI0BIayLEAoLCLd2DQmKjIa@VCBEsVaHeogjHVhxP01h2ir2lDkfl0iRlTGEgAq0KG/jgS1k92CKopZBUldALkWJAaTtYSWk0islMEJPFigdAJ1QvAxRExaoMOnCpRGIBNSYqhtw2yqZy9pRBIu4juPMhlxzUU4aVgmW90T9OWpiouCFOHFhJsgUArE7BHcbGHFswgRmR8giYKEauhyYPxUJVDIplrizOLB@BGXSUD6fT3FQC6BjumyqDkzVDLb2IYaB4fpWJTOkNCxLw6OZRzpwbzKrwGKvIi7lSmY0zj0NYFaff6Dg6Bh1BChlWUBhScjcyHce/15mnGvJjBkDFk83tx8zwI5ra2AdGoD3cF34irLiKaniV/HL7s7@uxKn987J/nYqtmImvw91abrxj2FD37x6qLAkTneDcI@L6gbgeEdf3xK4nTvnUCY9X8jhfyQcDlo8LcA8FuFEB7r6Api@ADhQyZCPK5oGyGVE2t5Qwp@54dh2W/PruqeZid36rX449NtYM@rHvsD@1Xbvf3bixuMI2267/GsRo@F18K5exwXgEr2L5D1jtg3WEpR@gnI@5iJIfoBofa/6HGunpi3@U1DvHqtIRb4QNAtCnFTSt3y1F5a/Pt5TesVj47@ZY/EDYbr70LVhGRyg73Efpb1KLw9Hn9CxPn5qfuyePnt/xBTA3aDK5vv8F). [Answer] # R, 59 bytes ``` function(l,i)l[j<-l>l[i]][which.min(abs(1:length(l)-i)[j])] ``` returns an anonymous function. In the event that there are two elements greater at equal distances, will return the first (lesser index). [Try it online!](https://tio.run/nexus/r#PcxBCsIwEEDRfU8RcJOBiZiiTZHqCbxByELTxE6JU6EpevuoXbh9fH48lbiwzzSxTEiQ7NipdE6WnLOvgfywfRDL622W@pgC3/MgEygCOzpwhfi55AvNWXRKeKk07k2DB9NibXCHGr@isYaKuA/vX9SIjZg4qBVCX0X5f@BqUD4) [Answer] # Pyth - 28 bytes ``` JEehf>@T1@JQo@NZm(adQ@Jd)UlJ ``` [Try it](http://pyth.herokuapp.com/?code=JEehf%3E%40T1%40JQo%40NZm%28adQ%40Jd%29UlJ&input=2%0A%5B3%2C-1%2C-3%2C-2%2C5%5D&debug=0) [Answer] **Java, 96 Bytes** ``` int f(int n,int[]a){for(int s=1,i=1,x=a[n];0>(n+=i++*s)|n>=a.length||a[n]<=x;s=-s);return a[n];} ``` Identifiers are named like @Leaky Nun's answer. Furthermore, most parts have been aligned to be basically the same: In comparison, the `if` has been replaced by the `for`-condition (sacrificing the additional semicolon). A colon has been removed by moving increment-part into condition (so the parentheses of the previous if-statement practically "moved") - changing & to | did not have impact on character count. [Answer] # PHP, 73 bytes ``` function($i,$a){for(;$b<=$a[$i];)$b=max($a[++$d+$i],$a[$i-$d]);return$b;} ``` closure takes 0-based index and array from arguments. [Verify all test cases](http://sandbox.onlinephpfunctions.com/code/66790388992de6caca8d8677f59e4b104bf4be1b). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` >แป‹@Tแบกรžแป‹โธแธข ``` [Try it online!](https://tio.run/##bVM9bt4wDL2KkVkGREmkrKXoIboFGbMUuUDGzL1DgXbpFYJ2zEm@XsThe6Q7FAFsS@LPM98j9fXx6en5PD/d/nz7/OX2@8fbd9/9fXm9vf48337dnef9LmVMKzqP0mapRYpbpLSHst3bKtvoZTt8Xb5aK1tTt5VNBK/vj@mb6RarfvBVDw/y19wxEaW@Gf66rTuILEcRpEWqY3RYuga4dDdHDKIVEEhHMPKBBptHLEvfgg9VLT8gqyLa3LIqrO5vEuXMGTyEntayqIaEQ6N8/r06eMMLTr7OFQA4NyqAzwzSAng5QBvGebl1XZ/qmIpfdgs5SDqLg34SrKACCpIjaLEUz1sIMUvi@MlK8jJ4PIIsJQfUuHDrJYEYKeNDrSA28aelWuYgICHVPxMuMp1sBMIHIjEK3VHYI0tuQ69eXNVAF7RwMbvnzLA@ZmmKgKqV8rtL0xHy1zCQO/4YSkSPOT1imdv@JQKOkzNSkcFGkCJnSBIHnZa@ctBQ4JIcONNsqUFIANZYIRDUoIhdc@JCJQ4UhEOXkMyZYofQTM59W6kffZCUYnICF67cKHvDHexFcWyE3tmB/b8W7B/0YDBL/B630rHtuM6O5qj6cGL0LG4In/4O "Jelly โ€“ Try It Online") ## How it works ``` >แป‹@Tแบกรžแป‹โธแธข - Main link. Takes the array A on the left and the index i on the right แป‹@ - Get the i'th element of A, k > - Is k greater than each element of A? T - Get the indices of the 1s รž - Sort these indices by: แบก - Absolute difference with i แป‹โธ - Index back into A แธข - Take the first element ``` [Answer] # Pyth, 16 bytes ``` JEh>#@JQ@LJaDQUJ ``` [Test suite](http://pyth.herokuapp.com/?code=JEh>%23%40JQ%40LJaDQUJ&test_suite=1&test_suite_input=45%0A%5B69%2C+43%2C+89%2C+93%2C+62%2C+25%2C+4%2C+11%2C+115%2C+87%2C+174%2C+60%2C+84%2C+58%2C+28%2C+67%2C+71%2C+157%2C+47%2C+8%2C+33%2C+192%2C+187%2C+87%2C+175%2C+32%2C+135%2C+25%2C+137%2C+92%2C+183%2C+151%2C+147%2C+7%2C+133%2C+7%2C+41%2C+12%2C+96%2C+147%2C+9%2C+134%2C+197%2C+3%2C+107%2C+164%2C+90%2C+199%2C+21%2C+71%2C+77%2C+62%2C+190%2C+122%2C+33%2C+127%2C+185%2C+58%2C+92%2C+106%2C+26%2C+24%2C+56%2C+79%2C+71%2C+24%2C+24%2C+114%2C+17%2C+84%2C+121%2C+188%2C+6%2C+177%2C+114%2C+159%2C+159%2C+102%2C+50%2C+136%2C+47%2C+32%2C+1%2C+199%2C+74%2C+141%2C+125%2C+23%2C+118%2C+9%2C+12%2C+100%2C+94%2C+166%2C+12%2C+9%2C+179%2C+147%2C+149%2C+178%2C+90%2C+71%2C+141%2C+49%2C+74%2C+100%2C+199%2C+160%2C+120%2C+14%2C+195%2C+112%2C+176%2C+164%2C+68%2C+88%2C+108%2C+72%2C+124%2C+173%2C+155%2C+146%2C+193%2C+30%2C+2%2C+186%2C+102%2C+45%2C+147%2C+99%2C+178%2C+84%2C+83%2C+93%2C+153%2C+11%2C+171%2C+186%2C+157%2C+32%2C+90%2C+57%2C+181%2C+5%2C+157%2C+106%2C+20%2C+5%2C+194%2C+130%2C+100%2C+97%2C+3%2C+87%2C+116%2C+57%2C+125%2C+157%2C+190%2C+83%2C+148%2C+90%2C+44%2C+156%2C+167%2C+131%2C+100%2C+58%2C+139%2C+183%2C+53%2C+91%2C+151%2C+65%2C+121%2C+61%2C+40%2C+80%2C+40%2C+68%2C+73%2C+20%2C+135%2C+197%2C+124%2C+190%2C+108%2C+66%2C+21%2C+27%2C+147%2C+118%2C+192%2C+29%2C+193%2C+27%2C+155%2C+93%2C+33%2C+129%5D%0A2%0A%5B4%2C+-2%2C+1%2C+-3%2C+5%5D%0A0%0A%5B2124%2C+-173%2C+-155%2C+146%2C+193%2C+-30%2C+2%2C+186%2C+102%2C+4545%5D%0A0%0A%5B1%2C0%2C2%2C3%5D&debug=0&input_size=2). [Answer] ## Clojure, 95 bytes ``` #(%(nth(nth(sort-by first(for[i(range(count %)):when(>(% i)(% %2))][(Math/abs(- i %2))i]))0)1)) ``` This is the shortest I could come up with :( I also tried playing around with this but couldn't bring it to the finish line: ``` #(map(fn[f c](f c))[reverse rest](split-at %2 %)) ``` [Answer] # [JavaScript](https://nodejs.org), 44 bytes ``` a=>g=(i,p)=>(x=a[i-p])>a[i]?x:g(i,p<0?-p:~p) ``` [Try it online!](https://tio.run/##dVPLTiMxELzvV@Q4I9krt59jYMKHoBwiFqIgREaAECd@PXR193DYzR5sj/tR7qruedp/7N/uX4/Lu385/Xk4P87n/bw9zMPRLeO8HT7n/d3RL7txy@fu9vPqAM9NuPXL1dcynq9/3Z9e3k7PD7@fT4fhcbir3W1ycpuJz85njW4TC9vchgiLv6fGH40tNfCFzzJxEK/Kjoaowh@ZF9sSg1BnFEKapjJGgiUVBafEZo1BdAEE0hGMfKDBxhG9mq/Dh6o6X5AVEF3Z0gOs7I@k5bSmPEg8MVpREQlT0fLl9cDgEQuc@GxdAXCPogC2pqQJ8DSBNoxtdZe@boExC55MVeUQ0lYc9CNlBRVQEE1KS0rhvI6QWo04HulGnrJcJyUrkgMqr7hhlYCqUMYmWkFswW/V1KoMAhIUeGtwCdMmjUB4RiRGITGK9Kgat1zWXqzVQBe0sEt2spmR@iSrmAiouoj87CrmUPmDGoQ7XlQltMcyPVQtN/4kAk4mJ5siWRohFGWGyHDQaUrdBg0FdrKBq8VaWiEkAIOeEAhqiIip2MSpSjJQEA5dQrLMlHQIzZS5j930Ex8kFTFlAvtuHHIZx39@w@x8dOR8coVD4oWIKBV4aZT/q1P@QqsygMIFIHLBRZf@403OSxlczlrJ@Rs "JavaScript โ€“ Try It Online") from <https://codegolf.stackexchange.com/a/118765/> [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` รจโ€บฦถ0K<ยน.xรจ ``` 0-based indexing. [Try it online](https://tio.run/##yy9OTMpM/f//8IpHDbuObTPwtjm0U6/i8Ir//w24og11DHSMdIxjAQ) or [verify all test cases](https://tio.run/##XVKxilRBEPyV5eJ6Mj0zPTMNwiVmfsKycCcamGggiJsZ@QF@xZkYGggmd2DsN9yPrFX9FETYt8z0q66uqn5v392@eP3q8v58c311uH3z8nB1zcPjp888nH/9eHa@uf9yebh7/Pj957fy/On91ycfHu4uuByPx83Q54DPhTpRYGDFUE/wEw7H4wj0hhWIhlFRHR1GhDnWhM2OUbA6nP0LY2LypU@SYqE1WFQYkQl2NN6ai8baRL4jxtnDBkLYwV5eK2JkMVjkyJggsBAyOoI6I1BN0@aUMFOt1hxJI7ZckjSgDFT@KHFghjp4rnLBZ0q7kcgW1fM@97rH/pQKJ3EbMiTxOZiuLUXSCefZkkqNKgi@GiP1ky3SgnWdl2QrHXb2naPsPmxIOx/5ZDKi4k7kdCxQmJWFyaJUT@VFUCeAO2kFCnGk1O57ZPs4OmO4IXzLnWm4kJ5WqMYVlMGzlEEVXeSBvGlHsWt3NhJd/2DZrMX1NNUVmPRqgZZ9zN5a5HY5PCx3PDyjHvTP9qJ/@qMheW@eS06P2iUtM0fCtU2FyJT1MdVI36oyBiWgjceJ5vOD7di0pq3pA65ZqiLdlNz2b3Tbf9mJoGSDQW/a36v6REji5Dz9Bg). **Explanation:** ``` รจ # Get the item in the second (implicit) input-list at the first (implicit) # input-index โ€บ # Check for each value in the second (implicit) input-list if it's larger # than this value (1 if truthy; 0 if falsey) ฦถ # Multiply each by its 1-based index 0K # Remove all 0s from this list < # Decrease each value by 1 to make it a 0-based index ยน.x # Pop the list and get the item closest to the first input-index รจ # Use that to index into the second (implicit) input-list # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~110~~ 108 bytes ``` c,o;e(g,l,f)int*g;{for(o=g[l],c=1;c<f;c++)l+c<f&&g[l+c]>o?o=g[l+c],c=f:0,l>=c&&g[l-c]>o?o=g[l-c],c=f:0;g=o;} ``` -2 bytes thanks to ceilingcat!! [Try it online!](https://tio.run/##fVPLbttADDw3X7EI0MCqV6i4L2mrOv2Q1IdAtQwDjhWkPtXwt7scLtXERZCD9kFyZskhNdTbYbhcBjv1m8XW7u1Y7Q7HL9v@NE4vi2m1fdiv7bCifvg@9sNyWe2XfLq7Y/tyWN9PPySEjxw0fmvs/n41iLd@9dazt9@upv58eXrcHRbVzenmEz9ljvSwNitzMilbE7w1He@Z9@SscZFt1hDh43PX8qFlS2r4wnvsOIi/xI4WUZEPgT@2eSahzCwEWIEyh4fFx0JOns0lBtERFIAjGHiwwcYROakvw4esMl@AahCd2JIbWNnvqKTTtqUOEo9zmpQDoIslfXm9YXKHDzXx3uZCgLsTBbC0pWgCPXUoG8Z2dsc8Lw1zRjzpU5FDitbkoB@VqqACEqKulCWpMC4jJCUtHI9kLZ6CXLtSrEgOqjDzNrMElKRkLKIVxBb@NqlaiUlQBDW8tHBJpa00AuEBkRgFzyzSo6S1hTj3Ys4GuqCFWdBeZ0byE1RUEZB1FPnZFdVR5G@KQWrHi0WJ0mOZHkqKdf@AoJPJCapIkEZIiTJDpDzoNPmsg4YEM@nApagtTRAShE3ZIRDUEBF91IkrKslAQTh0CWCZKekQmilz77LqJz5IKmLKBGZz7vUHdPoDBls7S7b2Nr46vTqdPFtLd@r/2lO/05/whiMoB2dZAr34nl/YOy5uj8Tez79@Hm6t2SyOVNr7e/dnM418rczX@cLxVVW9hborqBP2Gek@RPorpJfUZqT/EBmukOEKGd5Bni9/AQ "C (gcc) โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` gUรฐ>UgV)รฑaV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=Z1XwPlVnVinxYVY&input=Wy0xLDQ3Niw1NzgsMjcsMCwxLC0xLDEsMl0KNQ) [Answer] # APL(Dyadic Classic), 21 bytes ``` A[1โ†‘{โต[โ‹|I-โต]}โธA>IโŒทA] ``` [Try it online!](https://tio.run/##LVJLilRBENzPKeICDZX1yarcCL3slQcYZtGMIEKDwqxE3c5GexgXHkX0PO8ibUQ@4dWjKisyMyKyzp8uh3efz5eP7w@Pl/PT04fH2/by6/R2e34td0f@PdAbViAavKIOdJjxG1gTNju8YHWMhbrgE5OXY6JPLLQGiwojMsEDjac2VMbaRN4RM5jDBEKYwVweK8IzGAyyZUwQWAjxjigMBKqp25wiZorVmi0rUWuIkhoUR@VHio4ZyuC@SgXXFHdjIVtkz/Pc4yP2VSoGCzeXIJHPxlRtSZJK2M@WWKpVQfDKPfmzWqQE69ov0ZY7zOx7jbLrMBd3LumkMyo1PZX6AolZWZgMivWUXwR1AjiTViATPan2sVu2t6MymhvCt5yZmgs5UgrZDBllGBlKo4oO0sC6KUe2a3bmia7/sUzW4HqK6jJMfDVAyzx6by1yumweljP2kVY79TO96E99FCTtbeSQU6NmScn0kXBNUybSZT2mGqlbUdogBzTxuDvxsfah18vN8d62559ftuvv@@36/evpwN3Dt@369/jmtP34c3y43f4B "APL (Dyalog Classic) โ€“ Try It Online") [Answer] # TI-Basic, 46 bytes ``` Prompt A Prompt I seq(abs(J-I),J,1,dim(สŸAโ†’B SortA(สŸB,สŸA สŸA(1+sum(not(cumSum(สŸA>สŸA(1 ``` Index is 1-based. Output is stored in `Ans` and is displayed at the end. ]
[Question] [ Create a program or function to unjumble a square of digits by flipping (reversing around the centre point) only rows and columns. **Input** Input will be a 9x9 grid of digits in the form of a 9 line string like the following: ``` 986553229 264564891 759176443 643982153 567891234 526917874 685328912 891732537 117644378 ``` This input format is non-negotiable - any solutions which are "creative" with the input format will be considered invalid. **Output** Output should be a list of flip moves which, when applied to the input in the given order, should recreate the target grid. An example output (not a solution to the previous input example): ``` 28IF5D3EAB9G3 ``` This output format is also non-negotiable. There should be no newlines or spaces in the output, only the characters `1`-`9` and `A`-`I` (lower case characters are acceptable in place of upper case characters if you prefer). The target grid (the state you need to recreate) is as follows: ``` 123456789 234567891 345678912 456789123 567891234 678912345 789123456 891234567 912345678 ``` The numbers `1`-`9` should be used as instructions to flip the rows, and the letters `A`-`I` should be used for the columns. This is shown below with the grid in its restored state. ``` ABCDEFGHI ||||||||| vvvvvvvvv 1 -> 123456789 2 -> 234567891 3 -> 345678912 4 -> 456789123 5 -> 567891234 6 -> 678912345 7 -> 789123456 8 -> 891234567 9 -> 912345678 ``` So an `8` means flip the second row from the bottom, and an `F` means flip the sixth column. In the case that no solution is possible, the program should end without outputting anything at all. **Examples** Input: ``` 987654321 234567891 345678912 456789123 567891234 678912345 789123456 891234567 912345678 ``` Output: ``` 1 ``` In this case only the top row needs flipping to return to the goal state. Input: ``` 123456788 234567897 345678916 456789125 567891234 678912343 789123452 891234561 912345679 ``` Output: ``` I ``` In this case only the final column (column `I`) needs flipping to recreate the goal state. Input: ``` 123456788 798765432 345678916 456789125 567891234 678912343 789123452 891234561 912345679 ``` Output: ``` 2I ``` In this case we need to flip row `2` and then flip column `I` to return to the goal state. **Notes:** * Please include an example usage in your answer. * The output given does not have to be the shortest sequence that will return the goal state - any sequence which returns the goal state will do as long as it works (i.e. as long as I can test it) * I'll endeavour to test each answer and upvote all those that work and have obviously had an attempt at golfing. * **This is an open-ended competition - I'll accept the shortest answer sometime next week, but if a newer valid answer comes along which is shorter at any point in the future I'll change the accepted answer to reflect that**. * The bounty has been set at 200 reputation for the shortest answer received by **23:59:59 (GMT) on 26/01/2014** The bounty was awarded to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for his [268 character GolfScript solution](https://codegolf.stackexchange.com/a/19425/737). **Testing** Please provide your program's output for the following three test grids with your answer: ``` 986553229 264564891 759176443 643982153 567891234 526917874 685328912 891732537 117644378 927354389 194762537 319673942 351982676 567891234 523719844 755128486 268534198 812546671 813654789 738762162 344871987 341989324 567891234 576217856 619623552 194435598 926543271 ``` I've created a small Python program to generate valid grids for testing purposes: ``` import random def output(array): print '\n'.join([''.join(row) for row in array]) def fliprow(rownum, array): return [row[::1-2*(rownum==idx)] for idx,row in enumerate(array)] def flipcol(colnum, array): return zip(*fliprow(colnum, zip(*array))) def randomflip(array): op=random.randint(0,1) row=random.randint(0,9) if(op==1): return fliprow(row, array) else: return flipcol(row, array) def jumble(array): arraycopy=array for i in range(10, 1000): arraycopy=randomflip(arraycopy) return arraycopy startarray=[ ['1','2','3','4','5','6','7','8','9'], ['2','3','4','5','6','7','8','9','1'], ['3','4','5','6','7','8','9','1','2'], ['4','5','6','7','8','9','1','2','3'], ['5','6','7','8','9','1','2','3','4'], ['6','7','8','9','1','2','3','4','5'], ['7','8','9','1','2','3','4','5','6'], ['8','9','1','2','3','4','5','6','7'], ['9','1','2','3','4','5','6','7','8']] print output(jumble(startarray)) ``` [Answer] # Mathematica ~~582~~ ~~575~~ ~~503~~ ~~464~~ 282 To fight with golfscripters I have to use heavy artillery! ``` i = "986553229 264564891 759176443 643982153 567891234 526917874 685328912 891732537 117644378"; a=Array;h@M_:=Join@@a[9(Mใ€š##ใ€›/. 9->9โŒˆ2Random[]โŒ‰)+Abs[{##}-5]&,n={9,9}]; For[i_~t~j_:=i{#2,10-#2}+j#-9&~a~{9,4},!ListQ[e=GroupElementToWord[ PermutationGroup[Cycles/@Join[1~t~9,9~t~1]], h[ToCharacterCode@StringSplit@i-48]~FindPermutation~h@a[Mod[8+##,9,1]&,n]]],]; e~IntegerString~36<>"" ``` Output: ``` g69g69g8g8g7g7gd96d96d8d8d7d7dh6h64a6a46d6d4g4g6b6b7h7h7c7c2a8a27b7bd8db8b7f7fg8g82c2c94a4a3a3aigfdc91 ``` Here `PermutationGroup[...]` sets up possible flips and `GroupElementToWord[...]` solves the problem (about `0.2` sec). The main problem is that it is difficult to identify the correspondence between the position of `9` in the initial and the final grid. For golfing I do it randomly (it takes several seconds). There are some warnings but one can ignore them. Other to test grids: ``` g69g69g8g8g7g7gh89h89h7h7h6h6hf6f6g6g64f4f4h4hg7g73g3g2a8a28d8db8b83d3dg8g82c2c9a3a643a3a2g9f9d9c9ga h89h89h7h7h6h6h6h6h6f6f6g6g6d6d3a7a37g7g7h7h3c3c2a8a27b7b8d8d2f2f8b8b3f3f2b2ba2a764a8aih9g9c9gb1i ``` It completely reproduces the examples: ``` 1 i 2i ``` --- ## Previous solution (464) without any clever built-in functions and with runtime 4 ms: ``` M=ToCharacterCode@StringSplit@i-48; S="";s=Signature;H=(S=S<>{#,#2+9}~IntegerString~36)&; A=(m=Mใ€š##ใ€›)-9Mod[m+##,2]&[s@{2#3,5}#,2#2#3~Mod~2-#2]&~Array~{4,4,4}; u=s/@Join@@A; H@@({k,l}=#&@@@#~Position~1&/@{v=uใ€š13;;ใ€›;{h=#2uใ€š2ใ€›,-#uใ€š5ใ€›,-#uใ€š9ใ€›}&@@v,vใ€š4ใ€›=uใ€š4ใ€›h;v}); Aใ€škใ€›=Aใ€šk,;;,{2,1,3,4}ใ€›;Aใ€š;;,lใ€›=Aใ€š;;,l,{3,2,1,4}ใ€›; MapIndexed[4#โ‰ #4&&H@@@If[#2<3,#0[#3,#,#2,#4];k,#0[#,#3,#4,#2];10-k]&@@ If[s@#<0,#ใ€š{1,3,2,4}ใ€›,#]&@Ordering[k={#2,#2};#]&,A,{2}]; Mใ€š5,1ใ€›<5&&5~H~{};Mใ€š1,5ใ€›<5&&{}~H~5;S ``` All new lines here are not necessary. Output: ``` 3b9i9i1a1a1a1a9i9i1a1a9h9h1b1b1b1b9h9h9g9g1c1c9g9g9f9f1d1d9f9f8h8h2b2b8f8f8f8f7i7i7h7h3b3b3b3b7h7h3b3b7h7h7g7g3c3c7g7g3c3c7f7f6i6i4a4a6h6h4b4b4b4b6g6g4c4c6g6g4c4c6f6f4d4d4d4d6f6f4d4d6f6f4d4d ``` Other two test grids: ``` 13ab9i9i1a1a9i9i9h9h1b1b1b1b9h9h9f9f8i8i8i8i8h8h2b2b2b2b8h8h8h8h8g8g8g8g8f8f2d2d2d2d8f8f2d2d7i7i3a3a3a3a7i7i7h7h3b3b7h7h3b3b7g7g3c3c3c3c7g7g3c3c7f7f3d3d3d3d7f7f7f7f6i6i4a4a6i6i6h6h4b4b4b4b6h6h4b4b6g6g4c4c4c4c6f6f4d4d4d4d6f6f4d4d6f6f 2bc9i9i1a1a9i9i9g9g1c1c9g9g1c1c9f9f1d1d1d1d8i8i8i8i8h8h2b2b2b2b8f8f2d2d7i7i7h7h3b3b3b3b7h7h3b3b7g7g3c3c7f7f3d3d3d3d7f7f3d3d6i6i4a4a4a4a6h6h4b4b6g6g6g6g6f6f4d4d ``` Visualization: ``` anim = Reap[Fold[Function[{m, i}, If[i > 9, (Sow@Grid[#, Background -> {i - 9 -> Pink, None}] & /@ {m, #}; #) &@ Transpose@MapAt[Reverse, Transpose@m, i - 9], (Sow@Grid[#, Background -> {None, i -> Pink}] & /@ {m, #}; #) &@ MapAt[Reverse, m, i]]], M, IntegerDigits[FromDigits[S, 36], 36]]]; ListAnimate[Join[{#, #} &@Grid@M, anim[[2, 1]], {#, #} &@Grid@anim[[1]]], 5] ``` ![enter image description here](https://i.stack.imgur.com/S4W7F.gif) The input string `i` can be generated randomly by ``` M = Array[Mod[8 + ##, 9, 1] &, {9, 9}]; (M[[#]] = Reverse@M[[#]]; M[[All, #2]] = Reverse@M[[All, #2]];) & @@@ RandomInteger[{1, 9}, {10000, 2}]; i = ToString /@ # <> "\n" & /@ M <> "" ``` ## Brief discussion * Flips can interchange only these elements ("quadruple"): ![enter image description here](https://i.stack.imgur.com/6Cg4m.png) * It is possible to interchange these elements separately from other elements only if the initial and the final order has the same signature. * Flips of these four elements form the [alternating group of degree 4](http://groupprops.subwiki.org/wiki/Alternating_group:A4) ( = group of rotations of the tetrahedral). Every element of this group is a composition of 2 generating elements. So if we know the initial and final position we can decompose the corresponding transformation as a combination of a simple flips. ## Details For sportsmanship I post details before the end of the bounty! ``` M=ToCharacterCode@StringSplit@i-48; ``` Convert the string `i` to the matrix `M`. ``` S="";s=Signature;H=(S=S<>{#,#2+9}~IntegerString~36)&; ``` We will append chars to `S`. Now it is the empty string. `H[i,j]` will add the character `i` (`1,2,3,...,9`) and the character `j` (`a,b,c,...,i` in base-36). ``` A=(m=Mใ€š##ใ€›)-9Mod[m+##,2]&[s@{2#3,5}#,2#2#3~Mod~2-#2]&~Array~{4,4,4}; ``` I convert elements as ![enter image description here](https://i.stack.imgur.com/kpGa9.png) to obtain the target matrix in the following form ![enter image description here](https://i.stack.imgur.com/Z5VFn.png) Then there are two main steps in my algorithm 1. Find flips to obtain the signatures as in the target matrix (e.g. the signature of `{-7,-1,1,7}` is `1` and the signature of `{-6,2,-2,6}` is `-1`): ``` u=s/@Join@@A; H@@({k,l}=#&@@@#~Position~1&/@{v=uใ€š13;;ใ€›;{h=#2uใ€š2ใ€›,-#uใ€š5ใ€›,-#uใ€š9ใ€›}&@@v,vใ€š4ใ€›=uใ€š4ใ€›h;v}); Aใ€škใ€›=Aใ€šk,;;,{2,1,3,4}ใ€›;Aใ€š;;,lใ€›=Aใ€š;;,l,{3,2,1,4}ใ€›; ``` 2. Rotate every "quadruple" to obtain the right order: ``` MapIndexed[4#โ‰ #4&&H@@@If[#2<3,#0[#3,#,#2,#4];k,#0[#,#3,#4,#2];10-k]&@@ If[s@#<0,#ใ€š{1,3,2,4}ใ€›,#]&@Ordering[k={#2,#2};#]&,A,{2}]; ``` It is the most nontrivial part of the algorithm. For example, the transformation `1b1b` will convert `{-7,-1,1,7}` to `{-1,1,-7,7}`. The transformation `9h9h` will convert `{-7,-1,1,7}` to `{-7,7,-1,1}`. So we have two maps ``` {1,2,3,4} -> {2,3,1,4} {1,2,3,4} -> {1,4,2,3} ``` and we want to convert an arbitrary ordering `{x,y,z,w}` to `{1,2,3,4}`. The simple method is (except a random search) ``` repeat {x, y, z, w} -> If[z < 3, {y, z, x, w}, {x, w, y, z}] until {1,2,3,4} ``` I can't proof it, but it works! The last step is ``` Mใ€š5,1ใ€›<5&&5~H~{};Mใ€š1,5ใ€›<5&&{}~H~5;S ``` It performs trivial flips of the center row and the center column and return the result. [Answer] ### GolfScript, 300 279 268 characters ``` n%`{\5,{.9+}%{;.2/\2%},\;''{1${.9/7+7*+}%+:z;}:?~{{.9<77*{\zip\9-}>:Z~{1$!{-1%}*\(\}@%\Z;}/}:E~{:^;{:c;.`{[\E[.^=\8^-=]{.c=\8c-=}%[^c+^8c-+8^-c+16c-^-]{9%49+}%=}+[[]]:K[[8^- 17c-][^9c+]1$]{:s;{[[]s.+.2$+]{1$+}/}%.&}/\,K+0=z?E}5,/}5,/{{+9%)}+9,%''*}9,%={z:u;}*}+1024,/u ``` Note that this code is extremely slow (also due to heavy code-block manipulation) and might run several minutes. The code is very un-golfscript-ish with lots of variables and explicit loops. I had written a more analytic solution which ran for less than a second. I completely broke that one during golfing. Unfortunately, I wasn't able to backtrack or repair the code in the last two days. Therefore, I produced this try-and-check version which is shorter anyways. The answers for the puzzles given above: ``` 1A2C4D9G9G9G9G1C1C1C1C9F9F9F9F1D1D1D1D2A2A2A2A8H8H8H8H2B2B2B2B2C2C8F8F2D2D2D2D3A3A7I7I3B3B7H7H7G7G7G7G3D3D7F7F6I6I6I6I4A4A4A4A6H6H6H6H6G6G4C4C4C4C6F6F4D4D 1AB39I9I1A1A9I9I1B1B9F9F8I8I8I8I2B2B8H8H8G8G8G8G2D2D2D2D3A3A3A3A7H7H7H7H3C3C3C3C3D3D7F7F6I6I4A4A6I6I4B4B4B4B6G6G4C4C4C4C6F6F6F6F4D4D 1A34D9I9I9I9I1A1A1A1A1B1B1B1B9G9G1C1C1C1C9F9F9F9F1D1D9F9F8I8I2A2A2A2A8H8H8H8H2C2C2C2C8F8F2D2D8F8F7I7I7I7I3A3A3B3B7G7G7G7G3C3C3C3C6I6I6I6I6H6H6H6H4B4B4B4B6G6G6G6G4C4C6G6G6F6F4D4D6F6F ``` [Answer] # J ~~487~~ 438 ``` q=:3 :'(>:9|+/~i.9)=/&((,{;/(,.8&-)y){])g' l=:2 :0 : o=:o,(m+x){a. x&(|.@{`[`]})&.v y ) r=:49 l] c=:97 l|: w=:2 :'g=:4 v^:(4=(<m){g)g' p=:_1=C.!.2@,@:I.@q t=:2 :'for_i.>:i.3 do.g=:i v^:(p m*i)g end.' z=:2 :0 'i j I J'=.y,8-y g=:".'(',(,' ',.,(I.m{q y){,;._1 n),'])^:2 g' ) d=:3 :0 g=:9 9$".,_ list,' ',.y o=:'' 0 4 w c 4 0 w r 0 1 t c g=:0 c^:(-.(p 1 0)=p 1 2)g 1 0 t r for_k.>,{;~i.4 do.0 z';;jcir;irjc;Irjc'k 3 z';;IrJc;JcIr;'k end.o ) ``` `d` is a verb which takes a grid string in the specified format and returns a solution string in the specified format. Example use: ``` d '987654321',LF,'234567891',LF,'345678912',LF,'456789123',LF,'567891234',LF,'678912345',LF,'789123456',LF,'891234567',LF,'912345678' bcda2341a1a1b1b1c1c1d1da2a2b2b2c2c2d2d2a3a3b3b3c3c3d3d3a4a4b4b4c4c4d4d4 ``` Now accepts either newline type. Solutions to the test grids: ``` b3a1a11b1bc9c99g9gd9d99f9fb8b8f8f87i7i7h7hc3c3g7g77f7fa6a64b4bh6h6c4c4g6g6d6d6f6f6 cd24a9a91c1c1d1d9f9fa2a2i8i88h8hc2c2g8g82d2d3b3bh7h7d3d37f7fa6a64b4bg6g64d4d6f6f bc2a9a99i9ic1c1g9g91d1df9f9i8i8b2b2h8h82c2cd8d87i7ib3b3c7c7d3d34a4ai6i6b6b6g6g6d6d6 ``` I'm fairly new to J; this could probably be golfed even further. --- Checking for invalid/unsolvable grids incurs a 123 character penalty. I don't think the other answers to date have such error checking. To do so, change the first line of `d` to this: ``` if.-.+./89 90=#y do.0 return.end.if.-.*./(/:~y)=/:~(#y)$'123456789',LF do.0 return.end.g=:9 9$".,_ list,' ',.y ``` and the last line to this: ``` 3 z';;IrJc;JcIr;'k end.if.*./,g=>:9|+/~i.9 do.o return.end.0 ``` I've chosen to return `0` on such errors as returning an empty string would be indistinguishable from correctly solving a fully solved grid. Note that this assumes UNIX newlines (again). [Answer] ## C# ~~540~~ 399 Well, sacrificed performance (now it takes up to 30 seconds), introduced dynamic variables, slightly changed logic of solution. And yes, now it is expecting input as one string with line-breaks (as required in rules). Of course C# do not have predefined math functions, so it would be hard to fight with Mathematica guys. Nevertheless, this was a great challenge, thanks to the author! ``` string S(string _){for(i=0,e=1>0;e;){ for(h=v=j=0;j<89;)m[j/10,j%10+9]=_[j++]-49;a=""; for(j=i++;j>0;v++,j/=2)if(j%2>0)F(v); for(;h<9&(h<4|!e);h+=j/36,j%=36)if((e=m[h,g=j++%9+9]!=(t=(h+g)%9))|m[v=8-h,g]==t){F(v);F(g);F(v);F(g);} }return a;}void F(int z){for(f=z<9;++l<9;)m[0,l]=m[f?z:l,f?9+l:z];for(;l-->0;)m[f?z:l,f?9+l:z]=m[0,8-l];a+=(char)(z+=f?49:56);} dynamic h,v,i,j,e,t,l=-1,g,a,m=new int[9,19],f; ``` Test grids: ``` 3B9A9A9B9B9C9C9D9D9F9F9G9G9H9H9I9I9B9B9C9C9D9D9F9F9G9G9H9H9C9C9D9D9C9C9D9D8B8B8F8F8H8H8B8B8F8F8B8B8H8H7B7B7C7C7F7F7H7H7I7I7H7H6A6A6B6B6C6C6D6D6F6F6H6H6A6A6B6B6D6D6F6F6D6D6D6D6F6F5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I 13AB9A9A9B9B9F9F9H9H9A9A9B9B9H9H9I9I8B8B8D8D8F8F8G8G8H8H8I8I8B8B8G8G8H8H8I8I8H8H7A7A7B7B7C7C7D7D7F7F7G7G7I7I7A7A7D7D7F7F7I7I7F7F6A6A6B6B6C6C6D6D6F6F6G6G6H6H6I6I6A6A6C6C6F6F6I6I6A6A6A6A5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I 2BC9A9A9C9C9D9D9F9F9A9A9D9D9I9I8B8B8D8D8H8H8I8I8B8B8D8D8I8I7B7B7C7C7D7D7F7F7G7G7H7H7I7I7C7C7C7C7G7G6A6A6B6B6D6D6F6F6G6G6I6I6A6A6B6B6D6D6G6G6D6D6F6F5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I5A5A5B5B5C5C5D5D5E5E5F5F5G5G5H5H5I5I ``` --- ## Old Solution (540) Works in less than a second on any input (tested on thousands randomly generated grids). Maximum length of output string is 165 (initially any grid was solved in no more than 82 flips, but during golfing I sacrificed this). ``` string S(string[]_){for(i=0;i<1<<18;){ for(j=0;j<81;)m[j/9+49,j%9+65]=_[j/9][j++%9]-49;a="";char g,h='1',v='9',b,x=h,y; for(j=i;j>0;x=x==v?'A':++x,j/=2)if(j%2>0)F(x);j=i+1; for(i+=1<<19;h<58;h++,v--)for(g='A',b='I';g<74;g++,b--){ t=(h+g-6)%9;e=m[h,g];q=m[v,g];i=h>52&t!=e?j:i; if(e!=t|q==t){x=q==t?v:g;y=q==t?g:v; if(m[h,b]==t){x=b;y=h;} F(x);F(y);F(x);F(y);}}}return a;} void F(char z){var f=z<65;for(l=0;l<4;l++){n=m[d=f?z:49+l,s=f?65+l:z];m[d,s]=m[o=f?z:57-l,u=f?73-l:z];m[o,u]=n;}a+=z;} int i,j,q,e,t,l,s,d,n,u,o;int[,]m=new int[99,99];string a; ``` Answer for example 1: ``` 15A5A5B5B5C5C5D5DE5E55F5F5G5G5H5H5I5I ``` Answer for example 2: ``` 19AI1I1H1H1G1G1F1F19F9F9G9G9H9H9I9I8A8AI8I87A7AI7I76A6AI6I65A5A5B5B5C5C5D 5DE5E55F5F5G5G5H5H5I5I ``` Answer for example 3: ``` 129AI1I1H1H1G1G1F1F19F9F9G9G9H9H9I9I8A8AI8I87A7AI7I76A6AI6I65A5A5B5B5C5C5 D5DE5E55F5F5G5G5H5H5I5I ``` Answers for test squares: ``` 346B9A9AH1H1C9C9D9D99F9F9G9GH9H99I9IB8B8F8F87B7B7C7C7F7FH7H77I7I6A6A6B6BC6C66D6DG6G6H6H66I6I5A5A5B5B5C5C5D5DE5E55F5F5G5G5H5H5I5I 1346ABA9A9H1H19F9FH9H99I9IH2H28D8D8F8FG8G8I8I8I3I37B7B7C7CF3F37G7GI7I7H4H4D6D66F6F5A5A5B5B5C5C5D5DE5E55F5F5G5G5H5H5I5I 2BCA9A99C9CF1F19F9F9I9IH2H2D8D88H8HI8I87B7BC7C77D7D7F7F7H7H7I7II4I4B6B6D6D6G6G66I6I5A5A5B5B5C5C5D5DE5E55F5F5G5G5H5H5I5I ``` ]
[Question] [ A traveler needs to stay for *n* days in a hotel outside town. He is out of cash and his credit card is expired. But he has a gold chain with *n* links. The rule in this hotel is that residents should pay their rent every morning. The traveler comes to an agreement with the manager to pay one link of the golden chain for each day. But the manager also demands that the traveler should make the least possible damage to the chain while paying every day. In other words, he has to come up with a solution to cut as few links as possible. Cutting a link creates three subchains: one containing only the cut link, and one on each side. For example, cutting the third link of a chain of length 8 creates subchains of length [2, 1, 5]. The manager is happy to make change, so the traveller can pay the first day with the chain of length 1, then the second day with the chain of length 2, getting the first chain back. Your code should input the length *n*, and output a list of links to cut of minimum length. **Rules**: * *n* is an integer > 0. * You can use either 0-based or 1-based indexing for the links. * For some numbers, the solution is not unique. For example, if `n = 15` both `[3, 8]` and `[4, 8]` are valid outputs. * You can either return the list, or print it with any reasonable separator. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. **Test cases**: ``` Input Output (1-indexed) 1 [] 3 [1] 7 [3] 15 [3, 8] 149 [6, 17, 38, 79] ``` **Detailed example** For *n* = 15, cutting the links 3 and 8 results in subchains of length `[2, 1, 4, 1, 7]`. This is a valid solution because: ``` 1 = 1 2 = 2 3 = 1+2 4 = 4 5 = 1+4 6 = 2+4 7 = 7 8 = 1+7 9 = 2+7 10 = 1+2+7 11 = 4+7 12 = 1+4+7 13 = 2+4+7 14 = 1+2+4+7 15 = 1+1+2+4+7 ``` No solution with only one cut exists, so this is an optimal solution. **Addendum** Note that this problem is related to integer partitioning. We're looking for a partition *P* of *n* such that all integers from 1 to *n* have at least one patition that is a subset of *P*. Here's a [YouTube video](https://www.youtube.com/watch?v=CZN26bjRY7g) about one possible algorithm for this problem. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~11~~ 8 bytes ``` ฮ”รN-;ะธg= ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JTDvX661hd2pNv@/29kDAA "05AB1E โ€“ Try It Online") Uses 0-based indexing. ### Explanation: ``` # start from the implicit input ฮ” # loop forever ร # subtract 2 N- # subtract the current iteration number ; # divide by 2 ะธ # create a list of length x g # get the length of the list = # print ``` `ะธg` looks like a noop, but it actually does two useful things: it truncates to an integer (`;` returns a float), and it crashes the interpreter if x is negative (this is the only exit condition). --- The 23 byte solution used a very different approach, so here it is for posterity: `ร…ล“ส’R2รคฮธP}ส’รฆOรชยฅP}ฮธ2รคฮธฮทโ‚ฌO` ([TIO](https://tio.run/##yy9OTMpM/f//cOvRyacmBRkdXnJuR0DtqUmHl/kfXnVoaUDtuR1gsXPbHzWt8f//3wIA), [explanation](https://paste.ubuntu.com/p/39zJw6XpfG/)). [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` f=lambda n,i=0:n>=i<<i and f(n,i+1)or[min(n,2**j*i-i+j)for j in range(1,i)] ``` [Try it online!](https://tio.run/##TcixDsIgFAXQ3a94W3kUE@jYlP6IdcBU9BL7aAiLX0/r5njO/q3vLENr0X/C9lgDiYG3o8we0wQKslJU5/WOc7ltkBOD1knjij5xzIUSQagEeT2VM@B7@yX@01nL44X2AqkE0y21M1GB2wE "Python 2 โ€“ Try It Online") --- ### Explanation: Builds a sequence of 'binary' chunks, with a base number matching the number of cuts. Eg: `63` can be done in 3 cuts, which means a partition in base-4 (as we have 3 single rings): Cuts: `5, 14, 31`, which gives chains of `4 1 8 1 16 1 32` (sorted: `1 1 1 4 8 16 32`). All numbers can be made: ``` 1 1 2 1 1 3 1 1 1 4 4 ... 42 1 1 8 32 ... 62 1 1 4 8 16 32 63 1 1 1 4 8 16 32 ``` Other examples: ``` 18: 4,11 -> 3 1 6 1 7 27: 5,14,27 -> 4 1 8 1 13 1 36: 5,14,31 -> 4 1 8 1 16 1 5 86: 6,17,38,79 -> 5 1 10 1 20 1 40 1 7 ``` [Answer] # [R](https://www.r-project.org/), ~~77~~ 69 bytes -8 bytes thanks to Aaron Hayman ``` pmin(n<-scan(),0:(k=sum((a=2:n)*2^a<=n))+cumsum((k+2)*2^(0:k))+1)[-n] ``` [Try it online!](https://tio.run/##RclBCsMgEADAe1@xeNptDKhHiS9JWxBBWMRNSSIESt9um156nVl7DrlJ2nkRPDRsKcof6KBXf1YWlGk8C0kbjyVsrSLG4LzQ1T3iFIRoSK3@vAzuVDS@fNXSPMq9vy95WZGBBay3xhCkuCNrUF5pyMik1U0U9Q8 "R โ€“ Try It Online") Let \$k\$ be the number of cuts needed; \$k\$ is the smallest integer such that \$(k+1)\cdot2^k\geq n\$. Indeed, a possible solution is then to have subchains of lengths \$1,1,\ldots,1\$ (\$k\$ times) and \$(k+1), 2(k+1), 4(k+1), 8(k+1), \ldots, (k+1)\cdot 2^{k-1}\$. It is easy to check that this is sufficient and optimal. (The last subchain might need to be made shorter if we exceed the total length of the chain.) Ungolfed (based on previous, similar version): ``` n = scan() # read input if(n - 1){ # If n==1, return NULL k = match(F, (a = 2:n) * 2 ^ a > n) # compute k b = (k + 1) * 2 ^ (1:k - 1) # lengths of subchains c = 1:k + cumsum(b) # positions of cuts pmin(c, n ) # if last value is >n, coerce it to n } ``` (Proof that the value of \$k\$ is as I state: suppose we have \$k\$ cuts. We then have \$k\$ unit subchains, so we need the first subchain to be of length \$k+1\$. We can now handle all lengths up to \$2k+1\$, so we need the next one to be of length \$2k+2\$, then \$4k+4\$... Thus the maximum we can get out of \$k\$ cuts is obtained by summing all those lengths, which gives \$(k+1)\cdot 2^k-1\$.) If \$a(k)\$ is the smallest integer \$n\$ requiring \$k\$ cuts, then \$a(k)\$ is [OEIS A134401](https://oeis.org/A134401). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` โ€™_โ€˜ษผ:2ยป-ยตฦฌแน–แธŠ ``` [Try it online!](https://tio.run/##AUYAuf9qZWxsef//4oCZX@KAmMm8OjLCuy3Ctcas4bmW4biK/zDCqeG5mzvigJwgLT4g4oCdO8OHxZLhuZgkCjEwMDDDh@KCrFn/ "Jelly โ€“ Try It Online") Translation of [Grimy's 05AB1E answer](https://codegolf.stackexchange.com/a/186992/42248) so be sure to upvote that one too! Slightly disappointed this comes in a byte longer, but does at least have something a bit like an emoticon as the first three bytes! [Answer] # JavaScript (ES6), 66 bytes This is a port of [TFeld's answer](https://codegolf.stackexchange.com/a/186986/58563). ``` n=>(g=a=>n<++i<<i?a.map(j=>(j+=(i<<j)-i)>n?n:j):g([...a,i]))(i=[]) ``` [Try it online!](https://tio.run/##DcixDoIwFEDR3a/oZps@moAYBWmZXBx0cCQMDdLaBl8JEBO/vvYOdzhef/U6LG7eMgyvMRoZUSpqpZYKG85d07hWi4@eqU/uuaSJPMscU9hi7VltaSeE0OB6xqiTXc/ipcuhgAOc4AwV5EcoSsjLqt8JE5arHt4UiVRkCLiGaRRTsAk42ZNMpXFyez7uYt0Wh9aZHzUUWSr@AQ "JavaScript (Node.js) โ€“ Try It Online") [Answer] # C++, ~~109~~,107 bytes -2 bytes thanks to Kevin ``` #include<iostream> main(){int n,k=0;for(std::cin>>n;++k<<k<n;);for(n-=k;n>0;k*=2,n-=k+1)std::cout<<n<<',';} ``` The algorithm is similar to the Robin Ryder's answer. The code is written in a compilable, whole form. [Try it!](https://wandbox.org/permlink/2IHg21MGQENjJRyE) Details: ``` std::cin>>n; // get the value of n as input while(++k<<k<n); // determine k for(n-=k;n>0;k*=2,n-=k+1) // we don't need n, so the lengths... std::cout<<n<<' '; // of links are subtracted repeatedly ``` This has a **C** variation with the same byte length (doesn't seem to need a separate answer): ``` #include<stdio.h> main(){int n,k=0;for(scanf("%d",&n);++k<<k<n;);for(n-=k;n>0;k*=2,n-=k+1)printf("%d,",n);} ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` .+ 11,$&$* +`\b(1+),(\1(1*)1?\3)$ 1$2ยถ1$1,$3 1+, 1 1A` 1+ $.& ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5vL0FBHRU1Fi0s7ISZJw1BbU0cjxlDDUEvT0D7GWFOFy1DF6NA2QxWgImMuQ20dLkMuQ8cEIItLRU/t/38jYwA "Retina 0.8.2 โ€“ Try It Online") 1-indexed port of @Grimy's answer. Explanation: ``` .+ 11,$&$* ``` Start with `N=2` and the input converted to unary. ``` +`\b(1+),(\1(1*)1?\3)$ ``` Repeatedly try to subtract `N` from the input and then divide by 2. ``` 1$2ยถ1$1,$3 ``` If successful, remember 1 more than the input on the previous line, increment `N` on the current line, and update the input to the new value. ``` 1+, 1 ``` Remove `N` and increment the last value so that it's also 1-indexed. ``` 1A` ``` Remove the incremented original input. ``` 1+ $.& ``` Convert the results to decimal. [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->n{(1...c=(0..n).find{|r|n<r<<r}).map{|b|[n,b-c+(c<<b)].min}} ``` [Try it online!](https://tio.run/##LcuxCoAgEADQva9wVKojt4azHxGHNISGDhECw/PbjaD9vXz7p0fT542q1AAQjFwASEE86aicmTAj5qbg2lNlz5YmP4dRBkSvHFwntda/uurfFB6ESMKWSURbnBtafwE "Ruby โ€“ Try It Online") Mostly stolen from TFeld's Python answer. ]
[Question] [ One of the lesser known programming paradigms which seems rather fitting for code golfing is *Overlapping Oriented Programming (OOP)* \*. When writing partly identical code, many bytes can be saved by simply overlapping the identical parts and remembering in some way where the two original code lines start. Your task is to write two **overlapping** programs or functions `compress` and `decompress` with the following specification: \*Do not use in production code, probably. ## `compress` `compress` takes two strings in any convenient format and overlaps them as much as possible. That is a string `s` with minimal length is returned such that both input strings are substrings of `s`. Additionally, some output which identifies the start and end indices of both string is returned. **Examples:** (The exact IO-format is up to you) ``` compress("abcd", "deab") -> "deabcd" ((2,5),(0,3)) compress("abcd", "bc") -> "abcd" ((0,3),(1,2)) compress("abc", "def") -> "abcdef" ((0,2),(3,5)) or "defabc" ((3,5),(0,2)) ``` ## `decompress` `decompress` computes the inverse function of `compress`, that is given a string and two start and end indices (in the format in which they are returned by your `compress`), return the two original strings. You need only handle valid inputs. The following equality should hold for all strings `s1`, `s2`: ``` (s1, s2) == decompress (compress (s1, s2)) ``` **Examples:** (inverses of `compress` examples) ``` decompress "deabcd" ((2,5),(0,3)) -> "abcd" "deab" decompress "abcd" ((0,3),(1,2)) -> "abcd" "bc" decompress "abcdef" ((0,2),(3,5)) -> "abc" "def" or (whichever version your "compress" generates) decompress "defabc" ((3,5),(0,2)) -> "abc" "def" ``` ## Scoring Your score is the size of the string returned by calling `compress("<code of compress>", "<code of decompress>")`. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") a lower score is better. **Example:** Assume the code for your function `compress` is `c=abcd` and the code for `decompress` is `d=efghi`. Then `compress("c=abcd", "d=efghi")` yields `"c=abcd=efghi"` (and the indices, but those don't affect scoring) so the score is `length "c=abcd=efghi" = 12`. ## Additional Rules * In the spirit of this challenge, your `compress` and `decompress` **must overlap** in at least one character. You may achieve this trivially by adding a comment, but note that doing so will increase your score and there might be shorter solutions using inherently overlapping code. * `compress` and `decompress` should be able to handle strings containing any printable ASCII characters as well as all characters you used to define `compress` and `decompress`. * The indices can be zero- or one-indexed. * Your programs or functions don't have to actually be named `compress` and `decompress`. [Answer] # GNU Prolog, 105 points ``` s(U,L/M,C):-prefix(A,C),length(A,M),suffix(U,A),length(U,L). o(A-B,C-X-Y):-length(C,_),s(A,X,C),s(B,Y,C). ``` (This requires GNU Prolog because `prefix` and `suffix` are not portable.) Prolog has one interesting, major advantage for this challenge; you can write a function to handle multiple call patterns (i.e. not only can you give the function an input to get a corresponding output, you can give the function an output to get the corresponding input). As such, we can define a function that can handle both compression and decompression, leading to a 105-byte submission that defines a function `o` that works both ways round. (Incidentally, I mostly wrote it as a decompressor โ€“ as it's simpler โ€“ and got the compressor "for free". ) In general, we could expect a very short program in Prolog for this task, if not for the fact that it's so bad at string handling (both in terms of missing primitives, and in terms of the primitives in question having terribly long names). The first argument to `o` is a tuple of strings, e.g. `"abcd"-"deab"`. The second argument has a form like `"deabcd"-4/6-4/4`; this is a fairly standard nested tuple, and means that the string is "deabcd", the first string has length 4 and ends at the sixth character, the second string has length 4 and ends at the fourth character. (Note that a string in GNU Prolog is just a list of character codes, which makes debugging annoying because the implementation prefers the latter interpretation by default.) If you give `o` one argument, it'll output the other for you (thus working as a compressor if you give the first argument, and a decompressor if you give the second). If you give it both arguments, it'll verify that the compressed representation matches the strings given. If you give it zero arguments, it'll generate output like this: ``` | ?- o(X,Y). X = []-[] Y = []-0/0-0/0 ? ; X = []-[] Y = [_]-0/0-0/0 ? ; X = []-[A] Y = [A]-0/0-1/1 ? ; โ€ฆmany lines laterโ€ฆ X = [A]-[B,A,C] Y = [B,A,C]-1/2-3/3 ? ; ``` The above description of the I/O format is pretty much entirely just a description of the program, too; there's not very much in the program at all. The only subtlety is to do with evaluation order hints; we need to ensure that the program doesn't just use a search strategy that's guaranteed to terminate, but also produces the shortest possible output string. When compressing, we start with `length(C,_)` ("`C` has a length"), which is a trick that I've used in many Prolog and Brachylog answers; if this is the first thing Prolog sees, it'll cause it to prioritise reducing the length of `C` over anything else. This ensures that we have a minimum-length `C`. The ordering of the constraints in `s` is carefully chosen so that the search will take a finite time for each possible candidate length of `C`; `A` is constrained by `C` (we don't know `C`, but we do know the target value we have for its length), `M` by `A`, `U` by `A`, and `L` by `U`, so none of the searches can take unlimited time. When decompressing, we're given `C` directly by the user. This again ensures the program will run in finite time, due to the same sequence of constraints. (People who are aware of Prolog's evaluation order will note that the definition of `s` is very inefficient when decompressing; placing `length(A,M)` and `length(U,L)` first would be faster, but moving `length(A,M)` to the start could cause an infinite loop when compressing because neither `A` nor `M` is bound by anything at the time.) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~50~~ 46 bytes ``` {ฤŠโˆงLฤ‹โ‚‚lโˆงLgj:?z{tTโˆง?h~cแนชhlIโˆงแนชbhTl:I+-โ‚:Iโ†”}แต:L} ``` [Try it online!](https://tio.run/nexus/brachylog2#@199pOtRx3KfI92PmppyQKz0LCv7quqSECDbPqMu@eHOVRk5nkAOkJGUEZJj5amt@6ip0crzUduU2odbJ1j51P7/H62UmJScoqSjlJKamKQU@z8KAA) **Decompress:** ``` ~{ฤŠโˆงLฤ‹โ‚‚lโˆงLgj:?z{tTโˆง?h~cแนชhlIโˆงแนชbhTl:I+-โ‚:Iโ†”}แต:L} ``` [Try it online!](https://tio.run/nexus/brachylog2#@19XfaTrUcdynyPdj5qackCs9Cwr@6rqkhAg2z6jLvnhzlUZOZ5ADpCRlBGSY@WprfuoqdHK81HblNqHWydY@dT@/x8dHW2kYxqrE22gYxwbq6OUkpqYlJyiFPs/CgA "Brachylog โ€“ TIO Nexus") *Saved 5 bytes thanks to @ais523* ### Explanation The good side of declarative languages is that we can reuse the same code for both compressing and decompressing. As such, the code for compress is *exactly* the same as for *decompress*, with an additional `~` at the beginning. This `~` tells Brachylog to reverse the order of arguments (that is, use the Input as output and the Output as input). Since compress has no `~`, it actually runs the predicate in the standard order. Since decompress has only one, it runs it with the Input as output and the Output as input. That way, we can use the same code (modulo that extra `~`) to both compress and decompress: compressing is providing the two strings as input and a variable as output, and decompressing is providing the indexes and compressed string as output and a variable as Input. Obviously this also means that we have to be a bit explicit about our compressing code, so that the interpreter is capable of running it "backwards". This is why the compressor itself is a bit long. Here is a breakdown of the code for Compress (and thus also of decompress): ``` {โ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ} Call that predicate the normal way (with swapped arguments for decompress) ฤŠ Input has two elements โˆงLฤ‹โ‚‚l L is a string of any length (measuring its length forces it to take a specific length from 0 to +inf) โˆงLgj The list [L,L] :?z The list [[L, First elem of Input],[L,second elem of input]] {โ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ}แต:L Final output is the [M,L] where M is the result of mapping the predicate below on both elements of the zip tT The second element of the input is T โˆง?h~cแนช Anticoncatenate the first element of the input into [A,B,C] hlI I = length(A) โˆงแนชbhTl:I+-โ‚ J = length(T) + I - 1 :Iโ†” Output = [I,J] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to ais523 (use `โพ` for a two-byte string) This may well be quite golfable... **[Compression](https://tio.run/nexus/jelly#AU8AsP//d8KzO3figbQkCjA7SuKBuOG4ozvigqwKw6c7w6dAw5HhuqAkw5BmTMOQ4bmC4bmqwrXCsyzigbRM4oKsxbxAw5Es////YWJjZP9kZWFi)** takes two string arguments and returns a list: `[[[startA, lengthA], [startB, lengthB]], compressedString]` ``` wยณ;wโด$ 0;Jโธแธฃ;โ‚ฌ รง;รง@ร‘แบ $รfLรแน‚แนชยตยณ,โดLโ‚ฌลผ@ร‘, ``` **[Decompression](https://tio.run/nexus/jelly#@6/D9ahx38Odqx/uWHx0j1sZ18Mdiw4vf9S05uHOVZH///@Pjo421lEwidVRiDYE0UCGekpqYlJyinosAA)** takes one argument (such a list) and returns two\* strings: ``` , โพแนซแธฃลผFv แธขรงโ‚ฌแนช ``` Overlapped code: ``` wยณ;wโด$ 0;Jโธแธฃ;โ‚ฌ รง;รง@ร‘แบ $รfLรแน‚แนชยตยณ,โดLโ‚ฌลผ@ร‘, โพแนซแธฃลผFv แธขรงโ‚ฌแนช ``` One-indexed. \* this may not be obvious due to Jelly's implicit print formatting, so the code at TryItOnline linked to above has an extra byte (a `Y` at the end) to insert a line feed between the two in the printed output. I started with a single program, which used the depth of the first (or only) argument to decide between compression and decompression, but having an unused link in the decompression code (the first line) and a single overlapping byte is shorter by seven bytes. ### How? ``` รง;รง@ร‘แบ $รfLรแน‚แนชยตยณ,โดLโ‚ฌลผ@ร‘, - Compression: stringA, stringB รง - call the last link (2) as a dyad รง@ - call the last link (2) as a dyad with reversed arguments ; - concatenate (gives all overlapping strings) รf - filter keep: $ - last two links as a monad ร‘ - call the next link (1) as a monad แบ  - All? (no zeros exist in that result) รแน‚ - filter keep with minimal: L - length แนช - tail (for when more than one exists) ยต - monadic chain separation (we now have the compressed string) ยณ,โด - [stringA, stringB] Lโ‚ฌ - length of โ‚ฌach ลผ@ - zip with reversed arguments with ร‘ - next link (1) as a monad with the compressed string , - paired with the compressed string J0;โธแธฃ;โ‚ฌ - Link 2, possible overlaps: stringL, stringR J - range(length(stringL)) - [1,2,...,length(stringL)] 0; - zero concatenate - [0,1,2,...,length(stringL)] โธ - stringL แธฃ - head (vectorises) - [empty string, first char, first two, ..., stringL] ;โ‚ฌ - concatenate โ‚ฌach with stringR wยณ;wโด$ - Link 1, substring indexes: stringX wยณ - first index of first program argument in stringX or 0 if not found ; - concatenated with $ - last two links as a monad wโด - first index of second program argument in stringX or 0 if not found ``` ``` แธขรฑโ‚ฌแนช - Decompression: [[[startA, lengthA], [startB, lengthB]], compressedString], ? แธข - head - [[startA, lengthA], [startB, lengthB]] แนช - tail - compressedString รงโ‚ฌ - call the last link (2) as a dyad for โ‚ฌach of the left list -- extra Y atom at TIO joins the resulting list of two strings with a line feed. โพแนซแธฃลผFv - Link 2, extract a substring: [start, length], string โพแนซแธฃ - string "แนซแธฃ" ลผ - zip with [start, length] to yield [['แนซ', start],['แธฃ', length]] F - flatten, making a list of characters v - evaluate as Jelly code with the string as an argument - this evaluates as string.tail(start).head(length) yielding the substring , - Link 1: only here to make an overlap with the compression program. ``` ]
[Question] [ This is Pascal's Braid: ``` 1 4 15 56 209 780 2911 10864 40545 151316 564719 1 3 11 41 153 571 2131 7953 29681 110771 413403 1542841 1 4 15 56 209 780 2911 10864 40545 151316 564719 ``` I totally made that up. Blaise Pascal didn't have a braid as far as I can tell, and if he did it was probably made of hair instead of numbers. It's defined like this: 1. The first column has a single `1` in the middle. 2. The second column has a `1` at the top and at the bottom. 3. Now we alternate between putting a number in the middle or two copies of a number at the top and bottom. 4. If the number goes on the top or the bottom, it will be the sum of the two adjacent numbers (e.g. `56 = 15 + 41`). If you tilt your head a little, this is like a step in Pascal's triangle. 5. If the number goes in the middle, it will be the sum of all three adjacent numbers (e.g. `41 = 15 + 11 + 15`). Your task will be to print (some part of) this braid. ## Input You should write a program or function, which receives a single integer `n`, giving the index of the last column to be output. You may choose whether the first column (printing only a single `1` on the middle line) corresponds to `n = 0` or `n = 1`. This has to be a consistent choice across all possible inputs. ## Output Output Pascal's Braid up to the `n`th column. The whitespace has to match exactly the example layout above, except that you may pad the shorter line(s) to the length of the longer line(s) with spaces and you may optionally output a single trailing linefeed. In other words, every column should be exactly as wide as the number (or pair of equal numbers) in that column, numbers in successive columns should not overlap and there should be no spaces between columns. You may either print the result to STDOUT (or the closest alternative), or if you write a function you may return either a string with the same contents or a list of three strings (one for each line). ## Further Details You may assume that `n` won't be less than the index of the first column (so not less than `0` or `1` depending on your indexing). You may also assume that the last number in the braid is less than 256 or the largest number representable by your language's native integer type, whichever is *greater*. So if your native integer type can only store bytes, you can assume that the largest `n` is `9` or `10` (depending on whether you use 0- or 1-based `n`) and if it can store signed 32-bit integers, `n` will be at most `33` or `34`. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code wins. ## OEIS Here are a few relevant OEIS links. Of course, these contain spoilers for different ways to generate the numbers in the braid: * Top/bottom: [A001353](https://oeis.org/A001353) or [A010905](https://oeis.org/A010905) or [A106707](https://oeis.org/A106707) or [A195503](https://oeis.org/A195503) * Middle: [A001835](https://oeis.org/A001835) or [A079935](https://oeis.org/A079935) * Both: [A002530](https://oeis.org/A002530) ## Test Cases These test cases use 1-base indexing. Each test case is four lines, with the first being the input and the remaining three being the output. ``` 1 1 --- 2 1 1 1 --- 3 1 1 3 1 --- 5 1 4 1 3 11 1 4 --- 10 1 4 15 56 209 1 3 11 41 153 1 4 15 56 209 --- 15 1 4 15 56 209 780 2911 1 3 11 41 153 571 2131 7953 1 4 15 56 209 780 2911 --- 24 1 4 15 56 209 780 2911 10864 40545 151316 564719 2107560 1 3 11 41 153 571 2131 7953 29681 110771 413403 1542841 1 4 15 56 209 780 2911 10864 40545 151316 564719 2107560 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 44 bytes The number generation took 20 bytes, and the formatting took 24 bytes. ``` jsMC+Led.e.<bkC,J<s.u+B+hNyeNeNQ,1 1Qm*;l`dJ ``` [Try it online!](http://pyth.herokuapp.com/?code=jsMC%2BLed.e.%3CbkC%2CJ%3Cs.u%2BB%2BhNyeNeNQ%2C1+1Qm%2a%3Bl%60dJ&input=23&debug=0) ``` jsMC+Led.e.<bkC,J<s.u+B+hNyeNeNQ,1 1Qm*;l`dJ input as Q .u Q,1 1 repeat Q times, starting with [1,1], collecting all intermediate results, current value as N: (this will generate more than enough terms) +hNyeN temp <- N[0] + 2*N[-1] +B eN temp <- [temp+N[-1], temp] now, we would have generated [[1, 1], [3, 4], [11, 15], [41, 56], ...] jsMC+Led.e.<bkC,J<s Qm*;l`dJ s flatten < Q first Q items J store in J m dJ for each item in J: ` convert to string l length *; repeat " " that many times jsMC+Led.e.<bkC, C, transpose, yielding: [[1, ' '], [1, ' '], [3, ' '], [4, ' '], [11, ' '], ...] (each element with as many spaces as its length.) .e for each sub-array (index as k, sub-array as b): .<bk rotate b as many times as k [[1, ' '], [' ', 1], [3, ' '], [' ', 4], [11, ' '], ...] jsMC+Led +Led add to each sub-array on the left, the end of each sub-array C transpose sM sum of each sub-array (reduced concatenation) j join by new-lines ``` [Answer] # Python 2, 120 bytes ``` a=1,1,3,4 n=input() y=0 exec"y+=1;t='';x=0;%sprint t;"%(n*"a+=a[-2]*4-a[-4],;v=`a[x]`;t+=[v,len(v)*' '][x+y&1];x+=1;")*3 ``` [Try it on Ideone.](https://ideone.com/CgYCWQ) [Answer] # [MATL](https://github.com/lmendo/MATL), 38 bytes ``` 1ti:"yy@oQ*+]vG:)!"@Vt~oX@o?w]&v]&hZ}y ``` [**Try it online!**](http://matl.tryitonline.net/#code=MXRpOiJ5eUBvUSorXXZHOikhIkBWdH5vWEBvP3ddJnZdJmhafXk&input=MjQ) Computing an array with the (unique) numbers takes the first 17 bytes. Formatting takes the remaining 21 bytes. ## Explanation ### Part 1: generate the numbers This generates an array with the numbers from the first and second rows in increasing order: `[1; 1; 3; 4; 11; 15; ...]`. It starts with `1`, `1`. Each new number is iteratively obtained from the preceding two. Of those, the second is multiplied by `1` or `2` depending on the iteration index, and then summed to the first to produce the new number. The number of iterations is equal to the input `n`. This means that `n+2` numbers are generated. Once generated, the array needs to be trimmed so only the first `n` entries are kept. ``` 1t % Push 1 twice i: % Take input n. Generage array [1 2 ... n] " % For each yy % Duplicate the two most recent numbers @o % Parity of the iteration index (0 or 1) Q % Add 1: gives 1 for even iteration index, 2 for odd *+ % Multiply this 1 or 2 by the most recent number in the sequence, and add % to the second most recent. This produces a new number in the sequence ] % End for each v % Concatenate all numbers in a vertical array G:) % Keep only the first n entries ``` ### Part 2: format the output For each number in the obtained array, this generates two strings: string representation of the number, and a string of the same length consisting of character 0 repeated (character 0 is displayed as a space in MATL). For even iterations, these two strings are swapped. The two strings are then concatenated vertically. So `n` 2D char arrays are produced as follows (using `ยท` to represent character 0): ``` ยท 1 1 ยท ยท 3 4 ยท ยทยท 11 15 ยทยท ``` These arrays are then concatenated horizontally to produce ``` ยท1ยท4ยทยท15 1ยท3ยท11ยทยท ``` Finally, this 2D char array is split into its two rows, and the first is duplicated onto the top of the stack. The three strings are displayed in order, each on a different line, producing the desired output ``` ! % Transpose into a horizontal array [1 1 3 4 11 15 ...] " % For each @V % Push current number and convert to string t~o % Duplicate, negate, convert to double: string of the same length consisting % of character 0 repeated X@o % Parity of the iteration index (1 or 0) ? % If index is odd w % Swap ] % End if &v % Concatenate the two strings vertically. Gives a 2D char array representing % a "numeric column" of the output (actually several columns of characters) ] % End for &h % Concatenate all 2D char arrays horizontally. Gives a 2D char array with the % top two rows of the output Z} % Split this array into its two rows y % Push a copy of the first row. Implicitly display ``` [Answer] # Haskell, 101 bytes ``` a=1:1:t t=3:4:zipWith((-).(4*))t a g(i,x)=min(cycle" 9"!!i)<$>show x f n=[zip[y..y+n]a>>=g|y<-[0..2]] ``` Defines a function `f :: Int โ†’ [String]`. * Michael Klein reminded me I didnโ€™t need to call `unlines` on the result, saving 7 bytes. Thanks! * I saved a byte by replacing `" 9"!!mod i 2` with `cycle" 9"!!i`. * Three more bytes by writing two corecursive lists instead of using `drop`. * My girlfriend pointed out I can save two more bytes by starting my answers at `0` instead of `1`. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~31~~ ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Q;Sโนo_ 3แธถแธ‚รง@โธรยกIยตa"แนพโ‚ฌoโถzโถZยตโ‚ฌZ ``` This is a monadic link; it accepts a 0-based column index as argument and returns a list of strings. [Try it online!](http://jelly.tryitonline.net/#code=UTtT4oG5b18KM-G4tuG4gsOnQOKBuMOQwqFJwrVhIuG5vuKCrG_igbZ64oG2WsK14oKsWgrDh-KCrGrigqzigbdq4oCcwrYtLS3CtuKAnQ&input=&args=MCwgMSwgMiwgNCwgOSwgMTQsIDIz) ### How it works ``` Q;Sโนo_ Helper link. Arguments: [k, 0, k] and [0, m, 0] (any order) Q Unique; deduplicate the left argument. ; Concatenate the result with the right argument. S Take the sum of the resulting array. โนo Logical OR with the right argument; replaces zeroes in the right argument with the sum. _ Subtract; take the difference with the right argument to remove its values. This maps [k, 0, k], [0, m, 0] to [0, k + m, 0] and [0, m, 0], [k, 0, k] to [m + 2k, 0, m + 2k]. 3แธถแธ‚รง@โธรยกIยตa"แนพโ‚ฌoโถzโถZยตโ‚ฌZ Monadic link. Argument: A (array of column indices) 3แธถ Yield [0, 1, 2]. แธ‚ Bit; yield [0, 1, 0]. I Increments of n; yield []. รยก Apply... รง@ the helper link with swapped arguments... โธ n times, updating the left argument with the return value, and the right argument with the previous value of the left one. Collect all intermediate values of the left argument in an array. ยต ยตโ‚ฌ Map the chain in between over the intermediate values. แนพโ‚ฌ Uneval each; turn all integers into strings. a" Vectorized logical AND; replace non-zero integers with their string representation. oโถ Logical OR with space; replace zeroes with spaces. zโถ Zip with fill value space; transpose the resulting 2D array after inserting spaces to make it rectangular. Z Zip; transpose the result to restore the original shape. Z Zip; transpose the resulting 3D array. ``` [Answer] # C, 183 177 176 bytes ``` #define F for(i=0;i<c;i++) int i,c,a[35],t[9];p(r){F printf("%*s",sprintf(t,"%d",a[i]),r-i&1?t:" ");putchar(10);}b(n){c=n;F a[i]=i<2?1:a[i-2]+a[i-1]*(i&1?1:2);p(0);p(1);p(0);} ``` ## Explanation C is never going to win any prizes for brevity against a higher level language, but the exercise is interesting and good practice. The macro F shaves off six bytes at the cost of readability. Variables are declared globally to avoid multiple declarations. I needed a character buffer for sprintf, but since K&R is loose with type checking, sprintf and printf can interpret t[9] as a pointer to a 36-byte buffer. This saves a separate declaration. ``` #define F for(i=0;i<c;i++) int i,c,a[35],t[9]; ``` Pretty printing function, where r is the row number. Sprintf formats the number and computes the column width. To save space we just call this three times, one for each row of output; the expression r-i&1 filters what gets printed. ``` p(r) { F printf("%*s", sprintf(t, "%d", a[i]), r-i&1 ? t : " "); putchar(10); } ``` Entry point function, argument is number of columns. Computes array a of column values a[], then calls printing function p once for each row of output. ``` b(n) { c=n; F a[i] = i<2 ? 1 : a[i-2] + a[i-1]*(i&1 ? 1 : 2); p(0); p(1); p(0); } ``` Sample invocation (not included in answer and byte count): ``` main(c,v) char**v; { b(atoi(v[1])); } ``` ## Updated Incorporated the inline sprintf suggestion from tomsmeding. That reduced the count from 183 to 177 characters. This also allows removing the the braces around the printf(sprintf()) block since it's only one statement now, but that only saved one character because it still needs a space as a delimiter. So down to 176. [Answer] ## PowerShell v2+, 133 bytes ``` param($n)$a=1,1;1..$n|%{$a+=$a[$_-1]+$a[$_]*($_%2+1)};$a[0..$n]|%{$z=" "*$l+$_;if($i++%2){$x+=$z}else{$y+=$z}$l="$_".Length};$x;$y;$x ``` 44 bytes to calculate the values, 70 bytes to formulate the ASCII Takes input `$n` as the zero-indexed column. Sets the start of our sequence array `$a=1,1`. We then loop up to `$n` with `1..$n|%{...}` to construct the array. Each iteration, we concatenate on the sum of (two elements ago) + (the previous element)\*(whether we're odd or even index). This will generate `$a=1,1,3,4,11...` up to `$n+2`. So, we need to slice `$a` to only take the first `0..$n` elements, and pipe those through another loop `|%{...}`. Each iteration we set helper `$z` equal to a number of spaces plus the current element as a string. Then, we're splitting out whether that gets concatenated onto `$x` (the top and bottom rows) or `$y` (the middle row) by a simple odd-even `if`/`else`. Then, we calculate the number of spaces for `$l` by taking the current number, stringifying it, and taking its `.Length`. Finally, we put `$x`, `$y`, and `$x` again on the pipeline, and output is implicit. Since the default `.ToString()` separator for an array when printing to STDOUT is a newline, we get that for free. ### Example ``` PS C:\Tools\Scripts\golfing> .\pascal-braid.ps1 27 1 4 15 56 209 780 2911 10864 40545 151316 564719 2107560 7865521 29354524 1 3 11 41 153 571 2131 7953 29681 110771 413403 1542841 5757961 21489003 1 4 15 56 209 780 2911 10864 40545 151316 564719 2107560 7865521 29354524 ``` [Answer] ## PHP 265 bytes ``` <?php $i=$argv[1];$i=$i?$i:1;$a=[[],[]];$s=['',''];$p='';for($j=0;$j<$i;$j++){$y=($j+1)%2;$x=floor($j/2);$v=$x?$y?2*$a[0][$x-1]+$a[1][$x-1]:$a[0][$x-1]+$a[1][$x]:1;$s[$y].=$p.$v;$a[$y][$x]=$v;$p=str_pad('',strlen($v),' ');}printf("%s\n%s\n%s\n",$s[0],$s[1],$s[0]); ``` Un-golfed: ``` $a = [[],[]]; $s = ['','']; $p = ''; $i=$argv[1]; $i=$i?$i:1; for($j=0; $j<$i; $j++) { $y = ($j+1) % 2; $x = floor($j/2); if( $x == 0 ) { $v = 1; } else { if( $y ) { $v = 2 * $a[0][$x-1] + $a[1][$x-1]; } else { $v = $a[0][$x-1] + $a[1][$x]; } } $s[$y] .= $p . $v; $a[$y][$x] = $v; $p = str_pad('', strlen($v), ' '); } printf("%s\n%s\n%s\n", $s[0], $s[1], $s[0]); ``` ## Python 278 bytes ``` import sys,math;a=[[],[]];s=['',''];p='';i=int(sys.argv[1]);i=1 if i<1 else i;j=0 while j<i:y=(j+1)%2;x=int(math.floor(j/2));v=(2*a[0][x-1]+a[1][x-1] if y else a[0][x-1]+a[1][x]) if x else 1;s[y]+=p+str(v);a[y].append(v);p=' '*len(str(v));j+=1 print ("%s\n"*3)%(s[0],s[1],s[0]) ``` [Answer] # Ruby, 120 bytes Returns a multiline string. [Try it online!](https://repl.it/CezQ) ``` ->n{a=[1,1];(n-2).times{|i|a<<(2-i%2)*a[-1]+a[-2]} z=->c{a.map{|e|c+=1;c%2>0?' '*e.to_s.size: e}*''} [s=z[0],z[1],s]*$/} ``` [Answer] ## Matlab, 223 characters, 226 bytes ``` function[]=p(n) r=[1;1];e={(' 1 ')',('1 1')'} for i=3:n;r(i)=sum((mod(i,2)+1)*r(i-1)+r(i-2));s=num2str(r(i));b=blanks(floor(log10(r(i)))+1);if mod(i,2);e{i}=[b;s;b];else e{i}=[s;b;s];end;end reshape(sprintf('%s',e{:}),3,[]) ``` Ungolfed and commented: ``` function[]=p(n) r=[1;1]; % start with first two e={(' 1 ')',('1 1')'} % initialize string output as columns of blank, 1, blank and 1, blank, 1. for i=3:n; % for n=3 and up! r(i)=sum((mod(i,2)+1)*r(i-1)+r(i-2)); % get the next number by 1 if even, 2 if odd times previous plus two steps back s=num2str(r(i)); % define that number as a string b=blanks(floor(log10(r(i)))+1); % get a number of space characters for that number of digits if mod(i,2); % for odds e{i}=[b;s;b]; % spaces, number, spaces else % for evens e{i}=[s;b;s]; % number, spaces, number end; end reshape(sprintf('%s',e{:}),3,[]) % print the cell array of strings and reshape it so it's 3 lines high ``` [Answer] # PHP, ~~135~~ ~~124~~ ~~123~~ 120 bytes ``` <?while($i<$argv[1]){${s.$x=!$x}.=${v.$x}=$a=$i++<2?:$v1+$v+$x*$v;${s.!$x}.=str_repeat(' ',strlen($a));}echo"$s $s1 $s"; ``` taking advantage of implicit typecasts and variable variables a third of the code (37 bytes) goes into the spaces, 64 bytes altogether used for output **breakdown** ``` $i=0; $x=false; $v=$v1=1; $s=$s1=''; // unnecessary variable initializations for($i=0;$i<$argv[1];$i++) // $i is column number -1 { $x=!$x; // $x = current row: true (1) for inner, false (empty string or 0) for outer // calculate value $a= $i<2? // first or second column: value 1 :$v1+(1+$x)*$v // inner-val + (inner row: 1+1=2, outer row: 1+0=1)*outer-val ; ${s.$x}.=${v.$x}=$a; // replace target value, append to current row ${s.!$x}.=str_repeat(' ',strlen($a)); // append spaces to other row } // output echo "$s\n$s1\n$s"; ``` [Answer] ## Batch, 250 bytes ``` @echo off set s= set d= set/ai=n=0,j=m=1 :l set/ai+=1,j^^=3,l=m+n*j,m=n,n=l set t=%s%%l% for /l %%j in (0,1,9)do call set l=%%l:%%j= %% set s=%d%%l% set d=%t% if not %i%==%1 goto l if %j%==1 echo %d% echo %s% echo %d% if %j%==2 echo %s% ``` Since the first and third lines are the same, we just have to build two strings. Here `d` represents the string that ends with the last entry and `s` represents the string that ends with spaces; the last four lines ensure that they are printed in the appropriate order. `i` is just the loop counter (it's slightly cheaper than counting down from `%1`). `j` is the toggle between doubling the previous number before adding it to the current number to get the next number. `m` and `n` contain those numbers. `l`, as well as being used as a temporary to calculate the next number, also gets its digits replaced with spaces to pad out `s`; `s` and `d` are exchanged each time via the intermediate variable `t`. ]
[Question] [ A [standard domino set](https://en.wikipedia.org/wiki/Dominoes) has 28 unique pieces: [![enter image description here](https://i.stack.imgur.com/7LxZh.png)](https://i.stack.imgur.com/7LxZh.png) Given a list of 28 or fewer unique dominoes, output the list required to make a complete set. Input and output dominoes are specified by two digits - the number of pips on each side of the domino, e.g. `00`, `34`, `40`, `66`. The digits may be given in any order, so `34` is the same domino as `43` ### Example Inputs ``` 00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66 00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 50 51 52 53 54 55 60 61 62 63 64 65 66 00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 34 35 36 44 45 46 55 56 66 00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66 <empty list> ``` ### Corresponding Example Outputs ``` <empty list> <empty list> 33 01 12 23 34 45 56 00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66 ``` [Answer] ## CJam, 11 bytes ``` {:$7Ym*:$^} ``` An unnamed block (function) with I/O as a list of pairs of integers. [Test it here.](http://cjam.aditsu.net/#code=qN%2F%7B%3A~2%2F%0A%0A%7B%3A%247Ym*%3A%24%5E%7D%0A%0A~p%7D%2F&input=00%2001%2002%2003%2004%2005%2006%2011%2012%2013%2014%2015%2016%2022%2023%2024%2025%2026%2033%2034%2035%2036%2044%2045%2046%2055%2056%2066%0A00%2010%2011%2020%2021%2022%2030%2031%2032%2033%2040%2041%2042%2043%2044%2050%2051%2052%2053%2054%2055%2060%2061%2062%2063%2064%2065%2066%0A00%2001%2002%2003%2004%2005%2006%2011%2012%2013%2014%2015%2016%2022%2023%2024%2025%2026%2034%2035%2036%2044%2045%2046%2055%2056%2066%0A00%2002%2003%2004%2005%2006%2011%2013%2014%2015%2016%2022%2024%2025%2026%2033%2035%2036%2044%2046%2055%2066%0A) ### Explanation ``` :$ e# Sort each pair in the input. 7Ym* e# Get all pairs with elements in range [0 .. 6] using a Cartesian product. :$ e# Sort each pair. ^ e# Symmetric set-difference. This will remove all pairs that are in the input e# and also remove duplicates, because it's a set operation. ``` [Answer] ## Pyth, ~~12~~ 10 bytes ``` -.CU7 2SMQ ``` Input and output in format `[[0, 0], [0, 1], ...]`. ``` U7 generate range [0, 1, ..., 6] .C 2 all combinations-with-replacement of 2, generates [[0,0],[0,1],...] Q get the input SM sort each domino (turns ex. [1,0] into [0,1]) - remove the map-sort'd input from the full array ``` [Try it here.](https://pyth.herokuapp.com/?code=-.CU7+2SMQ&input=%5B%5D&debug=0) Thanks to [@MartinBรผttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for saving 2 bytes with a different input/output format! [Answer] ## JavaScript (ES7 proposed), ~~80~~ 76 bytes ``` s=>[for(n of d="0123456")for(o of d.slice(n))if(s.search(n+o+'|'+o+n)<0)n+o] ``` Takes input as a space-separated string and returns an array of strings. Array comprehensions really pull their weight for this one. [Answer] # Ruby 74 bytes ``` ->b{a=(0..27).map{|i|"%d%d"%[i%7,(i+i/7)%7]} b.map{|e|a-=[e,e.reverse]} a} ``` Takes an array of strings, returns an array of strings. **Commented in test program** ``` f=->b{a=(0..27).map{|i|"%d%d"%[i%7,(i+i/7)%7]} #generate complete set of dominos (each domino once) and store in a b.map{|e|a-=[e,e.reverse]} #remove provided dominos (check both forward and reverse representations) a} #return a p f[%w{00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66}] p f[%w{00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 50 51 52 53 54 55 60 61 62 63 64 65 66}] p f[%w{00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 34 35 36 44 45 46 55 56 66}] p f[%w{00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66}] p f[[]] ``` **Output** ``` [] [] ["33"] ["01", "12", "23", "34", "45", "56"] ["00", "11", "22", "33", "44", "55", "66", "01", "12", "23", "34", "45", "56", "60", "02", "13", "24", "35", "46", "50", "61", "03", "14", "25","36", "40", "51", "62"] ``` In the last example (input empty list) note the order of generation of the complete list of dominoes using modular arithmetic. 7 Doubles are generated first, then 7 dominoes with a difference of 1 (or 6) pips between each side, then 7 dominoes with a difference of 2 (or 5) pips, and finally 7 dominoes with a difference of 3 (or 4) pips. [Answer] # [Julia 0.6](http://julialang.org/), 47 bytes ``` A->setdiff([[i,j]for i=0:6 for j=i:6],sort.(A)) ``` [Try it online!](https://tio.run/##LY9NisJAGET3nqLIxg7E4ftfCBnwHCELwQm0ZNpg4vmdtMzuLapeUffXnK/xvvXvy@l7/dlueZrSMOTuPk6PJ3JP50Cle5/PMXbr47l9pUvbvqe0tv0wlIHH05GOXRnkA@MnXpAL1mXO2x4bD4ff65L2heWZyzaXdEtTlbQdUkMEYpCAFGQgBwWYwQJWsIEdHBCBKMQgDgmoQR0aMIM5LOAOD0Q0HaqTqUqEIFy7SlCG7qAwgjFMYFrrTnCGC1zhVj1BCEYIQhGG8H9ts//@Aw "Julia 0.6 โ€“ Try It Online") *(Corrected range start thanks to JayCe.)* --- ## 48 bytes ``` A->[(i,j)for i=0:6 for j=i:6 if[i,j]โˆ‰sort.(A)] ``` [Try it online!](https://tio.run/##LY1NaoNQFEbnWcVHJnkPTLn/g4KFrEMcBILwxBpRu4d2m92I1dDZge@ec/uvodxje9Tb7frRpFL1uXvOKDW9Bw7q67JT6Zp9an@/f5bnvL6lW263Li25bpqx4fZ6oUs1NvKC9uWNKCOWaSjrftaeTp/3Ke0vprmM6zCmR@r2SM4V0pkIxCABKchADgowgwWsYAM7OCACUYhBHBJQgzo0YAZzWMAdHog4VziaTEdECMKHqwRl6A4KIxjDBKaH7gRnuMAVbkcnCMEIQSjCEP6fPee8/QE "Julia 0.6 โ€“ Try It Online") [Answer] # Perl, 48 + 1 = 49 bytes ``` for$=(0..6){for$.($=..6){/$=$.|$.$=/||say$=.$.}} ``` Requires the `-n` flag, and the free `-M5.010`|`-E`: ``` $ perl -nE'for$=(0..6){for$.($=..6){/$=$.|$.$=/||say$=.$.}}' <<< '00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66' 01 12 23 34 45 56 ``` Pretty boring answer overall, but here goes with an ungolfed version: ``` # '-n' auto reads first line into `$_`: # $_ = <>; foreach $a (0..6) { foreach $b ($a..6) { say $a . $b unless $_ =~ /$a$b|$b$a/; } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` lambda A,S="0123456":sum([[i+j for j in S[int(i):]if(i+j in A)+(j+i in A)<1]for i in S],[]) ``` **[Try it online!](https://tio.run/##JYxLCoNAGIP3PUVw4wyKzHshdeEZXFopliL9Bx3FB6Wnt9quknwJmT7rawxq74rb3rfD49miTKsiElJpY12UL9vA6poSj26c4UEBVU1hZcTzhjp2NgcrecJ8Qn97lc05/qWqSeuG72Uxt@87hWlbGc@WqadDL9N8PMWIMz9SYB0rOd@FgFAQGsJAWAgHKSE1pIG0kA5KQRkoC@WgNbSFdjAGxsFaOPcF "Python 2 โ€“ Try It Online")** [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes ``` s=>[for(n of d="0123456")for(o of d)if(n<o<!s.match(n+o+'|'+o+n))n+o] ``` [Try it online!](https://tio.run/##HchBbsIwEEbhq/ywiS0EGo9nZkV6kYpFFOI2LXhQjCpV4u4pZfOk930NP0Mbl/l237fbfJ6Wq9fv6Xct/dr6t/fiS6jwgnO/pcRZ1LbxH/2FcS6hHv24aYfrcB8/Q935rnt0z9YYn3NaR6/NL9Ph4h@hhI4IlEAMyiABKciQEhIjCZIiGZjBGSxgBRtyRhZkRTaIQBRiUIUazLoY1z8 "JavaScript (SpiderMonkey) โ€“ Try It Online") optimized from Neil's [Answer] # [R](https://www.r-project.org/), 111 bytes ``` function(s,p=paste0,L=lapply)setdiff(p(sequence(1:7)-1,rep(0:6,t=1:7)),L(L(strsplit(s,''),sort),p,collapse='')) ``` [Try it online!](https://tio.run/##tZJNagQhFIT3c5FWMODzLzDgDfoSjVHS0HQbdRZz@o61MANhQiCQTfFefWAVajmTP9NtD209dlZF9nmpLUox@23JebvzGtvbmhLLrMaPW9xDZHR95S8kSsxMXp1oHgYXM5tZbaXmbW39qGnioh6lcZFFOLZ@XI2@m/xMLLBJyklMkiAKoiEGYiGuC4ESKIESKIESqAJQAApAASgADU/D0/A0PIPVYDVYLSaLybne6HJ5VCI5khUmRSNKY9VYtRopBp6BZ@AZPaIsgAWwABbAmpHsQB2oA3WgDtTZZ5X@55b@ekG/FPmxw7NH@hb/lfwIfV/KElosrP@bTw "R โ€“ Try It Online") Not really proud of this, but R is not very "golfy" in splitting/concatenating strings... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 6รรฃโ‚ฌ{JIโ‚ฌ{Kร™ ``` -1 byte thanks to *@Emigna*. [Try it online.](https://tio.run/##HYqxDYAwDATHcUNhx4l3AEZAFERiCjq2oKCiZYtswiIm7@b0Ph@Xrcrubu1uz3e@xzSCc7vcF2KmgViABGhHDlcA6xA4yQCcIU6IU8Sx0ClORafRxTcWXIlltP4) **Explanation:** ``` 6ร # [0,1,2,3,4,5,6] รฃ # Duplicate and take the cartesian product (pair up each) โ‚ฌ{ # Sort each pair J # Join them together to strings Iโ‚ฌ{ # Sort each pair-string of the input K # Remove all pairs from the input from the cartesian list ร™ # Only leave unique values ``` [Answer] # Mathematica, 49 bytes ``` Complement[Join@@Table[{x,y},{x,0,6},{y,0,6}],#]& ``` Input is list of list of integers. [Answer] # Java 8, 105 bytes A void lambda accepting a mutable `java.util.Set<String>`. ``` s->{for(int i=0,a,b;i<49;)if(s.add(""+(a=i/7)+(b=i++%7))&(s.add(""+b+a)|a==b))System.out.print(" "+a+b);} ``` [Try It Online](https://tio.run/##nZJPj9owEMXP4VM8RWoVK5D6/6pAkKpeemhPHFeryglhawoJis1Wqy2fnTqhAkpZqerBdpR5/s2M563MkxmtFt8P212xtiXKtXEOX4yt8TKIfv903vhwrII223m7zpa7uvS2qbOPTe12m6qdnmPzyk/nvrX142yGJfLBwY1mL8umTWztYXM6NMNiYqfy/YTYZeIys1gkcZwmJrfv7kiaFLlN0zd3hLw9B4vUkJ8mzwtC5s/OV5us2flsG7L4JEacmrQgk/1hEE0G11U/NXaBTWgoOVZ1/wDTPjrS9RfdLDsoSuMqhxzJKwJy8Rgf2tY8u8z5tjKbJECjuvqBU7IuTRTFlIIyUA4qQCWoAtVgDIyDCTAJpsA0OAcX4BJcgWsIASEhFISGlJAKUkMpKA2t4@EJzWjH4hScdQhBIRgE7@5LCskgOaToEIpCMSgOJaBkx9IUmkFzaAEtodWf6P@p@l9KvgG9Il4@wgnXs86g47kPG@k@so3ZJg6jGcJAtmvbu4OcQ9dTG4@N@2ydv6X4ZNy3i6GPx2GsR51v@tt/a@8fTqpJWMH0rzioN9hXjI9GO3oxWmamLKutT/og6QjRtdvXddIHQsf7wf7wCw) ## Ungolfed ``` s -> { for (int i = 0, a, b; i < 49;) if ( s.add("" + (a = i / 7) + (b = i++ % 7)) & ( s.add("" + b + a) | a == b ) ) System.out.print(" " + a + b); } ``` ## Acknowledgments * -1 byte thanks to Jonathan Frech [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` แนขโ‚ฌ7แธถล’ฤ‹ยคแธŸ ``` [Try it online!](https://tio.run/##DcirDcJQGIDRVb4R/jebsAGGdAEsBoGrwpEQJApBWgt0kMsilyZHnf1uGA69t/n2Oz42bXot4/f8vrfp2tv03K65@pyWsc2X3kUQQxwJJJFCFXU00EQLMyywxAp3PPEigigyqfoD "Jelly โ€“ Try It Online") Argument is a list of length-2 lists of integers. The footer transforms the input from the format in the test cases to the format this solution accepts. [Answer] # J, 26, 24 bytes *-2 bytes thanks to FrownyFrog* ``` (;(,.i.,])&.>i.7)-.\:~"1 ``` * `(;(,.i.,])&.>i.7)` calculates the full set (this part could be golfed further, I believe. And please do if you see how...) * `-.` is "set minus" * `/:~"1` orders each of the inputs [Try it online!](https://tio.run/##FYuxDsIwDET3fMWpA22k1GqdNEhBsCAxMTG3YkBULQt/wK8Hn2w/@c6@T22kXXEuaBEwoNj0guvjfqvdqQuyS1j8QS67HH0vc/k1Y/XOufdr@2LFU5fZIgOslYhEIiYiA6OVdSQSMRF2UCaUntJTepF/kTJSJl4Tt4leRq5/ "J โ€“ Try It Online") ## Original [Try it online!](https://tio.run/##FYu9DsIwDIT3PMUpDG2kNm1@kcLPgsTExAxiqKiAhQdAyqsHn2x/8p19n6Ztt@JQ0GHAjCIzWpyul3Pr@03dl0k7cxx@u/q2WzPaqVTtmlFKPZfXFyse/n6T0AxpTwQiEonIgJOSDkQkEiEHz4Sn5@l5eoF/gTJQRl4jt0QvI7c/ "J โ€“ Try It Online") ``` ((#~<:/"1)>,{;~i.7)-./:~"1 ``` [Answer] # Python 2, ~~89~~ 86 bytes Saved a few bytes by simplifying domino set generation. ``` lambda z,s="0123456":{x+y for x in s for y in s[int(x):]}-{(a+b,b+a)[a>b]for a,b in z} ``` [Try it online!](https://tio.run/##vZLLaoNAGIXX8SkGV4oWnOtCMC9iXYy00kBrQnShCXl2k/kgtdALhUI3h99zPpzDzH@Yx5d9r5auelxe/Vv75MUpH6q4kEob6@LyPGWz6PZHMYldLwbGmbHe9WMypWVzeTgnPmvzNvNp7bdtExift4E6XZbxeRgHUYmkjosizsXt36hCNWpQi7qgEkbCSBgJI2EkjCJVpIpUkSpSja/xNb7GNzgGx@BYZsvsXNzk0Ubcu8pibaOYlVzP1jgaR6v1VINv8A2@0evZltSSWlJLas3axsE4GAfjYByMs191/ad7/eON/qrfz82@e@vPnT60ee/RpFEUNjTsZVhR9rOMNofjbaFFl4TvdLkC "Python 2 โ€“ Try It Online") Takes a list of strings like ["00", "10", "02] as an argument for the dominoes. Returns python set objects, which are unordered distinct lists. **Explanation** ``` # anonymous function, s should always have its default value lambda z,s="0123456": # contents are a set { } # iterate over characters in string for x in s # for each x, iterate over x from index of current item forward for y in s[int(x):] # add characters together for domino string x+y # contents are a set, return the difference between these two sets -{ } # iterate over items in input list, split strings into two characters for a,b in z # sort strings in input list (so that i.e. "10" => "01") # essentially, "ab" if a<b, otherwise "ba" (a+b,b+a)[a>b] ``` [Answer] ## Haskell, 65 bytes ``` f x=[[a,b]|a<-"0123456",b<-[a..'6'],notElem[a,b]x&&notElem[b,a]x] ``` Usage example: ``` *Main> f ["00","02","03","04","05","06","11","13","14","15","16","22","24","25","26","33","35","36","44","46","55","66"] ["01","12","23","34","45","56"] ``` Iterate `a` in an outer loop over all digits from `0` to `6` and `b` in an inner loop over all digits from `a` to `6` and keep those `ab` where neither `ab` nor `ba` are found in the input string. [Answer] ## Seriously, 16 bytes ``` ,`S`M7r;โˆ™`ฮตjS`M- ``` Takes input as a list of strings, outputs a list of strings [Try it online!](http://seriously.tryitonline.net/#code=LGBTYE03cjviiJlgzrVqU2BNLQ&input=WycwMCcsICcwMicsICcwMycsICcwNCcsICcwNScsICcwNicsICcxMScsICcxMycsICcxNCcsICcxNScsICcxNicsICcyMicsICcyNCcsICcyNScsICcyNicsICczMycsICczNScsICczNicsICc0NCcsICc0NicsICc1NScsICc2Nidd) Explanation: ``` ,`S`M7r;โˆ™`ฮตjS`M- ,`S`M map: sort each input string 7r;โˆ™ cartesian product of range(0,7) ([0,1,2,3,4,5,6]) with itself `ฮตjS`M map: join on empty string, sort (results in all valid dominoes with some duplicates) - set difference (all values present in valid dominoes set not present in input, with duplicates removed) ``` --- ## [Actually](https://github.com/Mego/Seriously/tree/v2), 13 bytes (non-competing) ``` โ™‚S7r;โˆ™`ฮตjS`M- ``` This is identical to the Seriously answer (with the exception of implicit input and `โ™‚S` being a shorter way to short each input string). [Try it online!](http://actually.tryitonline.net/#code=4pmCUzdyO-KImWDOtWpTYE0t&input=WycwMCcsICcwMicsICcwMycsICcwNCcsICcwNScsICcwNicsICcxMScsICcxMycsICcxNCcsICcxNScsICcxNicsICcyMicsICcyNCcsICcyNScsICcyNicsICczMycsICczNScsICczNicsICc0NCcsICc0NicsICc1NScsICc2Nidd) [Answer] # racket ``` (define (missing-dominoes input) (filter (lambda (n) (not (member n (map (lambda (n) (let ((x (quotient n 10)) (y (remainder n 10))) (if (<= x y) n (+ (* y 10) x)))) input)))) (for*/list ([i (in-range 7)] [j (in-range i 7)]) (+ (* 10 i) j)))) ``` ]
[Question] [ Given the 95 printable characters in ASCII plus newline, break it apart into two *equal, 48 character* groups (hereafter called group A and group B). Create a one-to-one mapping *of your choice* (you have total discretion) between the two groups. In other words, `A` might map to `a`, and vice versa, but `A` might also map to `>` and vice versa, if that's what you need for your program. Once you've broken up ASCII into two groups, write two programs and/or functions, using only the characters in each group, respectively. In other words, write one program / function that only uses the characters in group A, and another program / function that only uses the characters in group B. These programs must be able to receive one character as input. The program written with the characters in Group A should output / return the same character if the input was a group A character, and the mapped group A character if it received a group B character; the Group A program should always output a group A character. Similarly, the Group B program should output the same character if it's a group B character, and the mapped group B character if the input is a group A character. That might not be so clear, so here's an example. If you assume that all capital letters are in group A, and all lowercase letters are in group B, and you've chosen that your one-to-one mapping for these letters are from one to the other, then: then here are some sample input/outputs: ### Program A: ``` Input Output A A D D a A q Q ``` ### Program B: ``` Input Output A a D d a a q q ``` Other rules: * The two programs do not need to be in the same language. * They don't need to be both programs or both functions; one could be a program, the other a function, that is fine. * They don't need to work the same way, be of similar length, anything like that; they simply must meet the the other rules above. * Yes, only one of your programs may use newlines, and only one can use spaces (this could be the same, or a different program). * You do not need to use all 48 characters in each program. [Standard loopholes are banned, as normal.](http://meta.codegolf.stackexchange.com/q/1061/17249) All programs must be self contained, no files containing the mapping you choose. Scoring criteria: [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Specifically, the sum of the bytes of the text of the two programs. Please post your answer like this: > > # Language - # bytes + Language - # bytes = # bytes > > > An unambiguous description of your mapping. If it's complicated, use a chart like this: > > > ``` > ABCDEFGHIJKLMNOPQRSTUVWXYZ (etc.) > zyxwvutsrpqonmlkjihgfedcba (etc.) > > ``` > > Or, you can just explain it (first 48 maps to last 48 in sequence), followed by your answer as normal. [Answer] # CJam - ~~46~~ ~~44~~ ~~26~~ 11 bytes + GolfScript - ~~142~~ ~~125~~ ~~115~~ ~~93~~ ~~68~~ ~~47~~ ~~40~~ 36 bytes = 47 bytes *Thanks to Peter Taylor for golfing 6 bytes off the GolfScript program (and paving the way for many more.)* *Thanks to Dennis for golfing 15 bytes off the CJam program and 4 bytes off the GolfScript program.* Group A: all characters with even character code. Group B: all characters with odd character code, plus newline. I'm using the obvious mapping between the two, i.e. pair those characters which only differ in the least significant bit, as well as `~` and `\n`. Here is the complete map (the columns): ``` "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~ !#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}\n ``` Program A (CJam, [test it here](http://cjam.aditsu.net/#code=lX~f%26%22~%22%7CX%3C&input=a)): ``` lX~f&"~"|X< ``` Program B (GolfScript, [test it here](http://golfscript.apphb.com/?c=e10ucH59OmVkOwo7In4iCnsxfSd7LSd7KX0lJzExNSklMTEtWzkpaWUnOS97KSl9JSsrJQ%3D%3D)): ``` {1}'{-'{)}%'115)%11-[9)ie'9/{))}%++% ``` ## Explanation **Program A** *(Outdated, will update tomorrow.)* This program should turn odd character codes into even ones, i.e. set the least significant bit to 0. The obvious way to do this is bitwise AND with 126 (or 254 etc), but it's shorter to set it to 1 (via bitwise OR with 1) instead and then decrement the result. Finally, we need to fix newlines manually: ``` "r"( e# Push the string "r" and pull out the character. (~ e# Decrement to q and eval to read input. ( e# Pull out the character from the input string. 2(|( e# (input OR (2-1))-1 == input AND 126 0$ e# Copy the result. N& e# Set intersection with a string containing a newline. "~" e# Push "~". "@@"( e# Push "@@" and pull out one @. (| e# Decrement to ?, set union with the other string to give "@?". ~ e# Eval to select either the computed character or "~" if it was a newline. ``` **Program B** *(Outdated, will update tomorrow.)* This program can simply set the least significant bit to 1 via bitwise OR with 1 now. But it has to check for both `\v` (character code 0x0B) and `<DEL>` (character code 0xFF) manually and set them to `~` instead. In GolfScript I didn't have access to eval, but instead you can add a string to a block (which then becomes part of the code in that block), which I could map onto the input with `%`: ``` {1} # Push this block without executing it. '{--' # Push this string. {)}% # Increment each character to get '|..'. ')1)7?=[11=+9)?ie' # Push another string... 7/ # Split it into chunks of 7: [')1)7?=[' '11=+9)?' 'ie'] {))}% # For each chunk, split off the last character and increment it. + # Add the array to the string, flattening the array: '|..)1)7?=\11=+9)@if' + # Add it to the block: {1|..)1)7?=\11=+9)@if} % # Map the block onto the input, i.e. apply it to the single character. ``` And as for the generated code in the block: ``` 1|.. # Bitwise OR with 1, make two copies. )1)7?= # Check if the result is one less than 2^7 == 128 (i.e. if it's <DEL>). \11= # Check with the other copy if it's equal to 11 (i.e. if it's \v). + # Add them to get something truthy either way. 9) # Push a 10 (i.e. \n). @ # Pull up the original value. if # Select the correct result. ``` [Answer] ## Java - 1088 bytes + Java - 1144 bytes = 2232 bytes Thanks to @durron597 for helping to golf 1090 bytes from the first program. Proof that it is possible to do in one language (and a non-esolang at that). Use the unicode trick to convert the first one to all unicode characters. The second one uses reflection to get access to System.out in order to print to std. out. It couldn't use the u because that was used in the first program. I know this can be golfed more, but I wanted to post a valid solution first. The groups are fairly arbitrarily mapped, but basically, the first one required only u,\, and the hexadecimal digits (in any case). The groups: ``` !#7$&89'0123456>fB@UXZ\^AKCDEGH_JL`NOkQRxzVWYu~\n "%()*+,-./:;<=?FIMPST[]abcdeghijlmnopqrstvwy{|} ``` First program: ``` \u0076\u006F\u0069\u0064 k\u0028\u0069\u006E\u0074 x\u0029\u007B\u0069\u006E\u0074\u005B\u005Du\u003D\u007B33\u002C33\u002C35\u002C35\u002C36\u002C55\u002C38\u002C39\u002C36\u002C38\u002C56\u002C57\u002C39\u002C48\u002C49\u002C50\u002C48\u002C49\u002C50\u002C51\u002C52\u002C53\u002C54\u002C55\u002C56\u002C57\u002C51\u002C52\u002C53\u002C54\u002C62\u002C62\u002C64\u002C65\u002C66\u002C67\u002C68\u002C69\u002C102\u002C71\u002C72\u002C66\u002C74\u002C75\u002C76\u002C64\u002C78\u002C79\u002C85\u002C81\u002C82\u002C88\u002C90\u002C85\u002C86\u002C87\u002C88\u002C89\u002C90\u002C92\u002C92\u002C94\u002C94\u002C95\u002C96\u002C65\u002C75\u002C67\u002C68\u002C69\u002C102\u002C71\u002C72\u002C95\u002C74\u002C107\u002C76\u002C96\u002C78\u002C79\u002C107\u002C81\u002C82\u002C120\u002C122\u002C117\u002C86\u002C87\u002C120\u002C89\u002C122\u002C117\u002C126\u002C10\u002C126\u007D\u003B\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006Fu\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0028x>10\u003F\u0028\u0063\u0068\u0061\u0072\u0029u\u005Bx\u002D32\u005D\u003A'\u005C\u006E'\u0029\u003B\u007D ``` Equivalent to ``` void k(int x){int[]u={33,33,35,35,36,55,38,39,36,38,56,57,39,48,49,50,48,49,50,51,52,53,54,55,56,57,51,52,53,54,62,62,64,65,66,67,68,69,102,71,72,66,74,75,76,64,78,79,85,81,82,88,90,85,86,87,88,89,90,92,92,94,94,95,96,65,75,67,68,69,102,71,72,95,74,107,76,96,78,79,107,81,82,120,122,117,86,87,120,89,122,117,126,10,126};System.out.print(x>10?(char)u[x-32]:'\n');} ``` Second program: ``` void n(int r)throws Throwable{int p=(int)Math.PI;int q=p/p;int t=p*p+q;int w=q+q;int[]g={t*p+w,t*p+w,t*p+q+p,t*p+q+p,t*(q+p),t*p+t-p,t*(q+p)+q,t*(q+p)+q+p,t*(q+p),t*(q+p)+q,t*(q+p)+w,t*(q+p)+p,t*(q+p)+q+p,t*(q+p)+p+w,t*(q+p)+p+p,t*(q+p)+t-p,t*(q+p)+p+w,t*(q+p)+p+p,t*(q+p)+t-p,t*(p+w)+t-w,t*(p+w)+t-q,t*(p+p),t*(p+p)+q,t*p+t-p,t*(q+p)+w,t*(q+p)+p,t*(p+w)+t-w,t*(p+w)+t-q,t*(p+p),t*(p+p)+q,t*(p+p)+p,t*(p+p)+p,t*(t-p)+t-p,t*(t-q)+t-p,t*(t-p)+p,t*(t-q)+t-q,t*t,t*t+q,t*(t-p),t*t+p,t*t+q+p,t*(t-p)+p,t*t+p+p,t*(t-q)+t-w,t*t+t-w,t*(t-p)+t-p,t*(t+q),t*(t+q)+q,t*(t-w),t*(t+q)+p,t*(t+q)+q+p,t*(t-w)+p,t*(t-w)+q+p,t*(t-w),t*(t+q)+t-w,t*(t+q)+t-q,t*(t-w)+p,t*(t+w)+q,t*(t-w)+q+p,t*(t-q)+q,t*(t-q)+q,t*(t-q)+p,t*(t-q)+p,t*t+p+w,t*t+t-q,t*(t-q)+t-p,t*(t-q)+t-w,t*(t-q)+t-q,t*t,t*t+q,t*(t-p),t*t+p,t*t+q+p,t*t+p+w,t*t+p+p,t*(t+q)+w,t*t+t-w,t*t+t-q,t*(t+q),t*(t+q)+q,t*(t+q)+w,t*(t+q)+p,t*(t+q)+q+p,t*(t+q)+p+w,t*(t+q)+p+p,t*(t+w)+p,t*(t+q)+t-w,t*(t+q)+t-q,t*(t+q)+p+w,t*(t+w)+q,t*(t+q)+p+p,t*(t+w)+p,t*(t+w)+q+p,t*(t+w)+p+w,t*(t+w)+q+p};java.io.PrintStream o=(java.io.PrintStream)System.class.getFields()[p/p].get(p);o.print((r<=t)?"}":(char)g[r-t*p-w]);} ``` Try them out here: <https://ideone.com/Q3gqmQ> [Answer] # CJam - 11 bytes + CJam - 25 bytes = 36 bytes Characters are selected in alternating groups of 16: ``` !"#$%&'()*+,-./@ABCDEFGHIJKLMNO`abcdefghijklmno 0123456789:;<=>?PQRSTUVWXYZ[\]^_pqrstuvwxyz{|}~\n ``` It's cool that a few of the mappings can be obtained with the shift key :) ## Program A: ``` lL,H-f&'o+c ``` [Try it online](http://cjam.aditsu.net/#code=lL%2CH-f%26'o%2Bc&input=3) ## Program B: ``` q_S<\_0=16|_127<\S0=42^?? ``` [Try it online](http://cjam.aditsu.net/#code=q_S%3C%5C_0%3D16%7C_127%3C%5CS0%3D42%5E%3F%3F&input=A) **Explanation:** Program A: ``` l read a line from the input, this is a 1-character string or the empty string if the input was a newline L, get the length of an empty string/array (0) H- subtract 17, obtaining -17 (~16) f& bitwise-"and" each character (based on the ASCII code) with -17 'o+ append the 'o' character c convert to (first) character the result is the "and"-ed character, or 'o' for newline ``` Program B: ``` q_ read the whole input and duplicate it S<\ compare with " " and move the result before the input _0= duplicate the input again, and get the first (only) character 16| bitwise-"or" with 16 (based on the ASCII code) _127< duplicate and compare (its ASCII code) with 127 \ move the result before the "or"-ed character S0= get the space character (first character of the space string) 42^ xor with 42, obtaining a newline character stack: (input<" ") (input) ("or"-ed char<127) ("or"-ed char) (newline) ? if the "or"-ed character is less than 127, use the "or"-ed character else use the newline character ? if the input was smaller than space (i.e. it was a newline), use the input, else use the character from the previous step ``` [Answer] # FIXED! Pyth - 23 bytes + Pyth - 30 bytes = 53 bytes ~~*oops Fixing error --- please be patient*~~ same ASCII split as Martin's: ``` 1: "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~ 2:!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}\n ``` Prog#1: [Test Online](https://pyth.herokuapp.com/?code=.xhft%3CzT.Dr%5C%C2%A1b%3AZ140+2%5C~&input=a&test_suite=1&test_suite_input=A%0AB%0A~%0A!%0A&debug=0) ``` .xhft<zT.Dr\ยกb:Z140 2\~ ``` Prog#2: [Test Online](https://pyth.herokuapp.com/?code=C%3F%25KCwy1K%3Fqy5Ky5%3Fqy%2B1y31Ky5%2B1K&input=b&test_suite=1&test_suite_input=A%0A~%0AB&debug=0) ``` C?%KCwy1K?qy5Ky5?qy+1y31Ky5+1K ``` ]
[Question] [ One of my favorite definitions of the prime numbers goes as follows: * 2 is the smallest prime. * Numbers larger than 2 are prime if they are not divisible by a smaller prime. However this definition seems arbitrary, why 2? Why not some other number? Well lets try some other numbers will define n-prime such that * n is the smallest n-prime. * Numbers larger than n are n-prime if they are not divisible by a smaller n-prime. ## Task The task here is to write a program that takes two inputs, a positive integer **n** and a positive integer **a**. It will then decide if **a** is **n**-prime. Your program should output two distinct values one for "yes, it is n-prime" and one for "no, it is not n-prime". This is a code-golf question so answers will be scored in bytes with less bytes being better. ## Tests Here are lists of the first 31 primes for n=2 to n=12 (1 is the only 1-prime number) ``` n=2: [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] n=3: [3,4,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] n=4: [4,5,6,7,9,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] n=5: [5,6,7,8,9,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] n=6: [6,7,8,9,10,11,13,15,17,19,23,25,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107] n=7: [7,8,9,10,11,12,13,15,17,19,23,25,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107] n=8: [8,9,10,11,12,13,14,15,17,19,21,23,25,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89,97] n=9: [9,10,11,12,13,14,15,16,17,19,21,23,25,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89,97] n=10: [10,11,12,13,14,15,16,17,18,19,21,23,25,27,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89] n=11: [11,12,13,14,15,16,17,18,19,20,21,23,25,27,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89] n=12: [12,13,14,15,16,17,18,19,20,21,22,23,25,27,29,31,33,35,37,41,43,47,49,53,55,59,61,67,71,73,77] ``` [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` n!a=not$any(n!)[x|x<-[n..a-1],mod a x<1]||n>a ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08x0TYvv0QlMa9SI09RM7qipsJGNzpPTy9R1zBWJzc/RSFRocLGMLamJs8u8X9uYmaebUFRZl6JgoqCmaKh6X8A "Haskell โ€“ Try It Online") I define a nice recursive function `(!)`: `n!a` checks if any factor of `a`, in the range `[n,a-1]`, is an `n-prime`. Then it negates the result. It also makes sure that `n>a` [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ 37 bytes Thanks to Halvard Hummel for -2 bytes. ``` f=lambda n,i:n==i or i>i%n>0<f(n+1,i) ``` [Try it online!](https://tio.run/##RYyxCoMwAAV3v@ItgqEZoqWLNPmR0iFi0z5onxJc/Po0Tq7H3a379lk0lJL8N/6mOUKWo7wnlgwGtgrunjpdektTUoUChRz1fnWD7a9mbIA1UxsexCHwFJy9OQMm1EPtn@UP "Python 2 โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` lambda i,k:(i>k)<all(k%r for r in range(i,k)) ``` [Try it online!](https://tio.run/##RYxBCsMgEEX3OcUgCA5YaJpFQZqcxI0l2opmDJNsenpr2kV2n8d/b/3s70JDDaOt2S3P2UHUyag4JXy4nFWSDKEwMEQCdvTyqh0Q6wHLCW8a@gFNBytH2pWwJLdL24vfhCza0zw2Zklg9@ulU@31/XqYEAMEVVrd/CMJ6xc "Python 3 โ€“ Try It Online") ### How it works This takes two integers as input, **i** and **k**. First checks if **k โ‰ฅ i**. Then generates the range **[i, k)** and for each integer **N** in this range, checks if **N** is coprime to **k**. If both conditions are fulfilled, then **k** is an **i**-prime. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes ``` ฮตfโ‰ฅโฐแธŠ ``` [Try it online!](https://tio.run/##yygtzv7//9zWtEedSx81bni4o@v///9m/w1NAQ "Husk โ€“ Try It Online") or [see results up to 80](https://tio.run/##AS0A0v9odXNr/yBtKHdTLG9gZuG4ozgw4oKBKeKApjIgMTP/zrVm4oml4oGw4biK//8). Thanks to Leo for -1 byte. ## Explanation ``` ฮตfโ‰ฅโฐแธŠ Inputs are n and k. แธŠ Divisors of k. f Keep those that are โ‰ฅโฐ at least n. ฮต Is the result a one-element list? ``` [Answer] # [R](https://www.r-project.org/), ~~44~~ 37 bytes ``` function(a,n)a==n|a>n&all(a%%n:(a-1)) ``` [Try it online!](https://tio.run/##PYzBCsIwEETPyVfspSYL8VAFhUD8Ei9LMbChbiWtJ@23x8aIMIfh8WZyiaHEpwwLT2LJCVII8qaL7GgcLXWdeEv7HrHEKYMFBhY4@P4ICC@tBlosOzCPzPfb7M1Wr2JQq2anarM/nZutOG4w2uSA8Ye@F@m/U6uuqbCRtXwA "R โ€“ Try It Online") -7 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) Returns `TRUE` if * `a` is equal to `n` or (`a==n|`) * `a` is greater than `n` *and* (`a>n&`) for every number *k* from `n` to `a-1`, `a` is not evenly divisible by *k* (`all(a%%n:(a-1))`) Returns `FALSE` otherwise [Answer] # J, 30 bytes ``` >:*(-{1=[:+/0=[:|/~]+i.@[)^:>: ``` [Try it online!](https://tio.run/##y/r/P81Wz85KS0O32tA22kpb3wBI1ujXxWpn6jlEa8ZZ2VlxcaUmZ@QrGBooaMQq16XVKRloKmTqWRoo@DnpAUV1C4oyc1OLIYq09cHq0BT5leYmpRYp5KcpQNT@/w8A) Takes starting value as the right argument and the value to check at the left argument. I messed up originally and didn't account for left arguments less than the starting prime. I'm somewhat unhappy with the length of my solution now. # Explanation Let `x` be the left argument (the value to check) and `y` be the right argument (the starting prime). ``` >:*(-{1=[:+/0=[:|/~]+i.@[)^:>: ^:>: Execute left argument if x >= y i.@[ Create range [0..x] ]+ Add y to it (range now: [y..x+y]) |/~ Form table of residues 0= Equate each element to 0 +/ Sum columns 1= Equate to 1 -{ Take the element at position x-y >:* Multiply by result of x >= y ``` ### Notes The element at position `x-y` is the result of primality testing for `x` (since we added `y` to the original range). Multiplying by `x >: y` ensures that we get a falsey value (`0`) for `x` less than `y`. [Answer] # JavaScript (ES6), ~~33~~ ~~32~~ 30 bytes Takes input in currying syntax `(n)(a)`. Returns a boolean. ``` n=>p=(a,k=a)=>k%--a?p(a,k):a<n ``` ### Demo ``` let f = n=>p=(a,k=a)=>k%--a?p(a,k):a<n for(n = 2; n <= 12; n++) { for(a = n, P = []; P.length < 31; a++) { f(n)(a) && P.push(a); } O.innerText += 'n=' + n + ': ' + P.join(',') + '\n'; } ``` ``` <pre id=O></pre> ``` [Answer] # [Haskell](https://www.haskell.org/), 30 bytes *2 bytes saved thanks to H.PWiz's idea which was borrowed from [flawr's answer](https://codegolf.stackexchange.com/questions/149863/iterated-phi-sequence/149870#149870)* ``` n!a=[1]==[1|0<-mod a<$>[n..a]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08x0TbaMNYWSNQY2Ojm5qcoJNqo2EXn6eklxsb@z03MzLMtKMrMK1EpScxOVTA2VEnLzClJLdIwNFLUjDbU04v9DwA "Haskell โ€“ Try It Online") Ok since its been a while, and the only Haskell answer so far is 45 btyes, I decided to post my own answer. ## Explanation This function checks that the only number between **n** and **a** that **a** is divisible by is **a** itself. Now the definition only mentions **n**-primes smaller than **a**, so why are we checking all these extra numbers? Won't we have problems when **a** is divisible by some **n**-composite larger than **n**? We won't because if there is an **n**-composite larger than **n** it must be divisible by a smaller **n**-prime by definition. Thus if it divides **a** so must the smaller **n**-prime. If **a** is smaller than **n** `[n..a]` will be `[]` thus cannot equal `[1]` causing the check to fail. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~23~~ ~~19~~ 14 bytes ``` b>=a&$&b%(a,b) ``` Shortest method is a port of [Mr. Xcoder's Python answer](https://codegolf.stackexchange.com/a/149000/16766). Takes the smallest prime and the number to test as command-line arguments. [Try it online!](https://tio.run/##K8gs@P8/yc42UU1FLUlVI1EnSfP///9m/w1NAQ "Pip โ€“ Try It Online") [Answer] # C, 55 bytes ``` f(n,a,i){for(i=a;i-->n;)a%i||f(n,i)&&(i=0);return-1<i;} ``` [Try it online!](https://tio.run/##RY1BDoMwDATvvMJCAsXCSARuDfAXBE3llKaIwgl4O3Vaqd3jenbc57e@P0@rPHXEuNnnrLjpDOd56w12Ce97ODKmqRwKNPN1WWef65rNcbJf4NGxVxhtEUhkDyq0dxrJETfaANe6MpBlTDCty0vFMeIXnGZBrYqTcrjEBIwErhFsbAoDY11pSFPRtXrfXV1ikDj8/AlhC8oqwR3@y5CfthpAtI5kN6KJjvMN) **53 bytes if multiple truthy return values are allowed:** ``` f(n,a,i){for(i=a;i-->n;)a%i||f(n,i)&&(i=0);return~i;} ``` [Try it online!](https://tio.run/##RY1BDoIwEEX3nGJCQtMJQwKys8BdCFgzFStBWAFeHaea6F/@ef9Nl1277jis9tQS42ofk@a6NZxljTfYJrxt4ciolBxyNNNlXib/YrMf7Ge4t@w1RmsEElmDDu2NBnLEdWGAq6I0kKZMMC7zU8cx4hccJ0GtjpNTf44JGAlcLdhQ5waGqixAKdE1xba56oRB4vDzJ4QtaKsFd/gvQ37asgfROpLdgCbajzc) [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~40~~ ~~34~~ 37 bytes ``` [0p3Q]sf?se[dler%0=f1+dle>u]sudle>u1p ``` I would have included a TIO link, but TIO seems to be carrying a faulty distribution of `dc` seeing as how this works as intended on my system but the `Q` command functions erroneously on TIO. Instead, here is a link to a `bash` testing ground with a correctly functioning version of `dc`: [Demo It!](http://tpcg.io/lFU7Hc) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 24 bytes ``` {โตโˆŠo/โจ1=+/ยจ0=o|โจโŠ‚oโ†โบโ†“โณโต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bH3V05es/6l1haKutf2iFgW1@DZDzqKspHyj/qHfXo7bJj3o3A9XV/v@vYagNZBsZairoKEDYxgaaCo96VyloIHE7ZuilAY1QMAIrNtAEAA "APL (Dyalog Unicode) โ€“ Try It Online") **How?** `โณโต` - `1` to `a` `oโ†โบโ†“` - `n` to `a`, save to `o` `o|โจโŠ‚o` - modulo every item in `o` with every item in `o` `0=` - check where it equals `0` (divides) `+/ยจ` - sum the number of divisions `1=` - if we have only one then the number is only divided by itself `o/โจ` - so we keep these occurences `โตโˆŠ` - is `a` in that residual array? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 5 bytes ``` rแธแน›ฤ‹< ``` [Try it online!](https://tio.run/##y0rNyan8/7/o4Y7ehztnH@m2@X94udL//0Y6CmY6CuY6CoaGOgpG/w0tgSxTIAYKAikjAA "Jelly โ€“ Try It Online") This outputs `0` or `1` for "yes" and a positive integer greater than `1` for "no". This really stretches the "output two distinct values", so I've included a more reasonable 6 byte version: ``` rแธแน›แน–i< ``` [Try it online!](https://tio.run/##y0rNyan8/7/o4Y7ehztnP9w5LdPm/@HlSv//G@komOkomOsoGBrqKBj9N7QEskyBGCgIpIwA "Jelly โ€“ Try It Online") Outputs `0` for "yes, it is \$n\$-prime" and a positive integer for "no it is not \$n\$-prime". [+1 byte](https://tio.run/##y0rNyan8/7/o4c5pD3f0Ptw5O9XB5v/h5Ur//xvpKJjpKJjrKBga/je0BFKmQAwUMQUA) to use just `0` and `1`. ## How they work ``` rแธแน›ฤ‹< - Main link. Takes n on the left and a on the right r - Range from n to a inclusive แน› - Right; Yield a แธ - For each element in the range, is it divisible by a? < - Is n < a? ฤ‹ - Count the occurrences of (n < a) in the divisibility range ``` This works because in the range \$[n, a]\$, only one integer can be divisible by \$a\$ if \$a\$ is \$n\$-prime: \$a\$. Therefore, the range, after divisibility, would look like `[0, 0, 0, ..., 1]`. However, this doesn't check the condition that \$n\$ is the smallest \$n\$-prime, as `r` will generate a descending range if \$n < a\$. Therefore, we check that \$n < a\$ and count the occurrences of that (`1` or `0`) in the divisibility range. If \$n > a\$, there will be more than one `0` in the range, and if \$a\$ is not \$n\$-prime, but \$n < a\$, there will be more than `1` in the range. If \$n = a\$, then `r` will yield an empty list and `ฤ‹` will return `0`, no matter what the result of `<` is. ``` rแธแน›แน–i< - Main link. Takes n on the left and a on the right r - Range from n to a inclusive แน› - Right; Yield a แธ - For each element in the range, is it divisible by a? แน– - Remove the final element, 1 < - Is n < a? i - Index of (n < a) or 0 if not found ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 27 bytes ``` i=>f=n=>i==n||i>i%n&&f(n+1) ``` [Try it online!](https://tio.run/##BcFRCoAgDADQ0yQbURD1O@8iprHQLTL68u7zvTv8ocWXn28RPZNVMiafScgzkfTOnidxLoPMG1pUaVrSWvSCCgfCjmgD "JavaScript (Node.js) โ€“ Try It Online") Port of my Python answer, takes input in currying syntax: `m(number)(first prime)` [Answer] # JavaScript ES5, 34 Bytes ``` for(a=i=(p=prompt)();a%--i;);i<p() ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 20 bytes ``` L,2Dx@rBcB%B]b*!!A>* ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx8ilwqHIKdlJ1Sk2SUtR0dFO6////6b/LQE "Add++ โ€“ Try It Online") ``` L, - Create a lambda function - Example arguments: [5 9] 2D - Copy below; STACK = [5 9 5] x - Repeat; STACK = [5 9 [9 9 9 9 9]] @ - Reverse; STACK = [[9 9 9 9 9] 5 19] r - Range; STACK = [[9 9 9 9 9] [5 6 7 8 9]] Bc - Zip; STACK = [[9 5] [9 6] [9 7] [9 8] [9 9]] B% - Modulo; STACK = [4 3 2 1] B] - Wrap; STACK = [[4 3 2 1]] b* - Product; STACK = [24] !! - Boolean; STACK = [1] A - Arguments; STACK = [1 5 9] > - Greater; STACK = [1 1] * - Product; STACK = [1] ``` ]
[Question] [ ## [Sandbox](https://codegolf.meta.stackexchange.com/a/17644/75681) For the purposes of the current task, a cube of unit length is rendered in oblique projection with ASCII symbols as follows: ``` +-----+ / /| +-----+ | | | + | |/ +-----+ ``` * `+` for the vertices. * `-` for the X edges. The unit length along X is represented by five `-` between two vertices. * `|` for the Y edges. The unit length along Y is represented by two `|` between two vertices. * `/` for the Z edges. The unit length along Z is represented by one `/` between two vertices. * Vertices are only drawn where all the three planes intersect. * Edges are only drawn where exactly two planes intersect. When a unit face is extruded, it is offset by a unit length from its original position and four new edges are created for each direction (positive and negative). You can think of the extrusion as of drawing the axes of a 3D Cartesian coordinate system where each axis is represented as a cuboid with cross section 1x1 and length `n` away from (0,0,0) Extruded by 1 along X: ``` +-----------------+ / /| +-----------------+ | | | + | |/ +-----------------+ ``` ## Task Given three numbers for the XYZ axes, extrude the faces of a unit cube symmetrically by the indicated amounts and render the result with the ASCII symbols as specified above. ## Input x, y, z โ€“ non-negative numbers - extrusion lengths for the respective axes. 0 means no extrusion. The input can be three numbers, a list of three numbers, a triple, a string or anything thatโ€™s convenient for you. ## Output The ASCII drawing of the cube after extrusion. Leading and trailing wihtespaces are allowed. ## Test cases ``` X Y Z 0 0 0 +-----+ / /| +-----+ | | | + | |/ +-----+ 1 0 0 +-----------------+ / /| +-----------------+ | | | + | |/ +-----------------+ 0 0 1 +-----+ / /| / / | / / + / / / / / / +-----+ / | | / | |/ +-----+ 1 1 0 +-----+ / /| +-----+ | +---| | +-----+ / | |/ /| +-----+ +-----+ | | | + | |/ +-----+ +-----+ | | + | |/ +-----+ 2 0 1 +-----+ / /| +-----------+ +-----------+ / /| +-----------+ +-----------+ | | / /| | + | +-----+ | |/ +---------| | +-----------+ | |/ +-----+ 1 1 1 +-----+ / /|-+ +-----+ |/| +---| | +-----+ / | |/ /| +-----+-----+-----+ | | / /| | + | +-----+ | |/ +---| | +-----+ | |/| + +-----+ |/ +-----+ ``` ## Winning criteria The shortest solution in bytes in every language wins. Please add a short description of the method used and your code. [Answer] # JavaScript (ES6), ~~525 ... 475 471~~ 459 bytes *Saved 13 bytes thanks to @Neil* Takes input as an array `[X,Y,Z]`. Returns a matrix of characters. ``` a=>([X,Y,Z]=a,m=[],W=X*6+Z*2,'1uol9h824lsqpq17de52u1okgnv21dnjaww111qmhx1gxf4m50xg6pb42kzijq21xyh34t0h2gueq0qznnza2rrimsg3bkrxfh3yrh0em').replace(/.{7}/g,s=>[[c,x,A,y,B,w,C,h,D,t]=parseInt(s,36)+s,Y*W,Z,X,Y|!W,Z*X,X*Y*!Z,X*Z*!Y,Y*Z*!X][c]&&(g=H=>V<h&&((m[r=y-(3-B)*p+(t>1?H-V:V)+Y*3+Z*2]=m[r]||Array(W*2+9).fill` `)[x-2*(3-A)*p+(t>1?V:H-V*t)+W]=` ${c>5?' + ':t>1?'|-':'-|'}+/+`[(H%~-w?0:+t?4:2)|!(V%~-h)],g(++H<w?H:!++V)))(V=0,p=a[c%3],w-=-3*C*p,h-=-D*p))&&m ``` [Try it online!](https://tio.run/##bZLZbuJAEEXf8xVGSnAvZccLkIlJg7JJzA8YL2MJxxgb8EbbCWabX2fa0mgeonm6V6fubalKvQm/wjri66pRinIZX1fsGrIJ8h1wwQtYCDnzA5gzh4yoRwyQ9c8ye0x/GIOs3lU7/WEZD41PvdwmxZehL4tNuN/rur7L01ZP2tUgH2ptMqo@Bsb2uN7sDL09pOag0VIj@Yx32u5YFMfQ4Hyd14n5seXtKjUPPNXiXMYqj6ssjGJ0r54eLvcJ1Gzi@xG08AwHeIE9vEIKb9AErAp5Hf8sGlSDOcK0BpfMwQOxxbknDHHAIS7pCUI80nPFWIgT@FHQ76OEzdjEfkqFRbnP2UFBpvKCSUVRM9GnM8W2bExdYnYXCJiIBOfzM@fhAc2JQR@xulpn2UJaYL9VDCLKz//KtiXqpMF0HrCFdHuKJsOpLElUkq1uLJ8V2ZKVs3yh93Tho9ndb2U/1SzaTAeWgc89ZAuS4gASROnsaT@dWT1KbYwxspkGFQv96M4MYK8wxSSvpIJUuDdSYdzv59exr4EORqCuSv4eRilyJDaRvkP3f9Dr4OlGkqKyqMssVrMyQQuH3Z6cC0iuUFeoJ9S7LPD4W3DVfSHJFYEAq3lYId49x9VNuS6QLGP81/0qZNxdo9PxzUXsdf0D "JavaScript (Node.js) โ€“ Try It Online") ## How? ### Drawing steps The output consists of 15 sides, drawn in a specific order. [![animation](https://i.stack.imgur.com/2ey7R.gif)](https://i.stack.imgur.com/2ey7R.gif) ### Implementation The drawing function is \$g\$. It works with the following parameters: * \$(x, y)\$: where to start drawing * \$w\$: width * \$h\$: height * \$t\$: type of side The vertices are always drawn. Depending on the value of another parameter \$c\$, the edges are either drawn or erased. If \$t=0\$, the function draws a front side: ``` ........... ........... ..+-----+.. ..+ +.. ..| |.. or .. .. ..| |.. .. .. ..+-----+.. ..+ +.. ........... ........... ``` If \$t=1\$, it draws a top side: ``` ........... ........... ...+-----+. ...+ +. ../ /.. or .. .. .+-----+... .+ +... ........... ........... ``` If \$t=2\$, it draws a right side: ``` ......+.... ......+.... ...../|.... ..... .... ....+ |.... or ....+ .... ....| +.... .... +.... ....|/..... .... ..... ....+...... ....+...... ``` The coordinates \$(x,y)\$ and the size \$(w,h)\$ of each side either have a constant value or depend on exactly one of the input variables: \$X\$, \$Y\$ or \$Z\$. Besides, each side is drawn if and only if a specific condition is met. Both the input variable to use and the condition to check are identified with the parameter \$c \in[1..8]\$. To summarize, a side is fully described with: $$\begin{cases} c\\ t\\ x=o\_x+m\_x\times P\\ y=o\_y+m\_y\times P\\ w=o\_w+m\_w\times P\\ h=o\_h+m\_h\times P \end{cases} $$ where \$P\$ is the input variable deduced from \$c\$. Therefore, we need to store the following 10 parameters for each side: $$[c, o\_x, m\_x, o\_y, m\_y, o\_w, m\_w, o\_h, m\_h, t]$$ Below are the parameters of the 15 sides that need to be drawn: $$\begin{array}{|c|c|} \hline \text{side} & c & o\_x & m\_x & o\_y & m\_y & o\_w & m\_w & o\_h & m\_h & t\\ \hline 0 & 4 & 0 & 0 & 2 & -3 & 7 & 0 & 4 & 6 & 0\\ 1 & 4 & 6 & 0 & 2 & -3 & 4 & 6 & 3 & 0 & 2\\ 2 & 2 & 6 & -2 & 2 & 2 & 4 & 0 & 3 & 4 & 2\\ 3 & 3 & 6 & 6 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\ 4 & 3 & 0 & -6 & 2 & 0 & 7 & 12 & 4 & 0 & 0\\ 5 & 2 & 2 & 2 & 0 & -2 & 7 & 0 & 3 & 4 & 1\\ 6 & 3 & 2 & -6 & 0 & 0 & 7 & 12 & 3 & 0 & 1\\ 7 & 2 & 0 & -2 & 2 & 2 & 7 & 0 & 4 & 0 & 0\\ 8 & 5 & 6 & -2 & 2 & 2 & 4 & 0 & 1 & 2 & 2\\ 9 & 4 & 2 & 0 & 0 & -3 & 7 & 0 & 3 & 0 & 1\\ 10 & 1 & 0 & 0 & 2 & -3 & 7 & 0 & 1 & 3 & 0\\ 11 & 1 & 6 & 0 & 2 & -3 & 1 & 3 & 3 & 0 & 2\\ 12 & 6 & 0 & 0 & 2 & 0 & 7 & 0 & 4 & 0 & 0\\ 13 & 7 & 2 & 0 & 0 & 0 & 7 & 0 & 3 & 0 & 1\\ 14 & 8 & 6 & 0 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\ \hline \end{array}$$ We force all values into the range \$[0..9]\$ by applying the following operations: $$m\_x\gets (m\_x+6)/2\\ m\_y\gets m\_y+3\\ m\_w\gets m\_w/3$$ It results in 15 numbers of exactly 10 decimal digits, which are stored as 15 groups of 7 digits in base 36. For instance, the first side is encoded as `4032070460` and stored as `1uol9h8`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~162~~ ~~161~~ ~~132~~ 130 bytes ``` {' |+/+ +-? ??? ++'[โ‰(โŠƒ~โˆ˜0)โค1โฃ3โ‰โ†‘aโ†‘ยจโจโ†“(--1-โŒŠ/โˆ˜,)2-/1โŒฝโ†‘โณโดaโ†16|29|1+{2โŠฅ+/ยจโˆŠยจ=โŒฟยจโต(โ‰โต)(โ‰โ†“โต)}โŒบ2 2 2{โ‰โค2โ‰โŒฝ0,โต}โฃ6โ†‘3/โ†“2/6โŒฟ1<โต+.=โจโ†‘โณ1+2ร—โต]} ``` [Try it online!](https://tio.run/##RU/BSsNAEL37FXvrLtt1MxsJCJYcvNiTYL2Jh1CpFAIVepIkXoRQQzZUStG7FXLzoL0IRYh/Mj8SZ9ODDLszb97btzPRXaxu7qN4dqvGcTSfT8ctVuvpDPOl1yY9lkotmVQhC8OQSdm7QvvEsXh8wMWrJ9BuAO2bT03MnyM6TY22xnzFlQKFZaFJ1xdGacByRzzaT7RfpFxCkJrjFGRisHiXmh4uiqYeYPnjPLbcedqt6HK@cmWG5bdhFEnHbYxL5c7rE5nRGAH5@5rERgdkAyfUl4eDbiD3MUjz@0K966yd0ABoK1p1eE7bNB@@k1Tr0cUp3Zdnw1E7aWruMQrBYZ8cAofAIfOPQBzs1a4kwmdH4g8 "APL (Dyalog Classic) โ€“ Try It Online") * generate a 3d bool array of unit cubies * replicate each cubie 6 3 2 times along x y z * surround with zeroes * for each 2ร—2ร—2 subarray compute a number between 0 and 16 that determines the corresponding output char: `(1 + 4*cx + 2*cy + cz) mod 16` where `cx`,`cy`,`cz` are the number of same-value "rods" along axis x,y,z, i.e. vectors along that axis that consist of the same value: 0 0 or 1 1. we make an exception if the subarray is all-zero (or all-one - those don't matter) and we consider its number 0 instead of 28 * for each cell compute where the corresponding char should be drawn on screen * for each cell build a transparent (0-padded) matrix that contains only one opaque "pixel" * mix the matrices - at this point we have a 5d array with dimensions inx,iny,inz,outx,outy * reduce the first three axes, keeping only the first non-transparent (โ‰ 0) item along them * use a lookup table (a string) to convert the numbers into `-|/+` thanks Scott Milner for spotting that some `+`s rendered as `?`s [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 325 bytes ``` โ‰”ร—โถ๏ผฎฮธโ‰”ร—ยณ๏ผฎฮทโ‰”โŠ—๏ผฎฮถยฟโ€นยนโ„–โŸฆฮธฮทฮถโŸงโฐยซ๏ผขโบโทโŠ—ฮธโบโดโŠ—ฮทโ†—โ†—โŠ•โŠ—ฮถ+โบโตโŠ—ฮธ๏ผฐโ†™โŠ—โŠ•ฮถโ†“+โ†“โบยฒโŠ—ฮทโ†™+โ†™โŠ•โŠ—ฮถยปยซ๏ผฆโ€นโฐฮธยซโ†—+โ†—โ†+โ†โŠ–ฮธโ†™+/๏ผฐโ†’ฮธโ†“+โ†“ยฒ+โŠ–ฮธ+ยป๏ผฆโ€นโฐฮทยซ๏ผชโถยฆยณโ†—+โ†—โ†“+โ†“โŠ–ฮทโ†™+/๏ผฐโ†‘ฮทโ†+โ†โตโ†‘+โ†‘โŠ–ฮท+ยป๏ผฆโ€นโฐฮถยซ๏ผชโธยฑยฒโ†“+โ†“โ†“โ†—+โ†—โŠ–ฮถโ†‘+โ†‘ยฒ๏ผฐโ†™ฮถโ†+โ†โตโ†™+โ†™โŠ–ฮถ+ยป๏ผชโถยฆโฐ๏ผฆโ€นโฐฮถยซ๏ผงโ†“ยณโ†™โŠ•ฮถโ†โทโ†‘ยณโ†—โŠ•ฮถ โ†™+โ†™โŠ–ฮถโ†“+โ†“ยฒ+โ†’โต๏ผฐโ†—ฮถโ†‘+โ†‘ยฒ๏ผฐโ†โถโ†—+โ†—โŠ–ฮถยป๏ผฆโ€นโฐฮทยซ๏ผงโ†โถโ†‘โŠ•ฮทโ†—ยณโ†’โถโ†“โŠ•ฮท โ†‘+โ†‘โŠ–ฮทโ†+โ†โตโ†™+/๏ผฐโ†“ฮท+โต๏ผฐโ†—ยฒโ†“+โ†“โŠ–ฮทยป๏ผฆโ€นโฐฮธยซ๏ผงโ†—ยฒโ†’โŠ•ฮธโ†“โดโ†™ยฒโ†โŠ•ฮธ โ†’+โŠ–ฮธโ†—+/โ†‘+โ†‘ยฒ๏ผฐโ†ฮธโ†™+/๏ผฐโ†“ยณโ†+โ†โŠ–ฮธยป๏ผฐโ†—โˆงโˆงฮธฮทยฒ๏ผฐโ†“โˆงโˆงฮถฮธยณ๏ผฐโ†โˆงโˆงฮทฮถโถ+ ``` [Try it online!](https://tio.run/##rZZdb9owFIavy6@wcmVrmcoSoNV61Y2bTV2FpvZq2gWlhkQKcT67LRO/PbNjB3/FFaS7QMDxa5/Xz/FxsonWxYask7a9Lct4l8KHeI9LuPDBlzSrq/t6/4QLiJAPcnQz0TShrYmkZknqpwQ/Q1PSUEm8BfAOlyX84IPPpE4r@COnk@ngTx9MEULg7@TiE/kNV0ldwisf9IvlbIUuOJPBiE64mVx8Iy8YfnzMvse7qGKBVRHTlfsIM7sp8B6nFZ3Tz234XC713nnyT5dlrqXustRJFWd85SX5ld7hbSVFagpt6U7rAy2DiHWJAms7KzOHPZfH3ds6AJyUmLHckkIQn7JCdnwtPiKBDbJXaj704BJLE7k6rPq/FOsrCEVqa4qVhgcDJaQLdAO27GBAiASEr/U@eyDsvIdqutOhvOJW9RShM6g8ZryVTiE/121bKhZyGnHAaXQ41z64x7t1hWGA3FvnhFhs6K@LqxlXrTbohL0FFj0JtxnD0Oo4e8BpUvKU52rKIoN4VyT5syNpD5Lep462buitJ6zSy7Dbdth9D9xsTOsB73/taFw39n09HzjaYqgZVVvudvHGI@W6DI4FEWkEaxVvhFTwrAri50JUz5Yb1Ti3R0cd3IFLhZuLnDV7pVbB6Avv4Hr29KRlDolSBZijI9eZ1h/BsSVMucF78HQ4Hxfqcbr03nBG87NLE4561grKg3W7TZ8h@7CXK8SsDr3BSFnDXDMfpozn7WXsPQ2xJjTfnA5tG4AQzNr3L8k/ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` โ‰”ร—โถ๏ผฎฮธโ‰”ร—ยณ๏ผฎฮทโ‰”โŠ—๏ผฎฮถ ``` Input the extrusions, but premultiply them to save bytes. ``` ยฟโ€นยนโ„–โŸฆฮธฮทฮถโŸงโฐยซ๏ผขโบโทโŠ—ฮธโบโดโŠ—ฮทโ†—โ†—โŠ•โŠ—ฮถ+โบโตโŠ—ฮธ๏ผฐโ†™โŠ—โŠ•ฮถโ†“+โ†“โบยฒโŠ—ฮทโ†™+โ†™โŠ•โŠ—ฮถยปยซ ``` If at least two of the extrusions are zero, then simply draw a cuboid of dimensions (2x+1, 2y+1, 2z+1). Otherwise: ``` ๏ผฆโ€นโฐฮธยซโ†—+โ†—โ†+โ†โŠ–ฮธโ†™+/๏ผฐโ†’ฮธโ†“+โ†“ยฒ+โŠ–ฮธ+ยป ``` Print the left extrusion, if any. ``` ๏ผฆโ€นโฐฮทยซ๏ผชโถยฆยณโ†—+โ†—โ†“+โ†“โŠ–ฮทโ†™+/๏ผฐโ†‘ฮทโ†+โ†โตโ†‘+โ†‘โŠ–ฮท+ยป ``` Print the down extrusion, if any. ``` ๏ผฆโ€นโฐฮถยซ๏ผชโธยฑยฒโ†“+โ†“โ†“โ†—+โ†—โŠ–ฮถโ†‘+โ†‘ยฒ๏ผฐโ†™ฮถโ†+โ†โตโ†™+โ†™โŠ–ฮถ+ยป ``` Print the back extrusion, if any. ``` ๏ผชโถยฆโฐ ``` The remaining extrusions all meet at this point (which doesn't get drawn until the very end!) ``` ๏ผฆโ€นโฐฮถยซ๏ผงโ†“ยณโ†™โŠ•ฮถโ†โทโ†‘ยณโ†—โŠ•ฮถ โ†™+โ†™โŠ–ฮถโ†“+โ†“ยฒ+โ†’โต๏ผฐโ†—ฮถโ†‘+โ†‘ยฒ๏ผฐโ†โถโ†—+โ†—โŠ–ฮถยป ``` Print the front extrusion, if any, taking care to erase parts of the left and down extrusions that may overlap. ``` ๏ผฆโ€นโฐฮทยซ๏ผงโ†โถโ†‘โŠ•ฮทโ†—ยณโ†’โถโ†“โŠ•ฮท โ†‘+โ†‘โŠ–ฮทโ†+โ†โตโ†™+/๏ผฐโ†“ฮท+โต๏ผฐโ†—ยฒโ†“+โ†“โŠ–ฮทยป ``` Print the up extrusion, if any, taking care to erase parts of the back and left extrusions that may overlap. ``` ๏ผฆโ€นโฐฮธยซ๏ผงโ†—ยฒโ†’โŠ•ฮธโ†“โดโ†™ยฒโ†โŠ•ฮธ โ†’+โŠ–ฮธโ†—+/โ†‘+โ†‘ยฒ๏ผฐโ†ฮธโ†™+/๏ผฐโ†“ยณโ†+โ†โŠ–ฮธยป ``` Print the right extrusion, if any, taking care to erase parts of the down and back extrusions that may overlap. ``` ๏ผฐโ†—โˆงโˆงฮธฮทยฒ๏ผฐโ†“โˆงโˆงฮถฮธยณ๏ผฐโ†โˆงโˆงฮทฮถโถ+ ``` Draw the joins between the latter extrusions. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~195~~ ~~164~~ 144 bytes ``` โ‰”โบยณร—โถ๏ผฎฮธโ‰”โบยฒร—ยณ๏ผฎฮทโ‰”โŠ•โŠ—๏ผฎฮถ๏ผฆโ€ฆยทยฑฮถฮถ๏ผฆโ€ฆยทยฑฮทฮท๏ผฆโ€ฆยทยฑฮธฮธยซ๏ผชโปฮปฮนโบฮบฮนโ‰”โŸฆโŸงฮด๏ผฆ๏ผฅยฒโ†”โปโบฮนฮผยทโต๏ผฆ๏ผฅยฒโ†”โปฮบฮฝ๏ผฆ๏ผฅยฒโ†”โปโบฮปฮพยทโตโŠžฮดโŒŠโŸฆโ€นฮผฮถโ€นฮฝฮทโ€นฮพฮธโ€นยนโ„–๏ผฅโŸฆฮผฮฝฮพโŸงโ€นฯ€โŠ•ฯยนโŸงโ‰กฮฃฮดยน+ยฒยง |-/โบโŒ•ฮดยนโŒ•โฎŒฮดยนยฆยณ+โดยง +ฮฃโ€ฆฮดโดยฆโถยง |-/โŒ•ฮดโฐ ``` [Try it online!](https://tio.run/##fZHBT8IwFMbP8Fe87NSGoo4hBz0RjAlGCEFuhMPYKmtcu7FuOFH@9vlahpCAnPbW/t73vu81iPwsSPy4qvpai5Uik7jQxGMwE5Jr0mMwVGmRjwu55BmhlDJY08fmKdw5wN4FODrCQxVkXHKV85A8JcUyxu8Zv0X@PcnA0CguNnzqqxUnY77yc062FqFwBYns1KvI2qag8N1svBQynSVkJBQmiRkIvLKpPkyNZhq1@/mCQWj@re7IT03u/lLXrbZHMJDYf3OPUWoDZyDqqivXVgd9lEedSaEjEjJAQMhCkvkr15pIswgGtlYmcV2XJlpduwwGSaFyO2aOHQiWi/oyNa91fJHMrt@ldGFT60@RBxGQNxwY7lcV@JqD@wCTTKCk03IMZw87h8N@PlQhL4kDP@1bp97ks1Ch8e@ivq2nfMMzzVHXDqR/Ot4l8e65eAuljbHBVxDzQZSkRr57qtT7z9HBzN0e3jV3VeVCB7yqvYl/AQ "Charcoal โ€“ Try It Online") Link is to verbose version of code. I'm posting this as a separate answer as it uses a completely different approach to drawing the extrusion. Explanation: ``` โ‰”โบยณร—โถ๏ผฎฮธโ‰”โบยฒร—ยณ๏ผฎฮทโ‰”โŠ•โŠ—๏ผฎฮถ ``` Input the extrusions and calculate half the size of the enclosing cuboid, but in integer arithmetic because Charcoal's ranges are always integers. The origin of the output maps to the centre of the original unit cube. ``` ๏ผฆโ€ฆยทยฑฮถฮถ๏ผฆโ€ฆยทยฑฮทฮท๏ผฆโ€ฆยทยฑฮธฮธยซ ``` Loop over all coordinates within (including the boundary) the cuboid containing the extrusion. ``` ๏ผชโปฮปฮนโบฮบฮน ``` Jump to the output position corresponding to those coordinates. ``` โ‰”โŸฆโŸงฮด๏ผฆ๏ผฅยฒโ†”โปโบฮนฮผยทโต๏ผฆ๏ผฅยฒโ†”โปฮบฮฝ๏ผฆ๏ผฅยฒโ†”โปโบฮปฮพยทโตโŠžฮดโŒŠโŸฆโ€นฮผฮถโ€นฮฝฮทโ€นฮพฮธโ€นยนโ„–๏ผฅโŸฆฮผฮฝฮพโŸงโ€นฯ€โŠ•ฯยนโŸง ``` From the given coordinates, peek in all eight diagonal directions to determine whether the extrusion overlaps in that direction. The peeked coordinates are checked that they still lie within the cuboid, and then the number of axes in which the coordinate lies within the original cube must be greater than 1. Note that since the cube has an odd display height, the Y-axis values that are peeked are integers while the other axes use fractional coordinates. ``` โ‰กฮฃฮด ``` Consider the number of directions in which the extrusion overlaps. There are five cases of interest where we want to print something, as in the case of zero, that means that this is empty space and we don't want to print anything, while in the case of eight, that means that this is inside the extrusion and anything we did print would be overprinted by a layer nearer the eye point. ``` ยน+ ``` If the extrusion only overlaps in one direction then this is an outer corner and we need to output a `+`. ``` ยฒยง |-/โบโŒ•ฮดยนโŒ•โฎŒฮดยนยฆ ``` If the extrusion overlaps in two directions then this is an outer edge. Which sort of edge is determined from the separation between the two overlaps; 6 and 7 are rear-facing edges and will get overwritten, 4 is a diagonal edge, 2 is a vertical edge and 1 is a horizontal edge. (I actually calculate 7 minus the separation as it seems to be easier to do.) ``` ยณ+ ``` If the extrusion overlaps in three directions then this is an inner corner in the case where one of the extrusions is zero and we need to output a `+`. ``` โดยง +ฮฃโ€ฆฮดโดยฆ ``` If the extrusion overlaps in four directions then there are two cases: faces (any direction), and inner corners in the case with three positive extrusions. In the latter case there are an odd number of overlaps towards the viewer. ``` โถยง |-/โŒ•ฮดโฐ ``` If the extrusion overlaps in six directions then this is an inner edge. It works like the complement of an outer edge except that we're only interested when one of the two empty spaces is the direction towards the eye point (the last entry in the array). [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 172 bytes ``` {s:1+|/'i-:&//i:1_--':1_4#!#'2*:\a:16!29!1+2/(!3){+'+x}/'{2+':''1+':'0=':x}'{++'x}\6{+'+0,|x}/{6}#{3}#'{2}#''s#1<+/x=!s:1+2*x;" |+/+ +-? ??? ++"s#@[&*/s;s/i;{x+y*~x};,//a]} ``` [Try it online!](https://tio.run/##XY7LbsIwEEX3/YoJljBkEjl2EFKdovAf0IcFDo0ICYqT1pVxf506LDszOqujO/ectqf2fq@kM5LjjdE6lXPGasnf05QGrkhEqIjlXkm@jsRzxFGwRZQvHVK0nlEnkEpK@cRsQ6X11CFS6/frScmSW7Dc2hOXexLsAGoIf0FmN9H0VMS2mMENGQKmJZRlCYgzQ7a7ecxMYVhdOIs/8a/1RcKYevVTXbRvSRySd6J4rbbwf9hFnTVUoBrTQa8v3ZcGM/Z9N7bHuj3B92c9aHNVB/30AZlMWEUXGOUkXyYLATmsCp7B45YhTDUNjFcYOhCPVe0RFBy68dpo0HboFYS04f4H "K (ngn/k) โ€“ Try It Online") obligatory k rewrite of [my apl solution](https://codegolf.stackexchange.com/questions/185449/extrude-the-faces-of-a-cube-symmetrically-along-xyz/185458#185458) same algorithm, except that 3d->2d rendering is done with (the k equivalent of) scatter index assignment instead of creating 2d matrices for each 3d element and mixing them ]
[Question] [ Apparently yes! In three easy steps. ### Step 1 Let *f*(*n*) denote the prime-counting function (number of primes less than or equal to *n*). Define the integer **sequence** *s*(*n*) as follows. For each positive integer *n*, * Initiallize *t* to *n*. * As long as *t* is neither prime nor 1, replace *t* by *f*(*t*) and iterate. * The number of iterations is *s*(*n*). The iterative process is guaranteed to end because *f*(*n*) < *n* for all *n*. Consider for example *n*=25. We initiallize *t* = 25. Since this is not a prime nor 1, we compute *f*(25), which is 9. This becomes the new value for *t*. This is not a prime nor 1, so we continue: *f*(9) is 4. We continue again: *f*(4) is 2. Since this is a prime we stop here. We have done 3 iterations (from 25 to 9, then to 4, then to 2). Thus *s*(25) is 3. The first 40 terms of the sequence are as follows. The sequence is not in OEIS. ``` 0 0 0 1 0 1 0 2 2 2 0 1 0 2 2 2 0 1 0 3 3 3 0 3 3 3 3 3 0 3 0 1 1 1 1 1 0 2 2 2 ``` ### Step 2 Given an odd positive integer *N*, build an Nร—N array (matrix) by winding the finite sequence *s*(1), *s*(2), ..., *s*(*N*2) to form a square outward **spiral**. For example, given *N* = 5 the spiral is ``` s(21) s(22) s(23) s(24) s(25) s(20) s(7) s(8) s(9) s(10) s(19) s(6) s(1) s(2) s(11) s(18) s(5) s(4) s(3) s(12) s(17) s(16) s(15) s(14) s(13) ``` or, substituting the values, ``` 3 3 0 3 3 3 0 2 2 2 0 1 0 0 0 1 0 1 0 1 0 2 2 2 0 ``` ### Step 3 Represent the Nร—N array as an **image** with a grey colour map, or with some other colour map of your taste. The map should be gradual, so that the order of numbers corresponds to some visually obvious order of the colours. The test cases below show some example colour maps. # The challenge Given an odd positive integer *N*, produce the image described above. # Rules * The spiral must be outward, but can be clockwise or counter-clockwise, and can start moving right (as in the above example), left, down or up. * The scales of the horizontal and vertical axes need not be the same. Also axis labels, colorbar and similar elements are optional. As long as the spiral can be clearly seen, the image is valid. * Images can be output by any of the [standard means](https://codegolf.meta.stackexchange.com/q/9093/36398). In particular, the image may be displayed on screen, or a graphics file may be produced, or an array of RGB values may be output. If outputting a file or an array, please post an example of what it looks like when displayed. * Input means and format are [flexible as usual](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). A [program or a function can be provided](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * Shortest code in bytes wins. # Test cases The following images (click for full resolution) correspond to several values of *N*. A clock-wise, rightward-first spiral is used, as in the example above. The images also illustrate several valid colour maps. * *N* = 301: [![enter image description here](https://i.stack.imgur.com/Q36t8.png)](https://i.stack.imgur.com/Q36t8.png) * *N* = 501: [![enter image description here](https://i.stack.imgur.com/E3K4B.png)](https://i.stack.imgur.com/E3K4B.png) * *N* = 701: [![enter image description here](https://i.stack.imgur.com/boTIV.png)](https://i.stack.imgur.com/boTIV.png) [Answer] # MATLAB - ~~197~~ ~~185~~ ~~178~~ ~~175~~ ~~184~~ ~~163~~ ~~162~~ ~~148~~ ~~142~~ 140 bytes Shaved 12 bytes, thanks to Ander and Andras, and lots thanks to Luis for putting the two together. Shaved 16 thanks to Remco, 6 thanks to flawr ``` function F(n) p=@primes s=@isprime for a=2:n^2 c=0 if~s(a) b=nnz(p(a)) while~s(b) b=nnz(p(b)) c=c+1 end end d(a)=c end imagesc(d(spiral(n))) ``` Result for `N=301` (`F(301)`): [![enter image description here](https://i.stack.imgur.com/0xTqT.png)](https://i.stack.imgur.com/0xTqT.png) Explanation: ``` function F(n) p=@primes % Handle s=@isprime % Handle for a=2:n^2 % Loop over all numbers c=0 % Set initial count if~s(a) % If not a prime b=nnz(p(a)) % Count primes while~s(b) % Stop if b is a prime. Since the code starts at 2, it never reaches 1 anyway b=nnz(p(b)) % count again c=c+1 % increase count end end d(a)=c % store count end imagesc(d(spiral(n))) % plot ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 124 bytes Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478) for saving 12 bytes! ``` Image[#/Max@#]&[Array[(n=0;Max[4#2#2-Max[+##,3#2-#],4# #-{+##,3#-#2}]+1//.x_?CompositeQ:>PrimePi[++n;x];n)&,{#,#},(1-#)/2]]& ``` [Try it online!](https://tio.run/##NchNC4IwGADgu79CfEGMbX7lKbEPokOHwLqOlxg1bYdNMYOF@NvNiG4Pjxb9Q2rRq5uYqmI6alFLDtFJ2C2gz3ddJ948MEWcz8UzSCFlXxEAupwNSDNwgA2/YJCOSJIoCu11s2902zxVL8@rddkpLUvFCTG5xdwsfDoAhZEGCYNFlCL6k9K1W7gVT@IEnYNtm67n3pxha2qPurPQubwM96y9u//H6QM "Wolfram Language (Mathematica) โ€“ Try It Online") --- The image generated is: ## [Spiral](https://i.stack.imgur.com/07Dg5.png) Closed form formula of the spiral value taken directly from [this answer](https://codegolf.stackexchange.com/a/154458/69850) of mine. [Answer] ## MATLAB: 115 114 110 bytes One liner (run in R2016b+ as [function in script](https://uk.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html)) 115 bytes ``` I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N)));function k=s(n,k);if n>1&~isprime(n);k=s(nnz(primes(n)),k+1);end;end ``` Putting the function in a separate file, as suggested by flawr, and using the [1 additional byte per additional file](https://codegolf.meta.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934#4934) rule In the file `s.m`, 64 + 1 bytes for code + file ``` function k=s(n,k);if n>1&~isprime(n);k=s(nnz(primes(n)),k+1);end ``` Command window to define `I`, 45 bytes ``` I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N))) ``` **Total: 110 bytes** --- This uses recursion instead of `while` looping like the other MATLAB implementations do ([gnovice](https://codegolf.stackexchange.com/a/154490/73727), [Adriaan](https://codegolf.stackexchange.com/a/154467/73727)). Run it as a script (in R2016b or newer), this defines the function `I` which can be run like `I(n)`. Structured version: ``` % Anonymous function for use, i.e. I(301) % Uses arrayfun to avoid for loop, spiral to create spiral! I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N))); % Function for recursively calculating the s(n) value function k=s(n,k) % Condition for re-iterating. Otherwise return k unchanged if n>1 && ~isprime(n) % Increment k and re-iterate k = s( nnz(primes(n)), k+1 ); end end ``` Example: ``` I(301) ``` [![plot](https://i.stack.imgur.com/C4tkg.png)](https://i.stack.imgur.com/C4tkg.png) Notes: * I tried to make the `s` function anonymous too, of course that would reduce the count significantly. However, there are 2 issues: 1. Infinite recursion is hard to avoid when using anonymous functions, as MATLAB doesn't have a ternary operator to offer a break condition. Bodging a ternary operator of sorts (see below) also costs bytes as we need the condition twice. 2. You have to pass an anonymous function to itself if it is recursive (see [here](https://stackoverflow.com/questions/36310676/is-it-possible-to-have-a-recursive-anonymous-function-in-matlab)) which adds bytes.The closest I came to this used the following lines, perhaps it can be changed to work: ``` % Condition, since we need to use it twice c=@(n)n>1&&~isprime(n); % This uses a bodged ternary operator, multiplying the two possible outputs by % c(n) and ~c(n) and adding to return effectively only one of them % An attempt was made to use &&'s short-circuiting to avoid infinite recursion % but this doesn't seem to work! S=@(S,n,k)~c(n)*k+c(n)&&S(S,nnz(primes(n)),k+1); ``` [Answer] ## MATLAB - 126 121\* bytes I attempted a more vectorized approach than [Adriaan](https://codegolf.stackexchange.com/a/154467/38867) and was able to shave more bytes off. Here's the single-line solution: ``` function t(n),M=1:n^2;c=0;i=1;s=@isprime;v=cumsum(s(M));while any(i),i=M>1&~s(M);c=c+i;M(i)=v(M(i));end;imagesc(c(spiral(n))) ``` And here's the nicely-formatted solution: ``` function t(n), M = 1:n^2; c = 0; i = 1; s = @isprime; v = cumsum(s(M)); while any(i), % *See below i = M > 1 & ~s(M); c = c+i; M(i) = v(M(i)); end; imagesc(c(spiral(n))) ``` \**Note: if you're willing to allow a metric crapton of unnecessary iterations, you can change the line* `while any(i),` *to* `for m=v,` *and save 5 bytes.* [Answer] # Dyalog APL, 94 bytes ``` 'P2' 2โดnโ†โŽ• 9 (โช0){ร—โ‰ขโต:(โ‰ขโบ)((โ‰โˆ˜โŒฝโบ,โ†‘)โˆ‡โ†“)โตโ‹„โบ}2โ†“{โตโŒŠ1+โต[+\p]}โฃโ‰ก9ร—~pโ†1=โŠƒ+/(โ‰ โจ,โ‰ โจ,~โดโจ(ร—โจn)-2ร—โ‰ข)ยจ,\ร—โณn ``` assumes `โŽ•IO=0` output for n=701 (converted from .pgm to .png): [![enter image description here](https://i.stack.imgur.com/yPUKm.png)](https://i.stack.imgur.com/yPUKm.png) [Answer] # Python 3, ~~299~~ 265 bytes Saved 5 bytes thanks to formatting suggestions from Jonathan Frech and NoOneIsHere. Removed an additional 34 bytes by removing a function definition that was only called once. This is a little longer than some others, due to python not having a command to determine primeness, or spiral an array. It runs relatively quickly however, around a minute for `n = 700`. ``` from pylab import* def S(n): q=arange(n*n+1);t=ones_like(q) for i in q[2:]:t[2*i::i]=0 c=lambda i:0 if t[i]else 1+c(sum(t[2:i]));S=[c(x)for x in q] t=r_[[[S[1]]]] while any(array(t.shape)<n):m=t.shape;i=multiply(*m)+1;t=vstack([S[i:i+m[0]],rot90(t)]) return t ``` Test it with ``` n = 7 x = S(n) imshow(x, interpolation='none') colorbar() show(block=False) ``` [Answer] # J, 121 Bytes ``` load 'viewmat' a=:3 :'viewmat{:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0(,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1' ``` Defines a function: ``` a=:3 :'viewmat{:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0(,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1' | Full fuction (,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1 | Creates the number spiral {:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0 | Applies S(n) to each element viewmat | View the array as an image ``` [Answer] # R, 231 bytes ``` function(n){p=function(n)sum(!n%%2:n)<2;M=matrix(0,n,n);M[n^2%/%2+cumsum(c(1,head(rep(rep(c(1,-n,-1,n),l=2*n-1),rev(n-seq(n*2-1)%/%2)),-1)))]=sapply(1:(n^2),function(x){y=0;while(x>2&!p(x)){x=sum(sapply(2:x,p));y=y+1};y});image(M)} ``` Slightly less golfed: ``` function(n){ p=function(n)sum(!n%%2:n)<2 #"is.prime" function M=matrix(0,n,n) #empty matrix indices=n^2%/%2+cumsum(c(1,head(rep(rep(c(1,-n,-1,n),l=2*n-1),rev(n-seq(n*2-1)%/%2)),-1))) values=sapply(1:(n^2),function(x){ y=0 while(x>2&!p(x)){ x=sum(sapply(2:x,p)) y=y+1 } y}) M[indices]=values image(M) #Plotting } ``` Anonymous function. Output in a graphic window. Scale is on the red-scale with darkest shade equals to 0 and clearer shades increasing values. Result for n=101: [![n=101](https://i.stack.imgur.com/gKMeb.png)](https://i.stack.imgur.com/gKMeb.png) ]
[Question] [ Duodyadic tiles are kinds of square [function blocks](http://en.wikipedia.org/wiki/Function_block_diagram) that take two inputs, one from their top side and one from their left side, and have two outputs, one on their right side and one on their bottom side. Each of their outputs is a separate function of both of their inputs. For example, if `#` represents a generic tile, the right output `R` is a function `f` of inputs `T` and `L`, and the bottom output `B` is another function `g` of `T` and `L`: ``` T L#R R = f(T, L) B B = g(T, L) ``` (The tiles are termed "duo" since there are two functions, and "dyadic" since both functions [have two arguments](http://www.thefreedictionary.com/dyadic+function).) Tiles can then be composed together on a grid, the outputs of one tile going directly into the inputs of the tiles it neighbors. Here for example, the right output of the left `#` goes into the left input of the right `#`: ``` AB D = f(f(A, C), B) C##D E = g(A, C) EF F = g(f(A, C), B) ``` You can imagine that given a set of duodyadic tiles, each with specific functionality, complex (and potentially useful) compositions could be made. In this challenge, we'll only be concerned with the traditional set of ten [logic based](http://en.wikipedia.org/wiki/Logic_gate) duodyadic tiles, where all the inputs and outputs are single-bit binary numbers (zeros or ones). We'll use a separate ASCII character to denote each type of tile. The tile characters and their input-output relations are as follows: (`T` is for top input, `L` for left input, `R` for right output, `B` for bottom output.) 1. Zero: `0` or (space) โ†’ `R = 0`, `B = 0` 2. One: `1` โ†’ `R = 1`, `B = 1` 3. Cross: `+` โ†’ `R = L`, `B = T` 4. Mirror: `\` โ†’ `R = T`, `B = L` 5. Top only: `U` โ†’ `R = T`, `B = T` 6. Left only: `)` โ†’ `R = L`, `B = L` 7. Not: `!` โ†’ `R = not L`, `B = not T` 8. And: `&` โ†’ `R = L and T`, `B = L and T` 9. Or: `|` โ†’ `R = L or T`, `B = L or T` 10. Xor: `^` โ†’ `R = L xor T`, `B = L xor T` # Challenge Write a program or function that takes in a rectangular grid of the characters `0 1+\U)!&|^` that represents a "circuit" made using the ten logic based duodyadic tiles. You also need to take in two strings of `0`'s and `1`'s; one will be the left input column and one will be the top input row. Your program/function needs to print/return the bottom output row and the right output column (also in `0`'s and `1`'s). For example, in this grid ``` +++ +++ ``` all the inputs flow straight across the grid to the outputs ``` ABC D+++D E+++E ABC ``` so an input of `010`/`01` would have output `010`/`01`: ``` 010 0+++0 1+++1 010 ``` The exact output of your program would be `[bottom output row]\n[right output column]` or `[bottom output row]/[right output column]`: ``` 010 01 ``` or ``` 010/01 ``` If you wrote a function, you could return the two strings in a tuple or list (or still print them). # Details * Take the three inputs as strings in any reasonable manner (preferably in the order grid, top row, left column): command line, text file, sdtin, function arg. * You can assume the input row and column lengths will match the grid dimensions and will only contain `0`'s and `1`'s. * Your grid must use the proper characters (`0 1+\U)!&|^`). Remember that `0` and mean the same thing. # Test Cases (Read I/O as `top`/`left` โ†’ `bottom`/`right`.) **Nand:** ``` &! ``` `00`/`0` โ†’ `01`/`1` `00`/`1` โ†’ `01`/`1` `10`/`0` โ†’ `01`/`1` `10`/`1` โ†’ `11`/`0` **All ones:** ``` 1111 1\+\ 1+\+ 1\+\ ``` Any input should result in `1111`/`1111`. [**Xor from Nand:**](http://en.wikipedia.org/wiki/NAND_logic) (note the column of trailing spaces) ``` \)+\ U&!& +! ! \&!& ! ``` `00000`/`00000` โ†’ `00000`/`00000` `00000`/`10000` โ†’ `00010`/`00000` `10000`/`00000` โ†’ `00010`/`00000` `10000`/`10000` โ†’ `00000`/`00000` **Zig zag:** ``` +++\00000000 000\!!!!\000 00000000\+++ ``` The first bit of the left input becomes the last bit of the right output. Everything else is `0`. `000000000000`/`000` โ†’ `000000000000`/`000` `000000000000`/`100` โ†’ `000000000000`/`001` **Propagation:** ``` ))) UUU U+U U+U UUU ``` The first bit of the left input goes to all the outputs. `000`/`00000` โ†’ `000`/`00000` `000`/`10000` โ†’ `111`/`11111` [**Here's a pastebin of all 1ร—1 grid test cases.**](http://pastebin.com/rLrwkBsV) # Scoring The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. Bonus: What cool "circuits" can you make? P.S. Don't bother Googling "duodyadic tiles". I made them up yesterday ;D If you want to discuss expanding this idea into a full-fledged programming language, come to [this chatroom](http://chat.stackexchange.com/rooms/22148/expanding-duodyadic-tiles). [Answer] # Pyth, 122 Kind of a monster. Uses simply recursion, nothing fancy like dynamic programming. ``` D:NGHR@Cm+d[1HG&GH|GHxGH0),[GH!G)[HG!H)x"+\\!1U)&|^"N#aYw)M:@@YGH?hgGtHHv@eYG?egtGHGv@ePYHjkm+0egtleYklePYjkm+0hgbtlePYleY ``` [Online demonstration](https://pyth.herokuapp.com/?code=D%3ANGHR%40Cm%2Bd%5B1HG%26GH%7CGHxGH0)%2C%5BGH!G)%5BHG!H)x%22%2B%5C%5C!1U)%26%7C%5E%22N%23aYw)M%3A%40%40YGH%3FhgGtHHv%40eYG%3FegtGHGv%40ePYHjkm%2B0egtleYklePYjkm%2B0hgbtlePYleY&input=%2B%2B%2B%5C00000000%0A000%5C!!!!%5C000%0A00000000%5C%2B%2B%2B%0A000000000000%0A100&debug=0). Input is in the following way: First the grid (no escaping, no extra symbols) and then the two lines of input, e.g. (Zig zag) ``` +++\00000000 000\!!!!\000 00000000\+++ 000000000000 100 ``` [Answer] # Mathematica, ~~331~~ ~~276~~ ~~270~~ ~~267~~ ~~264~~ ~~262~~ ~~252~~ 250 bytes ``` Print@@@{#[[2;;,-1,2]],#[[-1,2;;,1]]}&@MapIndexed[h=Characters;({r@#2,b@#2}=<|##|>&@@Thread[h@"0 1+\\)U!&|^"->{0,0,1,i={##},{#2,#},##,1-i,1##,Max@i,(#-#2)^2}]&[r[#2-{1,0}],b[#2-{0,1}]]@#{1,1})&,Join[h@{"0"<>#3},h@StringSplit[#2<>" "<>#," "]๏‡],{2}]& ``` The `๏‡` is a private-use Unicode character which Mathematica uses as a superscript `T`, i.e. it's the transposition operator. Here is a more readable version: ``` Print @@@ {#[[2 ;;, -1, 2]], #[[-1, 2 ;;, 1]]} &@ MapIndexed[h = Characters; ( {r@#2, b@#2} = <|##|> & @@ Thread[ h@"0 1+\\)U!&|^" -> { 0, 0, 1, i = {##}, {#2, #}, ##, 1 - i, 1 ##, Max@i, (# - #2)^2 }] & [ r[#2 - {1, 0}], b[#2 - {0, 1}] ] @ # {1, 1} ) &, Join[ h@{"0" <> #3}, h@StringSplit[#2 <> "\n" <> #, "\n"]\[Transpose] ], {2}] & ``` This is an unnamed function which takes the three strings for grid, top and left inputs and prints the bottom and right outputs. ## Explanation Let's go through this step by step (I'll try not to assume any Mathematica knowledge). You sort of need to read the code back to front. The basic algorithm just sweeps through the lines computing each function and storing the results in `f` to be accessed by subsequent tiles. ### Input processing That's this bit: ``` Join[ h@{"0" <> #3}, h@StringSplit[#2 <> "\n" <> #, "\n"]\[Transpose] ] ``` This merely splits the grid into a nested list of characters (note that I defined `h` as an alias for `Character` somewhere in the code) and then prepends a row and a column with the inputs. This works, because `1` and `0` are also the names of the constant-function tiles, so actually putting them on the has the same effect as feeding the inputs in manually. Since these are functions they will technically take their input from outside the grid, but since they are constant functions that doesn't matter. The top left corner gets a `0` but this is fairly arbitrary since the results of that tile are never used. Also note the transposition. Adding columns takes more characters than adding rows, so I transpose the grid after adding the top row. This means that top/bottom and left/right are swapped for the main part of the program, but they're completely exchangeable so it doesn't matter. I just need to make sure to return the results in the correct order. ### Solving the grid *(This section is slightly outdated. Will fix once I'm really sure I'm done golfing.)* Next up, we run `MapIndexed` over the inner level of this nested list. This calls the anonymous function provided as the first argument for each character in the grid, *also* giving it a list with the current two coordinates. The grid is traversed in order, so we can safely calculate each cell based on the previous ones. We use the variables `r`(ight) and `b`(ottom) as lookup tables for the results of each cell. Our anonymous function has the current coordinates in `#2`, so we get the inputs to any cell with ``` r[#2 - {1, 0}], b[#2 - {0, 1}] ``` Note that in the first row and column this will access undefined values of `r` and `b`. Mathematica doesn't really have a problem with that and will just give you back your coordinates instead, but we discard this result anyway, since all tiles in that row/column are constant functions. Now this thing: ``` <|##|> & @@ Thread[ h@"0 1+\\U)!&|^" -> { z = {0, 0}, z, o = 1 + z, {##}, ... }] & ``` Is a golfed form of ``` <|"0" -> (z = {0, 0}), " " -> z, "1" -> (o = 1 + z), "+" -> {##}, ... |> & ``` Which in turn is a function which, given the two tile inputs, returns an Association (you'd call it a hashmap or a table in other languages), that contains all the possible tile results for these two inputs. To understand, how all the functions are implemented, you need to know that the first argument of such a function can be accessed with `#` and the second with `#2`. Furthermore, `##` gives you a sequence of both arguments which can be used to "splat" the arguments. * `0`: is straightforward, we just return a constant `{0, 0}` and also assign this to `z` for future use (e.g. in the space tile). * `1`: is essentially just `{1,1}`, but having `z` this is shortened to `1+z`. We also save this in `o`, because it'll come in handy for all the tiles where both outputs are identical. * `+`: Here we make use of the sequence. `{##}` is the same as `{#,#2}` and passes both inputs through unchanged. * `\`: We swap the two arguments, `{#2,#}`. * `U`: Now we can make use of `o`. `o#2` means `{1,1}*#2` so we just put the top argument into both outputs. * `)`: Analogously for the left argument: `o#`. * `!`: Bitwise not is annoying in Mathematica, but since we only ever have `0` and `1`, we can simply subtract both inputs from `1` (thereby inverting them) and pass them on: `1-{##}`. * `&`: This one is quite nifty. First we notice that bitwise and for `0` and `1` is identical to multiplication. Furthermore, `o##` is the same as `o*#*#2`. * `|`: Again, we use an equivalent function. Bitwise or is the same as `Max` in this case, so we apply `Max` to the input arguments and multiply the result into `{1,1}`. * `^`: The shortest I've found for xor is to take the difference and square it (to ensure positivity), so we've got `o(#-#2)^2`. After this function completes and returns the full association we use the current cell's character to pull out the element we're interested in and store it in `r` and `b`. Note that this is also the return value of the anonymous function used in `MapIndexed`, so the mapping will actually give me a grid of all the results. ### Output processing `MapIndexed` returns a 3D grid, where the first dimension corresponds to the horizontal grid coordinate (remember the earlier transposition), the second dimension corresponds to the vertical grid coordinate and the third indicates whether we've got a bottom or a left output. Note that this also contains the input row and column which we need to get rid of. So we access the bottom row's bottom output with ``` #[[2;;,-1,2]] ``` and the final column's right output with ``` #[[-1,2;;,1]] ``` Note that `2;;` is a range from the second to the last element. Lastly, we apply `Print` to both of those (using `@@@` as the syntactic sugar for second-level `Apply`), which just prints all of its arguments back-to-back (and since it's applied to two separate expressions, there will be a newline between bottom and right output). [Answer] # C, ~~332~~ ~~309~~ ~~272~~ ~~270~~ ~~266~~ ~~259~~ ~~247~~ 225 bytes ``` #define C(x)*c-x? i,k,T,L,m;f(c,t,l)char*c,*t,*l;{while(L=l[i]){for(k=0;T=t[k];c++)L=C(49)C(43)C(92)C(85)C(41)C(33)C(38)C('|')C(94)T=48:(T^=L-48):(T|=L):(T&=L):(T^=1,L^1):(T=L):T:(m=T,T=L,m):L:(T=49),t[k++]=T;c++;l[i++]=L;}} ``` View results online [here!](http://ideone.com/fJz1Pw "ideone C") This defines a function `void f(char*, char*, char*)`, which should take the board as its first input, then the top row of input, and then the left row of input. Here's what I used to test it: ``` #include "stdio.h" int main() { char buf[1024],top[33],left[33]; /* Copy and paste an example circuit as the first input, and put a 'Q' immediately after it. Note that the Q is never touched by the function f, and is used solely as a delimiter for input. */ scanf("%[^Q]Q ",buf); /* Then enter your top inputs */ scanf("%[01]%*[^01]", top); /* Then your left ones */ scanf("%[01]", left); /* OUTPUT: Bottom\nRight */ f(buf, top, left); return 0; } ``` Thus, by inputting Sp3000's 2-bit multiplier: ``` UUUU)))) UU++)))& UUU+) U UU++&))U U++&+)^U U)&\&)UU U+^UU \&UUUQ 11110000 00000000 ``` We get: ``` 00001001 11111111 ``` ~~On another note, with Sp3000's half adder in mind, I'd like to see a full adder...~~ [One](https://codegolf.stackexchange.com/a/48025/31054 "Full Adder Answer") of you guys did it! I don't think the system stands on its own as a programming language, but it's been very interesting. This seems like an excellent target for metagolf, though! # A Short Explanation: Here's the unraveled, commented code: ``` /* We define the first half of the ?: conditional operator because, well, it appears over and over again. */ #define C(x)*c-x? /* i,k are counting variables T,L are *current* top and left inputs */ i,k,T,L,m; f(c,t,l)char*c,*t,*l;{ /* The outer loop iterates from top to bottom over l and c */ while(L=l[i]){ /* Inner loop iterates from left to right over t and c */ for(k=0;T=t[k];c++) /* This line looks awful, but it's just a bunch of character comparisons, and sets T and L to the output of the current c */ L=C(49)C(43)C(92)C(85)C(41)C(33)C(38)C('|')C(94)T=48:(T^=L-48):(T|=L):(T&=L):(T^=1,L^1):(T=L):T:(m=T,T=L,m):L:(T=49), /* Write our output to our input, it will be used for the next row */ t[k++]=T; c++; /*Absorbs the newline at the end of every row */ /* Keep track of our right-most outputs, and store them in the handy string passed to the function. */ l[i++]=L; } /* Bottom output is now stored entirely in t, as is right output in l */ } ``` We iterate over `c`, left to right (then top to bottom), rewriting the `t` inputs each time and pushing out a right-most output which is shoved into the `l` string. We can imagine this as replacing the top row of `c` with `1`'s and `0`'s iteratively, and keeping track of the bits that are pushed out at the right. Here's a more visual sequence, row by row: ``` 111 1&+^ => 110 ->0 => ->0 => 0 Thus, "01" has been written to l, 1+&+ 1+&+ 110 ->1 1 110 And "110" is stored currently in t. ``` This obviously gets more complicated with different symbols and sizes, but the central idea holds. This works only because data never flows up or left. [Answer] # Python 2, 316 bytes This function builds 10 tile lambda functions, then iterates though the grid, updating logic states. The final vertical and horizontal logic states are then printed. ``` def b(d,j,g): h=enumerate;e=dict((s[0],eval('lambda T,L:('+s[1:]+')'))for s in' 0,0#00,0#11,1#+L,T#\\T,L#UT,T#)L,L#!1-L,1-T#&T&L,T&L#|T|L,T|L#^T^L,T^L'.split('#'));j=list(j+'\n');g=list(g) for y,k in h(d.split('\n')): L=g[y] for x,c in h(k):T=j[x];L,B=e[c](int(T),int(L));j[x]=`B` g[y]=`L` print''.join(j+g) ``` The ungolfed code including tests: ``` def logic(grid, top, left): loop = enumerate; func = dict((s[0], eval('lambda T,L:('+s[1:]+')')) for s in ' 0,0#00,0#11,1#+L,T#\\T,L#UT,T#)L,L#!1-L,1-T#&T&L,T&L#|T|L,T|L#^T^L,T^L'.split('#')); top = list(top+'\n'); left = list(left) for y,row in loop(grid.split('\n')): L = left[y] for x,cell in loop(row) : T = top[x]; L, B = func[cell](int(T), int(L)); top[x] = `B` left[y] = `L` print ''.join(top + left) import re testset = open('test.txt', 'rt').read().strip() for test in testset.split('\n\n'): if test.endswith(':'): print '------------------\n'+test elif re.match('^[01/\n]+$', test, re.S): for run in test.split(): top, left = run.split('/') print 'test', top, left logic(grid, top, left) else: grid = test ``` The `test.txt` file (including 2 other tests by Sp3000): ``` Nand: &! 00/0 00/1 10/0 10/1 All ones: 1111 1\+\ 1+\+ 1\+\ 1001/1100 Xor from Nand (note the column of trailing spaces): \)+\ U&!& +! ! \&!& ! 00000/00000 00000/10000 10000/00000 10000/10000 Half adder: +)) U&+ U+^ 000/000 000/100 100/000 100/100 Right shift: \\\ \++ \++ 001/110 010/101 101/100 ``` The test output: ``` ------------------ Nand: test 00 0 01 1 test 00 1 01 1 test 10 0 01 1 test 10 1 11 0 ------------------ All ones: test 1001 1100 1111 1111 ------------------ Xor from Nand (note the column of trailing spaces): test 00000 00000 00000 00000 test 00000 10000 00010 00000 test 10000 00000 00010 00000 test 10000 10000 00000 00000 ------------------ Half adder: test 000 000 000 000 test 000 100 001 101 test 100 000 101 001 test 100 100 110 110 ------------------ Right shift: test 001 110 000 111 test 010 101 101 010 test 101 100 010 110 ``` [Answer] # Python 2, ~~384~~ ~~338~~ 325 bytes ``` def f(G,T,L): def g(x,y): if x>-1<y:l=g(x-1,y)[1];t=g(x,y-1)[0];r=l,t,1-l,0,0,1,t,l,l&t,l|t,l^t;i="+\\!0 1U)&|^".index(G[y*-~W+x]);return((t,l,1-t)+r[3:])[i],r[i] return(int((y<0)*T[x]or L[y]),)*2 H=G.count("\n")+1;W=len(G)/H;return eval('"".join(map(str,[g(%s]for _ in range(%s)])),'*2%('_,H-1)[0','W','W-1,_)[1','H')) ``` Seriously CH, if this isn't a toy already you should start ringing up some toy factories. More golfed and much less efficient now, but still haven't caught up to CarpetPython. Input like `f("1111\n1\\+\\\n1+\\+\n1\\+\\","0101","1010")`, output is a tuple of two strings. Make sure the board doesn't have a trailing newline though, which will break things. ## Test program ``` def f(G,T,L): def g(x,y): if x>-1<y:l=g(x-1,y)[1];t=g(x,y-1)[0];r=l,t,1-l,0,0,1,t,l,l&t,l|t,l^t;i="+\\!0 1U)&|^".index(G[y*-~W+x]);return((t,l,1-t)+r[3:])[i],r[i] return(int((y<0)*T[x]or L[y]),)*2 H=G.count("\n")+1;W=len(G)/H;return eval('"".join(map(str,[g(%s]for _ in range(%s)])),'*2%('_,H-1)[0','W','W-1,_)[1','H')) import itertools G = r""" +)) U&+ U+^ """.strip("\n") def test(T, L): print f(G, T, L) def test_all(): W = len(G[0]) H = len(G) for T in itertools.product([0, 1], repeat=len(G.split("\n")[0])): T = "".join(map(str, T)) for L in itertools.product([0, 1], repeat=len(G.split("\n"))): L = "".join(map(str, L)) print "[T = %s; L = %s]" % (T, L) test(T, L) print "" test("000", "000") test("000", "100") test("100", "000") test("100", "100") ``` You can also test all possible cases with `test_all()`. ## Extra test cases ### Half adder Here's a half adder which adds the top left bits, outputting `<input bit> <carry> <sum>`: ``` +)) U&+ U+^ ``` Tests: ``` 000 / 000 -> 000 / 000 000 / 100 -> 001 / 101 100 / 000 -> 101 / 001 100 / 100 -> 110 / 110 ``` Output should be the same even if the second/third bits of the inputs are changed. ### Right shift Given `abc / def`, this outputs `fab / cde`: ``` \\\ \++ \++ ``` Tests: ``` 001 / 110 -> 000 / 111 010 / 101 -> 101 / 010 101 / 100 -> 010 / 110 ``` ### 3-bit sorter Sorts the first three bits of top into the last three bits of bottom. Right output is junk. ``` UUU))) UU)U U U&UU U U+|&)U \UU++| \)&UU \+|U UUU ``` Tests: ``` 000000 / 00000000 -> 000000 / 00000000 001000 / 00000000 -> 000001 / 11111111 010000 / 00000000 -> 000001 / 00001111 011000 / 00000000 -> 000011 / 11111111 100000 / 00000000 -> 000001 / 00001111 101000 / 00000000 -> 000011 / 11111111 110000 / 00000000 -> 000011 / 00001111 111000 / 00000000 -> 000111 / 11111111 ``` ### 2-bit by 2-bit multiplier Takes the 1st/2nd bits of top as the first number, and the 3rd/4th bits of top as the second number. Outputs to the last four bits of bottom. Right output is junk. ``` UUUU)))) UU++)))& UUU+) U UU++&))U U++&+)^U U)&\&)UU U+^UU \&UUU ``` *Edit: Golfed out a column and two rows.* Tests: ``` 00000000 / 00000000 -> 00000000 / 00000000 00010000 / 00000000 -> 00000000 / 10000000 00100000 / 00000000 -> 00000000 / 00000000 00110000 / 00000000 -> 00000000 / 10000000 01000000 / 00000000 -> 00000000 / 00000000 01010000 / 00000000 -> 00000001 / 11111111 01100000 / 00000000 -> 00000010 / 00000000 01110000 / 00000000 -> 00000011 / 11111111 10000000 / 00000000 -> 00000000 / 00000000 10010000 / 00000000 -> 00000010 / 10000000 10100000 / 00000000 -> 00000100 / 00000000 10110000 / 00000000 -> 00000110 / 10000000 11000000 / 00000000 -> 00000000 / 00000000 11010000 / 00000000 -> 00000011 / 11111111 11100000 / 00000000 -> 00000110 / 00000000 11110000 / 00000000 -> 00001001 / 11111111 ``` [Answer] # R, ~~524~~ 517 Probably lots of room to reduce this at the moment, but this has been really interesting to do. There are two functions. Function d is the worker and f is the comparer. The function d is called with 3 strings, Gates, Top and Left. The Gates are put into a matrix determined by the width. ``` I=strtoi;S=strsplit;m=matrix;f=function(L,T,G){O=I(c(0,1,L,T,!L,!T,L&T,L|T,xor(L,T)));X=which(S(' 01+\\U)!&|^','')[[1]]==G);M=m(c(1,1,1,2,1,1,3,2,2,4,3,4,5,4,3,6,4,4,7,3,3,8,5,6,9,7,7,10,8,8,11,9,9),nrow=3);return(c(O[M[2,X]],O[M[3,X]]))};d=function(G,U,L){W=nchar(U);H=nchar(L);U=c(list(I(S(U,'')[[1]])),rep(NA,H));L=c(list(I(S(L,'')[[1]])),rep(NA,W));G=m((S(G,'')[[1]]),nrow=W);for(i in 1:H)for(n in 1:W){X=f(L[[n]][i],U[[i]][n],G[n,i]);L[[n+1]][i]=X[1];U[[i+1]][n]=X[2]};cat(U[[H+1]],' / ',L[[W+1]],sep='',fill=T)} ``` Formatted a bit ``` I=strtoi;S=strsplit;m=matrix; f=function(L,T,G){ O=I(c(0,1,L,T,!L,!T,L&T,L|T,xor(L,T))); X=which(S(' 01+\\U)!&|^','')[[1]]==G); M=m(c(1,1,1,2,1,1,3,2,2,4,3,4,5,4,3,6,4,4,7,3,3,8,5,6,9,7,7,10,8,8,11,9,9),nrow=3); return(c(O[M[2,X]],O[M[3,X]])) }; d=function(G,U,L){ W=nchar(U);H=nchar(L); U=c(list(I(S(U,'')[[1]])),rep(NA,H)); L=c(list(I(S(L,'')[[1]])),rep(NA,W)); G=m((S(G,'')[[1]]),nrow=W); for(i in 1:H) for(n in 1:W){ X=f(L[[n]][i],U[[i]][n],G[n,i]); L[[n+1]][i]=X[1]; U[[i+1]][n]=X[2] }; cat(U[[H+1]],' / ',L[[W+1]],sep='',fill=T) } ``` Some tests ``` > d('&!','00','0') 01 / 1 > d('&!','00','1') 01 / 1 > d('&!','10','0') 01 / 1 > d('&!','10','1') 11 / 0 > d('\\)+\\ U&!& +! ! \\&!& ! ','00000','00000') 00000 / 00000 > d('\\)+\\ U&!& +! ! \\&!& ! ','00000','10000') 00010 / 00000 > d('\\)+\\ U&!& +! ! \\&!& ! ','10000','00000') 00010 / 00000 > d('\\)+\\ U&!& +! ! \\&!& ! ','10000','10000') 00000 / 00000 > d('+++\\00000000000\\!!!!\\00000000000\\+++','000000000000','100') 000000000000 / 001 > d('+++\\00000000000\\!!!!\\00000000000\\+++','000000000000','000') 000000000000 / 000 > d('+))U&+U+^','000','000') 000 / 000 > d('+))U&+U+^','000','100') 001 / 101 > d('+))U&+U+^','100','000') 101 / 001 > d('+))U&+U+^','100','100') 110 / 110 ``` ]
[Question] [ # Perfect License Plates Starting a few years ago, I made myself a little game while driving around: checking if nearby license plates are "perfect". It's relatively rare, but exciting when you find one. To check if a license plate is perfect: 1. Sum up the characters, with A = 1, B = 2, ... Z = 26. 2. Take each consecutive chunk of numerals, and sum them; multiply each of these sums together. If the values in part 1 and part 2 are equal, congratulations! You've found a perfect license plate! ### Examples ``` License plate: AB3C4F Digits -> 3 * 4 = 12 Chars -> A + B + C + F = 1 + 2 + 3 + 6 = 12 12 == 12 -> perfect! License plate: G34Z7T Digits -> (3 + 4) * 7 = 49 Chars -> G + Z + T = 7 + 26 + 20 = 53 49 != 53 -> not perfect! License plate: 10G61 Digits -> (1 + 0) * (6 + 1) = 7 Chars -> G = 7 7 == 7 -> perfect! ``` ## The Challenge I used license plates of length 5 and 6 as examples, but this procedure is valid for any plate length. Your challenge is, for a given length N, return the number of perfect license plates of that length. For the purposes of the challenge, a valid license plate is any combination of digits 0-9 and characters A-Z. The plate must contain *both a character and a numeral* to be considered potentially perfect. For checking purposes, here are the values I got (though I can't be 100% about their correctness, hahaha) ``` N < 2: 0 N = 2: 18 N = 3: 355 N = 4: 8012 ``` ### Notes If somehow it makes the problem simpler in your language, you may output the **proportion** of perfect license plates for a given N, to at least 2 significant digits. ``` N < 2: 0 N = 2: 0.0138888... N = 3: 0.0076088... N = 4: 0.0047701... ``` OR, you may output the equivalent value **mod 256** ``` N < 2: 0 N = 2: 18 N = 3: 99 N = 4: 76 ``` Shortest wins! [Answer] # Python 3.6, 150 bytes ``` f=lambda n,t=-1,p=-1,a=0:sum(f(n-1,*((t,c+p*(p>=0),a),((t<0 or t)*(p<0 or p),-1,a-c))[c<0])for c in range(-26,10))if n else 0<(t<0 or t)*(p<0 or p)==a ``` results: ``` f(2) = 18 f(3) = 355 f(4) = 8012 f(5) = 218153 ``` Ungolfed version with explanation: ``` digits=[*range(10)] letters=[*range(1,27)] def f(n, dt=-1, dp=-1, lt=0): if n: for d in digits: yield from f(n - 1, dt, d if dp < 0 else dp + d, lt ) for l in letters: yield from f(n - 1, dp if dt < 0 else dt if dp < 0 else dt*dp, -1, lt + l ) else: yield 0 < lt == (dt<0 or dt)*(dp<0 or dp) ``` The problem boils down to searching a tree in which each level of the tree corresponds to a position in a license plate number and each node has 36 children (10 digits and 26 letters). The function does a recursive search of the tree, accumulating the values for the digits and letters as it goes. ``` n is the number of levels to search. dp accumulates the sum of a group of digits. dt accumulates the product of the digit sums. lt accumulates the sum of the letter values. For dp and dt, a value < 0 indicates it is not initialized. ``` Golf included, converting the for loops to sums of generators: ``` sum(f(n-1, dt, d if dp < 0 else dp + d, lt) for d in digits) + sum(f(n-1, dp if dt<0 else dt if dp<0 else dt*dp, -1, lt+l) for l in letters) ``` Then combining the generators. Encode letters, A to Z, as -1 to -26 and digits as 0 to 9. So the sum becomes: ``` sum(f(n-1, *args) for c in range(-26, 10)), ``` where args is: ``` ((dp if dt<0 else dt if dp<0 else dt*dp, -1, lt-l) if c <0 else (dt, d if dp<0 else dp+d, lt)) ``` The rest of the golfing is converting the function to a lambda, shortening variable names, and simplifying expressions. [Answer] # Dyalog APL, ~~57~~ 56 bytes ``` +/(+/0โŒˆa-9)=ร—/c*โจ-2-/0,โŒˆ\(+\aร—b)ร—cโ†2>/0,โจbโ†9โ‰ฅaโ†โ†‘1โ†“,โณโŽ•โด36 ``` (assumes `โŽ•ioโ†0`) `a` matrix of all valid licence plates (except `00...0`) encoded with: 0-9 for digits, 10-35 for letters `b` bitmask for where digits occur `c` bitmask for the last digit in every group of consecutive digits [Answer] # Python 2, ~~359~~ 295 bytes Rather long; this is the trivial solution. I'm confident this is correct, though it does not match the test cases in the challenge. The solutions I'm getting match Dada's answers. ``` import itertools as i,re as r,string as s print len([''.join(x)for x in i.product(s.lowercase+s.digits,repeat=input())if(lambda t:r.search('\\D',t)and r.search('\\d',t)and reduce(int.__mul__,[sum(map(int,k))for k in r.split('\\D+',t)if k])==sum([k-96 for k in map(ord,t) if k>96]))(''.join(x))]) ``` -64 bytes thanks to suggestions from @numbermaniac [Answer] # [Python 2](https://docs.python.org/2/), ~~291~~ ~~287~~ ~~276~~ 273 bytes ``` lambda n:sum(1for x in s.product(y+z,repeat=n)if(lambda p,s=set:reduce(int.__mul__,[sum(map(int,i))for i in re.findall(r"\d+",p)],1)==sum(ord(i)-64for i in p if ord(i)>64)and s(p)&s(y)and s(p)&s(z))(''.join(x))) import re,itertools as s,string as t y=t.uppercase z=t.digits ``` [Try it online!](https://tio.run/nexus/python2#TY7BasMwEETv/gqRQ6MlqiGQ5mBQf6QpRo0ks8WWFu0aYv@8a9HS9rYzzLydaG/b6KYP71TqeJ70OeaiHgqT4pZK9vNd9HJaTQkUnNgEGPVPgQxbDtKVsKeCxiRt30/z2PfmraImR9U0CFChWKEltBGTd@Ooy@HmTwdD8G7OYG1t5OI1wvP18psnhVF926/XC7jkFWuCJ9bLf7EC6OOx/cyY9AMAGpwoF9nfGZRQJOeRlWPFhqVgGuotzWKlnYlCuTsOzborjwMKb39zXRqCfoGuUbT3RKGJ@5TtCw "Python 2 โ€“ TIO Nexus") --- Results: ``` 0 0 1 0 2 18 3 355 4 8012 ``` [Answer] # [Perl 5](https://www.perl.org/), 117 bytes 116 bytes of code + `-p` flag. ``` $"=",";@F=(A..Z,0..9);map{$r=1;$r*=eval s/./+$&/gr for/\d+/g;$r+=64-ord for/\pl/g;$\+=!$r*/\pl/*/\d/}glob"{@F}"x$_}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K@iZKuko2Tt4Gar4ainF6VjoKdnqWmdm1hQrVJka2itUqRlm1qWmKNQrK@nr62ipp9epJCWX6Qfk6Ktnw6U1bY1M9HNL0qBCBbkgARjtG0VgfrAXCCZol@bnpOfpFTt4FarVKESX1v9/78xAA "Perl 5 โ€“ TIO Nexus") It feels quite suboptimal, but I 'm out of ideas right now. The code itself is very inefficient as it computes every permutation of `a..z,0..9` of length `n` (it takes roughly 1 second for `n=3`, ~15 seconds for `n=4` and ~7 minutes for `n=5`). The algorithm is quite straight forward: for every possible plate of size `n` (generated with `glob"{@F}"x$_` - the `glob` operator is quite magic), `$r*=eval s/./+$&/gr for/\d+/g;` computes the product of every chunk of digits, and `$r+=64-ord for/\pl/g` subtract to it the weight of the letters. Then, we increment the counter `$\` if the `$r` is `0` (`!$r`) and if the plate contains numbers and letters (`/\pl/*/\d/`). `$\` is implicitly printed at the end thanks to `-p` flag. Note that the numbers I obtain are `n=2 -> 18`, `n=3 -> 355`, `n=4 -> 8012`, `n=5 -> 218153`. I'm pretty sure these are the right ones, but I might be mistaken, in which case let me know and I'll deleted this answer. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 71 bytes Full program body. Prompts for N. Nโ‰ฅ4 requires huge amounts of memory and computation. ``` +/((+/โŠขโณโˆฉ)โˆ˜โŽ•A=(ร—/'\d+'โŽ•S{+/โŽยจโต.Match}))ยจl/โจโˆงโŒฟโˆจ/ยจcโˆ˜.โˆŠlโ†,(โˆŠcโ†โŽ•DโŽ•A)โˆ˜.,โฃโŽ•โŠ‚โฌ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9TRnvZfW19DQ1v/UdeiR72bH3Ws1HzUMeNR31RHW43D0/XVY1K01YG84Gqgit6@Qyse9W7V800sSc6o1dQ8tCIHKLjiUcfyRz37H3Ws0D@0IhmoWe9RR1fOo7YJOhpARjKQAdTvAjIRZLKezqPexUDOo66mR71r/j/qaP@fxmXIlcZlBMTGAA "APL (Dyalog Unicode) โ€“ TIO Nexus") [Answer] ## [GAP](http://www.gap-system.org), 416 bytes Won't win on code size, and far from constant time, but uses math to speed up a lot! ``` x:=X(Integers); z:=CoefficientsOfUnivariatePolynomial; s:=Size; f:=function(n) local r,c,p,d,l,u,t; t:=0; for r in [1..Int((n+1)/2)] do for c in [r..n-r+1] do l:=z(Sum([1..26],i->x^i)^(n-c)); for p in Partitions(c,r) do d:=x; for u in List(p,k->z(Sum([0..9],i->x^i)^k)) do d:=Sum([2..s(u)],i->u[i]*Value(d,x^(i-1))mod x^s(l)); od; d:=z(d); t:=t+Binomial(n-c+1,r)*NrArrangements(p,r)* Sum([2..s(d)],i->d[i]*l[i]); od; od; od; return t; end; ``` To squeeze out the unnecessary whitespace and get one line with 416 bytes, pipe through this: ``` sed -e 's/^ *//' -e 's/in \[/in[/' -e 's/ do/do /' | tr -d \\n ``` My old "designed for Windows XP" laptop can calculate `f(10)` in less than one minute and go much further in under an hour: ``` gap> for i in [2..15] do Print(i,": ",f(i),"\n");od; 2: 18 3: 355 4: 8012 5: 218153 6: 6580075 7: 203255386 8: 6264526999 9: 194290723825 10: 6116413503390 11: 194934846864269 12: 6243848646446924 13: 199935073535438637 14: 6388304296115023687 15: 203727592114009839797 ``` ## How it works Suppose that we first only want to know the number of perfect license plates fitting the pattern `LDDLLDL`, where `L` denotes a letter and `D` denotes a digit. Assume we have a list `l` of numbers such that `l[i]` gives the number of ways the letters can give the value `i`, and a similar list `d` for the values we get from the digits. Then the number of perfect licence plates with common value `i` is just `l[i]*d[i]`, and we get the number of all perfect licence plates with our pattern by summing this over all `i`. Let's denote the operation of getting this sum by `l@d`. Now even if the best way to get these lists was to try all combinations and count, we can do this independently for the letters and the digits, looking at `26^4+10^3` cases instead of `26^4*10^3` cases when we just run through all plates fitting the pattern. But we can do much better: `l` is just the list of coefficients of `(x+x^2+...+x^26)^k` where `k` is the number of letters, here `4`. Similarly, we get the numbers of ways to get a sum of digits in a run of `k` digits as the coefficients of `(1+x+...+x^9)^k`. If there is more than one run of digits, we need to combine the corresponding lists with an operation `d1#d2` that at position `i` has as value the sum of all `d1[i1]*d2[i2]` where `i1*i2=i`. This is the Dirichlet convolution, which is just the product if we interpret the lists as coefficients of Dirchlet series. But we have already used them as polynomials (finite power series), and there is no good way to interpret the operation for them. I think this mismatch is part of what makes it hard to find a simple formula. Let's use it on polynomials anyway and use the same notation `#`. It is easy to compute when one operand is a monomial: we have `p(x) # x^k = p(x^k)`. Together with the fact that it is bilinear, this gives a nice (but not very efficient) way to compute it. Note that `k` letters give a value of at at most `26k`, while `k` single digits can give a value of `9^k`. So we will often get unneeded high powers in the `d` polynomial. To get rid of them, we can compute modulo `x^(maxlettervalue+1)`. This gives a big speed up and, though I didn't immediately notice, even helps golfing, because we now know that the degree of `d` is not bigger then that of `l`, which simplifies the upper limit in the final `Sum`. We get an even better speed up by doing a `mod` calculation in the first argument of `Value` (see comments), and doing the whole `#` computation at a lower level gives an incredible speed up. But we're still trying to be a legitimate answer to a golfing problem. So we have got our `l` and `d` and can use them to compute the number of perfect licence plates with pattern `LDDLLDL`. That is the same number as for the pattern `LDLLDDL`. In general, we can change the order of the runs of digits of different length as we like, `NrArrangements` gives the number of possibilities. And while there must be one letter between the runs of digits, the other letters are not fixed. The `Binomial` counts these possibilities. Now it remains to run through all possible ways of having lengths of runs digits. `r` runs through all numbers of runs, `c` through all total numbers of digits, and `p` through all partitions of `c` with `r` summands. The total number of partitions we look at is two less than the number of partitions of `n+1`, and the partition functions grows like `exp(sqrt(n))`. So while there are still easy ways to improve the running time by reusing results (running through the partitions in a different order), for a fundamental improvement we need to avoid looking at each partition seperately. ## Computing it fast Note that `(p+q)@r = p@r + q@r`. On its own, this just helps avoid some multiplications. But together with `(p+q)#r = p#r + q#r` it means that we can combine by simple addition polynomials corresponding to different partitions. We can't just add them all, because we still need to know with which `l` we have to `@`-combine, which factor we have to use, and which `#`-extensions are still possible. Let's combine all polynomials corresponding to partitions with the same sum and length, and already account for the multiple ways of distributing the lengths of runs of digits. Different from what I speculated in the comments, I don't need to care about the smallest used value or how often it is used, if I make sure that I won't extend with that value. Here is my C++ code: ``` #include<vector> #include<algorithm> #include<iostream> #include<gmpxx.h> using bignum = mpz_class; using poly = std::vector<bignum>; poly mult(const poly &a, const poly &b){ poly res ( a.size()+b.size()-1 ); for(int i=0; i<a.size(); ++i) for(int j=0; j<b.size(); ++j) res[i+j]+=a[i]*b[j]; return res; } poly extend(const poly &d, const poly &e, int ml, poly &a, int l, int m){ poly res ( 26*ml+1 ); for(int i=1; i<std::min<int>(1+26*ml,e.size()); ++i) for(int j=1; j<std::min<int>(1+26*ml/i,d.size()); ++j) res[i*j] += e[i]*d[j]; for(int i=1; i<res.size(); ++i) res[i]=res[i]*l/m; if(a.empty()) a = poly { res }; else for(int i=1; i<a.size(); ++i) a[i]+=res[i]; return res; } bignum f(int n){ std::vector<poly> dp; poly digits (10,1); poly dd { 1 }; dp.push_back( dd ); for(int i=1; i<n; ++i){ dd=mult(dd,digits); int l=1+26*(n-i); if(dd.size()>l) dd.resize(l); dp.push_back(dd); } std::vector<std::vector<poly>> a; a.reserve(n); a.push_back( std::vector<poly> { poly { 0, 1 } } ); for(int i=1; i<n; ++i) a.push_back( std::vector<poly> (1+std::min(i,n+i-i))); for(int m=n-1; m>0; --m){ // std::cout << "m=" << m << "\n"; for(int sum=n-m; sum>=0; --sum) for(int len=0; len<=std::min(sum,n+1-sum); ++len){ poly d {a[sum][len]} ; if(!d.empty()) for(int sumn=sum+m, lenn=len+1, e=1; sumn+lenn-1<=n; sumn+=m, ++lenn, ++e) d=extend(d,dp[m],n-sumn,a[sumn][lenn],lenn,e); } } poly let (27,1); let[0]=0; poly lp { 1 }; bignum t { 0 }; for(int sum=n-1; sum>0; --sum){ lp=mult(lp,let); for(int len=1; len<=std::min(sum,n+1-sum); ++len){ poly &a0 = a[sum][len]; bignum s {0}; for(int i=1; i<std::min(a0.size(),lp.size()); ++i) s+=a0[i]*lp[i]; bignum bin; mpz_bin_uiui( bin.get_mpz_t(), n-sum+1, len ); t+=bin*s; } } return t; } int main(){ int n; std::cin >> n; std::cout << f(n) << "\n" ; } ``` This uses the GNU MP library. On debian, install `libgmp-dev`. Compile with `g++ -std=c++11 -O3 -o pl pl.cpp -lgmp -lgmpxx`. The program takes its argument from stdin. For timing, use `echo 100 | time ./pl`. At the end `a[sum][length][i]` gives the number of ways in which `sum` digits in `length` runs can give the number `i`. During computation, at the beginning of the `m` loop, it gives the number of ways that can be done with numbers greater than `m`. It all starts with `a[0][0][1]=1`. Note that this is a superset of the numbers we need to compute the function for smaller values. So at almost the same time, we could compute all values up to `n`. There is no recursion, so we have a fixed number of nested loops. (The deepest nesting level is 6.) Each loop goes through a number of values that is linear in `n` in the worst case. So we need only polynomial time. If we look closer at the nested `i` and `j` loops in `extend`, we find an upper limit for `j` of the form `N/i`. That should only give a logarithmic factor for the `j` loop. The innermost loop in `f` (with `sumn` etc) is similar. Also keep in mind that we compute with numbers that grow fast. Note also that we store `O(n^3)` of these numbers. Experimentally, I get these results on reasonable hardware (i5-4590S): `f(50)` needs one second and 23 MB, `f(100)` needs 21 seconds and 166 MB, `f(200)` needs 10 minutes and 1.5 GB, and `f(300)` needs one hour and 5.6 GB. This suggests a time complexity better than `O(n^5)`. [Answer] # Scala, 265 bytes ``` (n:Int)=>{val i=('A'to'Z')++('0'to'9');Seq.fill(n)(i).flatten.combinations(n).flatMap(_.permutations).map(_.mkString).count(l=>"(?=.*[A-Z])(?=.*\\d)".r.findAllIn(l).size>0&&l.map(_-64).filter(_>0).sum==l.split("[A-Z]").filter(""<).map(_.map(_-48).sum).reduce(_*_))} ``` **Explanations :** ``` (n:Int) => { val i = ('A' to 'Z') ++ ('0' to '9'); // All license plates available characters. Seq.fill(n)(i).flatten // Simulate combination with repetition (each character is present n times) .combinations(n) // and generate all combinations of size n (all license plates). .flatMap(_.permutations) // For each combination, generate all permutations (ex. : Seq('A', '1') => Seq('A', '1') and Seq('1', 'A')), and .map(_.mkString) // convert each permutation to String (Seq('A', '1') => "A1"). .count ( l => // Then count all strings having : "(?=.*[A-Z])(?=.*\\d)".r.findAllIn(l).size > 0 && // at least 1 character and 1 digit and l.map(_ - 64).filter(_ > 0).sum == // a sum of characters (> 'A' or > 64) equals to l.split("[A-Z]").filter(""<) .map(_.map(_ - 48).sum) .reduce(_*_) // the product of sum of digits groups (split String by letters to get digits groups) ) } ``` *Notes :* * `-64` and `-48` are used to transform a `Char` (respectively letter and digit) to its `Int` value (`'A' - 64 = 1`, `'B' - 64 = 2`, ..., `'9' - 48 = 9`) * The filter in `l.split("[A-Z]").filter(""<)` is used to eliminate `""` values if `l` starts with a letter (example : `"A1".split("[A-Z]") => Array("", 1)`). There might be a better and shorter solution **Test cases :** ``` val f = (n:Int) => ... // assign function (1 to 5).foreach ( i => println(s"N = $i: ${f(i)}") ) ``` **Results :** ``` N = 1: 0 N = 2: 18 N = 3: 355 N = 4: 8012 N = 5: 218153 ``` The function is pretty slow for `n > 4` since all combinations must be generated. [Answer] # Java, ~~382~~ 365 bytes * Saved 17 bytes, thanks to **Kevin Cruijssen** **Golfed** ``` int h(String s){int m=0;for(int c:s.toCharArray())m+=c-48;return m;} int g(String t){int d=1,c=0;for(String s:t.split("[^0-9]"))d*=h(s);for(String s:t.split("[^A-Z]"))c+=s.charAt(0)-65;return d==c?1:0;} int f(String t,int n){int m=0;if(t.length()==n)return g(t);for(int d=48;d<58;)m+=f(t+d++,n);for(int c=65;c<91;)m+=f(t+c++,n);return m;} int s(int n){return f("",n);} ``` **Detailed** ``` // return sum of adjecent digits int h(String s) { int sum = 0; for(char c : s.toCharArray()) sum += c-'0'; return sum; } // check if perfect int g(String t) { int d = 1; int c = 0; for(String s : t.split("[^0-9]")) d *= h(s); for(String s : t.split("[^A-Z]")) c += s.charAt(0)-'A'; return d == c ? 1 : 0; } // tree of enumerations int f(String t, int n) { // base case if(t.length() == n) { return g(t); } // enumeration int sum = 0; for(char d='0'; d<='9'; d++) sum += f(t+d, n); for(char c='A'; c<='Z'; c++) sum += f(t+c, n); return sum; } int s(int n){ return f("",n); } ``` [Answer] # Pyth, 55 bytes ``` FNQI<xrG1N0=+ZsN).?=+YZ=Z0;qu*G?HH1Y1sm?<xrG1d00hxrG1dQ ``` ]
[Question] [ Your task is to pit each side of the keyboard against each other and build two programs, in the same language, one using only keys on the left-hand side of a standard keyboard that outputs `Pollinium milk; plump pumpkin; lollipop?`, and one using the keys on the right that outputs `Weatherheaded sweetheart haberdasheress!`. ## Rules The exact keys allowed for the left-hand program are: ``` 123456!@#$%^QWERTYqwertyasdfghASDFGH`zxcvb~ZXCVB ``` and for the right-hand program: ``` 7890-=&*()_+uiop[]UIOP{}jkl;'\JKL:"|nm,./NM<>? ``` There are four free keys `Esc` (`\x1b`), `Tab` (`\x09`), `Space` (`\x20`) and `Enter`(`\x0a` and/or `\x0d`) which can be used in either, neither, or both solutions. Your score will be the total byte count for both programs. Whilst I've used the term `program`, your submissions can either be full programs, or functions as usual, and both can be different types (eg. one full program, and one function). Your result must include the desired text, any amount of leading and trailing whitespace is fine, as long as the exact text appears within it. [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/q/1061/9365). The shortest solutions in each language win. [Answer] # [Perl 5](https://www.perl.org/), 261 = 88 + 173 bytes This is an example where "language options don't count" is a problem. The rigt side solution uses `-p`, the left side doesn't. So does it count as the same language or not? And should the options come from the left/right character set ? # Left 88 use `-M5.10.0` (or `-E` from the commandline) to activate `say` Again arguable if this option should count as code and should come from the left side or if it falls under "options to set language version don't count" ``` say eYYYYZYEYWYYYYYWQYEYQWQEYQYYZYWYYYYYQYQW^q%565504004w4052bw!504!w!04!204bw56550!6!h% ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhNRIIoiJdI8NBjMjwQCAzMDwQSICEIYKBQJG4QlVTM1NTAxMDA5NyEwNTo6RyRSBPsVwRSBgZmCSVg6UVzRQzVP///5dfUJKZn1f8X9fXVM/QQM8AAA "Perl 5 โ€“ Try It Online") # Right 173 Run with the `-p` option (which also consists of right characters) ``` }{*_=\(uuuuuuuuuuuuuiuuuuuuuuuuiuuuuuuuuuuuuuui&Uiipjipjiijij0puiipjiipp0jijipjipjipipp7|Ouiujujjuiuuu0kouuujuiju0jijujuikjujukk7&"7oulio7iouloli77ooliou7liiu7o7lu7io7o77i") ``` This can almost certainly be improved, but for now it was hard enough to get something working. Not having access to `print`, `say`, `$_` and `sub{}` makes output tricky [Try it online!](https://tio.run/##bYw9CkJBDITv8oqHCsI2MpVnsLITrCwmu5igplKvbl52sbAwhJn5yI9dbm0X8X5uzvvTyn@Lf@PA@Uia9KZQivlAmpXE78QS8TrkrbjIeFGqpmYW74s91a61Yp6g3qhgmjYCmqqORjoUzXOSDk7riI/ag3q9x9YW "Perl 5 โ€“ Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~1175~~ ~~1143~~ ~~655~~ ~~645~~ ~~638~~ ~~632~~ ~~639~~ 578 (293 + 285) bytes It had to be done.. ;p ~~Can definitely be golfed by filling the stack reversed and printing it all at the end in some kind of loop, but this is only my second Whitespace program ever, so I've yet to figure it out..~~ EDIT: Golfed. +7 bytes because I misspelled `pumpkin` as `pumkin`.. (Thanks for noticing, *@fษ™หˆnษ›tษชk*.) Letters `S` (space), `T` (tab) and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Left-sided `Pollinium milk; plump pumpkin; lollipop?`: ``` [S S T T S T T T T N _Push_-47_?][S S S T S N _Push_2_p][S S S T N _Push_1_o][S T S S T N _Copy_1st_p][S S T T S T N _Push_-5_i][S S T T S N _Push_-2_l][S N S _Duplicate_-2_l][S S S T N _Push_1_o][S T S S T N _Copy_1st_l][S S T T S S T T T S N _Push_-78_space][S S T T T S S T T N _Push_-51_;][S S S N _Push_0_n][S S T T S T N _Push_-5_i][S S T T T N _Push_-3_k][S S S T S N _Push_2_p][S S T T N _Push_-1_m][S S S T T T N _Push_7_u][S S S T S N _Push_2_p][S S T T S S T T T S N _Push_-78_space][S S S T S N _Push_2_p][S S T T N _Push_-1_m][S S S T T T N _Push_7_u][S S T T S N _Push_-2_l][S S S T S N _Push_2_p][S S T T S S T T T S N _Push_-78_space][S S T T T S S T T N _Push_-51_;][S S T T T N _Push_-3_k][S S T T S N _Push_-2_l][S S T T S T N _Push_-5_i][S S T T N _Push_-1_m][S S T T S S T T T S N _Push_-78_space][S S T T N _Push_-1_m][S S S T T T N _Push_7_u][S S T T S T N _Push_-5_i][S S S N _Push_0_n][S S T T S T N _Push_-5_i][S S T T S N _Push_-2_l][S N S _Duplicate_-2_l][S S S T N _Push_1_o][S S T T T T T S N _Push_-30_P][N S S N _Create_Label_LOOP][S S S T T S T T T S N _Push_110][T S S S _Add][T N S S _Print_as_char][N S N N _Jump_to_Label_LOOP] ``` [Try it online](https://tio.run/##bU9BCoAwDDs3r8jXRAZ6ExR8fu3aMVcnjLYkabLe236V81jWokqK2BMBbaRX2FCrU9HgTKbqGhGNYTDuvI5tTEjfniUZ/4kZZT3uK05@0@eGg/x6A8CIlfCQxpoQqg8) (with raw spaces, tabs and new-lines only). Right-sided `Weatherheaded sweetheart haberdasheress!`: ``` [S S T T S S S T S S N _Push_-68_!][S S S T T T S N _Push_14_s][S N S _Duplicate_14_s][S S S N _Push_0_e][S S S T T S T N _Push_13_r][S S S N _Push_0_e][S S S T T N _Push_3_h][S S S T T T S N _Push_14_s][S S T T S S N _Push_-4_a][S S T T N _Push_-1_d][S S S T T S T N _Push_13_r][S S S N _Push_0_e][S S T T T N _Push_-3_b][S S T T S S N _Push_-4_a][S S S T T N _Push_3_h][S S T T S S S T S T N _Push_-69_space][S S S T T T T N _Push_15_t][S S S T T S T N _Push_13_r][S S T T S S N _Push_-4_a][S S S N _Push_0_e][S S S T T N _Push_3_h][S S S T T T T N _Push_15_t][S S S N _Push_0_e][S N S _Duplicate_0_e][S S S T S S T S N _Push_18_w][S S S T T T S N _Push_14_s][S S T T S S S T S T N _Push_-69_space][S S T T N _Push_-1_d][S S S N _Push_0_e][S S T T N _Push_-1_d][S S T T S S N _Push_-4_a][S S S N _Push_0_e][S S S T T N _Push_3_h][S S S T T S T N _Push_13_r][S S S N _Push_0_e][S S S T T N _Push_3_h][S S S T T T T N _Push_15_t][S S T T S S N _Push_-4_a][S S S N _Push_0_e][S S T T T T S N _Push_-14_W][N S S N _Create_Label_LOOP][S S S T T S S T S T N _Push_101][T S S S _Add][T N S S _Print_as_char][N S N N _Jump_to_Label_LOOP] ``` [Try it online](https://tio.run/##dY9RCsAgDEO/k1P0amMI299ggx2/06DVyQaibUle6r3tVzqPZU3uZoDly4zlyQ1V1dbAqLtAHvZZqKAJMFgqvrlHR9O98BWlHVDOFGvNG5E/pI/VJymEZfxVaEVoRro/) (with raw spaces, tabs and new-lines only). --- **Explanation:** It first build the stack reversed. Pushing a number is done as follows: * `S` at the start: Enable Stack Manipulation * `S`: Push what follows as number to the stack * `S`/`T`: Sign bit where `S` is positive and `T` is negative * Some `T` and `S` followed by an `N`: Put number as binary to the stack (`T=1` and `S=0`). --- Then it will loop over the stack reversed and print everything as characters. It does this as follows: 1. Push 0 (`SSSN`) 2. Push all numbers indicating the characters reversed as explained above 3. Create a `Label_0` (`NSSN`) 1. Duplicate the top of the stack (`SNS`) 2. If this value is 0: Jump to `Label_1` (`NTSTN`) 3. Else: Pop and print the top of the stack as character (`TNSS`) 4. Jump to `Label_0` (`NSNN`) 4. Create `Label_1` (`NSSTN`) This above is the default layout for both programs. Here is the change-log for this default layout which lowered the byte-count even further: 1. All numbers are lowered by the same amount (~~`100`~~ `110` in the first program, and ~~`102`~~ `101` in the second) to decrease the binary digits used for the now lower numbers, and between step 3.2 and 3.3 the following two sub-steps are added: * Push 110 (`SSSTTSTTTSN`) in program 1, or 101 (`SSSTTSSTSTN`) in program 2 * Pop and add the top two values of the stack with each other, and the result is the new top of the stack (`TSSS`) 2. I've also used `SNS` in some cases to duplicate the top of the stack, which is used to golf the `ll`, `ll`, `ee` and `ss`. 3. In addition, step 4 (create `Label_1`) was removed completely. It will exit with an error, but will still output everything correctly ([which is allowed according to the meta](https://codegolf.meta.stackexchange.com/a/4781/52210)). 4. It's possible to copy an `n`'th value from the top of the stack (with `STS` + 0-indexed `n`), which is shorter than creating a new number in some cases. In the first program I've done this for: the second `p` in `pop` (`STSSTN` (copy 1st) is shorter than `SSSTTSSN` (create number for 'p')), the second `l` in `lol` (`STSSTN` (copy 1st) is shorter than `SSSTSSSN` (create number for 'l')), the second `p` in `p p` (`STSSTN` (copy 1st) is shorter than `SSSTTSSN` (create number for 'p')), the second `p` in `pumlp` (`STSSTTN` (copy 3rd) is shorter than `SSSTTSSN` (create number for 'p')), the second `p` in `pmup` (`STSSTSN` (copy 2nd) is shorter than `SSSTTSSN` (create number for 'p')), the second `m` in `m m` (`STSSTN` (copy 1st) is shorter than `SSSTSSTN` (create number for 'm')), the second `i` in `ini` (`STSSTN` (copy 1st) is shorter than `SSSTSTN` (create number for 'i')). In the second program this isn't done for any. The distance between some is pretty short, like `ere` or `ded`, but creating the number for 'e' (`SSTTN`) or 'd' (`SSTTSN`) are both shorter or of equal length as copy 1st (`STSSTN`), so I couldn't apply this trick in the second program to save bytes. ***NOTE: After golf-step 7, not all of these apply anymore.*** 5. In both programs I've changed step 1 of the loop from `SSSN` (Push 0) to `SSN` (Push error\_value), and removed the steps 3.1 (`SNS` Duplicate) and 3.2 (`NTSTN` If 0: Exit). Now it will simply exit with an error that `SSN` is an unknown value as soon as it's tries to access it. 6. Removed the `SSN`(error\_value) completely in both programs. It will now stop with the error "*Can't do Infix Plus*" when it tries to do the Add-function with nothing left on the stack. 7. Changed the constant values of `100` and `102` to `110` and `101` respectively. [Here the Java program](https://tio.run/##bVLdatswFL7PUxx0JaHUpNAyFkeEBnphaEap1zLIypBTJVUjy5p1XAgjz@7KcR277W5sfL5fHflFvsqzl6ddXa@N9B6WUtt/IwBXZUavwaPE8Hot9BPkAaIpltpuV48gWUMDaAdQKl8ZBAFyNXmMj4i2CD6XxijfAIlFtVVltLz69efh6ub@egyJ@HYZD106@l3nRkiLb4qSNn5aJLGenV9OYs35e4O@gyBkjGMnOlWry/aoIJu2DaOtwkUYeMpOcgAUJE0Jp9mZnk3m5CeZkpSw@IR38etpdwosFtrKct9G0wZlS4nPkcx8Y8PY/5NCFhfr2cX3eUiYhqQ@5DAaUMiP33aAlYJipP5W0njqWNAGOOiR8bInOYHdR@elN7SMjLJbfKYMZqcFDxp92fnAcXB9vU0PJ2GuP0a2z3TvUeVRUWHkwn7QWEpauSC8M@UkDvdJeMJJOOu77Wcl/VjvyDqMDnVd3xbGaKurHHJtdjE4U@Uu/Le522kbg2lgV7j5Gw) used to generate the `110` constant; and [here the Java program](https://tio.run/##bVFbS8MwFH7frzjmKSGzTFDEdUEUfCg4H6w3UJF0PW7RrqvJmTJkv72mq13r5aUl57vm5EW/692X9LUsJ5l2Dsba5J89gGKZZGYCjjT53/vCpDD3EI/Jmnx6/whaVDSAegAW3TIjUKDvB4/hBjE5gZvrLENXAVFOOEUbjE/unm5Ozq/P@hCpw4Ow69LQLxs3xmr8eWF55WdUFJrR3sEgNFJ@N2g7KMb61C9Uo6p1yYoQkmHdMJginfqB42IrByDF4phJnuya0eCYXbEhi5kIt3gTPxk2t6DFqcm1XdXRvELFWNMs0ImrbIT4P8lnSTUZ7R8d@4ShT2pD1r0OhV085B3MKk4Bvi115nghvNbDXk9C2pZUKGoOjZd55jbIMJ/SjAsYbRfcafRn5x3HzvO1Ni0c@bn5GVl/45UjnAeLJQWF3w9lOWe1XDHZmEoW@vdkMpLM3/Xb9reS/6y3Ya1767Isb9GvG@0MdYopuA9Ef9SWYKYTtKl2HkTndr4A) used to generate the `101` constant. Note that there are now less *Copy* used than described at point 4 above, because the new values are in many cases shorter than the copies, so re-pushing them is shorter. [Answer] # Lenguage, [this many](https://pastebin.com/raw/rQVuUq8s) bytes The left-hand side is 65721878296123796350462639500449228197646164622176218219262161264085219054330862921130017235140285847450697804123168755463678390611789188813352602373675420824698785508893489685489807676509031860196742608788337382365939621331808044899882497347443262020486908162559376082705672994569868 repetitions of the `a` character, which is equivalent to the following Brainfuck program: ``` -[--->+<]>-----.[--->+<]>-.---..---.+++++.-----.++++++++++++.--------.[->+++++<]>-.+[----->+<]>.----.+++.-.--[->+++<]>.+[-->+<]>++.[-->+++++++<]>.----.+++++++++.--------.+++.[------->++<]>.[-->+++++++<]>.+++++.--------.+++.-----.--.+++++.[-->+<]>++++.+[-->+<]>++.++[--->++<]>.+++.---..---.+++++++.-.+.[--->++++<]>-. ``` [Try it online!](https://tio.run/##bVBBCoAwDHtQaF8g@8jwoIIgggfB98813dwUexhtmqTt5nPajvVa9pQkikjAMAax0FaqlXxgod5HFw65KhChDpEgXbSK1PycZrBxSMgdpqh6fY9pM@DU4k3qR/kj8Oy5oU3NRb8DEJttEXbHc3@Uz6l3pnQD) The right-hand side is 636605880289050800007960838028215177632402180834140124157618258152393860687206680356620669530585999501769442445842690365640523699585001167392310123764258380235064746704898152544431842440556280249638840374132783257375880144623575829131522611446544303839106505176776161206935275549421170646618266717893044911373119804737614528140 repetitions of the `p` character, which is equivalent to the following Brainfuck program: ``` +[--->++<]>+.++[->++++<]>+.----.--[--->+<]>-.------------.---.+++++++++++++.----------.---.----.+++.+.-.-[--->+<]>-.---[->++++<]>-.++++.[->+++<]>..[--->+<]>---.------------.---.----.--[--->+<]>---.++.[---->+<]>+++.-[--->++<]>--.-------.+.+++.+++++++++++++.--------------.---.--[--->+<]>--.-----------.---.+++++++++++++.-------------.[--->+<]>----..+[-->+++++<]>-. ``` [Try it online!](https://tio.run/##jVBBCoAwDHtQaV4g@4h4UEEQwYPg@2vXTjqmgj2MJe2aZNMxrvtyzpsI9cyciLohEUiR3gvSBuvhA8qwMXdlAKoLTZPLBLSDZk3o@BI4oRiISX6RfLgyEXvkhDmJVLED5G4@PFcK1XL8jZx7tSkG8t9aTM8pcgE) [Answer] # [CJam](https://sourceforge.net/p/cjam), 128 + 192 = 320 bytes ``` 64G^c111c111Z^cT$111c6^111X^c1$116X^c111Y^c32c1$6$Y3#$111c4^56Z^c32c112c13$A$A$3$5$1$4$4$4$12$22$22$14$32c13$111c1$T$7$A$4$1$63c ``` [Try it online!](https://tio.run/##JU2xDcAwCDumfoCQ0rlTH8iQZECq2Cr1/5ESKmMLbEvYc7/uUi81Ilqcag1rFw3t4cclPfOhxiUMweAtS1V3mb9LQcYZYOwg1AQVlByq4GzkHzQc0Ywcwub@AQ "CJam โ€“ Try It Online") ``` 'U))'i(((('_))'u('i('i(((('p))'i('i(((('_))'_)))))'i(((('_)))))'&(((((('u(('u))'i(((('i(((('u('i('i(((('_))'p))'u('&(((((('i('_))'_)))'i(((('p))'_)))))'_))'u(('i('i(((('p))'i(((('u(('u(('&((((( ``` [Try it online!](https://tio.run/##S85KzP3/Xz1UU1M9UwMI1OOBrFINIAfKLwDLIEkCsSayahBHTQMMgBqBGC6ZCRVD1V8AsQCmJRNhKpKNUHMhjsFwDdwqDZg5//8DAA "CJam โ€“ Try It Online") [Answer] # [Fission](https://github.com/C0deH4cker/Fission), 958 + 752 = 1710 bytes .\_. ### Left ``` D z ^@$$$$$$$$$$$$$$$$$$$@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~@!!@~~~@!@$$$$$@!@~~~~~@!@$$$$$$$$$$$$@!@~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~~@!@$$$@!@~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@~~~~@!@$$$$$$$$$@!@~~~~~~~~@!@$$$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@$$$$$@!@~~~~~~~~@!@$$$@!@~~~~~@!@~~@!@$$$$$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~@!@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@!@$$$@!@~~~@!!@~~~@!@$$$$$$$@!@~@!@$@!@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@!V ``` [Try it online!](https://tio.run/##S8ssLs7Mz/v/34WriivOQQUTOChiE0VTUVdX56AIpRyQBBF8FLUwmTpqAsIOJQ1A3QcxFsQhw8H4tVDbxeiOxhbkqAKDNeyR0h1O54NpLKoGa/Qgux4ts8DTF1n@cFAM@/8fAA "Fission โ€“ Try It Online") ### Right ``` } \} \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \} \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ } \ O________________________________________I'/O\/O\__u'/O\____i'/O\++p'/O\___/O\_i'/O\__u'/O\___/O\_____i'/O\++p'/O\+++/O\+/O\_______/O\_i'/O\_________________________________________I'/O\_u'/O\++p'/O\____/O\___/O\_i'/O\_u'/O\/O\____i'/O\++u'/O\__u'/O\_________________________________________I'/O\_/O\+/O\+++/O\____/O\___/O\_i'/O\++p'/O\___/O\_i'/O\_u'/O\____/O\____i'/O\+++++++P'L ``` [Try it online!](https://tio.run/##S8ssLs7Mz/v/X4F4UKsQA0RQFlwIQSGTqBxswuhSCD6RbkE3FIsrEC7GrpYU2xBuJs7T2FwIYXD5xxMJPNX1/WOAKD6@VB1Mxcdnghja2gVQPojMVEdRAlWIolJbWxtEwqRQ9JHiFoglCOvj0V1RCncx3AGlqM4jxTaomyGux2IdtnAoRXUaTCEYBKj7/P8PAA "Fission โ€“ Try It Online") OK, here we are with plain luck, actually .\_. First cool feature of Fission is that it has 4 commands to create command pointers, AKA atoms: `RLDU`, so I have two commands for left and right groups. Second lucky charm is 2 commands for output `!` and `O`, which occurs in different groups. Third time the charm. Both outputting comands output ASCII equivalent of atoms' mass. So I need to change it some how. Lucky me! Both `+ (+1 mass)` and `_ (-1 mass)` are in one group and all needed three `$ (+1 energy)`, `~ (-1 energy)`, `@ (swap mass and energy)` are in other group. > > Also there are mirrors to control atoms in both groups! But I didn't use them in first program > > > So there is nothing to stop me, but it can't be compact, setting masses step-by-step. ### First program First program consists of only `Dz^@$~!V` ``` D create atom, going down z set its mass to ASCII code of 'z' ^ split atom in 2, dividing their mass. One goes left, second - right ``` Start can be simplier (just `R`), but using divide saves some bytes for first letter. Atom, that goes left wraps around and encounters `V`, which makes him going down and wrapping indefinitely, doing nothing. Second atom goes rigth and will encounter bunch of repeated patterns `@...@!` for each letter to output. ``` @ swap atom's mass and energy ... increament or decrement energy until it would match desired ASCII code @ swap again ! print character by atoms mass ``` Eventually it will encounter `V` and share fate of first atom. There is no way to destroy them or halt with left part of keyboard. ### Second program Second comes with its ups and downs. I've got comands to change mass directly, but output command `O` destroys atoms, so I need to preserve them somehow. Program starts on the right from `L` with atom going left. Repeated pattern: ``` } \ /O\...X' ``` `'` puts next encoutered char's ASCII code in atoms' mass, so code of some `X` is stored first, than mass is changed by `_` and `+` to exact value. Sometimes `X'` is skipped, if it is shorter to use just `_` and `+`. Atom comes from the left, mirrors two times and hits `}` from left. In this case `}` works like cloner, sending two identical atoms up and down. Down atom reflects by mirror and goes left. Up atom wraps, hits same mirror but from below and so reflects right, encountering `O` and printing. At the end last atom meets final `O` to be destructed. ]
[Question] [ ## Introduction: Before the task, here is what every element does on the map: **Plain land** (`X`): This does nothing. **Destroyed land** (`-`): This is the same as plain land, but destroyed by a bomb. **The active bomb** (`!`): On a map, this will destroy everything in a 3x3 square: ``` XXXXX XXXXX XXXXX X---X XX!XX > will become > X---X XXXXX X---X XXXXX XXXXX ``` **The passive bomb** (`@`): It does nothing, until it is detonated by another bomb. This also has a **3x3** square explosion radius: ``` XXXXX XXXXX XXXXX XXXXX XX@XX > will become > XX@XX (nothing happened) XXXXX XXXXX XXXXX XXXXX ``` But: ``` XXXXX XXXXX XXXXX X---X XX@XX > will become > ----X (both bombs have exploded) X!XXX ----X XXXXX ---XX ``` **The nuke** (`~`): It does nothing, until it is detonated by another bomb. The difference is that this bomb has a **5x5** square explosion radius: ``` XXXXX XXXXX XXXXX XXXXX XX~XX > will become > XX~XX (nothing happened) XXXXX XXXXX XXXXX XXXXX ``` But: ``` XXXXX ----- XXXXX ----- XX~XX > will become > ----- (both bombs have exploded) X!XXX ----- XXXXX ----- ``` ## The task * Given a **9x9 map**, output the map *after* the chain reaction. * You may provide a function or a program. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! ## Test cases Test case 1 (*3 steps*): ``` XXXXXXXXX XXXXXXXXX ----XXXXX ----XXXXX XXXX@XXXX XXXX@XXXX XXXXXXXX- XXX---XX- XXXX@XXXX > ------XXX XXXXXXXX- ------XX- XX~XXXXXX -----XXXX X!XXXXXX- -----XXX- XXXXXXXXX -----XXXX ``` Test case 2 (*2 steps*): ``` XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XX~XXXXXX XX~XXXXXX --------- --------- XXXX!XXXX > XXX---XXX XXXXXXXXX XXX------ XXX@@X@!X XXX@@---- XXXXXXXXX XXXXX---- XXXXXXXXX XXXXXXXXX ``` Test case 3 (*2 steps*): ``` XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XX~XXXXXX XX~XXXXXX XXXXXXXXX XXX---XXX XXXX!XXXX > XXX---XXX XXXXXXXXX XXX------ XXX@@X@!X XXX@@---- XXXXXXXXX XXXXX---- XXXXXXXXX XXXXXXXXX ``` Test case 4 (*1 step*): ``` XXXXXXXXX XXXXXXXXX XXXX-XXXX XXXX-XXXX XXXXXXXXX XXX---XXX XX-X!X-XX XX-----XX XXXXXXXXX > XXX---XXX XX-----XX XX-----XX XXXX-XXXX XXXX-XXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX ``` Test case 5 (*9 steps*): ``` !XXXXXXXX ---XXXXXX X@XXXXXXX ----XXXXX XX@XXXXXX -----XXXX XXX@XXXXX X-----XXX XXXX@XXXX > XX-----XX XXXXX@XXX XXX-----X XXXXXX@XX XXXX----- XXXXXXX@X XXXXX---- XXXXXXXX@ XXXXXX--- ``` Test case 6 (*9 steps*): ``` XX@@@XXXX ------XXX XXXXXXXXX ------XXX ~XXXXXXXX ---XXXXXX XXXXXXXXX ---XXXXXX ~XXXXXXXX > ---XXXXXX XXXXXXXXX ---XXXXXX ~XXXXXXXX ---XXXXXX @XXXXXXXX ---XXXXXX !XXXXXXXX ---XXXXXX ``` Test case 7 (*3 steps*): ``` !XXXXXXXX ---XXXXXX X@XXXXXXX ----XXXXX XX@XXXXXX ----XXXXX XXXXXXXXX X---X---- XXXXXX@@! > XXXXX---- XXXXXXXXX X---X---- XX@XXXXXX ----XXXXX X@XXXXXXX ----XXXXX !XXXXXXXX ---XXXXXX ``` [Answer] # Matlab, ~~120~~ 111 bytes ``` function f=c(f);c=@(x,i)conv2(x+0,ones(i),'s');a=c(f<34,3);for k=f;a=c(a&f<65,3)|a;a=c(a&f>99,5)|a;end;f(a)='-' ``` > > Convolution is the key to success. > > > The idea is following: Find the active bomb. Enlarge this area to a 3x3 square. Find new affected bombs, enlarge the correspoding areas to the corresponding size and add those to the previously destroyed area. Repeat this enough times (in my case as many times as we have input characters, just because that is the shortest variant) to be sure that we reached a stationary point (=no more exploding bombs). Then set all the destroyed area to `-` and display the result. The input is assumed to be a matrix of characters, e.g. ``` ['!XXXXXXXX'; 'X@XXXXXXX'; 'XX@XXXXXX'; 'XXX@XXXXX'; 'XXXX@XXXX'; 'XXXXX@XXX'; 'XXXXXX@XX'; 'XXXXXXX@X'; 'XXXXXXXX@']; ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~188~~ ~~168~~ ~~154~~ 152 bytes Bytes counted as ISO 8859-1. ``` +Tm`@~X!:`!:\-`(.)?.?.(.?(?<1>.)?)(?<=(:|(?(1)_)!|^(?(5)_)(?<-5>.)*(:|(?(1)_)!)(?<1>.*ยถ)?.*ยถ(.)*.|(?=(.)*ยถ.*(?<1>ยถ.*)?(:|(?(1)_)!)(?<-6>.)*(?(6)_)$))\2) ``` [Try it online!](http://retina.tryitonline.net/#code=K1RtYEB-WCE6YCE6XC1gKC4pPy4_LiguPyg_PDE-Lik_KSg_PD0oOnwoPygxKV8pIXxeKD8oNSlfKSg_PC01Pi4pKig6fCg_KDEpXykhKSg_PDE-LirCtik_LirCtiguKSoufCg_PSguKSrCti4qKD88MT7Cti4qKT8oOnwoPygxKV8pISkoPzwtNj4uKSooPyg2KV8pJCkpXDIp&input=WFhAQEBYWFhYClhYWFhYWFhYWAp-WFhYWFhYWFgKWFhYWFhYWFhYCn5YWFhYWFhYWApYWFhYWFhYWFgKflhYWFhYWFhYCkBYWFhYWFhYWAohWFhYWFhYWFg&debug=on) ~~This is more of a proof of concept. There is a horrible amount of duplication between bombs and nukes, which I'll try to get rid of before adding an explanation.~~ Well, I got rid of that duplication but it increased the complexity significantly so it didn't actually result in huge savings... [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 56 chars or 62 bytes\* My colleague [Marshall](http://dyalog.com/meet-team-dyalog.htm#Marshall) came up with an elegant solution, 21 characters shorter than mine: ``` {'-'@(({1โˆŠโตโ‰ฅโˆ˜.โŒˆโจ5โด1+4โ†‘1}โŒบ5 5ร—โˆ˜(('X'โ‰ โต)+'~'=โต))โฃโ‰ก'!'โˆ˜=)โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///Pzyx6FHbhGp1XXUHDY3qRx0r9HUe9W591Ln0UccMvUc9HY96V5g@6t1iqG3yqG2iYe2jnl2mCqaHpwNlNTTUI9QfdS4AKtfUVq9TtwUxNB/1Ln7UuVBdUR2owhbI21r73yWzuABsh4L6o95VQCEdDbNHPXtNH3VNs1QwNASaCxRWt1PXBNq8C4gUwLqADlMA6VSwVLAEOkA9AgZ0gQDOcYhAArrYROqgTEUkNWCgzoXTCiRQh7BUF2azIroiB4cIB0UsmkmyAgVQywpdNOW6QJNRxXQR4akbgRVgWqGIJfwpYmHzhYODA4FgwiPigBGQpPoCNfCRg94BjUZYAQA "APL (Dyalog Unicode) โ€“ Try It Online") `{`โ€ฆ`}`โ€ƒanonymous function where the argument is represented by *โต* โ€ƒ`'-'@(`โ€ฆ`)โต`โ€ƒ*dash* **at** the positions masked by the following tacit function: โ€ƒโ€ƒ`'!'โˆ˜=`โ€ƒBoolean where exclamation point equals the argument โ€ƒโ€ƒ`(`โ€ฆ`)โฃโ‰ก`โ€ƒapply the following tacit function until nothing more changes: โ€ƒโ€ƒโ€ƒ`ร—โˆ˜(`โ€ฆ`)`โ€ƒmultiply by the following constant: โ€ƒโ€ƒโ€ƒโ€ƒ`'~'=โต`โ€ƒBoolean where tilde equals the original argument โ€ƒโ€ƒโ€ƒโ€ƒ`(`โ€ฆ`)+`โ€ƒto that, add: โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ`'X'โ‰ โต`โ€ƒBoolean where X is different from the original argument โ€ƒโ€ƒโ€ƒ`{`โ€ฆ`}โŒบ5 5`โ€ƒfor each, apply the following function on the 5ร—5 area centered on it: โ€ƒโ€ƒโ€ƒโ€ƒ`4โ†‘1`โ€ƒtake the first four elements of one, padding with zeros [1,0,0,0] โ€ƒโ€ƒโ€ƒโ€ƒ`1+`โ€ƒadd one [2,1,1,1] โ€ƒโ€ƒโ€ƒโ€ƒ`5โด`โ€ƒreshape cyclically into length five [2,1,1,1,2] โ€ƒโ€ƒโ€ƒโ€ƒ`โˆ˜.โŒˆโจ`โ€ƒmaximum table with itself on both axes โ€ƒโ€ƒโ€ƒโ€ƒ`โตโ‰ฅ`โ€ƒBoolean where the corresponding neighbours are greater than or equal to that โ€ƒโ€ƒโ€ƒโ€ƒ`1โˆŠ`โ€ƒBoolean if any is true --- \* Just replace `โŒบ` with `โŽ•U233A` under Classic for single byte per character. [Answer] # Java, ~~574~~ ~~562~~ ~~558~~ ~~549~~ ~~525~~ 523 bytes ``` import java.util.*;interface B{static char[][]g=new char[9][9];static void d(int i,int j,int r){g[i][j]=45;for(int x=Math.max(i-r,0);x<Math.min(i+r+1,9);x++)for(int y=Math.max(j-r,0);y<Math.min(j+r+1,9);y++)if(g[x][y]==64){d(x,y,1);}else if(g[x][y]>99){d(x,y,2);}else g[x][y]=45;}static void main(String[]a){Scanner q=new Scanner(System.in);for(int i=0;i<9;i++){int j=0;for(char c:q.nextLine().toCharArray())g[i][j++]=c;}for(int j=0;j<9;j++)for(int k=0;k<9;k++)if(g[j][k]==33)d(j,k,1);for(char[]z:g)System.out.println(z);}} ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 61 bytes ``` '-'@({i/โจโˆจโŒฟโ†‘(โ†“โŒˆ/ยจ|โตโˆ˜.-i)โ‰ค3|'X@~-'โณa[โต]}โฃโ‰ก('!'=,a)/iโ†,โณโดa)โŠขaโ†โŽ• ``` [Try it online!](https://tio.run/##pVBNS8NAEL3vr3BPk0DHCOKhB2F@xkLxsFQqgUCF9iLWnCRNtRFFBK9@HHLzoJ6F/pT5I@m0mHaTBi30wbIzb2ffG549j/D0wkb9M@xGdjAIuwXfPYV9Tu4PFKfjXgEI5F2GAWc5pzlPfzh58Dh55GkazPIRZ9@cPu9j6PPk/XAEhmIEzj5tR15Orjh748mLBxqOW9YPQtFtyStnX9bnm1crvfgV4qQWdkPV49trYYSffRyJFSxPydlVBbCYL4aqvdcWNTAlULBqyDjAJib@LbUzswSoTW0H8doNS0tdHyIypBs@b6ddwc7aWJtDkaxyuI4OTSMcbd2Q8U5VZW8i@ieRPxjayGzrvasBu/FS7Xa05w "APL (Dyalog Classic) โ€“ Try It Online") `aโ†โŽ•` evaluate input and assign to `a` `iโ†,โณโดa` the indices (pairs of coords) of all cells `('!'=,a)/` filter only the initially active bombs `{ }โฃโ‰ก` perform a transformation on the list until it stabilizes * `'X@~-'โณa[โต]` substitute 0 for `X`, 1 for `@`, etc, 4 for anything else (`!`) * `3|` mod 3 to get the "radius" of impact; it must be greater or equal to the... * `(โ†“โŒˆ/ยจ|โตโˆ˜.-i)โ‰ค` ...Manhattan distances between cells in the list and all cells * `i/โจโˆจโŒฟโ†‘` get bitmask of which cells are affected and select those from `i` `'-'@( )โŠขa` put `-` at those positions ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/rCqky.png)](https://i.stack.imgur.com/rCqky.png) While doodling around on square-ruled paper the other day, I came up with the above negative-space font for digits. In case you haven't spotted it yet, the spaces between the above shapes yield the golden ratio **1.618033988749**. In this challenge, your task is to take a number as input and render it exactly as the example above shows. Here is how these are created: all lines will be on a regular grid, so that the individual digits are made up of a small number of grid cells. Here are the shapes of the 10 digits (we'll ignore the decimal point for this challenge): [![enter image description here](https://i.stack.imgur.com/D9q3N.png)](https://i.stack.imgur.com/D9q3N.png) Yes, the **7** differs from the golden ratio example at the top. I kinda messed that up. We'll be going with this one. Notice that each digit is five cells tall, and three cells wide. To render a number, you can imagine placing all its digits next to each other, such that there is exactly one empty column between each pair of digits. For example, taking `319` as input, we'd write: [![enter image description here](https://i.stack.imgur.com/HNpZX.png)](https://i.stack.imgur.com/HNpZX.png) Notice that we add one leading and trailing empty column. Now we invert the cells: [![enter image description here](https://i.stack.imgur.com/izPXn.png)](https://i.stack.imgur.com/izPXn.png) The output should then be the boundaries of the resulting polygons: [![enter image description here](https://i.stack.imgur.com/ztpo5.png)](https://i.stack.imgur.com/ztpo5.png) Of course you may generate the result in any other way, as long as the rendered output looks the same. ## Input * You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, as a string, or list of digits. (You can't take a number as that wouldn't allow you to support leading zeros.) * You may assume that there will be no more than 16 digits in the input. ## Output * Output may either be displayed on screen or written to a file in a common image format. * You may use both raster and vector graphics. * In either case, the aspect ratio of the cells of the underlying grid needs to be 1 (that is, the cells should be squares). * In the case of raster graphics, each cell should cover at least 20 by 20 pixels. * The lines must be no wider than 10% of the cell size. I'm willing to give one or two pixels leeway due to aliasing here. * Lines and background can be any two clearly distinguishable colours, but the shapes created by the lines must not be filled (that is the insides should be the background colour as well). * There must be no gaps within each closed loop. * Of course, the entire result must be visible. ## Test Cases Here are 10 inputs, which together cover all possible pairs of adjacent digits, as well as every possible leading and trailing digit: ``` 07299361548 19887620534 21456837709 39284106657 49085527316 59178604432 69471338025 79581224630 89674235011 97518264003 ``` And here are the expected results for those: [![enter image description here](https://i.stack.imgur.com/UTM1a.png)](https://i.stack.imgur.com/UTM1a.png) [![enter image description here](https://i.stack.imgur.com/Ct1sR.png)](https://i.stack.imgur.com/Ct1sR.png) [![enter image description here](https://i.stack.imgur.com/MJzQr.png)](https://i.stack.imgur.com/MJzQr.png) [![enter image description here](https://i.stack.imgur.com/OPK9E.png)](https://i.stack.imgur.com/OPK9E.png) [![enter image description here](https://i.stack.imgur.com/zlqOn.png)](https://i.stack.imgur.com/zlqOn.png) [![enter image description here](https://i.stack.imgur.com/vspRa.png)](https://i.stack.imgur.com/vspRa.png) [![enter image description here](https://i.stack.imgur.com/NQPdG.png)](https://i.stack.imgur.com/NQPdG.png) [![enter image description here](https://i.stack.imgur.com/ODUY8.png)](https://i.stack.imgur.com/ODUY8.png) [![enter image description here](https://i.stack.imgur.com/Rc7R1.png)](https://i.stack.imgur.com/Rc7R1.png) [![enter image description here](https://i.stack.imgur.com/f9Ldb.png)](https://i.stack.imgur.com/f9Ldb.png) Make sure that your code also works when given a single digit (I don't want to include the expected results here, because they should be obvious, and the test case section is bloated enough as it is). [Answer] # Octave, ~~233 225 216~~ 213 bytes ``` o=@ones;l=z=o(5,1);for k=input('')-47;l=[l,reshape(dec2bin([448,22558,8514,10560,3936,2376,328,15840,320,2368](k),15),5,[])-48,z];end;L=~o(size(l)+2);L(2:6,2:end-1)=l;O=o(3);O(5)=-8;M=~conv2(kron(L,o(25)),O);imshow(M) ``` Here the first test case (from a resized screen capture, s.t. it fits my monitor=): [![enter image description here](https://i.stack.imgur.com/p5gDT.png)](https://i.stack.imgur.com/p5gDT.png) ``` o=@ones; l=z=o(5,1); %spacer matrices for k=input('')-47; %go throu all input digis %decode the matrices for each digit from decimal l=[l,reshape(dec2bin([448,22558,8514,10560,3936,2376,328,15840,320,2368](k),15),5,[])-48,z]; end L=~o(size(l)+2); %pad the image L(2:6,2:end-1)=l; O=o(3);O(5)=-8; %create edge detection filter imshow(~conv2(kron(L,o(25)),O)) %image resizing /edge detection (change 25 to any cell size you like) ``` The input can be arbitrary length, like e.g. `'07299361548'` > > Convolution is the key to success. > > > [Answer] # Html+JavaScript ES6, 352 Test running the snippet below ``` <canvas id=C></canvas><script>s=prompt(),C.width=-~s.length*80,c=C.getContext("2d"),[...s].map(d=>[30,d*=3,++d,++d].map(w=a=>{for(a=parseInt("vhvivgtlnllv74vnltvlt11vvlvnlv0"[a],36)*2+1,p=1,y=100,i=64;i>>=1;p=b,y-=20)c.moveTo(x+20,y),b=a&i?1:0,c[b-p?'lineTo':'moveTo'](x,y),(a^q)&i&&c.lineTo(x,y-20);q=a,x+=20}),q=63,x=0),w(30),w(0),c.stroke()</script> ``` *Less golfed* ``` s=prompt(),C.width=-~s.length*80,c=C.getContext("2d"), w=a=>{ a=parseInt("vhvivgtlnllv74vnltvlt11vvlvnlv0"[i],36)*2+1 for(p=1,y=100,i=32;i;p=b,y-=20,i>>=1) c.moveTo(x+20,y), b=a&i?1:0, c[b-p?'lineTo':'moveTo'](x,y), (a^q)&i&&c.lineTo(x,y-20) q=a x+=20 }, [...s].map(d=>[30,d*=3,++d,++d].map(w),q=63,x=0), w(30),w(0) c.stroke() ``` [Answer] # Javascript ES6, 506 bytes ``` a=>{with(document)with(body.appendChild(createElement`canvas`))with(getContext`2d`){width=height=(a.length+2)*80;scale(20,20);translate(1,1);lineWidth=0.1;beginPath();["oint",...a.map(i=>"05|7agd7|oint 067128a45|oicgmnt 01de25|oil9amnt 01de23fg45|oint 03fh5|68ec6|oint 03fg45|oij78knt 05|9agf9|oij78knt 01dh5|oint 05|78ed7|9agf9|oint 03fg45|78ed7|oint".split` `[i]),"05"].map(i=>{i.split`|`.map(i=>[...i].map((e,i,_,p=parseInt(e,36),l=~~(p/6),r=p%6)=>i?lineTo(l,r):moveTo(l,r)));translate(4,0)});stroke()}} ``` Ungolfed: ``` a=>{ // anonymous function declaration, accepts array of numbers with(document) // bring document into scope with(body.appendChild(createElement`canvas`)) // create canvas, drop into html body, bring into scope with(getContext`2d`){ // bring graphics context into scope width=height=(a.length+2)*80; // set width and height scale(20,20); // scale everything to 20x translate(1,1); // add padding so outline doesn't touch edge of canvas lineWidth=0.1; // have to scale line width since we scaled 20x beginPath(); // start drawing lines ["oint", // beginning "glyph", draws left end of negative space, see below ...a.map(i=>`05|7agd7|oint // glyphs 0-9 encoded as vertices 067128a45|oicgmnt // glyphs seperated by " " 01de25|oil9amnt // lines within each glyph seperated by "|" 01de23fg45|oint // a single vertex is stored as a base36 char 03fh5|68ec6|oint // where a number corresponds to one of the verts shown below: 03fg45|oij78knt // 0 6 12 18 24 05|9agf9|oij78knt // 1 7 13 19 25 01dh5|oint // 2 8 14 20 26 05|78ed7|9agf9|oint // 3 9 15 21 27 03fg45|78ed7|oint` // 4 10 16 22 28 .split` `[i]), // 5 11 17 23 29 "05"] // end "glyph", draws right end of negative space, see above .map(i=>{ // for each glyph string i.split`|` // seperate into list of line strings .map(i=>[...i] // convert each line string into list of chars .map((e,i,_,p=parseInt(e,36), // convert base36 char to number l=~~(p/6),r=p%6)=> // compute x y coords of vertex i?lineTo(l,r):moveTo(l,r))); // draw segment translate(4,0)}); // translate origin 4 units to right stroke()}} // draw all lines to canvas ``` Assumes there's a `<body>` to append the canvas to, tested in Firefox 46. Example run (assigning anonymous function to f): ``` f([1,0,3]) ``` yields: [![Example output](https://i.stack.imgur.com/efj7R.png)](https://i.stack.imgur.com/efj7R.png) [Answer] # Java, 768 bytes ``` import java.awt.*;import java.awt.image.*;class G{public static void main(String[]v)throws Exception{int s=20,n=v[0].length(),i=0,j,w=(n*3+n+1)*s,h=5*s,a[][]={{6,7,8},{0,2,3,10,11,12,13},{1,6,8,13},{1,3,6,8},{3,4,5,6,8,9},{3,6,8,11},{6,8,11},{1,2,3,4,6,7,8,9},{6,8},{3,6,8}};BufferedImage o,b=new BufferedImage(w,h,1);Graphics g=b.getGraphics();g.setColor(Color.WHITE);for(;i<n;i++)for(j=0;j<15;j++){int c=j;if(java.util.Arrays.stream(a[v[0].charAt(i)-48]).noneMatch(e->e==c))g.fillRect((1+i*4+j/5)*s,j%5*s,s,s);}o=new BufferedImage(b.getColorModel(),b.copyData(null),0>1,null);for(i=1;i<h-1;i++)for(j=1;j<w-1;j++)if((b.getRGB(j+1,i)|b.getRGB(j-1,i)|b.getRGB(j,i+1)|b.getRGB(j,i-1))<-1)o.setRGB(j,i,-1);javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}} ``` ### Ungolfed ``` import java.awt.*; import java.awt.image.BufferedImage; class Q79261 { public static void main(String[] v) throws Exception { int scale = 20, n = v[0].length(), i = 0, j, width = (n * 3 + n + 1) * scale, height = 5 * scale, values[][] = {{6, 7, 8}, {0, 2, 3, 10, 11, 12, 13}, {1, 6, 8, 13}, {1, 3, 6, 8}, {3, 4, 5, 6, 8, 9}, {3, 6, 8, 11}, {6, 8, 11}, {1, 2, 3, 4, 6, 7, 8, 9}, {6, 8}, {3, 6, 8}}; BufferedImage output, temp = new BufferedImage(width, height, 1); Graphics g = temp.getGraphics(); g.setColor(Color.WHITE); for (; i < n; i++) for (j = 0; j < 15; j++) { int finalJ = j; if (java.util.Arrays.stream(values[v[0].charAt(i) - 48]).noneMatch(e -> e == finalJ)) g.fillRect((1 + i * 4 + j / 5) * scale, j % 5 * scale, scale, scale); } output = new BufferedImage(temp.getColorModel(), temp.copyData(null), 0 > 1, null); for (i = 1; i < height - 1; i++) for (j = 1; j < width - 1; j++) if ((temp.getRGB(j + 1, i) | temp.getRGB(j - 1, i) | temp.getRGB(j, i + 1) | temp.getRGB(j, i - 1)) < -1) output.setRGB(j, i, -1); javax.imageio.ImageIO.write(output, "png", new java.io.File("a.png")); } } ``` ### Notes * Input is a single string as argument. How to use: `javac G.java`, `java G 80085` * I'm starting with a black canvas, then I'm adding the numbers as white positives. I create a copy of the image and then flip every black pixel that has 4 black neighbours on the original image. ### Outputs [![0](https://i.stack.imgur.com/PINSK.png)](https://i.stack.imgur.com/PINSK.png) [![1](https://i.stack.imgur.com/YgW9O.png)](https://i.stack.imgur.com/YgW9O.png) [![2](https://i.stack.imgur.com/46aMt.png)](https://i.stack.imgur.com/46aMt.png) [![3](https://i.stack.imgur.com/PHpkk.png)](https://i.stack.imgur.com/PHpkk.png) [![4](https://i.stack.imgur.com/M9WVy.png)](https://i.stack.imgur.com/M9WVy.png) [![5](https://i.stack.imgur.com/hWkn4.png)](https://i.stack.imgur.com/hWkn4.png) [![6](https://i.stack.imgur.com/CP3Sv.png)](https://i.stack.imgur.com/CP3Sv.png) [![7](https://i.stack.imgur.com/wEfty.png)](https://i.stack.imgur.com/wEfty.png) [![8](https://i.stack.imgur.com/waXH1.png)](https://i.stack.imgur.com/waXH1.png) [![9](https://i.stack.imgur.com/R5otW.png)](https://i.stack.imgur.com/R5otW.png) Some single digits: [![enter image description here](https://i.stack.imgur.com/PKvRw.png)](https://i.stack.imgur.com/PKvRw.png) [![enter image description here](https://i.stack.imgur.com/uhyow.png)](https://i.stack.imgur.com/uhyow.png) [Answer] # R, too many bytes to golf (~~1530+~~ 1115) ``` library(reshape2);library(ggplot2);library(png) M=matrix(1,5,3) M=lapply(list(c(7:9),c(1,3,4,11:14),c(2,7,9,14),c(2,4,7,9),c(4:7,9,10),c(4,7,9,12),c(7,9,12),c(2:5,7:10),c(7,9),c(4,7,9)),function(x){M[x]=0;M}) g=function(P){ S=matrix(0,5,1) R=NULL for(N in P){R=Reduce(cbind2,list(R,S,M[[N+1]]))} cbind(R,S)} p=function(P){ o=t(apply(g(P),1,rev)) ggplot(melt(o),aes(x=Var1,y=Var2))+geom_raster(aes(fill=value))+coord_flip()+scale_fill_continuous(guide=FALSE,high="#FFFFFF",low="#000000")+scale_y_reverse()+scale_x_reverse()+theme_bw()+theme(panel.grid=element_blank(),panel.border=element_blank(),panel.background=element_blank(),axis.title=element_blank(),axis.text=element_blank(),axis.ticks=element_blank(),plot.margin=unit(c(0,0,0,0),"mm"))+ggsave("t.png",width=dim(o)[2]/2.5,height=2,units="in",dpi=99) q=readPNG("t.png") k=q[,,1] b=replace(k,k==1,0) for(i in 1:nrow(k)){ for(j in 1:ncol(k)){ u=(i==nrow(k)) v=(j==ncol(k)) if(u&v){b[i,j]=1;break} if((i==1)|u|(j==1)|v){b[i,j]=1;next}else{if(all(k[c((i-1):(i+1)),c((j-1):(j+1))])){b[i,j]=1}else{b[i,j]=0}}}} q[,,1:3]=abs(replace(k,b==1,0)-1) writePNG(q,"t.png")} # run p(c(0,1,2,3,4,5)) ``` [![enter image description here](https://i.stack.imgur.com/oV58G.png)](https://i.stack.imgur.com/oV58G.png) [![enter image description here](https://i.stack.imgur.com/I9mDB.png)](https://i.stack.imgur.com/I9mDB.png) [![enter image description here](https://i.stack.imgur.com/VuGPp.png)](https://i.stack.imgur.com/VuGPp.png) [![enter image description here](https://i.stack.imgur.com/zy81g.png)](https://i.stack.imgur.com/zy81g.png) [![enter image description here](https://i.stack.imgur.com/jQzRM.png)](https://i.stack.imgur.com/jQzRM.png) [![enter image description here](https://i.stack.imgur.com/CmBOo.png)](https://i.stack.imgur.com/CmBOo.png) [![enter image description here](https://i.stack.imgur.com/mLFRJ.png)](https://i.stack.imgur.com/mLFRJ.png) [![enter image description here](https://i.stack.imgur.com/GOI15.png)](https://i.stack.imgur.com/GOI15.png) [![enter image description here](https://i.stack.imgur.com/2DN85.png)](https://i.stack.imgur.com/2DN85.png) [![enter image description here](https://i.stack.imgur.com/jIzj4.png)](https://i.stack.imgur.com/jIzj4.png) lol at writing to disk, then reading from disk edit away the black fill. [Answer] # Python 3, 326 325 bytes ``` import numpy from skimage import io,transform as t,filters as f r=[[1]*5,[0]*5] for c in map(int,input()):r+=[map(float,bin(0x3f1fa7e1bd7b5aff84ff6b7fd6f087ff5ff6bf)[2:][15*c+5*i:15*c+5*-~i])for i in[0,1,2]]+[[0]*5] r+=[[1]*5] p=[[1]*len(r)] r=p+list(zip(*r))+p io.imsave("o.png",1-f.sobel((t.rescale(numpy.array(r),16,0)))) ``` [Answer] # BBC BASIC, 182 ASCII characters (tokenised filesize 175 bytes) Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> ``` I.n$ F.j=0TOLENn$*4p=ASCM."?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@",VALM.n$,j/4+1,1)*4+1+j MOD4)F.k=0TO4p*=2q=64A.p V.537;q;0;2585;0;q;537;-q;0;2585;0;-q;25;0;64; N.MOVEBY 64,-320N. ``` Scoring: When the above program is pasted into the editor and run, the editor will expand the abbreviated keywords into full keywords onscreen, though they are actually only 1 byte after tokenisation. (Example `I.`=`INPUT` storage space 1 byte.) **Explanation** I will just explain what the VDU line does: it draws a box by bit-flipping the current pixel colour on the screen. This means that (with a bit of care with the corners) it is possible simply to draw one cell next to each other, and the intervening edge will cancel out and disappear due to double drawing. Close examination will reveal that the top right and bottom left corners of a cell are drawn but the top left and bottom right are missing ("rounded") in order to make this work. After the cell is drawn, the graphics cursor is moved up 32 pixels ready for the next cell to be drawn. The rest of the program is a fairly straightforward ASCII bitmap decompression. The dimensions of the cell are 64x64 units for golfing/compatability with the way the bitmap is decompressed. `q` controls the size of the cell that is plotted: 64x64 units for a cell that is present, 0x0 for a cell that is absent. **Ungolfed code** ``` m$="?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@" :REM bitmap for digits, including column of filled cells at left. BBC strings are 1-indexed INPUTn$ :REM user input FORj=0 TO LENn$*4 :REM iterate 4 times per input digit, plus once more (plot column 0 of imaginary digit to finish) d=VAL MID$(n$,j/4+1,1) :REM extract digit from n$ (1-character string). VAL of empty string = 0, so 123->1,1,1,1,2,2,2,2,3,3,3,3,0 p=ASC MID$(m$,d*4+1+j MOD4) :REM get column bitmap from m$ d*4 selects digit, j MOD4 selects correct column of digit, add 1 to convert to 1-index FORk=0TO4 :REM for each cell in the column p*=2 :REM bitshift p q=64ANDp :REM find size of cell to draw. 64 for a filled cell, 0 for an absent cell. VDU537;q;0; :REM line q units right, inverting existing screen colour. Draw last pixel (will be inverted next line) VDU2585;0;q; :REM line q units up, inverting existing screen colour. Dont draw last pixel (will be filled in next line) VDU537;-q;0; :REM line q units left, inverting existing screen colour. Draw last pixel (will be inverted next line) VDU2585;0;-q; :REM line q units down, inverting existing screen colour. Dont draw last pixel (avoid inverting 1st pixel of 1st line) VDU25;0;64; :REM move up 64 units for cell above NEXT MOVEBY 64,-320 :REM move right and down for next column. NEXT ``` **Output** The `MOVE`s are just get the output to appropriate heights on the screen. BBC basic uses 2 units = 1 pixel in this mode, so the cells are actually 32x32 pixels. [![enter image description here](https://i.stack.imgur.com/1FBNo.png)](https://i.stack.imgur.com/1FBNo.png) [Answer] ## C#, 768 773 776 bytes ``` namespace System.Drawing{class P{static void Main(string[]a){uint[]l={0xEBFBFFFC,0xB89B21B4,0xABFFF9FC,0xAA1269A4,0xFFF3F9FC};var w=a[0].Length*80+20;var b=new Bitmap(w,100);var g=Graphics.FromImage(b);g.FillRectangle(Brushes.Black,0,0,w,100);for(int i=0;i<a[0].Length;i++)for(int r=0;r<5;r++)for(int c=0;c<3;c++)if((l[r]&((uint)1<<(175-a[0][i]*3-c)))>0)g.FillRectangle(Brushes.White,20*(1+i*4+c),20*r,20,20);for(int x=1;x<w-1;x++)for(int y=1;y<99;y++)if(b.GetPixel(x,y).B+b.GetPixel(x+1,y).B+b.GetPixel(x,y+1).B+b.GetPixel(x,y-1).B+b.GetPixel(x+1,y-1).B+b.GetPixel(x+1,y+1).B+b.GetPixel(x-1,y+1).B+b.GetPixel(x-1,y-1).B==0)b.SetPixel(x,y,Color.Red);for(int x=1;x<w-1;x++)for(int y=1;y<99;y++)if(b.GetPixel(x,y).R>0)b.SetPixel(x,y,Color.White);b.Save(a[0]+".bmp");}}} ``` Takes the number as command line argument. Outputs a nice, clean, non-aliased BMP image with the number as the name. Original before golfing: ``` namespace System.Drawing { class P { static void Main(string[] args) { var numbers = args[0]; uint[] lines = { 0xEBFBFFFC, // 111 010 111 111 101 111 111 111 111 111 00 0xB89B21B4, // 101 110 001 001 101 100 100 001 101 101 00 0xABFFF9FC, // 101 010 111 111 111 111 111 001 111 111 00 0xAA1269A4, // 101 010 100 001 001 001 101 001 101 001 00 0xFFF3F9FC // 111 111 111 111 001 111 111 001 111 111 00 }; var width = numbers.Length*4 + 1; var bmp = new Bitmap(width*20, 5*20); using (var gfx = Graphics.FromImage(bmp)) { gfx.FillRectangle(Brushes.Black, 0, 0, width*20+2, 5*20+2); // Process all numbers for (int i = 0; i < numbers.Length; i++) { var number = numbers[i]-'0'; for (int line = 0; line < 5; line++) { for (int col = 0; col < 3; col++) { if ((lines[line] & ((uint)1<<(31-number*3-col))) >0) gfx.FillRectangle(Brushes.White, 20*(1 + i * 4 + col), 20*line, 20 , 20 ); } } } // Edge detection for (int x = 1; x < width*20-1; x++) { for (int y = 1; y < 5*20-1 ; y++) { if (bmp.GetPixel(x,y).B + bmp.GetPixel(x + 1, y).B + bmp.GetPixel(x, y + 1).B + bmp.GetPixel(x, y - 1).B + bmp.GetPixel(x + 1, y - 1).B + bmp.GetPixel(x + 1, y + 1).B + bmp.GetPixel(x - 1, y + 1).B + bmp.GetPixel(x - 1, y - 1).B == 0) bmp.SetPixel(x, y, Color.Red); } } // Convert red to white for (int x = 1; x < width * 20 - 1; x++) { for (int y = 1; y < 5 * 20 - 1; y++) { if (bmp.GetPixel(x, y).R>0) bmp.SetPixel(x, y, Color.White); } } } bmp.Save(@"c:\tmp\test.bmp"); } } } ``` [Answer] # Mathematica 328 bytes ``` j@d_:=Partition[IntegerDigits[FromDigits[d/.Thread[ToString/@Range[0,9]->StringPartition["75557262277174771717557117471774757711117575775717",5]],16],2, 20]/.{0->1,1->0},4];j@"*"=Array[{1}&,5]; w@s_:= ColorNegate@EdgeDetect@Rasterize@ArrayPlot[Thread[Join@@Transpose/@j/@Characters@(s<>"*")],Frame->False,ImageSize->Large] ``` --- ``` w["07299361548"] w["19887620534"] ``` [![pic](https://i.stack.imgur.com/uBiqt.png)](https://i.stack.imgur.com/uBiqt.png) --- ## Explanation Four bits will be used in each of 5 lines of cells for each input digit. `"75557262277174771717557117471774757711117575775717"`represents 0 to 9 as bitmaps. The first 5 digits in the large integer above, namely `75557` indicate how each array row for zero should be displayed. `7` will represent `{0,1,1,1}`, that is, a white cell, followed, on its right, by 3 black cells; the leading `0` is a blank space to separate displayed digits. `5` corresponds to `{0,1,0,1}`, that is white, black, white, black cells. The following produces a list of replacement rules: ``` Thread[ToString /@ Range[0, 9] -> StringPartition["75557262277174771717557117471774757711117575775717", 5]] ``` > > {"0" -> "75557", "1" -> "26227", "2" -> "71747", "3" -> "71717", > "4" -> "55711", "5" -> "74717", "6" -> "74757", "7" -> "71111", > "8" -> "75757", "9" -> "75717"} > > > Note that when `3` is input, it will be replaced by `71717` This representation is expressed in binary: ``` p = Partition[IntegerDigits[FromDigits["3" /. {"3" -> "71717"}, 16], 2, 20], 4] ``` > > {{0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}} > > > Its black-white inverse is found by simply exchanging the `1`s and `0`s. ``` q = p /. {0 -> 1, 1 -> 0} ``` > > {{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}} > > > --- Let's see what `p` and `q` look like when displayed by `ArrayPlot`: ``` ArrayPlot[#, Mesh -> True, ImageSize -> Small, PlotLegends -> Automatic] & /@ {p, q} ``` [![pis](https://i.stack.imgur.com/Q8Ikz.png)](https://i.stack.imgur.com/Q8Ikz.png) --- This simply joins the arrays of zeros and ones for each digit before rendering the big array via `ArrayPlot`. `*` is defined in `j` as the final vertical space after the last digit. ``` Thread[Join @@ Transpose /@ j /@ Characters@(s <> "*")] ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/5334/edit) In the spirit of the [Underhanded C Contest](http://underhanded.xcott.com/?m=200912), I'm starting an Underhanded Code Contest. The objective of this contest is to straightforwardly implement some code, while subtly hiding a nefarious bug inside it. ## The contest You are a secret Russian mole working in the IT department of an American spy agency. Your American boss has just asked you to implement a password hashing algorithm to use for encrypting secret messages. Your boss wants you to implement the following function: ``` f: String -> byte[16] ``` which converts a password to a 16-byte quantity suitable for use as an AES key. Your boss wants a secure function, which in this context means that different password strings should generate different results with overwhelming probability. For instance, returning the [md5](http://en.wikipedia.org/wiki/MD5) hash of the input would be a simple implementation of `f`. Of course, your *real* boss in the Russian spy agency would want you to subvert this process. Your task is to implement `f` such that the Russians can decrypt all the secret messages encrypted using keys returned by `f`. To do so, you must implement `f` so that it returns only a small subset of the 2^128 possible outputs. In particular, your `f` must return at most 2^16 different results so that the Russians can do an easy brute-force search for the correct key for each encrypted message they wish to decrypt. Keep in mind, however, that espionage carries the death penalty. In order not to get caught, your function `f` must generate at least 2^8 different results, so that a cursory inspection of a few outputs of `f` is unlikely to reveal a duplicate. **And most importantly, the code you introduce to limit the range of `f` must look unintentional, not deliberate.** If you ever get hauled into a courtroom, there must be some reasonable doubt as to whether you introduced the bug deliberately or by accident. ## Judging I and two others I recruit will judge the entries (email me if you'd like to judge). I'm offering a 200 reputation bounty for the winning entry. Submissions must be uploaded by May 1. Judging will take into account the following criteria: * Does `f` adhere to the spec, i.e. does it generate between 2^8 and 2^16 possible outputs. Don't feel that these are hard limits, but we'll deduct points if you're too far out of range. * Is the bug plausibly the result of an unintentional mistake? * Do the outputs of `f` look random? * The shorter your implementation of `f`, the better. * The clearer your implementation of `f`, the better. ## Notes You may use any language to implement your code. You're trying to hide a bug in plain sight, so obfuscated code is not suggested. You might want to take a look at some of the previous [Underhanded C contest](http://underhanded.xcott.com/?page_id=4) winners to get a feel for what makes a good submission. Input strings will be printable ascii (32 through 126, inclusive). You may assume a reasonable max length if you want. [Answer] ## C 2^16 possible outputs (or 2^8 times the number of used characters). Uses Linux's MD5 implementation, which is, AFAIK, fine. But this gives the same hash, for example, for "40" and "42". EDIT: Renamed `bcopy` to `memcpy` (swapped parameters of course). EDIT: Converted from program to function, to meet requirements better. ``` #include <string.h> #include <openssl/md5.h> void f(const unsigned char *input, unsigned char output[16]) { /* Put the input in a 32-byte buffer, padded with zeros. */ unsigned char workbuf[32] = {0}; strncpy(workbuf, input, sizeof(workbuf)); unsigned char res[MD5_DIGEST_LENGTH]; MD5(workbuf, sizeof(workbuf), res); /* NOTE: MD5 has known weaknesses, so using it isn't 100% secure. * To compensate, prefix the input buffer with its own MD5, and hash again. */ memcpy(workbuf+1, workbuf, sizeof(workbuf)-1); workbuf[0] = res[0]; MD5(workbuf, sizeof(workbuf), res); /* Copy the result to the output buffer */ memcpy(output, res, 16); } /* Some operating systems don't have memcpy(), so include a simple implementation */ void * memcpy(void *_dest, const void *_src, size_t n) { const unsigned char *src = _src; unsigned char *dest = _dest; while (n--) *dest++ = *src++; return _dest; } ``` [Answer] # C This may not be the flashiest contest entry, but I think the following is the kind of hash function that could have been made by any coder too clever for their own good, with a vague idea of the kind of operations you see in hash functions: ``` #include <stdio.h> #include <string.h> #include <stdint.h> void hash(const char* s, uint8_t* r, size_t n) { uint32_t h = 123456789UL; for (size_t i = 0; i < n; i++) { for (const char* p = s; *p; p++) { h = h * 33 + *p; } *r++ = (h >> 3) & 0xff; h = h ^ 987654321UL; } } int main() { size_t n = 1024; char s[n]; size_t m = 16; uint8_t b[m]; while (fgets(s, n, stdin)) { hash(s, b, m); for (size_t i = 0; i < m; ++i) printf("%02x", b[i]); printf("\n"); } } ``` In fact the hash function can return no more than L\*2048 different results, where L is the number of different input string lengths that can occur. In practice, I tested the code on 1.85 million unique input lines from manual pages and html documents on my laptop, and got only 85428 different unique hashes. [Answer] ## Scala: ``` // smaller values for more easy tests: val len = 16 // make a 16 bytes fingerprint def to16Bytes (l: BigInt, pos: Int=len) : List[Byte] = if (pos == 1) List (l.toByte) else (l % 256L).toByte :: to16Bytes (l / 256L, pos-1) /** if number isn't prime, take next */ def nextProbPrime (l: BigInt) : BigInt = if (l.isProbablePrime (9)) l else nextProbPrime (l + 1) /** Take every input, shift and add, but take primes */ def codify (s: String): BigInt = (BigInt (17) /: s) ((a, b) => nextProbPrime (a * BigInt (257) + b)) /** very, very short Strings - less than 14 bytes - have to be filled, to obscure them a bit: */ def f (s: String) : Array [Byte] = { val filled = (if (s.size < 14) s + "secret" + s else s) to16Bytes (codify (filled + filled.reverse)).toArray.map (l => nextProbPrime (l).toByte) } ``` Test, if the result doesn't look similar for similar input: ``` val samples = List ("a", "aa", "b", "", "longer example", "This is a foolish, fishy test") samples.map (f) List[Array[Byte]] = List( Array (-41, -113, -79, 127, 29, 127, 31, 67, -19, 83, -73, -31, -101, -113, 97, -113), Array (-19, 7, -43, 89, -97, -113, 47, -53, -113, -127, -31, -113, -67, -23, 127, 127), Array (-41, -113, -79, 127, 29, 127, 31, 67, -19, 83, -73, -31, -101, -113, 97, -113), Array (37, -19, -7, 67, -83, 89, 59, -11, -23, -47, 97, 83, 19, 2, 2, 2), Array (79, 101, -47, -103, 47, -13, 29, -37, -83, -3, -37, 59, 127, 97, -43, -43), Array (37, 53, -43, -73, -67, 5, 11, -89, -37, -103, 107, 97, 37, -71, 59, 67)) ``` The error is using just primes for the encoding. Instead of ``` scala> math.pow (256, 16) res5: Double = 3.4028236692093846E38 ``` values, we end with ``` scala> math.pow (54, 16) res6: Double = 5.227573613485917E27 ``` since there are 54 primes below 256. ]
[Question] [ # Background In 1870 โˆšรขmile Baudot invented [Baudot Code](https://en.wikipedia.org/wiki/Baudot_code), a fixed-length character encoding for telegraphy. He designed the code to be entered from a manual keyboard with just five keys; two operated with the left hand and three with the right: ![Baudot 5-key keyboard](https://i.stack.imgur.com/t2c0p.png) The right index, middle and ring fingers operate the *I*, *II*, and *III* keys, respectively, and the left index and middle fingers operate *IV* and *โ€šร–ยง*. (Henceforth I'll use the more familiar numerals 1โ€šร„รฌ5.) Characters are entered as chords. To enter the letter "C," for example, the operator presses the *1*, *3*, and *4* keys simultaneously, whereupon a rotating brush arm reads each key in sequence and transmits a current or, for keys not depressed, no current. In modern terms, this is a 5-bit least-significant-bit-first binary encoding, in which our example, "C," is encoded as `10110`. ## 5 bits?? You might be thinking that 5 bits, which can express at most 32 unique symbols, isn't enough for even all of the English letters and numerals, to say nothing of punctuation. Baudot had a trick up his sleeve, though: His character set is actually *two* distinct sets: *Letters* and *Figures*, and he defined two special codes to switch between them. *Letter Shift* (LS), which switches to Letters mode, is activated by pressing the *5* key alone (`00001`), and *Figure Shift* (FS) is activated with the *4* key (`00010`). # Challenge Your challenge is to write a program or function that decodes Baudot Code transmissions. A real transmission would begin with some initialization bits, plus a start and stop bit before and after each character, but we're going to skip those and only worry about the 5 unique bits for each character. Input and output formats are discussed below. ## Baudot's Code There are two different versions of Baudot Code: Continental and U.K. We're going use the U.K. version, which *doesn't* include characters like "โˆšรข" from Baudot's native French. We're also going to leave out all of the symbols in the U.K. version that aren't among the printable ASCII characters. You will only have to decode the characters in the table below, all of which are printable ASCII characters except the final three control characters that are explained below the table. The "Ltr" column shows the characters in Letter mode and "Fig" shows the Figure mode characters: ``` Encoding Encoding Ltr Fig 12345 Ltr Fig 12345 --- --- -------- --- --- -------- A 1 10000 P + 11111 B 8 00110 Q / 10111 C 9 10110 R - 00111 D 0 11110 S 00101 E 2 01000 T 10101 F 01110 U 4 10100 G 7 01010 V ' 11101 H 11010 W ? 01101 I 01100 X 01001 J 6 10010 Y 3 00100 K ( 10011 Z : 11001 L = 11011 - . 10001 M ) 01011 ER ER 00011 N 01111 FS SP 00010 O 5 11100 SP LS 00001 / 11000 ``` The last three rows in the right column are control characters: * **`ER`** is *Erasure*. Baudot's telegraphy machines would print an asterisk-like symbol for this character to tell the reader that the preceding character should be ignored, but we're going to be even nicer to the reader and *actually omit (do not print) the preceding character*. It acts the same in both Letter and Figure mode. * **`FS`** is *Figure Shift*. This switches the character set from Letters to Figures. If the decoder is *already* in Figure mode, FS is treated as a *Space* (ergo `SP` in the "Ltr" column). When the decoder is in Figure mode it stays in Figure mode until an LS character is received. * **`LS`** is *Letter Shift*. It switches the character set from Figures to Letters. If the decoder is already in Letter mode, LS is treated as a *Space*. When in Letter mode the decoder stays in Letter mode until an FS character is received. The decoder always starts in Letter mode. Here's an example with Figure Shift, Letter Shift, and Space: ``` 01011 10000 00100 00001 00010 10000 11100 00001 10101 11010 M A Y LS/SP FS/SP 1 5 LS/SP T H ``` This yields the message `MAY 15TH`. As you can see, the first `00001` (Letter Shift/Space) character acts as a space, because the decoder is already in Letter mode. The next character, `00010` (Figure Shift/Space) switches the decoder to Figure mode to print `15`. Then `00001` appears again, but this time it acts as Letter Shift to put the decoder back in Letter mode. For your convenience, here are the characters in a format that's perhaps easier to digest in an editor, sorted by code: ``` A,1,10000|E,2,01000|/,,11000|Y,3,00100|U,4,10100|I,,01100|O,5,11100|FS,SP,00010|J,6,10010|G,7,01010|H,,11010|B,8,00110|C,9,10110|F,,01110|D,0,11110|SP,LS,00001|-,.,10001|X,,01001|Z,:,11001|S,,00101|T,,10101|W,?,01101|V,',11101|ER,ER,00011|K,(,10011|M,),01011|L,=,11011|R,-,00111|Q,/,10111|N,,01111|P,+,11111 ``` ## Input Input will be a string, array, or list of bits in least-significant-bit-first order. Each character will be represented by a quintet of 5 bits. Bits may be in any reasonable format, e.g. a binary string, an array of `0`s and `1`s, a string of `"0"` and `"1"` characters, a single very large number, etc., as long as it maps directly to the bits of the transmission. Every transmission will have at least one printable quintet and at most 255 quintets (printable or otherwise), i.e. 5โ€šร„รฌ1,275 bits inclusive. The input can contain *only* the bits of the transmission, with two allowed exceptions: Any number of leading or trailing `0` bits and/or, for string input, a single trailing newline may be added to the transmission. Leading or trailing bits or characters *cannot* be added before or after each quintet, i.e. you cannot pad each quintet to 8 bits (or take each quintet as a single number in an arrayโ€šร„รฎunless your language has a 5-bit integer type) or separate quintets with any additional bits, e.g. `"01111\n11100"`. ### Notes & edge cases 1. The transmission will contain only the characters in the "Ltr" and "Fig" columns in the table above. You will never receive e.g. `01110` in Figure mode, because it is absent from the "Fig" column. 2. It is assumed that the decoder will always be in Letter mode at the beginning of a transmission. However, the first character *may* be an FS character to switch to Figure mode immediately. 3. When the decoder is in Letter mode, it may receive an LS character, and when it is in Figure mode it may receive an FS character. In either event a Space character must be printed (see Output). 4. The ER character will never be the first character in a transmission, nor will it ever immediately follow an LS, FS, or another ER. 5. An FS character may immediately follow an LS character and vice versa. 6. Neither the LS nor FS character will be the last character in any transmission. 7. The `/` and `-` characters may be received in either Letter mode (codes `11000` and `10001`, respectively) or Figure mode (`10111` and `00111`). ## Output Output may be in any reasonable format, the most reasonable being ASCII (or UTF-8, for which all of the represented characters are the same as ASCII). Please indicate in your answer if your output is in another encoding or format. ### Notes * The space character (see 3. above) should be an ASCII space (0x20) or your encoding's equivalent, i.e. what you get when you press the space bar. # Winning This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest code in bytes wins. # Restrictions * Standard loopholes are forbidden. * Trailing spaces and/or a single trailing newline are allowed. Leading spaces or other characters (that are not part of the transmission) are disallowed. * You may not use any built-in or library functions that decode Baudot Code (or any of its descendants, e.g. Murray Code, ITA-1, etc.). # Test Cases ``` Input: 001101000010100111101110010101 Output: BAUDOT ``` ``` Input: 11010010001001100011110111101111100 Output: HELLO ``` ``` Input: 01011100000010000001000101000011100000011010111010 Output: MAY 15TH ``` ``` Input: 0001000100010000001000001011101110011100101010010110101010001111100101 Output: 32 FOOTSTEPS ``` ``` Input: 10110000110101011100111100001111011010000001101110 Output: GOLF ``` ``` Input: 000100011000001111100000100010110111001100010110010000111111 Output: 8D =( :P ``` ``` Input: 0000100001000010000100010001111011111011000011100010001 Output (4 leading spaces): -/=/- ``` [Answer] # Pyth, ~~98~~ ~~97~~ ~~95~~ ~~93~~ ~~90~~ ~~83~~ 80 bytes The code contains unprintable characters, so here is a reversible `xxd` hexdump: ``` 00000000: 753f 7133 4a69 4832 5047 2b47 3f3c 334a u?q3JiH2PG+G?<3J 00000010: 4040 6332 2e22 275a 75ae 5751 fb4e 3cd7 @@c2."'Zu.WQ.N<. 00000020: 02ce 8719 aac1 e0e0 fe1f 09e5 85bc a767 ...............g 00000030: 8e0c 1f47 508a cad1 1acb b26f 951e e5d6 ...GP......o.... 00000040: 225a 4a2a 5c20 715a 3d5a 744a 637a 356b "ZJ*\ qZ=ZtJcz5k ``` [Try it online.](http://pyth.herokuapp.com/?code=u%3Fq3JiH2PG%2BG%3F%3C3J%40%40c2.%22%27Zu%C2%AEWQ%C3%BBN%3C%C3%97%02%C3%8E%C2%87%19%C2%AA%C3%81%C3%A0%C3%A0%C3%BE%1F%09%C3%A5%C2%85%C2%BC%C2%A7g%C2%8E%0C%1FGP%C2%8A%C3%8A%C3%91%1A%C3%8B%C2%B2o%C2%95%1E%C3%A5%C3%96%22ZJ*%5C%20qZ%3DZtJcz5k&input=001101000010100111101110010101&test_suite_input=001101000010100111101110010101%0A11010010001001100011110111101111100%0A01011100000010000001000101000011100000011010111010%0A00010001000001000001011101110011100101010010110101010001111100101%0A10110000110101011100111100001111011010000001101110%0A000100011000001111100000100010110111001100010110010000111111%0A0000100001000010000100010001111011111011000011100010001&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=u%3Fq3JiH2PG%2BG%3F%3C3J%40%40c2.%22%27Zu%C2%AEWQ%C3%BBN%3C%C3%97%02%C3%8E%C2%87%19%C2%AA%C3%81%C3%A0%C3%A0%C3%BE%1F%09%C3%A5%C2%85%C2%BC%C2%A7g%C2%8E%0C%1FGP%C2%8A%C3%8A%C3%91%1A%C3%8B%C2%B2o%C2%95%1E%C3%A5%C3%96%22ZJ*%5C%20qZ%3DZtJcz5k&input=001101000010100111101110010101&test_suite=1&test_suite_input=001101000010100111101110010101%0A11010010001001100011110111101111100%0A01011100000010000001000101000011100000011010111010%0A00010001000001000001011101110011100101010010110101010001111100101%0A10110000110101011100111100001111011010000001101110%0A000100011000001111100000100010110111001100010110010000111111%0A0000100001000010000100010001111011111011000011100010001&debug=0) Quite long, but the lookup table does take up ~~most~~ half of the space. For 117 bytes, here's the same thing without unprintables (needs ISO-8859-1, though): ``` u?q3JiH2PG+G?<3J@@c2."'Zuยฌร†WQโˆšยชN<โˆšรณ\x02โˆšรฉ\x87\x19ยฌโ„ขโˆšร…โˆšโ€ โˆšโ€ โˆšรฆ\x1f\tโˆšโ€ข\x85ยฌยบยฌรŸg\x8e\x0c\x1fGP\x8aโˆšรคโˆšรซ\x1aโˆšรฃยฌโ‰คo\x95\x1eโˆšโ€ขโˆšรฑ"ZJ*\ qZ=ZtJcz5k ``` Or, for 93 bytes, with no compression on the lookup table: ``` u?q3JiH2PG+G?<3J@@c2"OVDPYSBREXGMIWFNA-JKUTCQ/ZHL5'0+3;8-2;7);?;;1.6(4;9/;:;="ZJ*\ qZ=ZtJcz5k ``` [Answer] # JavaScript (ES6), ~~ยฌโ€ 160 158 153ยฌโ€ ~~ 149 bytes ``` s=>s.replace(m=/.{5}/g,s=>["? !YSBREXGMIWFNA-JKUTCQ/ZHLOVDP? ?!3 8-2 7) ? 1.6(4 9/ : =5'0+"[(n='0b'+s-1)<2?m^n?~(m^=1):1:m<<5|n]]).replace(/.!/g,'') ``` [Try it online!](https://tio.run/##fVFHb4MwFL73Vxgu2EoBv7R0UFyre@/dKJEoJVEqRhSqXjr@OoUYG1Il9cH2e/a37Df/w8@C8XD0bibpa5j3WZ6xzcwah6PID0IcM9v6dL7twWLR7ugcaU8329d7jwdnRw/751vm8cnd7c6V/Xx4enG/e8kR15bQmtlGqwRxhMBawcto3UYuYo5BW3oHJ8ygL0YrM4F4bR73Ev6D4x4D4oIbe57zlXS7RMnbllZIGwbJgzTJ0ii0onSA@1inFIACLcZkAShLAFGCTsjGwh@EuA8TRAmuQWIqOrNgtOIVUmqR4uoIqoswm0Up0ymuCgNAG@5FW@6luXmxRBYFAPkadUDa8Aj/@6tcSQIZVfHKUqUvxhw@@TvNaerVa@fqqKTKfwE "JavaScript (Node.js) โ€šร„รฌ Try It Online") [Answer] # [Chip](https://github.com/Phlarx/chip), 1069 bytes It's a big'n, but was quite fun to write. Takes input as a string of `"1"`'s and `"0"`'s. (Though it really only looks at the low bit.) ``` AZZZZ,-o.AZZZZ AZZZZ,o-.AZZZZ *\\\\\]oo[\/\\\**//\\\]oo[/\\\\* *\\\\/]oo[\/\\/**//\\/]oo[/\\\/* *\\\//]oo[\/\//**//\//]oo[/\\//* *\\\/\]oo[\/\/\**//\/\]oo[/\\/\* *\\//\]oo[\///\**////\]oo[/\//\* *\\///]oo[\////**/////]oo[/\///* *\\/\/]oo[\//\/**///\/]oo[/\/\/* *\\/\\]oo[\//\\**///\\]oo[/\/\\* = o--------K-----o ,oo. z---+~S ,oo. ,LooR. !ZZZZ' ,LooR. ,LLooRR. ,LLooRR. ,LLLooRRR. ,LLLooRRR. ,LLLLooRRRR. ,LLLLooRRRR. ,LLLLLooRRRRR. ,LLLLLooRRRRR. ,~Z ,LLLLLLooRRRRRR.,LLLLLLooRRRRRR.>m' |||||||oo||||||||||||||oo||||||)/Rz. xxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxx\^-^S x)x))))))))))))xx)))))))))))))xx\g xx)xxxxxxxxxxxxxxxxxxxxxxxxxxx))\f xxxxxx))xxxxxxxxxxxxx)))))))))xx\e xx)x))x)xxxxx))x)))))xxxxxxx)))x\d xx))x))xxx)))xxxxx)))xxxx)))xx)x\c xx)xx)xx))x))x)xx)xx)xx))x))x)xx\b x)))))))x)xx)xxxx)x)xx)x)xx)xx)x\a x)x)x))))))x)x))x)))x)))xx))x))x/f x)x)x))))))x)x)xxx)xxxxxxxx)x)xx/e xxxxxxxx))xxxxxx))))x)))xxx)x))x/d xxxxx))xxxxx)x)xxx)xxx))xx))xx)x/c xxx)xxx)xxxx)x)xxxxxx))xxx))x))x/b x)xxx)x)x)xx)xxxxx))x)))xx))xxxx/a ``` [Try it online!](https://tio.run/##bZDLTsMwEEX38xVhVTkkuckHgMQaVumumEqlD2CBzNKqqv56sD0zsRuYRTzH92Ye3n9@/UxT9bQJ0bSuS0kl7Fpmqm2MN@deLUJS14BwPG3NBqgBbIAawAaoAWyAGqAGbQFuAW0BbgE1gA1QA2YD1AA2QA3cAjokeEjokLBq0Ba8JnTNyPRAlYRrJZ7T14nQONeF4xyu7q9rZpaaF@fGrrqL77mamViK@dhpbWXiPIGqmYmBieWSiUkw6gturhviK70buyU/fq/owuHc5SaUDcZzR/42zIK93bbbNYV7U4S/oYD2g/75t6xr7Ik0XSi5yjFVCalRpyjq9PZAci8XPp88mLd7nsWo0fxB@07aV6TUd/7EKru0tJ9dPIw0SYjT0lI@YEIcKe@Z95WJucqBSj1XkUYhR9woV9fn0UdIVeJGoulGvhg3BHbT1A/9MAx9iuIYGLI0iHHofwE "Chip โ€šร„รฌ Try It Online") Note: Erasure uses the ASCII backspace character (`\x08`), which means that they'll look funny in TIO, but they look fine in, say, xterm. ### Basic Structure At the top, above the `=` line, is the input decoder. It turns the input into one of 32 separate signals. These are sent from the `o`'s above the `=` to those below. The triangular mountains of `L`'s and `R`'s just rotate the pattern from separate rows to columns. The grid below that translates each column to its output character. For unknown signals, NUL (`\x00`) is produced. For the special shifts, instead of printing a character, the little blob to the right changes the mode. The cable-car like thing between the two mountains suppresses any printing between each quintet, otherwise, this would attempt to decode all overlapping quintets too. Try replacing the `!` with a `*` to see this for yourself. (Running in verbose mode `-v` may also be of interest here.) I'm not sure how to make this smaller at the moment; it's already quite dense for its size. [Answer] ## Batch, ~~306~~ 304 bytes ``` @echo off set/pc= set r= set d=! !!YSBREXGMIWFNA-JKUTCQ/ZHLOVDP!! !3!8-2!7)!?!!1.6(4!9/!:!=5'0+ set s=2 :l set/an=(s^&32)+0%c:~,2%%%6*8+0x%c:~2,3%%%14 set c=%c:~5% if %n%==%s% set/as^^=35&goto l call set r=%%r%%%%d:~%n%,1%% if %r:~-1%==! set r=%r:~,-2%&goto l if not "%c%"=="" goto l echo %r% ``` Takes input on STDIN. Since Batch has no binary conversion, I have to fake it using octal and hex conversion. * The first two digits are converted from octal (I can't use decimal because the first digit might be `0`). Possible values are `00`, `01`, `10` and `11`. The latter two have value `8` and `9` but I want `2` or `3` so I take the remainder modulo `6`. * The last three digits are converted from hexadecimal. Digits are either `14` or `252` times their desired value, to I take the remainder modulo `14` (`252=14*18`). * `c` is the coded string * `r` is the result so far * `d` is the decoding array * `s` is the the index (taking the shift state into account) of the character that switches shift state * `n` is the binary decode plus bit 5 of `s`, which either equals the shift state, in which case the shift state is toggled, or indexes into the decoding array to find the next character (or ! to erase) [Answer] # PHP, 206 Bytes ``` foreach(str_split($argv[1],5)as$s)($k="# f*YSBREXGMIWFNA-JKUTCQ/ZHLOVDP#l *3#8-2#7)#?##1.6(4#9/#:#=5'0+"[32*$f+bindec($s)])=="*"?array_pop($a):($k=="f"?$f=1:($k=="l"?$f=0:($k=="#"?:$a[]=$k)));echo join($a); ``` [Answer] # GNU sed, 334 + 1 = 335 bytes +1 byte for `-r` flag. Takes input on STDIN. Looking over old challenges I realized this one would be pretty easy with sed, and good for practice. I haven't attempted any compression, so the lookup table is more than half the code. ``` s|.*|#@&;01000E211000/%00100Y310100U401100I%11100O500010f 10010J601010G711010H%00110B810110C901110F%00001 l10001-.01001X%11001Z:00101S%10101T%01101W?11101V'00011<<10011K(01011M)11011L=00111R-10111Q/01111N%11111P+10000A111110D0| : s/@([01]{5})(.*;.*\1)(..)/\3@\2\3/ t s/@;.*// s/#f /@/ s/@ l/#/ s/#(.)./\1#/ s/@.(.)/\1@/ t s/.<|[#@]//g ``` [Try it online!](https://tio.run/##VVDHUsMwFLz7Kzx4DHaYSG8TQknCIHrvnTgHGAgccsLcMN9utHKsJDrotd19K7295l9l/vEeNr/DpTIvVKOIzGJPICL7LTDoWFg@t8FwvyLsHsdguOwIh6MQDCerQszhGhiOyIPsrINhd0PIOLBN2w7HVEZTURJPMbXw0qUIbmOycReThsct0vCwQDz6fQJxmhCB85QjnG2yh5smC1xr3rigQeBqmYtk2xWyJ0XQDXJtkoFg@Nv5SxPV6KlGBpuoVGdtk7Wytg5@CLIDrW0SjUJtmJhwrCPXSVSqdAZXGJWQClPRVL8YRGao9We5VLofcA5ccCbcx7knBtXQfYVDThHVZTuBTBiViA@1rB9hAoSleE2ZI04AgMyYqNp1Xq917ipLfor6BVOfMrMdM5sn@2p07diL1KV/hD2BNzp/zX3L1JMf/QM "sed โ€šร„รฌ Try It Online") ## Explanation The code works in two phases: First, it replaces each run of 5 binary digits with the corresponding two characters (letter and figure) from a lookup table. The lookup table is in the format ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรชรฃ๏ฃฟรนรชร–๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรผรฉ๏ฃฟรนรชรฃ๏ฃฟรนรชร–โ€šร„ยถ where ๏ฃฟรนรผรฉ is a binary digit and ๏ฃฟรนรชรฃ and ๏ฃฟรนรชร– are the corresponding letter and figure, respectively. `%` stands in for missing characters (this could be any character other than newline). `FS/SP` is represented by `f<space>` and `SP/LS` is `<space>l`. `ER` is represented by `<<`. Then it steps through each pair with a "cursor" corresponding to the current modeโ€šร„รฎ`#` for letter mode, `@` for figure mode. The `#` cursor removes the second character of the pair and then advances to the next pair, and the `@` removes the first and advances. In other words, `#A1B8` becomes `A#B8` and then `AB#`, and `@A1B8` becomes `1@B8` and then `18@`. When the `#` cursor encounters `f<space>` it deletes it and replaces itself with the `@` cursor, and vice versa when `@` encounters `<space>l`. When no pairs remain, the final cursor is removed along with any characters followed by `<`. ``` # Setup: Append a lookup table to the line. # Also prepends "#" and "@" which we'll use as "cursors" later. s|.*|#@&;01000E211000/%00100Y310100U401100I%11100O500010f 10010J601010G711010H%00110B810110C901110F%00001 l10001-.01001X%11001Z:00101S%10101T%01101W?11101V'00011<<10011K(01011M)11011L=00111R-10111Q/01111N%11111P+10000A111110D0| # Phase 1 : # Using "@" as a "cursor", substitute for each run of 5 binary digits the # two corresponding characters from the lookup table. s/@([01]{5})(.*;.*\1)(..)/\3@\2\3/ t # Loop (branch to `:`) as long as substitutions are made. s/@;.*// # Delete the "@" and lookup table # Phase 2 s/#f /@/ # FS (f ) in letter mode (#); delete and switch to figure mode (@ cursor). s/@ l/#/ # LS ( l) in figure mode (@); delete and switch to letter mode (# cursor). s/#(.)./\1#/ # Letter mode; replace pair with first of pair; advance cursor. s/@.(.)/\1@/ # Figure mode; replace pair with second of pair; advance cursor. t # If any substitutions were made, branch (loop) to `:`. # Teardown s/.<|[#@]//g # Delete characters followed by < (ER) and cursor. ``` ]
[Question] [ A **[portmanteau word](https://en.wikipedia.org/wiki/Portmanteau)** is a combination of two words that takes part of each word and makes them into a single new word. For example, **lion** + **tiger** => **liger**. Let's write a program to generate portmanteaus from a pair of input words. Computers aren't the best at English, so we'll need to establish some rules to ensure that the output portmanteaus are pleasant to the eye and ear. (Examples here are shown with a separator between the prefix and suffix for clarity: `li|ger`. However, the program's actual outputs should not have a separator: `liger`.) * Each portmanteau will consist of a nonempty prefix of the first word concatenated to a nonempty suffix of the second word: yes to `li|ger`, no to `|iger`. * If the prefix ends with a vowel, the suffix must start with a consonant, and vice versa: yes to `lio|ger` or `l|er`, no to `lio|iger` or `l|ger`. **You may decide whether to count `y` as a vowel or a consonant.** Your solution must pick one option and stick with it, however. * The resulting word must not contain either of the original words in full: yes to `lio|ger`, no to `lion|iger` or `li|tiger`. + This rule holds even if the portion in question is formed from parts of both words: with input of `two` + `words`, output `tw|ords` is still illegal because it contains the substring `words`. (The only valid output for this pair would be `t|ords`.) Your program or function must take two words and output/return **a list of all pleasant portmanteaus** that can be formed from those words in that order. ## Details * [Standard input and output methods](https://codegolf.meta.stackexchange.com/q/2447/16766) apply. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/16766) are forbidden. * Words will consist only of lowercase letters (or, if you prefer, only of uppercase letters). * You may take the two input words as a list, tuple, two separate inputs, a single string with a non-letter delimiter, etc. * Output format is similarly flexible; if you return or output a string, it should be delimited such that it's clear where one portmanteau word ends and the next one begins. * There should be no delimiters inside a portmanteau word. * It's okay if your output list includes duplicate results; it's also okay to remove duplicates. ## Test cases ``` > lion, tiger < liger, ler, liger, lir, lioger, lior > tiger, lion < tion, ton, tin, tigion, tigon, tigen > spoon, fork < sork, spork, spork, spok, spoork, spook > smoke, fog < sog, smog, smog, smokog > gallop, triumph < giumph, gumph, gariumph, gamph, gaph, gah, galiumph, galumph, galliumph, gallumph, galloriumph, gallomph, galloh > breakfast, lunch < bunch, brunch, brench, brech, breh, breanch, breach, breah, breakunch, breakfunch, breakfanch, breakfach, breakfah, breakfasunch > two, words < tords > harry, ginny (if y is treated as a consonant) < hinny, hanny, hany, hay, harinny, harrinny > harry, ginny (if y is treated as a vowel) > hinny, hy, hanny, hany, harinny, hary, harrinny ``` ## Reference solution Here's a [reference solution in Pip](https://tio.run/##K8gs@P@/wqpQIbKQq7rCzzNRrRJI1Cq4eSrEuzgXK/gqVCdEJ6Zm5pfGKkDpBJCqhOg4mGgcQhiizwukrcLBJkZHucI5oNLBTke58v//nMz8PK6SzPTUov@6OQA) (treats `y` as a consonant). --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest answer in each language wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes `y` is a vowel (same byte count as consonant though). ``` ะฝฮทยจsฮธ.sยจรขส’`ะฝsฮธโ€šลพOsรฅร‹_}Jส’sยขZ_ ``` [Try it online!](https://tio.run/##AUcAuP8wNWFiMWX//9C9zrfCqHPOuC5zwqjDosqSYNC9c8644oCaxb5Pc8Olw4tffUrKknPColpf//9bJ2hhcnJ5JywnZ2lubnknXQ "05AB1E โ€“ Try It Online") or as a slightly modified [Test Suite](https://tio.run/##MzBNTDJM/V9TVqns8v/C3nPbD60oPrdDr/jQisOLTk1KuLAXyHvUMOvoPv/iw0sPd8fXep2aVKl8aFFU/P/aSqXD@xV07RQO71fS@Z@TmZ@nUJKZnlrEBSYVQAJcxQX5QOG0/KJsruLc/OxUIDOdKz0xJye/QKGkKLM0tyCDK6koNTE7LbG4RCGnNC85g6ukPF@hPL8opZgrI7GoqFIhPTMvrxIA) [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 72 bytes ``` L$w`(?<=[aeiou]()|.())((.+),(.+))\B(?!\4)(?<!\5\3)(?([aeiou])\2|\1) $`$' ``` [Try it online!](https://tio.run/##LYpBasMwEADv@4uASySyGNK0txZDLr30B1XBm1S2hWWtWMmYQP7uyCWXYRhGbHaBjuuL@mrX72ppVfPx@UPW8fyr9L1WWitVHzRu0Oasmp1502XamXdzKqKeszavd3PUULXVfjUBcPWOA2bXW4F/4hYgRS65YxkhTTzaoj305D1HzOLmKQ5wEUtjRymjn8N1gLwwLix/CQYSuWHvQrhB9JYShYyRJU9FLM3pAQ "Retina โ€“ Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 38 bytes ``` f!s}RTQm+hd_edfxFm}ed"aeiou"T*._hQ.__e ``` Input is a list of the two words, and y isn't treated as a consonant. Try it online [here](https://pyth.herokuapp.com/?code=f%21s%7DRTQm%2Bhd_edfxFm%7Ded%22aeiou%22T%2A._hQ.__e&input=%5B%22gallop%22%2C%22triumph%22%5D&debug=0&input_size=2), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=f%21s%7DRTQm%2Bhd_edfxFm%7Ded%22aeiou%22T%2A._hQ.__e&test_suite=1&test_suite_input=%5B%22lion%22%2C%20%22tiger%22%5D%0A%5B%22tiger%22%2C%20%22lion%22%5D%0A%5B%22spoon%22%2C%20%22fork%22%5D%0A%5B%22smoke%22%2C%20%22fog%22%5D%0A%5B%22gallop%22%2C%20%22triumph%22%5D%0A%5B%22breakfast%22%2C%20%22lunch%22%5D%0A%5B%22two%22%2C%20%22words%22%5D%0A%5B%22harry%22%2C%20%22ginny%22%5D&debug=0). ``` f!s}RTQm+hd_edfxFm}ed"aeiou"T*._hQ.__e Implicit: Q=eval(input()) hQ First input word ._ All prefixes of the above e Second input word (Q inferred) .__ Reverse, take all prefixes * Cartesian product of the above f Filter the above using: m T Map d in the current element using: ed The last letter of the word part } "aeiou" Is it contained in the vowel list? xF Take the XOR of the list (This ensures that the word parts meet at one consonant) m Map d in the filtered set using: +hd_ed Add the first part to the reversed second part f Filter the above using: s}RTQ Does the portmanteau contain either of the input words? ! Logical NOT (remove from list if the above is true) ``` [Answer] # Java 8, ~~228~~ ~~225~~ 215 bytes ``` v->w->{String r="",t,p=" aeiou";for(int i=w.length(),j;--i>0;)for(j=1;j<v.length();)r+=(t=v.substring(0,j)+w.substring(i)).matches(v+".*|.*"+w)|p.indexOf(t.charAt(j-1))*p.indexOf(t.charAt(j++))>0?"":t+" ";return r;} ``` Takes two Strings in currying syntax and returns a String. Treats `y` as a consonant. Try it online [here](https://tio.run/##lZCxbsMgFEVn@ysQE8Q2StYSu@rSreqQsepAHOJAbEDwbDdK8u2u3SRVqnbpBNwDh6erRScy66TRm/2gGmc9ID1mrAVVs21rSlDWsOfrhsexa9e1KlFZixDQi1AGHePoGgYQMC6dVRvUjIiswCtTvb0j4atAp5vRTbW8sBT9Ci5rUaBpmkYYkKINKEdDlxV9VhwvHPkc4xRSl2MkpLIt5lvriTKAVN6zWpoKdoSmmmeZKuacTlTnC66X3Tfl1Cc5gbxjoV2HLy@Zp5om/V2gKGWNgHInA@kSzGYnNsNJT0@OKbORH69bAqzcCf8ERGcLSmd/gSShtJg/YvwACUaYewmtN8jz8xBFfCxmdQggG2ZbYG78F2pD7gtgwrn6QHA9VoXp7QSqkh5T@g/B9clP338Ewdn7EcZe95MgiuLoHJ@HTw). Thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) for golfing 2 bytes. Ungolfed: ``` v -> w -> { // lambda taking two String parameters in currying syntax String r = "", // result t, // temporary variable used for storing // the portmanteau candidate currently being evaluated p = " aeiou"; // vowels for the purposes of this function; // the leading space is so that they all have a positive index for(int i = w.length(), j; --i > 0; ) // loop over all proper suffixes // of the second word for(j = 1; j < v.length(); ) // loop over all proper prefixes // of the first word r += // construct the portmanteau candidate (t = v.substring(0, j) + w.substring(i)) // if it contains one of the input words ... .matches(v + ".*|.*" + w) // ... or the boundary is consonant-consonant // or vowel-vowel (here we make use of the facts // that all the vowels have a positive index, and // indexOf() returns -1 in case of no match) ... | p.indexOf(t.charAt(j-1)) * p.indexOf(t.charAt(j++)) > 0 ? "" // ... reject it ... : t + " "; // ... else add it to the result return r; // return the result } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 32 bytes ``` รฅ+ รฏVw รฅ+)f_xรจ"%v$" uรƒmrรˆ+YwรƒkรธN ``` [Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=5Ssg71Z3IOUrKWZfeOgiJXYkIiB1w21yyCtZd8Nr+E4=&input=Imxpb24iICJ0aWdlciI=) Saved 10 bytes thanks to Shaggy's clearer understanding of Japt's syntax. Saved 8 bytes due to a new language feature Saved 2 byte thanks to some suggestions from ETHproductions The newest version of Japt introduced the Cartesian Product function, which saved quite a few bytes and allowed me to restore the ordering of inputs (so "lion" "tiger" outputs "liger" and such). "y" is still treated as a consonant. Explanation: ``` รฏ ) Cartesian product of... รฅ+ prefixes of first input Vw รฅ+ and suffixes of second input. f_ รƒ Remove the ones where... xรจ"%v$" the number of vowels at the joining point u is not 1. m รƒ Replace each pair with... rรˆ+Yw the prefix and suffix joined together kรธN then remove the ones that contain either input ``` [Answer] ## [Python 3](https://docs.python.org/3.6/), ~~156~~ 150 bytes I've considered `y` as a consonant. ``` lambda a,b:{a[:i]+b[j:]for i in range(1,len(a))for j in range(1,len(b))if((a[i-1]in'aeiou')^(b[j]in'aeiou'))*0**(a in a[:i]+b[j:]or b in a[:i]+b[j:])} ``` -6 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) [Try it online!](https://repl.it/repls/DraftyUnrealisticDataset) [Answer] # JavaScript (ES6), 124 bytes Takes the 2 words in currying syntax `(a)(b)` and prints the results with `alert()`. Assumes ***y*** is a consonant. ``` a=>b=>[...a].map(c=>[...b].map((C,j)=>!(w=s+b.slice(j)).match(a+'|'+b)&v.test(c)-v.test(C)&&alert(w),s+=c),s='',v=/[aeiou]/) ``` [Try it online!](https://tio.run/##VVFdbvMgEHzvKfikKgaF2icgLz1GFKmLSzAxMRaQRFXbs@fjNyV@mJmd3R2t8Amu4EarVv@2mE9xP7I7sB1nu33f93Doz7DiMVc8V/idngjb/cM35ra8d1qNAp8ICU0/Thi23U@35WRz7b1wHo/krah3stmAFtbjG6Fuy8aArOvolQ17EMpcDgO5pwHE0GgWZ7TotZEvcTtYGCjiBLFd28Qf@9dv@EUDev3mv4cPgn7QEQPBPKp2kLykINxpZZaOos4rKWxHUP6GAeloUKQTFK0SmFIYWzLybghJYU2GDzVFPoFKILOjZCGxlAy3mnzI0di5zXChpii0nyljrcxcY85mFjlGPlJyjAyT5yecy3PiToLWZk3vYNXlvE5pN6zJVFEkC4GtBhTKmEA/evohGq8xjW1s86emcg@3AuYjOJ9e9bKM6aBwD486/HlbWVQulBGqC5ULzY@9kN9qaHUj/5SL4/WP30y87Gbsp3t6Zh@dMjSBtV9xTKpl@apjYWiKNUUTVEqYwNaWTer@Hw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ยนฦคpยนรฦค}ร˜.แป‹"eโ‚ฌร˜cโป/ฦฒฦ‡แบŽโ‚ฌwรแธŸฦ’@, ``` [Try it online!](https://tio.run/##AVYAqf9qZWxsef//wrnGpHDCucOQxqR9w5gu4buLImXigqzDmGPigbsvxrLGh@G6juKCrHfDkOG4n8aSQCz/w6crL@KCrMWS4bmY//9nYWxsb3D/dHJpdW1waA "Jelly โ€“ Try It Online") **Yy** is a consonant. Both cases supported. Returns duplicates. Output has been prettified over TIO. Remove `+/โ‚ฌ` from the footer to see the actual output. [Answer] # C++ 11, ~~217~~ 202 bytes ``` [](auto v,auto w){auto r=v,t=v,p=v;r="",p="aeiou";for(int i=w.size(),j;--i;)for(j=v.size();j;)(t=v.substr(0,j)+w.substr(i)).find(v)+1|t.find(w)+1|p.find(t[j-1])<5==p.find(t[j--])<5?v:r+=t+" ";return r;} ``` Makes heavy use of `std::string#find`. Treats `y` as a consonant. Try it online [here](https://tio.run/##hZBBbsMgEEXX9SnQdAOyHSWLboxpD5JGFXVohOsAgsGWmubsLiSulCyqLtD8@cxjxO@cqw9dN8uIljjr8SgNKhkDEfN2Ry/2WF3KxE6X6sVYYTpOjNwLgCRAKm0j8A/rqTZItJhWQX8pyqqe17XmLN/0Ylxc3nNGMbfxPaCn66pn5fTbacZWH9rs6cjKzTde9ZS1u2rc9vVmx9onIW6cOjsvY@NLgSUQ4F5h9IZ4fp55UTxq0w1xr0irbdqi5PG5KGLQ5kAC7pumsxH5rZGGkn4bNCovh9A01iWB1gOE9F7@51FqQxk5FQ@ZJm17FyGFQVsDoSKA@qA8BJZH4NUA/4tYBhNyZf8ngrPLkpTx5z2xJLDmxXn@AQ). Ungolfed: ``` // lambda; relies on auto to keep declarations short [] (auto v, auto w) { // let's declare some strings. To keep it terse, we're using auto and the type of the arguments. auto r = v, // result string t = v, // temporary string for storing the portmanteau candidate p = v; // vowels string // now assign them their values r = "", // result starts empty p = "aeiou"; // vowels don't include 'y' for(int i = w.size(), j; --i; ) // suffixes of the second word for(j = v.size(); j; ) // prefixes of the first word // create the portmanteau candidate (t = v.substr(0, j) + w.substr(i)) // if it includes one of the input words ... .find(v) + 1 | t.find(w) + 1 // ... or the boundary is consonant-consonant or vowel-vowel ... | p.find(t[j - 1]) < 5 == p.find(t[j--]) < 5 ? v // ... discard it ... : r += t + " "; // ... else add it to the result. return r; // return the result } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~179~~ ~~176~~ ~~166~~ 162 bytes ``` lambda s,t:[w for w in g(s,t)if(s in w)<1>(t in w)] g=lambda s,t:s[:-1]and[s[:-1]+t[j:]for j in range(1,len(t))if(s[-2]in'aeiou')^(t[j]in'aeiou')]+g(s[:-1],t)or[] ``` [Try it online!](https://tio.run/##TU7LDoMgELz7FdwWoh70aGp/hNIEKyjWLgYwpF9PfRzqbR47M7t8w2ixTrp9pFl@ul4SX4SGR6KtI5EYJAPdFGY09TuL7FbdaTihyIb2kvK8KSshsecnygOfGrEXTfu9kzgoWhWzQhrY0cjLWhgEqYxdgT3pFrhwkW/bR9P2gHVcpMUZDERTCNFCAdG63gPL/rIZlIOCwGwsXo3OKfnW0ofDXPE1AkvpBw "Python 2 โ€“ Try It Online") 3 bytes from [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). And 10 bytes thx to [The Matt](https://codegolf.stackexchange.com/users/81432/the-matt). In my world, `y` is not a vowel. (It's a yowl!) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~113 112 109~~ 104 bytes `y` is a consonant This outputs the same duplicates as the examples in the question, I must be using the same loop ``` ->a,b,i=j=1{r=a[0,i]+b[j..-1];g=:aeiou;!g[a[i-1]]^g[b[j]]|r[a]|r[b]||z=[*z,r];b[j+=1]||a[i+=j=1]?redo:z} ``` [Try it online!](https://tio.run/##VVHBbqMwFLznK97mkm7jouaayNvTnnqolKvllUxDjAPhoQeoSsp@e/ps7JReZsYzzLONacgvt6O8Pf0xIhdOnuTmk6RRz8Lpda5OWfa00Tsrt6ZwOOx@WWWUY0v/s4pjrUdSxkOux/Eq1eNVkN5xspYbdvjjtZ@pX6g44Pb6/6YWAGpVO2wE9M4WtBLASxYC6gBRuwAYF0grLUK1Tzk2vtpPk6Zx08w0O23RpGrXoveOSJWvdswC2PxJE6YVVvf2GavCt@1Utpyff2DFUfzYmrrGlvcnN5zb0jdsUAJsJEPJMJEmDFDfs/ouZt7MRJrZ@K3KdJScClMdTdfzTxua93CW3AsBOSUuEkea0CTXJI5U3Xs8eq7NXM/kt@rCGdJjfqCAD6RDF94yiBiVhujCd3FNc/Fh6YWA0iQKGIBSREGt9EJn/shwQBhd0w58dRx65pFHM3VwVI8hyLq2dv2D3@C3zk7omkmDlLECL7B8e13CFpZ/9/u3/XJRNIfbFw "Ruby โ€“ Try It Online") [Answer] # [Emacs Lisp](https://www.gnu.org/software/emacs/manual/html_node/elisp/index.html#Top), 306 + 13 = 319 bytes *+13 for `(require'seq)`* ``` (require'seq)(lambda(a b)(dotimes(i(1-(length b)))(dotimes(j(1-(length a)))(progn(setq w(substring a 0(1+ j))x(substring b(1+ i))c(concat w x))(defun V(c)(seq-contains"aeiou"(elt c 0)'char-equal))(if(not(or(string-prefix-p a c)(string-suffix-p b c)))(if(V(substring w -1))(if(not(V x))(print c))(if(V x)(print c)))))))) ``` [Try It Online!](https://tio.run/##TY/BsoMgDEX3/YoMm4Z5w0z9GfeRRksfAgKO/r2NulCW5yYnFx7JFuNdSRumHIfwwMzT7DI/C0/6gf0cLHm/oaexexMSdBrfsbqRCzpsDHoOQ/0I1lfwvQW0B4cbC9cJFixzV2p2YQCCFzZ/8NV6vdFuZ05rizbK9QoLrLucpQy0aLWIJiNZJReKInZxVsi@goWXftoPZSOfIC9LrscQK8aMp9ykzL1bTZLbu@iEZe5P2Ak8t9pboQVMc7nao02SpO7Tx7Cgi5xvUyXFGBSoPuZ/JeAH) Defines an anonymous lambda function. Outputs a sequence of newline-separated portmanteaus with each one surrounded by quotes. Golfing tips are welcome. The letter `y` is considered a consonant. ## Ungolfed ``` (require 'seq) (defun Portmanteus(word1 word2) "Find all valid portmanteus of the two given words" (dotimes (i (1- (length word2))) (dotimes (j (1- (length word1))) (progn (setq w (substring word1 0 (1+ j)) w2 (substring word2 (1+ i)) comb (concat w w2)) (defun isVowel (c) (seq-contains "aeiou" (elt c 0) 'char-equal)) (if (not (or (string-prefix-p word1 comb) (string-suffix-p word2 comb))) (if (isVowel (substring w -1)) (if (not (isVowel w2)) (princ (format "%s\n" comb)) ) (if (isVowel w2) (princ (format "%s\n" comb)) ) ) ) ) ) ) ) ``` ]
[Question] [ In this challenge, you must design a species of single-celled organisms to fight to the death in the petri-dish arena. The arena is represented as a rectangular grid, where each cell occupies one space: ``` .....x.... ...x...o.. ...x.c..o. .......o.. ``` ## Attributes Every cell has three attributes. When specifying your cell species at the start of the game, you allocate 12 points among these attributes. * **Hit Points** (HP): If a cell's HP falls to zero, it dies. New cells have full HP. + When a cell dies, it leaves behind a corpse which can be eaten by other cells for energy. + A cell cannot regain lost HP, but it can create a new cell with full HP by dividing. * **Energy**: Most actions a cell can take require energy. By actively resting, a cell can regain lost energy up to it species' maximum. + A cell species with less than 5 energy is likely to fail, because it cannot divide to create new cells. + A cell cannot regain energy beyond its species' maximum value. + A newly created cell has an initial energy value copied from its parent (and a max value dictated by its species specification). * **Acidity**: If a cell chooses to explode, the cell's acidity level is used in calculating damage to adjacent cells. ## Actions Each turn, every cell can take one action: * **Move:** The cell moves one space in any direction (N/S/E/W/NE/NW/SE/SW) at a cost of 1 energy. + A cell cannot move onto a space occupied by another living cell. + A cell cannot move off of the grid. + Moving onto a cell corpse destroys the corpse. * **Attack:** A cell attacks an adjacent cell, dealing 1 to 3 damage, by expending 1 to 3 energy points. + A cell can attack in any direction (N/S/E/W/NE/NW/SE/SW). + It is legal to attack friendly cells. * **Divide:** The cell divides and creates a new cell on an adjacent space, at a cost of 5 energy. + A cell can divide in any direction (N/S/E/W/NE/NW/SE/SW). + The new cell has full HP according to your original cell specification. + The new cell has as much energy as its parent cell does after subtracting division cost. (For example, a parent cell with an initial 8 energy points will be reduced to 3 energy and produce a child cell with 3 energy). + A new cell cannot act until your next turn. + A cell cannot divide into an space occupied by a living cell, but it can divide into a space occupied by a dead cell corpse (this destroys the corpse). * **Eat:** A cell eats an adjacent cell corpse, gaining 4 energy. + A cell can eat in any direction (N/S/E/W/NE/NW/SE/SW). * **Rest:** A cell does nothing for one turn, regaining 2 energy. * **Explode:** When a cell has 3 or fewer HP and more energy than HP, it may choose to explode, dealing damage to all eight adjacent cells. + Damage to each adjacent cell is `(exploding cell HP) + (explodng cell acidity)` + An exploded cell dies and leaves behind a corpse, as do any cells killed in the explosion. ## Protocol ### Setup Your program will run with the string `BEGIN` provided on stdin. Your program must write to stdout a space-separated list of 3 non-negative integers, representing HP, energy, and acidity for your cell species: e.g., `5 6 1`. The numbers must sum to 12. Acidity may be `0`, if you wish. (Other attributes may also be zero, but doing so functionally forfeits the game!) You begin with one cell, in the northwest or southeast corner, one space away from either edge. The beginning cell has full HP and energy. ### Every cells acts Every turn, your program will be invoked once for every cell alive on your team (except cells just created this turn) so that cell can act. Your program is provided with data on stdin that includes the petri dish state and information about this particular cell: ``` 10 4 .......... ..xx.c.... ...c...o.. ......o... 6 3 5 7 ``` The first two numbers indicate arena width and height: here, there is a 10-by-4 arena. * The `o` cells are yours; the `x` cells are your enemies. (This is always true; each player always sees their own cells as `o`.) * The `.` spaces are empty. * The `c` spaces represent edible cell corpses. The numbers after the empty line represent info about this cell: * The first two numbers are `x,y` coordinates, indexed from `0,0` in the top left (so `6 3` here refers to the south-most `o` cell). * The third number is the cell's HP; the fourth number is the cell's energy. Your program should output (to stdout) an action. In the examples below, we'll use `N` as an example direction, but it can be any direction legal for that action (`N`/`S`/`E`/`W`/`NE`/`NW`/`SE`/`SW`). All program output is case-insensitive, but examples will use uppercase. Any output action that is invalid (either because it has invalid syntax or attempts an illegal action) is ignored and results in the cell `REST`ing (and thus gaining 2 energy). * `MOVE N` * `DIVIDE N` * `EAT N` * `ATTACK N 2` - the number represents the strength of the attack (1 - 3) * `REST` * `EXPLODE` Your team's turn consists of all your cells being given an opportunity to act, one by one. All of your cells act before any of the opponent's cells act. Once all of your cells act, your turn ends, and your opponent's turn begins. Once all your opponent's cells act, your turn begins again. Within your turn, each cell is given priority to act based on its age: the oldest cells on your team act first before younger cells. ## Example Here's how a program might behave. Input from stdin is denoted here with leading `>` arrows (separated from actual input by a clarifying space) and output on stdout has `<` arrows. ``` > BEGIN < 5 6 1 ``` Then, the program is invoked again: ``` > 10 4 > .......... > .o........ > ........x. > .......... > > 1 1 5 6 < DIVIDE SE ``` After your opponent's turn (who decided to `DIVIDE W` with the single starting cell), your program is invoked twice, once for each cell: ``` > 10 4 > .......... > .o........ > ..o....xx. > .......... > > 1 1 5 1 < MOVE E ``` For the second invocation on your turn: ``` > 10 4 > .......... > ..o....... > ..o....xx. > .......... > > 2 2 5 1 < MOVE SE ``` Note this second cell sees the updated board state based on the other cell's movement earlier in your turn. Also note this cell has been created with 1 energy, because the parent cell had 6 energy when it performed division last turn (so the original 6, minus the 5-energy cost of division, created a child cell with 1 energy). Now your turn is over and your opponent's turn begins. The two opposing cells will be given a chance to act, and then your next turn begins. ## Victory You can win by either: * Destroying all opposing cells, or * Having more cells than your opponent after each player has completed 150 turns Scoring will be based on number of wins in 100 games against each other submission. In half of the simulations, your program will be allowed to go first. Tie games (i.e. exactly the same number of cells after 150 turns, or the only remaining cells are killed together in an explosion) are not counted in either player's win totals. ## Other information * Your program should not attempt to maintain state (beyond using the state of the Petri dish): monocellular organisms do not have a very good memory and react to the world moment by moment. In particular, writing to a file (or other data store), communicating with a remote server, or setting environment variables are explicitly disallowed. * Submissions will be run/compiled on Ubuntu 12.04.4. * The specifics of the 100 scoring games are not yet confirmed, but they will likely involve multiple arena sizes (for example, 50 runs on a small arena and 50 runs on a larger arena). For a larger arena, I may increase the max turn count to ensure that a proper battle can take place. ## Resources [Here is the driver code](https://gist.github.com/apsillers/c996e808bb9bef6777c0) that runs the simulation, written for Node.js, called by `node petri.js 'first program' 'second program'`. For example, pitting a Python-written cell against a Java-written cell might look like `node petri.js 'python some_cell.py' 'java SomeCellClass'`. Additionally, I understand that reading and parsing multiple lines on stdin can be a huge pain, so I've drafted a few complete sample cells in different languages which you are free to build upon, completely overhaul, or ignore entirely. * [Java cell](https://gist.github.com/apsillers/bbe1a22ba62fd059400f) * [Python cell](https://gist.github.com/apsillers/f181e7298af12b72da46) * [JavaScript cell](https://gist.github.com/apsillers/eacf6101cc829e36138b) (for use with Node.js) Of course you are free to write a cell in a different language; these are simply three languages I decided to write boilerplate code for as a time-saving aid. If you have any problems running the driver, feel free to ping me in [the chat room I've created for this challenge](http://chat.stackexchange.com/rooms/15696/battle-for-the-petri-dish-discussion). If you don't have sufficient reputation for chat, then just leave a comment. [Answer] Here's my relatively simple bot, which I programmed in Ruby. Basically, it prioritizes dividing first, and attempts to divide towards enemies in order to gain control over the field. Its second priority is eating, and third is attacking. It easily beat the sample Python cell. ``` def surroundingCells(x, y) result = Hash.new if x >= 1 if y >= 1 # northwest result["NW"] = $petriDish[x - 1][y - 1] end if y < ($sizeY - 1) # $sizeY - 1 is the farthest south square # southwest result["SW"] = $petriDish[x - 1][y + 1] end # west result["W"] = $petriDish[x - 1][y] end if x < ($sizeX - 1) if y >= 1 # northeast result["NE"] = $petriDish[x + 1][y - 1] end if y < ($sizeY - 1) # southeast result["SE"] = $petriDish[x + 1][y + 1] end # east result["E"] = $petriDish[x + 1][y] end # north result["N"] = $petriDish[x][y - 1] if y >= 1 # south result["S"] = $petriDish[x][y + 1] if y < ($sizeY - 1) return result end def directionTowardsEnemies(locX, locY) totalXDirections = 0 totalYDirections = 0 totalTargetsFound = 0 # enemies or corpses optimalDirections = [] for x in 0..($petriDish.length - 1) for y in 0..($petriDish[0].length - 1) if $petriDish[x][y] == 'c' or $petriDish[x][y] == 'x' totalXDirections += (x - locX) totalYDirections += (y - locY) totalTargetsFound += 1 end end end if totalXDirections == 0 if totalYDirections > 0 optimalDirections << "S" << "SE" << "SW" else optimalDirections << "N" << "NE" << "NW" end return optimalDirections end if totalYDirections == 0 if totalXDirections > 0 optimalDirections << "E" << "NE" << "SE" else optimalDirections << "W" << "NW" << "SW" end return optimalDirections end if totalXDirections > 0 if totalYDirections > 0 optimalDirections << "SE" if totalYDirections > totalXDirections optimalDirections << "S" << "E" else optimalDirections << "E" << "S" end else optimalDirections << "NE" if -totalYDirections > totalXDirections optimalDirections << "N" << "E" else optimalDirections << "E" << "N" end end return optimalDirections end if totalXDirections < 0 if totalYDirections > 0 optimalDirections << "SW" if totalYDirections > -totalXDirections optimalDirections << "S" << "W" else optimalDirections << "W" << "S" end else optimalDirections << "NW" if -totalYDirections > -totalXDirections optimalDirections << "N" << "W" else optimalDirections << "W" << "N" end end end return optimalDirections end firstLine = gets if firstLine == "BEGIN" puts "5 7 0" exit 0 end $sizeX, $sizeY = firstLine.split(' ')[0].to_i, firstLine.split(' ')[1].to_i $petriDish = Array.new($sizeX) { Array.new($sizeY) } for y in 0..($sizeY - 1) line = gets chars = line.split('').reverse.drop(1).reverse # this gets every character but the last for x in 0..(chars.length - 1) $petriDish[x][y] = chars[x] end end gets # blank line info = gets locX = info.split(' ')[0].to_i locY = info.split(' ')[1].to_i hp = info.split(' ')[2].to_i energy = info.split(' ')[3].to_i # dividing is our first priority if(energy >= 5) # try to divide towards enemies dirs = directionTowardsEnemies(locX, locY) directions = { "N" => [0, -1], "NE" => [1, -1], "E" => [1, 0], "SE" => [1, 1], "S" => [0, 1], "SW" => [-1, 1], "W" => [-1, 0], "NW" => [-1, -1] } for dir in dirs potentialNewX = locX + directions[dir][0] potentialNewY = locY + directions[dir][1] if $petriDish[potentialNewX][potentialNewY] == '.' puts "DIVIDE #{dir}" exit 0 end end # otherwise, just divide somewhere. surroundingCells(locX, locY).each do |k, v| if v == '.' puts "DIVIDE #{k}" exit 0 end end end # next, eating surroundingCells(locX, locY).each do |k, v| if v == 'c' puts "EAT #{k}" exit 0 end end # next, attacking surroundingCells(locX, locY).each do |k, v| attackStrength = 0 if (energy > 5) then # we want to save energy for dividing attackStrength = [(energy - 5), 3].min else attackStrength = [energy, 3].min end if v == 'x' puts "ATTACK #{k} #{attackStrength}" exit 0 end end # otherwise, rest puts "REST" ``` [Answer] # Amoeba First splits into four and then tries to get to the middle ground to limit the opponents replication space. Then starts replicating. When moving or replicating, finds the optimal path to the closest enemy, and moves or divides towards it, to try to cut off the enemy available space. If an enemy is adjacent or one space away, will always attack or move towards it, allowing the row behind doing nothing to fill any empty spaces. I haven't tested this against any other submissions so have no idea how well it will do. ``` var MAX_HP = 2; var MAX_ENERGY = 10; var ACIDITY = 0; function PathfindingNode(_x, _y, _prevNode, _distance, _adjacentEnemies) { this.x = _x; this.y = _y; this.prevNode = _prevNode; this.distance = _distance; this.adjacentEnemies = _adjacentEnemies; } PathfindingNode.prototype.GetDistance = function() { return this.distance; } var evaluatedNodes = {}; var initialNode = {}; var firstEval = true; function evaluateNode(x, y, arena) { //get surrounding reachable nodes that havent already been checked var adjacentEmpties = arena.getAdjacentMatches(arena.get(x, y), [".", "c"]); //if this node is adjacent to the start node - special case because the start node isnt an empty if (firstEval) adjacentEmpties.push({ 'x': initialNode.x, 'y': initialNode.y }); //find the optimal node to reach this one var prevNode = null; for (var i in adjacentEmpties) { if(evaluatedNodes[adjacentEmpties[i].x + "," + adjacentEmpties[i].y]) { var currentNode = evaluatedNodes[adjacentEmpties[i].x + "," + adjacentEmpties[i].y]; if (!prevNode) { prevNode = currentNode; } else { if(currentNode.GetDistance() < prevNode.GetDistance()) { prevNode = currentNode; } } } } var adjacentEnemies = arena.getAdjacentMatches(arena.get(x, y), ["x"]); var newNode = new PathfindingNode(x, y, prevNode, prevNode.GetDistance() + 1, adjacentEnemies.length); evaluatedNodes[x + "," + y] = newNode; } function evaluateNeighbours(arena) { //breadth first search all reachable cells var nodesToEvaluate = []; for (var i in evaluatedNodes) { var emptyNodes = arena.getAdjacentMatches(arena.get(evaluatedNodes[i].x, evaluatedNodes[i].y), [".", "c"]); //only ones that havent already been eval'd for (var j in emptyNodes) if (!evaluatedNodes[emptyNodes[j].x + "," + emptyNodes[j].y]) nodesToEvaluate.push(emptyNodes[j]) } //have all available nodes been evaluated if (nodesToEvaluate.length === 0) return false; for (var i in nodesToEvaluate) { evaluateNode(parseInt(nodesToEvaluate[i].x), parseInt(nodesToEvaluate[i].y), arena) } firstEval = false; return true; } function getAllReachableNodes(arena, cell) { //return a list of all reachable cells, with distance and optimal path evaluatedNodes = {}; //add the first node to get started var adjacentEnemies = arena.getAdjacentMatches(arena.get(cell.x, cell.y), ["x"]); var newNode = new PathfindingNode(parseInt(cell.x), parseInt(cell.y), null, 0, adjacentEnemies.length); evaluatedNodes[cell.x + "," + cell.y] = newNode; initialNode.x = parseInt(cell.x); initialNode.y = parseInt(cell.y); firstEval = true; while (evaluateNeighbours(arena)) ; return evaluatedNodes; } function passedMiddleGround(arena) { for (var i = (parseInt(arena.width) / 2) - 1; i < parseInt(arena.width); i++) { for(var j = 0; j < parseInt(arena.height); j++) { if (arena.get(i, j).symbol == "o") return true; } } return false; } function decide(arena, cell, outputCallback) { var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]); var nearbyEnemies = arena.getAdjacentMatches(cell.point, ["x"]); var nearbyCorpses = arena.getAdjacentMatches(cell.point, ["c"]); if (nearbyEnemies.length > 4 && cell.energy >= cell.hp && cell.hp <= 3) { outputCallback("EXPLODE"); return; } //attack whenever we get the chance. leave the replication to the cells doing nothing if (cell.energy > 0 && nearbyEnemies.length > 0){ outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length * Math.random()) | 0]) + " " + Math.min(cell.energy, 3)); return; } //if we are close to an enemy, move towards it. let the back line fill the new space if (cell.energy > 2) { for (var i = 0; i < nearbyEmpties.length; ++i) { var space = nearbyEmpties[i]; if (arena.getAdjacentMatches(space, ["x"]).length) { outputCallback("MOVE " + arena.getDirection(cell, space)); return; } } } //yum if (nearbyCorpses.length > 0) { outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length * Math.random()) | 0])); return; } //until we pass the middle ground, just keep moving into tactical position. afterwards we can start replication if (passedMiddleGround(arena) && cell.energy < 5 && nearbyEmpties.length > 0) { outputCallback("REST"); return; } //try to block the opponent cells - interrupt their replication //if we have enough energy to move, choose the best spot if (nearbyEmpties.length > 0 && ((cell.energy >= 2 && nearbyEnemies.length == 0) || cell.energy >= 5)) { var nextMove = null; if (nearbyEmpties.length === 1) { nextMove = nearbyEmpties[0]; } else { var reachableNodes = getAllReachableNodes(arena, cell); //select nodes that have an adjacent enemy var enemyAdjacentNodes = {}; var enemyNodesReachable = false; for (var node in reachableNodes) { if (reachableNodes.hasOwnProperty(node) && reachableNodes[node].adjacentEnemies > 0) { enemyAdjacentNodes[node] = reachableNodes[node]; enemyNodesReachable = true; } } if (enemyNodesReachable) { //if there are any then select the closest one var closest = null; for (var node in enemyAdjacentNodes) { if(!closest) { closest = enemyAdjacentNodes[node]; } else{ if(enemyAdjacentNodes[node].GetDistance() < closest.GetDistance()) { closest = enemyAdjacentNodes[node]; } } } //select the first move of the nodes path //trace the selected node back to the first node to select the first move towards the cell. while (closest.prevNode != null && closest.prevNode.prevNode != null) { closest = closest.prevNode; } nextMove = arena.get(closest.x, closest.y); } } //a path to the enemy was found if(nextMove) { //do this until we get half way across the board, then we just replicate if (!passedMiddleGround(arena)) { if (cell.energy >= 5) { outputCallback("DIVIDE " + arena.getDirection(cell, nextMove)); return; } outputCallback("MOVE " + arena.getDirection(cell, nextMove)); return; } else { outputCallback("DIVIDE " + arena.getDirection(cell, nextMove)); return; } } } //if theres no path to an enemy available, just divide anywhere if (cell.energy >= 5 && nearbyEmpties.length > 0) { outputCallback("DIVIDE " + arena.getDirection(cell, nearbyEmpties[(nearbyEmpties.length * Math.random()) | 0])); return; } outputCallback("REST"); return; } var input = ""; // quiet stdin EPIPE errors process.stdin.on("error", function(err) { log("slight error: " + err); }); process.stdin.on("data", function(data) { input += data; }); process.stdin.on("end", function() { if(input == "BEGIN") { // output space-separated attributes process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" ")); clearLog(); } else { // read in arena and decide on an action var arena = new Arena(); var lines = input.split("\n"); var dimensions = lines[0].split(" ").map(function(d) { return parseInt(d); }); arena.width = dimensions[0]; arena.height = dimensions[1]; for(var y=1; y<=dimensions[1]; ++y) { for(var x=0; x<lines[y].length; ++x) { arena.set(x, y-1, lines[y][x]); } } var stats = lines[dimensions[1]+2].split(" "); var cell = { x: stats[0], y: stats[1], hp: stats[2], energy: stats[3], point: arena.get(stats[0], stats[1]) }; // decide on an action and write the action to stdout decide(arena, cell, function(output) { process.stdout.write(output); }) } }); var Arena = function() { this.dict = {}; }; Arena.prototype = { // get Point object get: function(x,y) { if(!this.dict[x+","+y]) return 'w'; return this.dict[x+","+y]; }, // store Point object set: function(x,y,d) { this.dict[x+","+y] = new Point(x,y,d); }, // get an array of all Points adjacent to this one whose symbol is contained in matchList // if matchList is omitted, return all Points getAdjacentMatches: function(point, matchList) { var result = []; for(var i=-1; i<=1; ++i) { for(var j=-1; j<=1; ++j) { var inspectedPoint = this.get(point.x+i, point.y+j); if(inspectedPoint && (i!=0 || j!=0) && (!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) { result.push(inspectedPoint); } } } return result; }, // return the direction from point1 to point2 getDirection: function(point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; dx = Math.abs(dx) / (dx || 1); dy = Math.abs(dy) / (dy || 1); c2d = { "0,0":"-", "0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W", "-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" }; return c2d[dx + "," + dy]; } } var Point = function(x,y,d) { this.x = x; this.y = y; this.symbol = d; } Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ")"; } ``` [Answer] Simple cell done in `node.js`. Tested it agains examples node cell and against Kostronor it beats them. **Update** Still fairly simple, try to move towards enemy or divide. ``` // used in defining cell spec var MAX_HP = 4; var MAX_ENERGY = 8; var ACIDITY = 0; function decide(arena, cell, outputCallback) { var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]); var nearbyEnemies = arena.getAdjacentMatches(cell.point, ["x"]); var nearbyCorpses = arena.getAdjacentMatches(cell.point, ["c"]); var nearbyFriends = arena.getAdjacentMatches(cell.point, ["o"]); if (nearbyFriends.length >= 8) { outputCallback("REST"); return; } if (nearbyFriends.length >= 7 && nearbyEnemies.length < 0 && nearbyCorpses.length > 0 && energy < MAX_ENERGY) { outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0])); return; } // if you have two or more nearby enemies, explode if possible if(nearbyEnemies.length >= 1 && cell.energy >= cell.hp && cell.hp <= 1 && nearbyEnemies.length > nearbyFriends.length) { outputCallback("EXPLODE"); return; } // if you have two or more nearby enemies, explode if possible if(nearbyEnemies.length >= 3 && cell.energy >= cell.hp && nearbyEnemies.length > nearbyFriends.length) { outputCallback("EXPLODE"); return; } // if you have the energy and space to divide, do it if(cell.energy >= 5 && nearbyEmpties.length > 0) { var ed = arena.getEnemyDirection(cell); if (nearbyEmpties.indexOf(ed) >= 0 && Math.random() < 0.5){ outputCallback("DIVIDE " + ed); } else{ outputCallback("DIVIDE " + arena.getDirection(cell, nearbyEmpties[(nearbyEmpties.length*Math.random())|0])); } return; } // if at least one adjacent enemy, attack if possible if(cell.energy > 0 && nearbyEnemies.length > 0) { outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length*Math.random())|0]) + " " + Math.min(cell.energy, 3)); return; } if (Math.random() < 0.5) { for(var i=0; i<nearbyEmpties.length; ++i) { outputCallback("MOVE " + arena.getEnemyDirection(cell)); return; } } if (nearbyEmpties.length > 0 && nearbyEnemies.length <= 6) { outputCallback("REST"); // because next turn is divide time return; } // if there's a nearby corpse, eat it if your energy is below max if(nearbyCorpses.length > 0) { outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0])); return; } outputCallback("REST"); return; } var input = ""; // quiet stdin EPIPE errors process.stdin.on("error", function(err) { console.log("slight error: " + err); }); process.stdin.on("data", function(data) { input += data; }); process.stdin.on("end", function() { if(input == "BEGIN") { // output space-separated attributes process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" ")); } else { // read in arena and decide on an action var arena = new Arena(); var lines = input.split("\n"); var dimensions = lines[0].split(" ").map(function(d) { return parseInt(d); }); arena.width = dimensions[0]; arena.height = dimensions[1]; for(var y=1; y<=dimensions[1]; ++y) { for(var x=0; x<lines[y].length; ++x) { arena.set(x, y-1, lines[y][x]); } } var stats = lines[dimensions[1]+2].split(" "); var cell = { x: stats[0], y: stats[1], hp: stats[2], energy: stats[3], point: arena.get(stats[0], stats[1]) }; // decide on an action and write the action to stdout decide(arena, cell, function(output) { process.stdout.write(output); }) } }); var Arena = function() { this.dict = {}; }; Arena.prototype = { // get Point object get: function(x,y) { return this.dict[x+","+y]; }, // store Point object set: function(x,y,d) { this.dict[x+","+y] = new Point(x,y,d); }, // get an array of all Points adjacent to this one whose symbol is contained in matchList // if matchList is omitted, return all Points getAdjacentMatches: function(point, matchList) { var result = []; for(var i=-1; i<=1; ++i) { for(var j=-1; j<=1; ++j) { var inspectedPoint = this.get(point.x+i, point.y+j); if(inspectedPoint && (i!=0 || j!=0) && (!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) { result.push(inspectedPoint); } } } return result; }, // return the direction from point1 to point2 getDirection: function(point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; dx = Math.abs(dx) / (dx || 1); dy = Math.abs(dy) / (dy || 1); c2d = { "0,0":"-", "0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W", "-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" }; return c2d[dx + "," + dy]; }, getEnemyDirection: function(p) { for (var i = 0; i < this.width; i++) { for (var j = 0; j < this.height; j++) { var found = this.get(i,j); if (found != null && found.symbol == "x") { return this.getDirection(p, found); } } } return "N"; //should never happen } } var Point = function(x,y,d) { this.x = x; this.y = y; this.symbol = d; } Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ")"; } ``` [Answer] # Evolution This submission has evolved and is no longer a simple singe-cell organism! It tries to attack/explode whenever possible, otherwise it divides or moves towards the enemy. Moving should solve the problem of a cell surrounded by friendly cells with max energy, unable to do something useful. After moving there is always 3 energy left to hit the enemy as hard as possible. ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class Evolution { public static final int MAX_HP = 4; public static final int MAX_ENERGY = 8; public static final int ACIDITY = 0; // given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S") public static String decide(Arena arena, Point cell, int hp, int energy) { ArrayList<Point> nearbyEmpty = arena.getAdjacentMatches(cell, "."); ArrayList<Point> nearbyEnemies = arena.getAdjacentMatches(cell, "x"); ArrayList<Point> nearbyCorpses = arena.getAdjacentMatches(cell, "c"); ArrayList<Point> nearbyFriends = arena.getAdjacentMatches(cell, "o"); // more than 1 enemy around => explode if possible and worth it if(nearbyEnemies.size() > 1 && energy > hp && hp <= 3 && nearbyEnemies.size() > nearbyFriends.size()) { return "EXPLODE"; } // enemies around => always attack with max strength if(energy > 0 && nearbyEnemies.size() > 0) { int attackStrength = Math.min(energy, 3); Point enemy = nearbyEnemies.get(0); return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength; } // safe spot => divide if possible if(energy >= 5 && nearbyEmpty.size() > 0) { Point randomEmpty = nearbyEmpty.get((int)Math.floor(nearbyEmpty.size()*Math.random())); return "DIVIDE " + arena.getDirection(cell, randomEmpty); } // nearby corpse and missing energy => eat if(nearbyCorpses.size() > 0 && energy < MAX_ENERGY) { Point corpse = nearbyCorpses.get(0); return "EAT " + arena.getDirection(cell, corpse); } // move towards enemy => constant flow of attacks if(energy == 4) { return "MOVE " + arena.getEnemyDirection(cell); } return "REST"; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String firstLine; firstLine = br.readLine(); if(firstLine.equals("BEGIN")) { System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY); } else { String[] dimensions = firstLine.split(" "); int width = Integer.parseInt(dimensions[0]); int height = Integer.parseInt(dimensions[1]); Point[][] arena = new Point[height][]; String input; int lineno = 0; while(!(input=br.readLine()).equals("")) { String[] charList = input.substring(1).split(""); arena[lineno] = new Point[width]; for(int i=0; i<charList.length; ++i) { arena[lineno][i] = new Point(i, lineno, charList[i]); } lineno++; } String[] stats = br.readLine().split(" "); int x = Integer.parseInt(stats[0]); int y = Integer.parseInt(stats[1]); int hp = Integer.parseInt(stats[2]); int energy = Integer.parseInt(stats[3]); Arena arenaObj = new Arena(arena, width, height); System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy)); } } public static class Arena { public Point[][] array; public HashMap<String, String> c2d; public int height; public int width; public Arena(Point[][] array, int width, int height) { this.array = array; this.width = width; this.height = height; this.c2d = new HashMap<String, String>(); this.c2d.put("0,0", "-"); this.c2d.put("0,-1", "N"); this.c2d.put("0,1", "S"); this.c2d.put("1,0", "E"); this.c2d.put("-1,0", "W"); this.c2d.put("-1,-1", "NW"); this.c2d.put("1,-1", "NE"); this.c2d.put("-1,1", "SW"); this.c2d.put("1,1", "SE"); } // get the character at x,y // or return empty string if out of bounds public Point get(int x, int y) { if(y < 0 || y >= this.array.length){ return null; } Point[] row = this.array[y]; if(x < 0 || x >= row.length) { return null; } return row[x]; } // get arraylist of Points for each adjacent space that matches the target string public ArrayList<Point> getAdjacentMatches(Point p, String match) { ArrayList<Point> result = new ArrayList<Point>(); for(int i=-1; i<=1; ++i) { for(int j=-1; j<=1; ++j) { Point found = this.get(p.x+i, p.y+j); if((i!=0 || j!=0) && found != null && found.symbol.equals(match)) { result.add(found); } } } return result; } // get the direction string from point 1 to point 2 public String getDirection(Point p1, Point p2) { int dx = p2.x - p1.x; int dy = p2.y - p1.y; dx = Math.abs(dx) / (dx==0?1:dx); dy = Math.abs(dy) / (dy==0?1:dy); return this.c2d.get(dx + "," + dy); } public String getEnemyDirection(Point p) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Point found = this.get(x,y); if (found != null && found.symbol.equals("x")) { return getDirection(p, found); } } } return "N"; //should never happen } } public static class Point { int x, y; String symbol; public Point(int x, int y, String sym) { this.x=x; this.y=y; this.symbol=sym; } } } ``` [Answer] ## Berserker Because I used Clojure, which has some limitations, mainly the huge startup time, I took a little liverty. When the program is given `BEGIN` it outputs `4 6 2 LOOP`, indicating that it doesn't stop. Then it takes the inputs as a continuous stream and ends with `END`. It doesn't save any state, which is made clear by not using any global variables or reusing return values. Because the implementation for this loopy action hasn't been done yet, I couldn't fully test the code (I hope the code is clear enough). The cell gained it's name from it's nature of exploding whenever possible (and thus having acidity) and by prioritising attacking right after dividing. I uploaded the generated jar-file to my [Dropbox](https://dl.dropboxusercontent.com/u/22984741/codegolf/petridish-clojure.jar). Run with `java -jar petridish-clojure.jar` Just to clarify: ``` > BEGIN < 4 6 2 LOOP > 10 4 > .......... > ..xx.c.... > ...c...O.. > ......o... > > 3 4 6 < DIVIDE NW > 10 4 > .......... > ..xx.c.... > ...c.o.o.. > ......o... > > 5 2 4 1 < EAT N > END ``` ``` (ns petridish.core (:require [clojure.string :as s]) (:gen-class)) (def ^:const maxhp 4) (def ^:const maxenergy 6) (def ^:const acidity 2) (defn str->int [x] (if (empty? x) 0 (Integer. (re-find #"\d+" x)))) (defn sum-vectors [vec1 vec2] (vec (map #(vec (map + % vec2)) vec1))) (defn find-adjacent [[width height] board pos target] (let [cells (sum-vectors [[-1 -1] [0 -1] [1 -1] [-1 0] [1 0] [-1 1] [0 1] [1 1]] pos) directions ["NW" "N" "NE" "W" "E" "SW" "S" "SE"]] (for [cell cells :when (and (> width (cell 0) -1) (> height (cell 1) -1) (= target (get-in board (reverse cell))))] (directions (.indexOf cells cell))))) (defn decide [size board [x y hp energy]] (let [friends (find-adjacent size board [x y] \o) enemies (find-adjacent size board [x y] \x) corpses (find-adjacent size board [x y] \c) empty (find-adjacent size board [x y] \.)] (cond (and (<= hp 3) (> energy hp) (seq enemies)) "EXPLODE" (and (>= energy 5) (seq empty)) (str "DIVIDE " (first empty)) (and (>= energy 3) (seq enemies)) (str "ATTACK " (first enemies) " " (min 3 energy)) (and (< energy maxenergy) (seq corpses)) (str "EAT " (first corpses)) (or (and (<= 5 energy maxenergy) (not (seq empty))) (< energy 5)) "REST" (seq empty) (str "MOVE " (rand-nth empty))))) (defn read-board [[width height]] (let [result (vec (for [i (range height)] (read-line)))] (read-line) ; Skip the empty line result)) (defn reader [] (loop [] (let [firstline (read-line)] (when (not= firstline "END") (println (if (= firstline "BEGIN") (str maxhp " " maxenergy " " acidity " LOOP") (let [size (map str->int (s/split firstline #"\s+")) board (read-board size) status (map str->int (s/split (read-line) #"\s+"))] (decide size board status)))) (recur))))) (defn -main [] (reader)) ``` --- Update log ``` 1. Fixed the logic a little and removed redundancies. ``` [Answer] ## Hungry, hungry bot Here is an entry in R. I hope I understood correctly what were the technical specs on how to communicate with your program. Should be triggered with `Rscript Hungryhungrybot.R`. If it has at least 6 of energy it divides, preferentially in the direction of the enemy. Otherwise it eats whatever's next to it or whatever's reachable. If no food is reachable then it will either explode when there is more enemies around than sister cells, or fight with nearby enemies. Rests only if energy is 0 and nothing to eat is available. ``` infile <- file("stdin") open(infile) input1 <- readLines(infile,1) if(input1=="BEGIN"){ out <- "4 7 1" }else{ nr <- as.integer(strsplit(input1," ")[[1]][2]) nc <- as.integer(strsplit(input1," ")[[1]][1]) input2 <- readLines(infile, 2+as.integer(nr)) arena <- do.call(rbind,strsplit(input2[1:nr],"")) stats <- strsplit(input2[nr+2]," ")[[1]] coords <- as.integer(stats[2:1])+1 hp <- as.integer(stats[3]) nrj <- as.integer(stats[4]) closest <- function(coords,arena,object){ a <- which(arena==object,arr.ind=TRUE) if(length(a)){ d <- apply(a,1,function(x)max(abs(x-coords))) b <- which.min(d) f <- a[b,] dir <- f-coords where <- "" if(dir[1]<0)where <- paste(where,"N",sep="") if(dir[1]>0)where <- paste(where,"S",sep="") if(dir[2]<0)where <- paste(where,"W",sep="") if(dir[2]>0)where <- paste(where,"E",sep="") dist <- d[b] }else{dist <- NA; where <- ""} list(dist,where) } near <- expand.grid((coords[1]-1):(coords[1]+1),(coords[2]-1):(coords[2]+1)) near <- near[near[,1]<=nr&near[,2]<=nc,] adjacent <- t(matrix(apply(near,1,function(x)arena[x[1],x[2]]),nr=3,byrow=TRUE)) w <- matrix(c('NW','N','NE','W','','E','SW','S','SE'),nr=3,byrow=TRUE) if(coords[1]==1) w <- w[-1,] if(coords[1]==nr) w <- w[-3,] if(coords[2]==1) w <- w[,-1] if(coords[2]==nc) w <- w[,-3] if(any(arena=="c")){food <- closest(coords,arena,"c")}else{food <- list(nrj+2,"")} enemies <- closest(coords,arena,"x") if(nrj>=6){ empties <- w[adjacent=="."] if(!length(empties)){ if(sum(adjacent=="x")>sum(adjacent=="o") & hp<=3 & nrj>=hp){ out <- "EXPLODE" }else{out <- "REST"} }else if(enemies[[2]]%in%empties & enemies[[1]]!=1){ out <- paste("DIVIDE", enemies[[2]]) }else{ out <- paste("DIVIDE", empties[1]) } }else{ if(nrj==0 & !any(adjacent=="c")){ out <- "REST" }else{ if(any(adjacent=="c")){ out <- paste("EAT",w[adjacent=="c"][1]) }else if(any(arena=="c") & food[[1]]<=(nrj+1)){ out <- paste("MOVE",food[[2]]) }else if(sum(adjacent=="x")>sum(adjacent=="o") & hp<=3 & nrj>=hp){ out <- "EXPLODE" }else if(any(adjacent=="x")){ out <- paste("ATTACK",w[adjacent=="x"][1],max(nrj,3)) }else{ out <- paste("MOVE", enemies[[2]]) } } } } cat(out) flush(stdout()) ``` [Answer] ### Coordinated Bacteria I hope I'm not too late. Win against other opponents (and always by killing them all -- after many rounds), in my tests, and the battle will never end if it faces itself, an evidence that the strategy is strong. Always win within the 150 rounds limit, and if continued indefinitely will always kill all. When you are single-celled, you can memorize previous state, but you can exploit your own position to behave differently! =) This will divide the bacteria into divider and mover, and in doing so will keep more bacteria useful instead of just the front line, while keeping the defense line up. It also coordinates its attacks to focus on specific enemy, so that enemies get killed faster (this is to face my other single-cell which focuses on HP). In mid-game, which is detected by the number of cells on the board, they will try to shove into enemy territory by out-flanking them. This is the key winning strategy. This has the highest growth rate compared to all other opponents currently, but it has a slow start, so this works better on large arena. Run it with `java CoordinatedBacteria` ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; public class CoordinatedBacteria { public static final int MAX_HP = 6; public static final int MAX_ENERGY = 6; public static final int ACIDITY = 0; // given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S") public static String decide(final Arena arena, Point cell, int hp, int energy) { // empty and corpses are free for movement and division final Point2D enemyCenter = arena.getCenterOf("x"); final Point2D ourCenter = arena.getCenterOf("o"); final int moverPos = (enemyCenter.x <= ourCenter.x || enemyCenter.y <= ourCenter.y) ? (arena.width+arena.height+1)%2 : 1; final int attackPos = (enemyCenter.x <= ourCenter.x || enemyCenter.y <= ourCenter.y) ? (arena.width+arena.height)%2 : 1; int selfCount = arena.count("o"); boolean isMidWay = selfCount > (arena.width*arena.height/2-1); if(!isMidWay){ if(enemyCenter.x < ourCenter.x){ enemyCenter.x = 0; enemyCenter.y = 0; ourCenter.x = arena.width; ourCenter.y = arena.height; } else { enemyCenter.x = arena.width; enemyCenter.y = arena.height; ourCenter.x = 0; ourCenter.y = 0; } } ArrayList<Point> nearbyEmpty = arena.getAdjacentMatches(cell, "."); Collections.sort(nearbyEmpty, new Comparator<Point>(){ @Override public int compare(Point o1, Point o2) { Double score1 = arena.getAdjacentMatches(o1, ".").size() + arena.getAdjacentMatches(o1, "c").size() + arena.getAdjacentMatches(o1, "x").size() - arena.getAdjacentMatches(o1, "o").size() + distance(o1.x, o1.y, enemyCenter.x, enemyCenter.y)*100; Double score2 = arena.getAdjacentMatches(o2, ".").size() + arena.getAdjacentMatches(o2, "c").size() + arena.getAdjacentMatches(o2, "x").size() - arena.getAdjacentMatches(o2, "o").size() + distance(o1.x, o1.y, enemyCenter.x, enemyCenter.y)*100; return Double.compare(score2, score1); } }); ArrayList<Point> nearbyEnemies = arena.getAdjacentMatches(cell, "x"); Collections.sort(nearbyEnemies, new Comparator<Point>(){ @Override public int compare(Point o1, Point o2) { Integer score1 = (arena.getAdjacentMatches(o1, ".").size() + arena.getAdjacentMatches(o1, "c").size() - arena.getAdjacentMatches(o1, "x").size() + arena.getAdjacentMatches(o1, "o").size()) *10 + (isAtBoundary(o1, arena)?1000:0) + (o1.x + o1.y + attackPos + 1)%2; Integer score2 = (arena.getAdjacentMatches(o2, ".").size() + arena.getAdjacentMatches(o2, "c").size() - arena.getAdjacentMatches(o2, "x").size() + arena.getAdjacentMatches(o2, "o").size()) *10 + (isAtBoundary(o2, arena)?1000:0) + (o2.x + o2.y + attackPos + 1)%2; return Integer.compare(score2, score1); } }); ArrayList<Point> nearbyCorpses = arena.getAdjacentMatches(cell, "c"); Collections.sort(nearbyCorpses, new Comparator<Point>(){ @Override public int compare(Point o1, Point o2) { Integer score1 = arena.getAdjacentMatches(o1, "x").size() - arena.getAdjacentMatches(o1, "o").size(); Integer score2 = arena.getAdjacentMatches(o2, "x").size() - arena.getAdjacentMatches(o2, "o").size(); return Integer.compare(score1, score2); } }); ArrayList<Point> nearbyFriends = arena.getAdjacentMatches(cell, "o"); for(Point empty: nearbyEmpty){ if(nearbyFriends.size()>=2 && energy >= 1 && arena.getAdjacentMatches(empty, "x").size()==3 && isAtBoundary(empty, arena)){ return "MOVE "+arena.getDirection(cell, empty); } } for(Point empty: nearbyCorpses){ if(nearbyFriends.size()>=2 && energy >= 1 && arena.getAdjacentMatches(empty, "x").size()==3 && isAtBoundary(empty, arena)){ return "MOVE "+arena.getDirection(cell, empty); } } if ((cell.x+cell.y)%2 == moverPos && energy >= 1 && energy <= 5){ if(nearbyEmpty.size()>0){ Point foremost = nearbyEmpty.get(0); if(nearbyFriends.size() >= 4){ return "MOVE "+arena.getDirection(cell, foremost); } } if(nearbyCorpses.size() > 0) { Point corpse = nearbyCorpses.get(0); return "EAT " + arena.getDirection(cell, corpse); } if(energy > 0 && nearbyEnemies.size() > 0) { int attackStrength = Math.min(energy, 3); Point enemy = nearbyEnemies.get(0); return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength; } if(nearbyFriends.size() >= 4 && nearbyEmpty.size() > 0){ Point movePoint = getBestPointToDivide(arena, nearbyEmpty); return "MOVE " + arena.getDirection(cell, movePoint); } } if(energy >= 5 && nearbyEmpty.size() > 0) { Point divisionPoint = getBestPointToDivide(arena, nearbyEmpty); if(energy == MAX_ENERGY && nearbyFriends.size() >= 5 && distance(enemyCenter.x, enemyCenter.y, cell.x, cell.y) > distance(enemyCenter.x, enemyCenter.y, divisionPoint.x, divisionPoint.y)){ return "MOVE " + arena.getDirection(cell, divisionPoint); } return "DIVIDE " + arena.getDirection(cell, divisionPoint); } if(nearbyCorpses.size() > 0) { Point corpse = nearbyCorpses.get(0); if (energy < MAX_ENERGY){ return "EAT " + arena.getDirection(cell, corpse); } else { return "DIVIDE " + arena.getDirection(cell, corpse); } } if(energy >= 5 && nearbyCorpses.size() > 0) { Point divisionPoint = getBestPointToDivide(arena, nearbyCorpses); if(energy == MAX_ENERGY && nearbyFriends.size() >= 5 && distance(enemyCenter.x, enemyCenter.y, cell.x, cell.y) < distance(enemyCenter.x, enemyCenter.y, divisionPoint.x, divisionPoint.y)){ return "MOVE " + arena.getDirection(cell, divisionPoint); } return "DIVIDE " + arena.getDirection(cell, divisionPoint); } // if at least one adjacent enemy, attack if possible if(energy > 0 && nearbyEnemies.size() > 0) { int attackStrength = Math.min(energy, 3); Point enemy = nearbyEnemies.get(0); return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength; } return "REST"; } public static boolean isAtBoundary(Point point, Arena arena){ return point.x==0 || point.x==arena.width-1 || point.y==0 || point.y==arena.height-1; } public static double distance(double x1, double y1, double x2, double y2){ return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); } public static Point getBestPointToDivide(Arena arena, List<Point> nearbyEmpty){ Point result = null; double minDist = 100000; List<Point> mostEmpty = new ArrayList<Point>(); int max = -1000; List<Point> neighbor = nearbyEmpty; for(Point point: neighbor){ int emptyNeighborScore = arena.getAdjacentMatches(point, ".").size() + arena.getAdjacentMatches(point, "c").size() + arena.getAdjacentMatches(point, "x").size() - arena.getAdjacentMatches(point, "o").size(); if(emptyNeighborScore > max){ mostEmpty = new ArrayList<Point>(); mostEmpty.add(point); max = emptyNeighborScore; } else if(emptyNeighborScore == max){ mostEmpty.add(point); } } for(Point point: mostEmpty){ Point2D enemyCenter = arena.getCenterOf("x"); double dist = Math.pow(point.x-enemyCenter.x, 2) + Math.pow(point.y-enemyCenter.y, 2); if(dist < minDist){ minDist = dist; result = point; } } return result; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String firstLine; firstLine = br.readLine(); if(firstLine.equals("BEGIN")) { System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY); } else { String[] dimensions = firstLine.split(" "); int width = Integer.parseInt(dimensions[0]); int height = Integer.parseInt(dimensions[1]); Point[][] arena = new Point[height][]; String input; int lineno = 0; while(!(input=br.readLine()).equals("")) { char[] charList = input.toCharArray(); arena[lineno] = new Point[width]; for(int i=0; i<charList.length; ++i) { arena[lineno][i] = new Point(i, lineno, charList[i]); } lineno++; } String[] stats = br.readLine().split(" "); int x = Integer.parseInt(stats[0]); int y = Integer.parseInt(stats[1]); int hp = Integer.parseInt(stats[2]); int energy = Integer.parseInt(stats[3]); Arena arenaObj = new Arena(arena, width, height); System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy)); } } public static class Arena { public Point[][] array; public HashMap<String, String> c2d; public int height; public int width; public Arena(Point[][] array, int width, int height) { this.array = array; this.width = width; this.height = height; this.c2d = new HashMap<String, String>(); this.c2d.put("0,0", "-"); this.c2d.put("0,-1", "N"); this.c2d.put("0,1", "S"); this.c2d.put("1,0", "E"); this.c2d.put("-1,0", "W"); this.c2d.put("-1,-1", "NW"); this.c2d.put("1,-1", "NE"); this.c2d.put("-1,1", "SW"); this.c2d.put("1,1", "SE"); } // get the character at x,y // or return empty string if out of bounds public Point get(int x, int y) { if(y < 0 || y >= this.array.length){ return null; } Point[] row = this.array[y]; if(x < 0 || x >= row.length) { return null; } return row[x]; } // get arraylist of Points for each adjacent space that matches the target string public ArrayList<Point> getAdjacentMatches(Point p, String match) { ArrayList<Point> result = new ArrayList<Point>(); for(int i=-1; i<=1; ++i) { for(int j=-1; j<=1; ++j) { Point found = this.get(p.x+i, p.y+j); if((i!=0 || j!=0) && found != null && found.symbol.equals(match)) { result.add(found); } } } return result; } public ArrayList<Point> getAdjacents(Point p){ ArrayList<Point> result = new ArrayList<Point>(); for(int i=-1; i<=1; ++i) { for(int j=-1; j<=1; ++j) { Point found = this.get(p.x+i, p.y+j); if((i!=0 || j!=0) && found != null) { result.add(found); } } } return result; } public int count(String sym){ int result = 0; for(int y=0; y<array.length; y++){ for(int x=0; x<array[y].length; x++){ Point cur = this.get(x, y); if(cur!=null && cur.symbol.equals(sym)){ result++; } } } return result; } // get the direction string from point 1 to point 2 public String getDirection(Point p1, Point p2) { int dx = p2.x - p1.x; int dy = p2.y - p1.y; dx = Math.abs(dx) / (dx==0?1:dx); dy = Math.abs(dy) / (dy==0?1:dy); return this.c2d.get(dx + "," + dy); } public Point2D getCenterOf(String sym){ Point2D result = new Point2D(0,0); int count = 0; for(int y=0; y<array.length; y++){ for(int x=0; x<array[y].length; x++){ if(this.get(x,y).symbol.equals(sym)){ result.x += x; result.y += y; count++; } } } result.x /= count; result.y /= count; return result; } } public static class Point { int x, y; String symbol; public Point(int x, int y, String sym) { this.x=x; this.y=y; this.symbol=sym; } public Point(int x, int y, char sym){ this(x, y, ""+sym); } } public static class Point2D{ double x,y; public Point2D(double x, double y){ this.x = x; this.y = y; } } } ``` [Answer] I think i will post my submission, since you are so generous to add the boilerplate logic... There was a problem in your logic, where the eat-action would issue an ATTACK instead of an EAT and would waste the corpse. I have modified your gist just as much to have a working solution, that should perform relatively well. It starts with 4 hp and 8 energy, so after a split and a rest, both cells can split again. It will try to multiply itself, attack enemies, eat corpses and rest, in this order. So inner cells will store their 8 energy points, to quickly replace killed outer cells and leave them 3 energy points to make a 3 point attack or multiply themselves after one turn rest. The 4 hp are to survive at least one full force attack. acid seems to be a waste of points for me so i kept it out... I did not tested the submission, as it was a 2 minute thing ;) here is my code: ``` /* Sample code for a "Battle for the Petri Dish" cell Released under the terms of the WTF Public License No warranty express or implied is granted, etc, etc. I just hacked this together very quickly; improvements are welcome, so please fork the Gist if you like. used this code for a submission @kostronor */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class SlimeCell { public static final int MAX_HP = 4; public static final int MAX_ENERGY = 8; public static final int ACIDITY = 0; // given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S") public static String decide(final Arena arena, final Point cell, final int hp, final int energy) { // empty and corpses are free for movement and division ArrayList<Point> nearbyEmpty = arena.getAdjacentMatches(cell, "."); nearbyEmpty.addAll(arena.getAdjacentMatches(cell, "c")); ArrayList<Point> nearbyEnemies = arena.getAdjacentMatches(cell, "x"); ArrayList<Point> nearbyCorpses = arena.getAdjacentMatches(cell, "c"); ArrayList<Point> nearbyFriends = arena.getAdjacentMatches(cell, "o"); // if you have energy and space to divide, divide into a random space if((energy >= 5) && (nearbyEmpty.size() > 0)) { Point randomEmpty = nearbyEmpty.get((int)Math.floor(nearbyEmpty.size()*Math.random())); return "DIVIDE " + arena.getDirection(cell, randomEmpty); } // if at least one adjacent enemy, attack if possible if((energy > 0) && (nearbyEnemies.size() > 1)) { int attackStrength = Math.min(energy, 3); Point enemy = nearbyEnemies.get((int)Math.floor(nearbyEnemies.size()*Math.random())); return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength; } // if there's a nearby corpse, eat it if your energy is below max if(nearbyCorpses.size() > 0) { Point corpse = nearbyCorpses.get((int)Math.floor(nearbyCorpses.size()*Math.random())); return "EAT " + arena.getDirection(cell, corpse); } return "REST"; } public static void main(final String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String firstLine; firstLine = br.readLine(); if(firstLine.equals("BEGIN")) { System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY); } else { String[] dimensions = firstLine.split(" "); int width = Integer.parseInt(dimensions[0]); int height = Integer.parseInt(dimensions[1]); Point[][] arena = new Point[height][]; String input; int lineno = 0; while(!(input=br.readLine()).equals("")) { String[] charList = input.substring(1).split(""); arena[lineno] = new Point[width]; for(int i=0; i<charList.length; ++i) { arena[lineno][i] = new Point(i, lineno, charList[i]); } lineno++; } String[] stats = br.readLine().split(" "); int x = Integer.parseInt(stats[0]); int y = Integer.parseInt(stats[1]); int hp = Integer.parseInt(stats[2]); int energy = Integer.parseInt(stats[3]); Arena arenaObj = new Arena(arena, width, height); System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy)); } } public static class Arena { public Point[][] array; public HashMap<String, String> c2d; public int height; public int width; public Arena(final Point[][] array, final int width, final int height) { this.array = array; this.width = width; this.height = height; this.c2d = new HashMap<String, String>(); this.c2d.put("0,0", "-"); this.c2d.put("0,-1", "N"); this.c2d.put("0,1", "S"); this.c2d.put("1,0", "E"); this.c2d.put("-1,0", "W"); this.c2d.put("-1,-1", "NW"); this.c2d.put("1,-1", "NE"); this.c2d.put("-1,1", "SW"); this.c2d.put("1,1", "SE"); } // get the character at x,y // or return empty string if out of bounds public Point get(final int x, final int y) { if((y < 0) || (y >= this.array.length)){ return null; } Point[] row = this.array[y]; if((x < 0) || (x >= row.length)) { return null; } return row[x]; } // get arraylist of Points for each adjacent space that matches the target string public ArrayList<Point> getAdjacentMatches(final Point p, final String match) { ArrayList<Point> result = new ArrayList<Point>(); for(int i=-1; i<=1; ++i) { for(int j=-1; j<=1; ++j) { Point found = this.get(p.x+i, p.y+j); if(((i!=0) || (j!=0)) && (found != null) && found.symbol.equals(match)) { result.add(found); } } } return result; } // get the direction string from point 1 to point 2 public String getDirection(final Point p1, final Point p2) { int dx = p2.x - p1.x; int dy = p2.y - p1.y; dx = Math.abs(dx) / (dx==0?1:dx); dy = Math.abs(dy) / (dy==0?1:dy); return this.c2d.get(dx + "," + dy); } } public static class Point { int x, y; String symbol; public Point(final int x, final int y, final String sym) { this.x=x; this.y=y; this.symbol=sym; } } } ``` [Answer] # Thinly spread bomber Since you so kindly provided boilerplate code, I decided to make my own simple cell; This cell has 4 acidity, only 1 hp and 7 energy. It tries to get out of range of friendlies and then waits there (or eats if possible) until it gets the chance to blow up or replicate. Attacks only if it's the only option. It's a pretty ballsy strategy and will probably perform badly, but I'm curious to see how it does. I'll test it and improve it later today, maybe. ``` /* Sample code for a "Battle for the Petri Dish" cell Released under the terms of the WTF Public License, No warranty express or implied is granted, etc, etc. I just hacked this together very quickly; improvements are welcome, so please fork the Gist if you like. */ // used in defining cell spec var MAX_HP = 1; var MAX_ENERGY = 7; var ACIDITY = 4; /* The decide function takes an Arena object (see below for prototype methods), a cell object, and an outputCallback, which accepts a command string to output */ function decide(arena, cell, outputCallback) { var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]); var nearbyEnemies = arena.getAdjacentMatches(cell.point, ["x"]); var nearbyCorpses = arena.getAdjacentMatches(cell.point, ["c"]); var nearbyFriendlies = arena.getAdjacentMatches(cell.point, ["o"]); //attempt to move away from friendlies if possible if(nearbyFriendlies.length>1 && cell.energy>0) { for(var i=0; i<nearbyEmpties.length; ++i) { var space = nearbyEmpties[i]; if(arena.getAdjacentMatches(space, ["o"]).length == 1) { outputCallback("MOVE " + arena.getDirection(cell,space)); return; } } } // Explode if there are two more adjacent enemies than friendlies or enemies and no friendlies. if((nearbyEnemies.length - nearbyFriendlies.length > 1 || (nearbyEnemies.length>0 && nearbyFriendlies.length == 0)) && cell.energy >= cell.hp && cell.hp <= 3) { outputCallback("EXPLODE"); return; } // if you have the energy and space to divide, and there's a way for the child to get away from friendlies, do it. if(cell.energy >= 5 && nearbyEmpties.length > 0) { for(var i=0; i<nearbyEmpties.length; ++i) { var space = nearbyEmpties[i]; var possiblePositions = arena.getAdjacentMatches(space, ["o"]); for(var i=0; i<possiblePositions.length; ++i) { if(arena.getAdjacentMatches(possiblePositions[i], ["o"]).length == 0) { outputCallback("DIVIDE " + arena.getDirection(cell,space)); return; } } } } // if at least one adjacent enemy, attack if possible if(cell.energy > 0 && nearbyEnemies.length > 0) { outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length*Math.random())|0]) + " " + Math.min(cell.energy, 3)); return; } // if there's a nearby corpse, eat it if your energy is below max if(nearbyCorpses.length > 0) { outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0])); return; } outputCallback("REST"); return; } var input = ""; // quiet stdin EPIPE errors process.stdin.on("error", function(err) { //console.log("slight error: " + err); }); process.stdin.on("data", function(data) { input += data; }); process.stdin.on("end", function() { if(input == "BEGIN") { // output space-separated attributes process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" ")); } else { // read in arena and decide on an action var arena = new Arena(); var lines = input.split("\n"); var dimensions = lines[0].split(" ").map(function(d) { return parseInt(d); }); arena.width = dimensions[0]; arena.height = dimensions[1]; for(var y=1; y<=dimensions[1]; ++y) { for(var x=0; x<lines[y].length; ++x) { arena.set(x, y-1, lines[y][x]); } } var stats = lines[dimensions[1]+2].split(" "); var cell = { x: stats[0], y: stats[1], hp: stats[2], energy: stats[3], point: arena.get(stats[0], stats[1]) }; // decide on an action and write the action to stdout decide(arena, cell, function(output) { process.stdout.write(output); }) } }); var Arena = function() { this.dict = {}; }; Arena.prototype = { // get Point object get: function(x,y) { return this.dict[x+","+y]; }, // store Point object set: function(x,y,d) { this.dict[x+","+y] = new Point(x,y,d); }, // get an array of all Points adjacent to this one whose symbol is contained in matchList // if matchList is omitted, return all Points getAdjacentMatches: function(point, matchList) { var result = []; for(var i=-1; i<=1; ++i) { for(var j=-1; j<=1; ++j) { var inspectedPoint = this.get(point.x+i, point.y+j); if(inspectedPoint && (i!=0 || j!=0) && (!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) { result.push(inspectedPoint); } } } return result; }, // return the direction from point1 to point2 getDirection: function(point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; dx = Math.abs(dx) / (dx || 1); dy = Math.abs(dy) / (dy || 1); c2d = { "0,0":"-", "0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W", "-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" }; return c2d[dx + "," + dy]; } } var Point = function(x,y,d) { this.x = x; this.y = y; this.symbol = d; } Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ")"; } ``` ]
[Question] [ *This is a tips question for golfing in Python.* In Python golfing, it's common for a submission to be a function defined as a lambda. For example, ``` f=lambda x:0**x or x*f(x-1) ``` [computes the factorial](https://codegolf.stackexchange.com/a/3133/20260) of x. The lambda format has two [big advantages](https://codegolf.stackexchange.com/a/61526/20260): * The boilerplate of `f=lambda x:...` or `lambda x:...` is shorter than the `def f(x):...return...` or `x=input()...print...` * A recursive call can be used to loop with little byte overhead. However, lambdas have the big drawback of allowing only a single expression, no statements. In particular, this means no assignments like `c=chr(x+65)`. This is problematic when one has a long expression whose value needs to be referenced twice (or more). Assignments like `E=enumerate` are possible outside the function or as an optional argument, but only if they don't depend on the function inputs. Optional arguments like `f=lambda n,k=min(n,0):...` fail because input `n` hasn't been defined when `k` is evaluated at definition time. The result is that sometimes you suck up repeating a long expression in a lambda because the alternative is a lengthy non-lambda. ``` lambda s:s.strip()+s.strip()[::-1] def f(s):t=s.strip();print t+t[::-1] ``` The break even point is about 11 characters ([details](https://codegolf.stackexchange.com/a/52317/20260)), past which you switch to a `def` or `program`. Compare this to the usual break-even point of length 5 for a repeated expression: ``` range(a)+range(b) r=range;r(a)+r(b) print s[1:],s[1:]*2 r=s[1:];print r,r*2 ``` Other languages have workarounds, [Octave for example](https://codegolf.stackexchange.com/a/104753/20260). There are known tricks for Python, but they are long, clunky, and/or limited-use. A short, general-purpose method to simulate assignment in a lambda would revolutionize Python golfing. --- What are ways for a Python golfer to overcome or work around this limitation? What potential ideas should they have in mind when they see a long expression repeated twice in a lambda? My goal with this tips question is to dive deep into this problem and: * Catalog and analyze golfing workarounds to fake assignment inside a lambda * Explore new leads for better methods Each answer should explain a workaround or potential lead. [Answer] ## Assignment expressions in Python 3.8 [Python 3.8](https://www.python.org/downloads/release/python-380a1/) ([TIO](https://tio.run/#python38pr)) introduces [assignment expressions](https://www.python.org/dev/peps/pep-0572/), which use `:=` to assign a variable inline as part of expression. ``` >>> (n:=2, n+1) (2, 3) ``` This can be used inside a `lambda`, where assignments are not ordinarily allowed. Compare: ``` lambda s:(t:=s.strip())+t[::-1] lambda s:s.strip()+s.strip()[::-1] def f(s):t=s.strip();return t+t[::-1] ``` See [this tip](https://codegolf.stackexchange.com/a/180041/20260) for more. [Answer] ### `eval` This is not that great in of itself, but if your solution already uses `eval` in some way or form you can usually use this technique. ``` eval("%f*%f+%f"%((5**.5,)*3)) ``` [Answer] ## Inner lambdas These allow you to define multiple variables at once. ``` lambda s:s.strip()+s.strip()[::-1] ``` vs. ``` lambda s:(lambda t:t+t[::-1])(s.strip()) ``` is much longer, but if you have multiple variables, or variables that are longer, which are repeated many times: ``` lambda a,b,c:a.upper()*int(c)+b.lower()*int(c)+a.upper()[::-1]+b.lower()[::-1]+a.upper()*int(c)+a.lower()*int(c) ``` vs. ``` lambda a,B,c:(lambda A,b,n:A*n+b*n+A[::-1]+b[::-1]+A*n+b*c)(a.upper(),B.lower(),int(c)) ``` ### Character count Initial: `(lambda:)()` (11 bytes) First variable: `[space]a` (2 bytes) Subsequent variables: `,b,` (3 bytes) Use: `a` (1 byte). ``` (lambda* a*_,b_:)(*<value a>*_,<value b>_) ``` (Also saves on brackets) So, this takes `3n + 10` bytes, where `n` is the number of variables. This is a high initial cost, but can pay off in the end. It even returns it's inner value,so you can nest multiple (Though this will quickly become not worth it.) This is really only useful for long intermediate calculations in nested list comprehensions, as a `def f():a=...;b=...;return` will usually be shorter. For 1 value, this saves: `uses * length - length - uses - 13`, so is only useful when that expression is positive. For a `n` different expressions used `u` times in total, where their combined length is `l`, this saves: `l - (3 * n) - u - 10 ( + brackets removed )` [Answer] # Use a List Declare a list as parameter and use `.append() or` to store the value: `lambda s:s.lower()+s.lower()[::-1]` turns into `lambda s,l=[]:l.append(s.lower())or l[-1]+l[-1][::-1]` ### Character count: `,l=[]` 5 characters `l.append()or` 13 characters `l[-1]` 5 characters for each use ### Break Even The amount of added character is : `uses*(5-length) + 18 + length` In the previous example the statement is `s.lower()` is 9 characters long and is used 2 times, applying this technique added 19 characters. If it was used 7 times, there would be a 1 character reduction. The amount of minimal uses to this technique be worth is `min_uses = (18+length)/(length-5)` ## Upsides * Allow a new assignment at a slightly reduced cost (the list already is declared) * Is a `list` object so `[0]`, `.pop()`, `[x:y]` and other list functions can be used for tricks. *highly situational* ## Downsides * High initial cost * High use cost * Only works for uses with the length higher than `5` --- # Use a Dictionary thanks [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) Same idea as above Declare a dictionary as parameter and use `.setdefault()` to store (and return) the value: `lambda s:s.lower()+s.lower()[::-1]` turns into `lambda s,d={}:d.setdefault(0,s.lower())+d[0][::-1]` Note that, unlike the `list` counterpart, `setdefault` returns the value assigned. ### Character count: `,d={}` 5 characters `d.setdefault(k,)` 16 characters `d[k]` 4 characters for each use ### Break Even The amount of added character is : `(uses-1)*(4-length) + 21` In the previous example the statement is `s.lower()` is 9 characters long and is used 2 times, applying this technique added 16 characters. If it was used 7 times, there would be a 1 character reduction. The amount of minimal uses to this technique be worth is `min_uses = 1-21/(4-length)` ## Upsides/Downsides * Basically the same as the list * Only works for uses with the length higher than `4` --- [Answer] Use to set variables and return the data after operation like such: ``` add = lambda x, y: exec("x+=y") ``` [Answer] # List comprehensions This is more of a last resort since it's so ungolfy, but you can do `[<expression> for <variable> in <value>]` to pseudo-set a variable in a lambda. Basically the only good point about this method is that the inner expression can stay readable, which is obviously the least of your concern when golfing. ]
[Question] [ In the spirit of [this xkcd](http://xkcd.com/1313) ![enter link description here](https://imgs.xkcd.com/comics/regex_golf.png) Write a program that plays regex golf with arbitrary pairs of lists. The program should at least attempt to make the regex short, a program that just outputs `/^(item1|item2|item3|item4)$/` or similar is not allowed. Scoring is based on the ability to generate the shortest regex. The test lists are those of successful and unsuccessful US presidential candidates, found [here](http://pastebin.com/EvycCQTB) (thanks @Peter). Of course, the program must work for all disjoint lists, so simply returning an answer for the president one doesn't count. [Answer] # Perl (~~111~~ ~~110~~ 122 characters) ``` use Regexp::Assemble;@ARGV=shift;my$r=new Regexp::Assemble;chomp,add$r "^\Q$_\E\$"while<>;$_=as_string$r;s/\(\?:/(/g;print ``` This uses CPAN module called `Regexp::Assemble` in order to optimize the regular expressions. Because what is the better language for regular expressions then Perl. Also, readable version, just for fun (made with help of `-MO=Deparse`). ``` use Regexp::Assemble; my $r = Regexp::Assemble->new; while (<>) { chomp($_); $r->add("^\Q$_\E\$"); } $_ = $r->as_string; # Replace wasteful (?:, even if it's technically correct. s/\(\?:/(/g; print $_; ``` Sample output (I did CTRL-D after `item4`). ``` $ perl assemble.pl item1 atem2 item3 item4 ^(item[134]|atem2)$ ``` Also, as a bonus, I'm writing the regex for every word in the question. ``` ^(a((ttemp)?t|llowed\.|rbitrary)?|\/\^item1\|atem2\|item3\|item4\$\/|s(ho(rt,|uld)|imilar)|p((air|lay)s|rogram)|(Writ|mak|Th)e|l(ists\.|east)|o([fr]|utputs)|t(h(at|e)|o)|(jus|no)t|regex|golf|with|is)$ ``` Also, list of presidents (262 bytes). ``` ^(((J(effer|ack|ohn)s|W(ashingt|ils)|Nix)o|Van Bure|Lincol)n|C(l(eveland|inton)|oolidge|arter)|H(a(r(rison|ding)|yes)|oover)|M(cKinley|adison|onroe)|T(a(ylor|ft)|ruman)|R(oosevelt|eagan)|G(arfield|rant)|Bu(chanan|sh)|P(ierce|olk)|Eisenhower|Kennedy|Adams|Obama)$ ``` [Answer] *Not* my solution (obviously I'm not peter norvig!) but here's a solution of the (slightly modified) question courtesy of him: <http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb> the program he gives is as follows (his work, not mine): ``` def findregex(winners, losers): "Find a regex that matches all winners but no losers (sets of strings)." # Make a pool of candidate components, then pick from them to cover winners. # On each iteration, add the best component to 'cover'; finally disjoin them together. pool = candidate_components(winners, losers) cover = [] while winners: best = max(pool, key=lambda c: 3*len(matches(c, winners)) - len(c)) cover.append(best) pool.remove(best) winners = winners - matches(best, winners) return '|'.join(cover) def candidate_components(winners, losers): "Return components, c, that match at least one winner, w, but no loser." parts = set(mappend(dotify, mappend(subparts, winners))) wholes = {'^'+winner+'$' for winner in winners} return wholes | {p for p in parts if not matches(p, losers)} def mappend(function, *sequences): """Map the function over the arguments. Each result should be a sequence. Append all the results together into one big list.""" results = map(function, *sequences) return [item for result in results for item in result] def subparts(word): "Return a set of subparts of word, consecutive characters up to length 4, plus the whole word." return set(word[i:i+n] for i in range(len(word)) for n in (1, 2, 3, 4)) def dotify(part): "Return all ways to replace a subset of chars in part with '.'." if part == '': return {''} else: return {c+rest for rest in dotify(part[1:]) for c in ('.', part[0]) } def matches(regex, strings): "Return a set of all the strings that are matched by regex." return {s for s in strings if re.search(regex, s)} answer = findregex(winners, losers) answer # 'a.a|i..n|j|li|a.t|a..i|bu|oo|n.e|ay.|tr|rc|po|ls|oe|e.a' ``` where winners and losers are the winners and losers lists respectively (or any 2 lists of course) see the article for detailed explanations. [Answer] My [solution](https://github.com/bjourne/playground-factor/blob/master/xkcd1313/xkcd1313.factor) written in [Factor](http://factorcode.org/): ``` USING: formatting fry grouping kernel math math.combinatorics math.ranges pcre sequences sets ; IN: xkcd1313 : name-set ( str -- set ) "\\s" split members ; : winners ( -- set ) "washington adams jefferson jefferson madison madison monroe monroe adams jackson jackson vanburen harrison polk taylor pierce buchanan lincoln lincoln grant grant hayes garfield cleveland harrison cleveland mckinley mckinley roosevelt taft wilson wilson harding coolidge hoover roosevelt roosevelt roosevelt roosevelt truman eisenhower eisenhower kennedy johnson nixon nixon carter reagan reagan bush clinton clinton bush bush obama obama" name-set ; : losers ( -- set ) "clinton jefferson adams pinckney pinckney clinton king adams jackson adams clay vanburen vanburen clay cass scott fremont breckinridge mcclellan seymour greeley tilden hancock blaine cleveland harrison bryan bryan parker bryan roosevelt hughes cox davis smith hoover landon wilkie dewey dewey stevenson stevenson nixon goldwater humphrey mcgovern ford carter mondale dukakis bush dole gore kerry mccain romney" name-set winners diff { "fremont" } diff "fillmore" suffix ; : matches ( seq regex -- seq' ) '[ _ findall empty? not ] filter ; : mconcat ( seq quot -- set ) map concat members ; inline : dotify ( str -- seq ) { t f } over length selections [ [ CHAR: . rot ? ] "" 2map-as ] with map ; : subparts ( str -- seq ) 1 4 [a,b] [ clump ] with mconcat ; : candidate-components ( winners losers -- seq ) [ [ [ "^%s$" sprintf ] map ] [ [ subparts ] mconcat [ dotify ] mconcat ] bi append ] dip swap [ matches empty? ] with filter ; : find-cover ( winners candidates -- cover ) swap [ drop { } ] [ 2dup '[ _ over matches length 3 * swap length - ] supremum-by [ [ dupd matches diff ] [ rot remove ] bi find-cover ] keep prefix ] if-empty ; : find-regex ( winners losers -- regex ) dupd candidate-components find-cover "|" join ; : verify ( winners losers regex -- ? ) swap over [ dupd matches diff "Error: should match but did not: %s\n" ] [ matches "Error: should not match but did: %s\n" ] 2bi* [ dupd '[ ", " join _ printf ] unless-empty empty? ] 2bi@ and ; : print-stats ( legend winners regex -- ) dup length rot "|" join length over / "separating %s: '%s' (%d chars %.1f ratio)\n" printf ; : (find-both) ( winners losers legend -- ) -rot 2dup find-regex [ verify t assert= ] 3keep nip print-stats ; : find-both ( winners losers -- ) [ "1 from 2" (find-both) ] [ swap "2 from 1" (find-both) ] 2bi ; IN: scratchpad winners losers find-both separating 1 from 2: 'a.a|a..i|j|li|a.t|i..n|bu|oo|ay.|n.e|ma|oe|po|rc|ls|l.v' (55 chars 4.8 ratio) separating 2 from 1: 'go|e..y|br|cc|hu|do|k.e|.mo|o.d|s..t|ss|ti|oc|bl|pa|ox|av|st|du|om|cla|k..g' (75 chars 3.3 ratio) ``` It's the same algorithm as Norvig's. If hurting readability is the goal then you can probably golf away many more characters. [Answer] My code is not in a very golf-ish and condensed fashion, but you can check it at <https://github.com/amitayd/regexp-golf-coffeescript/> (or specifically the algorithm at src/regexpGolf.coffee). It's based on Peter Norvig's algorithm, with two improvements: 1. Create parts to use with character sets (i.e. use [ab]z, [ac]z, and [bc]z if valid parts are az, bz and cz). 2. Allow to construct "top optimal paths" of covers, and not just a cover made of the best candidate at each iteration. (And also threw in an optional randomness) For the sets of winners/losers in this quiz I found a 76 chars regex using it: ``` [Jisn]e..|[dcih]..o|[AaG].a|[sro].i|T[ar]|[PHx]o|V|[oy]e|lev|sh$|u.e|rte|nle ``` Some more details in my [blog post about porting the solver to coffeescript](http://www.doboism.com/blog/2014/01/19/coffeescript-regex-golf). ]
[Question] [ You are on an advanced intergalactic space station. A friend of yours who is minoring in the Study of Gravity just created a game that involves using microgravity as a way to move a ball around. She hands you a small controller with four directional arrows on it and a maze like structure with a ball sitting to the left. She begins to explain how the game works. * You have 2 directional buttons, left `<` and right `>`. * You also have 2 gravity buttons, up `^` and down `v` (at least from your frame of reference) * You will use these arrow buttons to move the ball around on your screen. "Now there are some rules that need to be followed." she says 1. All platforms must be traversed before getting to the cup `\ /` 2. Arrows `< > ^ v` will be used to specify movement of the ball 3. Gravity is `^ v` (up & down). This moves the ball all the way to the next platform in that direction. (Distance is not calculated for up and down) 4. Losing the ball is bad! Don't fall over the edge, and don't switch gravity too soon such that your ball never reaches a platform 5. Movement is counted in steps of `< >` 6. The ball can enter the cup from any direction as long as Rule 1 is followed 7. You must specify direction of gravity so your ball doesn't float away 8. Movement may be random as long as Rule 1 and Rule 4 is followed 9. For cases that cannot be solved output False or Invalid ## Simple Example of a ball, platform, and cup: ``` v o ---\ / ``` --- ``` v> o ---\ / ``` --- ``` v>> o ---\ / ``` --- ``` v>>> o ---\ / ``` --- ``` v>>>> ---\o/ ``` ## Example of traversing over the same platform again. ``` v o ---- \ /------- ``` --- ``` v> o ---- \ /------- ``` --- ``` v>> o ---- \ /------- ``` --- ``` v>>> o ---- \ /------- ``` --- ``` v>>>> ---- o \ /------- ``` --- ``` v>>>>> ---- o \ /------- ``` --- ``` v>>>>>> ---- o \ /------- ``` --- ``` v>>>>>>> ---- o \ /------- ``` --- ``` v>>>>>>>> ---- o \ /------- ``` --- ``` v>>>>>>>><<<<<<<< # move all the way to the left to get to the cup ---- \o/------- ``` --- ## Example of switching gravity ``` v --/ \ o ---- ``` --- ``` v> --/ \ o ---- ``` --- ``` v>> --/ \ o ---- ``` --- ``` v>>> --/ \ o ---- ``` --- ``` v>>>^ --/ \ o ---- ``` --- ``` v>>>^> --/ \ o ---- ``` --- ``` v>>>^>> --/ \ o ---- ``` --- ``` v>>>^>>> --/o\ ---- ``` ## Task Your task is to create a program that will take an ASCII representation of a course as input. And output a string of arrows `<>^v` representing the direction and gravitational pull to move a ball `o` across all `platforms` into a cup. Standard code golf rules apply ## Test Cases Input (A situation where gravity is being switched) ``` ---- --/ \ --- -- o ------ ----- ``` Output ``` ^>>v>>>>>^>>>>>v>>>>^>>> ``` [![enter image description here](https://i.stack.imgur.com/BIlgV.gif)](https://i.stack.imgur.com/BIlgV.gif) --- Input (A situation where direction is being switched) ``` --- o ---- --- ----- --\ / ``` Output ``` v>>>>>>^>>>v<<<<<v>>> ``` [![enter image description here](https://i.stack.imgur.com/9To6b.gif)](https://i.stack.imgur.com/9To6b.gif) --- Input (A situation where you need to traverse over the same platform twice) ``` o ------ ------ ------ \ /------ ``` Output ``` v>>>>>><<<<<<>>>>>>><<<<<< ``` [![enter image description here](https://i.stack.imgur.com/q1Y7l.gif)](https://i.stack.imgur.com/q1Y7l.gif) --- ## Bad Cases, Program should output Falsy for these No way for the ball to get to the next platform ``` o --- --- ``` Ball would float off into space ``` --- o --- ``` A situation where the ball gets to the cup, but all platforms don't get traversed. ``` o ---- ---- \ /---- ``` [Answer] # Pyth, 431 bytes This is my first Pyth program (actually this is my first program in any code-golf language), which means it can be probably still improved. ``` Jmmck\:cd\%c.Z"xรšUยฑรƒ@Dร… W,Jย รกDPรกร’ยญV`รฝรผw{g$รร€รžร‡rยงo.รทรฅ8รจรร‡r{รธยบy{~1รฅรต:noรŸรƒรบ/.yรงรญรคร‚'รซLยขรชFยธรจร†\kaยดQร’nร’@tรฃร’รยตร†ยพรตรถยปbรHยฅยฆ$ยจ%5Eyรฎรฟ}รณยงรปrhยณoร„รฅร‹ร„qรต Xร”Hรป"\_KYDrGHFN@JGIn=bm:d.*NHHRb)RHDiNTR.turNG.tT;M:jH)hh@JG0DXGHN=Ti+3qG\^HI!},GTK aK,GT aY+eKNI&!g5T}\EjT)N.q;D(GHNT)INIqHhT=ZrGhtTInZhtTXHZ+eTN))).?I&nHhTgGhtTXHhtT+eTH; aK,di2i1r0.z aY+eKk#=N.(Y0(6\vkN)(7\^kN)(8\v\<N)(9\v\>N)(10\^\<N)(11\^\>N ``` [Try it here (the last testcase needs too long, it must be tested with a local Pyth installation).](http://pyth.herokuapp.com/?code=Jmmck%5C%3Acd%5C%25c.Z%22x%C3%9AU%C2%8E%C2%B1%C2%8A%C3%83%40%0CD%7F%C3%85%C2%8D+W%2C%C2%99J%C2%A0%C3%A1DP%C3%A1%C3%92%C2%ADV%60%C2%87%C3%BD%C2%84%C3%BC%7Fw%7Bg%1F%24%C3%8D%C3%80%C2%83%19%C3%9E%1C%C3%87r%C2%A7o.%C3%B7%C3%A58%C3%A8%C3%9D%C3%87r%7B%C3%B8%C2%9E%C2%BAy%7B~1%C3%A5%C3%B5%C2%8E%3An%C2%8Fo%C3%9F%C3%83%C3%BA%2F.%0Cy%C3%A7%17%C3%AD%C3%A4%C3%82%1F%27%C3%AB%C2%83%C2%95%18%C2%9AL%15%14%0B%C2%A2%C2%8D%C3%AA%C2%82F%C2%B8%C3%A8%C3%86%5C%05%1Bk%1Da%C2%B4%C2%90%02Q%C3%92%C2%8Cn%C3%92%40%C2%87t%C3%A3%1A%C3%92%C3%81%C2%B5%C3%86%C2%BE%C3%B5%C3%B6%1C%C2%BBb%C2%86%C3%8DH%C2%A5%C2%A6%24%C2%A8%255Ey%C3%AE%C3%BF%7D%C3%B3%C2%8A%C2%8A%16%13%C2%A7%C3%BBr%04h%C2%B3o%C3%84%C3%A5%1B%16%0C%13%04%C3%8B%C3%84%C2%8Aq%C3%B5%7F+X%C3%94H%C3%BB%22%5C_KYDrGHFN%40JGIn%3Dbm%3Ad.%2aNHHRb%29RHDiNTR.turNG.tT%3BM%3AjH%29hh%40JG0DXGHN%3DTi%2B3qG%5C%5EHI%21%7D%2CGTK+aK%2CGT+aY%2BeKNI%26%21g5T%7D%5CEjT%29N.q%3BD%28GHNT%29INIqHhT%3DZrGhtTInZhtTXHZ%2BeTN%29%29%29.%3FI%26nHhTgGhtTXHhtT%2BeTH%3B+aK%2Cdi2i1r0.z+aY%2BeKk%23%3DN.%28Y0%286%5CvkN%29%287%5C%5EkN%29%288%5Cv%5C%3CN%29%289%5Cv%5C%3EN%29%2810%5C%5E%5C%3CN%29%2811%5C%5E%5C%3EN&input=+++++++++----+++--%2F+%5C%0A---++++--%0Ao%0A%0A++------++++-----&debug=0) Hex dump of the code (use `xxd -r <filename>` to decode): ``` 00000000: 4a6d 6d63 6b5c 3a63 645c 2563 2e5a 2278 Jmmck\:cd\%c.Z"x 00000010: da55 8eb1 8ac3 400c 447f c58d 2057 2c99 [[emailย protected]](/cdn-cgi/l/email-protection)... W,. 00000020: 4aa0 e144 50e1 d2ad 5660 87fd 84fc 7f77 J..DP...V`.....w 00000030: 7b67 1f24 cdc0 8319 de1c c772 a76f 2ef7 {g.$.......r.o.. 00000040: e538 e8dd c772 7bf8 9eba 797b 7e31 e5f5 .8...r{...y{~1.. 00000050: 8e3a 6e8f 6fdf c3fa 2f2e 0c79 e717 ede4 .:n.o.../..y.... 00000060: c21f 27eb 8395 189a 4c15 140b a28d ea82 ..'.....L....... 00000070: 46b8 e8c6 5c05 1b6b 1d61 b490 0251 d28c F...\..k.a...Q.. 00000080: 6ed2 4087 74e3 1ad2 c1b5 c6be f5f6 1cbb [[emailย protected]](/cdn-cgi/l/email-protection)........... 00000090: 6286 cd48 a5a6 24a8 2535 4579 eeff 7df3 b..H..$.%5Ey..}. 000000a0: 8a8a 1613 a7fb 7204 68b3 6fc4 e51b 160c ......r.h.o..... 000000b0: 1304 cbc4 8a71 f57f 2058 d448 fb22 5c5f .....q.. X.H."\_ 000000c0: 4b59 4472 4748 464e 404a 4749 6e3d 626d KYDrGHFN@JGIn=bm 000000d0: 3a64 2e2a 4e48 4852 6229 5248 4469 4e54 :d.*NHHRb)RHDiNT 000000e0: 522e 7475 724e 472e 7454 3b4d 3a6a 4829 R.turNG.tT;M:jH) 000000f0: 6868 404a 4730 4458 4748 4e3d 5469 2b33 hh@JG0DXGHN=Ti+3 00000100: 7147 5c5e 4849 217d 2c47 544b 2061 4b2c qG\^HI!},GTK aK, 00000110: 4754 2061 592b 654b 4e49 2621 6735 547d GT aY+eKNI&!g5T} 00000120: 5c45 6a54 294e 2e71 3b44 2847 484e 5429 \EjT)N.q;D(GHNT) 00000130: 494e 4971 4868 543d 5a72 4768 7454 496e INIqHhT=ZrGhtTIn 00000140: 5a68 7454 5848 5a2b 6554 4e29 2929 2e3f ZhtTXHZ+eTN))).? 00000150: 4926 6e48 6854 6747 6874 5458 4868 7454 I&nHhTgGhtTXHhtT 00000160: 2b65 5448 3b20 614b 2c64 6932 6931 7230 +eTH; aK,di2i1r0 00000170: 2e7a 2061 592b 654b 6b23 3d4e 2e28 5930 .z aY+eKk#=N.(Y0 00000180: 2836 5c76 6b4e 2928 375c 5e6b 4e29 2838 (6\vkN)(7\^kN)(8 00000190: 5c76 5c3c 4e29 2839 5c76 5c3e 4e29 2831 \v\<N)(9\v\>N)(1 000001a0: 305c 5e5c 3c4e 2928 3131 5c5e 5c3e 4e 0\^\<N)(11\^\>N ``` ## Explanation The main idea for this program was to use regular expressions to modify the input. To save space all these regular expressions are contained in a compressed string. The first step in the program is to decompress the string and to split it int single regular expression and the corresponding replacement strings. ``` .Z"..." Decompress the string c \_ Split the result into pieces (separator is "_") m cd\% Split all pieces (separator is "%") m ck\: Split all sub-pieces (separator is ":") J Assign the result to variable J ``` The contents of variable `J` are then: ``` [[['\\\\ /', '=M='], ['/ \\\\', '=W=']], [[' (?=[V6M=-])', 'V'], ['o(?=[V6M=-])', '6']], [['(?<=[A9W=-]) ', 'A'], ['(?<=[A9W=-])o', '9'], ['(?<=[X0W=-])V', 'X'], ['(?<=[X0W=-])6', '0']], [['6V', 'V6'], ['0X', 'X0'], ['6-', '6='], ['0-', '0='], ['6M', 'VE'], ['0M', 'XE']], [['A9', '9A'], ['X0', '0X'], ['-9', '=9'], ['-0', '=0'], ['W9', 'EA'], ['W0', 'EX']], [['[MW-]']], [['[60]']], [['[90]']], [['V6', '6V'], ['V0', '6X'], ['X6', '0V'], ['X0', '0X']], [['6V', 'V6'], ['0V', 'X6'], ['6X', 'V0'], ['0X', 'X0']], [['A9', '9A'], ['A0', '9X'], ['X9', '0A'], ['X0', '0X']], [['9A', 'A9'], ['0A', 'X9'], ['9X', 'A0'], ['0X', 'X0']]] ``` --- ``` KY Set the variable K to an empty list ``` --- The function `r` applies regex substitutions from the list stored in `J` at the index `G` to all strings in the list `H`. It returns as soon as any of the strings was changed. ``` DrGH Define the function r(G,H) FN@JG ) Loop for all entries in J[G] m:d.*NH Regex substitution, replace N[0] with N[1] in all strings in list H =b Store the result in variable b In HRb If b != H return b RH Return H ``` --- The function `i` is similar to function `r` with 2 differences. It applies the substitutions on a transposed list (vertical instead on horizontal). It also performs the substitutions repeatedly as long as anything is changed. ``` DiNT ; Define the function i(N,T) .tT Transpose the list T urNG Apply r(N,...) repeatedly as long as something changes R.t Transpose the result back and return it ``` --- The function `g` checks if the regex from the list stored in `J` at the index `G` can by found in any string in the list `H`. ``` M Define the function g(G,H) hh@JG Get the single regex stored in J[G] jH) Join all strings in H : 0 Check if the regex is found anywhere in the joined string ``` --- The rest of the code contains the actual program logic. It performs a breadth-first search for the possible movements until a solution is found. The position in the search tree is uniquely defined by the direction of the gravity and a modified copy of the program input. To avoid the processing of the same position again and again, processed positions are stored in the global list `K`. Positions which still have to be processed are stored together with the corresponding part of the solution in the list `Y`. The modification of the input and initialization of `K` and `Y` is performed by the following code: ``` .z Get all input as a line list i2i1r0 Apply the regular expressions stored in J[0] horizontally, and the the ones from J[1] and J[2] vertically ,d Create a list with " " (represents "no gravity set") and the modifed input aK Append the result to the list K eK Retrieve the appended list again + k Append "" to the list (represents the empty starting solution) aY Append the result to the list Y ``` The input modification does something like the following. The input: ``` ---- --/ \ --- -- o ------ ----- ``` is transformed to: ``` VVVVVVVVV----VVV--=W= ---VVVV--AAAXVVVXAAAA 9AXVVVVXAAAAXVVVXAAAA AAXVVVVXAAAAXVVVXAAAA AA------AAAA-----AAAA ``` The values have the following meaning: * `-` Platform which must be still visited * `=` Platform which doesn't need to be visited anymore * `M` Cup which can be entered with gravity set to "down" * `W` Cup which can be entered with gravity set to "up" * `V` Safe to move to this place with gravity set to "down" * `A` Safe to move to this place with gravity set to "up" * `X` Safe to move to this place regardless of the gravity setting * `6` Ball on a place which would be marked as `V` * `9` Ball on a place which would be marked as `A` * `0` Ball on a place which would be marked as `X` The logic is using regular expressions to perform the movements. In the example above, if the gravity would be set to "up", we can replace "9A" with "A9" with an regex to move the ball to the right. This means by trying to apply the regex we can find all possible movements. --- The function `X` performs vertical ball movements based on the current gravity setting, stores the result in global lists `K` and `Y`, and checks if a solution was found. ``` DXGHN ; Define the function X(G,H,N) +3qG\^ Select the correct set of regular expressions based on the current gravity setting G (3 for "v" and 4 for "^") =Ti H Apply i(...,H) and store the result in T I!},GTK If [G,T] not in K aK,GT Store [G,T] in K aY+eKN Store [G,T,N] in Y I&!g5T}\EjT) If J[5] not found in T and T contains "E" (all platforms visited and ball in cup) N.q Print N and exit ``` --- The function `(` implements checks for the 4 directional/gravity buttons. The gravity buttons can be pressed only if the current gravity would change and if the ball is in a safe place to change the gravity. The directional buttons can be pressed only if it is safe to move to the corresponding place. ``` D(GHNT) ; Define the function ( (G,H,N,T) IN ) If N is not empty (contains either "<" or ">" representing directional buttons) IqHhT ) If H (gravity setting for which this test is performed) is equal T[0] (the current gravity) =ZrGhtT Apply r(G,T[1]) and store the result in Z (G is the appropriate regex index for the combination of gravity and directional button, T[1] is the current modified input) InZhtT ) If Z != T[1] (the regex operation changed something, meaning we found a valid move) XHZ+eTN Call X(H,Z,[T[2],N]) .? Else (gravity button pressed) I If ... nHhT H (new gravity setting) is not equal T[0] (current gravity setting) & ... and ... gGhtT J[G] found in T[1] (ball is in an appropriate place to switch gravity) XHhtT+eTH Call X(H,T[1],[T[2],H]) ``` --- Finally the main loop. The first element of `Y` is removed repeatedly, and checks for all possible moves are performed. ``` # Loop until error (Y empty) =N.(Y0 Pop first element of Y and store it in the variable N (6\vkN) Call ( (6,"v","",N) (7\^kN) Call ( (7,"^","",N) (8\v\<N) Call ( (8,"v","<",N) (9\v\>N) Call ( (9,"v",">",N) (10\^\<N) Call ( (10,"^","<",N) (11\^\>N Call ( (11,"^",">",N) ``` ]
[Question] [ There seems to be this ongoing craze about people tediously learning new keyboard layouts like Dvorak or Neo because it supposedly makes them more productive. I argue that switching keyboard layouts is a bad idea, because it can take you months to get up to speed, and when you're finially 5% faster than the rest, you're screwed if you need to type on a computer that isn't your own. Also, all these people forget where the **real** bottleneck in modern communication lies - the telephone keypad. This is how your average telephone keypad looks like: ![The telephone keypad](https://i.stack.imgur.com/7oCLW.png) Letter 'r' is the third letter on button 7; so if you were to type the letter 'r' on a mobile phone, you would press button 7 three times, for 's' you'd press it 4 times, and for 'a' you'd press button 2 once. Considering this, putting 'e' after 'd' was probably a bad decision - 'e' is the most commonly used letter in the english alphabet, so, if you were to label button 3 "EDF" instead of "DEF", you would save quite a lot of keystrokes. Moreover, you've probably experienced yourselves that typing 2 letters that share the same button is a nuisance - if you want to write "TU", you can't just hit 8 three times, because that would result in 'V'. So usually you'd write 'T', then hit space, then hit backspace, and then write 'U', which equals 5 button presses instead of 3. --- ## TL;DR Given these two rules: * A letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label * Writing two letters that are typed using the same button requires an additional 2 button presses What's the telephone keyboard layout that requires the least amount of button presses, given a specific text? You should only use the buttons 2-9, 1 and 0 are reserved for special symbols. ### Input The text which you should find the optimal layout for is supplied via stdin. You don't need to handle anything other than the lowercase alphabet and can assume that the input consists of only that. You can also assume that the input text is reasonably large and every letter is in there at least once, if that helps. ### Output I don't want to put too many constraints on the output, since that sometimes gives some languages advantages over others; so however your language shows arrays is fine, alternatively you can seperate each label with a newline. There may be multiple possible optimal layouts, you can print any one of them. Here's a simple example: ``` >> echo "jackdawslovemybigsphinxofquartz" | foo.sh ojpt avhz cen skm dyf wbq ixu lgr ``` ### Bonus Points **-35** if your algorithm is not brute-forcing all possible layouts (I'm looking at Haskell's `permutations' here) **-3** if your code fits inside a text message (140 chars) and you post a pic of you sending your code to a friend. **This is my first challenge on StackExchange.** I'd be happy to hear whether you like it, or have any other feedback about it! [Answer] ## Perl, 333 ``` $_=<>;$c{$&}++while/./g;@c=sort{$c{$b}<=>$c{$a}}keys%c;$d{$&.$1}++while/.(?=(.))/g;sub f{my$x=shift;if(my$c=pop@$x){for(grep!$_[$_],0..7){my@y = @_;$y[$_]=$c;f([@$x],@y)}}else{for(0..7){$z=$_[$_];$c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]}}$c<$m?($m=$c,@n=@_):1}}while(@c){$m= ~0;f[splice@c,0,8];push@{$a[$_]},$n[$_]for 0..7}print@$_,$/for@a ``` Here's an attempt to optimize for rule #2. After my comment, above, and in lieu of answers taking that rule into account (cf. high question rating), I thought that I owe some effort here... Solutions that don't optimize for rule #2 can produce output very far from optimal. I checked long natural English text ("Alice in Wonderland", actually), pre-processed (lower case letters only), and e.g. Perl script from OJW's answer, result being ``` 2: ermx 3: tdfz 4: alp 5: oub 6: ick 7: nwv 8: hgj 9: syq ``` `er` alone ruins it, plus some other pairs should never have ended on the same key... Btw, `zxqjvkbpfmygwculdrshnioate` are letters sorted, frequency ascending, from that text. If we try to solve it easy way (hoping for -35 bonus, maybe) and place letters one by one, choosing available key by minimal pair-wise count, we can end with e.g.: ``` slbx hdmz nrf iuj ogv awk tcp eyq ``` I don't post code for this (wrong) solution here. E.g., note, `c` is more frequent than `w` and is placed first. `tc` (`ct`) pairs are obviously less frequent than `ac` (`ca`) - 43+235 against 202+355. But then `w` ends up with `a` -- 598+88. We end with pairs `aw` and `tc` (964 total), though it would be better `ac` and `tw` (635 total). Etc.. So, next algorithm tries to check each 8 remaining (or 2, if last) most frequent letters against letters already on the keypad, and to place them so that pair-wise count is minimal. ``` $_=<>; # Read STDIN. $c{$&}++while/./g; # Count letters (%c hash). @c=sort{$c{$b}<=>$c{$a}}keys%c; # Sort them by frequency, ascending $d{$&.$1}++while/.(?=(.))/g; # (@c array), and count pairs (%d hash). # Next is recursive sub that does the job. # Some CPAN module for permutations # would probably do better... # Arguments are reference to array of what's # left un-placed of current 8-pack of letters, sub f{ # and 8 element list of placed letters my$x=shift; # (or undefs). if(my$c=pop@$x){ # Pop a letter from 8-pack (if anything left), for(grep!$_[$_],0..7){ # try placing it on each available key, and my@y = @_; # call sub again passing updated arguments. $y[$_]=$c; f([@$x],@y) } }else{ # If, OTOH, 8-pack is exhausted, find sum of for(0..7){ # pairs count of current permutation (@_) and $z=$_[$_]; # letters placed in previous rounds (8-packs). # @a is "array of arrays" - note, we didn't # have to initialize it. First "8-pack" will # be placed on empty keypad "automatically". # We re-use undefined (i.e. 0) $c. $c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]} } $c<$m # Is sum for current placement minimal? ?($m=$c,@n=@_) # Then remember this minimum and placement. :1 } } while(@c){ $m= ~0; # Initialize "minimum" with large enough f[splice@c,0,8]; # number, then call sub with each 8-pack # (and empty list of placed letters # from current round). On return, # @n will have optimal arrangement. push@{$a[$_]},$n[$_]for 0..7 # Then place it permanently on keypad. } print@$_,$/for@a # Show us what you've done. ``` Result is: ``` sdfz hlmx nrv iyp ogk acq twb euj ``` I don't like the `ac` pair (The Cat being one of the characters, after all), but, still that's optimal letter placement for English, if my code is not wrong. Not exactly 'golfing' effort, just some working solution, ugly or not. [Answer] # Python3, it's Montecarlo Time! To solve this problem, I first count how many "clicks" you need with the default keyboard (intially: `abc,def,ghi,jkl,mno,pqrs,tuv,wxyz`). Then I modify this keyboard and see if it is cheaper (the text is written in less clicks). If this keyboard is cheaper, then it becames the default one. I iterate this process `1M` times. To change the keyboard I first decide how many changes to make (the maximum number of changes is the total number of letters n the keyboard). Then, for every switch, I choose two buttons and two positions and I transfer a character from the first position to the second one. The maximum number of switches per time is the number of letters in the keyboard becouse it is the minimum number of changes you need to switch from two complete different keyboards. (I want that it is always possible to switch from one keyboard to any other one) The output of `echo "jackdawslovemybigsphinxofquartz" | python .\myscript.py` is: ``` 61 ['anb', 'sef', 'hjc', 'iykl', 'odm', 'qgr', 'tuxv', 'wpz'] ``` Where `61` is the number of button pressed to compose a given message. **Characters (no spaces and no comments): 577** I know its long but I'm really new to this stuff. ``` from random import * S=['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'] def P(L): # perform a switch of the keys of the keyboard:to switch from a given keyboard to another, the maximum number of exchanges is the number of the keys. R=randint N = len(''.join(L)) W = randint(1,N) # decide how many switches to perform EL = list(L) for i in range(0,W): B1=R(0,len(EL)-1) # decide what buttons are considered in the switch B2=R(0,len(EL)-1) if len(EL[B1])==0: continue P1=R(0,len(EL[B1])-1) # decide what letter to switch and where if len(EL[B2])==0: P2=0 else: P2=R(0,len(EL[B2])-1) C1 = EL[B1][P1] EL[B1]=EL[B1].replace(C1,'') EL[B2]=EL[B2][:P2]+C1+EL[B2][P2:] return EL def U(L,X): # count how many clicks you need to compose the text X S=0 Z=' ' for A in X: for T in L: if A in T and Z not in T: S+=1+T.index(A) if A in T and Z in T: S+=3+T.index(A) # if the last character was in the same button..here the penality! Z=A return S X=input() n_iter=10**6 L = list(S) cc=U(L,X) print(cc,L) for i in range(0,n_iter): #do some montecarlo stuff cc=U(L,X) pl=P(L) pc=U(pl,X) if(cc>pc): L=pl print(pc,L) ``` --- I found it so funny that I decided to try this algorithm with **LO HOBBIT** (I have an original copy at home too!). It has `383964` letters and these are the couple **clicks** vs **keypad** that I'm finding: ``` 909007 ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] 879344 ['abkc', 'def', 'gqhi', 'jl', 'mno', 'rs', 'tupv', 'wxyz'] 861867 ['abg', 'def', 'qhyi', 'jcl', 'mno', 'r', 'tupxv', 'swkz'] 851364 ['abg', 'e', 'qchi', 'jyl', 'mn', 'dr', 'tupxv', 'sowkfz'] 829451 ['ag', 'ef', 'qchi', 'jyl', 'mn', 'dbr', 'tupxv', 'sowkz'] 815213 ['amg', 'ef', 'qch', 'ojyl', 'i', 'dbnr', 'tupxv', 'swkz'] 805521 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'dbnr', 'tupxv', 'swkz'] 773046 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'bnr', 'tupxv', 'dswkz'] 759208 ['amg', 'eqf', 'ch', 'ojyl', 'i', 'bnr', 'tupxv', 'dswkz'] 746711 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tupxv', 'dwz'] 743541 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tpxv', 'dwuz'] 743389 ['ag', 'ekq', 'clh', 'sojy', 'i', 'nmfr', 'tpxbv', 'dwuz'] 734431 ['ag', 'ekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dowumz'] 705730 ['ag', 'oekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dwumz'] 691669 ['ag', 'oekq', 'lh', 'nsjy', 'ic', 'rf', 'tpxbv', 'dwumz'] 665866 ['ag', 'hokq', 'el', 'nsjy', 'ic', 'rbf', 'tpxv', 'dwumz'] 661610 ['agm', 'hokq', 'e', 'nsj', 'ilc', 'rbf', 'tpyxv', 'dwuz'] ``` So I claim this last one is one of the most practical keypad (in terms of clicks). [Answer] Well if you just want the most popular characters assigned to the bins 2-9, Perl can do that in 127 chars... ``` foreach(split /\s*/,<>){$x{$_}++} foreach(sort{$x{$b}<=>$x{$a}}keys %x){$o{$n++%8}.=$_} for(0..7){printf "%d: %s\n",$_+2,$o{$_}} ``` giving something like: ``` echo "jackdawslovemybigsphinxofquartz" | perl ./keypad.pl 2: ajeb 3: iynz 4: suv 5: ohm 6: wkl 7: rgp 8: xfc 9: dtq ``` Or print it all on one line, removing 12 characters: ``` foreach(split /\s*/,<>){$x{$_}++} foreach(sort{$x{$b}<=>$x{$a}}keys %x){$o[$n++%8].=$_} print join",",values@o,"\n"; ``` [Answer] # Haskell, 160 - 35 = 125 ``` import Data.List import GHC.Exts main=interact f where f s=show$transpose$map($sortWith(\x->length$filter(/=x)s)['a'..'z'])[t,t.d,t.d.d,d.d.d];t=take 8;d=drop 8 ``` Example: ``` $ runhaskell % <<< "jackdaws loves my big sphinx of quartz" ["afpy","sgqz","ihr","ojt","bku","clv","dmw","enx"] $ </usr/share/dict/propernames tr A-Z a-z | runhaskell % ["atjx","edgq","rhb","nmp","iyv","lcf","ouw","skz"] ``` One might argue that this does not optimize for rule 2, but it does put most frequent letters on *different* keys. [Answer] # JavaScript, 192 - 35 = 157 Just noticed the repeating characters rule; this doesn't take that into account. But as @mniip noted in his answer: > > One might argue that this does not optimize for rule 2, but it does put most frequent letters on *different* keys. > > > ``` o={} a=[] b=['','','','','','','',''] i=-1 s.split('').forEach(function(x){o[x]=o[x]?o[x]+1:1}) for(x in o)a.push([o[x],x]) a.sort().reverse().forEach(function(x){b[i=(i+1)%8]+=x[1]}) alert(b) ``` This would have probably been in Ruby, but I'm not at home and am being forced to use Internet Explorer (eww). But hey, it's sometimes fun using languages terrible at golfing to golf! ;) Sample output (for your input): ``` avlc,sukb,otj,irh,zqg,ypf,xne,wmd ``` Since JS has no STDIN, the program assumes that input is stored in variable `s`. [Answer] # Python (119-35=84): Assuming the string is a variable a, and only contains lowercase letters: ``` for h in range(8): print h+2,zip(*sorted([(__import__("collections").Counter(a)[d],d) for d in set(a)])[::-1])[1][h::8] ``` ungolfed: ``` import collections #a="jackdawslovemybigsphinxofquartz" a=__import__("string").lowercase b=collections.Counter(a) c=set(a) d=[(b[d],d) for d in c] e=sorted(d) f=e[::-1] g=zip(*f)[1] for h in range(8): print h+2,g[h::8] ``` # [PYG](https://gist.github.com/Synthetica9/9796173#file-pyg-py-L100) (76-35=41): Aaah, we can drop the enourmous import. Again, this assumes the stripped string is in a. ``` for h in R(8): print h+2,Z(*S([(CC(a)[d],d) for d in Se(a)])[::-1])[1][h::8] ``` ]
[Question] [ ## Background Most people on here should be familiar with a few integer base systems: decimal, binary, hexadecimal, octal. E.g. in the hexadecimal system, a number \$abc.de\_{16}\$ would represent $$a\times16^2 + b\times16^1 + c\times16^0 + d\times16^{-1} + e\times16^{-2}$$ However, one can also use non-integer bases, like irrational numbers. Once such base uses the golden ratio \$ฯ† = \frac{1+โˆš5}2 โ‰ˆ 1.618...\$. These are defined analogously to integer bases. So a number \$abc.de\_ฯ†\$ (where \$a\$ to \$e\$ are integer digits) would represent $$a\timesฯ†^2 + b\timesฯ†^1 + c\timesฯ†^0 + d\timesฯ†^{-1} + e\timesฯ†^{-2}$$ Note that in principle any of the digits could be negative (although we're not used to that) - we'll represent a negative digit with a leading \$\text{~}\$. For the purpose of this question we restrict ourselves to digits from \$\text{~}9\$ to \$9\$, so we can unambiguously write a number as one string (with tildes in between). So $$-2\timesฯ†^2 + 9\timesฯ†^1 + 0\timesฯ†^0 + -4\timesฯ†^{-1} + 3\timesฯ†^{-2}$$ would be written as \$\text{~}290.\text{~}43\$. We call such a number a **phinary number**. A phinary number can always be represented in *standard form*, which means that the representation uses only digits \$1\$ and \$0\$, without containing \$11\$ anywhere, and with an optional minus sign to indicate that the entire number is negative. (Interestingly, every integer has a unique finite representation in standard form.) Representations which are not in standard form can always be converted into standard form using the following observations: 1. \$011\_ฯ† = 100\_ฯ†\$ (because \$ฯ†^2 = ฯ† + 1\$) 2. \$0200\_ฯ† = 1001\_ฯ†\$ (because \$ฯ†^2 + \frac1ฯ† = 2ฯ†\$) 3. \$0\text{~}10\_ฯ† = \text{~}101\_ฯ†\$ (because \$ฯ† - \frac1ฯ† = 1\$) In addition: 4. If the most significant digit is \$\text{~}1\$ (with the rest of the number being standard form), the number is negative, and we can convert it into standard form by swapping all \$1\$ and \$\text{~}1\$, prepending a minus sign, and applying the above three rules again until we obtain the standard form. Here is an example of such a normalisation of \$1\text{~}3.2\text{~}1\_ฯ†\$ (I'm using additional spaces for positive digits, to keep each digit position aligned): ``` 1~3. 2~1ฯ† Rule: = 0~2. 3~1ฯ† (3) = ~1~1. 4~1ฯ† (3) = ~1 0 0. 4~1ฯ† (3) = ~1 0 0. 3 0 1ฯ† (3) = ~1 0 1. 1 0 2ฯ† (2) = ~1 1 0. 0 0 2ฯ† (1) = ~1 1 0. 0 1 0 0 1ฯ† (2) = - 1~1 0. 0~1 0 0~1ฯ† (4) = - 0 0 1. 0~1 0 0~1ฯ† (3) = - 0 0 1.~1 0 1 0~1ฯ† (3) = - 0 0 0. 0 1 1 0~1ฯ† (3) = - 0 0 0. 0 1 1~1 0 1ฯ† (3) = - 0 0 0. 0 1 0 0 1 1ฯ† (3) = - 0 0 0. 0 1 0 1 0 0ฯ† (1) ``` Yielding \$-0.0101\_ฯ†\$. For further reading, Wikipedia has a very [informative article](http://en.wikipedia.org/wiki/Golden_ratio_base) on the topic. ## The Challenge Hence, or otherwise, write a program or function which, given a string representing a phinary number (as described above), outputs its standard form, without leading or trailing zeroes. The input does not necessarily contain the phinary point, but will always contain the digit left of it (so no \$.123\$). The output must always include the phinary point and at least one digit to the left of it. You may take input via STDIN, ARGV or function argument and either return the result or print it to STDOUT. You may use a different algorithm than the above procedure as long as it is in principle correct and exact for arbitrary (valid) inputs - that is, the only limits which could potentially break your implementation should be technical limitations like the size of built-in data types or the available RAM. For instance, evaluating the input as a floating-point number and then picking digits greedily is not allowed, as one could find inputs for which floating-point inaccuracies would lead to incorrect results. This is code golf, the shortest answer (in bytes) wins. ## Test Cases ``` Input Output 1 1. 9 10010.0101 1.618 10000.0000101 1~3.2~1 -0.0101 0.~1021 0. (or -0.) 105.~2 1010.0101 ~31~5.~1 -100000.1001 ``` [Answer] # Javascript (ES6) - ~~446~~ ~~418~~ ~~422~~ 420 bytes Minified: ``` F=s=>{D=[];z='000000000';N=t=n=i=e=0;s=(z+s.replace(/^([^.]*)$/,'$1.')+z).replace(/~/g,'-').replace(/-?\d/g,s=>((D[n++]=s/1),0));for(;i<n-3;i=j){if(p=D[j=i+1]){if(!e&&p<0){D=D.map(k=>-k);N=~N;p=-p}e=1}d=D[i];x=D[i+2];m=D[i+3];if(p<0){d--;p++;x++;e=j=0}if(p>1){d++;m++;p-=2;e=j=0}if(!d&&p*x==1){d=p;e=j=p=x=0}D[i]=d;D[i+1]=p;D[i+2]=x;D[i+3]=m}return(N?'-':'')+s.replace(/0/g,()=>D[t++]).replace(/^(0(?!\.))+|0+$/g,'')} ``` Expanded: ``` F = s => { D = []; z = '000000000'; N = t = n = i = e = 0; s = (z + s.replace( /^([^.]*)$/, '$1.' ) + z).replace( /~/g, '-' ). replace( /-?\d/g, s => ((D[n++]=s/1),0) ); for( ; i < n-3; i = j ) { if( p = D[j = i+1] ) { if( !e && p < 0 ) { D = D.map( k=>-k ); N = ~N; p = -p; } e = 1; } d = D[i]; x = D[i+2]; m = D[i+3]; if( p < 0 ) { d--; p++; x++; e = j = 0; } if( p > 1 ) { d++; m++; p-=2; e = j = 0; } if( !d && p*x == 1 ) { d = p; e = j = p = x = 0; } D[i] = d; D[i+1] = p; D[i+2] = x; D[i+3] = m; } return (N ? '-' : '') + s.replace( /0/g, ()=>D[t++] ).replace( /^(0(?!\.))+|0+$/g, '' ); } ``` The code produces a function `F` that performs the specified conversion. It's a tough problem to golf. Numerous edge cases creep up that prevent simplification of the code. In particular, dealing with negatives is a pain, both in terms of parsing and in terms of logical handling. I should note that the code only handles a "reasonable range" of inputs. To extend the domain of the function without bound, the number of zeros in `z` can be increased, and the constant bounding the `while( c++ < 99 )` loop can be increased. The range currently supported is already overkill for the supplied test cases. ### Sample Outputs ``` F('1') 1. F('9') 10010.0101 F('1~3.2~1') -0.0101 F('0.~1021') -0. F('105.~2') 1010.0101 F('~31~5.~1') -100000.1001 ``` The `-0.` isn't pretty, but the answer is still correct. I can fix it if necessary. [Answer] # Haskell, 336 bytes ``` z=[0,0] g[a,b]|a*b<0=g[b,a+b] g x=x<z k![a,b,c,d]=[b,a+b,d-c+read k,c] p('.':s)=1:0:2`drop`p s p('~':k:s)=['-',k]!p s p(k:s)=[k]!p s p[]=1:0:z [1,0]&y='.':z?y [a,b]&y=[b,a+b]?y x@[a,b]?y@[c,d]|x==z,y==z=""|g y='-':x?[-c,-d]|g[c-1,d]='0':x&[d,c+d]|g[c,d-1]='1':x&[d,c+d-1]|0<1=[b-a,a]?[d-c,c] m[a,b,c,d]=[1,0]?[a*d+b*c-a*c,a*c+b*d] f=m.p ``` This is the greedy algorithm, but with an exact representation `[a,b]` of numbers *a* + *bฯ†* (*a*, *b* โˆˆ โ„ค) to avoid floating-point errors. `g[a,b]` tests whether *a* + *bฯ†* < 0. Usage example: ``` *Main> f "9" "10010.0101" *Main> f "1~3.2~1" "-0.0101" *Main> f "0.~1021" "0." ``` ]
[Question] [ # Task Given a non-negative number, check if it's odd or even. In case it's even, output that number. Otherwise, throw any exception/error that your language supports, and stop the program. # Example with Python Input: `1` Output: ``` Traceback (most recent call last): File ".code.tio", line 1, in <module> IfYouWantThenThrowThis NameError: name 'IfYouWantThenThrowThis' is not defined ``` # Another example Input: `2` Output: `2` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with shortest bytes wins. * [These](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) loopholes are, obviously, forbidden. * Standard code-golf rules apply. * Please specify the language you are using and the amount of bytes. * It would be great if you would put a link to a sandbox where your code can be ran in action, such as [TIO](https://tio.run). * Explaining your code is very welcomed. --- # LEADERBOARD ``` <script>var QUESTION_ID=229052,OVERRIDE_USER=0;</script><style>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}</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>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)}}</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 2](https://docs.python.org/2/), 16 bytes ``` lambda n:n<<n%-2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKs/GJk9VFyiYX6SQp5CZpxBtqGOkY6xjomMaa8WlUFCUmVeikKfDpVBSVAnkQwXSNPI0uRRSK5JTC0oUwhJzSlNdi4ryixAKlMB8Ja7/AA "Python 2 โ€šร„รฌ Try It Online") The expression `n%-2` equals 0 for even `n` and -1 for odd `n`. Bit-shifting `n` by 0 positions leaves it unchanged, but for -1 positions it gives an error for "negative shift count". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Mยทโˆร‡ยฌยฐ ``` [Try it online!](https://tio.run/##y0rNyan8/9/34Y6mQwv///9vBAA "Jelly โ€šร„รฌ Try It Online") (even) and [Try it online!](https://tio.run/##y0rNyan8/9/34Y6mQwv///9vDAA "Jelly โ€šร„รฌ Try It Online") (odd) ## How it works `M` is an atom meaning "Given a list, yield the indices of that maximal elements". Now, typically, when given integer arguments to its array functions, Jelly promotes them to either a range, to digits, or just wraps it. Unfortunately, (I'm guessing due to `M`'s age - it was one of the earliest builtins in Jelly), `M` doesn't do this, and throws an error as it can't iterate over an integer. How the code actually works: ``` Mยทโˆร‡ยฌยฐ - Main link. Takes N on the left ยทโˆร‡ - Bit; Calculate N % 2 ยฌยฐ - Do the following a number of times equal to N % 2: M - Run the M builtin on N ``` If the input `N` is even, then `ยทโˆร‡` yields `0` and `ยฌยฐ` runs `M` on `N` `0` times i.e. an identity function. If the input is odd, then `ยทโˆร‡` yields `1` and `ยฌยฐ` runs `M` once, which is enough to error it [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 13 bytes ``` ?#\.@!:.!_@\| ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/99eOUbPQdFKTzHeIabm/38LS0MjY3MTC0tjE0MLI0tjU3NDC0ugiKkFUNzS3ATMAzEtoOrAFIRnClUJAA "Hexagony โ€šร„รฌ Try It Online") Expanded: (Made using [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer)) [![Hexagony Colorer Map](https://i.stack.imgur.com/g1mGK.png)](https://i.stack.imgur.com/g1mGK.png) This code is built around Hexagony's `#` operator. Hexagony initializes with 6 IP's, 1 in each corner of the code box, with the 0th one, the one in the top left, being active in the beginning. The `#` operator takes the value of the current memory cell mod 6, and then sets the corresponding IP as the active one. So making an even/odd checker is a matter of using the `#` operator and then having IP's 1,3, and 5 perform the 'odd' action, and IP's 0,2, and 4 perform the 'even' action. The consequence of doing it this way is that there are 6 separate paths that each need to be mapped to the correct endpoint, hence the mess of paths. In this case, the odd action is `:` (attempt to divide two non-existent values, resulting in a divide by zero error) and the even action is `!@` (print and terminate). To make it hopefully a bit more readable, here's a very low-tech drawing of the paths: [![Hand-drawn map](https://i.stack.imgur.com/lhX32.jpg)](https://i.stack.imgur.com/lhX32.jpg) The paths are: * n%6 == 0 : Green * n%6 == 1 : Yellow * n%6 == 2 : Blue * n%6 == 3 Pink * n%6 == 4 : Orange * n%6 == 5 : Red I'm pretty confident 12 bytes is possible, and potentially even shorter. Not sure if there's a better approach entirely, but with this method, it seems just about brute-force-able. It seems it should only require `?`,`#`, no more than 3 each of `@`,`!`, and `:`, and some control flow characters. [Answer] # x86 Machine Code, 5 bytes ``` A8 01 74 01 F4 ``` Takes the integer value of your choice in the `EAX` register, halts the CPU if the number is odd, or continues execution harmlessly if the number is even. Ungolfed assembly language mnemonics: ``` A8 01 test al, 1 74 01 jz IsEven F4 hlt IsEven: ``` The first two instructions (`test`+`jz`) are the fastest and smallest way to check whether an integer value is even or odd in x86 machine code. The reason they work is hopefully obvious: for binary numbers, the least-significant bit (bit 0) is only set if the number is odd (for even numbers, the least-significant bit is clear). Therefore, testing the least-significant bit and seeing if it is non-zero is the easiest, simplest, smallest, and fastest way to see whether a number is even. Here, I've used `jz` to jump if the zero flag (ZF) is setโ€šร„รฎi.e., if the bit we tested (bit 0) was zero, which means that it jumps if the number was even. Note that it jumps *over* the halt (`hlt`) instruction if the input value was even. If the input value was odd, then execution falls through the jump, and ends up halting the CPU. If you don't like `hlt` because you don't think that counts as throwing an exception/error, then replace it with an `int 3` instruction, which is also only 1 byte (`0xCC`), and thus doesn't change the overall code size (5 bytes). The `int 3` instruction is the trap to a debugger. The only way you could really argue that this code is cheating is that it doesn't "output" that number. I'd say it does: it allows execution to continue past the point where that number was generated, which is a lot like outputting it. You don't get any output for odd inputs; you can only get output for even inputs. Besides that, I think this is allowed by many, many different [agreed-upon input/output methods](https://codegolf.meta.stackexchange.com/q/2447). --- # x86 Machine Code, 6 bytes (non-competing) A division by 0 is another obvious solution, but it doesn't save any bytes. Even if you are willing to allow clobbering the input value, in order to arrange for a division by zero, you have to negate somewhere (either the original value, or the isolated LSB), and that requires an extra instruction (either `XOR`ing with 1, or a `NOT`), which means 2 extra bytes. ``` A8 01 test al, 1 34 01 xor al, 1 F6 F0 div al ``` That's 6 bytes, and I'm not even sure that I can figure out how to justify this clobbering of the original input value as being consistent with the requirements of the challenge to "output" the value. To avoid clobbering, there are a few different options. For example, we can stipulate that the input is taken in a different register (say, `ECX`). But this means that we can't use the short "implied accumulator" encoding of `test` and `xor`, so it costs us at least two bytes. (We could use `not` with the full register before the `test` to invert the bits, which is encoded in only 2 bytes, but that defeats the point, which is to avoid clobbering the input.) Or, we could `push` and `pop` the input, but that also costs two extra bytes (one for each, `push` and `pop`). Maybe I'm missing something obvious, but I'm not seeing a better solution here. [Answer] # [Java (JDK)](http://jdk.java.net/), 10 bytes ``` n->n/=~n&1 ``` [Try it online!](https://tio.run/##fVA9T8MwEN3zK54qBTmUGMrYECQGBoaKoWJCDK7jBIfEtuxLRYTKXw8mohUDYrl7p/dxp2vFXuRt9Tbp3llPaOPMB9IdrwcjSVvDz4tEdiIEbIQ2@EgAN@w6LRFIUGx7qyv0kWNb8to0zy8QvgnZLAUeDD0Z4cdHp7wg61GjnEx@ay7LT3O2mopZVUeCaUPQKJGvrooIbkrMYLk8ZgHbMZDquR2Iu7iMarZIr6s1FhfQWfEjIj@eDH9bqtRER82Fc914F@KNTGcn/wFSkHwFu3@Xyn0/ASr7P1F5b/0aaZiDFW8UbVQIolHsV25yrIfkMH0B "Java (JDK) โ€šร„รฌ Try It Online") ## Explanations This code basically divides by zero when the input number is odd or by one when it is even. ### `~n` The `~` character negates each bit of `n` because `n&1` returns `0` when `n` is even and `1` when it's odd, but we want the opposite: `0` when odd (to make it fail) and `1` when even to return it, so `~` is the easiest way to negate the last bit. ### `~n&1` This is the part that reduces `n` to either `0` or `1`. `~n&1` is not exactly the same as `~n%2` because, in Java, `%2` keeps the signum of `n`, and since we definitely swap the signum with `~`, we'd always end up with negative number, not matter what `n` is: if `n<0` we'd get negative divided by positive, and if `n>=0`, we'd get positive divided by negative. We want to divide by `0` or by `1`, nothing else. Only `&1` can guarantee that. No matter what, the operator priority will first evaluate `~n` so no parenthesis are required. ### `/=` This bit is weird. Why do we do divide and assign, instead of just dividing? Technically, `n/~n&1` will be parsed as `x=n/~n` then `x&1`. This is not the behavior we want: `n/~n` is always equal to `0`. What we want is to have `n/(~n&1)`. It could work well, but the whole answer would be `n->n/(~n&1)`. The `/=` operator is a shortcut to that as it evaluates the right-hand side entirely, so we can get rid of parenthesis, gaining one byte. Assigning is a side effect we can live with. [Answer] # MATLAB/Octave, ~~17~~ ~~13~~ 12 bytes *-4 bytes thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)* ``` @(x)x(i^2^x) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCs0IjM84orkLzf5ptYl6xNRdXSmZxgYa6Z15BaYmVkbomlO9fWgISAPLTNIw00VSZYVdmhqbOEChcUlQJlDKEqXctKsovUsjLL1EoySjKL88DqkhOLEnOUHCFKHDVy00tLk5MT9XkSs1LQTPOHGGeOXkG/gcA "Octave โ€šร„รฌ Try It Online") Anonymous function. Throws indexing error for odd numbers. This function returns element from input at index `i^2^x = (-1)^x`, so * at index `1` for even numbers (which is input itself) * at index `-1` for odd numbers (which is invalid index since indices in MATLAB start at 1) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes I think this uses an approach that isn't yet represented in the other answers. *โ€šร„รฌ1 byte thanks to att!* ``` #+0^I^#^2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1nbIM4zTjnOSO2/S360QkBRZl5JtJJnXkFpia2SjkK2jgKQzC8tgfDTo7NjY3UUqoHChjoKJrUKsf//AwA "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") Here `I` represents the imaginary number *i*. Since the square of every even number is a multiple of 4, `I^#^2` equals 1 when the input is even, and so `0^I^#^2` becomes \$0^1\$ which is a perfectly nice 0 to add to the input. However, since the square of every odd number is one more than a multiple of 4, `I^#^2` equals *i* when the input is odd, and so `0^I^#^2` becomes \$0^i\$ which throws an "Indeterminate expression " error. ## first submission: 11 bytes ``` #+0^(-1)^#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1nbIE5D11AzTlntv0t@tEJAUWZeSbSSZ15BaYmtko5Cto4CkMwvLYHw06OzY2N1FKqBwoY6Cia1CrH//wMA "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") Since โ€šร„รฌ1 to an even power equals 1, `0^(-1)^#` becomes \$0^1\$ when the input is even, which is a perfectly nice 0 to add to the input; however, since โ€šร„รฌ1 to an odd power equals โ€šร„รฌ1, `0^(-1)^#` becomes \$0^{-1}\$ (the reciprocal of 0) when the input is odd, which throws an error. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes ``` โ€šร‡ร‡ยทโˆโ‰  ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%82%E1%B8%AD&inputs=42&header=&footer=) -1 thanks to Aaron Miller ``` โ€šร‡ร‡ # Is_even(n) (Vyxal has no booleans, only 0 and 1) ยทโˆโ‰  # Integer division (ordinary division doesn't error on 0) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~31~~ ~~25~~ ~~14~~ 19 bytes *-6 bytes thanks to @mazzy* ``` param($n)$n/!($n%2) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPXxFIqxpp/v//3xAA "PowerShell โ€šร„รฌ Try It Online") Calculates the modulo of the input number and `2`, implicitly converts the result to a boolean in order to negate it, then divides the input number by the negation. Inadvertently ditched the spec for a while there, sorry! [Answer] # [R](https://www.r-project.org/), 20 bytes ``` n=scan();n+(n%%2&&a) ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOk9bI09V1UhNLVHzv8l/AA "R โ€šร„รฌ Try It Online") The `&&` operator is logical AND, evaluating left to right until the result is determined. If `n` is even then `n%%2` is `0`, coerced to `FALSE`, and the `a` part of the expression is therefore not evaluated. We then output `n+0`, ie `n`. If `n` is odd, then `n%%2` is 1, coerced to `TRUE`, and we need to evaluate the `a` part of the expression to determine the result of `n%%2&&a`. Since `a` is undefined, this produces an error. This strategy comes out 3 bytes shorter than [Dominic's strategy](https://codegolf.stackexchange.com/a/229061/86301) with `if`. [Answer] # [Python 2](https://docs.python.org/2/), 17 bytes ``` lambda n:n/(~n%2) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk9foy5P1Ujzf0FRZl6JRpqGkaYmF4xtrKn5HwA "Python 2 โ€šร„รฌ Try It Online") thanks to @hyper-neutrino for -4 bytes # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda n:n%2and 1/0 or n ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk/VKDEvRcFQ30Ahv0gh739BUWZeiUaahpGmJheMbayp@R8A "Python 3 โ€šร„รฌ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 10 bytes ``` n=>n%2?_:n ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5P1cg@3irvf3J@XnF@TqpeTn66RpqGiaYmF6qIqabmfwA "JavaScript (Node.js) โ€šร„รฌ Try It Online") Not a very hard answer [Answer] # MMIX, 12 bytes (3 instrs) ``` ihateodds PBEV $0,0F // if(n even) goto ret; LDVTS $0,$0,6 // privileged instruction 0H POP 1,0 // ret: return n ``` The `LDVTS` tries to make whatever memory page the input points to RWX in the cache, though not in the page table (if the input is one more than a multiple of 8). This is a privileged instruction for obvious reasons. [Answer] # [Python 3](https://docs.python.org/3/), 17 bytes ``` lambda x:[x][x%2] ``` [Try it online!](https://tio.run/##K6gsycjPM/5fYZuZV6KRmVdQWqKhqcmVZqvxPycxNyklUaHCKroiNrpC1Sj2vyZXQRFIWZpGhabmfyMA "Python 3 โ€šร„รฌ Try It Online") It's very simple - construct a list with a single (zeroth) number and take an element of it with index equal to that number modulo 2. Since there is no element 1, it will obviously throw an exception on odd input. [Answer] # [PHP](https://php.net), 14. ``` die($argv[0]); ``` There's no need to differentiate odd and even. The criteria say odd numbers can display *any* error, while even ones should be displayed. Since the criteria allow for ANY error on an even number, and die() displays an error and terminates, the input is fine as an error. The criteria allow for even numbers to be displayed in any manner, including as an error, so again, the input is fine as an error. But if die() isn't accepted as an error, and a genuine terminating error's required... **~~27~~ 26 bytes**. Sadly we can't use `die()` here... ``` echo($a=$argv[1])%2?$b:$a; ``` If warnings are acceptable as errors, then in the comments [Matthew Anderson](https://codegolf.stackexchange.com/users/94492/matthew-anderson)'s suggestion to use division by zero also gives us **26 bytes**: ``` echo($a=$argv[1])/!($a%2); ``` [Answer] # [Factor](https://factorcode.org/), 15 bytes ``` [ 2 / 1 shift ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFQUJRaUlJZUJSZV6JgzcVlpGD8P1rBSEFfwVChOCMzrUQhFsjXU4hVSM7PLcgvTlVIynT4DwA "Factor โ€šร„รฌ Try It Online") *Thanks to @umnikos* # [Factor](https://factorcode.org/), 19 bytes ``` [ dup 1 + 2 mod / ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFQUJRaUlJZUJSZV6JgzcVlpGD8P1ohpbRAwVBBW8FIITc/RUFfIRYopqcQq5Ccn1uQX5yqkJTp8B8A "Factor โ€šร„รฌ Try It Online") Throws a divide by zero error on odd numbers, while returning even numbers. ## Explanation: * `dup` Duplicate the input. **Stack:** (e.g.) `2 2` * `1 +` Add one. **Stack:** `2 3` * `2 mod` Modulo two. **Stack:** `2 1` * `/` Divide. (Here is where the error happens for odd input.) **Stack:** `2` Here's a slightly longer version that simply asserts the number is not odd: ``` [ dup odd? f assert= ] ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 13 bytes ``` +`[13579]$ 99 ``` [Try it online!](https://tio.run/##K0otycxL/P9fOyHa0NjU3DJWhcvS8v9/IwA "Retina 0.8.2 โ€šร„รฌ Try It Online") Explanation: If the number is odd, simply keeps appending `9`s until Retina eventually runs out of memory, or until TIO kills it, whichever is sooner. If you want a more direct error, then for 21 bytes: ``` [13579]$ 9999999999$* ``` [Try it online!](https://tio.run/##K0otycxL/P8/2tDY1NwyVoXLEg5UtP7/twQA "Retina 0.8.2 โ€šร„รฌ Try It Online") Explanation: Tries to append more than a 32-bit integer length of `9`s to the odd input, which throws an OverflowException. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` #/Mod[#+1,2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1nfNz8lWlnbUMcoVu1/QFFmXolDerShQSwXjG0c@/8/AA "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") -1 byte from @att [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ([SBCS](https://github.com/abrudz/SBCS)) Anonymous tacit prefix function ``` โ€šรคยขโˆšโˆ‘1-2|โ€šรคยข ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXosPbDXWNaoCM/2mP2iY86u171NX8qHfNo94th9YbP2qb@KhvanCQM5AM8fAM/p@mYMSVpmACxMYA "APL (Dyalog Unicode) โ€šร„รฌ Try It Online") `โ€šรคยข`โ€šร„ร‰the argument `โˆšโˆ‘`โ€šร„ร‰divided by `1-`โ€šร„ร‰one minus `2|`โ€šร„ร‰the division remainder when 2 divides `โ€šรคยข`โ€šร„ร‰the argument Or in other words:$$x\over{1-\Big({x\over2}-\big\lfloor{x\over2}\big\rfloor}\Big)$$ [Answer] # [Perl 5](https://www.perl.org/) `-p`, 9 bytes ``` $_%2&&die ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXtVITS0lM/X/f@N/@QUlmfl5xf91CwA "Perl 5 โ€šร„รฌ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Throws ~~a `TypeError`~~ an overflow error on odd numbers. ***Still** convinced* there must be a much shorter way ๏ฃฟรผยงรฎ `/v` would work if JavaScript errored on division by 0. ``` *v ยฌโ„ขโˆšรผ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KnYgqt8&input=OA) ``` *v ยฌโ„ขโˆšรผ :Implicit input of integer * :Multiply by v : Divisible by 2? ยฌโ„ข :Logical OR with โˆšรผ :A recursive call ``` [Answer] # [R](https://www.r-project.org/), ~~25~~ ~~23~~ 22 bytes *Edit: -2 bytes after looking at [ophact's answer](https://codegolf.stackexchange.com/a/229060/95126), and then -1 byte thanks to Robin Ryder* ``` `if`((n=scan())%%2,,n) ``` [Try it online!](https://tio.run/##K/r/PyEzLUFDI8@2ODkxT0NTU1XVSEcnT/O/8X8A "R โ€šร„รฌ Try It Online") Throws an 'argument is missing' error when `n` is odd and the `if` expression tries to read the missing expression that should be between the two commas. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~28~~ ~~15~~ 14 bytes -13 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) -1 thanks to [Olivier Grโˆšยฉgoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire) ``` f(a){a/=~a&1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1GzOlHfti5RzdC69n9mXolCbmJmnoYmVzWXAhAUFAGF0jSUVFOUdNI0TDQ1rbEIm4KEa///S07LSUwv/q9bDgA "C (gcc) โ€šร„รฌ Try It Online") How `~a&1` works is explained in [this solution](https://codegolf.stackexchange.com/a/229111/16236). [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 11 10 bytes ``` 1/($1%2-1) ``` [Try it online!](https://tio.run/##SyzP/v/fUF9DxVDVSNdQE8g2AQA "AWK โ€šร„รฌ Try It Online") *Thanks to tail spark rabbit ear for helping drop one char...* Divides by zero if the number is odd, otherwise the test is truthy and the default action prints the commandline.. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` โˆšร โ€“โˆยฌรธ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cMeFHYf2//9vBAA "05AB1E โ€šร„รฌ Try It Online") or ``` โˆšร โˆšรณF ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cMfh6W7//xsBAA "05AB1E โ€šร„รฌ Try It Online") `โˆšร ` checks if the input is even. Returns `1` for even numbers, `0` for odd numbers. * `โ€“โˆ` creates a list of this many copies of the input, and `ยฌรธ` calculates the gcd of the list [and throws an error for empty lists](https://github.com/Adriandmen/05AB1E/issues/178) * `โˆšรณ` repeats the input as a string this many times. This results in the input for even inputs and the empty string for odd inputs. `F` is a for loop which crashes if it gets the empty string as an argument. In the end the stack is empty and the input is implicitly printed. `F` could be any of `E`, `F`, `G` and `โˆ†รญ`. [Answer] # [Zsh](https://www.zsh.org/) (math function), 14 bytes ``` ((1/1&~$1,$1)) ``` [Try it online!](https://tio.run/##FcoxDoAgDAXQnVP8gZg2UbTewxu4ERpcIBFcNHp11Pm9s8SmR/J1y6lgWKAQiFHitRHJKN1jpbfC3DTvqKFU0CXOzdPNBgg@ZlgiKP3G@OIL "Zsh โ€šร„รฌ Try It Online") Unlike in Bash, C and many other languages, in Zsh `&` binds more tightly than `/` by default, allowing us to get division by zero on odd numbers with just `1 / 1 & ~$1`. (Zsh does have a `C_PRECEDENCES` option which changes arithmetic binding to the traditional order.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ยทโˆร‡NXo ``` [Try it online!](https://tio.run/##y0rNyan8///hjia/iPz///@bAQA "Jelly โ€šร„รฌ Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` %2NXo ``` [Try it online!](https://tio.run/##y0rNyan8/1/VyC8i/////6YA "Jelly โ€šร„รฌ Try It Online") Look ma, no unicode! ``` ยทโˆร‡NXo Main Link ยทโˆร‡ Same thing as %2. 1 if it's odd, 0 if it's even. N Negate. -1 if it's odd, 0 if it's even. X Random number. Errors with -1 as input, returns 0 with 0 as input. o Logical OR. If the input was odd, the program's already errored. Otherwise, it's 0, so logical OR gives the right value, which is the input. ``` Unfortunately, since dividing by zero isn't actually an error in Jelly, I cannot use that. Although, it wouldn't save me any bytes: `%2C:@` is the same length. [Answer] # [><>](https://esolangs.org/wiki/Fish), 7 bytes ``` :2%?Cn; ``` The input should be put onto the stack using the `-v` command-line argument. [Try it even!](https://tio.run/##S8sszvj/38pI1d45z/r///@6ZQpGAA) [Try it odd!](https://tio.run/##S8sszvj/38pI1d45z/r///@6ZQqGAA) --- ### Explanation: Initially, the stack contains the input number, \$ n \$. * `:` duplicates the top of stack: [\$n\$, \$n\$] * `2` pushes \$2\$ onto stack: [\$n\$, \$n\$, \$2\$] * `%` pops two values and pushes their modulo: [\$n\$, \$n \% 2\$] * `?` pops the top value, and if it is \$0\$, the next instruction is skipped: [\$n\$] If \$n \% 2 \neq 0\$: * `C` is not a valid instruction, so the program crashes. If \$n \% 2 = 0\$: * `n` pops off the top value (\$n\$) and prints it: [] * `;` terminates the program. [Answer] # R, ~~20~~ 19 bytes ``` (x=scan())[[!x%%2]] ``` [Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DUzM6WrFCVdUoNva/Mdd/AA "R โ€šร„รฌ Try It Online") # R 4.1, ~~15~~ 14 bytes ``` \(x)x[[!x%%2]] ``` Takes advantage of the fact that an R numeric is automatically a vector. -1 byte by using a different indexing error due to Dominic van Essen. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 44 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Duplicate_input][S S S T S N _Push_2][T S T T _Modulo][N T S N _If_0_Jump_to_Label_EVEN][N S N S N _Jump_to_nonexistent_Label][N S S N _Create_Label_Even][T N S T _Print_as_integer] ``` Letters S (space), T (tab), and N (new-line) added as highlighting only. [...\_some\_action] added as explanation only. [**Try it online**](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIAgIgxanACRRS4ALJAQmgAFDN///mAA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer input = STDIN as integer Integer temp = input modulo-2 If (temp == 0): Go to label EVEN Go to nonexistent label (causing an error) Label EVEN: Print input as integer (also shows an error: no exit defined; could be prevented by adding three trailing newlines) ``` ]
[Question] [ Write a snippet to calculate the mode (most common number) of a list of positive integers. For example, the mode of ``` d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8] ``` is `1`, because it occurs the maximum of 5 times. You may assume that the list is stored in a variable such as `d` and has a unique mode. e.g.: Python, 49 ``` max(((i,d.count(i))for i in set(d)), key=lambda x:x[1]) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins. [Answer] ## Python 2 - 18 ``` max(d,key=d.count) ``` Since your python answer doesn't seem to print, I expect this is what you want. Add 6 bytes for `print` normally. [Answer] # Matlab/Octave, ~~7~~ 5 bytes Unsurprisingly there's a built-in function for finding modes. As an anonymous function: ``` @mode ``` This returns the most commonly occuring element in the input vector with ties going to the smaller value. Saved 2 bytes thanks to Dennis! [Answer] ## [Pyth](https://github.com/isaacg1/pyth) - 6 ``` eo/QNQ ``` [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) Expects input on stdin like `[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]`. Ties are resolved by last occurrence because Python performs stable sorts. Sorts the list by count the value in the list, then prints the last number of the list. `Q` could be replaced with `d` if you initialized `d` to contain the value before e.g. `=d[4 3 1 0 6 4 4 0 1 7 7 3 4 1 1 2 8)` Python-esque pseudo-code: ``` Q=eval(input());print(sorted(Q,key=Q.count)[-1]) ``` Full Explanation: ``` : Q=eval(input()) (implicit) e : ... [-1] o Q : orderby(lambda N: ...,Q) /QN : count(Q,N) ``` Pyth's `orderby` runs exactly like Python's `sorted` with `orderby`'s first argument being the `key` argument. [Answer] # Mathematica, 25 bytes ``` Last@SortBy[d,d~Count~#&] ``` or ``` #&@@SortBy[d,-d~Count~#&] ``` As in the challenge, this expects the list to be stored in `d`. ## or... 15 bytes Of course, Mathematica wouldn't be Mathematica if it didn't have a built-in: ``` #&@@Commonest@d ``` `Commonest` returns a list of all most common elements (in case of a tie), and `#&@@` is a golfed `First@`. [Answer] # Ruby, 22 bytes ``` d.max_by{|i|d.count i} ``` Basically a port of my Mathematica answer, except Ruby has a direct `max_by` so I don't need to sort first. [Answer] # R, ~~33~~ 25 bytes Thanks @Hugh for the help shortening: ``` names(sort(-table(d))[1]) ``` --- The original: ``` v=table(d);names(v[which.max(v)]) ``` This calculates the frequency of each element in the vector `d`, then returns the name of the column containing the largest value. The value returned is actually a character string containing the number. It didn't say anywhere that that wasn't okay, so... Any suggestions to shorten this are welcome! [Answer] # CJam, ~~11~~ 10 bytes ``` A{A\-,}$0= ``` Assumes the array in a variable called `A`. This is basically sorting the array based on the occurrence of each number in the array and then picks the last element of the array. Example usage ``` [1 2 3 4 4 2 6 6 6 6]:A;A{aA\/,}$W= ``` Output ``` 6 ``` 1 byte saved thanks to Dennis! [Try it online here](http://cjam.aditsu.net/) [Answer] # K5, 6 bytes ``` *>#:'= ``` The first (`*`) of the descending elements (`>`) of the count of each (`#:'`) of the group (`=`). Step by step: ``` i 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 =i 4 3 1 0 6 7 2 8!(0 7 8 15 1 10 14 2 5 11 16 17 3 9 4 6 12 13 ,18 ,19) #:'=i 4 3 1 0 6 7 2 8!4 3 5 2 2 2 1 1 >#:'=i 1 4 3 7 6 0 8 2 *>#:'=i 1 ``` [try it in your browser](http://johnearnest.github.io/ok/index.html?run=%20*%3E%23%3A'%3D4%203%201%200%206%201%206%204%204%200%203%201%207%207%203%204%201%201%202%208)! [Answer] # Powershell 19 ``` ($d|group)[0].Count ``` (this asumes the array is already on `$d`) [Answer] # J - 12 char Anonymous function. Sorts list from most to least common, taking first item. ``` (0{~.\:#/.~) ``` * `0{` First of * `~.` Unique items * `\:` Downsorted by * `#/.~` Frequencies [Try it for yourself.](http://tryj.tk/) [Answer] # JavaScript (ES6) 51 Just a single line expression using the preloaded variable d. Sort the array by frequency then get the first element. Nasty side effect, the original array is altered ``` d.sort((a,b)=>d.map(w=>t+=(w==b)-(w==a),t=0)&&t)[0] ``` As usual, using .map instead of .reduce because it's 1 char shorter overall. With .reduce it' almost a clean, non-golfed solution. ``` d.sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))[0] ``` At last, a solution using a function, not changing the original array and without globals (62 bytes): ``` F=d=>[...d].sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))[0] ``` **Test** In FireFox/FireBug console ``` d=[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8] d.sort((a,b)=>x.map(w=>t+=(w==b)-(w==a),t=0)&&t)[0] ``` *Output* 1 The d array becomes: ``` [1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 3, 3, 0, 6, 6, 0, 7, 7, 2, 8] ``` [Answer] # [Perl 6](http://perl6.org), 21 bytes ``` .Bag.invert.max.value ``` ### Example: ``` $_ = < 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 >ยป.Int; say .Bag.invert.max.value; # implicitly calls $_.Bagโ€ฆ ``` If there is a tie it will print the larger of the ones that tied. --- The `.Bag` method on a List or an Array creates a quantified hash that associates the total count of how many times a given value was seen with that value. ``` bag(4(4), 3(3), 1(5), 0(2), 6(2), 7(2), 2, 8) ``` The `.invert` method creates a List of the pairs in the bag with the key and the value swapped. ( The reason we call this is for the next method to do what we want ) ``` 4 => 4, 3 => 3, 5 => 1, 2 => 0, 2 => 6, 2 => 7, 1 => 2, 1 => 8 ``` The `.max` method on a List of Pairs returns the biggest Pair comparing the keys first and in the case of a tie comparing the values. ( This is because that is how `multi infix:<cmp>(Pair:D \a, Pair:D \b)` determines which is larger ) ``` 5 => 1 ``` The `.value` method returns the value from the Pair. ( It would have been the key we were after if it wasn't for the `.invert` call earlier ) ``` 1 ``` --- If you want to return all of the values that tied in the case of a tie: ``` say @list.Bag.classify(*.value).max.valueยป.key ``` The `.classify` method returns a list of pairs where the keys are from calling the Whateverย lambdaย `*.value` with each of the Pairs. ``` 1 => [2 => 1, 8 => 1], 2 => [0 => 2, 6 => 2, 7 => 2], 3 => [3 => 3], 4 => [4 => 4], 5 => [1 => 5] ``` Then we call `.max` to get the largest Pair. ``` "5" => [1 => 5] ``` A call to `.value` gets us the original Pairs from the Bag ( just one in this case ) ``` 1 => 5 ``` Then we use `>>.key` to call the `.key` method on every Pair in the list, so that we end up with a list of the values that were seen the most. ``` 1 ``` [Answer] # Python - 32 ``` max((x.count(i),i)for i in x)[1] ``` Don't see an 18 character solution anywhere in the future to be honest. EDIT: I stand corrected, and impressed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` .MJ ``` Explanation: ``` .M # Gets the most frequent element in the [implicit] input J # Converts to a string, needed as the program would output "[1]" instead of "1" without this. ``` If you want to store the array in a variable instead of using input, just push the array to the stack at the start of the program. [Try it online!](https://tio.run/nexus/05ab1e#@6/n6/X/f7SJjrGOoY6BjhmQNNMxAUIDsIg5EBoDeYZAaKRjEfs1L183OTE5IxUA "05AB1E โ€“ TIO Nexus") [Answer] # JavaScript, ES6, 71 bytes A bit long, can be golfed a lot. ``` f=a=>(c=b=[],a.map(x=>b[x]?b[x]++:b[x]=1),b.map((x,i)=>c[x]=i),c.pop()) ``` This creates a function `f` which can be called like `f([1,1,1,2,1,2,3,4,1,5])` and will return `1`. Try it on your latest Firefox's Console. [Answer] # Dyalog APL, 12 characters [`d[โŠƒโ’+/โˆ˜.=โจd]`](http://tryapl.org/?a=d%u21904%203%201%200%206%201%206%204%204%200%203%201%207%207%203%204%201%201%202%208%20%u22C4%20d%5B%u2283%u2352+/%u2218.%3D%u2368d%5D&run) `โˆ˜.=โจd` is the same as `dโˆ˜.=d`, reflexive outer product of `=`. It creates a boolean matrix comparing every pair of elements in `d`. `+/` sums that matrix along one of the axes and produces a vector. `โ’` grades the vector, i.e. sorts it by indices. (As the glyphs suggest, `โ’` grades in descending order and `โ‹` would grade in ascending order.) `โŠƒ` takes the first index from the gradingโ€”the index of the largest element of `d`. `d[...]` returns that element. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ร†แนƒ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Odzf8PtyscnfRw54z//6NNdIx1DHUMdMyApJmOCRAagEXMgdAYyDMEQiMdi1gA "Jelly โ€“ Try It Online") Jelly finally got a mode builtin! A non-builtin version however is 5 bytes: ``` ฤ‹@รž`แนช ``` [Try it online!](https://tio.run/##y0rNyan8//9It8PheQkPd676f7hd4eikhztn/P8fbaJjrGOoY6BjBiTNdEyA0AAsYg6ExkCeIRAa6VjEAgA "Jelly โ€“ Try It Online") ## How they work ``` ร†แนƒ - Main link. Takes a list d on the left ร†แนƒ - Return the mode of d ``` Well that was unimpressive. How about the 5 byte, non-builtin version? ``` ฤ‹@รž`แนช - Main link. Takes d on the left ` - Use d as both the left and right argument to: รž - Sort d by: ฤ‹@ - Count occurrences in d แนช - Take the last element (i.e. the element with a maximal count in d) ``` [Answer] # C# - 49 Can't really compete using C# but oh well: Assuming `d` is the array `d.GroupBy(i=>i).OrderBy(a=>a.Count()).Last().Key;` [Answer] # bash - ~~29~~ 27 characters ``` sort|uniq -c|sort -nr|sed q ``` Using it: ``` sort|uniq -c|sort -nr|sed q 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 [ctrl-D] 5 1 ``` i.e. "1" is the mode, and it appears five times. [Answer] # GolfScript, 10 bytes ``` a{a\-,}$0= ``` From [this answer](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript/25737#25737) I wrote to [Tips for golfing in GolfScript](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript). Expects the input in an array named `a`, returns result on stack. (To read input from an array on the stack, prepend `:` for 11 bytes; to read input from stdin (in the format `[1 2 1 3 7]`), also prepend `~` for 12 bytes.) This code works by iterating over the input array, subtracting each element from the original array, and counting the number of elements left. This is then used as a key to sort the original array by, and the first element of the sorted array is returned. [Online demo.](http://golfscript.apphb.com/?c=IyBUZXN0IGlucHV0IChpbiBhcnJheSBhKToKWzQgMyAxIDAgNiAxIDYgNCA0IDAgMyAxIDcgNyAzIDQgMSAxIDIgOF06YTsKCiMgQ29kZToKYXthXC0sfSQwPQ%3D%3D) *Ps.* Thanks to Peter Taylor for [pointing out this challenge to me](http://chat.stackexchange.com/transcript/message/19178279#19178279). [Answer] # Java 8, 83 Bytes ``` d.stream().max((x,y)->Collections.frequency(d,x)-Collections.frequency(d,y)).get(); ``` `d` must be a `Collection<Integer>`. --- If `Collections` can be statically imported: **59 Bytes** ``` d.stream().max((x,y)->frequency(d,x)-frequency(d,y)).get(); ``` [Answer] # [Haskell](https://www.haskell.org/), ~~42~~ 39 bytes ``` f s=snd$maximum[([1|y<-s,y==x],x)|x<-s] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2LY4L0UlN7EiM7c0N1oj2rCm0ka3WKfS1rYiVqdCs6YCyIv9n5uYmadgq1BQlJlXoqCikKYQbaJjpGOmYwokDXWMgbQZkGUMhEax/wE "Haskell โ€“ Try It Online") *Edit: Thans to Zgarb for -3 bytes* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` แนขล’rแนชรžแนชแนช ``` [Try it online!](https://tio.run/nexus/jelly#@/9w56Kjk4oe7lx1eB6QAKL///9Hm@gY6xjqGOiYAUkzHRMgNACLmAOhMZBnCIRGOhaxAA "Jelly โ€“ TIO Nexus") Longer than K :( Assumes the first argument has the array. There are no variables in Jelly. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` x=>x.map(a=t=>a[t]=0+a[t]||[1+t]).sort()[0]-1 ``` [Try it online!](https://tio.run/##HcjBCoMwEATQ30lwDUkVWyjr0Z8IOSxWSot1xSziwX9Pt@XBDDNv2imP22uVeuHHVAYsB/aH@9BqCAV7ipLQV786zxgqSdZl3sTY6FMdyn3kJfM8uZmfZjCxhQYCeOg0O2iV/z9X1egK6gK3ZG35Ag "JavaScript (Node.js) โ€“ Try It Online") [42](https://tio.run/##FYhBCoMwEEWvk@AYkiq2IuPSS4QsBiulRR0xobjw7nHkwX@8/6M/xXH/bqlc@T3lAfOBfXGYhTZFmLAnnwLa4tZ5ymgTeU9KextyN/IaeZ7MzB81KF9DBQ5aC42ogVqQuL@nUEk64QGvoHW@AA) without 0 support [Answer] ## Java 8 : 184 bytes ``` Stream.of(A).collect(Collectors.groupingBy(i -> i, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst().get().getKey(); ``` Input **A** must be of type `Integer[]`. Note `java.util.*` and `java.util.stream.*` need to be imported, however in the spirit oneliner they are left out. [Answer] # Bash + unix tools, 62 bytes Expects the array in the STDIN. The input format does not count, as long as the numbers are non-negative integers. ``` grep -o [0-9]\*|sort|uniq -c|sort -n|awk 'END{print $2}' ``` Edited: escaped wildcard in grep argument. Now it can be run safely in non-empty directories. Thanks to manatwork. [Answer] # Perl, 27 bytes ``` $Q[$a{$_}++]=$_ for@F;pop@Q ``` Returns the last most common value in case of a tie. [Answer] # jq, 29 characters ``` group_by(.)|max_by(length)[0] ``` Sample run: ``` bash-4.3$ jq 'group_by(.)|max_by(length)[0]' <<< '[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]' 1 ``` [On-line test](https://jqplay.org/jq?q=group_by(.)|max_by(length)[0]&j=[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]) [Answer] # PHP, ~~53~~ 50 bytes ``` <?=array_flip($c=array_count_values($d))[max($c)]; ``` Run like this: ``` echo '<?php $d=$argv;?><?=array_flip($c=array_count_values($d))[max($c)]; echo"\n";' | php -- 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 ``` ## Tweaks * Saved 3 bytes by making use of the freedom to assume the input is assigned to a variable `d` [Answer] # Haskell 78 ``` import Data.List import Data.Ord g=head.maximumBy(comparing length).group.sort ``` If the imports are ignored, it's **45**. ]
[Question] [ It seems we've managed to go all this time without a plain vanilla Number-To-Binary challenge! Whilst this will inevitably be only one element in many languages, it should put a few esolangs through their paces. I truly looked for this challenge to no avail. If it already exists, comment as such and I'll delete this post-haste. # Input A single non-negative integer. # Output The same number as represented in Base 2. # Test Cases * `4 -> 100` * `10 -> 1010` * `1234 -> 10011010010` # Victory Condition [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! # Notes * The output must consist of digits `0` and `1`, either as characters or individual numbers in a list. * Zero may optionally return nothing. * [Standard IO Applies](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * Have Fun! [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 29 bytes (6โˆšรณ9=54 codels) ``` tkvuumf_iliqqdltT QqKln?_sf ? ``` [Try Piet online!](https://piet.bubbler.one/#eJxtjcEOgzAIht-F898EbHW2r1I9LK5LTFxn0u1k9u5D504KBPj5CCw0PG-JQowMD0GtLgKxkBbie0RhNNDk1KXSnsHr2K_aH0OZw8n8hxpctsvtEdntqz9hPaikmQIZYwg0jQ_thdVUpTJQuF-nkkBjnt-vlVXWdVm3u8x7_WvZq6_p8wWwszr1) ![](https://piet.bubbler.one/api.svg?6,9,0,9,1,5,5,11,13,18,19,10,6,10,4,4,12,6,0,0,19,4,19,19,19,19,19,19,19,4,9,19,19,19,19,19,19,19,6,7,18,18,19,19,19,19,19,3,13,19,18,19,19,19,19,19) B2C2 is `I` (no-op). The printing loop is now: ``` O d 1 % D I ``` which nicely forms a color loop. --- # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 33 bytes (5โˆšรณ9=45 codels) ``` tkvuumf_iliqqdltT _?tser?_iqtf? ? ``` [Try Piet online!](https://piet.bubbler.one/#eJxlTEEOwjAM-0vOrpR0G7T9SrcDGkWaNMqkwmni76Qw2IEkSuzY8krj7ZwoxMjwEHTaIpAG4iB-QBTGAbpabbGKGVzf_uP4nyo6dWnEEfbtcrtSg_iXv0sDqKSFAhljCDRPV8XCWspSGSlcTnNJoCkvj3vVbNP2Wd195u1-uWzXd_R8AR7-NQs) ![](https://piet.bubbler.one/api.svg?5,9,0,9,1,5,5,11,13,18,19,10,6,10,4,4,12,6,0,0,19,18,19,19,19,19,19,19,19,18,0,3,17,2,18,18,19,19,10,4,0,13,18,19,18,19,19) The bit-extracting logic is the same as [Parcly Taxel's](https://codegolf.stackexchange.com/a/258456/78410). The printing logic is new. Loop 1: push bits of the input (`A1 -> A8 -> B8 -> B1 -> A1`) ``` D No-op I Take input (n); no-op afterwards d 2 % [...bits n n%2] 2 1 r 2 / [...bits n%2 n/2] d ! D Turn right if the new n is 0 ``` Now there is a leading zero, which is handled nicely by `A2->B2` (`>`). Since the number below is 0 or 1, and `0>0 == 0` and `1>0 == 1`, the net effect is to simply remove the extra zero. Loop 2: print bits until the stack is empty (`D2 -> E2 -> E1 -> D2 -> D5 -> E4 -> E1`) ``` d 1 > ! If the top exists, push 1; otherwise push 0 D Turn right if it is 1; halt otherwise (white trap) O Output as number ``` [Answer] # [Python](https://www.python.org), 13 bytes ``` "{:b}".format ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZrlaqtkmqV9NLyi3ITSyBiNxULijLzSjS0NNI0KjQVgFIKFQqZeQpFiXnpqRqGBpqamhCFCxZAaAA) [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), ~~50~~ ~~44~~ 42 bytes (~~2โˆšรณ25=50~~ ~~2โˆšรณ22=44~~ 2โˆšรณ21=42 codels) ``` tabru?qd?t?itknmdjem_ a?liqdltailckt?iq ? ``` [Try Piet online!](https://piet.bubbler.one/#eJw9jNEKgzAMRf8lz7fQdLWr_RXtw3AdCM4J3Z5k_75E6UJIbk5ustP0uhdKw2DBAezh0IEjPNhpt1rYSu9xBbNiAaeMGQP30AzqC-o8LgPOf1ZZJ7ftjz_cMWdQLRslMsYQaJmfotlKyFTqROlxW2oBzev2ecvOj6tYx5VtE-7S2B_R9wfDfzDK) ### Pointer Path [![](https://i.stack.imgur.com/N9PTk.png)](https://i.stack.imgur.com/N9PTk.png) [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 73 bytes (7โˆšรณ12=84 codels) ``` um R metabrujjL ? ll?dD j d ?T l rr tN ttbj nfI nn ``` [Try Piet online!](https://piet.bubbler.one/#eJxtjsEOgjAQRP9lz9OkW0oL_RXCwWBNSFBJqifDv7sFFEXbSbqTeTvpg7rrMVJomhLM4HqT-XJct2jyK5CHBjuwFaZEJddt-VvVOricipE-s2NeCJt1Q__2uOUvM6Hhd4DOK3YpkqwA_6n4lJ8rMtOCUhwpkFKKQEN_lpm1HHExdRROhyFFUH8Z77ecmcLS9ATEoUJ-) ![](https://i.stack.imgur.com/VBTu5.png) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 132 bytes ``` {(({})<><(()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})<>({}<(()())>)({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)}<> ``` Outputs the individual numbers in a list with newlines as separators, and does not output anything for 0. Explanation: ``` { # loop while top of left stack is not 0 (({})<><(()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})<> # leave the result of modulo 2 on right stack ({}<(()())>)({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>) # integer division by 2 on left stack } # end loop <> # switch to right stack # implicit output of active (right) stack ``` [Try it online!](https://tio.run/##bYwxDoAwDAO/Yw@ssET5SNWhDEgIxMAa9e3FLWulKHLsnPe3nM9y3OVqLYCoNDeAIJ06YU5Zf8TQTmCWU6NqzJH0xDxApRMWnQjQZh0@Siy6pFRr2/oB "Brain-Flak โ€šร„รฌ Try It Online") I'm not the best at this language so I may have left a lot of room for further golfing, please let me know if you found a better way to do it. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 37 ``` b()(((a=$1/2))&&b $a echo -n $[$1%2]) ``` [Try it online!](https://tio.run/##NYtBCoAgEADv@4o9WOghSvMWvSQ6rLlgEAoZ9HyzoLnNwDjKoRQnlZSSZqF7o1TbOhQEvIWEXUSxCN2YVZU77AfjyeTx4nxtlHlCnwAr9fjb5@8MPkUuFvQA2owWHg "Bash โ€šร„รฌ Try It Online") This is a recursive function `b()` that takes its argument and divides by 2. If the result is non-zero, then `b()` is recursively called with the result. After the recursive call, the remainder when the argument is divided by 2 is the current binary digit. This is a pretty standard base conversion by repeated division by 2, with remainders becoming digits in base 2. Making it a recursive function has a couple of advantages here: * Recursive function boilerplate is marginally shorter than while loop boilerplate for the same algorithm * The repeated division yields digits (remainders) in reverse order to how they should be presented. By outputting the digit at each level after the recursive call, we effectively use the call stack to store the yielded digits and replay them back in the correct order Ungolfed and perhaps a bit more readable: ``` function b() { a=$(( $1 / 2 )) if (( $a != 0 )); then b $a fi echo -n $(( $1 % 2 )) } ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 1\log\_{256}(96)\approx \$ 0.82 bytes ``` b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYLkyA0lLtgkaEBhAUA) [Answer] # JavaScript, 16 bytes ``` x=>x.toString(2) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/wtauQq8kP7ikKDMvXcNI838BkFGikaZhoqnJBWMbGmhq/gcA) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 2 bytes ``` 2\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLszKK4eLS5zLhMjTgMjQyNuECcq1CrBI8VYzjNWpiLI1stazUNeMNrBISi9LLFAy5uNLUQ7gAO34MFQ==) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` b ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/6f9/QwMA "05AB1E โ€šร„รฌ Try It Online") [Answer] ## [bc](https://man.archlinux.org/man/extra/bc/bc.1.en) - 14 bytes ``` obase=2;read() ``` Run bc by typing `bc` into a terminal and pressing `Enter`. Type this code in, press `Enter`, type in the number to convert, and finally press `Enter` one more time. Press `Ctrl` + `C` to exit `bc`. `read()` reads user input (in base 10 by default), and then `obase=2` sets it to output in binary. Given that we don't tell it to do any math operations (other than base-conversion), it just outputs the input, but in binary due to the `obase=2`. Example: ``` $ bc bc 1.07.1 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. obase=2;read() <-- Press Enter 1234 <-- Press Enter again 10011010010 <-- Press Ctrl + C to exit ^C (interrupt) Exiting bc. ``` I've tested this on Arch Linux, but any system with `bc` installed should work. [Answer] # [C (GCC)](https://gcc.gnu.org), 21 bytes ``` f(n){printf("%b",n);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FlvTNPI0qwuKMvNK0jSUVJOUdPI0rWshcjddgaIKuYmZeRqaXNVcnGkaJprWCgWlJcUaSkqa1iABQwMMESNjVFVQw2AWAgA) Will be pretty shocked if there is any way to do it shorter in C (unless I missed a weird print function). [Answer] # [Befunge-93 (PyFunge)](https://pythonhosted.org/PyFunge/), 28 bytes ``` 2&v 2/>:0`!#^_:2%\ ._@#-2:< ``` [Try it online!](https://tio.run/##S0pNK81LT9W1NNYtqAQz//83UivjMtK3szJIUFSOi7cyUo3hUtCLd1DWNbKy@f/f0MjYhAsA "Befunge-93 (PyFunge) โ€šร„รฌ Try It Online") ## Explanation: `2&v` and `>` below: Push 2 (used as an "end of string" character of sorts), push user input (henceforth X), then go down and enter the main loop. ### Main Loop `:0\`!`: Check if X is greater than 0. Invert the answer. (Specifically: duplicate X, push 0, swap, greater than, invert) `#^_`: If top of stack is 1 (i.e. X <= 0), go up to print loop, else continue right. (Bridge, (up), horizontal if) `:2%`: Get X%2. (Duplicate X, push 2, modulo) `\`: Store below X on stack. (Swap) `2/`: Divide X by 2. Loop restarts with this as X. (push 2, integer divide) ### Print Loop `<`: Go left. (going right here would add a `!` but it would not increase bytes as we have a spare whitespace on the left) `-2:`: Check if top of stack = 2 (end of string). (RTL; duplicate, push 2, subtract) `_@#`: Terminate program if top of stack = 0 (i.e. next item is 2). (RTL; bridge, (terminate), horizontal if) `.`: Print top of stack as integer. Note: I originally had a `$` to pop the leading 0 above the `^` in the main loop, but as per comments, leading 0s are allowed. Changing the `^` to a `v` would be equivalent, unless I were to add back in the `$` at the cost of 6 vs 10 bytes. [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` f 0=0 f n=n`mod`2+10*f(n`div`2) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNaAK00hzzYvITc/JcFI29BAK00jLyElsyzBSPN/bmJmnoKtQko@V0FRZl6JgopCmoIJEtvQAJljZGzyHwA "Haskell โ€šร„รฌ Try It Online") I'm unsure why `f$n`div`2` doesn't work as opposed to `f(n`div`2)`... I hope someone can explain this to me and help golf this code. [Answer] # [Quipu](https://github.com/cgccuser/quipu), 78 bytes ``` 2&1@0&2&0&3& //**[][][][] 1&2&2&++1&/\ >>>>%% -- \/1&1& 0& [] >> ** ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m720sDSzoHTBgqWlJWm6Fjf9jNQMHQzUjNQM1IzVuPT1tbSiYyGQyxAoaqSmrW2oph_DZQcEqqoKCrq6XDH6hmqGagoKBmpcCkAQHaugYGcHZmppQUyFGr5giaGRsQmEDQA) ### Explanation Programs in Quipu consist of several "threads," vertical strips of code that are executed one at a time and also store values. Quipu is missing a lot of features that would have been useful for this challenge: lists, string concatenation, exponentiation... Lacking better methods, we generate the output as a base-10 number whose digits are either 0 or 1. The first time thread 0 is executed, it loads the input number; subsequently, it divides its value by 2: ``` # Previous value of this thread (implicit; initially 0) 2& # Push 2 // # Divide 1& # Push 1 >> # Go to that thread if the above result is greater than 0 \/ # Otherwise, read input number ``` Thread 1 generates successive powers of 10, starting at 1: ``` # Previous value of this thread 1@ # Push 10 ** # Multiply 2& # Push 2 >> # Go to that thread if the above result is greater than 0 1& # Otherwise, push 1 ``` Thread 2 takes the current value mod 2 and multiplies by the appropriate power of 10: ``` 0& # Push 0 [] # Load that thread's value 2& # Push 2 %% # Mod 1& # Push 1 [] # Load that thread's value ** # Multiply ``` Thread 3 keeps a running sum of the values generated by thread 2. This will be our output number. ``` # Previous value of this thread 2& # Push 2 [] # Load that thread's value ++ # Add ``` Thread 4 tests if the value in thread 0 is still greater than 1; if so, jump back to thread 0: ``` 0& # Push 0 [] # Load that thread's value 1& # Push 1 -- # Subtract 0& # Push 0 >> # Go to that thread if the above result is greater than 0 ``` Once thread 0's value has reached 1 (or 0), execution continues with thread 5, which simply outputs the final result: ``` 3& # Push 3 [] # Load that thread's value /\ # Print ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 26 bytes ``` :-read(X),format("~2r",X). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30q3KDUxRSNCUyctvyg3sURDqc6oSEknQlPv/39DI2MTPQA "Prolog (SWI) โ€šร„รฌ Try It Online") With builtin. # [Prolog (SWI)](http://www.swi-prolog.org), ~~42~~ ~~36~~ 35 bytes *-6 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)* *-1 byte thanks to [@false](https://codegolf.stackexchange.com/users/65772/false)* ``` N+X:-N<1,X=0;N//2+B,X is N/\1+10*B. ``` [Try it online!](https://tio.run/##Dcg9DoMgAAbQqxAnKR8Cav9sS4IHYCaxDC5tTLQQMenm1Wnf@OIa5vDm6TvlbJnruL0ruIe8WSFq1sORKRErnoopeeir3PFljPOUtnIwXuvSMIdXWJdxK4s9Eq7JHvdPgcHAeUoxSCjUaNDiiBPOuOAK9c@6aT2t8g8 "Prolog (SWI) โ€šร„รฌ Try It Online") Without builtin. --- Man, I haven't golfed in Prolog in a while; I forgot how wonky it is to code in it lol. Please tell me if there are any more golfs! [Answer] # [Minecraft Data Pack](https://minecraft.fandom.com/wiki/Data_pack) via [Lectern](https://github.com/mcbeet/lectern), 355 bytes ``` @function a:b data modify storage b set value [] scoreboard players set i 2 function a:c @function a:c scoreboard players operation a i = i i data modify storage b prepend value 0 execute store result storage b[0] int 1 run scoreboard players operation a i %= i scoreboard players operation i i /= i execute if score i i matches 1.. run function a:c ``` The function is `a:b`. Takes input in the fake player `i` and the objective `i` (Which can be set using `/scoreboard objectives add i dummy`, `/scoreboard players set i i <input number>`). Outputs a list via data storage `: b` (Which can be read by `/data get storage : b`). I'm not sure this I/O format is valid, but this would be the standard way to do that if you were writing a library, although with the objective created by the data pack (and, of course, with more meaningful names). [Answer] # [Python](https://www.python.org), 17 bytes ``` lambda n:f"{n:b}" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhYbcxJzk1ISFfKs0pSq86ySapUg4msKijLzSjTSNEyMNDUhQgsWQGgA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` b ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJiIiwiIiwiMTAiXQ==) [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 54 bytes ``` i,o=input(),"" while i:i,j=divmod(i,2);o=`j`+o print o ``` [Try it online!](https://tio.run/##FcxLCoAgEADQ/ZxC2qjloqxV4V0EFZooR8J@p7c6wHvpyTNFXRz5YDjnBRUZjOnIQqqqgmvGNTAcUS3G47mRF6i0nMjYxTYEaceYGZWPQriDE38k674M0LXQ6X54AQ "Python 2 โ€šร„รฌ Try It Online") Just as a way of doing it without any builtins. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 70 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input_n][N S S N _Create_Label_BINARY_LOOP][S N S _Duplicate_n][N T S S N _If_0_Jump_to_Label_PRINT_LOOP][S N S _Duplicate_n][S S S T S N _Push_2][T S T T _Modulo][S N T _Swap_top_two][S S S T S N _Push_2][T S T S _Integer_divide][N S N N _Jump_to_Label_BINARY_LOOP][N S S S N _Create_Label_PRINT_LOOP][T N S T _Print_as_integer][N S N S N _Jump_to_Label_PRINT_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [**Try it online**](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QYALwuPihNBAwAnicIJJGAckxQWS5OIEaQRx//83NDI2AQA) (with raw spaces, tabs and new-lines only). Outputs with one additional leading `0`. This can be removed at the cost of 8 additional bytes: [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QYALwuPihNBAwAnicIJJGAckxcUF0QiigXpBBgDluP7/NzQyNgEA). **Explanation in pseudo-code:** ``` Integer n = STDIN as integer Start BINARY_LOOP: If n==0: Jump to PRINT_LOOP Push n modulo-2 to the stack n = n integer-divided by 2 Go to the next iteration of BINARY_LOOP PRINT_LOOP: Print current top of the stack as integer to STDOUT Go to the next iteration of PRINT_LOOP ``` Stops the program with an error when it tries to print while the stack is empty. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 1 byte ``` B ``` Try it at [MATL Online](https://matl.io/?code=B&inputs=4&version=22.7.4) [Answer] # [Julia 0.7](http://julialang.org/), 3 bytes ``` bin ``` [Try it online!](https://tio.run/##yyrNyUw0/59m@z8pM@@/g55CQVFmXklOnkaaRrSJjqGBjqGRsUmspuZ/AA "Julia 0.7 โ€šร„รฌ Try It Online") # [Julia 1.x](https://julialang.org), 9 bytes ``` bitstring ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBojTbpaUlaboWK5MyS4pLijLz0iH8XQ56CgVAbklOnkaaRrSJjqGBjqGRsUmspiZEwYIFEBoA) Prints with leading zeroes. [Answer] # [J](https://www.jsoftware.com), 2 bytes ``` #: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxSNkKwtiiyZWanJHvkKZmp2CiYGigYGhkbAKRWrAAQgMA) `#:` returns the binary expansion of a given number y as a boolean list. [Answer] # [Desmos](https://desmos.com/calculator), 50 bytes ``` f(n)=mod(floor(n/2^{[floor(log_2(n+0^n))...0]}),2) ``` [Try It On Desmos!](https://www.desmos.com/calculator/58jgg1jumw) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ilmjn4qc3o) [Answer] # [Haskell](https://www.haskell.org), 62 bytes ``` import Data.Sequence d 0=Nothing d n=Just$divMod n 2 unfoldl d ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNx0ycwvyi0oUXBJLEvWCUwtLU_OSU7lSFAxs_fJLMjLz0oHsPFuv0uISlZTMMt98IE_BiCvJtjQvLT8nJUchBWLO1tzEzDwFW4WCosy8EgUVhSQFQyNjE4gczC4A) A different approach than [Aiden Chow's answer](https://codegolf.stackexchange.com/a/258528/16766); this one uses `unfoldl` from `Data.Sequence`, which is elegant but unfortunately much less golfy. ### Explanation `unfold` is conceptually the opposite of `fold`. `fold` takes a function that combines two values into one and a sequence of values, and returns a single value; `unfold` takes a function that splits one value into two and a single value, and returns a sequence of values. Specifically, the type of `unfoldl` looks like this: ``` unfoldl :: (b -> Maybe (b, a)) -> b -> Seq a ``` It takes a function and a single value of type `b` and returns a sequence of values of type `a`. The function must take a value of type `b` and return either a tuple containing one `b` and one `a` or `Nothing`. `unfoldl` applies the function repeatedly to the initial value, taking the first element of the tuple as the new value and saving off the second tuple elements as the sequence. It stops when it gets `Nothing` instead of a tuple. In our case, both types are `Int`. We want the first element of the tuple to be the input int-divided by 2, and the second element to be the input mod 2. Conveniently, Haskell has a `divMod` function that returns exactly the tuple we want. Thus, our binary converter is just ``` unfoldl d ``` where `d` is a function that stops when it hits `0`: ``` d 0 = Nothing ``` and otherwise returns the result of `divMod` wrapped in a `Maybe`: ``` d n = Just (divMod n 2) ``` [Answer] # [Swift](https://developer.apple.com/swift/), ~~55~~ ~~49~~ 20 bytes ##### -6 bytes thanks to @RydwolfPrograms ##### -29 bytes thanks to @Jacob ``` {String($0,radix:2)} ``` [Try it online!](https://tio.run/##Ky7PTCsx@V9QlJlXoqHxvzq4BMhK11Ax0ClKTMmssDLSrP2vqWFkrqn5HwA "Swift โ€šร„รฌ Try It Online") [Answer] # [R](https://www.r-project.org), 9 bytes ``` intToBits ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhYrM_NKQvKdMkuKIfw9aRoGmlxpGoYgwgTMgvCNjE00IUoWLIDQAA) Outputs as little-endian with trailing zeros. --- # [R](https://www.r-project.org), 18 bytes ``` \(n)n%/%2^(n:0)%%2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhabYjTyNPNU9VWN4jTyrAw0VVWNIBJ70jQMNLnSNAxBhAmYBeEbGZtoQpQsWAChAQ) Outputs as big-endian (standard convention) with possibly a lot of leading zeros. [Answer] # Scratch, ~~70~~ 68 bytes Puts a list of binary digits onto the [`a` global variable, which is automatically displayed when the program finishes execution.](https://codegolf.meta.stackexchange.com/a/25520/108687) Saved 2 bytes by using `([floor v]of((n)/(2` instead of `((n)-(((n)mod(2))/(2` ![](https://i.stack.imgur.com/bk6B4.png) Scratchblocks syntax: ``` define a(n if<(n)>(0)>then a([floor v]of((n)/(2 add((n)mod(2))to[a v ``` [Try it on Scratch](https://scratch.mit.edu/projects/810738346) [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 40 bytes ``` {(<>)<>({<({}[()])><>[(()[{}])]()<>})}<> ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v@/WsPGTtPGTqPaRqO6NlpDM1bTzsYuWkNDM7q6NlYzVgMoV6tZa2P3//9/Q3MA "Brain-Flak (BrainHack) โ€šร„รฌ Try It Online") The other Brain-flak answer looked very long. # Explanation The first thing we can notice is that the following snippet: ``` (()[{}]) ``` does something very nice. It's equivalent to `1-x`, which when constrained to the inputs of `0` and `1` will give us an increment and mod 2 operation. So we can calculate the mod 2 of a number by just repeating this snippet that many times starting with `0`. ``` {({}[()])<>(()[{}])<>} ``` This is nice and it can be modified to give us the full `divmod`. Each cycle we add the value of the accumulator we are building. Since it is `1` half the time and `0` the other half this gives us half the value. The one issue is it rounds up instead of down, so instead of adding `n` each step we add `1-n`. That is we add 1 when the accumulator is 0 and 0 when the accumulator is 1. ``` ({<({}[()])><>[(()[{}])]()<>}) ``` Now we add a bit of code to add a new accumulator each step and we can just repeat this divmod process until the div is zero. ``` {(<>)<>({<({}[()])><>[(()[{}])]()<>})}<> ``` ]
[Question] [ Write the shortest program that takes one input (n) from STDIN (or equivalent) and outputs a simple incrementing function with one argument (x) that returns x + n but the function must be in a different language. Pretty simple! **This is code-golf, normal rules apply, shortest program wins.** Example: ><> to Python (Ungolfed) ``` !v"def i(x):"a" return x+"ir! >l?!;o ``` Input: ``` 3 ``` Output: ``` def i(x): return x+3 ``` EDIT: Anonymous functions and lambda expressions are allowed! [Answer] # [GS2](https://github.com/nooodl/gs2) โ†’ K, 2 bytes ``` โ€ข+ ``` This prints a tacit, monadic function. The source code uses the [CP437](https://en.wikipedia.org/w/index.php?title=Code_page_437&oldid=565442465#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=4oCiKw&input=NDI) ## Test run ``` $ xxd -c 2 -g 1 sum-func.gs2 00000000: 07 2b .+ $ printf 42 | gs2 sum-func.gs2 42+ $ kona K Console - Enter \ for help (42+) 69 111 f : 42+ 42+ f 69 111 ``` ## How it works ### GS2 * GS2 automatically reads from STDIN and pushes the input on the stack. * `โ€ข` indicates that the next byte is a singleton string literal. * Before exiting, GS2 prints all stack items. ### K Left argument currying is automatic in K. Here, `n+` turns the dyadic function `+` into a monadic function by setting its left argument to `n`. [Answer] # [ShapeScript](https://github.com/DennisMitchell/ShapeScript) โ†’ J, 4 bytes ``` "&+" ``` This prints a tacit, monadic verb. Try it online: [ShapeScript](http://shapescript.tryitonline.net/#code=IiYrIg==&input=NDI=), [J](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=42%26%2B%2069) ## Test run ``` $ cat sum-func.shape; echo "&+" $ printf 42 | shapescript sum-func.shape; echo 42&+ $ j64-804/jconsole.sh 42&+ 69 111 f =: 42&+ f 69 111 ``` ## How it works ### ShapeScript * ShapeScript automatically reads from STDIN and pushes the input on the stack. * `"&+"` pushes that string on the stack. * Before exiting, ShapeScript prints all stack items. ### J `&` performs argument currying. Here, `n&+` turns the dyadic verb `+` into a monadic verb by setting its left argument to `n`. [Answer] # GolfScript โ†’ CJam, 4 bytes ``` {+}+ ``` This prints a code block (anonymous function). Try it online: [GolfScript](http://golfscript.apphb.com/?c=IjQyIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp7K30r), [CJam](http://cjam.aditsu.net/#code=69%20%7B42%20%2B%7D%20~&input=42) ## Test run ``` $ cat sum-func.gs; echo {+}+ $ printf 42 | golfscript sum-func.gs {42 +} $ cjam > 69 {42 +} ~ 111 > {42 +}:F; 69F 111 ``` ## How it works ### GolfScript * GolfScript automatically reads from STDIN and pushes the input on the stack. * `{+}` pushes that block on the stack. * `+` performs concatenation, which happily concatenates a string and a block. * Before exiting, GolfScript prints all stack items. ### CJam `{n +}` is a code block that, when executed, first pushes `n` on the stack, then executes `+`, which pops two integers from the stack and pushes their sum. [Answer] # BrainF\*\*\* to JavaScript ES6, 57 bytes ``` ----[-->+++<]>--.[-->+<]>+.+.--[->++<]>.[--->+<]>+++.[,.] ``` (Assumes that the input is composed of numeric characters) Say `1337` is your input. Then, this would compile to: ``` x=>x+1337 ``` [Answer] # R to Julia, 19 bytes ``` cat("x->x+",scan()) ``` This reads an integer from STDIN using `scan()` and writes an unnamed Julia function to STDOUT using `cat()`. The Julia function is simply `x->x+n`, where `n` comes from the R program. [Answer] # Rotor to K, 2 bytes ``` '+ ``` Might as well jump in on the K bandwagon. [Answer] # [Malbolge](http://zb3.github.io/malbolge-tools/#interpreter) to JavaScript ES6, 71 bytes ``` ('&%@9]!~}43Wyxwvutsr)Mon+HGi4~fBBdR->=_]:[875t4rT}0/Pf,d*((II%GEE!Y}Az ``` It's always fun to generate Malbolge code. [Answer] # Minecraft 1.8.7 to K, ~~7~~ 6 + 33 + 27 + 62 = ~~129~~ 128 Bytes This is using [this version of byte counting](http://meta.codegolf.stackexchange.com/a/7397/44713). [![the system](https://i.stack.imgur.com/Y7fFE.png)](https://i.stack.imgur.com/Y7fFE.png) Command blocks (going from left to right): ``` scoreboard objectives add K dummy ``` ``` scoreboard players set J K <input> ``` ``` tellraw @a {score:{name:"J",objective:"K"},extra:[{text:"+"}]} ``` This could probably be golfed a little more, but it's fairly simple: generate a variable `J` with the objective `K` and set its score for that objective to the input (there is no STDIN - I figured this was close enough). Then, after a tick, output the score of the variable `J` for the objective `K` followed by a `+`. Easy peasy. [Answer] # [O](https://github.com/phase/o) to K, 5 bytes ``` i'++o ``` Thanks to **[@kirbyfan64sos](https://codegolf.stackexchange.com/users/21009/kirbyfan64sos)** Another version using features added after the challenge was created. ``` i'+ ``` * Gets input, pushes to stack * Pushes '+' as a string * Outputs stack contents [Answer] ## [Seriously](https://github.com/Mego/Seriously) to Python, 15 bytes `,"lambda n:n+"+` Expects input to be in string form, i.e. `"3"` Explanation: ``` ,: read value from input "lambda n:n+": push this literal string +: concatenate top two values on stack ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c226c616d626461206e3a6e2b222b&input=%223%22) (you will have to manually enter the input because the permalinks don't like quotes) [Answer] # Pyth to APL, ~~7~~ 5 bytes ``` +z"-- ``` The Pyth code simply concatenates the input (`z`) with the string `"--"`. This creates an unnamed monadic train in APL with the form `n--`, where `n` comes from Pyth. When calling it in APL, `(n--)x` for some argument `x` computes `n--x = n-(-x) = n+x`. Try: [Pyth](https://pyth.herokuapp.com/?code=%2Bz%22--&input=3&debug=0), [APL](http://tryapl.org/?a=f%u21903--%u22C4f%202&run) Saved 2 bytes thanks to Dennis! [Answer] # rs -> K, 2 bytes ``` /+ ``` [Live demo.](http://kirbyfan64.github.io/rs/index.html?script=%2F%2B&input=2) [Answer] ## [><>](https://esolangs.org/wiki/Fish) to Python, 25 + 3 = 28 bytes ``` "v+x:x adbmal o/?(3l ;>~n ``` Takes input via the `-v` flag, e.g. ``` py -3 fish.py add.fish -v 27 ``` and outputs a Python lambda, e.g. `lambda x:x+27`. For a bonus, here's an STDIN input version for 30 bytes: ``` i:0(?v x+"r~/"lambda x: o;!?l< ``` [Answer] # [Mouse](http://en.wikipedia.org/wiki/Mouse_(programming_language)) to Ruby, 19 bytes ``` ?N:"->x{x+"N.!"}"$ ``` Ungolfed: ``` ? N: ~ Read an integer from STDIN, store in N "->x{x+" ~ Write that string to STOUT N. ! ~ Write N "}"$ ~ Close bracket, end of program ``` This creates an unnamed Ruby function of the form `->x{x+n}` where `n` comes from Mouse. [Answer] # Haskell to Mathematica, 14 bytes ``` (++"+#&").show ``` [Answer] # Mathematica to C#, 22 bytes ``` "x=>x+"<>InputString[] ``` Outputs a C# `Func<int, int>` of form ``` x=>x+n ``` [Answer] # Pyth -> K, 4 bytes ``` +z\+ ``` K is really easy to abuse here... [Live demo.](https://pyth.herokuapp.com/?code=%2Bz%5C%2B&input=2&debug=0) [Answer] # Brainfuck to Java, 273 ``` +[----->+++++.+++++.++++++.[---->++++.+[->++++.-[->+++-.-----[->+++.+++++.++++++.[---->++++.-[--->++-.[----->++-.[->+++.---------.-------------.[--->+---.+.---.----.-[->+++++-.-[--->++-.[----->+++.,[.,]+[--------->+++.-[--->+++. ``` Outputs a method like `int d(int i){return i+42;}` (which doesn't *look* like a Java method, but... Java!) [Answer] # POSIX shell to Haskell, 19 bytes ``` read n;echo "($n+)" ``` Anonymous functions being allowed, Haskell is a good output choice with the operator sections. [Answer] # PHP โ†’ JavaScript (ES6), 20 ~~24~~ bytes Reading from *STDIN* is always expensive in PHP. It looks a bit strange: ``` x=>x+<?fgets(STDIN); ``` It prints `x=>x+` and waits for user input to complete the string, terminates with the complete anonymous JavaScript function, e.g. `x=>x+2`. **First version (24 bytes**) ``` <?='x=>x+'.fgets(STDIN); ``` [Answer] # [Retina](https://github.com/mbuettner/retina) to [Pip](https://github.com/dloscutoff/pip), 4 bytes Uses one file for each of these lines + 1 penalty byte; or, put both lines in a single file and use the `-s` flag. ``` $ +_ ``` Matches the end of the input with `$` and puts `+_` there. This results in something of the form `3+_`, which is an anonymous function in Pip. [Answer] # Bash โ†’ C/C++/C#/Java, 33 bytes and maybe others ``` echo "int f(int a){return a+$1;}" ``` [Answer] ## [Tiny Lisp](https://codegolf.stackexchange.com/q/62886/2338) to [Ceylon](http://ceylon-lang.org/), ~~68~~ 61 ``` (d u(q((n)(c(q(Integer x))(c(q =>)(c(c(q x+)(c n()))())))))) ``` Tiny Lisp doesn't have real input and output โ€“ it just has expression evaluation. This code above creates a function and binds it to `u`. You can then call `u` with the argument `n` like this: `(u 7)`, which will evaluate to this Tiny Lisp value: ``` ((Integer x) => (x+ 7)) ``` This is a valid Ceylon expression, for an anonymous function which adds 7 to an arbitrary integer. *Thanks to DLosc for an improvement of 7 bytes.* [Answer] # JavaScript to [Lambda Calculus](http://www.ics.uci.edu/~lopes/teaching/inf212W12/readings/lambda-calculus-handout2.pdf), 39 bytes (This uses the linked document as a basis.) ``` alert((x=>`ฮปa(${x}(add a))`)(prompt())) ``` Say input is `5`. Then this becomes: ``` "ฮปa(5(add a))" ``` [Answer] # Python 2 to CJam, ~~18~~ 20 bytes *Thanks to LegionMammal978 for correcting the functionality.* ``` print"{%f+}"%input() ``` The Python does a basic string format. `%f` is the code for a float, and since I wouldn't lose any bytes for handling floats, I went ahead and did so. The CJam is much the same as the Golfscript->CJam answer. It looks something like this: ``` {7.4+} ``` or: ``` {23+} ``` It's a block that takes the top value off the stack, pushes the special number, then adds them. [Answer] # [Microscript II](http://esolangs.org/wiki/Microscript_II) to Javascript ES6, 9 bytes ``` "x=>x+"pF ``` [Answer] # GNU sed to C, 46 bytes ``` sed -r 's/^([0-9]+)$/f(int x){return x+\1;}/' ``` [Answer] # Vitsy to K, 5 Bytes \o/ K will be being used very soon if it can do this. ``` N'+'Z ``` or maybe... ``` N'+'O ``` If the input is taken as a string (only for 0-9 input)... ``` i'+'Z ``` All of these, for input 2, will output: ``` 2+ ``` [Answer] ## [Ceylon](http://ceylon-lang.org/) to [Tiny lisp](https://codegolf.stackexchange.com/q/62886/2338), 76 ``` shared void run(){print("(q((x)(s ``process.readLine()else""``(s 0 x))))");} ``` This produces (after reading a line of input) output like `(q((x)(s 5(s 0 x))))`, which evaluates in Tiny Lisp to `((x) (s 5 (s 0 x)))`, a function which takes an argument `x`, subtracts it from 0, and subtracts the result from 5. (Yeah, this is how one adds in Tiny Lisp, there is only a subtraction function build in. Of course, one could define an addition function first, but this would be longer.) You can use it like this as an anonymous function: ``` ((q((x)(s 5(s 0 x)))) 7) ``` (This will evaluate to 12.) Or you can give it a name: ``` (d p5 (q((x)(s 5(s 0 x))))) (p5 7) ``` *Corrections and Golfing Hints from DLosc, the author of Tiny Lisp.* [Answer] # [Japt](https://github.com/ETHproductions/Japt) โ†’ [TeaScript](https://github.com/vihanb/TeaScript), 5 bytes ``` U+"+x ``` This is pretty simple. --- ### Explanation ``` U+ // Input added to the string... "+x // This is the string ``` ]
[Question] [ # Challenge You will be given a string that can contain lowercase letters, uppercase letters, or spaces. You have to turn the vowels (a, e, i, o, u) in the string to upper case and consonants to lower case. This applies whether or not the letter was originally upper case or lower case. Spaces remain as is. Note that "y" is a consonant. # Examples ``` Hello World -> hEllO wOrld abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVXWYZ -> AbcdEfghIjklmnOpqrstUvwxyz AbcdEfghIjklmnOpqrstUvxwyz ``` # Info * The input string can contain letters A to Z, lowercase or uppercase, and spaces. # Input The string # Output The formatted string (Vowels uppercase and consonants lowercase). [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~55 ... 46~~ 45 bytes *Saved 1 byte thanks to @KevinCruijssen* ``` s=>Buffer(s).map(c=>c^(c^~68174912>>c)&32)+'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1s6pNC0ttUijWFMvN7FAI9nWLjlOIzmuzszC0NzE0tDIzi5ZU83YSFNbXf1/cn5ecX5Oql5OfrpGmoaSR2pOTr5CeH5RToqSpiYXmmxiamZ@aVJySlp6RlZ2Tm5eQWFRcUlZeUVllYKjq6d/qJOzi5u7h5e3j69fQGBQcEhYeERkFNCc/wA "JavaScript (Node.js) โ€“ Try It Online") ### How? The constant \$68174912\$ is a bitmask describing the positions of the vowels: ``` 00000100000100000100010001000000 v v v v v zyxwvutsrqponmlkjihgfedcba`_^]\[ ``` As per [the ECMAScript specification](https://www.ecma-international.org/ecma-262/10.0/index.html#sec-signed-right-shift-operator-runtime-semantics-evaluation), the following expression: ``` ~68174912 >> c & 32 ``` is equivalent to: ``` ~68174912 >> (c % 32) & 32 ``` and therefore evaluates to \$32\$ for a consonant or \$0\$ for a vowel, no matter the case of \$c\$. ### Commented ``` s => // s = input string Buffer(s) // turn s into a buffer .map(c => // for each ASCII code c: c ^ // change the case if: ( c // c is not in lower case ^ // XOR ~68174912 >> c // c is a consonant ) & 32 // ) + '' // end of map(); coerce back to a string ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes Port of [my JS answer](https://codegolf.stackexchange.com/a/201521/58563). ``` f(char*s){for(;*s;s++)*s^=(*s^~68174912>>*s)&32;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLM6Lb9Iw1qr2LpYW1tTqzjOVgNI1JlZGJqbWBoa2dkBlagZG1nX/s/MK1HITczM0yjLz0zRVKjmUlAAGaFQHB2rYKug5JGak5OvEO5flJOikJiamV@alJySlp6RlZ2Tm1dQWFRcUlZeUVml4Ojq6R/q5Ozi5u7h5e3j6xcQGBQcEhYeERmlZA00MU2jWBNEF5SWFIOZtf8B "C (gcc) โ€“ Try It Online") --- # [C (clang)](http://clang.llvm.org/), 48 bytes *A version suggested by @Neil* This is abusing the way clang is dealing with the pointer post-increment. ``` f(char*s){for(;*s;)*s++^=(*s^~68174912>>*s)&32;} ``` [Try it online!](https://tio.run/##HYzHCsJAFADvfsXDg2wiHixYCAbsvXdFYd24MbommheNBf1013KaOQzDIkxQ25SSE7alrorKgzsu0VTUFBXD4VWWqLh6JdPRVCITjen6twjFY9pTWrYHB2rZ5OJYhgKPAMDvALhYQhaC1Y0QDkw6rjCAbiznvGYGN7e7vTjYx5OL3sW/3u6QK9U6o3yhWK5U641mq93t9QfD8WQ6mwe175ETVH48nj3861O@GRfURBnxPw "C (clang) โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~20~~ 19 bytes *-1 due to @NahuelFouilleul* ``` $_=lc;y;aeiou;AEIOU ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYn2brSOjE1M7/U2tHV0z/0/3@P1JycfIXw/KKclH/5BSWZ@XnF/3ULAA "Perl 5 โ€“ Try It Online") Convert everything to lower case, then change vowels to upper case. [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda s:[[c,c.upper()][c in"aeiou"]for c in s.lower()] ``` [Try it online!](https://tio.run/##HYoxDoMwEAR7XnGiwZYSN@mQSJ0fpCAUBGzlIuOz7owihHi7A3Q7MxuX9KFwy655Zd9P77EHqdt2uAxmjtGy0l07AIayt0hz2TliOBjEePqdPeMUiRPIIsWRPQZ7PhYxkkYMdQEg0JxhN4xR6V3xrpySY0bGkJQrV9ngeoe1qsyXMCjWW6nzw3pP8CT24x8 "Python 3 โ€“ Try It Online") **Input**: A string/sequence of characters **Output**: a list of characters. ### Explanation The solution converts the string to lower case, then convert all vowels to uppercase. * `for c in s.lower()` converts the string to lower case, then loop through each character in the string. * `[c,c.upper()][c in "aeiou"]` converts any vowel to uppercase, and consonant to lower case. `c in "aeiou"` evaluates to `0` or `1`, which is used to index into the list `[c,c.upper()]`. [Answer] # [Python](https://docs.python.org/2/), 53 bytes ``` lambda s:[(c*2).title().strip('aeiou')[-1]for c in s] ``` [Try it online!](https://tio.run/##DcTHDoIwAADQu1/R9EJrhESOJpi4994iB1alCG1ti4o/j77DE6VOOLMr4tyqzM@DyAeq5aKwbmNLU53FCFtKSyqQ4ceUFwZ2zaZHuAQhoAwor1IOZaLQCNeEpEwD1QDQbMP/0Eo5ZYgghXEF/SCMYnJPaPrIcsbFUypdvN6f8gs63V5/MByNJ9PZfLFcrTfb3f5wPJ8uV/gD "Python 2 โ€“ Try It Online") Outputs a list of characters. Here is an explanation of how it transforms each character `c`, with examples `c='A'` and `c='B'`: ``` 'A' 'B' (c*2) 'AA' 'BB' # Two copies of c in a two-character string .title() 'Aa' 'Bb' # Title case: uppercase first letter and the rest lowercase # This disregards the case of c .strip("aeiou") 'A' 'Bb' # Remove any leading or trailing lowercase vowels 'aeiou' # For a two-character string, this removes all such letters [-1] 'A' 'b' # Take the last letter ``` **55 bytes** ``` lambda s:[(c*2).title()[~(c in'aieouAEIOU')]for c in s] ``` [Try it online!](https://tio.run/##Fci5DoIwAADQ3a9outAaZWA0wcQDFS@88EIGTilCW2lRcfDXUZc3PF7JhFGtjvVLnXm5H3pAdBwUNDWsSiKzCGHngwJAqOKRiJU9w7RsBbsxK8B/gXBroRPKS4lwgxeESiBaALa78CdUU0YoipHAuIaeH4RRfE1Iestyyvi9ELJ8PF/VG/T6g6ExGk/M6Wy@WFqr9Wa7s/fHw@kMvw "Python 2 โ€“ Try It Online") If we were instead lowercasing vowels and uppercasing consonants, we wouldn't need the `~()` and would have 52 bytes. [Answer] # [CJam](https://sourceforge.net/p/cjam), 15 bytes ``` lel"aeiou"_euer ``` [Try it online!](https://tio.run/##S85KzP3/Pyc1RykxNTO/VCk@tTS16P9/j9ScnHwdhfL8opwURQA "CJam โ€“ Try It Online") ### Explanation ``` l e# Read line el e# To lowercase "aeiou" e# Push this string _ e# Duplicate eu e# To uppercase er e# Transliterate. Implicitly display ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~25~~ 23 bytes ``` tr aeiou AEIOU<<<${1,,} ``` [Try it online!](https://tio.run/##S0oszvj/v6RIITE1M79UwdHV0z/UxsZGpdpQR6f2////iUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVUKjk7OLq5u7h6eXt4@vn7@AYFBwaFh4RGRUQA "Bash โ€“ Try It Online") *Saved 2 bytes thanks to a suggestion of Nahuel Fouilleul.* Input is passed as an argument, output is on stdout. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Saved 2 using a variation of [Luis Mendo's CJam approach](https://codegolf.stackexchange.com/a/201519/53748) ``` ร˜Cล’Hyล’u ``` A monadic Link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##y0rNyan8///wDOejkzwqj04q/f//vwdQLF8hPL8oJ0VHwdHf2x4A "Jelly โ€“ Try It Online")** ### How? ``` ร˜Cล’Hyล’u - Link: list of characters, S e.g. "I am OK!" ร˜C - consonants "BCDF...XYZbcdf...xyz" ล’H - split into two ["BCDF...XYZ", "bcdf...xyz"] ล’u - convert (S) to upper-case "I AM OK!" y - translate "I Am Ok!" ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 [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 tacit prefix function. ``` โŒˆ@(โˆŠโˆ˜'aeiou')โŒŠ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPh4PGo46uRx0z1BNTM/NL1TUf9XT9T3vUNuFRb9@jruZHvWse9W45tN74UdvER31Tg4OcgWSIh2fw/zQFdY/UnJx8hfD8opwUdQA "APL (Dyalog Extended) โ€“ Try It Online") `โŒŠ`โ€ƒlowercase `โŒˆ@(`โ€ฆ`)`โ€ƒuppercase **at** the following positions: โ€ƒ`โˆŠโˆ˜'aeiou'`โ€ƒmembers of "aeiou" [Answer] # [sed](https://www.gnu.org/software/sed/), ~~41~~ ~~25~~ 24 bytes Saved 16 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!! Saved a byte thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!! ``` s/./\L&/g y/aeiou/AEIOU/ ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1hfTz/GR00/natSPzE1M79U39HV0z9U//9/j9ScnHyFcP@inBQFsAxYQqGisioiMgoA "sed โ€“ Try It Online") [Answer] # Java 8, ~~86~~ 34 bytes ``` S->S.map(c->c^(c^~68174912>>c)&32) ``` -52 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/201521/52210), so make sure to upvote him!! **Original 86 bytes answer:** ``` s->{s=s.toLowerCase();for(var p:"aeiou".toCharArray())s=s.replace(p,p&=~32);return s;} ``` [Try it online.](https://tio.run/##dZDfT8IwEMff@SsuezBdlD3oGwsmiCgoP9Sh@CM@lK3AoLS1vQ2R4L8@uzlJiCFpmuvd9@776c1pSqvzaJGFnBoDPRqLTQUgFsj0hIYM@vkTIEAdiymEpAyM69v8tmIvgxTjEPogoJ6Z6vnG1I2HsitXTDepYcT1J1KTlGpQNYeyWCaOrTdnVDe0pmviunmHZopbQ6JO1FH9@@zU9TXDRAsw/jbzcyOVjLk1Kv1SGUewtLwl0ts7UPcXFplB4rQZ5xJGUvPIKWj/CgXCOIwm09l8wZdCfWiD6epz/QWNVmfweNG8vLpu39x2e/27@4dg@DR6fnndH2E/19L7KWzHAdjTAGyZofNvPwVvIS1XmMf5fkroYG2QLT2ZoKdsHbkgTkeoBGsAzvFO7B8UDxIs1M6x8EKyazjcUSJusx8) **Explanation:** ``` s->{ // Method with String as both parameter and return-type s=s.toLowerCase(); // Convert the entire String to lowercase for(var p:"aeiou".toCharArray()) // Loop over the vowels as characters: s=s.replace(p,p&=~32); // And replace the lowercase vowels to uppercase ones return s;} // Then return the modified String as result ``` [Answer] # x86-64 machine code, 21 bytes (Or **20 bytes** for an x86-32 version with an explicit length input, allowing `dec/jnz` as the loop condition. Using `cl` for a shift count makes it not a win to use `loop`, and 64-bit mode has 2-byte `dec` so it's break-even to make it explicit-length). Callable as `void vucd_implicit(char *rdi)` with the x86-64 System V calling convention. (It leaves RDI pointing to the terminating `0` byte if you want to use that bonus return value.) ``` # disassembly: objdump -drwC -Mintel 0000000000401000 <theloop>: 401000: b8 a0 bb ef fb mov eax,0xfbefbba0 401005: d3 e8 shr eax,cl 401007: 30 c8 xor al,cl 401009: 24 20 and al,0x20 40100b: 30 c8 xor al,cl 40100d: aa stos BYTE PTR es:[rdi],al 000000000040100e <vowel_up_consonant_down>: # the function entry point 40100e: 8a 0f mov cl,BYTE PTR [rdi] 401010: 84 c9 test cl,cl 401012: 75 ec jne 401000 <theloop> 401014: c3 ret ``` Notice that the function entry point is in the middle of the loop. This is something you can do in real life; as far as other tools are concerned, `theloop` is another function that falls into this one as a tailcall. This uses something like Arnauld's xor/and/xor idea for applying the lcase bit to an input character, instead of the more obvious `and cl, ~0x20` to clear it in the original, `and al, 0x20` to isolate it from the mask, and `or al, cl` to combine. That would be 1 byte larger because `and cl, imm8` can't use the AL,imm special encoding with no ModRM. Having the bitmap left-shifted by 5 so the bit we want lines up with 0x20 is also due to [@Arnauld's answer](https://codegolf.stackexchange.com/questions/201508/vowels-up-consonants-down/201521#201521). I had been planning to use `bt`/`salc` like in [a previous vowel/consonant bitmap answer](https://codegolf.stackexchange.com/questions/123194/user-appreciation-challenge-1-dennis/123458#123458) and mask that with `0x20` until I tried Arnauld's way and found it could be done even more efficiently. NASM source ([Try it online!](https://tio.run/##lVZrV9s4EP3uXzFfKAlN2DjQLgeXnoWUlLS8yqO09LA@sq0koorklew8@PPsSLKdNEALPoeESJqrq5k71yJa01HEZ01B9Oj@HvAJAugQzpkYQCzFmIqMSQE7cD7TX2G69bb5dtMr1o0lS2Ccx0nIRilnMctq8ZAoWFMJqz9cRKfLixqg2R0NM1AaAwZcRoRjwITyME9D3F5LQUQWJnIivGxIuZTptgV@9hNABQMRy0YkdcTmK66/f7v6enlxfvbl9OT46PDzp97Bx@7@h87e7j9muisVMJHQqcnIhGVD2D3v9HoQv9rwIWGKxhmfWcyRHOMnJdMG@OZpLX26vwjevYM3lgImmUKeOlQ8HvCYaGpovvSMNlhOTCgwDT5kElJFNVVjCq1puwWrsGpB9VCVJGP@AGf3EF659YgyRMACmKqSGazpocx5sgYRBU0d06k0oIQ/gomgGJWwfh81VBsR/fP9@7iOu8Q2koikiLS7LkUyLTnJ6EMWz9i1z1n6a1KB9UFQmtDEZSKTOnoyo4YYrlDUe0KP2ws1j5HDD9TzjR3LqM7cWMztwK24g0K99rfCtHkBSI6NQVH6UngryK31hw4Ix7739NS2F2C3Ea3zkUkYyYBTAe93wPfW533j@CYV32C5CH934d@yFtg7nGKrPky/i9N5VMSt7q4uJk8RMaBNPWT9zCjRzO7g8WxQPErLoOvVZhUYmOrg2SdEI3GtzRGEiWwAVm7CODeCI8CJGmDTCM0GgiYg8lFElUO@JQDrQoqQ8HRISv9BSe9AKjWzPsYE2NmIZlBrNdtv6niW4NmOgJOtpnUDFJGLK7o@@W3XR7860V@2jIUfQR91nGNirQ1E2Qv9yS/5IIaxqMKdZEL1o/ak2e@IvpxplEEJi0lYbqNOF7Nvuh47vuZfGu@rGees163kO6eXRycf9mFnBzbarisJj5/2OX8Pv6TgM2M92tW2BciqNe121wGOZQZkTBgnEaem2G83m6bzR5gOb4VyTd0mUVSaIH4sb9Lec5MldtNvAIljiQ2D@UU9d7rrCCbQ1JZ8KOHPMLXbHO3hT45WIFmP8uai3rZZ6x2dHvY6vYvwcP/448XBgumYWDI3Hdv4C@c2P6tBy7/yI/f7Pnj0KY0p1BlRmee@nKEEKwntm/fY6cXZee96HzbdC0nl1MplutG2@dhoV4VYd7sGVpDU3AJ@KJ2@3oTXsLnm35hwlBNmH1t9/MO/matXVYu3cPFWsVgtLra7m3e2ooMczaK4skBNoDSQTH0BzW83DCQ6wCNZNZpsefOy6Uyhodaqq828pRApRiU1/Wrc1XGusGpC0RRTpbHoUeGUsZFZ04FDE9rVUsO3wK7GEhpXY8GCAt1xorRhZ5byhce0IzHe6p68XC3E6IUYVyJ7o7F0w/D4LJwoltGFabOJv/jbHDpyrzo903bfMos2tmYaypWrUeQ1RA3WvdKzjceYDilEs7vXA7w94n8FHOLjxdT0t5GX8TqrNV1eQ2cFkOHj2BcDDG@BrelW65eGtNA1TK4QTIec/aS1gl0dCk62oPag@FEd1UC3N/wCprAaQ9YAhgMl87SGFlJfzIR3f39AOZdwJRW@/3F558N@9@NB79Pnw6Pjk9MvZ@cXl1@vvn2/BhLF2FuDIbv9yUdCpv8pneXjyXR29z8 "Assembly (nasm, x64, Linux) โ€“ Try It Online") with a test caller that does strlen on a command line arg and uses a write() system call afterward) ``` global vowel_up_consonant_down theloop: ; consonant bitmap ; ZYXWVUTSRQPONMLKJIHGFEDCBA@ For indexing with ASCII c&31 directly mov eax, 111110111110111110111011101b << 5 ; line up with the lcase bit ; the low bit is 1 to preserve 0x20 ' ' shr eax, cl ; AL & 0x20 is how the lowercase bit *should* be set xor al, cl ; bitdiff = (mask>>c) & c and al, 0x20 ; isolate the lowercase bit xor al, cl ; flip the lcase bit if needed stosb ; and store vowel_up_consonant_down: mov cl, [rdi] test cl, cl jnz theloop ; }while(c != 0) ret ``` --- ## Variants ### no spaces: 19 bytes If we didn't need to handle spaces (ASCII 0x20), we enter the function at the top, with the `mov cl, [rdi]` load at the top, but still leave the loop condition at the bottom. So we'd load and re-store the terminating `0`, and the XOR that produced it would set ZF. The low bit of the bitmap would be 0 instead of 1. ``` vucd_pure_alphabetic: .loop: mov cl, [rdi] ... ; same, but with bitmap[0] => 0 xor al,cl jnz .loop ; mask>>0 leave the terminating 0 unmodified; xor sets ZF ``` ### Upper-case-only input, like the A to Z in the question indicates: 19 bytes (Or 17 without spaces either.) If we can assume the lower-case bit was already cleared on input ASCII bytes, we can save one XOR (and change the other one to an OR) ``` ... shr eax, cl and al, 0x20 or al, cl ... ``` --- ### Using the `bt` instruction: Normally testing a bitmap is a job for the `bt` instruction, but where we're not branching on the result, it turns out to be cheaper to shift it, even though that means we can't easily use the `loop` instruction. (I haven't gone back to this idea to re-golf it after realizing we need to handle spaces). I suspect there's room for more golfing, but the first version of this I tried was ``` vucd: .loop: mov dl, [rdi] ; ZYXWVUTSRQPONMLKJIHGFEDCBA@ 1-indexed using ASCII codes directly mov esi, 111110111110111110111011101b ; consonant/vowel bitmap for use with bt bt esi, edx ; CF = mask & (1U << (c&31)) %if CPUMODE == 32 salc ; 1B only sets AL = 0 or 0xFF. Not available in 64-bit mode %else sbb eax, eax ; 2B eax = 0 or -1, according to CF. %endif xor al, dl and al, 0x20 ; just the lowercase bit xor al, dl loop .loop ret ``` Not re-tested after tweaking to handle spaces. `bt` + `salc` in 32-bit mode costs the same as `shr reg,cl` + the extra `test cl,cl` that's needed because we can't use `loop`. So I think this is also 21 bytes. But 32-bit mode explicit-length can just `dec/jnz` a reg other than `cl` for a 20-byte total. `mov esi, imm32` can be hoisted out of the loop, or we can use EAX. Neither affects byte count, only efficiency or the calling-convention. [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->s{s.downcase.tr"aeiou","AEIOU"} ``` Straightforward solution: downcase everything, then upcase vowels. [Try it online!](https://tio.run/##TcrLCoJAFIDhfU9xOOvyDQoM71oSFkXhwstIgnmmGUebomefaBG0/b9fqFKbZmkWK/mSVk1TXxWSWYPAgrWkcI62G6YHfBuuBgnNBQPWdQRHEl2N@exX7xMTg1YtcbAzx/ODKE7g@ajGsr/9bfurCzsVVjGsRTptwaMTRGrDM0hHV8CXk@KswSEfc/MB "Ruby โ€“ Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 9 bytes ``` T`vVL`VVl ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyShLMwnISws5/9/j9ScnHyF8PyinBQA "Retina โ€“ Try It Online") Explanation: ``` T`v`V ``` Lowercase vowels get uppercased. ``` T`V`V ``` Uppercase vowels also get uppercased, to avoid being matched later. ``` T`L`l ``` All other uppercase letters get lowercased. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~75~~ \$\cdots\$~~72~~ 71 bytes Added 4 bytes to fixed a bug. Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` u;f(char*s){for(;*s;*s++=u-65&&u-69&&u-73&&u-79&&u-85?*s|32:u)u=*s&95;} ``` [Try it online!](https://tio.run/##S9ZNT07@/7/UOk0jOSOxSKtYszotv0jDWqsYiLS1bUt1zUzV1ICkJYg0NwaTYLaFqb1WcY2xkVWpZqmtVrGapal17f/cxMw8Dc1qLpBZChnRsbZKHqk5OfkK4f5FOSlK1hDxkmhDo1hrrtzU3OSCSo0SnQwdQyNNa66Cosy8kjQNJdViBV07BSWdEqBYmkYJikxMHkS89j/U3HyguQA "C (gcc) โ€“ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~58~~ \$\cdots\$ 58 bytes ``` f(char*s){for(;*s;)*s++=index("aeiou",*s|32)?*s&95:*s|32;} ``` I tried to find a pattern in the vowels' representations using the modulo operator but nothing short enough. Instead, use `strchr`. *Fixed a bug kindly pointed out by [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) at the cost of 3 bytes.* *-1 byte thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9)!* *-1 byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!* *-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLM6Lb9Iw1qr2FpTq1hb2zYzLyW1QkMpMTUzv1RJR6u4xthI016rWM3S1ArMsa79n5lXopCbmJmnUZafmaLJVc2lAAQg0xQyUnNy8qNjFWwVlDxATIVw/6KcFAWwYQqOrp7@oUrWYNVpGmClmhBeQWlJMVyg9j8A "C (gcc) โ€“ Try It Online") [Answer] # x86 platform-independent machine code, 46 bytes. Expects the string pointer to be passed in `eax`, trashes `ebx` and `edx`. Entry point is located at 0x26. Hex dump: ``` BA 22 82 20 00 D3 EA F6 C2 01 74 0B 8D 51 9F 83 FA 19 8D 59 E0 EB 09 8D 51 BF 83 FA 19 8D 59 20 0F 46 CB 88 08 40 0F BE 08 85 C9 75 D3 C3 ``` Disassembly: ``` 00000000 BA22822000 mov edx,0x208222 00000005 D3EA shr edx,cl 00000007 F6C201 test dl,0x1 0000000A 740B jz 0x17 0000000C 8D519F lea edx,[ecx-0x61] 0000000F 83FA19 cmp edx,byte +0x19 00000012 8D59E0 lea ebx,[ecx-0x20] 00000015 EB09 jmp short 0x20 00000017 8D51BF lea edx,[ecx-0x41] 0000001A 83FA19 cmp edx,byte +0x19 0000001D 8D5920 lea ebx,[ecx+0x20] 00000020 0F46CB cmovna ecx,ebx 00000023 8808 mov [eax],cl 00000025 40 inc eax 00000026 0FBE08 movsx ecx,byte [eax] 00000029 85C9 test ecx,ecx 0000002B 75D3 jnz 0x0 0000002D C3 ret ``` byte count = 0x2E = 46 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Saved 3 using [Luis Mendo's CJam approach](https://codegolf.stackexchange.com/a/201519/53748) ``` lลพMDuโ€ก ``` **[Try it online!](https://tio.run/##yy9OTMpM/f8/5@g@X5fSRw0L///3SM3JyVcIzy/KSdFRcPT3tgcA "05AB1E โ€“ Try It Online")** (Footer formats the resulting list of characters as a plain string) ### How? ``` lลพMDuโ€ก e.g. input="LowEr" stack: [] l - push lower-case (input) ["lower"] ลพM - push lower-case vowels ["aeiou", "lower"] D - duplicate ["aeiou", "aeiou", "lower"] u - upper-case ["AEIOU", "aeiou", "lower"] โ€ก - transliterate ["lOwEr"] - implicit print lOwEr ``` [Answer] # [Io](http://iolanguage.org/), 72 bytes Takes input as a special format. ``` method(x,x map(i,if("aeiou"containsSeq(i),i asUppercase,i asLowercase))) ``` [Try it online!](https://tio.run/##LcyxCgIxEATQX1m22oV8gWBvYSdiYxMuKy7ksjHJcff3MWiKBzNTjFrfcrA9wekMz75Ke1ugwx2w@kzq9EXoRW3DxVLzmupNPqTsFHy95yxl8VV@7Wr7vzHzPKWotRFe0KEMcbIBhsfMZe4BmSEXTS2m/gU "Io โ€“ Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~83~~ 82 bytes ``` func[s][v: charset"aoeiu"parse lowercase s[any[to v change t: v(uppercase t/1)]]s] ``` [Try it online!](https://tio.run/##PYq7CgIxEAD7@4plK63ENq2F1jYWIUVINnqwZMPmcfj10QOxmxlGKc47ReuWZGbqOdjq7DAQXl4rNfRCa8eyC7BspMF/qVqf37YJjH3MT4JmYBx6Kb@hnc5H56qbRdfcIAHeiFngIcoRl3@9SCS4CiecHw "Red โ€“ Try It Online") [Answer] # [Javascript (V8)](https://v8.dev/), 97 bytes ``` s=>[...s].map(c=>{t="aeiouAEIOU";return(t.includes(c)?c.toUpperCase():c.toLowerCase())}).join('') ``` Takes a string, iterate over every chars and check if the char is a vowel. If so return the char in uppercase, otherwise in lowercase. Then join the return of the map with a void char. * First post/answer here, if you see some errors or missed case, or just want to improve my code feel free to do so [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` import Data.Char f=map(g.toLower) g x|x`elem`"aeiou"=toUpper x|1<2=x ``` [Try it online!](https://tio.run/##DcnLEoIgFADQvV/BMC1q00ytY1Ha297Za@WtUEkQQkxq@nfqbE8GZU45d44JJbVBARho@xloLyECVDNtGxnKmuqWlyL7tTHlVMQYKJMVJkZGSlH9j06vS6wTwAqiNCtMI0EYrrc7TdKMPXIuCqmeujTVq7bvD@oP/GA4Gk@ms3m4WK7Wm@1uHx1Ox/MFux8 "Haskell โ€“ Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 93...77 bytes Log: * -5 bytes thanks to @Benji * -14 bytes: switched to case insensitive matching and `.test()` ``` s=>[...s].map(c=>/[aeiou]/i.test(c)?c.toUpperCase():c.toLowerCase()).join('') ``` [Try it online!](https://tio.run/##bY/ZVsIwFEXf/QpwaqISnEW0IJOCMs/QgpY0xdbSpE0YHX69Vpe8uHg86@519rmWNtM49kwmIrOYb8g@lxMKQogP0ERjAMuJqKIRk04HURMJwgXAMImRoC3GiJfROAEw/pOLdL7OEFnUdIAkQR9Th1ObIJuOgQGkPLFtGupQz9bDEoRb/86/InfuiSXjujF@td7s1QLPRs5kEzzCOgkgM6AmDmWux8V0vliuQql0Jpu7f8gXHp@KpXKlWqs3mq12p9vrb6h5OTk9O7@4vIpdH0dkN/hBLKcmZcpAVbX1iBtV@ttxhKJf4bud3b3h/gGAz4e1Tq7e7LUKler750eqkQ2sgTS@3e9m2uly6TaRDJT@Nw "JavaScript (V8) โ€“ Try It Online") ``` s=> // es6 arrow function [...s]. // split input string into array map(c => // another es6 arrow function, this time for a callback iterating over the array /[aeiou]/i // case insensitive regex .test(c)? // use a ternary operator to check if the character matches the regex c.toUpperCase(): // if true return character to uppercase c.toLowerCase()) // otherwise return lowercase .join('') // join the array back into a string ``` Methods mentioned: * [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) * [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 ~~[`-m`](https://codegolf.meta.stackexchange.com/a/14339/)~~, ~~10~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` u r\c_v ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=dSByXGNfdg&input=IkhlbGxvIFdvcmxkIg) [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda s:bytes(c^(c^~68174912>>c%32)&32for c in s) ``` [Try it online!](https://tio.run/##DcJZC4IwAADg937FEIoN7EGNLlDovu87InDqcqXT3LTsob@@@vjiXPgRMyQxLzKwQ@zagDdxLjwOnev/t1rXapWGpluWUzR0VDJ0EiXAAZQBjiQ3vcwOIGVxKiBChTihTECuAqVsKSogkCMksWJjx/XIzaf3RxCyKH4mXKTZ651/QKvd6fb6g@FoPJnO5ovlar3Z7vbHw@ms/AA "Python 3 โ€“ Try It Online") Port of [Arnauld's JS answer](https://codegolf.stackexchange.com/a/201521/78410) using bytes object in Python. Because Python's `>>` does not imply `%32` on its right argument, it must be done manually. [Answer] # T-SQL, 48 bytes ``` SELECT TRANSLATE(LOWER(v),'aeiou','AEIOU')FROM t ``` Takes input from a pre-existing table *t* with varchar column *v*, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Converts the entire string to lowercase, then makes just the vowels uppercase. The function [`TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017) works in SQL 2017 and later. [Answer] # [K4](https://kx.com/download/), 24 bytes **Solution:** ``` .q.ssr/[;_v;v:"AEIOU"]@_ ``` **Explanation:** Replace each lowercase vowel with the uppercase equivalent. ``` .q.ssr/[;_v;v:"AEIOU"]@_ / the solution _ / lowercase @ / apply .q.ssr/[; ; ] / search/replace, iterate over vowels v:"AEIOU" / store uppercase vowels as 'v' _v / lowercase vowels ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~27~~ ~~23~~ 21 bytes **Solution:** ``` `c$x-32*~^"aeiou"?x:_ ``` [Try it online!](https://tio.run/##y9bNz/7/PyFZpULX2EirLk4pMTUzv1TJvsIqXikxKTklNS09IzMrOyc3L7@gsKi4pLSsvKKySsHRydnF1c3dw9PL28fXzz8gMCg4JDQsIjwySun/fwA "K (oK) โ€“ Try It Online") **Explanation:** Even nicer approach thanks to @ngn... either substract 0 or 32 from the input based on whether or not it's a vowel: ``` `c$x-32*~^"aeiou"?x:_ / the solution _ / lowercase input x: / store as 'x' "aeiou"? / lookup input in "aeiou" else null ^ / is null? ~ / not -32* / multiply boolean list by -32 (yields 0 or -32) x / subtract from x `c$ / cast back to characters ``` **Notes:** * **-6 bytes** thanks to @ngn [Answer] # [Julia](https://julialang.org) 49 bytes ## [Try it!](https://tio.run/##BcFBCoAgEADAryyeFDSobkHWsR90lk3J2NpQxH5vM1eh6PqvhbmRsbd7JRobH4laOB@5CAULoBkHmAA1cfUJXfadJKXamk@uEKTYPBHDzokOodoP) ``` f=l->map(c->in(c,"aeiou") ? c-32 : c,lowercase.(l)) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` K"aeiou"smrd}d+KrK1w ``` [Try it online!](https://tio.run/##K6gsyfj/31spMTUzv1SpOLcopTZF27vI27D8//@SjFSFwFBPZ2@FpKL88jwFN/8IhazS3IJiBf8w1yAFkLSPY1SkQkp@OgA "Pyth โ€“ Try It Online") # Explanation ``` w=input() K"aeiou" K="aeiou" s "".join( m map( r lambda d:r( d d, d d } in K K + + rK1 K.upper())), w w) ``` ]
[Question] [ Let's start by defining a Two Bit Numberโ„ข: * It is a positive integer * When expressed as a binary string it has exactly 2 true bits OR * When expressed as a decimal number, it has exactly 2 of the numeral one, and all other numerals are zero. Or as a sentence A Two Bit Numberโ„ข is a number which contains exactly 2 of the numeral 1 and no other numerals besides 0, when expressed as a decimal string or a binary number. So here area all the Two Bit Numbersโ„ข between 0 and 256 ``` Dec Bin Type 3 00000011 Binary 5 00000101 Binary 6 00000110 Binary 9 00001001 Binary 10 00001010 Binary 11 00001011 Decimal 12 00001100 Binary 17 00010001 Binary 18 00010010 Binary 20 00010100 Binary 24 00011000 Binary 33 00100001 Binary 34 00100010 Binary 36 00100100 Binary 40 00101000 Binary 48 00110000 Binary 65 01000001 Binary 66 01000010 Binary 68 01000100 Binary 72 01001000 Binary 80 01010000 Binary 96 01100000 Binary 101 01100101 Decimal 110 01101110 Decimal 129 10000001 Binary 130 10000010 Binary 132 10000100 Binary 136 10001000 Binary 144 10010000 Binary 160 10100000 Binary 192 11000000 Binary ``` The challenge: * Write some code which accepts a number and outputs true or false (or some indicator of true or false) if it is a Two Bit Numberโ„ข. * Input will always be an integer, but it may not always be positive. * It can be in any language you like. * It's code golf, so the fewest bytes wins. * Please include links to an online interpreter for your code (such as tio.run). ## Test Cases Binary Two Bit Numbersโ„ข: ``` 3 9 18 192 288 520 524304 ``` Decimal Two Bit Numbersโ„ข: ``` 11 101 1001 1010 1100 1000001 1100000000 1000000010 ``` Non Two Bit Numbersโ„ข: ``` 0 1 112 (any numerals over 1 prevent it being a Decimal Two Bit Numberโ„ข) 200 649 -1 -3 ``` --- Fun fact: I was not able to find any DecimalBinary Two Bit Numbersโ„ข checking up to about 14 billion, and I have a hypothesis that such a number does not exist, but I have no mathematical proof. I'd be interested to hear if you can think of one. [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ ~~62~~ 48 bytes -6 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! -14 bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)! ``` lambda n:' 11 'in f' {n:b} {n} '.replace('0','') ``` [Try it online!](https://tio.run/##RY7BDoJADETvfMXcCslidgENkOiPIAdUVklwIYgHQ/h2bCHGQyftm2na/jM@Ohcv9nhe2up5uVVwOcEYUONgCZPLLzPrDNoNdd9W19onTYooWMb6Nb5wROEBRayQKZiUK4sUopS7faRFklgnpZKQMWzrVTY1HDA8rERvcOv0HzLW274gScgB8Q8J3wwZhTEHSs@z3YD70L178PvrfznvCZVB4OoKBPqhcaNvaRJvRnjCZH3pg5kC7@cHyxc "Python 3 โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` f n=or[b^x+b^y==n|b<-[2,10],x<-[0..n],y<-[x+1..n]] ``` [Try it online!](https://tio.run/##FctBDoMgEEbhq8yiO38Mo5s2kZMQTCSRlJSODXWBiXdHXL1v897L/7OmVGsgMVu2fi6dnw9j5PSTsgNYO5Qm3fficDSVjm@7@l2ikKFfjrLTg0JM@5opkB3xAj/B3G6GRisPUAw1unoB "Haskell โ€“ Try It Online") Brute force search. ## Alternative 50 bytes ``` b!0=0 b!x=rem x b^3+b!quot x b f n=2!n==2||10!n==2 ``` `b!x` computes a base-`b` โ€œcubed digit sumโ€ of `x`. For example, `10!123` = \$1^3+2^3+3^3\$ = 36. We check if either of `2!n` or `10!n` equals 2. `quot` is necessary to support negative input. It rounds toward zero, whereas `div` rounds down, meaning `div (-1) 10 == (-1)`, causing an infinite loop. [Answer] # JavaScript (ES6), 38 bytes Returns **0** for *true*, or a non-zero integer for *false*. ``` n=>(g=n=>!(n&=n-1)|n&n-1)(n)*g('0b'+n) ``` [Try it online!](https://tio.run/##dZHLDoIwEEX3fgVuaKtBW0ADMbj0C9ypi8pLDA4G0ITEf8caFj5m3LTJ6Z07tzNnfddNXBfX1oEqSfss6iFa8zwy55iDHYGjxAPs18VBTHLO5JFNQfRxBU1VprOyMmy3rW/tqbPm1rEAXXcHJlajT0XGPSF@SIiICjAKXcTcAOsWriSY70nf4C/O9vCOm6RxcdElkVcpnEVSjIQKp1FGSpVL0mF4kH9L5NAC/Wyjy4YaP@FDNCVmTSRY@nh1DrZzzMr7Jw "JavaScript (Node.js) โ€“ Try It Online") ### How? The helper function **g** removes the two least significant bits set in `n` by computing `n & (n - 1)` twice. If we get **0** the first time, it means that `n` has at most one bit set, which is not enough. If we *don't* get **0** the second time, it means that `n` has more than 2 bits set, which is too much. For the decimal test, we invoke **g** with `'0b' + n` to parse it as a binary value. If `n` is negative, this gives something such as `'0b-10100'`, which is NaN'ish and fails as expected. --- # JavaScript (ES6), ~~40~~ 39 bytes Returns a Boolean value telling whether the input is *not* a Two Bit Number. ``` n=>[n,'0b'+n].every(n=>!(n&=n-1)|n&n-1) ``` [Try it online!](https://tio.run/##dZFNDoJADIX3ngI3DETBGUADMbj0BO6QxQCDYrAYQBIS744YFv60rib55vX1tb3ITjZpXdxaC6pMDXk4QLiLYMl4whYQ26pTdW@MbG6AHoIlzAfor2dIK2iqUtlldTJYdKjv7bnXVlpSgKz7mJnb2aciN1zT/CEBIsLHKHAQc3ysWzucYJ7LvRF/cXaEd9xMpcVVlkReIXAWTjESCpxGjFKqnJMO0wf/W8KnFmiyvSwbav2ED9GU2DWRYOPh01nYzhpPPjwB "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` bโ€šโ‚ฌ{11รฅ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/6VHDrEdNa6oNDQ8v/f/f0NAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6RHDbMeNa2pNjQ8vPS/zv9oYx1LHUMLHUNLIx0jCwsdUyMDIDYxNjDRMTTUMTQAYkMDIG0A5hiAeGCugQFECgp0YCygEiAHKAM0DihsDMRmJpY6uoY6usZA0jAWAA). `โ‚ฌ{` could alternatively be `0ะผ` for the same bytecount: [Try it online](https://tio.run/##yy9OTMpM/f8/6VHDLIMLewwNDy/9/9/Q0AAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6RHDbMMLuwxNDy89L/O/2hjHUsdQwsdQ0sjHSMLCx1TIwMgNjE2MNExNNQxNABiQwMgbQDmGIB4YK6BAUQKCnRgLKASIAcoAzQOKGwMxGYmljq6hjq6xkDSMBYA). **Explanation:** ``` b # Convert the (implicit) input-integer to a binary string โ€š # Pair it together with the (implicit) input-integer โ‚ฌ{ # Sort the digits in each string 11รฅ # And check if this pair contains an 11 (which is truthy for "011","0011",etc.) # (after which the result is output implicitly) 0ะผ # Remove all 0s from both the binary string and input in the pair ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 bytes ``` 2โˆŠ+/โ†‘(*3)2 10โŠคยจ0โŒˆโŽ• ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L/Ro44ubf1HbRM1tIw1jRQMDR51LTm0wuBRT8ejvqkgJf8VwKCAy4gLxjKGs0zhLENDJKYBEhshfmi9KQA "APL (Dyalog Extended) โ€“ Try It Online") Jo King's 18 byte solution. # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20 21 20 26~~ 25 bytes ``` {<โต:2โˆŠ+/โ†‘(โŠ‚ร—โจโŽยจโ•โต)โชโŠ‚โŠคโตโ‹„0} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR71Y7AyujRx1d2vqP2iZqPOpqOjz9Ue@KR719h4DEVKC85qPeVUDhR11LgJxH3S0Gtf/THrVNAKp41NX8qHfNo94th9YbAzU/6psaHOQMJEM8PIP/pykYcaUpGAOxKRAbGoIJAzAJYh9abwoA "APL (Dyalog Extended) โ€“ Try It Online") +1 byte after correcting the answer(ovs). -1 byte after ovs's suggestion.(yay!) +7 bytes after properly accepting negative test cases. -1 byte from Adรกm. Inspired from the J solution. ## Explanation ``` {โต>0:2โˆŠ+/โ†‘(โŠ‚2*โจโŽยจโ•โต)โชโŠ‚โŠคโตโ‹„0} โต>0: If number is positive โŠคโต Decode number to binary ร—โจโŽยจโ•โต square each digit โ†‘ โŠ‚ โชโŠ‚ join into two rows +/ sum each row 2โˆŠ is two present in it? โ‹„0 otherwise return 0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` โ„•{แธƒc|}o11 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f9Qytfrhjubkmtp8Q8P//6ONdSx1DC10DC2NdIwsLHRMjQyA2MTYwETH0FDH0ACEwYShAVDAwADENQCLQBgGcCEDkBIgBygDNAoobGZiqRNvqBNvHAsA "Brachylog โ€“ Try It Online") Somewhat embarrassed I didn't think to translate other solutions' sort-based approaches earlier... A more fun solution: # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` โ„•{|แบน~แธƒ}แธƒ+2 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f9Qytbrm4a6ddQ93NNcCsbbR///RxjqWOoYWOoaWRjpGFhY6pkYGQGxibGCiY2ioY2gAwmDC0AAoYGAA4hqARSAMA7iQAUgJkAOUARoFFDYzsdSJN9SJN44FAA "Brachylog โ€“ Try It Online") ``` โ„• The input is a whole number (necessary to exclude -3 etc.), {| } which either unchanged or แบน with its decimal digits ~แธƒ interpreted as binary (impossible if any โ‰ฅ 2), แธƒ has binary digits +2 that sum to 2. ``` # [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 11 bytes ``` โ„•{แธƒ|แบน}<แต›ยฒ+2 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f9Qytfrhjuaah7t21to83Dr70CZto///o411LHUMLXQMLY10jCwsdEyNDIDYxNjARMfQUMfQAITBhKEBUMDAAMQ1AItAGAZwIQOQEiAHKAM0CihsZmKpE2@oE28cCwA "Brachylog โ€“ Try It Online") -1 byte thanks to xash ``` โ„• The input is a whole number, { | } and either แธƒ its binary digits แบน or its decimal digits <แต›ยฒ are all less than 2 +2 and sum to 2. ``` [Answer] # [R](https://www.r-project.org/), ~~50~~ ~~49~~ ~~48~~ 46 bytes *Edit: -1 byte, and then -1 more byte, and then -2 more bytes, thanks to Robin Ryder* ``` gsub(0,'',n<-scan())!=11&sum(n%/%2^(0:n)%%2)-2 ``` [Try it online!](https://tio.run/##bZDdTgMhEIXveQqMWYGkRMCftI19E6OZRWqJ3aFh2Jg@/cpemCyrl9@ZM4cz5Gn6pLGXZiPEBl80eUCp1M3B2jsaB4ndfefepNmj6jqntJuenGHMQ5HiFYVi7JbnoL9zLIETDIHD5ZIT@BMH4scRfYkJeUk8AMXzlftT8F@8BCrcAwXas0jvmIrrYzn8@iUqtqhV6whrxf@F5gZ9RMjXRZJ8UEvaNWS3Le5cw27bzuvBqr7xEXwc4Nxs2jbIrPmPYE0rVMucjQn1LCxnK@dqr638/NheqFu7rr/B2PQD "R โ€“ Try It Online") Tests for decimal 2bit numbers using text manipulation to remove '`0`' digits and check whether the result is *not* '`11`', and then tests for binary 2bit numbers by calculating the binary digits and checking if they *do not* sum to `2`. Returns FALSE for 2bit numbers and TRUE for non-2bit numbers. It seems a bit clunky to do two different kinds of tests for essentially the same feature, but somehow comes-out quite short... [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` โ‚fb3eแน 2c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLDt+G5oShuzrsiLCLigo1mYjNl4bmgMmMiLCI74oCgW24sXSkiLCJbLTMyLDI1Nl0iXQ==) [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oKNZmIzZeG5oDJjIiwiIiwiM1xuOVxuMThcbjE5MlxuMjg4XG41MjBcbjUyNDMwNFxuMTFcbjEwMVxuMTAwMVxuMTAxMFxuMTEwMFxuMTAwMDAwMVxuMTEwMDAwMDAwMFxuMTAwMDAwMDAxMFxuMFxuMVxuMTEyXG4yMDBcbjY0OVxuLTFcbi0zIl0=) - test cases only ``` โ‚ # Parallel Apply Wrap - applies the following two operations to the input, # wrapping the two results in a list. f # Flatten (convert decimal string into list of digits) b # Convert to binary (as a list of digits, which will all be negative if the # number is negative) 3e # Cube (applied to each digit) แน  # Vectorized Sum (apply individually to each list) 2c # Does the resulting list (of two items) contain the number 2? ``` Alternatively instead of `3e` to cube each digit, `ส€แน ` could be used to triangularize each digit, or `โˆšโˆš` to take the fourth root of each digit. If not for the fact that the challenge requires that negative numbers be tested (and that they can't be Two Bit Numbersโ„ข), this could be 7 bytes, because we could use `ยฒ` to square instead of `3e` to cube. # [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 9 bytes ``` โˆ†b"vsโŒŠ11c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLDt+G5oShuzrsiLCLiiIZiXCJ2c+KMijExYyIsIjvigKBbbixdKSIsIlstMzIsMjU2XSJd) [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oiGYlwidnPijIoxMWMiLCIiLCIzXG45XG4xOFxuMTkyXG4yODhcbjUyMFxuNTI0MzA0XG4xMVxuMTAxXG4xMDAxXG4xMDEwXG4xMTAwXG4xMDAwMDAxXG4xMTAwMDAwMDAwXG4xMDAwMDAwMDEwXG4wXG4xXG4xMTJcbjIwMFxuNjQ5XG4tMVxuLTMiXQ==) - test cases only ``` โˆ†b # Convert to binary as a string. " # Pair that string and the original number as two items in a list. vs # Vectorized Sort - sort each individual item in the list (sorts the digits) โŒŠ # Floor - in this context, used to interpret strings as decimal and convert # them to integers. 11c # Does the resulting list (of two items) contain the number 11? ``` This solution was unusable at the time of my original posting, due to `โŒŠ` not working on `0`. The bug has since been fixed. [Answer] # Regex (ECMAScript), ~~70~~ ~~68~~ ~~56~~ 52 bytes *-4 bytes by successfully combining base \$2\$ and \$10\$ into a single expression, as was already accomplished in the other versions* ``` ^((x)|(x))((((\2*)\3*)(\2\7){8}x(?=\6$))*x){2}\2{8}$ ``` [Try it online!](https://tio.run/##TY/BTsJAEIZfBRsCM8WWUhUN68LJAxcOerSabGBoV5ftZneBSttnr@Vg4iR/Mvm/SSbflzgJt7XS@MgZuSN7KPU3/XSWazoPXil/qQzAhS@nYfcJUGHTB6GfLA0xuwuxX7JHrJ/aClY8mw8RwwrrtM3Svht24fSCsS/fvJU6B4ydkluC@W10j8gcT9i5kIoAFLckdkpqAsQbro9KYZ1zFTujpIdxNEYm9wCa57EinfsCl2nTSLcRG5DcCOtorT3k78kH4h@g/0AvZ6vZ4orRF7Y8B2t9EkruBlbonBaDYKLYvrTA5DMnJicT7B8GVRBbMiQ8SIwPwm8LsIi1G41Mr@ThajFj5uidt/0Ja9suiR7S5Bc "JavaScript (SpiderMonkey) โ€“ Try It Online") Takes its input in unary, as a sequence of `x` characters whose length represents the number. Here are some examples of how this **52 byte** version works: ``` Example input: 1001000 Choose base 10 and subtract 1 from tail 1000999 Iteration 1 of the outer loop: 1000999 100099 10009 1000 tail -= 1 999 Iteration 2 of the outer loop: 999 99 9 tail -= 1 8 Assert tail == 10 - 2 Example input: 11 Choose base 10 and subtract 1 from tail 10 Iteration 1 of the outer loop: 10 tail -= 1 9 Iteration 2 of the outer loop: 9 tail -= 1 8 Assert tail == 10 - 2 ``` The regex, pretty-printed and commented: ``` ^ # tail = N = input number # Pick which base to operate in, and tail -= 1 ( (x) # \2 = 1 or unset (unset=0 due to ECMAScript NPCG behavior); B=10 | (x) # \3 = 1 or unset (unset=0 due to ECMAScript NPCG behavior); B=2 ) # Assert tail is the sum of two powers of B ( ( # tail = (tail + 1) / B - 1 ((\2*)\3*) # if \2=1, then \6 = \7 = (tail + 1) / 10 - 1; # if \3=1, then \6 = (tail + 1) / 2 - 1, and \7 = 0 (\2\7){8} x (?=\6$) )* # Loop the above zero or more times x # tail -= 1 ){2} # Loop the above exactly twice \2{8}$ # Assert tail == B - 2 ``` *The following text applies to the earlier 56 byte version:* This turned out to be very similar to [Neil's 58 byte regex](https://codegolf.stackexchange.com/a/212103/17216). I looked at the byte count, but not at the regex itself, in that answer's heading before working on the problem myself. It took me a while to figure out how to make a non-ECMAScript-specific regex shorter than 70 bytes. The hangup for me was, that I was doing it like this: ``` ^((((x+)\4{8}(?=\4$))*x(?=(xx)*$)){2}|(((x+)(?=\8$))*x(?=(xx)*$)){2})$ ``` In order to prevent the loop from subtracting the same power of 2 or 10 twice (and matching, for example, 512 and 200) I had to use `(?=(xx)*$)` to assert that tail is even after subtracting 1 (this works for both 2 and 10, as they are both even). Finally I figured out that I could just use two alternatives inside the `(`...`){2}` loop, one that must do at least one division before subtracting 1, and one that can only subtract 1 if it's the first thing done, and this saved 7 bytes per base, giving 70 - 2ร—7 = 56 bytes: ``` ^((((x+)\4{8}(?=\4$))+x|^x){2}|(((x+)(?=\7$))+x|^x){2})$ ``` # Regex (ECMAScript / Perl / PCRE / Java / Boost / Python / .NET), 54 bytes ``` ^(x?)(^x|\B)((((\1*)\2*)(\1\6){8}x(?=\5$))*x){2}\1{8}$ ``` This is a port of the 52 byte ECMAScript version to be NPCG-behavior-independent and compatible with a wide variety of regex engines including ECMAScript (i.e., "generic"). This is done by changing `((x)|(x))` (where `\2` and `\3` are differently 1 or unset) to `(x?)(^x|\B)` (where `\1` and `\2` are differently 1 or 0). [Try it online!](https://tio.run/##TY9Ba8JAFIT/ig2i78UmJqFKcbsKhR689NAemwqLPpNt182yu2pqzG9P46HQOQ3zDQzzJU7Cba00PnJG7sgeKv1NP53lms6DNypeagNw4ctp2G2gXiFs6mv@jNArT0PMsxB7k8@xeWxrWPF8NkQMa2yyNk/7bNiF0wvGvnr3VuoCMHZKbgnm99EDInM8YedSKgJQ3JLYKakJEO@4PiqFTcFV7IySHsbRGJncA2hexIp04UtcZterdK/iFSQ3wjpaaw/FR/KJ@AfoP9DLdJUubhh9aatzsNYnoeRuYIUuaDEIJortKwtMPnFicjLBfjCog9iSIeFBYnwQfluCRWzcaGT6Sx5uL1Jmjt5521dY23ZJNMuSXw "JavaScript (SpiderMonkey) โ€“ Try It Online") - ECMAScript [Try it online!](https://tio.run/##RU5dS8MwFP0rYYQ1t2tpU6iIadZO5qtPvi1bmLJCIG41qRCJ8a/XrA68D5dzzv04ZzgZXU/vXwgbhry@vB01wgWLlDfbzctmHVB/MQRbXrJmzcAj1UcGfjDqPKKFOC9YQJ3mdtBqJEmeZPbz1Y7xRGY5zSicPq5L7b9aRh0esAR2/WWj49F0uqnAd3pH9zz2cs9uvupGsWr4PI5otQKvekRI4hLkUFwCQPwHFdgU4LFdLudwc7YYnLK/rFixEIKUT89bKacDcS2Qg/sWj0BiCZqCqFKIQNyBvw@OtFzUGCB14KsgaNTwNJV5XZW/ "Perl 5 โ€“ Try It Online") - Perl [Try it online!](https://tio.run/##XVDfa8IwEH73rwgh0JxWbYu6SSzC2AaDsYdtb0ZD7aItq2lIIxScf3t3lT0tcMf9@r7vcraw3WptC0uYIymhU0omxDp9VE7bKss1D6aT4VqpIqu8yuuTLSvtJJcg5Pu0CUISoB2wqI66HzBeG99wpZ5fXp@UgpDEgJRILAalKVWjPac2d3qyz/Jv79CpqjyVnoaEzpLlbLm4S5ZzCmJwqB1nZRoJVqUHZG/4x@fjyxsIuJDywFm1abyrtMEIxvE2Tak0FHC4Oe@xg@UwCscx9Hjd2qr@0pyOaYjjAvF5fTa@x64SBG2QAH20FQNCbsrmL2dmld76GI1GgNKE3y50ynxecOZCFOvPpTPPgzYImQEAculXLEHnRd3vJQh@JRakzwkz4ooy139n5SC6HW/XwHftj3wAjk/GQ5DJEDCQC7jcX1u@TuWcAQxbuCRXGWONdV00nifRLw "PHP โ€“ Try It Online") - PCRE [Try it online!](https://tio.run/##bVLvb9sgEP3ev@JmdQo4KU0idZpGrWqdNqnSuk3txziViI0TUow9wI3TLH97djjej0rlC9zd4x3vcWvxJM7W@eNBlXVlPawxZqpiMYf/M41X@tWclUvZYuWkbhZaZZBp4RzcCmVgB33OeeFxe6pUDiVWyL23yixB2KWbzSn4la02Dj63may9qvDmCcAXpSUUiZGb7kgillW5ZFiPKL9uikJamd9JkUsLiw72Mkn@3OzDglLe93UjzzerwE@ISxaoQeRflZGE0jeJabSmqiCOyZ@N0I5E53EcR5TuXkKPDIT4Vwl2yOD/MiDBOTIsEPfI3TAZpGYQds/3x9z@h/BeWgM26U@otqxDA0c5urGoKi2FgeekQEbJ4T4TxqB0ZerGQwJBbZ8j91vnZcmUoRx6nR2MrYT7JluPz@wsBugN0fh25DiCDCJ6iX19NgeN5YBirtbKk@gMPwHxHswYKzfG4xhYVgvrJAZEz8ZzOgIzebXItDRLv7qcwhUEJHzAbTJHxmwl7Gze9nq6yEzmHD5aK7aOFUpr0o4G7aAzBaCobNCGz0jMmIO5TMwEt@EQBd4Kn63QoRLZLCuPEekm1@CAf0Ly48SwjRU16VtkVb39XtwJs5TYaTwylAalBZAS25scvQt/@0x7kyt0bGOVlyR8KuXPibdN@J9/5Ro99AWJ3roILaF8H9ZJmKrDA2mvKHlof6XXlOBKJzFNpzHFQ/qO7t7vW3KVpBenlMYt3U336QRzp4cwT4fx2cV0/Bs "Java (JDK) โ€“ Try It Online") - Java [Try it online!](https://tio.run/##dVNtb9owEP7Or7ixqtgktIRuaEpIkSr1D0z7sInQKDUmsQZO5DgihfHXx85OYRkDf0h8b8/dPXdmRTFIGTt8FJKtqgWHyWuel/pe8ZTXd1lRPHbOTbxmvNAil/cLkaQSVYLFQi5ztU6MuoliWaIgLmZzCOFr92mz@fn6UP14e/v@LRtvMnJ4IfWUkpf6V/RECZ7I69No1Kd4icZ092Vfk2kYfb6htF/T3Wgfeai7OdBzpK4L/SKMC8cLWpUKrErxZP3YEVLDOhGSUNh1AE8xQ9OKS1LQgTcPhwFU6PMwijXkRjIBqbmUeuH76Ctkisqi0oGNZ7ksNVgqfN/SBIojWHDUlUgDy2CTJe8RyAwQA7sNhy5s@Qk85XolJCdWYEK6TR4aHGs1xwTKIbKY6FwQ63DHYqyLUOqC9Fwo8hLNjWUp5IL0Bj0anACkh1bj8yFs9@T70iinF3DBsf4OeBR8TP4Xy061b9JJvmmkmfQcbx7Amq9LrknpQq/umcKQkRKNhuJT/IkKEUrD9SSUXgCOI9odm6PV25nGcrEE0mY@LnmiWEZIqy96a7IOxNy1I3BxOpRewDribSlg66YV0oskEodj8oKL7s2c8krDZALif59957rE7FKQf7bn9JLglitFrzR8ucCzYsyn68OzUrnqBpdxOIWlQbIwrgEwWQOzkSc81LTxuub/Xu3l104sxpXGm1vzVVxXSgIuw/4wHIw/DX@z5SpJy8NgZRPEdqJ/AA "C++ (gcc) โ€“ Try It Online") - Boost (throws some errors, but this is fixed in later versions than what is on TIO) [Try it online!](https://tio.run/##NY7BasMwEETv/opF5LDr2sZySSl2RaC/YTkQWiVRUWWzUqlDmm93rZTuaZjhzc50iefRPy72cxo5QriEgk3xEUbfASsWQix7nHeE@/lHvxKup2VOuslpFfqJrs@3GXdKbzdE@UzX5qbl6m2WFe1lW8qhA6vq7DgyOLA@vahCfLe@zcApV4XJ2YiiFJSBPYIzHh29NC24Xg7K9fWQQYJ9gvngTwatj5gCKv6UHOhB0tqXCthUwRz47YxcgJhF7u9JimwLEyeE7oaS3f@a8StW32yjwRAZPdFSl9um/gU "Python 3 โ€“ Try It Online") - Python [Attempt This Online!](https://ato.pxeger.com/run?1=NU9BasMwELz7FYvIQevaxjIkBLsi0G_YDoRWTlRU2UgKVUjzkl5ySX_RQ5_R39Sy0z3NzjCzO59fw8kden39lm9DbxzYk02M2AufvNpeV2C4IYTcjq5L17-rLfUbpFv_0TwhHadhMTZFjCNoVnheXzzd8Ga5QIw9notLw0ZucXf_jEE1K1PWViB5HnW9AQVSh5uZdS9SlxEorjI7KOkoSQlGIDtQQlOFj0UJqmYtV3XeRhDMOpjNTu8FldrRIGAyI9biA8MxLwRMfTIrdub5QE0CxJNYT2JQZQmDCS6cCM6q_4f6o8vejXSCWmeoRpyLXG95uizyefkD "Python - Attempt This Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`) [Try it online!](https://tio.run/##RY9ha4MwEIb/isiBOV2KCh2jElq2z/sFxoK06QxkicQUQ11@u4sbY/fpnofj5d7RzMJOg1BqBctaKz6E7w4HLWZyytYz8UckZ//FX5HE4VWOvM4xLvwZl5fgyZHxPSDmHpc68Co6WLPTU/pmPkepxDXFBh6sbG7Giv4yEFCJ1AlIPd4dLtAzUHQalXQpTRt5I9DvLuauHVUuqbeDgkHfll2IAQQ0a6V23Y9pQFMl/rjauChw2TLs7r13l0FMJPNZDhp/9QOX2Uon6GAmF@JbVfPPCdUm1lZSiwR0CGEt6b4uvwE "PowerShell โ€“ Try It Online") - .NET It [exposes a bug](https://bugs.ruby-lang.org/issues/17774) in the regex engine used by Ruby. The 56 byte regex works in Ruby: [Try it online!](https://tio.run/##TY5Ra8IwEMff9yluRTCZNKTFsUEWhuBe9yB7azU4jDUQzpJGzFD31WviphhI4H73/13O7b5/egcSZrrRoWWo9zCdfE2Y08uVACO5gP3GWA1WNtp3DwBmDbbKi7mUWY2ZiA1bccbyci5A4yomImFda40nw3xI/xVmNTZ@Q@hbGZ0q@lG7KeutAwSDkCDzW2VIwSljKXgrY@4yi2Qhe0IK8hecSMA8pj3bne8u89LeRaydQQ94/SK96Sr18TlVql@QeMKI1uPD64m8y3o8oHQUjotAD@Xp@NdM/OWe00Hf8/y55Gc "Ruby โ€“ Try It Online") But the 54 byte regex does not: [Try it online!](https://tio.run/##PY7Ra8IwEMbf91fcimCu0NAWHIMaRHGvexh7azRsGGsgxJJGzHDuX@8ushlIuO/L97s7f/r8Gj0IeNOdjj13@gzr5fuSe/2xa8CIsoHzwVgNVnQ6DA8AZg@2LaqNEJl0WUMfti05L@pNA9rtKEEOH3prApsWU/xDuNWuCweG85qYlnjC7sj@6MGBcZBMHo7KsKpEzlPwLil368WymOUOQfyAb5JhHtOe/SkMt35p74q0Ny6A@x@R3nSVenldKzVuWVwg28ZvuUJGR1Y5yjpHKuQTXp6vkS2EnE0Q84iX@ior8ibjWBazuvwF "Ruby โ€“ Try It Online") Boiling this down, it appears that [`^((x*)(){4}(?=\2$))*x$`](https://tio.run/##PY5Bi8IwEIXv@ytmi2BS6JCW9RSDCHr1sHirbtjFWANhLGnEyqJ/vSaiHmZg3rzvzfjT32XwoODbNKZvkcwZFvP1HL353UmwSkg4H6wz4FRjQvcBYPfg6qLcKpVtKJNx4WqBWFRbCYZ20REV7FpnAxsXY/5E0BlqwoHxaRWZOvIReyP7owcCS5BEDEdtWSk4YjK@x@h7ZLGsz3LioG7gZRLsZ/qzPYXukZf@LuPsLQWg14nUU2m9XC20Hn4Y63PO@P/Xlc3UphpxnvejYRDFpBJ3 "Ruby โ€“ Try It Online") matches powers of 2 just fine, but [`^((x*)(){5}(?=\2$))*x$`](https://tio.run/##PY5Bi8IwEIXv@ytmi2BS6JAWPGWDCHr1IHurbtilsQbCWNKIFVn/ek1EPczAvHnfm/Gnv8voQcHGtGbokMwZlovvBXrz20iwSkg4H6wz4FRrQv8BYPfg6qLcKZVtKZNx4WqBWFQ7CYaa6IgK9p2zgU2LKX8i6Ay14cD4VxWZOvIReyP7owcCS5BEDEdtWSk4YjK@x@h7ZLFsyHLioG7gZRLsZ/qzO4X@kZf@LuPsLQWg14nUU2m9Wi@1Hn8YG3LO@HX2z@ZqW004z4fJOIpiVok7 "Ruby โ€“ Try It Online") does not. Similarly, while it works with Python's `re` module (see above), it exposed a bug in the the more powerful `regex` module: [Try it online!](https://tio.run/##NY/BasMwEETv/opF5LDr2sZySSh2RaC/YTkQWiVRUWQjqVQhzbe7lkv3NMzwZnenW7iM9nnW12l0AfzNF06dVSw@/Wg7cMIxxuYDxj3hIf7IN8JlJM9JNjktQu7o/vKIuBdyuyHKI92bh@SLt5kXtOdtyYcOtKiz0@jAgLZpS@XDh7ZtBkaYyk9GB2Qlowz0CYyyaOi1acH0fBCmr4cMEmwT7I72rFDbgCmg4k/xgZ44LX2pYP2guh7D@wVdASyy3K5ZCnULk0sQrYbg3f8941eovp0OCn1waInmutw29S8 "Python 3 โ€“ Try It Online") ย ย  [This bug has [now been fixed!](https://bitbucket.org/mrabarnett/mrab-regex/commits/1e6986b92f978087eb34ca79732d3b0c45be8652)] It also exposes a bug in older versions of Boost, as stated above โ€“ throwing an error on `480`, `512`, `584`, and many other larger numbers. In older versions of Notepad++ (using the older Boost versions), this is treated as a match. # Regex (ECMAScript+`(?*)` / PCRE2 v10.35+), ~~54~~ 47 bytes ``` ^(?*(x)|(x))((((\1*)\2*)\6{8}(?=\5$))+x|^x){2}$ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVJfa9swEIc95lNchailxE7sQEeZIvyybBRGW7y91a1wPTnx4shGVsCQ5JPspTD2obpPs7OzP6wPE5x8d7_f7-50-Ou3Zt08_XgVL2J0gFqQQGYEptBYvVJWN1WWa-bNpuNYqXVWOZXX26astE1ZykWazFrPBw-twKRa6Z5gnDauZUq9u_qwVIr7EHEsiYXFqDSlarVjpMmtnj5m-cZZvFRVbktHfCBBRLiAf2lW5zvblrX5P-3LCQoRGRW1ZbSUoaCVLHCsln389Pbqmgu-h7JgtLprna20QY8H0b2UJDWEI7ndPSKCaT_0g4j3et01Vf1ZMxIQH-kC9Xm9M67XLuYousMCeIf3YgQwdDa_YmoWcsDRm0w47JEAOACwM0Y3ctjyNnP5mlHrY99-5TpzzOs8nxqOB6g-0aqsdUpbi-X5mZS3yfK9ur5RyyS5ScSfsnQDhwNqsFX_zJLrfF33bxOA64gE9DFQI45_J0HN-fmgGUDyBsj0RUu1bVeM922Oo-OLPwHz33euCC6fZw8sHrOOH9A4w5NGY57O0V7vL48slukF5XzSHR46vp8f6Un29PsTBhfz8BT8BA "PHP - Attempt This Online") - PCRE2 In this version, the two bases \$10\$ and \$2\$ are combined, by choosing between them using the initial `(x)|(x)`. Thanks to molecular lookbehind `(?*)`, this can be done without subtracting 1 from the number being tested: ``` ^ (?* (x) # \2 = 1 or unset (unset=0 due to ECMAScript NPCG behavior); B=10 | (x) # \3 = 1 - \2; B=2 ) # Assert tail is the sum of two powers of B ( # Alternative #1: Divide evenly by B as many times as possible, at least once # (meaning tail has to be initially divisible by B), then subtract 1. ( ((\1*)\2*)\6{8}(?=\5$) # assert tail % B == 0; tail /= B )+ x # tail -= 1 | # Alternative #2: Don't divide at all, and just subtract 1, but only if this is # the first thing we do. If this path is taken, only alternative #1 can next. ^x # assert tail == N; tail -= 1 ){2} # Loop the above exactly twice $ # Assert tail == 0 ``` When `\1`=1 and `\2`=0, `((\1*)\2*)\6{8}(?=\5$)` behaves like `(x*)\5{8}(?=\5$)`, dividing by \$10\$. When `\1`=0 and `\2`=1, `((\1*)\2*)\6{8}(?=\5$)` behaves like `(x*)(?=\5$)`, dividing by \$2\$. # Regex (ECMAScript 2018 / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 51 bytes ``` ((x)|(x))$(?<=^(x((?<=^\6)\7{8}(\3*(\2*)))+|x$){2}) ``` **[Try it online!](https://tio.run/##TZBPa8JAEMW/igRhZ4xZkpT@IXH11IMXD@2xaXFJ1jhl3aS7qwYSP7tNhYKHYQZ@M@895luepCsttT4yTaWuTsS5FW@qfu1aePeWTM2tPG@vAB0OY@EUVgvxBR3cevGExXP/coHiYQZFOkPEcOim2KcXvG6501QqSOZRgnN2YJhb9XMkq4BZJStNRjHk5Th7tTZe2Z0c13sy7dFnrW1K5Rx3viJzQd4YYLeLuRbLvhaau1aTBxaNurQDMKLmWpna73GZDgO5jdwAiVZa96cO9Uf8ifgP1D0wy2SVZH8Y/d4252BtTlJTNbHS1CqbBKHOd42FnBZC5RSGOBoGXcCtasfwQMgP0pd7sIj9XfDm6PnZklcAbsUKwzLGMCTMnUjyy/iiOHpM418 "JavaScript (Node.js) โ€“ Try It Online") - ECMAScript 2018 (Node v11.6.0, with bug workaround) [Attempt This Online!](https://ato.pxeger.com/run?1=TZDBboJAEIbTF2mMMdkZkQ1g2hpw9dSDFw_tsbSRwIKb0IXuLpUEeJJePNR36Ku0T1PUmHiYzEy--Wf-zNe3LBK-_9HMCRR74tljXcKzUUJmVEW7zaEyqT37nQLU2PaBI1jO2RvUcMrhPYYPzayDcDqG0BsjotXWI2y8Ds_Sv5vbDdW5iDm4E9tFDBT_qITiQBSPklxITpDGfW34Shqu0qgfbYQsK-OXqoi51lSbRMgOaSGBnBSTnC2ajOVUl7kwQGyCgUgBJMtozmVmtrjw2lbodbQGwcpI6eN2yF6cV8QL4NdALtyl6x8xmq0qdsOV_IxykQxUJDPuD4ZWHqSFgkDMGQ-EZWF_cFgPqeJlbx4E0vfIxFtQiM2V8aIydKeE4QB6SUJJfELQEhho5gbd5U37g2Pfec65-Qc "JavaScript (Node.js) - Attempt This Online") - ECMAScript 2018 (Node v17.3.0+, bug fixed)** [Attempt This Online!](https://ato.pxeger.com/run?1=NY9NboMwEIX3nGJkZTFDAAFR2whi9SBApag1iSvXINtRiZKcpJts0lt00WP0NsUkWYzm5-l7M_P13e_dttPnH_nRd8aB3dvIiI0Yonfb6RIMN4yxy8618fJvgTjQcQya4fOKv-CAU64fqX46LE9YL0Ks85CI5sdhRof8RDf0d3SpsiLOmhIkT4O2M6BAar8wse5N6iIAxVVieyUdsphRALIFJTQqWuUFqCpruKrSJgAPaw-btd4IlNqhFyi6VllD84xGP28wPZNYsTavWzQRsIGFehK9KgvojadoGvCsvB_U7VzyaaQTaJ1BTbdHzpc0fsjTa_MP "Python - Attempt This Online") - Python `import regex` [Try it online!](https://tio.run/##RY/vaoQwEMRfRWTBXW0Oz9I/nA096Oc@gVoINlcDaSIxh3Jent3qldIPy/AbhmGnt6N0Qye1XsDxyskvOTWHg5EjHpMFcaLregT4@sI/cMKb1o9UP83PAev7FOsiJaLsOgHNRaAlOd7Fb/a7V1p@xlTCheflyTop2g5BR8pEoEx/9jSD4KDZ0GvlYxaX6oQgdq09G8@0j4otkHEQVd6EtQDB8EoZ39ycEgzT8o/3G2cZzVuH270L33ZywGRKUjD0a19oHp3yknV28GF9a1/@c8SMXTdrZWQEJoSw5OyhyH8A "PowerShell โ€“ Try It Online") - .NET This is a port of the ECMAScript+`(?*)` version to variable-length right-to-left-evaluated positive lookbehind `(?<=)`. It starts 1 off from the end, reaches the end by capturing a determination of whether to work in base \$10\$ or \$2\$, then does the rest of its work going backwards. It [**exposed a bug**](https://chat.stackexchange.com/transcript/message/57527758#57527758) present in the ECMAScript 2018 regex engine of both SpiderMonkey (Firefox) and V8 (Chrome / Node). To make this regex work, the **m**ultiline flag must be enabled. [It fails to work without the flag.](https://tio.run/##TZBPa8JAEMW/igRhZ4xZkpT@IevqqQcvHtpj0@KSrHFKukl3Vw3EfHYbhYKH4Q385s085lsdlSsstT4yTakvTsbCyjddvXYtvHtLpuJWnbYXgA7PY@EUVgv5BR3cNH/C/Ll/GSB/mEGezhAxPHdT7NMBL1vuaio0JPMoQRRW/x7IamBWq7ImoxnyYuy9Xhuv7U6Noz2Z9uCz1jaFdo47X5IZkDcG2M0xr@Wyr2TNXVuTBxYxFLQDMLLitTaV3@MyPZ/JbdQGSLbKuut2qD7iT8R/oO@BWSarJLti9HvbnIK1OaqayolVptLZJAhrsWssCFpILSgMcTwYdAG3uh3DAyH/Ub7Yg0Xs74I3B89PlrwGcCuWG5YxhiGhcDIRw/ieOHpM4z8 "JavaScript (Node.js) โ€“ Try It Online") pxeger [has reported the bug](https://bugs.chromium.org/p/v8/issues/detail?id=11616). It was since then fixed. ``` ( (x) # \2 = 1 or unset (unset=0 due to ECMAScript NPCG behavior); B=10 | (x) # \3 = 1 - \2; B=2 ) $ # head = N = input number # Assert head is the sum of two powers of B (?<= # Lookbehind - evaluated right-to-left ^ # Assert head == 0 ( # Alternative #1: Divide evenly by B as many times as possible, at least once # (meaning head has to be initially divisible by B), then subtract 1. x # head -= 1 ( (?<=^\6)\7{8}(\3*(\2*)) # assert head % B == 0; head /= B )+ | # Alternative #2: Don't divide at all, and just subtract 1, but only if this is # the first thing we do. If this path is taken, only alternative #1 can next. x$ # assert head == N; head -= 1 ){2} # Loop the above exactly twice ) ``` # Regex (Perl / PCRE / Boost / Python / Ruby / .NET), ~~51~~ 39 bytes ``` ^()?(((x*)(?(1)\4{8})(?=\4$))+x|^x){2}$ ``` [Try it online!](https://tio.run/##RU5BasMwEPzKEkSsrW1smQRKZcUOpNeeeqsTkZYYBGriSi6oqOrXXcUN9LLMzM7uzHAyej29fwExHLy@vB01kIJHKurd9nm7CdBfDCVWlLzecPSg@sjQD0adR1h05wUP0GphB61GmuRJZj9f7RhPZJazjOHp42pq/tUy6vhAJPLrLxsTj6bVdYW@1S9sL@Is9/yWq26UqFrM64jSFL3qgdLEJeAgmhBB/EBBTIGe2OVyLjd3i8UZ/@tKFA8hSPn4tJNyOlBsKKXuDmlDGXYrfx8iFN2KIKbu@@DQV4FMU5mvq/IX "Perl 5 โ€“ Try It Online") - Perl [Try it online!](https://tio.run/##XVBNa8JAEL37K5ZlITMaNQnaVtbgpS0USg9tb0aXmK4mNG6WzQoB62@3E@mphx3efLz3ZseW9rpc2dIy4VjK@JSzCbNOH5TTts4LDcF0MlwpVea1V0VztFWtXQYZyux92gYhC@jtqagOuh8wXhvfglLPL69PSmHIYiRJEpaDylSq1R64LZye7PLi2zsKqq6Olech47NkMVvc3SeLOUc52DcORJVGUtTpntRb@Ph8fHlDiWdW7UHU69a7WhtCOI43acozw5GG29OOOlQOo3AcY8/Xna2bLw18zEMal8QvmpPxPXeZEGlNAhSjjRwwdnM2f7kwy/TWJzQaIVkzuF3omPuiBOFCMuvPpXMPQReEwiAiO/crVqiLsun3koy@EkvW50wYeSGby7@zAsrrFnAFAN0QYQUxZrPzw4Vgms0E4qj72XZ4Ti7ieo3G8yT6BQ "PHP โ€“ Try It Online") - PCRE [Try it online!](https://tio.run/##dVNdb9owFH3nV9yxqtgkaUmLqikhRZq0PzDtYROlUWpMYg2cyHFEgPHXx66dkjEW/JDY9@Pce861WVF4KWPHj0KyVbXgMHnL81LfK57y@i4riufepYvXjBda5PJ@IZJUokmwWMhlrtaJMTdZLEsUxMVsDhF87X/ebH6@PVY/ttvv37KnTUaOr4ROCSH1kJIp8enLeP/pgNvoZXxDqVP/eq3p/uFwc6SXqX0XhkUUF44fnrUmsA3Fk/VzT0gN60RIQmHfA1zFDF0rLklBPX8ejUKoMObxIdaQm5NJSM2m1IsgwFghUzQWlQ5tPstlqcFyDwKrCyiOYOHJViJvlsEmS94zUAogBnYXjVzY8RY85XolJCf2wIR0mzo0PPVqlkmUI5Qt0bkgNuCOxdgXodQF6btQ5CW6G89SyAUZeAMatgDSR6@J@RCdcwoCaYzTDlxwbLwDPoUAi//FsmMcmnKSb5rTTPqOPw9hzdcl16R0YVAPTGOoSIlOI3Gb30ohImm0nkTSD8FxxDljs7TaXlisFksg58rHJU8Uywg540VvTVVPzF07AhenQ2kH1glvRwGpGypk8CJROByTH3aGN3PKKw2TCYj/Yw696ydmLwX55/a0TwduuVL0CuHuBi@aMZ9@AF@UylU/7MbhFJYGycK4BsBUDc2NbPHQco7XN//3brufN7EYV4g3u@aruK6UBLwMh@PIexqPfrPlKknLo7eyBWI70T8 "C++ (gcc) โ€“ Try It Online") - Boost [Try it online!](https://tio.run/##NY7RasMwDEXf8xXC9EFqkxBnHYxkph@SplA2t/XwlCB7LKXrt2dxx94uOvdcNF7jZeCn2X2Og0QI15CLzT/CwC2IEaXUfEDaIeK0Jtyhpv329nJfotlvV0Sb6ecw0a2@r@al2@mm0H0LzlTZaRDw4DhtliG@O24y8MaXYfQuoioUZeBO4C2jp9e6Ad/p3viu6jNIMidZjny26DhiApT/Jd3TRtOylwbElsEe5e2CkoOa1JofJCHXwChJocfB6Pb/m@Erlt/iosUQBZlorornuvoF "Python 3 โ€“ Try It Online") - Python [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BbsIwEEX3OcXIQuoMJFEcUQkltThICBJqHXDlOpFt1CDKSbphQ2_RRY_R2zRO6G5m_rw_8z-_upM_tOb6rd661npwJxdbuZd9_OpaU4IVljF2O_omWf0-bJHWiNjPCdfIabM8ry5DKTbLGdGi_9j2dM4vs_v6z0BWvEh4XYISWdS0FjQoE46kzr8oU0SghU5dp5VHljCKQDWgpUFNT3kBuuK10FVWRxBgE2C7M3uJyngMAsVTxWtacBr8gsEYIHVyZ58PaGNgPZubUQyqKqCzgaJxIHj5_1B79Om7VV6i8xYN0RTkesuSxzybmj8 "Python - Attempt This Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`) [Try it online!](https://tio.run/##PY7BasMwDIbvewotFCp1xDihg4FnSqG77jB2S1qzUTc1GDc4LvXoulfP7LL1ICH9@j9J/vj5NXqQ8KY7HXvm9AlWy/cl8/pjK8BILuC0N1aDlZ0Owx2A2YFtymotZdG6QqSBbThjZb0WoN02OZLCht6agNNySn8Is9p1YY/0XCemSXzCbsju4MGBcZBFFg7KYMWJsWy8tcl33YVFLGaOQP6AF1kw9/nP/hiG6778d5V6b1wA938i5xxKvbyulBo3SAtEjDPCBVbUzs9Pl1TKdj4heojfm0jn@jIZR14@1vwX "Ruby โ€“ Try It Online") - Ruby [Try it online!](https://tio.run/##RY/haoNAEIRfRWTBvdgLKimUyJFAf/cJjAGxm3pw3ZPzghJ7z261pfTffMMwzPR2JDd0ZMwCTlWOPmiqj0emEc/JckVxQsRpJ/CEubgc5pewSnU5gBDp9HWdxFwEWJLzU/xqP3tt6D0WJTxUVt6so6btEEykOQLN/d2LGRoFRg690T6WcalvCM2@tXf20vio2AKpgqbK6rAWILCqNPv6xymBpaE/zjdOUzFvHW7/1vi2owGTKdkBi1/7IebRaU@ys4MP66y8/OdIsl1/Gs0UAYcQlkw@F9k3 "PowerShell โ€“ Try It Online") - .NET This version takes advantage of a conditional group `(?(1)\4{8})` to determine whether to work in base \$10\$ or \$2\$. ``` ^ ()? # \1 = choose between B=10 (if set) or B=2 (if unset) # Assert tail is the sum of two powers of B ( # Alternative #1: Divide evenly by B as many times as possible, at least once # (meaning tail has to be initially divisible by B), then subtract 1. ( (x*)(?(1)\4{8})(?=\4$) # assert tail % B == 0; tail /= B )+ x # tail -= 1 | # Alternative #2: Don't divide at all, and just subtract 1, but only if this is # the first thing we do. If this path is taken, only alternative #1 can next. ^x # assert tail == N; tail -= 1 ){2} # Loop the above exactly twice $ # Assert tail == 0 ``` # Regex (Perl / PCRE / Java / Boost / Python / Ruby / .NET), 44 bytes ``` ^()?(((x*)(\1\4{8}|(?!\1))(?=\4$))+x|^x){2}$ ``` **[Try it online! - Java](https://tio.run/##bVLbbtswDH3vV7BGh1C5uEnRAcNUI9iGDRiwbkP7mKSAYsuJUln2JLlxm@bbM8rxLgXqF5rk0aHOETfiQYw22f1BFVVpPWwoj1UZ9zn8X6m90q/WrFzJhjonVb3UKoVUC@fgWigDO@hqzgtP4aFUGRTUwVtvlVmBsCs3WzDwa1tuHXxuUll5VdLJE4AvSkvIEyO37S9GcVpmMqZ@xPjHOs@lldmNFJm0sGxhL4v452SX5ozxbq4ber5dB35ElyxJg8i@KSORsdPE1FozlaOL5a9aaIfReb/fjxjbvYQeGRD9qwQ7YvB/GYjgnBiWhLvnbpD05qYXouf7Y23/U3gvrQGbdH@ktqjCAMc4ubEsSy2FgackJ0bJ4TYVxpB0ZaraQwJBbVfD20fnZRErwzh0OltYvBbuu2w8XbO1GKAzRNPdieMIMoToJHb92QI0tQMqdpVWHqMRPQLhPZgxdb4aT2tg40pYJylBPRsv2BDM5NVmrKVZ@fXVBUwhIOE9hcmCGNO1sLNF0@lpMzNZcPhgrXh0ca60xmbYa3qtKQB5aYM2ukZixhzMVWImFAYDEngtfLomhwpis3FxzLDdXEML/onIjxsTb62osBuRltXjj/xGmJWkSeOhYSwozQELGm8y8i687RPrTC7Jsa1VXmJ4VMafEm/r8D7/2hV56HOM3riILGF8H76TsFWHO2RTRGz6DOeT@eXu3f4Zp6fzCWM4TeaXZ4wNmue7hu0u9meHsEWH8ejtxfg3 "Java (JDK) โ€“ Try It Online")** / [Perl](https://tio.run/##RY5fa8IwFMW/yp0Em7u2tCkKsjS2gnvd095WDU4sBDLtkg46YvbVu9gJe7ncc@6f8@tORi/Hj28ghoPTl@NBA8l4kKLcbl43aw/txVBiRc7LNUcHqg0KXWfUuYdZc55xD7UWttOqp1EaJfbr3fbhRCYpSxiePm9L1b@bBx@fiER@@2VD4sHUuizQ1fqN7USo@Y7fc9VdElWKaRy6OEanWqA0GiIYICwhgviBjJgMHbHz@QQ3sQVwxv9YieLeeymfX7ZSjnuKFaV0eETasGbhVv5Kq4eGIdJKNAuCGA/X/YCu8GQc83RZ5L8 "Perl 5 โ€“ Try It Online") / [PCRE](https://tio.run/##XVDLasMwELznK1Qh8G7iJLZJH0ExvrSFQumh7S1OhesqtakjC1kBQ5JvT9ehpx607GtmVmMre15ltrJMOJYyPudsxqzT38pp2xSlhmA@G2dKVUXjVdnubN1ol0OOMn@dd0HIAnpbaqpvPSwYr43vQKnHp@cHpTBkMRIlEctRbWrVaQ/clk7PPovyxzsKqql3tech44tkuVje3CbLa45ytG0diDqNpGjSLbF38PZ@//SCEg@s3oJo1p13jTaU4TTepCnPDUda7vafNKF2GIXTGAe87m3TfmngUx7SuiR82e6NH7CrhEBrIqAYbeSIsYuy@auFWaWXOWWTCZI0g4tDu8KXFQgXkthgly48BH0QCoOI7DCcWKMuq3a4SzL6SizZUDNh5IlkTv9sBZTnD8AMAPoxQh7ni8Pd6QjZVR4jQpbmC4E46Y8fPR6Skzifo@l1Ev0C "PHP โ€“ Try It Online") / [Boost](https://tio.run/##dVNtb9owEP7Or7iyqtgkaUmLqikhRZq0PzDtwyagUWpMYg0cy3FEgPLXx2ynZBkL/pD43p67e@5MhPBSQk6fGCfrcklh8pbnhXqQNKXVfSbES@/SRCtChWI5f1iyJOVaxUjM@CqXm8So6yiSJRJiMVtABN/6X7bbX29P5c/d7sf37HmbodMrwlOEUDXEaO7Px4fPx3c0vZn7GKNpNB/fYuxU768VPjweb0/4Mr7vwlBEsXD8sFUf07VImmxeeowr2CSMIwyHHugjZtq0phwJ7PmLaBRCqX2eHmMFuZFMQGouhVoGgfZlPNVKUarQxpOcFwosAUFgyQFJNVh41hW6eZLBNks@IjQfgAzsPhq5sKcNeErVmnGKrEAYd@s8ODzXao4J5CPNXaJyhqzDPYl1XQhjF7jvgsgLba4tK8aXaOANcNgAcF9bjc9N1O4pCLhRTjtwwbH@DvgYAp38L5ad5dCk43RbSzPuO/4ihA3dFFShwoVBNTCFaUYKbTQUN/ENFSzihutJxP0QHIe1OzZHyd2FxnKxAtRmPi5oIkmGUKsvfGeyemzh2hG4ejoYd2Cd8fYYdOumFTSYc02cHpMfdrrXc8pLBZMJsP99jr3rErFLgf7Znub9wB2VEl9puLvAi2LMpx/AVylz2Q@7cSiGlUGyMK4BMFlDs5ENnta08frm/1Ft9xtHFuNK4/Wt/kqqSslBL8PxNPKex6PfZLVO0uLkrW2C2E70Dw "C++ (gcc) โ€“ Try It Online") / [Python](https://tio.run/##NY5BasMwEEX3PsVUZDGT2MZyUih2hQ9iOxBapVFRJTNSqUOSs7tRSnfDf7zHTOd48m67mK/Jc4RwDjnr/DN41wIrFkIse6QOEec14SCH3eXldsXuaZBE2KlhtyLazNf9TJf6tlruQi@bQo4tGFVlR89gwbgULkN8N67JwCpbhsmaiKIQlIE5gtUOLb3WDdhejsr21ZhBkl2S@eA@NBoXMQHK/y450kbSvZcCrMugD/x2Qs5BzGLtHiQh08DESaHHoGT7/43/juUPm6gxREZHtFTFc139Ag "Python 3 โ€“ Try It Online") / [Ruby](https://tio.run/##PY5Ba8MwDIXv@xVqKFTqiLFDB4PMhEJ33WHsFrdho25qMG5wXJrRdn89s8vWgwR6et@T/PHre/Qg4V23euiY0ydYLT@WzOvPbQlG8hJOe2M1WNnq0D8AmB3YOhdrKTPlsjIubM0Zy4t1CdptoyMqrO@sCTjLZ/SHMKtdG/ZIL0Vk6shH7I7sDh4cGAdJZOHQGBScGEvG@xh9tyzMhmzuCOQP@DIJZpL@7I6hv@Wlv0WcvXEB3P@J1FM1zevbqmnGDVKFiMOcUAm1OD9fL1hNlCDCSqrFlOhxuGwGOhfX6Tjy/Kngvw "Ruby โ€“ Try It Online") / [.NET](https://tio.run/##RY/haoMwFIVfxckF761NUelgVIKF/d4TqAVx6QykicQUpTbP7nRj7Od3OHyc05tR2KETSi1geWnFl5jq00mLEc/RckEqEHHaEVZpdZzf/BOLlyolwoJXRyCKp@dlojnzsETnffhubr1U4jOkHB48ya/GiqbtEFQgdQBS93dHMzQcFBt6JV3IwlxeEZpDa@7aMeWCbCvEHJoyqf0qQNC8lNrVP0kOminxx@nGcUzz5rCHj8a1nRgwmqIdaPqNHzSPVjrBOjM4v85K838OmDbrWSW1CEB775eEvWbJNw "PowerShell โ€“ Try It Online") ``` ^(()|())(((x*)(\2\6{8}|\3)(?=\6$))+x|^x){2}$ ``` **[Try it online! - Java](https://tio.run/##bVLvb9owEP3ev@IWdeIMNAWmVdPcqNqmTZq0blP7EahkEgdMHSeznZKW8rezc8h@VCJfLnf3/M7v@dbiQZyts/u9KqrSelhTHqsy7nP4v1J7pY/WrFzKhjonVb3QKoVUC@fgWigDW@hqzgtP4aFUGRTUwVtvlVmCsEs3nTPwK1tuHHxuUll5VdLJE4AvSkvIEyM37S9GcVpmMqZ@xPjHOs@lldmNFJm0sGhhL4v452SX5ozxbq4ber5ZBX5ElyxIg8i@KSORsVeJqbVmKkcXy1@10A6j836/HzG2fQk9MCD6owRbYvB/GYjgnBgWhLvnbpD0ZqYXoue7Q233U3gvrQGbdH@ktqjCAMc4ubEoSy2FgackJ0bJ4TYVxpB0ZaraQwJBbVfD20fnZRErwzh0OltYvBLuu2w8XbO1GKAzRNPdieMAMoToJHb96Rw0tQMqdpVWHqMzegTCezAj6nw1ntbAxpWwTlKCejqasyGY8dFmrKVZ@tXlBK4gIOE9hfGcGNOVsNN50@lpMzOec/hgrXh0ca60xmbYa3qtKQB5aYM2ukZiRhzMZWLGFAYDEngtfLoihwpis3FxyLDdXEML/onIDxsTb6yosBuRltXjj/xGmKWkSaOhYSwozQELGm8y8i687RPrTC7JsY1VXmJ4VMafEm/r8D7/2hV56HOMXruILGF8F76TsFX7O0T2TJSI2PQZziazi@273fPsDcOrZHZxytigeb5r2HayO92HLdqPzt5ORr8B "Java (JDK) โ€“ Try It Online")** / [Perl](https://tio.run/##RY7LasMwEEV/ZQginqlt/CgJpbISB9JtV93ViUhLDAI1cSUXXGT1110lDXQzzL3zuKc7Gr2YPr6BGQ5On98PGljGgxTVdvOyWXlozwaZFTmvVpwcqDYocp1Rpx5mzWnGPdRa2E6rHqM0SuzXm@3DiUzSIino@HlZWv@7efDpkUnil182JB5MrauSXK1fi50INd/xW666SaYqcR2HLo7JqRYQoyGCAcISEYgfyJjJyDE7n1/hrmwBvOB/rExx772UT89bKac9Io1IhIjDHWFTNkv34MfmnnAtmiUjiodxP5ArPZumPF2U@S8 "Perl 5 โ€“ Try It Online") / [PCRE](https://tio.run/##XVBNa8JAEL37K5ZlITMaNabWVtbgpS0IpYe2N9Muabqa0LhZNisE1N@eTqSnHnaYr/fe7LOF7VZrW1gmHEsYn3I2YdbpvXLaVlmuIZhOhmuliqzyKq8Ptqy0SyFFmb5OmyBkAb0dNdVe9wvGa@MbUOpp8/yoFIZshkRJxHJQmlI12gO3udOTryz/8Y6CqspD6XnI@DxezpeLu3h5y1EOdrUDUSaRFFWyI/YG3t4fNi8o8cTKHYhq23hXaUMZjmcfScJTw5GWm@MXTagdRuF4hj1et7aqvzXwMQ9pXRI@r4/G99hVTKAtEVCMPuSAsauy@auFWSXXOWWjEZI0g6tDh8znBQgXklhvl848BG0QCoOI7NSfWKLOi7q/SzL6ykyyvmbCyAvJXP7ZCii7TwA8AyIAtEOENE4Xp/vLOb1BWCfpQiCO2vNni6f4IrouGt/G0S8 "PHP โ€“ Try It Online") / [Boost](https://tio.run/##dVNtb9owEP7Or7ixqtgkaQlMaEpIK03aH5j2YRPQKDUmsQaO5TgiFPjrY7ZTsowFf0h8b8/dPXcmQngpIeePjJNNuaIwe83zQj1KmtLqIRPiqXdtohWhQrGcP65YknKtYiRmfJ3LbWLUdRTJEgmxmC8hgm/9L7vdr9dJ@XO///E9m@4ydH5BCB8RxgihaojRYryYHj6fjosJRs/RYnqHsVMdXyp8GJ/uzvg6vu/CUESxcPywVR/TtUiabJ96jCvYJowjDIce6CPm2rShHAns@ctoFEKpfSbjWEFuJBOQmkuhVkGgfRlPtVKUKrTxJOeFAktAEFhyQFINFl50hW6eZLDLkvcIzQcgA/sWjVx4ow14StWGcYqsQBh36zw4vNRqjgnkI81donKGrMMDiXVdmjIXuO@CyAttri1rxldo4A1w2ABwX1uNz4eo3VMQcKN87sAFx/o74GMIdPK/WHaWQ5OO010tzbnv@MsQtnRbUIUKFwbVwBSmGSm00VDcxDdUsIgbrmcR90NwHNbu2Bwl91cay8UaUJv5uKCJJBlCrb7wvcnqsaVrR@Dq6WDcgXXBe8OgWzetoMGCa@L0mPyw072eU14qmM2A/e9z6t2WiF0K9M/2NO8H7qmU@EbD3QVeFWM@/QC@SpnLftiNQzGsDZKFcQ2AyRqajWzwtKaN1zf/92q73ziyGDcar2/1V1JVSg56GU7nkTf9NPpN1pskLc7exiaI7UT/AA "C++ (gcc) โ€“ Try It Online") / [Python](https://tio.run/##NY5BasMwEEX3PsUgsphJbGM5NBQ7ogexHQit0qgokhmp1CHO2d0opbvhP95jxms8e7ddzGX0HCFcQ846/wretcCKhRDLAZFmJELEaU3Y1/3u9nqf@y3hm@p3K6LNNB8mutX31fIQOtkUcmjBqCo7eQYLxqVwGeKHcU0GVtkyjNZEFIWgDMwJrHZoaV83YDs5KNtVQwZJdknmo/vUaFzEBCj/u@RAG0mPXgqwLoM@8vsZOQcxibV7koRMAyMnhZ6Dku3/N/47lj9sosYQGR3RUhUvdfUL "Python 3 โ€“ Try It Online") / [Ruby](https://tio.run/##PY5Ba8MwDIXv@xVaKFTqiEk8VgaZGYXuusPYLWnNRt3UYNzguNSj6f56Zpe1Bwn09L4nucP3z@hAwIdqVeiYVUdYLj4XzKmvTQVaFBUcd9ooMKJVvr8D0FswdV6uhMgam1VxYeqCsZyvKlB2Ex1RYX1ntMdpPqV/hBllW79DeuGRqSMfsRuy3TuwoC0kkfm91FgWxFgy3sbou2RhFrKZJRC/4Kok6Pv0Z3fw/SUv/V3G2WnrwV5PpJ5Kyrf3pZTjGpEGJELEMCNseDM/PZ@H5pHwVTTzCdFDGNaBTvw8Gccif@LFHw "Ruby โ€“ Try It Online") / [.NET](https://tio.run/##RY/haoMwFIVfReSC99alWMfKqIQV9ntPoBbEpjOQJRJTlMY8u9ONsZ/f4fBxTm9GYYdOKLWA5aUVn2KqTyctRjwnywWRZiRCxGlHWOXV0b@GuXomfOPVEYjSab5M5PMAS3J@it/NVy@VuMZUwINnxc1Y0bQdgoqkjkDq/u7IQ8NBsaFX0sUsLuQNodm35q4dUy7Kt0LKoSmzOqwCBM1LqV39kxSgmRJ/fNg4TclvDrv/aFzbiQGTKdmBpt/4QX600gnWmcGFddah@OeIabOeVVKLCHQIYcnYS559Aw "PowerShell โ€“ Try It Online") These are ports of the 39 byte version, to a regex flavor that has no conditionals. In the first one, the `(?(1)\4{8})` conditional is replaced with `(\1\4{8}|(?!\1))` which behaves equivalently at a cost of 5 extra bytes. In the second the expression `(()|())` instead of `()?` is used to determine the mode (which either sets `\2` or `\3` leaving the other one unset), and the conditional is replaced with `(\2\6{8}|\3)`. The regex is otherwise unchanged (except for shifting the capture group numbering). [Answer] # [J](http://jsoftware.com/), 25 bytes ``` 0&<*10&#.inv+&(2=1#.*~)#: ``` [Try it online!](https://tio.run/##RU7LDoJADLzzFRNJgEXZtN2lPCInE0@e/AUjEQ9688ivY40Sm/Qxzcy092Xj8xFDjxw7EHrLyuNwPh0XyvYlU5b66fHaZoUMnPpydmm/uOR6uT0xgpl@sW5qiYHiFxVFOmPckMPkIbU6VD0Caig6MJkaLOAG3EIIEhECglVFJMQWalSFtmgELaFTU/HnqOnMIVgPZmB8jhGshjtJ/s/JOmrsljc "J โ€“ Try It Online") ### How it works ``` 0&<*10&#.inv+&(2=1#.*.~)#: 0&<* input is a positive number 10&#.inv list of digits base 10 #: list of digits base 2 +&( ) OR the result of both โ€ฆ *.~ square each digit (x>=2 will be larger than 2) 1#. sum 2= is equal to two ``` If there is a DecimalBinary number, the `+` as OR could result in 2, thus needing one byte more for `+.`. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` {$_|.base(2)~~/^10*10*$/} ``` [Try it online!](https://tio.run/##PYzdCsIwDIXv8xS5KKKOuaSto70Q38QxoQVh/rBejelevaYThJyQ851DXmEc2nyfcBPxhHlW3ftw7VPY6t2yNBemvYxqPjn1E54jVqrD@BxxuD1CygY8sAP2GrRzcNQksoYsMANT0bqYBBAVSyv5HfRHVCpiJJFXglvroWaozRc "Perl 6 โ€“ Try It Online") Checks if the input or the base 2 of the input matches the regex `^10*10*$` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ~~There's gotta be a way to shave at least one more byte off this.~~ I got there eventually! ``` รฌร-Bยฉaยขรฑ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=7M0tQqlhovE&input=Mw) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7M0tQqlhovE&footer=VmdX%2bSkrIiA9ICIrIVU&input=WwozLDksMTgsMTkyLDI4OCw1MjAsNTI0MzA0CjExLDEwMSwxMDAxLDEwMTAsMTEwMCwxMDAwMDAxLDExMDAwMDAwMDAsMTAwMDAwMDAxMAowLDEsMTEyLDIwMCw2NDksLTEsLTMKXS1tUg) ``` รฌร-Bยฉaยขรฑ :Implicit input of integer U รฌ :Convert to digit array ร :Sort (and implicitly convert back to integer) -B :Subtract 11 ยฉ :Logical AND with a :Absolute difference of B and ยข :Convert U to binary string รฑ :Sort :Implicit output of logical NOT of result ``` [Answer] # [Julia 1.3](http://julialang.org/), ~~61~~ ~~57~~ 50 bytes using a regex on the binary and decimal representation of the number ``` !x=count(r"^0*10*10*$",x)>0 ~x=!"$x"|!bitstring(x) ``` [Try it online!](https://tio.run/##RZFNa4NAEIbv/oqJycEtfuwmaUksBlropZQemkMPIYVVN2rYrKJraqHkr9tZbQjoOPO878zs4rGVBWddPwWepiKFQsGrQcD8hTWFXOuqCYMgK3Texn5SnoJBfuMqC44mC2JZxsEZ7T4N3l8@t/4pnSrx7ckirnn94x1aleiiVI31zBuBI1qlnYprLWoVhh8iE50Lja4LlYXhU4wZT/R2qB@hPIta8io6cNkIEkmhMp07SSmlSLQjeJKfuE7y67zroFvj/5cQ0k@6aFxe21/0jg3PzHY7sqHWpYsm9qyzfydxoccZTkd6LRrdQAQ7C2C3cGHtAlvhu567MF9hdj@nJiwXdLl3jYkxlOkQxsjQwLAYCB3hmNEbREzHfoOMwyww@sMSd3qIvIXBDF17yzqUNWR12Vbmfw2HxF4DTW7YICIDqPAuWirHKC7YEG3AduEy1ISgRajUutmIhXX/Bw "Julia 1.0 โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 13 bytes ``` โ„–โŸฆโปฮธ0โปโ˜๏ผฎยฒ0โŸง11 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5vxRIRvtm5pUWaxTqKCgZKGnqKEC4TonFqcElQGXpGp55BaUlfqW5SalFGkB5I02IylggZWiopKlp/f@/kYHBf92yHAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a two bit number, nothing if not. Port of @Kaddath's PHP answer. Explanation: ``` ฮธ Input as a string โป 0 Remove zeros ๏ผฎ Input as a number โ˜ ยฒ Convert to base 2 โป 0 Remove zeros โŸฆ โŸง Make into a list โ„– 11 Count occurances of literal string `11` ``` [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes ``` lambda n:n>2in{g(n,2),g(n,10)} g=lambda x,b:x and(x%b)**2+g(x//b,b) ``` [Try it online!](https://tio.run/##RY7RDoIwDEXf9xV9MWw64jbQKAn8CPLAgiCJDoKYYAjfji1ofFh3e@5t2vbd3xoXzGV8me/5wxY5uMglpnZjxZ00QtKnlZhYFX8Dg7TRALkr@LCxYrs1u4oP@72VVsz99dk/IYaUAaSBhLMEfcJ3NhLMCdXBKCphoMJMUkhrtNVS1qoxoLFZiFrhqtQfIlbrPCFK0ALyjyHu9BH5AQYyxsqmg6prXi3UDpb7IpwjSg3BxSUI0Ha163npjeRN4Ccwlpy0mDzBfr6YPw "Python 3 โ€“ Try It Online") Port of my Haskell answer. (I took the test harness from ovs's Python answer. Thanks!) [Answer] # [Perl 5](https://www.perl.org/) `-lp`, 35 bytes ``` $_=grep/^10*10*$/,$_,sprintf"%b",$_ ``` [Try it online!](https://tio.run/##PYzRCoMwDEXf8xnSvQyLN20d7cN@ZYLghiAaqt@/LnUg5IackxCZ8tKXYobnJ0/SvRh3LdO1Zmh3yfN6vJvb2CiW4ikRR@LkyMVIvYMmeARiJkbN2RgqgIo4zX/ApVBPFHSjr1Q/QiLLZP13k2Pe1r3YRX4 "Perl 5 โ€“ Try It Online") returns 1 or 2 (if a number can be decimal and binary Two Bit number) for true, 0 for false. [Answer] # [R](https://www.r-project.org/), ~~71~~ 64 bytes -7 bytes thanks to Dominic van Essen ``` `+`=function(n,k)sum((n%/%k^(0:n)%%k)^2)-2 n=scan();n<0|n+2&n+10 ``` [Try it online!](https://tio.run/##K/r/P0E7wTatNC@5JDM/TyNPJ1uzuDRXQyNPVV81O07DwCpPU1U1WzPOSFPXiCvPtjg5MU9D0zrPxqAmT9tILU/b0OC/ocV/AA "R โ€“ Try It Online") Output is reversed: gives `FALSE` if the input is a Two Bit Number, and `TRUE` if it is not. The helper function `+` converts an integer to a vector of digits in base `k` (we need `k=2` and `k=10`). Then sum the square of these digits. This sum is equal to 2 exactly for a Two Bit Number. Will fail due to memory limits for large input, in which case you can use `0:log2(n)` instead of `0:n` and `||` instead of `|`: [Try it online!](https://tio.run/##BcFBCoAgEAXQffcwZrBIXUXlVcQQirC@kLnz7vbe25qX3h4F4bsSCEPkXB4iiElER2q502kIzEJEdoZH08HmsIN4xaZqhTQ9pFZNz@0H "R โ€“ Try It Online"). [Answer] # Ruby 2.7, 44 bytes ``` ->n{[2,10].any?{n.to_s(_1).tr(?0,'')=='11'}} ``` **Explanation:** ``` ->n{ # a lambda with one argument [2,10].any?{ # Return true if for either of 2 or 10... n.to_s(_1) # input in that base .tr(?0,'') # after removing all 0-s =='11' # is exactly '11' } } ``` ## Equivalent in ruby < 2.7, 46 bytes ``` ->n{[2,10].any?{|b|n.to_s(b).tr(?0,'')=='11'}} ``` [Try it out](https://tio.run/##XZC7DoMgFIZ3n4JOaKLkHLRGBuuDENKUwcnYxstg1GenpAiaTv93/styhlkvpiW1yR79KnmKoNirX5p101vPpvdzjHXCpiFuIKU0qWuKSPfdfOZpJDIipJW5Sn8qDsXKg@AH8cp7dw6BihwKe7gu@hGcdEH0M7T2WYBLx53wF4ObWufWShdZwADIPXIIcVkIj1moZrmK7HO6rjFf) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` ^\d+ $*1ยถ$& +`^(1+)\1 $+0 m`^10*10*$ ``` [Try it online!](https://tio.run/##HYtBCgIxFEP3OUcdxikDSVulPYGXGEoHdOFCF@LZPIAXq79CEpIHed3e9@feD/Ol9bpdPdyi78dN8K3O8sdNcJ54tCouJtd7RIEyVAJCzjgFmlNkggRx@B@iAXJMDmLNgJ2MnVPBKqzxBw "Retina 0.8.2 โ€“ Try It Online") Link includes most test cases (the larger ones cause Retina to run out of memory). Explanation: ``` ^\d+ $*1ยถ$& ``` If the input is non-negative, prefix it with a unary copy. ``` +`^(1+)\1 $+0 ``` Begin converting the unary copy to binary. At this point there are too many zeros in the result, but fortunately they are irrelevant. ``` m`^10*10*$ ``` Match either number as being a two bit number. [Answer] # [Factor](https://factorcode.org/), ~~79~~ ~~74~~ 70 bytes -4 bytes thanks to chunes ``` : n ( n -- ? ) dup present swap >bin [ 48 swap remove "11"= ] bi@ or ; ``` [Try it online!](https://tio.run/##VU7LTsMwELz3K0Y9wcFV1jZukoqHuKBccimcEAenGDWCOMF2qFDFt6cbkJB62MeMZmb3ze5SH6anbVU/lHh3wbsPdDbtV4MN0QVE9zk6v3MRQ3DR@TTPlL6H0PK@WVR1iSqKtLdJ@LFrXBBWPB56cd8mUf8SUwmPCy4hcItLvI7Df1g82AE3TevxDJ3/weC6/sthSbS8xgua9g59wGY6QuEKBgUoAxFIgtagHDKD1FAKiruBzuYow1IDk2MtkWcoDLvYM1slJyieigNYT1qDDONC4of/8Hy04z9WWBzBNJsk38hgdAFBEOpcNp0A "Factor โ€“ Try It Online") [Answer] # [MUMPS](http://www.cs.uni.edu/%7Eokane/), 55 bytes ``` i $tr(n,01) f q:n<1 s %=n#2_%,n=n\2 w $tr(n_%,0)=11 ``` [Try it online!](https://tio.run/##jZI/D4IwEMV3PsVZNYGEJm1BA0YW4goTo4lBxaSJFPkX4qfHAgvDYejQ4ffeXd71mrf5p@6hAxJKlVZfSLqChrIBM4ksiNv8nlU1MbRhA0@QtZa1mkSmYyHQxyD3UOoLDAsPdR8Ew7HrMHdShotcsofM0/fqKThHs7EFvMC1sOBnf0qms1yoS9lstLhQdO1YeFc8CL4GPNjRRTdM0dZ0@CKlMSNKgxr2ASE9SNg1lals/T7wAihP6sxhVNVW3Pa2CtRVDF1HmwbMCjjvoex/ "MUMPS โ€“ Try It Online") * Each line has a leading space so that the commands aren't interpreted as line labels. * `$tr` is short for `$translate` which replaces one or more characters in a string with one or more other characters. For example, `$tr("abc","a","c")` evaluates to `"cbc"`. Omitting the third parameter is the same as passing the empty string, in which case the characters in the second parameter are removed. Therefore `$tr(n,01)` is nonempty only if it contains any characters other than 0 or 1, and `$tr(n,0)` removes all zeroes from the string. * `i` is short for `if`, its condition is the following `$tr(n,01)` expression. The condition is only met if `n` needs to be converted to binary. * `f` is short for `for` and loops until the `quit` condition (`q:n<0`) becomes true. The loop converts `n` to binary in `%`. * `w` is short for `write` and prints the expression that follows it. * If the `for` loop was executed then `n` will be empty or zero, otherwise `%` will be empty. `n_%` concatenates the two so that the result can be evaluated in a single expression. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ,Bแนขโ‚ฌแธŒ11e ``` [Try it online!](https://tio.run/##y0rNyan8/1/H6eHORY@a1jzc0WNomPr/cDuQDUT//0cb6yhY6igYWgCxpZGOgpEFkGVqZAAiTIwNTGJ1FKINDYGSBmACQhoCpQ2BHLCIAUQQwjJACAKFDUC6QQIgeZDhIFkzE6B9ukAhXeNYAA "Jelly โ€“ Try It Online") ## Explanation ``` ,Bแนขโ‚ฌแธŒ11e Main Link , Pair the integer with B Convert the integer to binary แนขโ‚ฌ Sort Each (sorts the digits of the integer implicitly) แธŒ Convert from decimal to integer 11e Is 11 in this list? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` !FreeQ[Tr/@(#~IntegerDigits~{10,2}^2),2]&&#>0& ``` [Try it online!](https://tio.run/##NYxBC8IwDIX/ijIYChlL0intQdlBBG8K3kRhjFJ72A61t7H99RqnBl7Il/eSrolP2zXRt01yu7Q8Bmsvt2so61U2nfponQ0H73x8TQMh8PjgNfA9z7M95ukcfB8XZe3KelBggDSQYWCtYcMoqhRWQASEIrknxBnwQzMifq1fwX@SiIA48k7WSrStDBQEhZJOY0pv "Wolfram Language (Mathematica) โ€“ Try It Online") *-1 byte from @att* [Answer] ## PCRE Regex, ~~100~~ 95 bytes ``` ^(((?(2)\2\2|.))*.)(?!\1)((?(3)\3\3|.))*.$|^(((?(5)\5{10}|.{9}))*.)(?!\4)((?(6)\6{10}|.{9}))*.$ ``` Assume unary input (no support for negative numbers). Should work in flavors with support for conditional regex and forward-declared back-reference. The regex consists of 2 similar portions, one check for binary and the other for decimal. * The code makes use of sum of geometric series to match 2n and 10n. 1 + (1 + 2 + 22 + ... + 2n) = 2n+1 * Then it try to decompose the number into sum of 2n + 2k (or 10n + 10k for decimal), and check that 2n != 2k Update: * Drops unused capturing group * Drops `$` in `(?!\1$)` since it's fine if we reject 2n < 2k [regex101](https://regex101.com/r/Eyz3Se/2) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~25~~ 24 bytes -1 byte thanks to ngn ``` {("11"~($x)^$0)+2=+/2\x} ``` [Try it online!](https://tio.run/##FYxLCsJAEAX3nuIRAkkIg9MfOzOCNxGX40LIOiB69fG56UdDVb3S/tx7b9f3PIgM33k8lseYl1Vv61nvx6e3yXBBoEIyRCAK2SAFmqEOMxhvwDO8IIgGomBTlIwatOj8VWXBuMYAeXGHBP@qpzZxSSmjGeEVSZAM/Qc "K (ngn/k) โ€“ Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes ``` #2ยงยคeแน^3แธ‹d ``` [Try it online!](https://tio.run/##yygtzv5/aElq7qOmxv/KRoeWA9kPdzbGGT/c0Z3y////aGMdSx1DCx1DSyMdIwsLHVMjAyA2MTYw0TE01DE0AGEwYWgAFDAwAHENwCIQhgFcCChoEPs/GsgFygENA0qYmVjq6Brq6BoDSQPDWAA "Husk โ€“ Try It Online") ### Explanation ``` ยง Apply to input the two functions d Convert to list of digits แธ‹ And convert to list of binary digits ยคe Then apply to both values แน^3 Cube each and sum #2 How many 2s are there in the list? ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~73~~ ~~63~~ ~~54~~ 52 bytes ``` n=>Seq(n+"",n.toBinaryString)find(_ matches "10*"*2) ``` [Try it online!](https://tio.run/##fY5NS8NAEIbv/RVDTkm1ZXcTpRFSUPTgRQ/1JiLbZNSVZhKz40cRf3sMFjTKjtfnmfd9x5d2Y/tm/Yglw9Vrc@L44rleY@cB3xip8nDctvA@ebEbsEdwTgzFEi5bdg1dr7hzdH8DRU/FcoVPMe1F0T7Neegh2213PrlzVMW3UFsuH9BDpNU0mpqkt95jx7GN02Tu/CkOd1glk2@ch7FeCDw3YWEWQuLAKElkqcp@udGOFvaVKGSjhQ/0EBLblFy4s@r/sPo7@3Pwxc/qlrfjVBBqE8JGBSsOszyEZ8HqWTqiH/0n "Scala โ€“ Try It Online") **Edit:** * Thanks to @Tomer Shetah for pointing out that lamdbas do not require their type definition (see comments), which reduces the length from 73 to 63 bytes * Thanks to @user for adding some nice syntax tricks that further reduce the length from 63 to 54 bytes * Again thanks to @user for the comment on using `find` instead of `exists`, which saves another 2 bytes and is valid for this challenge, since it is stated that a valid solution should *"output true or false (or some indicator of true or false)"* [Answer] # Generic regex, ~~58~~ 56 bytes ``` ^(((1+)(?=\3$))+1|^1){2}$|^(((1+)\6{8}(?=\6$))+1|^1){2}$ ``` [Try it online!](https://tio.run/##VYq9CsMgHMT3ew4DfysBTxvRofRFJDSQDl06lG6Jz261ZMlwH9zvPs/v673UQR55NVCXOosIjZb7LXulteE@U2@uqP0gOWyxdBxOuFaPBEYwObgYMTkLErRdf2MfrEWLVtqr9XBNGInR/wA "Retina 0.8.2 โ€“ Try It Online") Link includes test harness written in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) although the regex itself should work in most engines. Takes input in signed unary i.e. `^-?1*$`. Explanation: Given `k` and `m` we can write a specific test for a number being the sum of `k` distinct powers of `m` by repeatedly dividing by `m` and subtracting `1` `k` distinct times along the way, before we eventually reach zero: ``` ^(((1+)\3{<m-2>}(?=\3$))+1|^1){<k>}$ ``` where `<m-2>` and `<k>` represent substitutions for the specific values being tested (subject to trivial reductions such as `\3{0}` being a no-op). This works as follows: ``` (1+) Find `i` such that \4{<m-2>} `i+(m-2)i=(m-1)i` is equal to (?=\4$) `n-i`, therefore `i=n/m`. ( )+ Divide `n` by `m` at least once 1 Then decrement ( |^1) Or on the first loop just decrement {<k>} Decrement `k` distinct times ^ $ Consume entire input ``` The problem then reduces to an alternation of two such tests. Edit: Saved 2 bytes by noticing from @Deadcode's answer that `(((...)+|^)1)` is the same as `((...)+1|^1)`. [Answer] # [Perl 5](https://www.perl.org/), 45 bytes ``` sub($n){$_=sprintf"=$n=%b=",$n;s/0//g;/=11=/} ``` [Try it online!](https://tio.run/##TU/RisMgEHzvVyxiSkINapIebYNcf6B/cFDSnpZAMcE1T@V@/Tw1Dz3BYXZ2lt2ZtXvuAzUq4HIrqa1e9KpwdqP1hihqVXFThFHbIxecP3qupFT8J/Rw9hr9fUCNoKDcQHwtgyMDeYj/2DBoDpHtG5Gga0XHsknK2BYZVpTRIGORFbGKKxNvUSRbnk9ScqQFqf/RxZ11lOq26jfxYnplsAYAUkj5fYICvyxhQC2DcktNigmfQLxbNIETEDM8UZMKzOT@xQq/0@zHyWKoL0YPfnF6h@PDZoZ/ "Perl 5 โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 35 bytes ``` $_.=sprintf" %b",$_;$_=/\b10*10*\b/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXs@2uKAoM68kTUlBNUlJRyXeWiXeVj8mydBAC4hikvT//7f8l19QkpmfV/xft@C/rq@pnoGhAQA "Perl 5 โ€“ Try It Online") ]
[Question] [ It's a [normal truth machine](https://esolangs.org/wiki/Truth-machine) but instead of taking input, it uses the first character of the program. Thus, internal. The 0 and 1 are plain characters, i.e. ASCII code 0x30 and 0x31 respectively. Example: `0abcd` prints 0 and halts, and `1abcd` prints 1 infinitely. Then your submission is `abcd`, whose score is 4 bytes. The 0 or 1 (the first character of the program) is not counted towards your score. Of course, you're not allowed to look inside the file itself. Like a quine. ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 198288; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` or~print(0) while 1:print(1) ``` A full program, which if prefixed with `0` will print `0` then halt, exiting with an error, or if prefixed with `1` will print `1` forever. **[Try 0 online!](https://tio.run/##K6gsycjPM/7/30Ahv6iuoCgzr0TDQJOrPCMzJ1XB0AoiYKgJlE/MS9GosLI11MwvUkBTVwFVV6EJAA "Python 3 โ€“ Try It Online")** **[Try 1 online!](https://tio.run/##K6gsycjPM/7/31Ahv6iuoCgzr0TDQJOrPCMzJ1XB0AoiYKj5/79BYl6KRoWVraFmfpECmroKqLoKTQA "Python 3 โ€“ Try It Online")** The right of a logical `or` is only executed if the left is falsey (which `0` is, while `1` is not). If the prefix is `0` the argument, `print(0)`, of bitwise-not, `~`, is evaluated - this has a side-effect of printing `0` and returns `None` which is an invalid argument for `~` causing an error which halts the program. If the prefix is `1` the code `~print(0)` is not evaluated and the infinite loop of `while 1:print(1)` is reached. [Answer] ## [W](https://github.com/a-ee/w), 2 bytes You know, duplicate the first character and apply while. Simple enough. ``` :w ``` ## Explanation, applied the bits ``` 1: % The condition and the body is both 1 w % While the condition 1 is true, output 1 ``` ## Explanation 2 ``` 0: % The condition and the body is both 0 w % This while does not get executed % The condition 0 gets returned & printed ``` [Answer] # [R](https://www.r-project.org/), 20 bytes ``` ->a while(print(a))0 ``` [0Try it online!](https://tio.run/##K/r/30DXLpGrPCMzJ1WjoCgzr0QjUVPT4P9/AA "R โ€“ Try It Online") [1Try it online!](https://tio.run/##K/r/31DXLpGrPCMzJ1WjoCgzr0QjUVPT4P9/AA "R โ€“ Try It Online") Uses rightwards assignment `->`, which I now seem to use about [once](https://codegolf.stackexchange.com/a/191416/86301) [a](https://codegolf.stackexchange.com/a/196869/86301) [month](https://codegolf.stackexchange.com/a/197103/86301) on this site (and never anywhere else). [Answer] # x86-16 machine code, IBM PC DOS, 11 bytes **Binary:** (`0` example) ``` 00000000: 3002 ad8a d03c 30cd 2175 fcc3 0....<0.!u.. ``` (`1` example) ``` 00000000: 3102 ad8a d03c 30cd 2175 fcc3 1....<0.!u.. ``` **Unassembled listing:** ``` ?? 02 DB ?, 2 ; first byte is '1' or '0', second byte is DOS write char fnc AD LODSW ; load input from [SI] into AL, INT 21H function 2 in AH 8A D0 MOV DL, AL ; output to DL 3C 30 CMP AL, '0' ; is input 0? OUTPUT: CD 21 INT 21H ; write to console 75 FC JNZ OUTPUT ; if not a '0', keep looping forever C3 RET ; return to DOS (only if it was a 0) ``` **Explanation:** The first byte of the program is either a `'0'` or a `'1'`, and combined with a second byte of `2` (more on that later) decodes to a benign instruction of either `XOR [BP+SI], AL` or `XOR [BP+SI], AX`. In PC DOS, many registers are [initialized to known values](http://www.fysnet.net/yourhelp.htm), so we know that `AX` is `0`, and `SI` is `100H` which is the first byte of the program. Whatever memory address `[BP+SI]` translates to, it simply XOR's `0` to it, doing nothing. The `LODSW` instruction puts the input byte into the `AL` register and a `2` into the AH register, which is the DOS `INT 21H` API function number to write an ASCII char in `DL` to the console. The input is compared and `ZF` (zero flag) is set "true" if input is a `0`. The char is written to the console and if `ZF` is not zero, it will loop indefinitely. **Output of both variants:** [![enter image description here](https://i.stack.imgur.com/mp3w6.png)](https://i.stack.imgur.com/mp3w6.png) [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` !f=f 0 _!f=f 1*>0!f main=0!print ``` I think this is the only answer posted so far where the first character (the digit) isn't the entry point. Anyway, explanation: I'm creating an operator function called `!`, and defining it by cases. We enter the top case if the left operand matches the program's first digit, and the bottom case otherwise. The right operand is bound to `f` in both cases (and it happens to always be `print`). In the top case, we just print a 0. In the bottom case, we print a 1, and then recursively call ourself with the same operands. (We know the left operand will always be 0.) Finally, `main`, the entry point, calls our operator with `0` and `print`. [Try it online with 0!](https://tio.run/##y0gszk7Nyfn/30AxzTZNwYArHkwbatkBBbhyEzPzbA0UC4oy80r@/wcA "Haskell โ€“ Try It Online") [Try it online with 1!](https://tio.run/##y0gszk7Nyfn/31AxzTZNwYArHkwbatkZKKZx5SZm5tkaKBYUZeaV/P8PAA "Haskell โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` ยต=0 ``` [Try `0ยต=0` online!](https://tio.run/##yy9OTMpM/f/f4NBWW4P//wE "05AB1E โ€“ Try It Online") [Try `1ยต=0` online!](https://tio.run/##yy9OTMpM/f/f8NBWW4P//wE) Also 3 bytes: ``` i[, ``` [Try `0i[,` online!](https://tio.run/##yy9OTMpM/f/fIDNa5/9/AA "05AB1E โ€“ Try It Online") [Try `1i[,` online!](https://tio.run/##yy9OTMpM/f/fMDNa5/9/AA "05AB1E โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แน„แธทยฟ ``` **[Try 0 online!](https://tio.run/##y0rNyan8/9/g4c6Whzu2H9r//z8A "Jelly โ€“ Try It Online")** **[Try 1 online!](https://tio.run/##y0rNyan8/9/w4c6Whzu2H9r//z8A "Jelly โ€“ Try It Online")** ``` แน„แธทยฟ - Main Link: no arguments . - set Left to 0 or 1 ยฟ - while... แธท - ...condition: Left แน„ - ...do: print and yield (Left) - implicit print (Left) ``` [Answer] # Scratch 3.0, 10 blocks/80 bytes [![Program](https://i.stack.imgur.com/NkFDV.png)](https://i.stack.imgur.com/NkFDV.png) As SB Syntax: ``` //1 or 0 repeat until<(n)=[0 say[1 end say[0 define 0 set [n v]to[0 define 1 set[n v]to[1 ``` It's more of a snippet than a program, but it works. [Try it on~~line~~ Scratch!](https://scratch.mit.edu/projects/361363482/) [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~6~~ 5 bytes -1 thanks to Jo King! ``` :n?!; ``` **[Try 0 online!](https://tio.run/##S8sszvj/38Aqz17R@v9/AA "><> โ€“ Try It Online")** **[Try 1 online!](https://tio.run/##S8sszvj/39Aqz17R@v9/AA "><> โ€“ Try It Online")** ### How? Instruction pointer starts at the top left (i.e. 0 or 1) facing right. If the instruction pointer leaves the code it wraps around to the other side, continuing in the same direction. ``` X:n?!; - X=0 X=1 X - push X {0} {1} : - duplicate {0,0} {1,1} n - pop & print {0,} "0" {1} "1" ? - pop & if... {} {} ! - ...truthy: skip & wrap to X ; - ...falsey: exit ``` [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 5 bytes ``` " !"@ ``` **[Try 0 online!](https://tio.run/##y0lMqizKzCvJ@P/fQIlLUcnh/38A "Labyrinth โ€“ Try It Online")** **[Try 1 online!](https://tio.run/##y0lMqizKzCvJ@P/fUIlLUcnh/38A "Labyrinth โ€“ Try It Online")** ### How? Instruction pointer starts at the top left (i.e. `0` or `1`) facing right, the stack starts as infinite zeros. **0:** ``` 0" !"@ ``` ``` - stack = {0,0,0,...} (infinite supply of zeros) 0 - multiply top of stack by 10 and add 0 {0,0,0,...} - 2 neighbours, 0 -> go forward " - no-op {0,0,0,...} - 2 neighbours -> go forward " - no-op {0,0,0,...} - 3 neighbours T-junction from stem, 0 -> turn around " - no-op {0,0,0,...} - 2 neighbours -> go forward 0 - multiply top of stack by 10 and add 0 {0,0,0,...} - 2 neighbours -> go forward ! - pop top of stack, print as decimal "0" {0,0,0,...} - 2 neighbours -> go forward " - no-op {0,0,0,...} - 3 neighbours T-junction from side, 0 -> go forward @ - exit labyrinth ``` **1:** ``` 1" !"@ ``` ``` - stack = {0,0,0,...} (infinite supply of zeros) 1 - multiply top of stack by 10 and add 1 {1,0,0,...} - 2 neighbours -> go forward " - no-op {1,0,0,...} - 2 neighbours -> go forward " - no-op {1,0,0,...} - 3 neighbours T-junction from stem, 1 -> turn right ! - pop top of stack, print as decimal "1" {0,0,0,...} - 2 neighbours -> go forward 1 - multiply top of stack by 10 and add 1 {1,0,0,...} - ...etc. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 65 63 56 bytes Pyth's prefix operators don't really suit well to this challenge... ``` Ws@`$__import__("inspect").stack()[1][0].f_locals$_101 1 ``` Edit 1: Saved 2 bytes by letting Pyth do the dictionary index, and using `h` instead of `@<py_code>0` because I remembered it exists. Edit 2: Saved 7 bytes because @isaacg found an even sillier trick :) [Try it online!](https://tio.run/##K6gsyfj/3yC82CFBJT4@M7cgv6gkPl5DKTOvuCA1uURJU6@4JDE5W0Mz2jA22iBWLy0@Jz85MadYJd7QwJDL8P9/AA "Pyth โ€“ Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~12~~ 10 bytes ``` :?vn; n:< ``` -2 bytes thanks to @JonathanAllan ## Answer History ``` :?vn; >:n:< ``` [Try it online!](https://tio.run/##S8sszvj/X8HKvizPmsvOKs/K5v9/AA "><> โ€“ Try It Online") or [Try it with `1`](https://tio.run/##S8sszvj/31DByr4sz5rLzirPyub/fwA "><> โ€“ Try It Online") [Try it with `0`](https://tio.run/##S8sszvj/30DByr4sz5rLzirPyub/fwA "><> โ€“ Try It Online") ## Explained [![Gif showing execution path with 0](https://i.stack.imgur.com/vdAqX.gif)](https://i.stack.imgur.com/vdAqX.gif) [![Gif showing execution path with 0](https://i.stack.imgur.com/RD6tz.gif)](https://i.stack.imgur.com/RD6tz.gif) Path visualiser is <https://fishlanguage.com/> Gif converter is <https://www.onlineconverter.com/video-to-gif> [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytesSBCS ``` {โžโ†โบ}โฃโ‰ 1 ``` [0Try it online!](https://tio.run/##SyzI0U2pTMzJT///36D6Ue@8R20THvXuqn3Uu/hR5wLD//8B "APL (Dyalog Unicode) โ€“ Try It Online") [1Try it online!](https://tio.run/##SyzI0U2pTMzJT///37D6Ue@8R20THvXuqn3Uu/hR5wLD//8B) Prints to stderr. ### How they work ``` 0{โžโ†โบ}โฃโ‰ 1 {โžโ†โบ}โฃโ‰  โ Iterate {โžโ†โบ} until (next value)โ‰ (prev value) is true {โžโ†โบ} โ First iteration: print and return left arg (0) โ‰  โ (next value)=0, (prev value)=1, so 0โ‰ 1 is true โ Function terminates 1{โžโ†โบ}โฃโ‰ 1 {โžโ†โบ}โฃโ‰  โ Iterate {โžโ†โบ} until (next value)โ‰ (prev value) is true {โžโ†โบ} โ First iteration: print and return left arg (1) โ‰  โ (next value)=1, (prev value)=1, so 1โ‰ 1 is false {โžโ†โบ} โ Second and subsequent iterations: called with the same arg (1) โ Never terminates; prints 1 infinitely ``` [Answer] ## [Befunge-93](https://github.com/catseye/Befunge-93), 5 bytes ``` :_.@# ``` [Try 0 online](https://tio.run/##S0pNK81LT/3/38AqXs9B@f9/AA) [Try 1 online](https://tio.run/##S0pNK81LT/3/39AqXs9B@f9/AA) First submission, and I only started learning Funge yesterday, so it's very likely there's a shorter solution. I tried to find a way to remove the need for the ":" but I couldn't. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~14~~ 11 bytes ``` ,1...&say^1 ``` [0Try it online!](https://tio.run/##K0gtyjH7b/Bfx1BPT0@tOLEyzvD/fwA) [1Try it online!](https://tio.run/##K0gtyjH7b/hfx1BPT0@tOLEyzvD/fwA "Perl 6 โ€“ Try It Online") Abuses the range operator to loop infinitely and the XOR Junction (`^`) to print and to evaluate if the range should stop. [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` and exec('while 1:print(1)');print(0) ``` 0: [Try it online!](https://tio.run/##K6gsycjPM/7/3yAxL0UhtSI1WUO9PCMzJ1XB0KqgKDOvRMNQU13TGsI00Pz/HwA "Python 3 โ€“ Try It Online") 1: [Try it online!](https://tio.run/##K6gsycjPM/7/3zAxL0UhtSI1WUO9PCMzJ1XB0KqgKDOvRMNQU13TGsI00Pz/HwA "Python 3 โ€“ Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ร„oโ†‘ ``` [Try `0ร„oโ†‘` online.](https://tio.run/##y00syUjPz0n7/9/gcEv@o7aJ//8DAA) [Try `1ร„oโ†‘` online.](https://tio.run/##y00syUjPz0n7/9/wcEv@o7aJ//8DAA) **Explanation:** ``` 1 # Push 1 โ†‘ # While true without popping, ร„ # by using a single builtin as inner block: o # Print with trailing newline without popping 0 # Push 0 โ†‘ # While true without popping # (output the entire stack joined together implicitly as result) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 21 bytes ``` 0|?{$_}|%{for(){1}};0 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/37DGvlolvrZGtTotv0hDs9qwttba4P9/AA "PowerShell โ€“ Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 4 bytes ``` {:|โ‘ฃ ``` [Try it online!](https://tio.run/##y05N//@/2qrm0cTF////180oAgA "Keg โ€“ Try It Online") It seems I'm a bit late to the party! ยฏ\\_(ใƒ„)\_/ยฏ ~~Anyhow, this is simply a modification of the usual truth machine~~ This is literally the same truth machine as it would be if we didn't have to place the digit at the start. Funny how implicit input works. By this, I mean it doesn't matter if y'all place the digit at the start or you place it in input. (โŒโ– โ—กโ– ) [Answer] # JavaScript, 34 bytes ``` ?(_=>{for(;;)alert(1)})():alert(0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38n5iTWlRim5yfV5yfk6qXk5/@314j3tauOi2/SMPaWhMsrWGoWaupoWkF4Rho/v8PAA "JavaScript (SpiderMonkey) โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` 1๏ผทฮฃโŠŸ๏ผซ๏ผก๏ผค ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJUEnTmqs8IzMnVUEjuDRXIyC/QCMgNTXbMSdHQxMIFFxKcws0NK3///@vW5YDAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. ``` 0๏ผทฮฃโŠŸ๏ผซ๏ผก๏ผค ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJQEnTmqs8IzMnVUEjuDRXIyC/QCMgNTXbMSdHQxMIFFxKcws0NK3///@vW5YDAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: The leading `1` or `0` simply prints literally to the canvas. There then follows a `while` loop, the condition of which is the digital sum of the last character on the canvas. Thus if this is zero, the loop never gets off the ground, and the canvas gets implicitly output with the `0` still on it. However, if this is a non-zero digit, such as `1`, then the loop will dump a copy of the canvas for ever. (Note that the `dump` command has a rate limit on it, so that TIO will time out before the output reaches the size limit.) There are a few variants with the same byte count, such as using `Cast` rather than `Sum`, or `Maximum` or `Minimum` rather than `Pop`, or even by using `Count` or `Find` instead. [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 27 bytes ``` a->a+Out_b _+0a->a+b a+b->_ ``` [Try it online with 0!](https://tio.run/##S8xJzkjNzSwu@f/fIFHXLlHbv7QkPokrXhvCS@ICYl27@P//AQ "Alchemist โ€“ Try It Online") [Try it online with 1!](https://tio.run/##S8xJzkjNzSwu@f/fMFHXLlHbv7QkPokrXtsAzEviAmJdu/j//wE "Alchemist โ€“ Try It Online") This was a bit tricky. Every execution path up to the first application of the first line must be possible in both programs, and the two possible patterns in the first line are mutually exclusive. Hence, in order for the program to work, execution up to that point must be non-deterministic. This program swaps infinitely between two states until the first line is applied. ``` 0a->a+Out_b # the 0 version: from the initial state, add an a to halt and output 0 1a->a+Out_b # the 1 version: from the a+b state, output 1 and leave the state unchanged _+0a->a+b # From the initial state, move to the a+b state a+b->_ # From the a+b state, move to the initial state ``` A deterministic solution is possible by starting the first line with a two-digit number, but this is [14 bytes longer](https://tio.run/##S8xJzkjNzSwu@f/fMFE7WdcuiSte184QxOZK0jZIBApo@5eWxCcBeUAOmPn//3/dFAA "Alchemist โ€“ Try It Online"). [Answer] # [PHP](https://php.net/), 24 bytes ``` ?:die(0.);for(;;)echo 1; ``` Uses ternary condition knowing that in PHP one of the alternatives can be empty and i doesn't need to be assigned to a variable. 0: [Try it online!](https://tio.run/##K8go@G9jXwAkDeytUjJTNQz0NK3T8os0rK01U5Mz8hUMrf//BwA "PHP โ€“ Try It Online") 1: [Try it online!](https://tio.run/##K8go@G9jXwAkDe2tUjJTNQz0NK3T8os0rK01U5Mz8hUMrf//BwA "PHP โ€“ Try It Online") Edit: had to add `'0'` to properly echo zero Edit2: Had forgotten that `die` was synonym of `exit` (thanks manual) Edit3: saved 1 byte with `for(;;)` instead of `while(1)` Edit4: saved 1 byte with `die(0.)` instead of `die('0')` thanks to @Christoph [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 5 bytes ``` ^O?@u ``` 0 [Try it online!](https://tio.run/##Sy5Nyqz4/98gzt/eofT/fwA "Cubix โ€“ Try It Online") 1 [Try it online!](https://tio.run/##Sy5Nyqz4/98wzt/eofT/fwA "Cubix โ€“ Try It Online") Maps onto the cube like ``` 0 ^ O ? @ u ``` * `^` Redirect up onto the top face * `0` or `1` pushed to the stack * `?` test + `uO?@` if `0` then u-turn onto the integer output pass through the test again and halt + `O^` if `1` output the integer and redirect up again [Answer] # [Turing Machine Code](http://morphett.info/turing/turing.html), ~~29~~ bytes or 28 bytes With the strange rule that the leading '0' or '1' doesn't count towards the byte count. ``` 0 0 1 * 1 * _ 0 * 1 * 1 1 r 1 ``` [Try '0' online!](http://morphett.info/turing/turing.html?e5750226d485c40676e8bfce2a18ffab) ``` 1 0 1 * 1 * _ 0 * 1 * 1 1 r 1 ``` [Try '1' online!](http://morphett.info/turing/turing.html?bc348194dbef0b4ddae4c81dbfff4544) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~16~~ 15 bytes *-1 byte thanks to Jo King* ``` &&1 xx*X[&put]$ ``` [Try0 it online!](https://tio.run/##K0gtyjH7/99ATc1QoaJCKyJaraC0JFbl/38A "Perl 6 โ€“ Try It Online") [Try1 it online!](https://tio.run/##K0gtyjH7/99QTc1QoaJCKyJaraC0JFbl/38A "Perl 6 โ€“ Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~15~~ 9 bytes ``` ?\0n; n1< ``` [Try it online!](https://tio.run/##S8sszvj/3z7GIM@aK8/Q5v9/AA "><> โ€“ Try It Online") * -6 bytes thanks to JoKing My first fish program~~, doesn't beat the other one but I wanted to post it anyway.~~ Beats the other one now! ### Explanation: For 0: `0?` skip the next command `0` push `0` to the stack `n` output the top of the stack `;` terminate For 1: `1?` don't skip the next command (no-op) `\` mirror down `>` switch direction to forward `1` push `1` to the stack `n` output, then wrap round [Answer] # [Python 3](https://docs.python.org/3/), 38 bytes ``` 0 or print(0)or exit() while 1:print(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/30Ahv0ihoCgzr0TDQBPITK3ILNHQ5CrPyMxJVTC0gsgYav7/DwA "Python 3 โ€“ Try It Online") ``` 1 or print(0)or exit() while 1:print(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/31Ahv0ihoCgzr0TDQBPITK3ILNHQ5CrPyMxJVTC0gsgYav7/DwA "Python 3 โ€“ Try It Online") --- If output to STDERR is allowed (30 bytes): ``` 0 or exit('0') while 1:print(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/30Ahv0ghtSKzREPdQF2TqzwjMydVwdCqoCgzr0TDUPP/fwA "Python 3 โ€“ Try It Online") --- If output as exit code is allowed (28 bytes): ``` 0 or exit(0) while 1:print(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/30Ahv0ghtSKzRMNAk6s8IzMnVcHQqqAoM69Ew1Dz/38A "Python 3 โ€“ Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 17 bytes ``` >0?loop{p 1}:p(0) ``` [Try it online!](https://tio.run/##KypNqvyfnJ@Saquurv7fzsA@Jz@/oLpAwbDWqkDDQPM/UJQrtSwxR8HeQBukTK@4pCizACpkiCT0HwA "Ruby โ€“ Try It Online") [Answer] # TI-BASIC, 10 bytes ``` Repeat not(Ans:Disp Ans:End:" ``` Add either `0:` or `1:` to the beginning of the code to get the desired output. Output is either just 0 or an infinite amount of 1s. `Repeat` loops until its condition is true and ignores the condition for the first loop. Thus, `not(Ans` will be 1 if `0:` is added and 0 if `1:` is added. An empty string is added to the end of the program to prevent it from printing `Done`. **Examples:** prgmA: `0:Repeat not(Ans:Disp Ans:End:"` prgmB: `1:Repeat not(Ans:Disp Ans:End:"` ``` prgmA 0 prgmB 1 1 1 1 1 1 1 ``` **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. ]
[Question] [ The task is to display *n* characters of the [ASCII table](http://www.asciitable.com/). You may write a function (or a program that takes the argument as a parameter, STDIN is allowed as well) that takes a parameter *n*, which will be the index of the last character to print. The task is quite simple, so as an example here's a possible implementation in Python 2.7: ``` (lambda n:map(chr, range(n)))(256) ``` As I said it's a simple task. So this is code-golf and the shortest codes wins! **EDIT** As some of you pointed out this code doesn't print the result. It's just an example since I might struggle explaining the problem in english ;-). **EDIT2** Feel free to post the answer in any programming language, even if it's not the shortest code. Maybe there are some interesting implementations out there! **EDIT3** Fixed the example so it prints the result. [Answer] # brainfuck - ~~169~~ ~~146~~ 142 bytes ``` -[+>+[+<]>+]>+>>,[>,]<[<]<[->>[->]<[<]<]>>>[[<[-<+<+<+>>>]+++++++++[<[-<+>]<<[-<+>>>+<<]<[->+<]>>>>-]]<,<<,>[->>>+<<<]>>>---------->]<-[->.+<] ``` Limitations: * EOF must be 0 * Requires 8-bit wrapping cells * Because of ^, mods input by 256 Not the shortest answer here, but hey, brainfuck! This would be a really, really good brainfuck challenge, except for the fact that it requires human readable input without guaranteeing the number of digits. I could have required input to have leading zeroes to make it 3 characters long, but what fun is that? :D One major problem with taking input this way is that brainfuck's only branching or looping structure checks if the current cell is zero or not. When the input can contain zeroes, it can cause your code to take branches it shouldn't be taking. To solve this problem, I store each digit of input **plus 1**, then subtract the excess at the last possible second. That way, I always know where my zeroes are. I did say that this would have been a great brainfuck challenge without having to parse input. Why is that? Well, let's pretend that we don't take a numeric input. We'll say the challenge is "Given a byte of input, output all ASCII characters below that byte". Here's what my answer would be: --- # brainfuck - 8 bytes ``` ,[->.+<] ``` --- It's quite a difference! The real program uses 135 instructions to collect the input (over 95% of the program!), just because it's a human typing it. Store the number as a byte and give *that* to me, and it only takes one. (Fun fact: If you understood the hypothetical program, then congratulations! You understand brainfuck in its entirety. The whole language has only eight commands, and that program happens to use each one exactly once.) **Explanation** ``` -[+>+[+<]>+]>+ abuse 8 bit wrapping to put 47 in cell 4 >>,[>,] starting in cell 6; get each character of input <[<]<[->>[->]<[<]<] subtract the value of cell 4 from each input character '0' has an ascii value of 47 so subtracting 47 from each digit gives you that digit's value plus 1 >>>[ if the number is in more than one cell (when the program first starts this means "if the input has more than one digit") [<[-<+<+<+>>>] copy first input cell to 3 new cells +++++++++[<[-<+>]<< do some fancy addition magic to multiply that value by 10 [-<+>>>+<<]<[->+<]>>>>-]] <,<<,> clean up a bit (abusing comma to set cells to 0) [->>>+<<<]>>> add the value to the next cell of input ---------- because we multiplied (the digit plus 1) by 10; the answer is 10 too high; so subtract 10 >] if the input is still in multiple cells; do the song and dance again (multiply by 10; add to next cell; subtract 10) <- we never got a chance to fix the final digit; so it's still 1 too high ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we have now finished processing input ;; ;; the tape is empty except for the current cell ;; ;; the current cell contains the number that was input ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; [ while the cell containing input != 0 - subtract 1 from it >.+ go a cell to the right; output that cell; then add 1 <] repeat ``` [Answer] # CJam, 4 bytes ``` ric, ``` Full program that reads from STDIN (input field in the [online interpreter](http://cjam.aditsu.net/ "CJam interpeter")). This simply executes `range(chr(int(input())))`, taking advantage of the fact that `,` gives a return an array of characters if its argument is a character. I call dibs on `c,` (2 bytes), just in case that assuming the input is already on the stack turns out to be allowed. [Answer] ## [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` VQCN ``` Basically a translation of the Python 3 program: ``` for N in range(eval(input())):print(chr(N)) ``` [Answer] # Befunge 93 - ~~23~~ 21 ``` &> :#v_,>:#,_@ ^-1:< ``` # Befunge 93 - ~~15~~ 13 (by Ingo Bรผrk) This one prints the list in reverse, but OP only said we need to print the first `n` characters, not that it has to be in order. ``` &>::>v @^-1,_ ``` Might not be golfable any further without moving on to Befunge98 (for the ";" operator, see [@Kasran's answer](https://codegolf.stackexchange.com/a/40524/32047)) Try it here: ``` function BefungeBoard(source, constraints) { constraints = constraints || { width: 80, height: 25 }; this.constraints = constraints; this.grid = source.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/).map(function (line) { return (line + String.repeat(' ', constraints.width - line.length)).split(''); }); for (var i = this.grid.length; i < constraints.height; i++) { this.grid[i] = String.repeat(' ', constraints.width).split(''); } this.pointer = { x: 0, y: 0 }; this.direction = Direction.RIGHT; } BefungeBoard.prototype.nextPosition = function () { var vector = this.direction.toVector(), nextPosition = { x: this.pointer.x + vector[0], y: this.pointer.y + vector[1] }; nextPosition.x = nextPosition.x < 0 ? this.constraints.width - 1 : nextPosition.x; nextPosition.y = nextPosition.y < 0 ? this.constraints.height - 1 : nextPosition.y; nextPosition.x = nextPosition.x >= this.constraints.width ? 0 : nextPosition.x; nextPosition.y = nextPosition.y >= this.constraints.height ? 0 : nextPosition.y; return nextPosition; }; BefungeBoard.prototype.advance = function () { this.pointer = this.nextPosition(); if (this.onAdvance) { this.onAdvance.call(null, this.pointer); } }; BefungeBoard.prototype.currentToken = function () { return this.grid[this.pointer.y][this.pointer.x]; }; BefungeBoard.prototype.nextToken = function () { var nextPosition = this.nextPosition(); return this.grid[nextPosition.y][nextPosition.x]; }; var Direction = (function () { var vectors = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; function Direction(value) { this.value = value; } Direction.prototype.toVector = function () { return vectors[this.value]; }; return { UP: new Direction(2), DOWN: new Direction(3), RIGHT: new Direction(0), LEFT: new Direction(1) }; })(); function BefungeStack() { this.stack = []; } BefungeStack.prototype.pushAscii = function (item) { this.pushNumber(item.charCodeAt()); }; BefungeStack.prototype.pushNumber = function (item) { if (isNaN(+item)) { throw new Error(typeof item + " | " + item + " is not a number"); } this.stack.push(+item); }; BefungeStack.prototype.popAscii = function () { return String.fromCharCode(this.popNumber()); }; BefungeStack.prototype.popNumber = function () { return this.stack.length === 0 ? 0 : this.stack.pop(); }; function Befunge(source, constraints) { this.board = new BefungeBoard(source, constraints); this.stack = new BefungeStack(); this.stringMode = false; this.terminated = false; this.digits = "0123456789".split(''); } Befunge.prototype.run = function () { for (var i = 1; i <= (this.stepsPerTick || 10); i++) { this.step(); if (this.terminated) { return; } } requestAnimationFrame(this.run.bind(this)); }; Befunge.prototype.step = function () { this.processCurrentToken(); this.board.advance(); }; Befunge.prototype.processCurrentToken = function () { var token = this.board.currentToken(); if (this.stringMode && token !== '"') { return this.stack.pushAscii(token); } if (this.digits.indexOf(token) !== -1) { return this.stack.pushNumber(token); } switch (token) { case ' ': while ((token = this.board.nextToken()) == ' ') { this.board.advance(); } return; case '+': return this.stack.pushNumber(this.stack.popNumber() + this.stack.popNumber()); case '-': return this.stack.pushNumber(-this.stack.popNumber() + this.stack.popNumber()); case '*': return this.stack.pushNumber(this.stack.popNumber() * this.stack.popNumber()); case '/': var denominator = this.stack.popNumber(), numerator = this.stack.popNumber(), result; if (denominator === 0) { result = +prompt("Illegal division by zero. Please enter the result to use:"); } else { result = Math.floor(numerator / denominator); } return this.stack.pushNumber(result); case '%': var modulus = this.stack.popNumber(), numerator = this.stack.popNumber(), result; if (modulus === 0) { result = +prompt("Illegal division by zero. Please enter the result to use:"); } else { result = Math.floor(numerator / modulus); } return this.stack.pushNumber(result); case '!': return this.stack.pushNumber(this.stack.popNumber() === 0 ? 1 : 0); case '`': return this.stack.pushNumber(this.stack.popNumber() < this.stack.popNumber() ? 1 : 0); case '>': this.board.direction = Direction.RIGHT; return; case '<': this.board.direction = Direction.LEFT; return; case '^': this.board.direction = Direction.UP; return; case 'v': this.board.direction = Direction.DOWN; return; case '?': this.board.direction = [Direction.RIGHT, Direction.UP, Direction.LEFT, Direction.DOWN][Math.floor(4 * Math.random())]; return; case '_': this.board.direction = this.stack.popNumber() === 0 ? Direction.RIGHT : Direction.LEFT; return; case '|': this.board.direction = this.stack.popNumber() === 0 ? Direction.DOWN : Direction.UP; return; case '"': this.stringMode = !this.stringMode; return; case ':': var top = this.stack.popNumber(); this.stack.pushNumber(top); return this.stack.pushNumber(top); case '\\': var first = this.stack.popNumber(), second = this.stack.popNumber(); this.stack.pushNumber(first); return this.stack.pushNumber(second); case '$': return this.stack.popNumber(); case '#': return this.board.advance(); case 'p': return this.board.grid[this.stack.popNumber()][this.stack.popNumber()] = this.stack.popAscii(); case 'g': return this.stack.pushAscii(this.board.grid[this.stack.popNumber()][this.stack.popNumber()]); case '&': return this.stack.pushNumber(+prompt("Please enter a number:")); case '~': return this.stack.pushAscii(prompt("Please enter a character:")[0]); case '.': return this.print(this.stack.popNumber()); case ',': return this.print(this.stack.popAscii()); case '@': this.terminated = true; return; } }; Befunge.prototype.withStdout = function (printer) { this.print = printer; return this; }; Befunge.prototype.withOnAdvance = function (onAdvance) { this.board.onAdvance = onAdvance; return this; }; String.repeat = function (str, count) { var repeated = ""; for (var i = 1; i <= count; i++) { repeated += str; } return repeated; }; window['requestAnimationFrame'] = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; (function () { var currentInstance = null; function resetInstance() { currentInstance = null; } function getOrCreateInstance() { if (currentInstance !== null && currentInstance.terminated) { resetInstance(); } if (currentInstance === null) { var boardSize = Editor.getBoardSize(); currentInstance = new Befunge(Editor.getSource(), { width: boardSize.width, height: boardSize.height }); currentInstance.stepsPerTick = Editor.getStepsPerTick(); currentInstance.withStdout(Editor.append); currentInstance.withOnAdvance(function (position) { Editor.highlight(currentInstance.board.grid, position.x, position.y); }); } return currentInstance; } var Editor = (function (onExecute, onStep, onReset) { var source = document.getElementById('source'), sourceDisplay = document.getElementById('source-display'), sourceDisplayWrapper = document.getElementById('source-display-wrapper'), stdout = document.getElementById('stdout'); var execute = document.getElementById('execute'), step = document.getElementById('step'), reset = document.getElementById('reset'); var boardWidth = document.getElementById('board-width'), boardHeight = document.getElementById('board-height'), stepsPerTick = document.getElementById('steps-per-tick'); function showEditor() { source.style.display = "block"; sourceDisplayWrapper.style.display = "none"; source.focus(); } function hideEditor() { source.style.display = "none"; sourceDisplayWrapper.style.display = "block"; var computedHeight = getComputedStyle(source).height; sourceDisplayWrapper.style.minHeight = computedHeight; sourceDisplayWrapper.style.maxHeight = computedHeight; sourceDisplay.textContent = source.value; } function resetOutput() { stdout.value = null; } function escapeEntities(input) { return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } sourceDisplayWrapper.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; execute.onclick = function () { resetOutput(); hideEditor(); onExecute && onExecute.call(null); }; step.onclick = function () { hideEditor(); onStep && onStep.call(null); }; reset.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; return { getSource: function () { return source.value; }, append: function (content) { stdout.value = stdout.value + content; }, highlight: function (grid, x, y) { var highlighted = []; for (var row = 0; row < grid.length; row++) { highlighted[row] = []; for (var column = 0; column < grid[row].length; column++) { highlighted[row][column] = escapeEntities(grid[row][column]); } } highlighted[y][x] = '<span class="activeToken">' + highlighted[y][x] + '</span>'; sourceDisplay.innerHTML = highlighted.map(function (lineTokens) { return lineTokens.join(''); }).join('\n'); }, getBoardSize: function () { return { width: +boardWidth.innerHTML, height: +boardHeight.innerHTML }; }, getStepsPerTick: function () { return +stepsPerTick.innerHTML; } }; })(function () { getOrCreateInstance().run(); }, function () { getOrCreateInstance().step(); }, resetInstance); })(); ``` ``` .container { width: 100%; } .so-box { font-family:'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 75px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #controls-container, #options-container { height: auto; padding: 6px 0; } #stdout { height: 50px; } #reset { float: right; } #source-display-wrapper { display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display { font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f88912; } .clearfix:after { content:"."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } ``` ``` <div class="container"> <textarea id="source" placeholder="Enter your Befunge-93 program here" wrap="off">&> :#v_,>:#,_@ ^-1:<</textarea> <div id="source-display-wrapper"> <div id="source-display"></div> </div> </div> <div id="controls-container" class="container clearfix"> <input type="button" id="execute" class="control so-box" value="โ–บ Execute" /> <input type="button" id="step" class="control so-box" value="Step" /> <input type="button" id="reset" class="control so-box" value="Reset" /> </div> <div id="stdout-container" class="container"> <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea> </div> <div id="options-container" class="container"> <div class="option so-box">Steps per Tick: <span id="steps-per-tick" contenteditable>500</span> </div> <div class="option so-box">Board Size: <span id="board-width" contenteditable>80</span> x <span id="board-height" contenteditable>25</span> </div> </div> ``` [Answer] # Java, ~~151~~ ~~128~~ ~~77~~ ~~62~~ 56 bytes First try at code-golfing. ``` void f(int n){for(char i=0;++i<=n;System.out.print(i));} ``` Usage: ``` import java.util.Scanner; class A { public static void main(String[] a) { int num = new Scanner(System.in).nextInt(); new A().f(num); } void f(int n) { for (char i = 0; ++i <= n; System.out.print(i)); } } ``` Thanks to @Shujal, @flawr, @Ingo Bรผrk and @Loovjo for the serious byte reduction. [Answer] ## APL,5 ``` โŽ•UCSโณ ``` Example usage: ``` โŽ•UCSโณ256 ``` [Answer] # JavaScript, ES6 - ~~52~~ ~~58~~ ~~56~~ ~~53~~ ~~44~~ 42 bytes ``` n=>String.fromCharCode(...Array(n).keys()) ``` Paste this into the Firefox console. Run as `f(NUM)`. ~~Had to make it longer because the first didn't properly accept input.~~ Down 3, thanks edc65! Down to 44 thanks to Swivel! [Answer] # Haskell, ~~17~~ 23 bytes ``` flip take['\0'..] ``` Not sure if it is possible to do any better without imports. ## Edit My first solution didn't actually *print* the result, so allow 6 more chars for that: ``` print.flip take['\0'..] ``` Also, not shorter (25 chars with printing, 19 without), but an interesting alternate approach (it requires 'Data.List', though): ``` print.((inits['\0'..])!!) ``` [Answer] # Perl, 17 bytes ``` say chr for 0..$_ ``` [Answer] # awk - 27 ``` {while(i<$0)printf"%c",i++} ``` To give the parameter on stdin run it like: ``` awk '{while(i<$0)printf"%c",i++}' <<<96 ``` --- Just for fun: The "think positive version" starting with a definitive `yes`: ``` yes|head -96|awk '{printf"%c",NR-1}' ``` `NR-1` is needed to print `(char)0` for `NR==1`.ย  ย  :-( And why don't we have a `no` command? That's kinda mean! [Answer] # Bash+BSD common utilities, 9 bytes ``` jot -c $1 ``` # GNU dc, 20 bytes ``` ?sc_1[1+dPdlc>m]dsmx ``` [Answer] # C, ~~31~~ ~~30~~ ~~28~~ 27 ``` k;f(n){putch(k++)<n&&f(n);} ``` Since putch is nonstandard, here's the fully compliant version: ``` k;f(n){putchar(k++)<n&&f(n);} ``` Must be called from main: ``` main(){f(255);} ``` EDIT: Improved by taking advantage of putchar return value EDIT 2: Reduced by another character through recursion [Answer] ## CJam, 3 ``` ,:c ``` I assumed the argument to be the top stack element. Example usage: ``` 256,:c ri,:c ``` [Answer] # Ruby, 30 characters ``` puts (0..$*[0].to_i).map &:chr ``` [Answer] ## J - 5 bytes ``` {.&a. ``` `{.` is Head, `a.` is Alphabet ( a list of all chars) and `&` Bonds them, generating a monadic verb called like: ``` {.&a. 100 NB. first 100 characters ``` *Note*: It seems this does not work interactively: Jconsole and jQt seems to set up a translation, outputting box characters instead of some control characters. In a script or from the commandline, it does work though: ``` ijconsole <<< '127 {. a.' | hd ``` [Answer] # gs2, 2 bytes ``` V. ``` This should be competing, I think! It wouldโ€™ve worked even in the early days of gs2. [Try it here.](http://gs2.tryitonline.net/#code=Vi4&input=MTAw) [Answer] ## Brainfuck, 44 bytes > > > ``` > , > [ > <[>++++++++++<-] > -[>-<-----] > >+++>, > ] > <[>.+<-] > ``` > > > > Expects a decimal string without a trailing newline. [Try it online.](http://brainfuck.tryitonline.net/#code=LFs8Wz4rKysrKysrKysrPC1dLVs-LTwtLS0tLV0-KysrPixdPFs-Lis8LV0&input=MTAw) Reading integers in the range `[0, max_cell_size]` in brainfuck is not difficult. I encourage you to invent a clean method on your own. I consider this a beginner level exercise. (The reverse operation of printing a cell's numeric value is more involved, and could be considered an intermediate level task.) Here's a 58-byte version that can handle `256` on 8-bit implementations: > > > ``` > , > [ > <[<+> >++++++++++<-] > -[>-<-----] > >+++>, > ] > <[>] > -<<[>.] > >[>+.<-] > ``` > > > > [Answer] # [โˆš รฅ ฤฑ ยฅ ยฎ ร ร˜ ยฟ](https://github.com/cairdcoinheringaahing/UnprintableName) , 3 bytes *Note: Language post-dates challenge* ``` IrW ``` ### Explanation ``` I โ€บ Take input from command line, evaluate and push to stack r โ€บ Push the range from 0 to top value + 1 W โ€บ Output the whole stack as Unicode characters ``` # Alternate Solution As pointed out by @FlipTack in his Java answer, it is not clear if the OP wants us to print up to and including the input or excluding the input. If the second is true, the solution below is the correct answer. ``` IrPW ``` ### Explanation ``` I โ€บ Take input from command line, evaluate and push to stack r โ€บ Push the range from 0 to top value + 1 P โ€บ Pop the top value from the stack W โ€บ Output the whole stack as Unicode characters ``` [Answer] # Golfscript - 5 Thanks to @Dennis ``` ~,''+ ``` [Answer] ## Lua - ~~43~~ 41 Bytes ``` for i=1,arg[1]do print(string.char(i))end ``` [Answer] # Befunge 98, 22 ``` &:00pv>0gk,@ 0::-1<^j` ``` Kind of sad that this is so long. ``` &:00p ; gets numerical input, stores a copy at cell (0,0) ; v ; IP goes down ; < ; IP goes left, so I execute 1-::0`j^ ; ::-1 ; (1-::) subtract one from our number and duplicate it twice ; 0 ` ; (0`) compare the number with 0, push 1 if greater else 0 ; <^j ; if the result was 0, go up, otherwise continue going left ; >0gk, ; get the value at cell (0,0), print that many numbers from stack ; @ ; terminate program ; ``` [Answer] # Python 3.4 - 36 bytes / 43 bytes ``` print(*map(chr,range(int(input())))) print(*map(chr,range(int(input()))),sep='') ``` 255 input() How this works is: 1. Get upper limit of range 2. Generate a range of the table. 3. Map the range to chr function ( takes int, returns ascii ). 4. Consume the map via splat argument expansion ( number -> character -> print! ) The second one just removes the space separating each character in exchange for 7 bytes. [Answer] # Pascal 87 ``` program _;var c:char;n:byte;begin n:=0;readln(n);for c:=chr(0)to chr(n)do write(c);end. ``` # Pascal 73 ``` program _;var c,n:byte;begin readln(n);for c:=0to n do write(chr(c));end. ``` Builds and runs fine from <http://www.onlinecompiler.net/pascal> [Answer] # x86 ASM (Linux) (many many bytes unless you compile it) Written as a function, assumes parameter is passed in AX (I forget the number for the read syscall) Also doesn't preserve [SP] or BX. ``` test ax,ax jz @Done mov [sp],ax @Loop: mov ax,4 mov bx,1 mov cx,sp mov dx,1 int 0x80 sub [sp],1 ; Can I do this? Or do I need to load/sub/store separately? jnz @Loop @Done: ret ``` [Answer] # Perl - 29 ``` sub f{print map{chr}0..shift} ``` [Answer] # Ruby, 23 ``` f=->n{puts *?\0..n.chr} ``` ## Explanation * Input is taken as the argument to a lambda. It expects an Integer. * The "destructuring operator" (`*`) invokes `#to_ary` on the Range to print every character on its own line. [Answer] # Julia: 20 characters (REPL) This is close to the question's example: just generates the characters and let the REPL to do whatever it wants with them. ``` f(n)=map(char,[0:n]) ``` ## Julia: 33 characters Prints each character in a separate line. ``` print(map(char,[0:int(ARGS[1])])) ``` [Answer] # M (MUMPS) - 21 `R n F i=1:1:n W $C(i)` In expanded form: `READ n FOR i=1:1:n WRITE $CHAR(i)` [Answer] ## T-SQL: ~~68~~ 63 As a print loop ``` DECLARE @i INT=64,@ INT=0A:PRINT CHAR(@)SET @+=1IF @<=@i GOTO A ``` ## T-SQL: ~~95~~ 86 As a query ``` DECLARE @ INT=64SELECT TOP(@+1)CHAR(ROW_NUMBER()OVER(ORDER BY 0/0)-1)FROM sys.messages ``` **Edit:** Made changes and fixes pointed out by Muqo. Thanks. Fixes and golfing suggested by @t-clausen.dk [Answer] # BrainFuck - 140 112 Bytes ``` ,>,>,>-[>+<-----]>---[<+>-]<[<<<->->->-]<[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>>[>.+<-] ``` [Try It Here!](https://fatiherikli.github.io/brainfuck-visualizer/#LD4sPiw+LVs+KzwtLS0tLV0+LS0tWzwrPi1dPFs8PDwtPi0+LT4tXTxbPis8LV08Wz4+KysrKysrKysrKzw8LV08Wz4+Pj4rKysrKysrKysrWzwrKysrKysrKysrPi1dPDw8PC1dPj4+Wz4uKzwtXQ==) *Saved 28 bytes by changing `[<<<->>>->+<]>[<<<->>>->+<]>[<<<->>>-]` to `[<<<->->->-]`.* **What it does** ``` ,>,>,> Takes three inputs in three separate cells -[>+<-----]>---[<+>-]<[<<<->->->-]< Takes 48 off of each to convert them to decimal [>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>> Combines them into a three digit number by multiplying the first by 100, the second by 10 and then adding all three [>.+<-] Repeatedly prints the value of the adjacent cell and then adds one to it until it reaches the input value. ``` ]
[Question] [ # Task Given a positive integer `n`, output `n+1` if `n` is odd, and output `n-1` if `n` is even. # Input A positive integer. You may assume that the integer is within the handling capability of the language. # Output A positive integer, specified above. # Testcases ``` input output 1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7 313 314 314 313 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply. # References * [OEIS A103889](http://oeis.org/A103889) [Answer] # C, 20 bytes ``` f(x){return-(-x^1);} ``` [Try it online](https://tio.run/nexus/c-gcc#XVDtasMwDPzvpzhaCnaqbE2/NkjbF@kyCImzClZn2O4oDXn2zG6glOmHkE6606GhkVfVWe0v1qQyvX5mKu@HKZvq@1Jr7JyvuX05HYRg43Eu2UDGqrRfFaE6lRZJEppfJTqBEHHotfNV6bQ7FtijQ0ZYElaENWFD2BLeCO8ByVYxrdHnDy6PZdPacCiwFzkYO0jHN9028iGt8Ir/2HFRKBX253OF0U2MHxt0GzmZ1UgPmNUfZkJPFrkgPGtw1LiT@3sefxN8iH74Aw). [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 3 + 3 (`-n`) = 6 bytes ``` -*- ``` [Try it online!](https://tio.run/nexus/stackcats#@6@rpfv/v7Gh8X/dPAA "Stack Cats โ€“ TIO Nexus") Needs the `-n` flag to work with numeric input and output. ### Explanation Stack Cats is usually far from competitive, because of its limited set of commands (all of which are injections, and most of which are involutions) and because every program needs to have mirror symmetry. However, one of the involutions is to toggle the least-significant bit of a number, and we can offset the value with unary negation which also exists. Luckily, that gives us a symmetric program, so we don't need to worry about anything else: ``` - Multiply the input by -1. * Toggle the least significant bit of the value (i.e. take it XOR 1). - Multiply the result by -1. ``` Input and output are implicit at the beginning and end of the program, because taking input and producing output is not a reversible operation, so they can't be commands. [Answer] # x86 Assembly, 9 bytes (for competing entry) Everyone who is attempting this challenge in high-level languages is missing out on the *real* fun of manipulating raw bits. There are so many subtle variations on ways to do this, it's insaneโ€”and a lot of fun to think about. Here are a few solutions that I devised in 32-bit x86 assembly language. I apologize in advance that this isn't the typical code-golf answer. I'm going to ramble a lot about the thought process of iterative optimization (for size). Hopefully that's interesting and educational to a larger audience, but if you're the TL;DR type, I won't be offended if you skip to the end. The obvious and efficient solution is to test whether the value is odd or even (which can be done efficiently by looking at the least-significant bit), and then select between *n+1* or *nโˆ’1* accordingly. Assuming that the input is passed as a parameter in the `ECX` register, and the result is returned in the `EAX` register, we get the following function: ``` F6 C1 01 | test cl, 1 ; test last bit to see if odd or even 8D 41 01 | lea eax, DWORD PTR [ecx + 1] ; set EAX to n+1 (without clobbering flags) 8D 49 FF | lea ecx, DWORD PTR [ecx - 1] ; set ECX to n-1 (without clobbering flags) 0F 44 C1 | cmovz eax, ecx ; move in different result if input was even C3 | ret ``` **(13 bytes)** But for code-golf purposes, those `LEA` instructions aren't great, since they take 3 bytes to encode. A simple `DEC`rement of `ECX` would be much shorter (only one byte), but this affects flags, so we have to be a bit clever in how we arrange the code. We can do the decrement *first*, and the odd/even test *second*, but then we have to invert the result of the odd/even test. Also, we can change the conditional-move instruction to a branch, which may make the code run more slowly (depending on how predictable the branch isโ€”if the input alternates inconsistently between odd and even, a branch will be slower; if there's a pattern, it will be faster), which will save us another byte. In fact, with this revision, the entire operation can be done in-place, using only a single register. This is great if you're inlining this code somewhere (and chances are, you would be, since it's so short). ``` 48 | dec eax ; decrement first A8 01 | test al, 1 ; test last bit to see if odd or even 75 02 | jnz InputWasEven ; (decrement means test result is inverted) 40 | inc eax ; undo the decrement... 40 | inc eax ; ...and add 1 InputWasEven: ; (two 1-byte INCs are shorter than one 3-byte ADD with 2) ``` **(inlined: 7 bytes; as a function: 10 bytes)** But what if you did want to make it a function? No standard calling convention uses the same register to pass parameters as it does for the return value, so you'd need to add a register-register `MOV` instruction to the beginning or end of the function. This has virtually no cost in speed, but it does add 2 bytes. (The `RET` instruction also adds a byte, and there is a some overhead introduced by the need to make and return from a function call, which means this is one example where inlining produces both a speed *and* size benefit, rather than just being a classic speed-for-space tradeoff.) In all, written as a function, this code bloats to 10 bytes. What else can we do in 10 bytes? If we care at all about performance (at least, *predictable* performance), it would be nice to get rid of that branch. Here is a branchless, bit-twiddling solution that is the same size in bytes. The basic premise is simple: we use a bitwise XOR to flip the last bit, converting an odd value into an even one, and vice versa. But there is one niggleโ€”for odd inputs, that gives us *n-1*, while for even inputs, it gives us *n+1*โ€” exactly opposite of what we want. So, to fix that, we perform the operation on a negative value, effectively flipping the sign. ``` 8B C1 | mov eax, ecx ; copy parameter (ECX) to return register (EAX) | F7 D8 | neg eax ; two's-complement negation 83 F0 01 | xor eax, 1 ; XOR last bit to invert odd/even F7 D8 | neg eax ; two's-complement negation | C3 | ret ; return from function ``` **(inlined: 7 bytes; as a function: 10 bytes)** Pretty slick; it's hard to see how that can be improved upon. One thing catches my eye, though: those two 2-byte `NEG` instructions. Frankly, two bytes seems like one byte too many to encode a simple negation, but that's the instruction set we have to work with. Are there any workarounds? Sure! If we `XOR` by -2, we can replace the second `NEG`ation with an `INC`rement: ``` 8B C1 | mov eax, ecx | F7 D8 | neg eax 83 F0 FE | xor eax, -2 40 | inc eax | C3 | ret ``` **(inlined: 6 bytes; as a function: 9 bytes)** Another one of the oddities of the x86 instruction set is [the multipurpose `LEA` instruction](https://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction), which can do a register-register move, a register-register addition, offsetting by a constant, and scaling all in a single instruction! ``` 8B C1 | mov eax, ecx 83 E0 01 | and eax, 1 ; set EAX to 1 if even, or 0 if odd 8D 44 41 FF | lea eax, DWORD PTR [ecx + eax*2 - 1] C3 | ret ``` **(10 bytes)** The `AND` instruction is like the `TEST` instruction we used previously, in that both do a bitwise-AND and set flags accordingly, but `AND` actually updates the destination operand. The `LEA` instruction then scales this by 2, adds the original input value, and decrements by 1. If the input value was odd, this subtracts 1 (2ร—0ย โˆ’ย 1ย =ย โˆ’1) from it; if the input value was even, this adds 1 (2ร—1ย โˆ’ย 1ย =ย 1) to it. This is a very fast and efficient way to write the code, since much of the execution can be done in the front-end, but it doesn't buy us much in the way of bytes, since it takes so many to encode a complex `LEA` instruction. This version also doesn't work as well for inlining purposes, as it requires that the original input value be preserved as an input of the `LEA` instruction. So with this last optimization attempt, we've actually gone backwards, suggesting it might be time to stop. --- Thus, for the final competing entry, we have a 9-byte function that takes the input value in the `ECX` register (a semi-standard [register-based calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall) on 32-bit x86), and returns the result in the `EAX` register (as with all x86 calling conventions): ``` SwapParity PROC 8B C1 mov eax, ecx F7 D8 neg eax 83 F0 FE xor eax, -2 40 inc eax C3 ret SwapParity ENDP ``` Ready to assemble with MASM; call from C as: ``` extern int __fastcall SwapParity(int value); // MSVC extern int __attribute__((fastcall)) SwapParity(int value); // GNU ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` -*แบก ``` [Try it online!](https://tio.run/nexus/jelly#@6@r9XDXwv86h9tVHjWtcf//P9pQR8FIR8FYR8FER8FUR8FMR8FcR8ECKGJoDCJMYgE "Jelly โ€“ TIO Nexus") Pseudocode: `abs((-1)**n - n)` [Answer] # Python3, ~~20~~ 18 bytes ``` lambda n:n-1+n%2*2 ``` Pretty simple. First we calculate **n-1** and decide whether to add 2 to it, or not. **If n is even** --> **n mod 2** will be 0, thus we'll add **2\*0** to **n-1**, resulting in **n-1**. **If n is odd** --> **n mod 2** will be 1, thus we'll add **2\*1** to **n-1**, resulting in **n+1**. I prefer an explanation that I made with MS paint & a laptop touchpad... [![Visual explanation](https://i.stack.imgur.com/Y8p0D.png)](https://i.stack.imgur.com/Y8p0D.png) [Answer] # Python, 16 bytes ``` lambda x:-(-x^1) ``` [Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQYaWroVsRZ6j5Py2/SCFTITNPoSgxLz1Vw1DH0FzTiouzoCgzr0RDKU1DNUXTSkE1RUlVI1NHIU0jU1NT8////wA) [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` Q:HePG) ``` This avoids any arithmetical operations. [Try it online!](https://tio.run/nexus/matl#@x9o5ZEa4K75/785AA "MATL โ€“ TIO Nexus") ### Explanation Consider input `4` as an example. ``` Q % Implicit input. Add 1 % STACK: 5 : % Range % STACK: [1 2 3 4 5] He % Reshape with 2 rows in column-major order. Pads with a zero if needed % STACK: [1 3 5; 2 4 0] P % Flip vertically % STACK: [2 4 0; 1 3 5] G % Push input again % STACK: [2 4 0; 1 3 5], 4 ) % Index, 1-based, in column major order. Implicitly display % STACK: 3 ``` [Answer] ## Python, 68 bytes ``` lambda x:[m.floor(x-m.cos(m.pi*x)) for m in [__import__('math')]][0] ``` In the spirit of a unique approach. The following graph shows the function (with purple dots representing the first 10 cases). It should in theory be possible to construct a solution for this question based on most (all?) periodic functions (e.g. sin, tan, sec). In fact, substituting cos for sec in the code as is should work. [![Graph demonstrating function](https://i.stack.imgur.com/jXgXM.png)](https://i.stack.imgur.com/jXgXM.png) [Answer] # [Braingolf v0.1](https://github.com/gunnerwolf/braingolf), ~~11~~ 10 bytes ``` .1>2,%?+:- ``` [Try it online!](https://tio.run/nexus/python3#zVlNc9s2EL3rVyBuXZGNpEpJDx3JcjrTSWZ6ag@dXhTVw5CghIYiWYB05Gmnf93dBUB8kFAi9WL74CGBxe7bh90lsHrMeXUg4kEQdqgr3pCE7@5XIzmat2XaVFVh5jjN2pTq2bQqCpo2rCrNfEb/amFav1ViVifN3r7XlCdNxc0AayiX@lejUVokQhAhNUTyf7wcEdCYk7u7HW1A9nB3Fwla5BPCyowe5TwhLCdMsFI0SZnSSM5MiChYSrUAAdhNy0vSPNRUKogjY3nGpKirdwaqeGNfqto@0zqOR45KCXR2CuBohPARXRMJiabhD0uiYMsxV9dvvKXwTo8prRvye1K09C3nFV@6Qu@SQlClV9FJo47WCckZFwBc0LQqM2lPr@pEIl9ipRQBeHA5/XifFJF8mJCaU0H5PZ2AhnupCWjuBj1AcsFmvkUBkCUU8OnB6WK7QodgZLhkVld1QfMmiocrcS4KoBNBeOB3weoOZEFLJRWTW7IwIeJjJwRNk/UZ6CVutttb6UVQ@pWWtt76Rs7xN2DtvGXW6GlXfSfmp@EO7CsbevMilJooIYmprBq5AQpYJCcmUle3g3XCBY3SKlMZWXOM/fGvMMrKHbkWY3JN5CyakVbRuqoEckxvK1Ym3NXXCrCSfLmWFWvzerldBSJgrmS1zZ/Lum2W2uQGh1hM8ooTBvmoFWI92SpWywyAyIxbSdyKV3cM0ugeKok7BHtEwV93SDQcPXVGqEiT2pM5tEXDJExv5Ucg1nlnuQdJMHDWWyB3wnkvqsp733FKs4e@hKx4MDhfdfuTVq1UfHVlwKX7hJuRYyf9aQ8Y4PVG8m42GagBCXzdHHWoHXGvFhAT@IKkPyDpPCl3NJpP7K6Zsg07oYL1ATJOyEADZN0ssZNrVU31a6xN4HKgz9EGkNZk/M@YgHH1vBw76npcd8uy/iBsesNK/NB1dpDDgZ2to9u4AqXGBKXrBYxPJTt2Aik2m2Mn3IyVWdvbYU@vLR92agjfxp7jhPpspbG15QQG7GQa0hiC2IUSqrMqYlWqjEZZPRYu73LDVYS7/upUHs/@rFgZbdI9j5jECyG4WCy@XyxeKWXzfmpvbIxNpdHldhtPMM3X43E8MN2vo7bmdEV02Ve4tUrC@dy5MKwkWv8goQfUdxmo/kykyxIziMGrMUmgiqE7quS42dMvSq6LsMGbimdefTRVoO@mVxlUABgE79/7aRCC4tRDPASFw8hassGn7Kga3EmquE/qGvY1QhfSOHYyt1@uPbBLSxfkvdGoCoOF5qy4Glu7ms@g3N3Y2RvUrwrx8tx4/9IZDT85oVi@NNR8zv38cVGdhPs/AdvlfebWhjmlOPzZ3sYDyn/8EuVeip4OPNzYXtad5kUKY4B@piythjyGas3gLLTZektPb60iCqE4C4Zffo@trwxbNkmCkfzv2F6rupNOUPBrmxpdqAXlJkZOH16CUt8YKeNIUG42DhYCc6YfxkkRXuEcSAZL/jZL8EJnc7is5XcODpmR/z2BMXdrMX7SPQZQbyJUvvZxfPrr74lPF0ZS3yLf/vLOuUOeXuD49sb4BqkL7pyVyCvn3AChB7IxuVm7B51BEbWHK3fsVFAHTtUe6o1Brc9DrlL3iHscLH35pTqBN0@fCHGSCX0ZXYX57l/ZZ0mWTTrGBBwCY@cNYjU@q5L3z/yhEuYXEtEedGxvz68Q3z0hTzlsIc/Y/VOQpZpeISwXU/jtE1IIX7vnwJ6EcTFx0yckTrQfngNxEsbFxP3xhMTV1afnQJyEcTFx10@ZqlX2LFIVYVxAXL9j4DmppobHjRfO8d64EjzZ3fTOabxqkLXQGeY2LBqQXBlJ1e2zlkfB1sjlzYzgTSnUxDirXRF7SvvXhl57wmtKnGpIhCNoeDvs7u5l5rZUnSbxsPeqeJD30ZHXw71RPVzTlYXIZhn2ccULdXnVMz9VnNO0Ia1IdhT7tuQmL5LdLbkRVctTeks26kGu3b4vEZgWWZK3rNlTTqY59vum6QyfWJmxFGJBkGafNFYPEyQhObYym4p8oJC4SUbwZ66J7nBO08@t/cATuPxXRS5bnp2Otpxho1n2p@e6p3xk8m4wOqCc7l3jLw3aDz2CvyYgZUoKP4D52GWMiH3VFhmaADBUWWX4DGDQja7JrdRK0zhcJge0oUb1ruqf6WZMoETUiek0/gQk4u9HsK9KFUnAggm4DnU@Q8a6W4/q@Du2beHRHrxDTq9VUzeHKM1eIFpjW@epJguSUaasZSP9DBvAANIRYKAHqwPVC0MMHx2GHYDHx8dp@jh7Nbl@s3i5XEymj4sf/gM "Python 3 โ€“ TIO Nexus") (Second argument is the Braingolf code, third argument is the input) Saved a byte thanks to Neil First ever competing braingolf answer :D Explanation: ``` . Duplicate the top of the stack 1> Push 1 to the bottom of the stack 2 Push 2 to stack ,% Pop last 2 items, mod them and push result ? If last item > 0 + Add the 1 to the input : Else - Subtract the 1 from the input No semicolon in code so print last item ``` # [Braingolf v0.2](https://github.com/gunnerwolf/braingolf), 9 bytes ``` .2%?1+:1- ``` [Try it online!](https://tio.run/nexus/python3#zVlLj9s2EL77VzDbbi01tmsnBQr4sSlQJEBP7aHoxXEXikTZbLSSSkobL1r0r29nSIoPiU7sXnb3sJDI4cw3H2dG5Pgx59UdEQ@CsLu64g1J@P5@NZKjeVumTVUVZo7TrE2pnk2roqBpw6rSzGf0rxam9VslZnXSHOx7TXnSVNwMsIZyqX81GqVFIgQRUkMk/8fLEQGNObm93dMGZO9ubyNBi3xCWJnRo5wnhOWECVaKJilTGsmZCREFS6kWIAC7aXlJmoeaSgVxZCzPmBR19c5AFW/sS1XbZ1rH8chRKYHOTgEcjRA@omsiIdE0/GFJFGw55ur6jbcU3ukxpXVDfk@Klr7lvOJLV@hdUgiq9Co6adTROiE54wKAC5pWZSbt6VWdSORLrJQiAA8upx/vkyKSDxNScyoov6cT0HAvNQHN3aAHSC7YzncoALKEAj49OF3sVugQjAyXzOqqLmjeRPFwJc5FAXQiCA/8LljdgSxoqaRickMWJkR87ISgabI5A73EzfYHK70ISr/S0tZb38g5/gasnbfMGj3tqu/E/DTcgX1lQ29ehFITJSQxlVUjN0ABi@TEROrqdrBOuKBRWmUqI2uOsT/@FUZZuSfXYkyuiZxFM9IqWleVQI7pbcXKhLv6WgFWki83smJtXy93q0AEzJWstvlzWbfNUpvc4hCLSV5xwiAftUKsJzvFapkBEJlxK4lb8eqOQRrdQyVxh2CPKPjrDomGo6fOCBVpUnsyd23RMAnTW/kRiHXeWe5BEgyc9RbIndjIWoKvRVV56/ec0uzBHUEJWfBgcL7qtietWqn36spgSw8JNyPHTvrTASDA61rSbvYYmAEJfN0edaQdcasWEBL4gpw/IOc8Kfc0mk/sppmqDRuhYvUBEk7IOANk3SyxkxtVTPVrrE3gcmDP0QaQNmT8z5iAcfW8HDvqelR3y7L@IOx5w0rkt7ODHA7s7BzdxhWoNCYmXS9gfCrZsRNIsdkcO@EmrEza3g57em31sFND@Db0HCfUVyuNrS0nMGAn05DGEMQulFCdVRGrSmU0yuKxcHmXG64C3PVXZ/J49mfFymibHnjEJF4IwcVi8f1i8Uopm/cze2tjbCqNLne7eIJZvhmP44Hpfhm1Jaerocu@wp1VEk7nzoVhIdH6B/k8oL7LQPVnIl1WmEEMXo1JAkUM3VEVx82efk1yXYQN3lY888qjqQJ9N73KoALAIHj/3k@DEBSnHHZ1axhG1pINPmVHleBOUsV9UtewrxG6kMaxk7n9au2BXVq6IO@Nxo9eSfVWXI2tXc1nUO527OwN6leFeHluvH/piIZfnFAsXxpqPud@/rioTsL9n4Dt8j5zG8OcUhz@au/iAeU/folyL0VPBx5ubC/rTvMihTFAP1OWVkMeQ7VmcBTa7rylp7dWEYVQnAXDL7/H1leGLZskwUj@d2xvVd1BJyj4tU2NLtSCchMjp88uYYDfGDHjSVDdbBysBOZMPwyUv80KvJ3ZjCxr@dWCE2Pkfx1gzN0ojIb0gOHQmwgVo0Mcn/6We@LThZHUV8K3v7xzLoSnFzi@vTG@QSKCO2el5co5BUAggWxM1hv32DIoifao5I6dCtHAEdlDvTWo9enGVeoeWI@DpS@/lPV4jfSJECeZ0DfLVZjv/v17lmTZpGNMwJEudt4g8OKz6nLvAB@qR35VEO2dPoTszk/3756Qphx2kGfs/gm4Uv2rEJSLGfz2CRmEL9czIE@iuJi36RPyJtoPz4A3ieJi3v54Qt7q6tMz4E2iuJi366fM0yp7DnmKKC7grX/z93xUU8ODxgvnmG48CR7Q1r0DGq8aJC10erkJiwYkV0ZSNe2s5VGwxXF5UyJ44wk1I85qO8Se0v7xv9dm8JoLpxoL4QAa3vK6O3iZuZ1Rp9c7bKEqHuS9cuS1YteqFWuaqxDYLMN2rHihLqF65qeKc5o2pBXJnmL7lazzItnfkLWoWp7SG7JVD3Lt7n2JwLTIkrxlzYFyMs2xbzdNZ/jEyoylEAuCNIeksXqYIAnJsSXZVOQDhbxNMoK/Vk10p3Kafm7tB57AJb4qctm67HS05Qz7xbLNPNet4SOTt4LRHcrpFjT@YKD90CP4owBSpqTw65ePXcaIOFRtkaEJAEOVVYbPAAbd6HrVSq00jcNlcoc21KjeVf1r24wJlIg6MZ3Gn4BE/BkI9lWpIglYMAHXoc5nyFh331GNe8e2LTzag3fI6bVqzuYQpdkLRGts6zzVZEEyypS1bKSfYQMYQDoCDPRgdaB6YYjho8OwA/D4@DhNH2eL9avrNy@X08fFD/8B "Python 3 โ€“ TIO Nexus") (Second argument is the Braingolf code, third argument is the input) See above for explanation. Only difference is in Braingolf v0.2, the default behaviour of diadic operators, and the function of the `,` modifier, are reversed, meaning the 2 commas in the v0.1 answer are no longer needed. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~10~~ 9 bytes ``` cO1)I(//@ ``` [Try it online](https://ethproductions.github.io/cubix/?code=Y08xKUkoLy9A&input=MzEz&speed=3) ### Explanation Net version ``` c O 1 ) I ( / / @ . . . . . . . . . . . . . . . ``` The executed characters are ``` I(1c)O@ I Input ( Decrement 1c XOR with 1 ) Increment O@ Output and exit ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 bytes -2 thanks to Razetime ``` โŠข-ยฏ1*โŠข ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYt0D6031ALS//8/6l2VdmiFxqPezRaaOsaGxkBsAgA "APL (Dyalog Unicode) โ€“ Try It Online") Explanation: ``` โŠข-ยฏ1*โŠข ยฏ1*โŠข โ calculate ยฏ1*โต - for even โต: 1, for odd โต: ยฏ1. โŠข- โ subtract 1 for even, subtract ยฏ1 (add 1) for odd. ``` [Answer] # JavaScript (ES6), ~~14~~ ~~13~~ ~~12~~ 10 bytes ``` n=>-(-n^1) ``` * 1 byte saved thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke). * 2 bytes saved by porting [feersum's C solution](https://codegolf.stackexchange.com/a/118833/58974). (If that's frowned upon, please let me know and I'll roll back to my previous solution below) --- ## Try It ``` f= n=>-(-n^1) i.addEventListener("input",_=>o.innerText=f(+i.value)) ``` ``` <input id=i type=number><pre id=o> ``` --- [Answer] # PHP, 15 bytes ``` <?=-(-$argn^1); ``` [Answer] # Javascript, 17 12 bytes ``` x=>x-(-1)**x ``` ``` f=x=>x-(-1)**x; ``` ``` <input id=i oninput=o.innerText=f(this.value) type=number><pre id=o> ``` # Another approach, 10 bytes stolen from the C answer (sssshhh) ``` x=>-(-x^1) ``` ``` f=x=>-(-x^1) ``` ``` <input id=i oninput=o.innerText=f(this.value) type=number><pre id=o> ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 11 bytes ``` u%2!I(/+@O< ``` [Try it online!](https://tio.run/nexus/cubix#@1@qaqToqaGv7eBv8/@/EQA "Cubix โ€“ TIO Nexus") # Explanation Net version: ``` u % 2 ! I ( / + @ O < . . . . . . . . . . . . . ``` Characters are executed in following order: ``` I(2%!+O@ I # Take a number as input ( # Decrement it 2% # Take the parity of the decremented number # (0 if the input is odd, 1 if it's even) ! # If that number is zero: + # Add 2 O # Output the number @ # Terminate the program ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes ``` (({})(())){({}[()]<([{}])>)}{}({}{}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hUV2rqaGhqalZDWRFa2jG2mhEV9fGatpp1lbXAoWA0v//GxoAAA "Brain-Flak โ€“ TIO Nexus") I'm personally really happy with this answer because it is a lot shorter than what I would deem a traditional method of solving this problem. ## Explanation The first bit of code ``` (({})(())) ``` converts the stack from just `n` to ``` n + 1 1 n ``` Then while the top of the stack is non zero, we decrement it and flip the sign of the number under it ``` {({}[()]<([{}])>)} ``` The we remove the zero and add the two remaining numbers ``` {}({}{}) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes ``` โ€นue+ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E2%80%B9ue%2B&inputs=5&header=&footer=) Me and the boys porting risky be like ## Explained ``` โ€นue+ โ€น # input - 1 u # -1 e # ^^ ** ^ + # ^ + input ``` [Answer] # Python, 20 bytes ``` lambda n:n+(n%2or-1) ``` `n%2or-1` will return 1 if it's odd, but if it's even, `n%2` is "false" (0), so it instead returns -1. Then we simply add that to `n`. ### Previous solution, 23 bytes ``` lambda n:[n-1,n+1][n%2] ``` `n%2` calculates the remainder when `n` is divided by 2. If it's even, this returns 0, and element 0 in this list is `n-1`. If it's odd, this returns 1, and element 1 in this list is `n+1`. [Answer] # [Retina](https://github.com/m-ender/retina), 21 bytes ``` .+ $* ^11(?=(11)*$) ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/ivp82losUVZ2ioYW@rYWioqaWiycX1/78hlxGXMZcJlymXGZc5lwWXsaExEJsAAA "Retina โ€“ TIO Nexus") My first Retina answer with two trailing newlines! Explanation: The first two lines convert from decimal to unary. The third and fourth lines subtract two from even numbers. The last line converts back to decimal, but adds one too. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` (1^( ``` [Try it online!](https://tio.run/nexus/05ab1e#@69hGKfx/78ZAA "05AB1E โ€“ TIO Nexus") [Answer] # Mathematica, ~~22~~ 19 bytes Saved 3 bytes thanks to Greg Martin! ``` #-1[-1][[#~Mod~2]]& ``` ### Previous answer, 22 bytes ``` #+{-1,1}[[#~Mod~2+1]]& ``` ### Explanation (for previous answer) Mathematica has the nice feature that operations such as arithmetic automatically thread over lists. In this case, we take `Mod[#,2]` which will return 0 or 1, but we need to add 1 because Mathematica lists are 1-indexed. If it's **even**, this comes out to 1, so `#-1` is returned. If it's **odd**, this comes out to 2, so `#+1` is returned. [Answer] # [Wise](https://github.com/Wheatwizard/Wise), 8 bytes ``` -::^~-^- ``` [Try it online!](https://tio.run/nexus/wise#@69rZRVXpxun@///f0sA "Wise โ€“ TIO Nexus") ## Explanation If this were the other way around, (decrement if odd, increment if even), it would be quite easy to do this. We would just flip the last bit. ``` ::^~-^ ``` The fix here is that we flip the last bit while negative. The negative numbers are 1 off from the negation of the numbers `~` so this creates an offset resolving the problem. So we just take out program and wrap it in `-`. ``` -::^~-^- ``` [Answer] # R, 17 bytes ``` (n=scan())-(-1)^n ``` where `n=scan()` takes the digit value. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck) (8-bit), 51 bytes ``` ,[->>++>+<<<]+++[->>[-<++>]<[->++<]<]>>[>++<[-]]>-. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXzk5b207bxsYmVltbG8SN1rUBisTaANna2jaxNrFAIRArWjc21k5X7/9/QwA "brainfuck โ€“ Try It Online") Requires a fixed 8-bit cell size. Decided to do something entirely on my own. Inspired by [some meme ARM code I wrote to check if it is a multiple of 4 (screenshot)](https://i.stack.imgur.com/0iptM.png) Instead of modulo, negate+xor, or binary AND, I shift out all the bits but the lowest to determine if it is even or odd. ``` // Checks parity by shifting n << 7. // Requires 8-bit cells , // [ n 0 0 0] // copy loop, shifting one once [->>++>+<<<] // [ 0 0 n<<1 n] // n <<= 6 +++ // c = 3 [- // loop 3 times, shifting twice >>[-<++>] // [ c n<<1 0 n] <[->++<] // [ c 0 n<<1 n] <] // end loop // if even: // tape[2]==0 // else: // tape[2]==0x80 >>[ // if tape[2] != 0: >++<[-] // n += 2 ] >- // n -= 1 . // print n ``` Equivalent C: ``` uint8_t parity(uint8_t n) { uint8_t is_odd = n << 7; if (is_odd != 0) n += 2; return n - 1; } ``` The input is a byte from stdin, and the output is a byte printed to stdout. 0-255 only. The demo uses ASCII arithmetic. # [boolfuck](https://github.com/TryItOnline/boolfuck) (joke), 3 bytes ``` ,+; ``` [Try it online!](https://tio.run/##S0oszvj/P7UiNVnByE7NkKs4tURBt4yroCgzryRNQV1H21pdwU6hJLW4RC8pPz8NLhFjoK5Qo6CfX1CiDxTPSStNzgYx0hBKgdIVFSkIDYbEafj/3wAA) **For a real Boolfuck solution, see [here](https://codegolf.stackexchange.com/a/218203/94093)** Operation works on 1-bit integers from stdin, prints to stdout. Obviously a joke. [Answer] # [Factor](https://factorcode.org/), 15 bytes ``` [ -1 over ^ - ] ``` [Try it online!](https://tio.run/##NY2xCsIwFEX3fsWlsy3WsYKrdOkiTqVCjK82aJP48qL06yO2uFw4cA53UFocp/OpaY81FLOaA4zDg9jSE5OScZlyiFaLcTasyMreKWSeSWT2bKwg0CuS1RSwz5q2RtCsRI9ZbqyPEmogx4eNEHZbdNXm2uOwHOIWPcrUoajg3sS4oECfchdlDf/dpH7eFw "Factor โ€“ Try It Online") Uses `x-(-1)^x` method as in many other answers (specifically inspired by [the APL one](https://codegolf.stackexchange.com/a/216648/78410)). In Factor, it is usually better (code-golf-wise) to minimize the number of conditionals, then minimize the number of functions overall (especially when the answer can be found with arithmetic, where all the functions have short names). The top answer beats a different arithmetic answer `x+x%2*2-1` (23 bytes) ``` [ dup 2 mod 2 * + 1 - ] ``` [Try it online!](https://tio.run/##NY07D4IwFIV3fsUJow8ijJi4GhYW40QYarlIo7T19jaGX48KcflOTnIevdLieL5eqvpcQjGrKcA4PIgtPTEqGRZkfbRajLNhtazsnULimUQmz8YKAr0iWU0Bx6SqSwTNSvSQpMb6KKEEUrzZCKE4oMl3txan5RBd9MjmZtECo@u@3GCLHHu0c@qirAP//qh@@Q8 "Factor โ€“ Try It Online") and a conditional-based answer `x+(x.odd()?1:-1)` (21 bytes) ``` [ dup odd? 1 -1 ? + ] ``` [Try it online!](https://tio.run/##NY0xD4IwFIR3fsWFVSXiiImMhoXFOBGGWh7SCG19fY3h12OEuNzlku/L9UqL4@V@q@prAcWs5gDj8CK2NGJSMqyR9dFqMc6GbbKyTwqJZxKZPRsrCPSOZDUFnJOqLhA0K9FDkhrro4QCSPFhI4TTEU2@f7S4rIfooke2NGu7riuR45CjxA7tkroom/63J/Wjvw "Factor โ€“ Try It Online") [Answer] # [Risky](https://github.com/Radvylf/risky), 4 bytes ``` ?+0--2? ``` [Try it online!](https://radvylf.github.io/risky?p=WyI_KzAtLTI_IiwiWzZdIiwwXQ) ### Explanation ``` ? The input number +0 plus 0 - minus - -1 2 to the power of ? the input number ``` [Answer] # Java 8, ~~16~~ 10 bytes ``` n->-(-n^1) ``` # Java 7, ~~34~~ 28 bytes ``` int c(int n){return-(-n^1);} ``` Boring ports of [*@feersum*'s amazing C answer](https://codegolf.stackexchange.com/a/118833/52210). [Try it here.](https://tio.run/nexus/java-openjdk#hc7NCoMwEATgu0@xx@SgkNo/8Bl68lgspKmUQFwl2RRE8uypgtduL3P5hmGM0yHAbSkAAmmyBrJFAiO2RLn4nqLHUpT4ULJJGWCKT7fW9vZntC8YtEXRkrf4vneg5bYG0M6B@qEaI1XTSuRQGKGkbH7rgdWa1SOrJ1bPrF5YvfKfVf3H99@pSPkL) --- Old answers: **Java 8, 16 bytes** ``` n->n%2<1?n-1:n+1 ``` **Java 7, 34 bytes** ``` int c(int n){return--n%2>0?n:n+2;} ``` **Explanation (of old Java 7 answer):** [Try it here.](https://tio.run/nexus/java-openjdk#hc5NCsIwEAXgfU8xGyFBWmzqHxb0BK66FBcxFgm009JMBCk5e2yhW8fN23xvhmca7RxcxwTAkSZrIFokMGJOlONQkx8wTXGlzpsLnnCtyhABev9opvJy8@7sE1ptUVQ0WHzd7qDl/BOg@jiq26zzlPUTUYPCiFzK8rcqVgtWt6zuWN2zemD1yG/Oiz@@7A5JiF8) The answer above is a shorter variant of `int c(int n){return n%2<1?n-1:n+1;}` by getting rid of the space. ``` int c(int n){ // Method with integer parameter and integer return-type return--n%2>0? // If n-1 mod-2 is 1: n // Return n-1 : // Else: n+2; // Return n+1 } // End of method ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` n ^1 n ``` [Try it online!](https://tio.run/nexus/japt#@5@nEGeokPf/vykA "Japt โ€“ TIO Nexus") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 15 bytes ``` {$1+=$1%2*2-1}1 ``` [Try it online!](https://tio.run/nexus/awk#@1@tYqhtq2KoaqRlpGtYa/j/v4KCoQIIcIEIIxjDGMYwgTFMYQwzGMMcxrCAMIwNjWEMsC4A "AWK โ€“ TIO Nexus") I could save 1 byte by using `(-1)^$1`, but then it would be pretty much the same as everyone else, and this is what I came up with before looking at other answers. :) [Answer] # Python, 20 bytes ``` lambda n:n+(n&1)*2-1 ``` ]
[Question] [ Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement? Write a function (or program) that takes one input `x` in any form, that outputs `ln(x)`. When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input `x` in any form and output `e^x` instead. * Your answer must have at least 3 correct significant figures. * Approximations are fine, as long as they have at least 3 correct significant figures. * Your code must be in the same programming language both forwards and backwards. Let's say this program implements `ln(x)`: ``` abcโ€ฐฮฉโ€ ร‚โ€ขฮฉ ``` Then this program has to implement `e^x`: ``` \xBD\xA5\xE5\xA0\xBD\xE4cba ``` Gold star if you use a language without float support. This is a weird form of code-golf, so the shortest program wins. [Answer] ## Haskell, 11 bytes ``` f=log pxe=f ``` and in reverse order: ``` f=exp gol=f ``` This works without the "comment" trick. Instead each version defines an additional, but unused function (`pxe`/ `gol`). [Answer] # APL, 3 bytes ``` *โ€šรคยฃโ€šรงรผ ``` This is a function train. Monadic `*` returns `e^x`, monadic `โ€šรงรผ` returns `ln(x)`. `โ€šรคยฃ` is a dyadic function that returns its left argument. Thus, `*โ€šรคยฃโ€šรงรผ` is equivalent to just `*`, and the reverse `โ€šรงรผโ€šรคยฃ*` is equivalent to just `โ€šรงรผ`. [Answer] ## Jelly, ~~5~~ 4 bytes Yay, my first Jelly answer. :) Input is via command-line argument. Jelly [has its own code page](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) so each character is one byte. ``` eโˆšรœโˆšรœl ``` [Try it online!](http://jelly.tryitonline.net/#code=ZcOGw4Zs&input=&args=NQ) Reversed: ``` lโˆšรœโˆšรœe ``` [Try it online!](http://jelly.tryitonline.net/#code=bMOGw4Zl&input=&args=NQ) ### Explanation The `โˆšรœ` on its own is an unrecognised token, so it acts the same as a linefeed. That means in either case the main link is only `โˆšรœl` or `โˆšรœe` which is the 2-character built-in for `exp()` or `ln()` and is by default performed on the first command-line argument. [Answer] ## Javascript, 18 bytes ``` Math.log//pxe.htaM ``` [Answer] ## Seriously, 5 bytes ``` ,_.e, ``` Input, ln, output, then exp on an empty stack (does nothing), and input (does nothing since input is exhausted). [Try it online!](http://seriously.tryitonline.net/#code=LF8uZSw&input=Mi43MTgyODE4Mjg0NTkwNDUyMzUzNjAyODc0NzEzNTI2NjI0OTc3NTcyNDcwOTM2OTk5NQ) Reversed: ``` ,e._, ``` [Try it online!](http://seriously.tryitonline.net/#code=LGUuXyw&input=MQ) [Answer] # Mathematica, 19 bytes ``` 1&#@pxE+0&0+Log@#&1 ``` Reversed: ``` 1&#@goL+0&0+Exp@#&1 ``` This was interesting to golf! Mathematica has *no* line comments / implicit string endings, so I couldn't take the simple route. Instead, I used the fact that `0 + x == x`, `0 x == 0`, and that `1 x == x`, no matter what `x` is! Testing: ``` In[1]:= (1&#@pxE+0&0+Log@#&1)[x] Out[1]= Log[x] In[2]:= (1&#@goL+0&0+Exp@#&1)[x] x Out[2]= E ``` [Answer] # Julia, 7 bytes ``` log#pxe ``` This is an anonymous function. Assign it to a variable to call it. Evaluates to builtins `log` or `exp` plus a comment. [Answer] # Python2, 73 bytes io: stdin/stdout ``` from math import*;print log(input())#))(tupni(pxe tnirp;*tropmi htam morf ``` inverse: ``` from math import*;print exp(input())#))(tupni(gol tnirp;*tropmi htam morf ``` [Answer] ## CJam, 11 bytes ``` rdmle#eemdr ``` [Test it here.](http://cjam.aditsu.net/#code=rdmle%23eemdr&input=5) Reversed: ``` rdmee#elmdr ``` [Test it here.](http://cjam.aditsu.net/#code=rdmee%23elmdr&input=5) Basically the same comment-trick as the OP's Python answer. `e#` starts a comment. `rd` reads the input and `ml` or `me` computes the logarithm or exponential. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` *โ€šร‡ร…โ€šรขยฐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wX@tRU@OjzoX//0cb6hjpGOmZG1oYWYCwiamlgYmpjnEsAA "Brachylog โ€šร„รฌ Try It Online") Initially, I had hoped to use `~*`, but although `*~` computes `e^x` and successfully ignores the trailing tilde, `~*` fails for all integer inputs and hits a float overflow on most non-integer inputs. Forwards: ``` The output โ€šรขยฐ is *โ€šร‡ร… the natural logarithm of the input. ``` Backwards: ``` The output is * Euler's number to the power of the input โ€šรขยฐ passed through the identity predicate โ€šร‡ร… with an extraneous subscript. ``` This uses the identity predicate because, although trailing tildes are tolerated, leading subscripts are not. (If they were, the Brachylog answer would be `*โ€šร‡ร…` alone, which is just the normal builtin for natural log.) [Answer] # Vitsy, 5 bytes This is a program that exits on an error. ``` EL^rE E E Push java.lang.Math.E L Push log_(top) (input) (ln(input)) ^ Push (top)^(input) (e^(input)) r Reverse the stack ``` This program exits on an error with ln(input) on the stack. [Try it online!](http://vitsy.tryitonline.net/#code=RUxOXkU&input=&args=Mi43MTgyODE4Mjg0NTkwNDUyMzUzNjAyODc0NzEzNTI2NjI0OTc3NTcyNDcwOTM2OTk5NQ) (note that I have put `N` to have visible output) Then it's inverse: ``` Er^LE ``` This program exits on an error with e^(input) on the stack. [Try it online!](http://vitsy.tryitonline.net/#code=RXJeTkxF&input=&args=MQ) [Answer] # Fuzzy Octo Guacamole, 7 bytes non-competing, FOG is newer than the challenge ``` EZO@pZE ``` This is the equivalent of a function in FOG. It assumes the input is on the stack. This can be assigned to a function by the code `"EZO@pZE""f"o`, where `f` is any single-char name you want to assign. Then use it like any other command. Example: `"EZO@pZE"'f'o^f`. Explanation: ``` EZO@pZE E # Push E (2.718....) Z # Reverse stack (it is now [e, input]) O # log(x, y) which is ln(input) @ # Exit. (implicit output) Nothing after this gets run. p # x^y (power function) Z # Reverse stack E # Push E. ``` Reversed: ``` EZp@OZE E # Push E (2.718....) Z # Reverse stack (it is now [e, input]) O # x^y (power function) @ # Exit. (implicit output) Nothing after this gets run. p # log(x, y) which is ln(input) Z # Reverse stack E # Push E. ``` [Answer] # Matl, 5 bytes ``` Yl%eZ ``` `Yl`: log `Ze`: exp `%`: comment [Answer] # Pyth, 12 bytes Finds `ln(input())` ``` .lQ) " Q1n.^ ``` Finds `e^input()` ``` ^.n1Q " )Ql. ``` Spaces stop implicit printing of strings, each version calculates it then creates a string with the remaining characters. [`ln(x)` mode here](http://pyth.herokuapp.com/?code=.lQ%29+%22+Q1n.%5E&input=2&debug=0) [`e^x` mode here](http://pyth.herokuapp.com/?code=%5E.n1Q+%22+%29Ql.&input=1&debug=0) [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ, 8 chars / 10 bytes ``` โ€“รบโ‰ˆยจโˆšร˜//โˆšร˜โ‰ˆยถโ€“รบ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=1&code=%D0%9C%C5%AC%C3%AF%2F%2F%C3%AF%C5%A6%D0%9C)``[Try reverse here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=1&code=%D0%9C%C5%A6%C3%AF%2F%2F%C3%AF%C5%AC%D0%9C)` Just 2 builtins separated by a comment. [Answer] # Jolf, 9 bytes Program 1: `exp` of input ``` amoj"jOma a print moj e^j "jOma the rest of the line is captured as a string; implicit printing is restricted. ``` Program 2: `ln` of input ``` amOj"joma a print mOj ln(j) "joma the rest of the line is captured as a string; implicit printing is restricted. ``` Bonus points for being a case-insensitive palindrome? [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=YW1vaiJqT21h) [Answer] # J, 8 bytes The natural logarithm is `^.`, and exponential `^`. The problem is, `.` can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase `^.[^` would cause an error when reversed, as `^[.^` creates an invalid verb. So, we must use comments; but `NB.` is so long :( Fortunately, they both end with `.`, so&ldots there's that. Logarithm: ``` ^.NB.BN^ ``` Exponential: ``` ^NB.BN.^ ``` You can enter them for yourself [online](http://tryj.tk/)! [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 9 bytes ``` i'lA@Ae'i ``` [Try it online!](https://tio.run/##KyrNy0z@/z9TPcfRwTFVPfP/fwA "Runic Enchantments โ€šร„รฌ Try It Online") An ungodly uninteresting program. `@` insures termination of the implied entry point at the left, everything after is unexecuted. I tried really hard to re-use the `'` or `A` instructions, but to no avail, even at larger program sizes. The required explicit entry point for multi-line programs essentially precludes it. [Answer] # Java 8, ~~198~~ ~~182~~ 30 bytes ``` d->Math.log(d)//)d(pxe.htaM<-d ``` [Try it online.](https://tio.run/##NY6xEoIwEER7v@LKpCBUVqh/AA2lY3EmEYIhyZCD0XH49hgVm5vb23m7N@CChQ/aDeqepMUYoUbjXjsA40hPN5Qamo8EUH6@Wg2SbYviVb6vXy@PSEhGQgMOjkkVpxqpF9Z3TPGy5IqFhxY9YX0oVKr@UMhJGdrYxRsFY@5nLU3GdecL8l93@4ykR@FnEiE7ZB1zQrI9335Y0xs) and reversed: ``` d->Math.exp(d)//)d(gol.htaM<-d ``` [Try it online.](https://tio.run/##NY6xEoIwEER7v@LKpCBUVqh/AA2lY3EmEYIhyZCD0XH49hgVm5vb23m7N@CChQ/aDeqepMUYoUbjXjsA40hPN5Qamo8EUH6@Wg2SbYviVb6vXy@PSEhGQgMOjkkVpxqpF/oRmOJlyRXrvBU9YX0oVKr@UMhJGdrYxRsFY@5nLU3GdecL8l93@4ykR@FnEiE7ZB1zQrI9335Y0xs) Uses the comment trick (`//`) with built-ins for `Math.log` and `Math.exp`. ]
[Question] [ One element of the list `aa, ab, ba, bb, c` has been removed, and the remainder shuffled and joined with no separator. Find the missing element. For example, if the input was `aaabbac`, this is made by concatenating `aa ab ba c`, so the output would be `bb`. ## Rules * Standard I/O rules apply. * You must take input as a string (or equivalent in your language), and you must use the characters `abc` as in the question; you cannot substitute them for others. * This is code golf, shortest code in bytes wins. ## Test cases ``` cbbbaab -> aa bbbaabc -> aa cabbabb -> aa baaacbb -> ab bbcaaba -> ab caababb -> ab bbcabaa -> ba abcaabb -> ba abcbbaa -> ba bacaaab -> bb aacabba -> bb caaabba -> bb bbabaaba -> c aaabbabb -> c abaabbba -> c ``` [Answer] # [Python](https://www.python.org), ~~ยฌโ€ 55ยฌโ€ ~~ 51 bytes ``` lambda a:'%x'%(-int(a.replace('c','0c'),16)%255-39) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZBfisIwEIfZR3OKkKUkgVZcRVkFvYj6MDO1GKi1dCvoWXwpyO6d3NPsNGmp-xQ-vt9k_tx_ylt9PBfNI1vvvi91lnw-ZzmcMAUJKx1ddWQSV9QGxtWhzIEORpOO9YS0jT8WNprO58lsaUPp79t7ulZKESICoJTJRgKIQNQjATMOFgCoR-QwcRh69PDfcoFHBAE-jC-ILxaBbTcGouA2becevRuwnck3ZiQRHP8cqDXYOd5v_FXmrjZqVygrsnMlnXSFTFdiVFbtsTLjuojdTvY2lgNO992tmia8fw) Explain: * Observe that 'a', 'b', 'c' are base 16 digits. * I learnt from Albert.Lang's solution that we can use int(a.replace('c',''),x)%(x\*x-1) to extract sum of character at odd and even position. * Replace 'c' with '0c' allow us to subtract by 39 to get 'c' without affecting other output cases (Original idea is to replace 'c' with '33', by xnor). * Finally, '%x'% is used to convert int back to base 16. Logs: * Saved 4 bytes thank to xnor's suggests. # [Python](https://www.python.org), ~~ยฌโ€ 94ยฌโ€ ~~92 bytes ``` lambda a:('c'in a)*''.join(chr(390-sum(map(ord,a.replace('c','')[i::2])))for i in(0,1))or'c' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZDBToQwEIbj0T5FUw9tDRBcL0qyvgiLyUxZsjVQSJc9-CxeSIy-kz6NQwthPTVfvr_9p_PxPbyPp95Nn83-8HUZm_Tp57WFDmvgUChppHUc9L2U2VtvnSrNyavH5zw9XzrVwaB6XyeQ-ePQgjnO-URKXdqi2FVa66b33HK6lycPutK9p0Bs-b25q_dCCIOIAMh5-sIBWCSzogFi3CwAmBWRwobCsGKA_5YuBERgEMJ4hXhlEcguYyAyqpmbVwxuw3mmUExoWHT0cqTZ4OLof9l5aO2oxMEJzdZ18Lpgt4O3blSNsktEl3mlE74hbTDuapri-Qc) Logs: * Saved 2 bytes thank to Jonathan Allan's tip. [Answer] # JavaScript (ES6), 59 bytes ``` s=>(s+"aaabbabbc").replace(q=/c|../g,s=>(q[s]^=1)?o=s:0)&&o ``` [Try it online!](https://tio.run/##TU7BTsMwDL3vK0wOq6O2GVw3ZdMO3HefxpSGtCsKTdaUXYA/QOLCEf6D79kP8AnFCZqEZD372X7PflAnFXTf@qHs3L0ZazkGucSQM6VUVVFoxkVvvFXa4FHO9IsQs6aIS8dt2N3JG75yMsyv@XTqRmsGWIOELZCeFYRVxCrVVao1g91iMlmL2vW3Sh8QfQEdB7mE5wlAdLBtGKLJroANZVQFeMqMpS0lrOma4QArKh@VRzwV0KbRBpWoWzuYHveRt2XJozaHE@eECubJXPincEDPF3Rwg@uLBvcXoxauJD2VFpLg8myIU@264KwR1jXUyIFBuSTIocbAE48EE5OS7q8g@/l@P39@EGb0Q3b@esv4n/1/M2q88vEX "JavaScript (Node.js) โ€šร„รฌ Try It Online") ## Commented ``` s => // s = input string (s + "aaabbabbc") // append all the patterns to s .replace( // replace: q = // we use q as an object to keep track of // encountered patterns /c|../g, // a pattern is either 'c' or 2 characters s => // for each matched pattern s: (q[s] ^= 1) ? // if this is the first time we see it: o = s // save it into o : // else: 0 // do nothing ) && o // end of replace(); return o (i.e. the last // pattern seen for the first time) ``` --- # JavaScript (ES6), 52 bytes Porting [Phan Trยทยชรงng Nhโˆšยขn's excellent answer](https://codegolf.stackexchange.com/a/266576/58563) is definitely shorter. ``` s=>(216-`0x${s}`.replace('c','0c')%255).toString(16) ``` [Try it online!](https://tio.run/##TU7BSgMxEL3vV4yLkgndDW2hPVjS0oP3gkcpbTZm20jcDZtYhNI/ELx41P/we/oDfsKaRApe3rw3M@/NPImDcLLT1pdN@6j6mveOz3E8mpbb4ev10Z22rFPWCKmQSFKQoST0ZjyZUObbe9/pZoejKe2N8rAEDg@QC5EXAauIVeJV4jKH9SzLlqxuuzsh94i2gIYCn8MxA4gJRjsfQ9YFrEJFUYANNc/TlmBGNTu/h0Wgz8IiHgrQabRCwWptvOpwE7UuSxq9AzhQGlDAbQpn9sXt0dJZOLjC5cWDm0uQhisenkoLyXB51sWpbBvXGsVMuwuNAeRQzgMMoEZHk44Ck@I83F8A@fl@P39@BCThB3L@eiP0L/5/WGicaP8L "JavaScript (Node.js) โ€šร„รฌ Try It Online") --- # JavaScript (ES6), 64 bytes My original answer. ``` s=>"b__c__aab"[q=s.replace(/c|../g,s=>'0x'+s|0)%9]+["ab"[q%7%5]] ``` [Try it online!](https://tio.run/##TU5BTsMwELz3FYulKraSuL0gBJVb9cC99yqKNsZpg0xi4lAhUX6AxIUj/IP39AM8IayNKnGZ3dmdmd17PKDXfeOGvO3uzFir0aslq8pSlyVixbaPysveOIva8Jk@SjnbZSRJ5s9J6o9zMb0u0i2LyunV9LIoRmsGWIOCLTBElkFYElaxr2KvGRSLyWQt666/Rb3n3GXQClBLeJkAhATb@CGEFBlsqHLMwFFlLKpQWtPuhj2sqH1Ax/khgyauNhxl3djB9LwMvMlzEbwpHIQgRLiJ4dI9@T13YkEHN3x99vDyHNTAhaKnoiAazs/6sNVd6ztrpO12NEiBQb4kSKHmXkQeCI9MKbq/guTn@/30@UGY0A/J6estEX/x/8No8CrGXw "JavaScript (Node.js) โ€šร„รฌ Try It Online") ## How? ### Identifying the missing pattern We look for the relevant patterns in the input string with `/c|../g` and replace each of them with its decimal value when parsed as hexadecimal. This gives: | original pattern | replaced with | | --- | --- | | aa | 170 | | ab | 171 | | ba | 186 | | bb | 187 | | c | 12 | For instance, `"abbabbc"` is turned into `"17118618712"`. It is a well known fact that \$n \bmod 9\$ is the sum of the decimal digits of \$n\$ modulo \$9\$. (Obviously, the order of the digits doesn't matter.) Because each decimal pattern described above has a different remainder modulo \$9\$, we can identify the missing one by just reducing the entire transformed string modulo \$9\$: | \$q=n \bmod 9\$ | missing pattern | | --- | --- | | 0 | ba | | 3 | c | | 6 | ab | | 7 | aa | | 8 | bb | ### Output We use a 9-character lookup string for the first character: ``` "b__c__aab"[q=...] ``` We could also use the following trick, which is unfortunately just as long: ``` "bac"[7/(q=...)|0] ``` And we use a shorter lookup string with a modulo chain for the 2nd character, wrapped into brackets so that *undefined* is turned into an empty string for \$q=3\$: ``` ["ab"[q%7%5]] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` โˆšฯ€ยฌยขโ€šรฏรฌโ€šรฎรฒ0โˆšร˜<ล’ยฃEZ1 ``` [Run and debug it](https://staxlang.xyz/#p=979bd6d9308b3ce4455a31&i=%22cbbbaab%22&a=1) Unpacked (13 bytes): ``` 'c|^2/M{{SkmT ``` Explanations: ``` 'c|^ Set xor with "c" without deduplication or changing of order. 2/ Split into 2 character chunks. M Transpose (aka zip). {{Skm Map by reduce by xor of the character codes. The two lines work like reducing by vectorized xor. T Trim on the right. For some reasons null bytes are also printed as spaces and are also removed. ``` ~~The difficult part is to find the right language that had all the required features.~~ Many languages have them but they may not be the default behavior of the most obvious operator, so I thought they don't. The most important one is set xor (set symmetric difference) without deduplication. Others are splitting to equally sized chunks, and doing mathematics on character values. But Stax doesn't have map and reduce operators with block starters omitted for a single character operation. # [Vyxal](https://github.com/Vyxal/Vyxal), 87 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), ~~11~~ 10.875 bytes ``` \cโˆšรปโ€šรครงC2ยทโˆซรกโˆ†รญรรฒรงCโ€šร รซยซรง ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiXFxjw57iio1DMuG6h8aS6piNQ+KIkceNIiwiIiwiY2JiYmFhYiJd) Bitstring: ``` 011010100001110110101010000101011001101011111101101001000110111010111001101110101010000 ``` Explanations: ``` \cโˆšรปโ€šรครง Set xor with "c" without deduplication or changing of order. C Convert characters to numbers. 2ยทโˆซรก Split into 2 character chunks. โˆ†รญรรฒรง Reduce by automatically vectorized xor. C Convert back to characters. โ€šร รซ Concatenate. ยซรง Remove non-letters, i.e. the null byte if the answer is "c". ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` ยทโˆรผโ€šร„รนcQp`ยทโˆรผs2$โˆ†โ‰คยปร˜โ€šร„รนc ``` [Try it online!](https://tio.run/##VY4xCsJAEEX7PUUKWxvbgHewtPP/wUZSCFZ2wSbgGRTBWhCCRSBlIHiN3Yuss5ssid2@fX/mz2FfFGfvbfNw5V02x52@TqtFX3/f4cPnrrxly3WmkHeVse3HNrVtnl3VX93ltfVeSALMQgowA0lCgTInC0ASUsOiYSSM8G91ICJhEMOcIWeWUDueQRqtCc0Jo5sw3BSLFcUMTjcPFAxH9wM "Jelly โ€šร„รฌ Try It Online") *Thanks to @JonathanAllan for saving a byte!* A full program taking a string as its argument and printing the missing piece. (It can also be used as a monadic link, but will return a Jelly string if the result is one of the `ab` permutations and a single character for `c`.) ## Explanation ``` ยทโˆรผโ€šร„รนcQp`ยทโˆรผs2$โˆ†โ‰คยปร˜โ€šร„รนc ยทโˆรผโ€šร„รนc | Filter out "c" โˆ†โ‰ค | Following as a monad: Q | - Uniquify p` | - Cartesian product with itself ยทโˆรผ | - Filter out s2$ | - The c-less input split into twos ยปร˜โ€šร„รนc | Or "c" ``` ## Alternative approach: [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` โ‰ˆรฌ^โ€šร„รนcs2โ‰ˆรฌ^"/ ``` [Try it online!](https://tio.run/##VY6xCsIwFEX3fEVwF8G14H@4CPc@XKSbk1txKbi66uLsJA4Fx1L/I/mR@JI0tG45Ofe9@w77uj6FMFx3vrnLca2PxSpUvrnZ5cbqX9W3xn3ernu57tG334s/P7chCEmANqYAk0kKCpQ5WQBSkBoWDaNggn@rAwkJgxTmDDmzhNrxDNJoTWwumNyE8aZUrCgmO92cKRqO7gc "Jelly โ€šร„รฌ Try It Online") This is a translation of [@jimmy23013โ€šร„รดs clever Stax answer](https://codegolf.stackexchange.com/a/266596/42248); Iโ€šร„รดve not replaced my main one since I wanted to preserve my different approach, but this is clearly shorter! `โ‰ˆรฌ^โ€šร„รนcโ‰ˆรญโ‰ˆรฌโ‰ˆรฌ^/โ€šร‡ยจ` would also work for ten. [Answer] # [Python](https://www.python.org), 55 bytes ``` lambda a:f'{int("cc"+(30*a).strip("ab"),16)%255%192:x}' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU5LisJAFNznFI8GsTv2BD9EnUBvPIebl9bGFvtD5wUyDHOBuYKbgDh3mtv4iW6qKOpDnf_iFx2C7y9Gba8tmY_1_-qErt4hYGXG39YTZ1qzCV9McxRFQ8lGzrBmQs6WYjQvy9Hsc151P-NX_de6GBKBpX2iEE4NYHMX2QYUMM1kznFSgwkJUNZg_d0rYgq7VtNzVz7HRfZIOJnrd2SfXEtINviGb0SVAcT0eNdVirHiGKznWkjDuwGUcmJ41PcD3wA) This produces 15 (= base - 1) on frame and (if `c` is present) 15 off frame copies of the input. The sum will therefore be 0 modulo 0x11 x 0x0f. `.strip("ab")` removes one set of on frame copies of all but c. Adding 0xcc which is the sum of the four possible non c terms mod 0xff yields the missing item unless it is c which is dealt with separately. # [Python](https://www.python.org), 57 bytes ``` lambda s:" aabbcbaba"[int(s.replace("c",""),14)%195%8::5] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU5LasMwFNz7FI8HASlVDYEGEoE2uUabxZNiUxXrg_QM6RV6hWwMIb1Tb1Mbt5sZhvkwt-_8ye8pTvfevD1G7p8PP8eBgr0QVI1AZK2zZAlffWRR29LlgVwn0KFClGr3Ije7435z0Hp__hv48iGnwuC5K5zSUIHqLJoTGFh6W0FPFvpUgJQFH2evzSVdRscCyc7DM0jZLImgtu4_0pUwMrFPsYqT1A1ALsurqzaI7UfyUTipenFdwZgg10fTtPIv) ### How? First get rid of the evil frame-shifting "c". Afterwards read as base 14 and add all pairs by reducing modulo 195. Further reduce and produce the answer by indexing into a magic string. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 106 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 13.25 bytes ``` โ€šร„รตab2โ€šรœรฎ\cpยทฯ€รฑ'ยทโˆยฃโ€šร รซ?=;hh ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwi4oCbYWIy4oaUXFxjcOG5lifhuKPiiJE/PTtoaCIsIiIsImFiYWFiYmJhIl0=) Bitstring: ``` 1010100100110111101010010101000011000010000011011100110001101010100111101011100111001010011100110100101110 ``` ## Explained ``` ยฌยดF^ยซรญโ€šรกยฉvยฌยด2ยทโˆซรกยทฯ€รฑ'ยทโˆยฃโ€šร รซ?=;hhยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  ยทฯ€รฑ # โ€šร„รฉโ€šร…ยฐPermutations of ยฌยดF^ยซรญโ€šรกยฉvยฌยด # โ€šร„รฉโ€šร…ยขThe string "aaabbabbc" 2ยทโˆซรก # โ€šร„รฉโ€šร…ยฃsplit into chunks of size 2 ' ; # โ€šร„รฉโ€šร…ยงFiltered by: ยทโˆยฃ # โ€šร„รฉโ€šร…ยขโ€šร…ยฐ the permutation with the head removed โ€šร รซ # โ€šร„รฉโ€šร…ยขโ€šร…ยข joined into a single string ?= # โ€šร„รฉโ€šร…ยขโ€šร…ยฃ equals the input. hh # โ€šร„รฉโ€šร…ยขโ€šร…ยงGet the first item of the first item in that list. ๏ฃฟรผรญรฉ ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [J](https://www.jsoftware.com) 9.4, 25 bytes ``` (]>.&XOR&.dfh _2]\-.)&'c' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNbRc3DwVbK4WUtAwFKz2FjLQULiU99TSQkLqCjoKBghUQ6-opOAf5uC0tLUnTtdipEWunpxbhH6SmB9IbbxQbo6unqaaerA6Rv8XIrsmVmpyRr5CmoJ6clJSUmJikDheA8JMRAsmJQJEkoAqEksTExOQkFD3JQD2JyHoS0fUAlQD1IZQkgvUkoQgkgVUg2QNUguw2oLUgx6DYAxFAsgdkDbIaiBJUm0BCQDWQ8FiwAEIDAA) `dfh` and `hfd` were [recently modified](https://github.com/jsoftware/jsource/blame/32cb7235527fe9132c76a0c054c3992a5fb05975/jlibrary/system/main/stdlib.ijs#L252) to have each other as inverses. ATO doesn't have the change yet. # [J](https://www.jsoftware.com), 26 bytes ``` 12(hfd@>.XOR)_2 dfh\-.&'c' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxy9BIIyMtxcFOL8I_SDPeSCElLSNGV09NPVkdouAWI7smV2pyRr5CmoJ6clJSUmJikjpcAMJPRggkJwJFkoAqEEoSExOTk1D0JAP1JCLrSUTXA1QC1IdQkgjWk4QikARWgWQPUAmy24DWghyDYg9EAMkekDXIaiBKUG0CCQHVQMJjwQIIDQA) The XOR of three of `aa, ab, ba, bb` interpreted as hexadecimal (or any base that is a greater power of 2) is the missing one, and the XOR of all four is zero. When all four are present, the XOR value is replaced with 12 before converting back to hexadecimal. ``` 12(hfd@>.XOR)_2 dfh\-.&'c' input: a string -.&'c' remove 'c' _2 dfh\ convert each chunk of 2 with "hex->int" ( XOR) reduce by bitwise XOR 12 >. max with 12; if the result is 0, use 12 instead hfd@ convert with "int->hex" ``` # [Vyxal](https://github.com/Vyxal/Vyxal), 99 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 12.375 bytes ``` \co2ยทโˆซรกHโˆ†รญรรฒรง12โ€šร ยฅk6ล“ร‘ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBPSIsIiIsIlxcY28y4bqHSMaS6piNMTLiiLRrNs+EIiwiIiwiY2JiYmFhYlxuY2FhYmFiYlxuYWJjYmJhYVxuYmFjYWFhYlxuYWJhYWJiYmEiXQ==) Bitstring: ``` 011010100001111110010011010110100010110000110101011111111011101001101110100010100100100101011011010 ``` Literal translation of the J solution above. ``` \co2ยทโˆซรกHโˆ†รญรรฒรง12โ€šร ยฅk6ล“ร‘ \co remove 'c' 2ยทโˆซรก chunks of 2 H convert each with "hex->int" โˆ†รญรรฒรง reduce by bitwise XOR 12โ€šร ยฅ max with 12 k6ล“ร‘ into base "lower hex digits"; convert with "int->hex" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ยฌโ€ 20 18ยฌโ€ ~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-p%5Bage) -3 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) reminding me to golf the magic table. ``` โ€šร…รฆabp`โ€šร„รนcยทฯ€โ‰ โ‰ˆรญ!F=ยฌโ€ขโˆšรปโ€šร…โˆยทฯ€โ„ขยทฯ€โ„ข ``` A full program that accepts the flattened, redacted permutation and prints the missing item. **[Try it online!](https://tio.run/##y0rNyan8//9R477EpIKERw1zkx/uXHt0kqKb7aGlh@c9atzxcOcqIPr//79SUlJyYlJiohIA "Jelly โ€šร„รฌ Try It Online")** Or see all twenty four of each of the five choices [here](https://tio.run/##y0rNyan8//9R477EpIKERw1zkx/uXHt0kqKb7aGlh@c9atzxcOcqIPr/qGFOYmJiUhIQJQNVFRsdnZxscmgrSOWjpjWH24GEt2bkfwA "Jelly โ€šร„รฌ Try It Online"). #### How? Brute force... ``` โ€šร…รฆabp`โ€šร„รนcยทฯ€โ‰ โ‰ˆรญ!F=ยฌโ€ขโˆšรปโ€šร…โˆยทฯ€โ„ขยทฯ€โ„ข - Link: list of characters, X โ€šร…รฆab - "ab" p` - Cartesian product with itself -> ["aa","ab","ba","bb"] โ€šร„รนcยทฯ€โ‰  - tack 'c' character -> ["ab","ba","bb","aa",'c'] โ‰ˆรญ! - all permutations โˆšรป - sort by: ยฌโ€ข โ€šร…โˆ - last two links as a dyad - f(Permutation, X): F - flatten the Permutation = - equals X (vectorised) ยทฯ€โ„ข - tail -> permutation with matching prefix ยทฯ€โ„ข - tail -> the missing pair - implicit print ``` --- ### Non-brute-force 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-p%5Bage) I quite like this non-brute force method at **21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-p%5Bage)** though (maybe it can be improved upon?)... ``` ยทโˆรผโ€šร„รนcOยทโˆยงโˆšรชoS;ยทโˆยง$%5Qยทยชรฃโ€šร„รบbbaac ``` A full program that accepts the flattened, redacted permutation and prints the missing item. **[Try it online!](https://tio.run/##y0rNyan8///hjvmPGuYm@z/cseTwhPxgayCtomoa@HB396OGOUlJiYnJ////V0pKSk4EspUA "Jelly โ€šร„รฌ Try It Online")** Or see all twenty four of each of the five choices [here](https://tio.run/##y0rNyan8///hjvmPGuYm@z/cseTwhPxgayCtomoa@HB396OGOUlJiYnJ/4HyD3dOO7SECyiSmJgIFExKSgYKFhsdnZxscmjr0UmKbo@a1hxuBxKa7v//KwEVJSclJSkBAA "Jelly โ€šร„รฌ Try It Online"). #### How? ``` ยทโˆรผโ€šร„รนcOยทโˆยงโˆšรชoS;ยทโˆยง$%5Qยทยชรฃโ€šร„รบbbaac - Main Link: list of characters ยทโˆรผโ€šร„รนc - remove any 'c' character O - cast to ordinal values ('a' -> 97, 'b' -> 98) โˆšรชo - apply to odd indices (first, third, ...): ยทโˆยง - double S - sum ;ยทโˆยง$ - concatenate double this value -> [sum, 2โˆšรณsum] %5 - modulo five -> [sum%5, (2โˆšรณsum)%5] Q - deduplicate ยทยชรฃโ€šร„รบbbaac - index into "bbaac" ``` #### Examples: **1. missing "c"** `"aaabbbba"` -> `"aaabbbba"` (removed `'c'`; no change) -> `[97,97,97,98,98,98,98,97]` (cast to ordinals) -> `[194,97,194,98,196,98,194,97]` (double values at odd indices) -> `1170` (sum those) -> `[1170, 2340]` (concatenate double itself) -> `[0, 0]` (modulo five) -> `[0]` (deduplicate) -> `"c"` (index into "bbaac" - Note that indexing is one-based and modular) **2. missing "bb"** `"aaacbba"` -> `"aaabba"` (removed `'c'`) -> `[97,97,97,98,98,97]` (cast to ordinals) -> `[194,97,194,98,196,97]` (double values at odd indices) -> `876` (sum those - i.e. \$1170 - (2 \times 98) - 98 = 876\$) -> `[876, 1752]` (concatenate double itself) -> `[1, 2]` (modulo five) -> `[1, 2]` (deduplicate; no change) -> `"bb"` (index into "bbaac") [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->s{"%x"%(726-s.scan(/c|../).sum(&:hex))} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664Wkm1QklVw9zITLdYrzg5MU9DP7lGT09fU6@4NFdDzSojtUJTs/Z/gUJatHpyYmJiUlKieixXgYJBRbK2QUViIohIAhJJIFZS0n8A "Ruby โ€šร„รฌ Try It Online") `0xaa+0xab+0xba+0xbb+0xc` is 726. [Answer] # [TypeScript](https://typescriptlang.org/)'s Type System, ~~144~~ 142 bytes ``` type F<S,X=0>=S extends`c${infer R}`?F<R,X|"c">:S extends`${infer A}${infer B}${infer R}`?F<R,X|`${A}${B}`>:Exclude<"aa"|"ab"|"ba"|"bb"|"c",X> ``` [Try it at the TypeScript playground.](https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgPAZQDQA0C8AGAfGhUIAewEAdgCYDOABgMYAkA3gJYkBmEATlAEoC+VAfnjdUAHwBENcVgBceQsXLVGLdlwCCvFW05QAQluY6ufQcLFVGmxgaqyAogRoAbAK5kIccQENv4id4ARv7igX4SgcESUqhYALAAUImgkFDEFMAAjFBosF6+QWGR0okA9KVQlQB6Asng0OnAAEw5eZKFhSUJ5ZVQNXWpjQDMrfA+gTS+xfHdFdW1CUA) This is only so long because it has to check for "c" separately because TypeScript annoyingly doesn't let you `infer` part of a string that is a union of strings of variable length. I also have a different idea that might be shorter, but it's not at all obvious how to accomplish it in TS types so it might take me a while to figure out. [Answer] # [Go](https://go.dev), 209 bytes ``` import."strings" func f(s string)string{r,S:=ReplaceAll(s,"c",""),map[string]int{"aa":0,"ab":0,"ba":0,"bb":0} for i:=0;i<len(r);i+=2{k:=r[i:i+2] if S[k]<1{S[k]++}} for k,v:=range S{if v<1{return k}} return"c"} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZLBattAEIaht-ylrzBZMEh4a9KcipwtBNprCbFvrgmzi2QWyWshrUPCoifJxQTyEHmMHtOn6axWInZ60ex--mf0z4yenje7w2uNusRNDls0lpltvWvcjBdbx1_2rvjy7e3PyFrXGLtpOSv2VkORtBBJGoNvxCKTt3ldoc6vqyppBddccJ6KLdarKFob6zxH5NmF4Kj6oOJNhVvHil0DJpMXc3NV5TZp0rmZyktfZrJZmcxML9fMFLBYleurrz6E6bSLWaW4JxFa6mXhSXNPgiZ3-8ZCSZJ4JEtdbOzvp8_usc5hGdrYawfe2FpA_lAPfXWx0TCXJAXPXN66FjIJq_XSM8-1UgqpBwGhoU4QikQfI43E1KkKEfWA1JioKRGPUQ_-V1FyQGqohX2i-oDUB5VCUkWraqhFFoKzY9RrTlHwPhrTY-J7RyMKGnWk6hi7oRG6yiZcSgmL5fXtEujE035Vd8KFQcZlxbl6doa6p0XiZrSKlJ3REndlQOENlXEz2s4czgl66D9QJHzSgvwO9EwmbQoT99uSjb6CCHkiZgmqlEJHzk6Mwc9fP2AwNvwXh0OM_wA) ### Explanation ``` import."strings" func f(s string)string{ // remove "c" from the input. guaranteed to be even length r:=ReplaceAll(s,"c","") // map to keep track of seen pairs S:=map[string]int{"aa":0,"ab":0,"ba":0,"bb":0} // for each pair of chars... for i:=0;i<len(r);i+=2{ // get the pair k:=r[i:i+2] // if pair is not seen yet, increment the counter if S[k]<1{S[k]++}} // for each pair... for k,v:=range S{ // if not seen, return that pair if v<1{return k}} // otherwise return "c" return"c"} ``` [Answer] # [Uiua](https://uiua.org), ~~31~~ 29 bytes Two bytes saved by replacing `"ab"` with `โ€šรครน.` ``` โ€šรครฎโ€šรคยฐโ€šรครณ0โ€šรครชโ€šรคร‰โ€šร รค'โ€šรคร‡โ€šรครด"c"โ€šร ยฉ(โ€šรœร˜~2)โ€šรครปโ€šรครผ.โ€šรครน.โ€šรฑฮฉโ€šรขโ€ @c. ``` [Try it online!](https://uiua.org/pad?src=RmluZE1pc3Npbmcg4oaQIOKKlOKKoeKKlzDiipDiioPiiIon4oqC4oqZImMi4oipKOKGr34yKeKKnuKKny7iip0u4pa94omgQGMuCkZpbmRNaXNzaW5nICJjYmJiYWFiIiAgIyBhYQpGaW5kTWlzc2luZyAiYmJiYWFiYyIgICMgYWEKRmluZE1pc3NpbmcgImNhYmJhYmIiICAjIGFhCkZpbmRNaXNzaW5nICJiYWFhY2JiIiAgIyBhYgpGaW5kTWlzc2luZyAiYmJjYWFiYSIgICMgYWIKRmluZE1pc3NpbmcgImNhYWJhYmIiICAjIGFiCkZpbmRNaXNzaW5nICJiYmNhYmFhIiAgIyBiYQpGaW5kTWlzc2luZyAiYWJjYWFiYiIgICMgYmEKRmluZE1pc3NpbmcgImFiY2JiYWEiICAjIGJhCkZpbmRNaXNzaW5nICJiYWNhYWFiIiAgIyBiYgpGaW5kTWlzc2luZyAiYWFjYWJiYSIgICMgYmIKRmluZE1pc3NpbmcgImNhYWFiYmEiICAjIGJiCkZpbmRNaXNzaW5nICJiYmFiYWFiYSIgIyBjCkZpbmRNaXNzaW5nICJhYWFiYmFiYiIgIyBjCkZpbmRNaXNzaW5nICJhYmFhYmJiYSIgIyBjCg==) Interestingly, since Uiua has an autoformatter that runs during execution, afterwards it is 30 bytes. (Specifically, `'โ€šรคร‡โ€šรครด"c"` is turned into `(โ€šรคร‡โ€šรครด"c")`) ## Explanation ``` โ€šรฑฮฉโ€šรขโ€ @c. # Remove all c from the string โ€šรครปโ€šรครผ.โ€šรครน. # construct "ab" and generate all pairs of its elements โ€šร ยฉ(โ€šรœร˜~2) # Simultaneously: # flatten the table into an array of 2-char strings # chunk the input (sans c) into 2-char strings โ€šรครชโ€šรคร‰โ€šร รค # Both find which of aa,ab,ba,bb are in chunked input... 'โ€šรคร‡โ€šรครด"c" # ...and add c to the array of aa,ab,ba,bb โ€šรครณ0 # Index of pair that was not found (4 if all were found) โ€šรครฎโ€šรคยฐ # Select from aa,ab,ba,bb,c ``` [Answer] # [Uiua](https://www.uiua.org/), 27 bytes ``` ?"c"โ€šรงรบ(-@a)(โ€šรณรธ2/+โ€šรœร˜~2โ€šรฑฮฉ<2.)=8โ€šรŸยช. ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAgPyJjIuKNnCgtQGEpKOKXvzIvK-KGr34y4pa9PDIuKT044qe7LgoKZiAiY2JiYmFhYiIgICMgImFhIgpmICJiYmJhYWJjIiAgIyAiYWEiCmYgImNhYmJhYmIiICAjICJhYSIKZiAiYmFhYWNiYiIgICMgImFiIgpmICJiYmNhYWJhIiAgIyAiYWIiCmYgImNhYWJhYmIiICAjICJhYiIKZiAiYmJjYWJhYSIgICMgImJhIgpmICJhYmNhYWJiIiAgIyAiYmEiCmYgImFiY2JiYWEiICAjICJiYSIKZiAiYmFjYWFhYiIgICMgImJiIgpmICJhYWNhYmJhIiAgIyAiYmIiCmYgImNhYWFiYmEiICAjICJiYiIKZiAiYmJhYmFhYmEiICMgImMiCmYgImFhYWJiYWJiIiAjICJjIgpmICJhYmFhYmJiYSIgIyAiYyIK) **Explanation:** For the cases where 'c' is in the string, this uses a little trick by converting 'a' to 0 and 'b' to 1, then the XOR of the three pairs results in the missing pair. ``` ?"c" =8โ€šรŸยช. # If the string length is 8, return "c" โ€šรงรบ(-@a)( ) # Subtract char 'a' from the string to get an # array where a=0, b=1, c=2. Then perform the # following and add char 'a' back at the end: โ€šรฑฮฉ<2. # Remove any 2s (char 'c') โ€šรœร˜~2 # Reshape to pairs โ€šรณรธ2/+ # XOR by adding the pairs and taking modulo 2 ``` **Example:** Input: "cbbbaab" | Operation | Stack (top on left): | | --- | --- | | | "cbbbaab" | | `โ€šรŸยช.` | 7 "cbbbaab" | | `=8` | 0 "cbbbaab" | | `?"c"` | "cbbbaab" | | `โ€šรงรบ(-@a)(` | [2 1 1 1 0 0 1] | | `โ€šรฑฮฉ<2.` | [1 1 1 0 0 1] | | `โ€šรœร˜~2` | [[1 1] [1 0] [0 1]] | | `/+` | [2 2] | | `โ€šรณรธ2` | [0 0] | | `)` | "aa" | [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~29~~ 23 bytes ``` $ ยฌโˆ‚aaabbbbac D`c|.. 1A` ``` [Try it online!](https://tio.run/##LU4xCoAwENvzDgWngk8QBL/R9HBwcRBH3@UD/NiZOz3KhaRJ2mM9t53eD0v1Ds9NsmlomKtdpWCcqruFxIYPDCaTDsRogc2kE7l/rjsw9RYYSfktHoBS0YBkwmjLgo9nIj/CFw "Retina 0.8.2 โ€šร„รฌ Try It Online") Link includes test cases. Explanation: ``` $ ยฌโˆ‚aaabbbbac ``` Append another copy of the whole list on a separate line. ``` D`c|.. ``` Remove duplicate elements from the copy. ``` 1A` ``` Remove the original input. [Answer] # [Perl 5](https://www.perl.org/) (`-p`), ~~32~~, 29 bytes ``` $_=s/c//?eval s/..\K\B/^/gr:c ``` [Try it online!](https://tio.run/##Vc5BCsIwEIXhfU6RhSuhnZUbRQW3XqEo7w1FhGJLIx7fOEkbWpcf/yQzQzt2uxjE11uRQ9zcj0FU5Nx@0Pkgdd1cm4vc5DHuNUYlCdD76uQBN0kLFWYuFYAW0obVhlGY8V/tQSbhkIe5IleVsDqfQTpbkzYX5rYw3ZQXG9VNzX6elArn9u2H97N/hVh1ww8 "Perl 5 โ€šร„รฌ Try It Online") If `c` can't be removed returns `c` otherwise bitwise xor 2 char strings. -3 bytes thanks to Kjetil S, changing `(?!$)` (negative lookahead end anchor) with `\B` (non-word-boundary) [Answer] # [Java (SE)](https://www.oracle.com/de/java/technologies/java-se-glance.html), 164 bytes `b->{if(b.contains("c"))l:for(var c:"aa ab ba bb".split(" ")){for(int i=0;i<6;i+=2)if(c.contains(b.replace("c","").substring(i,i+2)))continue l;return c;}return"c";}` **[Try it online!](https://tio.run/##VVE9T8MwEN3zK06eYoVaqANDQ1lYWGDpiBjuXBdcXCeynUqoym8PZycU8OD78Lvnd3dHPOPquP@c7KnvQoIjx2pI1qknjB87k9qq0g5jhGe0Hi4V8LE@mXBAbeBlyeSzS8H6d9D14kTZlrexKiYmTFZzhYctTLR6uNhDTUp3PjFzrIUWUrrNoQv1GQPojUAEJCAEIqFi72yqBTDokjGsAez2trX3d61ttmvJbPqXjVQwvWOJmfdGCKniQLEIq@2NbdZSygy2fjDg2mDSEDzodpw9LmrHqZ2V9wM5Vr40cO7sHk78ydLn6xug/DMGFgc/I0gmpkeMBjYgNBFh7qcYDRrZodwfos6WNOcRyr3EVEaQM5RtrmQ8x8zDVZkBSlSGlOHszHGpyB7h/@FdhZadfcVkTqobkupZcXK@vmpuQLDsxit9zcllpfNa53ucvgE "Java (JDK) โ€šร„รฌ Try It Online")** **Formatted:** ``` static Function<String, String> f1 = b -> { if (b.contains("c")) l:for (var c : "aa ab ba bb".split(" ")) { for (int i = 0; i < 6; i += 2) if (c.contains(b.replace("c", "").substring(i, i + 2))) continue l; return c; } return "c"; }; ``` **Logs:** * Golfing tips for I/O defaults respected (lambda function `b`) Thanks @corvus\_192 ! * `String` replaced with `var` at one place (-3 bytes) * `System.out.println`s replaced with `return`s (-31 bytes) Thanks @ceilingcat ! * `return "c";` replaced with `return"c";` (-1 byte) [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->s{a=%w[aa ab ba bb c];a.find{[*(a-[_1]).permutation].join[s]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZBNCsIwGAVx6ymCIqjQgjtBLK68RAjyXrRQwbb0BxHxJG6K6KH0NKZNq9K6CgzD8L5c70nOU3Hzl4888535c-V46RnL0VECAhSEIIVWC7h-EG7PcjqGIzczNXHjXXLIM2RBFCp3HwWhTNXlYjuv3joWvhxokgAHSgwdTwD9ilqoW1TDYHZcAPpL2RS0KaBFK_bXNZWasu6iKrBL2XUJ436uYN01u8rFLVqZHVpeZgeXVDeB5uJfWHr8mPY7i8K-bw) [Answer] # [Python 3.8](https://docs.python.org/3.8/), 82 bytes ``` lambda a:("cbbaa"*469)[(k:=sum(map(ord,(r:=a.replace('c',''))+r[::2])))::k][r==a:] ``` An unnamed function that accepts the flattened, redacted permutation and returns the missing item. **[Try it online!](https://tio.run/##bU@9TsMwEN7zFIeX2BB1AITAklc2nqB0uKQONY1/dHYHFOXZg522KQM3WGd9f/eFn3Tw7uk10Nyrz3lA2@4RUHLWtS0iu39@eRNbfpQqniy3GLinfcNJKtyQDgN2mtdd3dS1EA@0lfJxJ4SQ8rjbklIod3NP3oJJmpL3QwRjg6cEQZM9JUzGu1hVASlFUMBZjmyAYVvedtnbZe@YqKreE1gTo3FfYBwsKllBnkDGJd6zjws6XmiTzLpCKNKSuej@ZHMezthqCKbPvzt1TcptFocySceUz6zrzbc3jhcjsYKk42kocM8L7wZgjLn9iq/ODfTsHc2g98sJY7GbZJaPRT@JbDWeRVMDzqdbK7Z6X4v/J7pUP1PE/As "Python 3.8 โ€šร„รฌ Try It Online")** A port of my non-brute-force [Jelly solution](https://codegolf.stackexchange.com/a/266575/53748). [Answer] # [Python 3](https://docs.python.org/3.8/), 73 bytes ``` b,*l=0,{'c'},{0} for c in input():l[b]^={c};b^=c<'c' print(str(l)[3::10]) ``` [Try it online!](https://tio.run/##LYzRCoMwDEXf@xXii@3wQfFldOuXiEISHApFS9exDfHbu7QOQm5OknvdN8zb2l2dj@95sVPR6ukzkSzLMmJ9saap94qqo96bQzw2X1CxrFzuFaTStsdhNDsdNxwN3flROL@sQT6Dl1b1ndZtM6jIaSoSIgKgOIUEAQ/IDACUFIn3IHL/M98E5D0mTU7@Z@YcdqUEkYk1peWAk7MjTQg/ "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") **71 bytes** ``` b=k=62 for c in input():k^=ord(c)*b;b^=c<'c' print("babbaac"[k%7:][:2]) ``` [Try it online!](https://tio.run/##LYzhCsIwDIT/9ylGQdb6zwkq1T7J2CCJk41JV8pEffqadELp5UvuLn7XcQnHS0z5PU7PoTq44TOQ0Vpn9LM/NeqxpIqqKfCLr9VYN/d@SXdDdo9X7D3daqpVTFNYjUZABCDdzruz61rXdDZzl82EckC1CSkSIzID20WReA@q/H/mm4KyR1FJsp@ZezglDaoQq7SVgo1LQiaEHw "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ 15 bytes ``` โ€šรฅรคโ€šร…ยชโ€šโ„ขโ„ขโ€šร„รน&โ€šร ยฎOโ€šรครฏโ€šร„รนยฌโ‰คโ€šโ„ขโ„ขโ€šร…ยชร”ยบโ‰ฅcยฌโ‰ค ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3My8ztzQXRJcWawQX5GSWaCglJiYmAUFispKOgpGmjgJEGKLEM6@gtCS4BKg5XQMopZSspAlSBATW//8nAXUmJyX91y3LAQA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` โ€šร„รน...โ€šร„รน Compressed string `aaabbbbac` โ€šโ„ขโ„ข ยฌโ‰ค Split into pairs of characters โ€šร…ยช Remove elements from ร”ยบโ‰ฅ Input string โ€šร…ยช c Remove the `c` โ€šโ„ขโ„ข ยฌโ‰ค Split into pairs of characters โ€šรฅรค Take the minimum Implicitly print ``` If all of the `a`/`b` pairs were successfully removed then the only remaining element is the trailing `c` otherwise the minimum element is the missing `a`/`b` pair. [Answer] # Google Sheets, 80 bytes `=substitute(regexreplace("aa|ab|ba|bb|c",regexreplace(A1,"(c|..)","$1|"),),"|",)` Put the input in cell `A1` and the formula in `B1`. Nothing clever here, just two replaces, plus removal of hardcoded separators. Translation to JavaScript (90 bytes, non-competing): ``` s=>(r=(x,y,z)=>x.replace(RegExp(y,'g'),z||''))(r('aa#ab#ba#bb#c',r(s,'(c|..)','$1|')),'#') ``` [Answer] # [J](http://jsoftware.com/), 31 30 29 bytes ``` (e.~{];,@{@;[[emailย protected]](/cdn-cgi/l/email-protection)._2<\-.)&'c' ``` [Try it online!](https://tio.run/##XZAxC8IwEIX3/IrDwSg0QRxblYLg5OSsyF1oURcXB6HQv14vyaVNHTJ8d@/x8u41LKxuYV@ChgI2UPIzFo6X82lYNbbvblVRd3XV18Yae9/ursaul9rpYa1U4x5vaEE7IkIkPQ4iu2ngkCfEikmCiI5mHscezD3472EJ@yYJBg/NBhQUWQ5L8r9xrP/MLCcOshwfk2uiZJ7kR9H2fX60VnIFAHMARCU3SCgXGLexfkRSUj6hVM@3bAhIqKR1hpRtpXBEUlI3oZRNmJp6dCq1FJKGgYYf "J โ€šร„รฌ Try It Online") *-1 thanks to ovs* * `,@{@;~@-.` All valid 2 char pairs, constructed by the crossing the input with itself after removing 'c'. This will contain dups but is guaranteed to have all the valid pairs. * `-.` Minus * `_2<\-.` All 2 char input pairs, formed after removing 'c' + At this point we will either have our answer or the empty list (in the case that 'c' itself is missing) * `];` Prepend 'c' + Now we will have an answer that looks like `c;ab` (in the case we're missing a 2 char sequence) or simply `c` (in the case we're missing 'c') * `e.~{` If 'c' is an element of the input, take the 2nd element. Otherwise take the first (ie, return 'c' itself). ## [J](http://jsoftware.com/), 30 bytes ``` (-.~,&;(,{;~'ab')-._2<\-.)&'c' ``` [Try it online!](https://tio.run/##XZAxC8IwEIX3/IrDoddCE8SxVRfByclZkLtgURcXB0HoX6/X5NKmDhm@u/d4efccVg472DWAUMMaGnnWweF8Og6ldX1dtGX9bXskxsq662Z7sa4q0ONQGXPz9xd0gJ6ZSRTTILKfB55kwqKYJUTkeeHx4qHcQ/8ekYhvllDw8GLAQZHliCT/m8SOn1nkxEGWM8bkmihZJo2jaPs83ohGrwBg90Bk9AYJ9QLTNtaPyEbLJ9Tq@VYMAZmMts6Qs60WjshG6ybUsglT0xG9SS2VtGGg4Qc "J โ€šร„รฌ Try It Online") A similar alternate solution that has unboxed output and no conditional logic. Feels slightly cleaner to me despite being 1 byte longer. [Answer] # [Python](https://www.python.org), 86 bytes ``` lambda s:[*{'aa','ab','ba','bb'}-{*map(str.__add__,*[filter('c'.__ne__,s)]*2)},'c'][0] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZDBasMwDEDZcf4K4x1sh6SMnkah-4xd0hAkp2aG1A2JdxilX7JLYGz_tH3NFDsh3cX205Ml2R_f3Xt4Pfvx0-4PX2_BFk8_Ly2csAE-7MrsIgFkLgFpwemEKK_FJTtBp4bQb-oamqau86y0rg3HXkkjKeiPFBt0lW31NadQVT5Wqfrv3UOzF0IYRARAzotnDsASmQUNEONqAcAsiJRsKBkWjPDf0oWICAxiMt4g3lgEsvMYiIzaTJ0XjG7FaabYmNCw5Khyosng7Oh9m6FrXVDi4IVm9txzx53nzY7dd73zQVnl5hRNf6NzvuK20umvxjHtfw) No magic numbers here, just another approach to solving in Python, this one a straightforward-ish golfing of removing each of the pairs in the string (with `'c'` removed) from the initial set, and if none are left, defaulting to `'c'`. [Answer] # Uiua, 38 characters (62 bytes) `("c";|โ€šรคยขโ€šรฑฮฉยฌยจโ€šร รค,โ€šรคร‰(โ€šรœร˜ยฌร˜1_2โ€šรฑฮฉโ€šร รค,)(/โ€šรคร‡โ€šรครปโ€šรคร‡.)"ab")โ€šร รค@c.` [Uiuapad](https://uiua.org/pad?src=VGVzdERhdGEg4oaQIOKGr8KvMV8yIHJlZ2V4ICJcXHcrIiAkIGNiYmJhYWIgIC0-IGFhCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICQgYmJiYWFiYyAgLT4gYWEKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJCBjYWJiYWJiICAtPiBhYQogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAkIGJhYWFjYmIgIC0-IGFiCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICQgYmJjYWFiYSAgLT4gYWIKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJCBjYWFiYWJiICAtPiBhYgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAkIGJiY2FiYWEgIC0-IGJhCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICQgYWJjYWFiYiAgLT4gYmEKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJCBhYmNiYmFhICAtPiBiYQogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAkIGJhY2FhYWIgIC0-IGJiCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICQgYWFjYWJiYSAgLT4gYmIKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJCBjYWFhYmJhICAtPiBiYgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAkIGJiYWJhYWJhIC0-IGMKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJCBhYWFiYmFiYiAtPiBjCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICQgYWJhYWJiYmEgLT4gYwoKIyBTdGFjayBqdWdnbGluZwojIFNvbCDihpAgKCJjIjt84oqi4pa9wqziiLbiipniiIouL-KKguKKnuKKgi7iiLbihq_CrzFfMuKWveKIiiws4oi2ImFiIiniiIpAYy4KIyBVc2luZyBmb3JrIChzYW1lIG51bWJlciBvZiBjaGFyYWN0ZXJzIGJ1dCBmZXdlciBieXRlcyB1c2luZyBVVEYtOCkKU29sIOKGkCAoImMiO3ziiqLilr3CrOKIiiziioMo4oavwq8xXzLilr3iiIosKSgv4oqC4oqe4oqCLikiYWIiKeKIikBjLgoKIyBUZXN0aW5nIGl0CuKJoSjijaQiV3Jvbmci4omNU29s4oip4oqU4o2Y4oqfKVRlc3REYXRhCgo=) ``` ("c";|โ€šรคยขโ€šรฑฮฉยฌยจโ€šร รค,โ€šรคร‰(โ€šรœร˜ยฌร˜1_2โ€šรฑฮฉโ€šร รค,)(/โ€šรคร‡โ€šรครปโ€šรคร‡.)"ab")โ€šร รค@c.ยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  ( | )โ€šร รค@c. # โ€šร„รฉโ€šร…ยฐIs 'c' a member of the string? "c"; # โ€šร„รฉโ€šร…ยขIf not, just return 'c' โ€šรคร‰ (/โ€šรคร‡โ€šรครปโ€šรคร‡.)"ab" # โ€šร„รฉโ€šร…ยฃElse, generate the list L = ["aa" "ab" "ba" "bb"] โ€šรคร‰(โ€šรœร˜ยฌร˜1_2โ€šรฑฮฉโ€šร รค,) # โ€šร„รฉโ€šร…ยงAnd filter out any the c's from the string (by keeping only members of "ab") and reshape it into a nโˆšรณ2 matrix โ€šรคยขโ€šรฑฮฉยฌยจโ€šร รค, # โ€šร„รฉโ€šร…ยขโ€šร…ยฐReturn the element of L which does not appear in this matrix. ``` [Answer] # [Python](https://www.python.org), 83 bytes ``` lambda a:min({'aa','ab','bb','ba','c'}-{a.replace('c','')[i:i+2]for i in[0,2,4,6]}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZCxasMwEIbpWO3dhRZZ1A4hlFIM6Ut0dDz8J8dE4CjGcYYS8iRdDKV9p_ZpepZski4SH9-vu9N9fLfv_e7gh896vfk69XX28vPWYE8VJPK988lZAzrVID4oHCNafcnOWHTbtoHdJsyp1qZwuXtclfWhk046XyzTVfqUPpcXE0v_3j1Ua6WUJSKApMxeJSAi2RktmOlqAdgZicOWw5gxwH_LDwISBEKYbpBuLIHtNAaR4DZj5xmDu-I4U2jMaEV0XDnSaGhy_L_FsW1cn6iNV0bM25BVLu7bzvk-qRM3RUyxLM20nWGI9x8) * -17 bytes thanks to Neil [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'cK2โˆšยฅH.ยฌยด^12Mhl ``` Port of [*@Bubbler*'s J & Vyxal answer](https://codegolf.stackexchange.com/a/266592/52210), so make sure to upvote that answer as well! [Try it online](https://tio.run/##yy9OTMpM/f9fPdnb6PAWD71Dq@MMjXwzcv7/T05KSkpMTAIA) or [verify all possible I/O test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/9WRvo8NbPPQOrY4zNPLNyPmvoxnzP1opOSkpKTExSUlHCcJIBrKSE4HMJLBYYmJiMoSVlAyUTQTLJsJkgWJAFUBWIlg2CcJKgoglJQLFwCYDzQCZCNELZYFsgBoIEYPqBrGBorEA). **Explanation:** ``` 'cK '# Remove a potential "c" from the (implicit) input-string 2โˆšยฅ # Split it into pairs H # Convert each string-pair from hexadecimal to a base-10 integer .ยฌยด # Reduce this list by: ^ # Bitwise-XORing 12 # Push 12 M # Push the largest value on the stack h # Convert it from a base-10 integer to (uppercase) hexadecimal l # Convert it to lowercase # (after which the result is output implicitly) ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/), ~~67~~ 64 bytes ``` patsplit($0,l,/c|[ab]./){$0="aaabbbbac";for(k in l)sub(l[k],a)}1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5NCoMwEIX3cwoRFwbSaneFUug9xMXLgCCGVqoi9Ock3Qilh_I2nUkMIY83mffNfL6Yu2X5TWOzO66XHuPQ-3bMs9J6W_Crgqv3hXlm5TkF4OSA01Nzu-dd0l4Tb4bJ5b7qagvzPkTOhlvWB2s_HEVhYiHIJXFgVcdSB4V38_JHCHWnqknpZ51OklICBSeqtACIPiTClogr_AE) Removed a semicolon by moving `patsplit` out to the pattern part (-1), and golfed the regex a bit (-2). previous answer, 67 bytes: ``` {patsplit($0,l,/c|[ab]{2}/);$0="aaabbbbac";for(k in l)sub(l[k],a)}1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BCoMwEEX3cwoRFwoWbVcF6arHEBc_A4IYWqlKodaTdBMoPZS36UxiCPn8yfw38_ni2Tv3m6f2cN6uy4BpHGw3pUmZ27zgdw3TLKe1yKqkvMQAjBxwXLX3R9pH3S2y2Tib1NZ9kyNbjwG1E932Yu2HoSBMLAS5JA6saljqIP_uXv4Ivm5UNSn9rNNJUkog70SV5gHB-4TfEmGFPw) * `patsplit($0,l,/c|[ab]{2}/)`: Split `$0` (the input string) into valid chunks and store as a list in `l`. `/c|../` doesn't work because regex matching is done in favor of longer length across all alternatives. * `$0="aaabbbbac"`: Replace `$0` with this fixed string. * `for(k in l)sub(l[k],a)`: For each chunk in `l`, find and remove once from `$0`. An uninitialized variable `a` is used in place of an empty string. * `1`: An all-match pattern. This causes `$0` to be printed as a default action. Replacing **without** splitting `"aaabbbbac"` into chunks first works because * there is only one place to be replaced for `ab` and `ba`, and * for `aa` and `bb`, it doesn't matter which part of the runs is removed. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) โ€šรขยง [v2.21.12](https://github.com/Vyxal/Vyxal/releases/tag/v2.21.12), 14 bytes ``` \cยทโˆซรœยซรญfยฌยดHโ€šร‡ยฅยซรจ3Fยฌยดยซรญโ€šรครง ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBIiwiIiwiXFxj4bqGMnbhuodmwqtI4oK0x48zRsKrMuG6h+KKjSIsIiIsImNiYmJhYWJcbmNhYWJhYmJcbmFiY2JiYWFcbmJhY2FhYWJcbmFiYWFiYmJhIl0=) (code modified to work on current version) I'm using an older version of Vyxal because for some reason `ยซรญ` was modified in a recent version. Also, yes there's another Vyxal answer, but this one's shorter in regular SBCS bytes. ``` ยทโˆซรœ # Split (keeping delimiter) on \c # "c" ยซรญf # Cut each into chunks of length 2 ยฌยดHโ€šร‡ยฅยซรจ3Fยฌยด # Compressed string "abaabbbac" ยซรญ # Cut into chunks of length 2 โ€šรครง # Take the set difference ``` [Answer] # [C#](https://www.microsoft.com/net/core/platform), 93 bytes ``` x=>"aa ab ba bb c".Split().Except(x.Replace("c","").Chunk(2).Select(z=>""+z[0]+z[1])).First() ``` Explanation ``` x => // input string "aa ab ba bb c".Split() // construct array with the four pairs + c .Except( // remove from it... x.Replace("c","") // remove c from input .Chunk(2) // split into chunks of size 2 (each chunk is a char[]) .Select( // transform each item z=>""+z[0]+z[1] // convert char[] to string ) ).First(); // first item remaining. this is c if all pairs were removed ``` [Try it online!](https://dotnetfiddle.net/p1ToID) Uses `.Chunk` which isn't supported on tio.run. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 12 bytes ``` ฦ’รฏ<ฦ’โ‰ โˆšรชโ‰ˆยงย โ‰ฅXH"c"I ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FhuPTLU5svbwhKNLTm2O8FBKVvJcUpyUXAyVXXBzhlJyUlJSYmKSEpcShJEMZCUnAplJYLHExMRkCCspGSibCJZNhMkCxYAqgKxEsGwShJUEEUtKBIqBTQaaATIRohfKAtkANRAiBtUNYgNFIQ4EAA) The `xor` trick is borrowed from [this answer](https://codegolf.stackexchange.com/a/266592/9288) by [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). ``` ฦ’รฏ<ฦ’โ‰ โˆšรชโ‰ˆยงย โ‰ฅXH"c"I ฦ’รฏ Pick one char out from the input string < Check that all remaining chars are less than the picked char If this does not fail, which means the input contains 'c': ฦ’โ‰ โˆšรช Uninterleave the remaining chars into a pair of strings โ‰ˆยง Transpose ย โ‰ฅX Reduce by xor (chars are converted to code points implicitly) H Convert from code points I Otherwise: "c" Return "c" ``` ]
[Question] [ # Final Result The competition is over. Congratulations to `hard_coded`! Some interesting facts: * In 31600 out of 40920 auctions (77.2%), the winner of the first round won the most rounds in that auction. * If example bots are included in the competition, the top nine places won't change except that `AverageMine` and `heurist` will swap their positions. * Top 10 results in an auction: ``` [2, 2, 3, 3] 16637 [0, 3, 3, 4] 7186 [1, 3, 3, 3] 6217 [1, 2, 3, 4] 4561 [0, 1, 4, 5] 1148 [0, 2, 4, 4] 1111 [2, 2, 2, 4] 765 [0, 2, 3, 5] 593 [1, 1, 4, 4] 471 [0, 0, 5, 5] 462 ``` * Tie count (number of auctions that the i-th round had no winner): `[719, 126, 25, 36, 15, 58, 10, 7, 19, 38]`. * Average winning bid of the i-th round: `[449.4, 855.6, 1100.8, 1166.8, 1290.6, 1386.3, 1500.2, 1526.5, 1639.3, 3227.1]`. **Scoreboard** ``` Bot count: 33 hard_coded Score: 16141 Total: 20075170 eenie_meanie_more Score: 15633 Total: 18513346 minus_one Score: 15288 Total: 19862540 AverageMine Score: 15287 Total: 19389331 heurist Score: 15270 Total: 19442892 blacklist_mod Score: 15199 Total: 19572326 Swapper Score: 15155 Total: 19730832 Almost_All_In Score: 15001 Total: 19731428 HighHorse Score: 14976 Total: 19740760 bid_higher Score: 14950 Total: 18545549 Graylist Score: 14936 Total: 17823051 above_average Score: 14936 Total: 19712477 below_average Score: 14813 Total: 19819816 Wingman_1 Score: 14456 Total: 18480040 wingman_2 Score: 14047 Total: 18482699 simple_bot Score: 13855 Total: 20935527 I_Dont_Even Score: 13505 Total: 20062500 AntiMaxer Score: 13260 Total: 16528523 Showoff Score: 13208 Total: 20941233 average_joe Score: 13066 Total: 18712157 BeatTheWinner Score: 12991 Total: 15859037 escalating Score: 12914 Total: 18832696 one_upper Score: 12618 Total: 18613875 half_in Score: 12605 Total: 19592760 distributer Score: 12581 Total: 18680641 copycat_or_sad Score: 11573 Total: 19026290 slow_starter Score: 11132 Total: 20458100 meanie Score: 10559 Total: 12185779 FiveFiveFive Score: 7110 Total: 24144915 patient_bot Score: 7088 Total: 22967773 forgetful_bot Score: 2943 Total: 1471500 bob_hater Score: 650 Total: 1300 one_dollar_bob Score: 401 Total: 401 ``` --- In this game, we will simulate a sealed-bid auction. Each auction is a 4-player game, consists of 10 rounds. Initially, players have no money. At the start of each round, each player will get $500, and then make their own bids. The bid can be any non-negative integer less or equal than the amount they have. Usually, one who bid the highest win the round. However, to make things more interesting, if several players bid the same price, their bid won't be taken into account (thus can't win the round). For example, if four players bid 400 400 300 200, the one bids 300 wins; if they bid 400 400 300 300, no one wins. The winner should pay what they bid. Since it is a "sealed-bid" auction, the only information player will know about the bidding is the winner and how much they paid when next round starts (so player can know how much everyone has). --- # Scoring One auction will be held for every possible 4-player combination. That is, if there are N bots in total, there will be NC4 auction. The bot which wins the most rounds will be the final winner. In the case that there's a tie, the bot which paid the least in total will win. If there's still a tie, in the same way as the bidding, those ties will be removed. --- # Coding You should implement a **Python 3** class with a member function `play_round` (and `__init__` or others if you need). `play_round` should take 3 arguments (including self). The second and third argument will be, in order: the id of winner of the previous round, followed by how much they paid. If no one wins or it is the first round, they will both be -1. Your id will always be 0, and id 1โ€“3 will be other players in an order only determined by the position on this post. --- # Additional rules **1. Deterministic:** The behavior of your function should depend only on the input arguments within an auction. That is, you can't access files, time, global variables or anything that will store states **between different auctions or bots**. If you want to use a pseudorandom generator, it's better to write it by yourself (to prevent affecting others' programs like `random` in Python lib), and make sure you have it reset with a fixed seed in `__init__` or the first round. **2. Three Bots per Person:** You're allowed to submit at most 3 bots, so you can develop a strategy to make your bots "cooperate" in some way. **3. Not Too Slow:** Since there will be many auctions, make sure that your bots won't run too slow. Your bots should be able to finish at least 1,000 auctions in a second. --- # Controller Here's the controller I'm using. All bots will be imported and added to `bot_list` in the order on this post. ``` # from some_bots import some_bots bot_list = [ #one_bot, another_bot, ] import hashlib def decide_order(ls): hash = int(hashlib.sha1(str(ls).encode()).hexdigest(), 16) % 24 nls = [] for i in range(4, 0, -1): nls.append(ls[hash % i]) del ls[hash % i] hash //= i return nls N = len(bot_list) score = [0] * N total = [0] * N def auction(ls): global score, total pl = decide_order(sorted(ls)) bots = [bot_list[i]() for i in pl] dollar = [0] * 4 prev_win, prev_bid = -1, -1 for rounds in range(10): bids = [] for i in range(4): dollar[i] += 500 for i in range(4): tmp_win = prev_win if prev_win == i: tmp_win = 0 elif prev_win != -1 and prev_win < i: tmp_win += 1 bid = int(bots[i].play_round(tmp_win, prev_bid)) if bid < 0 or bid > dollar[i]: raise ValueError(pl[i]) bids.append((bid, i)) bids.sort(reverse = True) winner = 0 if bids[0][0] == bids[1][0]: if bids[2][0] == bids[3][0]: winner = -1 elif bids[1][0] == bids[2][0]: winner = 3 else: winner = 2 if winner == -1: prev_win, prev_bid = -1, -1 else: prev_bid, prev_win = bids[winner] score[pl[prev_win]] += 1 total[pl[prev_win]] += prev_bid dollar[prev_win] -= prev_bid for a in range(N - 3): for b in range(a + 1, N - 2): for c in range(b + 1, N - 1): for d in range(c + 1, N): auction([a, b, c, d]) res = sorted(map(list, zip(score, total, bot_list)), key = lambda k: (-k[0], k[1])) class TIE_REMOVED: pass for i in range(N - 1): if (res[i][0], res[i][1]) == (res[i + 1][0], res[i + 1][1]): res[i][2] = res[i + 1][2] = TIE_REMOVED for sc, t, tp in res: print('%-20s Score: %-6d Total: %d' % (tp.__name__, sc, t)) ``` --- # Examples If you need a pseudorandom generator, here is a simple one. ``` class myrand: def __init__(self, seed): self.val = seed def randint(self, a, b): self.val = (self.val * 6364136223846793005 + 1) % (1 << 64) return (self.val >> 32) % (b - a + 1) + a class zero_bot: def play_round(self, i_dont, care): return 0 class all_in_bot: def __init__(self): self.dollar = 0 def play_round(self, winner, win_amount): self.dollar += 500 if winner == 0: self.dollar -= win_amount return self.dollar class random_bot: def __init__(self): self.dollar = 0 self.random = myrand(1) def play_round(self, winner, win_amount): self.dollar += 500 if winner == 0: self.dollar -= win_amount return self.random.randint(0, self.dollar) class average_bot: def __init__(self): self.dollar = 0 self.round = 11 def play_round(self, winner, win_amount): self.dollar += 500 self.round -= 1 if winner == 0: self.dollar -= win_amount return self.dollar / self.round class fortytwo_bot: def play_round(self, i_dont, care): return 42 ``` **Result** ``` all_in_bot Score: 20 Total: 15500 random_bot Score: 15 Total: 14264 average_bot Score: 15 Total: 20000 TIE_REMOVED Score: 0 Total: 0 TIE_REMOVED Score: 0 Total: 0 ``` The winner is `all_in_bot`. Note that `zero_bot` and `fortytwo_bot` have the same score and total, so they're removed. These bots will not be included in the competition. You can use them if you think they are great. --- The final competition will be held at **2017/11/23 14:00 (UTC)**. You can make any change to your bots before that. [Answer] # hard\_coded ``` class hard_coded: def __init__(self): self.money = 0 self.round = 0 def play_round(self, did_i_win, amount): self.money += 500 self.round += 1 if did_i_win == 0: self.money -= amount prob = [500, 992, 1170, 1181, 1499, 1276, 1290, 1401, 2166, 5000][self.round - 1] if prob > self.money: return self.money else: return prob ``` This bot is the results of genetic training against a lot of other pseudo-random bots (and some of the bots in other answers). I've spent some time fine-tuning at the end, but its structure is actually very simple. The decisions are based only on a fixed set of parameters and not on the outcome of previous rounds. The key seems to be the first round: you have to go all-in, bidding 500 is the safe move. Too many bots are trying to outsmart the initial move by bidding 499 or 498. Winning the first round gives you a big advantage for the rest of the auction. You are only 500 dollars behind, and you have time to recover. A safe bet in the second round is a little over 990, but even bidding 0 gives some good result. Bidding too high and winning could be worse than losing this round. In the third round, most bots stop escalating: 50% of them have less than 1500 dollars by now, so there is no need to waste money on this round, 1170 is a good tradeoff. Same thing in the fourth round. If you lost the first three, you can win this one very cheap, and still have enough money for the next. After that, the average money required to win a round is 1500 dollars (which is the logical conclusion: everyone wins a round out of four by now, bidding less to win later is just wasting money, the situation has stabilized and it's just round-robin from now on). The last round must be all-in, and the other parameters are fine-tuned to win the last round by bidding as low as possible until then. A lot of bots try to win the ninth round by bidding more than 2000 dollars, so I took that into account and try to overbid them (I can't win both the last two rounds anyway, and the last will be harder). [Answer] # Above Average Bids above the average amount of money the other players have. Bids everything in the last round. ``` class above_average: def __init__(self): self.round = 0 self.player_money = [0] * 4 def play_round(self, winner, winning_bid): self.round += 1 self.player_money = [x+500 for x in self.player_money] if winner != -1: self.player_money[winner] -= winning_bid if self.round == 10: return self.player_money[0] bid = sum(self.player_money[1:]) / 3 + 1 if bid > self.player_money[0]: return self.player_money[0] return min(self.player_money[0], bid) ``` [Answer] # I Don't Even ``` class I_Dont_Even: def __init__(self): self.money = 0 self.round = 0 def play_round(self, loser, bid): self.money += 500 - (not loser) * bid self.round += 1 return self.money * (self.round & 1 or self.round == 10) ``` Only participates in odd rounds and the last round. [Answer] The forgetful bot doesn't know how much money he has, so he just puts in the money he was given for this round. If he finds he has some money at the end, he just donates it to a charity. ``` class forgetful_bot: def play_round(self, winner, amt): return 500 ``` [Answer] # One Upper I don't know much about Python, so I might make some kind of error ``` class one_upper: def __init__(self): self.money = 0 self.round = 0 def play_round(self, winner, win_amount): self.money += 500 if winner == 0: self.money -= win_amount self.round += 1 bid = win_amount + 1 if self.money < bid or self.round == 10: bid = self.money return bid ``` bids 1 higher than the previous winning bid, or goes all-in during the last round. I may in the future decide on a different strategy for when `win_amount` is -1 [Answer] # Patient Bot ``` class patient_bot: def __init__(self): self.round = 0 self.money = 0 def rand(self, seed, max): return (394587485 - self.money*self.round*seed) % (max + 1) def play_round(self, winner, amount): self.round += 1 self.money += 500 if winner == 0: self.money -= amount if self.round < 6: return 0 else: bid = 980 + self.rand(amount, 35) if self.money < bid or self.round == 10: bid = self.money return bid ``` Bids nothing for the first five rounds, then bids ~1000 dollars for the next four rounds, and finally bids everything it has in the last round. [Answer] # Copycat Or Sad Third and final bot. This bot will bid exactly the same amount as the previous winner (including itself). However, if it doesn't have enough cash to do so it will be sad, and will bid a measly 1 dollar bill with his tear on it instead. In the final round it will go all-in. ``` class copycat_or_sad: def __init__(self): self.money = 0 self.round = -1 def play_round(self, winner, win_amount): # Default actions: # Collect 500 dollars self.money += 500 # If it was the winner: subtract the win_amount from his money if winner == 0: self.money -= win_amount # One round further self.round += 1 # If it's the final round: bid all-in if self.round == 9: return self.money # Else-if there was no previous winner, or it doesn't have enough money left: bid 1 if win_amount < 1 or self.money < win_amount: return 1 # Else: bid the exact same as the previous winner return win_amount ``` I never program in Python, so if you see any mistakes let me know.. [Answer] # Test run I've edited a previous test run put together by [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox) adding in the newest submissions. I'm posting it here so there is a place where the link can be updated with more recent versions, this post is a community wiki so feel free to update it if you post a new submission, modify an old one, or simply see something new from some other submission! [Here's the link to the test run! (TIO)](https://tio.run/##7Vxtb9s4Ev5c/wouil6lhE4k20nrIAnQvfZuC1zbQ7e7i0MQCLJFx7rqxZDkJtm9/e29Gb5IpEQ5TpPedg8p2tSWhsPhzMPhzJDM6rpa5tn48zwJy5LkGQuiPEnCIpjls6MBIRFbkFUSXgdFvs4i54pe019dfEFIwap1kRF/MBCNF3lxwarFOoG2laVtyZIFJZdxlrGCkjCtTD4Hnqc4rcIqZlml@AhOQRBncRUEnI9sin/w6x7vgZwQz3ycwoCu68fIpQhrSUrGIkrS8EpjJmVxxtPJwfNnk@cHZKhx2mn62sHWLnlCHGBAdonv1l1sGDI8rOyi756AIi2yw3NUjHoTLyQ3cgKjaji1Wg1PZGd6Q623Y3JotpXjbjpiSclMklmMCp4@92C0ghWqUnRDyfjANahVf0KeY946LwxjwYhbI2i6adraxAQaBZVwln9iQfiJFeEFU6CzQcUCE/4IrcWKQCHlzDsnO2RyE3rx/zi7CECSLv/altYOrnbBoDhZyBWJsy7N@cA09HcnZOgrPXWozwTVOZpcE2rQtbmhb6nILjtPdC@tsE6dLol/dO6SfTJG1Kt@kP7Uym7bHuX7NM4cGw3FLlxl9dfByxz8w6tPLDsaPLKZ/NGjlgOQDxoEPLIaOMlLtK@wq8FEzETwB06WV4LOBaigsg3e3PqPHunjFQx2iKOR/YX4tglRDxFd8Xq1YkWvBySbfF0P5G8CdWD3Udv4opb/aZjd6O4E2JoGNbC@2JH0OpGuA1mGyQL0eqPrMNVrqHboD26r2cfkJVuE66Qi4byK86xUj8lfYfll84pjTSzF5aDfDtDg9YLEFbkMS1ItmewRjLGeVQXwVg@VahdFnpJlXJJGL/Y1ZaM1odt3GSNCAYt1AZ0UVi8oqbmMT4WEizgLE9H0iBsqTBJwhHaPNbW5j0b0x@QVrlPke2CDhiSXy7BCdSxBHQlbVEaEoQ1pn4wUAMokvwzKKiwqMdceUPA/RgFO55iLH@WszJ6i9T4xwrJ8fbEUEgpb3oyWlmfYISPQ36k2iu3ghP1gyxRME6@SmEUw9GrJBZ@viwJiUyn6JXtaMG5xWHiVUpy3eQVcXlfIqCSeHHBRylZuB5SauAqW83x1PQ@rIC@CMowegPlHuqfhndzTEJqhBIxrIcvJqmCf4nxd1vrHCbAd@n1NJUpnx1okoVbJ5nVLQr8DdBw0u0JblGHKiDRUS0YdsZqyJVajuKyKeLa@iwct4Znvb5812gGn8xueNOoy@rEEwpPpdGuwgQy6OhzH6BQyQZjIOD12tXYYMGtkSnEpC7OYbZnjdlOUdlhV61B7UeVVmATlCn0War03DJQq7mY2XQFsKYyWu/QaYkNi0@5mU17TO75dO62IBluhqy7gKfhoSGa7DI/RI3vW4DLOKsfhb1WJQGvo7mvs9yfurt@OQDHPAUY0Da8cbdSYW@36VHvindcpwY/L/DJfLDZNMV2FJccKJfj3fNAxyz/AqSBevNvnuqDAdJUXFUnDamnvV/uKeN1F9dNOst9ueeYjqb8d7UjR9g1Ow12DulOzbNLq3Iq2/qJLa5R9rTtab7HprB7lWT2oIoQF2EhmuKD7LVVI6iS/AF8cz@NfGYLU8UFFDlppj5EdSECHzzENFTyHxNs7cOEPvhn6pkPkbRZJnhdOa5A7Ric1OFk5DxPgm13cJVbxHkKVzaEKOh/xNFunM@gJ/O@KFXP0VlWcshIMmIYxYlAIRgm3IsChytFpsQtzNTcKFFqn@/voGqRx/xZ/YuqfGFYm6jM418VKBI6sWYO8L1nR@CPF1yQEpZXb0DUw2rbasU05Fhe6GBVdhNkFc4z@3d4FLD5vF0wkRGJEh0TXoN/BIYMaL5WdEPUiO/J7Sr0Y7dxY621Xh4UUyqLW5riAHRwcUNJaq24qIBvkPcVds@izN8fZgqulC6KNOWekGtY7Dy@yKn4TXil9PmDzm8VmvbpcOU7KhU/NCBIjIBQkPT4xgWUNCCLh@k@asumLJM3LKniRJMHrP1FteKgb@AmAfAf@DclYDet7FlYfluwXzTIPKP9mUZ5eK73avR0O55IK5EMYzSLn13jl1Px0n@pSSMRhlOzkQ7FmrbHiPJFdnZK0OxQ127T04zHGKIxcsIqIkgQj8xCrDuECpIpIvi7UrCKQ1IcQL0AIUebtGYzpj@x7X9u1eCE24t7E2Z8kTjAey23E2@yW3DN6twJnI6ZjfDc3mIZk5GL0L@U0MgZArIslCZPed7/GZLhxUm4ZryDivL3p1FOmtcUctwlkjCADIXNqrEM8u2zKAnaq0VZUY07VPz9bNYBzavRADU6usTtm1iNaaDC1BO2eH/RFcgYp5Vut9xHI1XsscbpK2MN5jvs7z7H5NIavH8f42juoM4Y7aA9HMP6IIxjg5P@gIxizJJx/TGKItdM8ulery/d1B/DyN49iif73/wtMtMe3F0aRoxGBEwJRXCst@Q8o40pQbBAWAfI7Z1CxrAqr@BMLtBltM364rnIQAkjq5agDud16P8Vke6xaK31cLuOEtYhwjXTMR2Kg9QjqUTauqC2@@X0oDaovUe0WUrJBj95tAumTwXivsP/3IrxWct437HltFoPY3/zfm6dRvFjwh949zYEeIGt1crElonE79dorHReVq7F3Auzr4pjN@Zg2tx5aWt9qrt1hqreB1OsWN80Xwxy7/uGUbvDo@/tjJBED3XIKgfyOQEG6U7itikq7B/66qF8L@0EiAE8tbNNhtA2/qH7NDeq6fTPRPnc3zTP4GCzji@WGQ3AtSPEy/1c6BCeZtyK4vpgvzuaY4Y79zeflJFP7gTlb9GCs4qJ1qwe1QSF60R9Y0y4pwanKFOUJPJDfteZhbaoNiUKni/4cyFCGmd90@RpVbImVHwAnP@SFIr1LmeGu4NkmJQDVeH2Jvm3DqNoumbhtFb@nBHmL5O@GzA@85roM8uy2hxy8L02/7jfNsqmp3nb4Bfx6GmaB/@f1Tt4X@46v78pM19F2O1/BN92bL7qUwBh9C8Doq0fYASOBMZo@AONegfHm3dtX/wr@@ep98P7dT29fSrW9/emN@P6jWKYkft5DoJenPeARha62lT@FCXfLLDJKY6oqCN4S0nd7I6f@vEMOx4cTf3w4Go2fTw6fTceed8CLYVgY88nxMTmcuJ3iWt3@9JSMR5x2Bn4yFC13SViLNF/m8ZwpiYqiW6mDh2d1PYuXfGnCMgdph757Xl/7EdWm4N@51HqxFmE2RNfm7tPmMiNXNDQQGncmI3e7fSvLETkD@kO/nT2Jp5alBw@XfMRW5IP45Li9RHsZu6qkTHw5OmnhyrWBf/LsYAPeN/IHqTb2YDRer6KwggA@TMIMrGxTV7exbrjd/rN@alaqvpqznM0cslwmE6KogEU1vmBVLaXn9s1aSbHFNFcbZaofAas9iXaB5xkLqwDPe0JGU1Z5cS13@Zrnsr/zXoFUN44G0g7bNs7xXS2Xpuv9fZtCbRv1mPhyLrtkRDcp0qWeVTJFsUEynaGa26qZu0mo3W1EeqymFllXcRJX14R7EelL5Lvb7EyU3bVa5sYN4qJ4Xu3hIbGP7Lp0xNbfxKVE1xEKC45zzcp2X3KoZxbeZ@KryL7F53aGLin3eNfoNVWH2vwWPk14Eax62cfZ2cjcpkOLg@kZArAXWYShEh0wVPbY1c0Gvg27lk/SOVLCrlYsK1l76D2yQvwiG5jStvHasqSwrwK6ZnEXSyjtQUnbrFNHUGGZHxdA@a05C3wZbrwceF@ZrXHmpTfRsp582SIFNu9D3pyh@v2JWX2fj62LuoR8V8UMWzFzBta7zItq2arcbgwXLLq7yx5hK2HVNd0u6raE1gulHQMZQ7NVSGuCBrPgiGVt72wyfU59z/OoD7Ej9cdTHz4dwNfpyKejAx@@Hh4ewg8gAd7e@VmjiPOercpT1YEVGHi0ma8CgqYpwzbj9Y/G5@6mnexeFM3yWbAMK32CafaFt/QyThKa5LnhPiS/@m4hY1nMAnHLI0jz4hu56nFDJPtw2eNulz0mE6/vugex3/cg9gsfy7CIgnkesehuZ@r7toyiOAriALTYKqbddLfK2EaqmWy8MlXn/KsinyGs8I4HmU4hfPP9Zx7@fA568CfTKfwcPTvEn1N8PvHg@Qi8ByVtx4ErQr0vyxlvf9dTdwaSAjl8nuVVIHedz/hr83eiUPPXnFD9d5VQ87dRUP3XFNDmQj9Vd86pcfeYtq58igOv2tU6Kq@LUXURiGqXLqhxRp82R6KpeSSWmkdJqX5ij2rndETvxtEOau7503oblGobNbQpxNOm@EubWiltqmNUT@OpCmlEz3IZp40npl1vSrUZMoCgb1XgRH36fV7h/Vm8/EieRE/JEx5BKcNiDCWvLy3DcpnEs8EAZ0fE5nHEQPkRpOCJOpiHJNIBSOq9chn6DlgFifZYhr07rru3ZFdRfMHKyoEg3z/EMshIeO4s4YcSBVJbhwEn/H7W0NfcL5DvoSZgmiblGRfgCYm1tDBiCdHf1C/4k/19EFffWgN@g8FbkMDQwqCcgwbrNebtgHs07TtXSrjml2oafVwkOcS5hDemhLcR0xqbGiqUJ1uTUq7AM7QKsFcSnMXnjtuoY5WIcdS1UH3tw9uowk/xT8IpD32qAjS@rynce61ZX09p@EXs2gY2O7hHsmvLCcUurbFGVOlK@L9aznbpQj1HFxkfaQ28VnVBp/2uLiPVj4711p1Tls1ahbqGcexpHl@2ajTodn5hjzjK4eF2sDhMVCvkCEYel4z8jFnIq6LIC2eVnMWtUgUqWSFXrHax1gl/i6Bw5IlmXvFas4ZCRbnEWLuxHWAB4XByIr7559qpJpNwZBCOOWHDuFO0Vc18o9mo1WzcrQE1L0d9FUBTwJsgbA9QFS3VICRklCGTGSPhrIR89UwRn1vO4vI52yVSPRm0EgA1Ja7lNeEAp0XYTIu3eGFBTg18NWte8VIwJW/5oeQjY17NG6pZQ@W3plh90EBQziUlTFrloc6wwA1rKEQ1GEAVIuUWPigNV45YqPg5e8134fqilgVKPvIQKgnTWRSSj0fEGX7k594@Aj6a1PvD61fB@1dv3v386uURLP9lKTQRm5pQIwBQAOBxNnJW8iPwQ5CINzgY7a34ChR6XsFbjQCiOg3/ronD5ShBBTDSasXlYXLfVy6NT4YjryQ/ogZgbRweRuQDqkGtk0612guCLExZEFDByXU/f/4v) [Answer] # Half In This bot always bids half of what it has left, except in the final round where it will go all in. ``` class half_in: def __init__(self): self.money = 0 self.round = -1 def play_round(self, winner, win_amount): # Default actions: # Collect 500 dollars self.money += 500 # If it was the winner: subtract the win_amount from his money if winner == 0: self.money -= win_amount # One round further self.round += 1 # If it's the final round: bid all in if self.round == 9: return self.money # Else: Bid half what it has left: return self.money / 2 ``` I never program in Python, so if you see any mistakes let me know.. [Answer] # Graylist ``` class Graylist: def __init__(self): self.round = 0 self.player_money = [0] * 4 self.ratios = {1} self.diffs = {0} def play_round(self, winner, winning_bid): self.round += 1 if winner != -1: if winner >0 and winning_bid>0: self.ratios.add(self.player_money[winner]/winning_bid) self.diffs.add(self.player_money[winner]-winning_bid) self.player_money[winner] -= winning_bid self.player_money = [x+500 for x in self.player_money] tentative_bid = min(self.player_money[0],max(self.player_money[1:])+1, winning_bid+169, sum(self.player_money[1:])//3+169) while tentative_bid and (tentative_bid in (round(m*r) for m in self.player_money[1:] for r in self.ratios)) or (tentative_bid in (m-d for m in self.player_money[1:] for d in self.diffs)): tentative_bid = tentative_bid - 1 return tentative_bid ``` Inspired by the [blacklist submission by histocrat](https://codegolf.stackexchange.com/a/147835/62393), this bot keeps in memory all the previous winning bets of other players as both the ratio of money they bet compared to their full money and the difference between their bet amount and the full amount. In order to avoid losing to a tie (which apparently is actually a big factor in this competition) it then avoids betting any number that could give the same results given its opponents' current moneys. EDIT: as the starting value for the bid now uses the minimum between: its current money, 1 more than the money of the richest opponent, X more than the last winning bet, or Y more than the average money of its opponents. X and Y are constants that will probably be modified before the end of the competition. [Answer] # AverageMine This player calculates the percentage (bid / total money) for the winner of each round and bids his (total money \* average winning percentage + 85) unless he has more money than all the other players, then he bids 1 more than the highest competitor. Starts with a bid of 99.0% of the starting amount. ``` class AverageMine: nplayers = 4 maxrounds = 10 def __init__(self): self.money = [0] * self.nplayers self.wins = [0] * self.nplayers self.round = 0 self.average = 0 def play_round(self, winner, win_amt): self.round += 1 for i in range(self.nplayers): if i == winner: self.average = (self.average * (self.round - 2) + (win_amt / self.money[i])) / (self.round - 1) self.money[i] -= win_amt self.wins[i] += 1 self.money[i] += 500 if self.round == 1: return int(0.990 * self.money[0]) elif self.round < self.maxrounds: if self.money[0] > self.money[1] + 1 and self.money[0] > self.money[2] + 1 and self.money[0] > self.money[3] + 1: return max(self.money[1],self.money[2],self.money[3]) + 1 bid = int(self.average * self.money[0]) + 85 return min(self.money[0],bid) else: bid = self.money[0] return bid ``` [Answer] # Eenie Meanie More This player is identical to Meanie, except for one variable. This version bids more aggressively and causes some players to spend more than meanie thinks the auction is worth. ``` class eenie_meanie_more: def __init__(self): self.money = [0] * 4 self.rounds = 11 self.total_spent = 0 def play_round(self, winner, winning_bid): self.money = [x+500 for x in self.money] self.rounds -= 1 if winner != -1: self.money[winner] -= winning_bid self.total_spent += winning_bid bid = 500 if self.rounds > 0 and self.total_spent < 20000: bid = int((20000 - self.total_spent)/self.rounds/4)+440 return min(bid, max(self.money[1:])+1, self.money[0]) ``` [Answer] # Distributer When this bot loses a round, he distributes the excess cash among all of the next rounds. He puts in $499 on the first round thinking that the others will tie with $500 and be eliminated. ``` class distributer: def __init__(self): self.money = 0 self.rounds = 11 def play_round(self, winner, amt): self.money += 500 self.rounds -= 1 if self.rounds == 10: return 499 if winner == 0: self.money -= amt return ((self.rounds - 1) * 500 + self.money) / self.rounds ``` [Answer] # Meanie This player takes the total cash that will enter play to get the mean bid across the number of players and remaining rounds. If this target is more than all other players currently hold it lowers its bid to the balance of its greatest competitor plus one. If the player cannot afford its target, it is all-in. ``` class meanie: def __init__(self): self.money = [0] * 4 self.rounds = 11 self.total_spent = 0 def play_round(self,winner,winning_bid): self.money = [x+500 for x in self.money] self.rounds -= 1 if winner != -1: self.money[winner] -= winning_bid self.total_spent += winning_bid bid = 500 if self.rounds > 0 and self.total_spent < 20000: bid = int((20000 - self.total_spent)/self.rounds/4)+1 return min(bid,max(self.money[1:])+1,self.money[0]) ``` [Answer] # Beat the Winner Bid 1 more than the player with the most wins so far ``` class BeatTheWinner: nplayers = 4 maxrounds = 10 def __init__(self): self.money = [0] * self.nplayers self.wins = [0] * self.nplayers self.round = 0 def play_round(self, winner, win_amt): self.round += 1 for i in range(self.nplayers): self.money[i] += 500 if i == winner: self.money[i] -= win_amt self.wins[i] += 1 mymoney = self.money[0] for w,m in sorted(zip(self.wins, self.money),reverse=True): if mymoney > m: return m+1 #if we get here we can't afford our default strategy, so return int(mymoney/10) ``` [Answer] # Minus One ``` class minus_one: def __init__(self): self.money = 0 def play_round(self, winner, amount): self.money += 500 if winner == 0: self.money -= amount return self.money - 1 ``` [Answer] # Bid Higher ``` class bid_higher: def __init__(self): self.dollar = 0 self.round = 0 def play_round(self, winner, win_amount): self.dollar += 500 self.round += 1 inc = 131 if winner == 0: self.dollar -= win_amount if self.round == 10: return self.dollar if win_amount == 0: win_amount = 500 if self.dollar > (win_amount + inc): return win_amount + inc else: if self.dollar > 1: return self.dollar -1 else: return 0 ``` Still learning python; bid a bit higher than the last winner. [Answer] # FiveFiveFive Skips the first round and bids $555 on remaining rounds. In last round, will go all in unless 2 other bots have the same amount (and will presumably tie out). ``` class FiveFiveFive: nplayers = 4 maxrounds = 10 def __init__(self): self.money = [0] * self.nplayers self.wins = [0] * self.nplayers self.round = 0 def play_round(self, winner, win_amt): self.round += 1 for i in range(self.nplayers): self.money[i] += 500 if i == winner: self.money[i] -= win_amt self.wins[i] += 1 if self.round == 1: return 0 elif self.round < self.maxrounds: return min(555, self.money[0]) else: bid = self.money[0] return bid if self.money.count(bid) < 3 else bid-1 ``` [Answer] # Almost All In ``` class Almost_All_In: def __init__(self): self.money = 0 self.round = 0 def play_round(self, loser, bid): self.money += 500 - (not loser) * bid self.round += 1 return self.money - self.round % 3 * 3 - 3 ``` Always bids slightly less than it has. [Answer] # Escalating Quickly Bids increasing fractions of its money each round (please let me know if any errors, a while since I used Python) ``` class escalating: def __init__(self): self.money = 0 self.round = 0 def play_round(self, winner, win_amount): # Default actions: # Collect 500 dollars self.money += 500 # If it was the winner: subtract the win_amount from his money if winner == 0: self.money -= win_amount # One round further self.round += 1 # bid round number in percent times remaining money, floored to integer return self.money * self.round // 10 ``` [Answer] # Below Average Similar to above average, but goes a bit lower ``` class below_average: def __init__(self): self.round = 0 self.player_money = [0] * 4 def play_round(self, winner, winning_bid): self.round += 1 self.player_money = [x+500 for x in self.player_money] if winner != -1: self.player_money[winner] -= winning_bid if self.round == 10: return self.player_money[0] bid = sum(self.player_money[1:]) / 3 - 2 if bid > self.player_money[0]: return self.player_money[0] return min(self.player_money[0], bid) ``` [Answer] # HighHorse This player bids all his money minus the current round number, except on the last round, where he goes all in. ``` class HighHorse: maxrounds = 10 def __init__(self): self.money = 0 self.round = 0 def play_round(self, winner, win_amt): self.round += 1 if 0 == winner: self.money -= win_amt self.money += 500 if self.round < self.maxrounds: return self.money - self.round else: bid = self.money return bid ``` [Answer] # Swapper Alternates between bidding one under his max and going all in. ``` class Swapper: def __init__(self): self.money = 0 self.round = 0 def play_round(self, loser, bid): self.money += 500 - (not loser) * bid self.round += 1 if self.round & 1: return self.money - 1 return self.money ``` I figured I needed to find something that could beat Steadybox's minus\_one. :) [Answer] # Modular Blacklist ``` class blacklist_mod: def __init__(self): self.round = 0 self.player_money = [0] * 4 self.blacklist = {0, 499} def play_round(self, winner, winning_bid): self.round += 1 self.player_money = [x+500 for x in self.player_money] if winner != -1: self.player_money[winner] -= winning_bid self.blacklist.add(winning_bid % 500) self.blacklist |= {x % 500 for x in self.player_money[1:]} tentative_bid = self.player_money[0] autowin = max(self.player_money[1:])+1 if tentative_bid < autowin: while tentative_bid and (tentative_bid % 500) in self.blacklist: tentative_bid = tentative_bid - 1 else: tentative_bid = autowin self.blacklist.add(tentative_bid % 500) return tentative_bid ``` Bets the highest amount it can that isn't congruent modulo 500 to any numbers it's seen before. Edited to not apply the blacklist when it can get a guaranteed win. [Answer] ## Heurist The *Heurist* treats this game as one of repeatable probability, so it knows where to draw the line. It is also miserly, so it bids the bare minimum required for a win when it can. ``` class heurist: def __init__(self): self.money = 0 self.round = -1 self.net_worth = [0] * 4 def play_round(self, winner, bid): self.round += 1 self.money += 500 if winner == 0: self.money -= bid if winner != -1: self.net_worth[winner] -= bid self.net_worth = [x+500 for x in self.net_worth] max_bid = [498,1000,1223,1391,1250,1921,2511,1666,1600,5000][self.round] if self.money > max_bid: return 1 + min(max_bid,max(self.net_worth[1:3])) else: return self.money ``` *Disclaimer: `max_bid` is subject to change* [Answer] # bob\_hater This bot does not like Bob and thus will always bid 2$ to win against Bob. ``` class bob_hater: def play_round(bob,will,loose): return 2 ``` [Answer] ## Showoff This is that guy who shows off his math ability in situations that truly do not require anything so complicated. Until the last round (in which he goes all-in), he uses a logistic model to determine his bid, more if his enemies have a greater portion of their money remaining. ``` class Showoff: def __init__(self): self.moneys = [0, 0, 0] self.roundsLeft = 10 def play_round(self, winner, winning_bid): import math self.moneys = [self.moneys[0] + 500, self.moneys[1] + 1500, self.moneys[2] + 1500] self.roundsLeft -= 1 if winner > 0: self.moneys[1] -= winning_bid if winner == 0: self.moneys[0] -= winning_bid if self.roundsLeft == 0: return self.moneys[0] ratio = self.moneys[1] / self.moneys[2] logisticized = (1 + (math.e ** (-8 * (ratio - 0.5)))) ** -1 return math.floor(self.moneys[0] * logisticized) ``` The logistic curve used is f(x)=1/(1+e-8(x-0.5)), where x is the ratio of current enemy-money to the round's total potential enemy-money. The more the others have, the more he bids. This has the [possible benefit](https://codegolf.stackexchange.com/a/147598/73884) of bidding almost-but-not-quite $500 the first round. [Answer] # AntiMaxer Match the highest amount we can afford of all player's money. Will cause any bot going for all-in on that round to tie out. ``` class AntiMaxer: nplayers = 4 maxrounds = 10 def __init__(self): self.money = [0] * self.nplayers self.wins = [0] * self.nplayers self.round = 0 def play_round(self, winner, win_amt): self.round += 1 for i in range(self.nplayers): self.money[i] += 500 if i == winner: self.money[i] -= win_amt self.wins[i] += 1 return max((m for m in self.money[1:] if m<=self.money[0]), default=0) ``` [Answer] # Simple Bot ``` class simple_bot: def __init__(self): self.round = 0 self.money = 0 def rand(self, seed, max): return (394587485 - self.money*self.round*seed) % (max + 1) def play_round(self, winner, amount): self.round += 1 self.money += 500 if winner == 0: self.money -= amount bid = 980 + self.rand(amount, 135) if self.money < bid or self.round == 10: bid = self.money return bid ``` Almost the same as Patient Bot, but not as patient. Gets a **much** better score than it, though. [Answer] # Wingman 2 If one wingman is good, two must be better ? ``` class wingman_2: def __init__(self): self.dollar = 0 self.round = 0 def play_round(self, winner, win_amount): self.round += 1 self.dollar += 500 inc = 129 if win_amount == 0: win_amount = 500 if winner == 0: self.dollar -= win_amount if self.round == 10: return self.dollar if self.dollar > win_amount + inc: return win_amount + inc else: if self.dollar > 1: return self.dollar -1 else: return 0 ``` ]
[Question] [ # How many petals around the rose How many petals around the rose is a dice game you can play with your friends. Similar to ["can I join the music box"](https://codegolf.stackexchange.com/q/199153/75323), there is a person that knows how the game works and the others have to discover the rule. In this game, someone rolls some dice (usually two or more) and then people have to call "how many petals are around the rose". # Algorithm If you want to play it by yourself, you can [play it over at TIO](https://tio.run/##Zc49CoAwDAXg3VO8sVUH8WcRehjBFAvSlrQOnr5aFRGcQr73AvF7XJzt0kwanuK0BlGyCxTkWOARKDTnoh0jRzD2miE3AKNvVQrdLe9dpdBeQuunNfxb/SlMcWP7YPJsbBTvC2Ko0ctCpnQA). Just hide the header (which is where the rule is implemented) and try passing different arguments (from 1 to 6) in the function. **spoiler, what follows *is* the rule you are invited to find by yourself!** > > The "roses" here are the dice, and the "petals" are the black dots that are *around* a central dot. Because only the odd numbers have a central black dot, only numbers `1, 3, 5` matter for the petals. Those numbers have, respectively, `0, 2, 4` dots around the central dot, the "petals". > > > [![enter image description here](https://i.stack.imgur.com/xuMCB.jpg)](https://i.stack.imgur.com/xuMCB.jpg) # Input Your input will be a non-empty list (or equivalent) of integers in the range `[1, 6]`. # Output The number of petals around the rose. # Test cases [Reference implementation](https://tio.run/##Zc49CoAwDAXg3VO8sVUH8WcRehjBFAvSlrQOnr5aFRGcQr73AvF7XJzt0kwanuK0BlGyCxTkWOARKDTnoh0jRzD2miE3AKNvVQrdLe9dpdBeQuunNfxb/SlMcWP7YPJsbBTvC2Ko0ctCpnQA) in Python, that also generated the test cases. ``` 1, 1 -> 0 1, 2 -> 0 1, 3 -> 2 1, 4 -> 0 1, 5 -> 4 1, 6 -> 0 2, 1 -> 0 2, 2 -> 0 2, 3 -> 2 2, 4 -> 0 2, 5 -> 4 2, 6 -> 0 3, 1 -> 2 3, 2 -> 2 3, 3 -> 4 3, 4 -> 2 3, 5 -> 6 3, 6 -> 2 4, 1 -> 0 4, 2 -> 0 4, 3 -> 2 4, 4 -> 0 4, 5 -> 4 4, 6 -> 0 5, 1 -> 4 5, 2 -> 4 5, 3 -> 6 5, 4 -> 4 5, 5 -> 8 5, 6 -> 4 6, 1 -> 0 6, 2 -> 0 6, 3 -> 2 6, 4 -> 0 6, 5 -> 4 6, 6 -> 0 3, 1, 5 -> 6 4, 5, 2 -> 4 4, 3, 5 -> 6 1, 4, 4 -> 0 5, 5, 2 -> 8 4, 1, 1 -> 0 3, 4, 1 -> 2 4, 3, 5 -> 6 4, 4, 5 -> 4 4, 2, 1 -> 0 3, 5, 5, 2 -> 10 6, 1, 4, 6, 3 -> 2 3, 2, 2, 1, 2, 3 -> 4 3, 6, 1, 2, 5, 2, 5 -> 10 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing! [Answer] # [Python 3](https://docs.python.org/3/), 30 bytes ``` lambda l:sum(n**3&6for n in l) ``` [Try it online!](https://tio.run/##XZPBboMwEETvfIXFoYKISmVtVlEkeuwX9JbmQBujRCIQgSO1Qnw7xVh2p1yQh7Fn3y74/mMuXSvnuvyYm@r2ea5Ecxget6Td7eQT110vWnFtRZPORg9mKJMoOeaZyE@ZeEkzJwiFXAR5odApFqG84OAQphGmEaYRphGmEaZJl0ZeEAoZzkiXFhybxl5wcBSyKWRTyKaQTSGbQrbCpSkvCIUMBIVLC45N23vBwWFkY2RjZGNkY2RjZOPtEHEmtiXEtc2jb780linC/n0YI9LKdX@O85Obetsp0ub8X4k8NOAw/nUv15O0erT5Adi/LdzTZ6VRX47v/UMf4mqIM/FWNcOybjsjFj1F9lKYTNtrsd6JQyTu/bU1SR2PZhLPr2KsE5NOYuyPdlGW@jQJ/X3XX0af43T@BQ "Python 3 โ€“ Try It Online") (test cases shamelessly borrowed from [xnor's answer](https://codegolf.stackexchange.com/a/200407/58563)) ### How? Given \$1\le n\le6\$, the number of petals can be computed with: $$p=n^{2k+1} \operatorname{and}6,\:k\in\mathbb{N}^\*$$ where \$\operatorname{and}\$ is a bitwise operator. This can also be written as: $$p=2\times\left\lfloor\frac{n^{2k+1}\bmod 8}{2}\right\rfloor$$ And is based on the fact that, for any \$k\ge1\$: $$n^{2k+1}\bmod 8=\cases{ n&\text{if $n$ is odd ($1$, $3$ or $5$)}\\ 0&\text{if $n$ is even ($2$, $4$ or $6$)} }$$ More specifically, choosing \$k=1\$: $$p=n^3 \operatorname{and}6$$ As Python code, the resulting expression is just as long as the nice `n%-2%n` [found by xnor](https://codegolf.stackexchange.com/a/200407/58563). But because it ends with a digit, we can get rid of the space just before the `for`, saving a byte. ``` n | n**3 | as binary | AND 6 ---+------+------------+------- 1 | 1 | 00000 **00** 1 | 0 2 | 8 | 00001 **00** 0 | 0 3 | 27 | 00011 **01** 1 | 2 4 | 64 | 01000 **00** 0 | 0 5 | 125 | 01111 **10** 1 | 4 6 | 216 | 11011 **00** 0 | 0 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 11 bytes ``` 5 33 3 33 3 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w35TL2JjLGEz8/29samrEZWZoYgbkGRkZGgEpM0MjUyNTAA "Retina 0.8.2 โ€“ Try It Online") Link includes test cases. Input can be in almost any format really as only the `5`s and `3`s count. Explanation: ``` 5 33 ``` A `5` has as many petals as two `3`s. ``` 3 33 ``` Speaking of `3`s, they have two petals, so make them count twice. ``` 3 ``` Count the petals. [Answer] # [Python](https://docs.python.org/3/), 31 bytes ``` lambda l:sum(n%-2%n for n in l) ``` [Try it online!](https://tio.run/##XZNRa4MwFIXf/RUXoaBgYd7EUArucb9gb10f3BZZwaZFU9gQf7szhmRnvkiOJzn3u1dz/7FfNyPmtn6bu@b6/tlQdxwe18zs9rwz1N56MnQx1OWz1YMd6izJTmVB5bmgp7zwglGIRXAQEp1qETIIFR3GNMY0xjTGNMY0xjTh0zgIRiHiGeHTouPSVBAqOhLZJLJJZJPIJpFNIlvl02QQjEJEgsqnRcelHYJQ0VHIppBNIZtCNoVsCtnUdog4E9cS4rrm0XdfGstUcf8hjhFpxbq/xPmJTb3tFHlz/q9EGRvwGP@6F@tJXj3e/AAqvK38M2TlSV@Pr/1DH9NmSAt6abphWZubpUVPibsUttDuWqx34pjQvb8Ym7XpaCfaP9PYZjafaOxPblHX@jyR/r7rD6s/03z@BQ "Python 3 โ€“ Try It Online") The core expression `n%-2%n` evaluates to zero for even `n` and to `n-1` for odd `n`. ``` | n%-2 n%-2%n -------+-------------- n even | 0 0 n odd | -1 n-1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 4 bytes -3 using [Giuseppe's method](https://codegolf.stackexchange.com/a/200387/53748)! ``` แธ‚ร—โ€™S ``` **[Try it online!](https://tio.run/##y0rNyan8///hjqbD0x81zAz@//9/tLGOgpmOgqGOgpGOgimEjAUA "Jelly โ€“ Try It Online")** ### How? We know that 3's and 5's "score", that they score one less than their pips, and that \$1-1=0\$ so: ``` throw 1 2 3 4 5 6 x=throw - 1 0 1 2 3 4 5 y=throw % 2 1 0 1 0 1 0 score = x * y 0 0 2 0 4 0 ``` So: ``` แธ‚ร—โ€™S - Link: throws, list of integers in [1,6] e.g. [1,2,3,4,5,6] แธ‚ - (throws) % 2 [1,0,1,0,1,0] โ€™ - (throws) - 1 [0,1,2,3,4,5] ร— - multiply [0,0,2,0,4,0] S - sum 6 ``` [Answer] # [R](https://www.r-project.org/), ~~26~~ 23 bytes ``` function(l)l%%2%*%(l-1) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHM0dV1UhVS1UjR9dQ83@aRrKGsY6CERgZgkljTc3/AA "R โ€“ Try It Online") *-3 thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder)!* Returns a 1x1 matrix with the result. --- Old answer, since there are a handful of explicit ports: ``` function(l)sum((l-1)*l%%2) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHs7g0V0MjR9dQUytHVdVI83@aRrKGsY6CERgZgkljTc3/AA "R โ€“ Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~17~~ 16 bytes ``` {sum $_>>ยณX+&6} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V0El3s7u0OYIbTWz2v/WXMWJlQppCtHGOgpmOgqGOgpGOgqmEDL2PwA "Perl 6 โ€“ Try It Online") Uses [Arnauld's formula](https://codegolf.stackexchange.com/a/200429/76162) of \$n^3\&6\$. If HyperWhatevers worked, then something like `(**ยณ+&6).sum` should be possible for 13 bytes. My old regex based solution: ``` {sum m:g/3|5/X-1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyHXKl3fuMZUP0LXsPa/NVdxYqVCmkK0sY6CmY6CoY6CkY6CKYSM/Q8A "Perl 6 โ€“ Try It Online") Match 3s and 5s from the input, subtract one from each and sum them together. [Answer] # [Python](https://docs.python.org), 32 bytes ``` lambda d:sum(r%2*~-r for r in d) ``` Port of [Giuseppe's R answer](https://codegolf.stackexchange.com/a/200387/53748). **[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHFqrg0V6NI1UirTrdIIS2/SKFIITNPIUXzf0FRZl6JRppGtLGOmY6hjpGOKQjHamr@BwA "Python 3.8 โ€“ Try It Online")** [Answer] # [J](http://jsoftware.com/), 9 bytes ``` 1#.2&|*<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jNRqtGys/mtypSZn5CsYKdimKZjpKBjqKJjogBjGEHETkLixjoIRGBmCSaiUoYGCrQJY0gwmYwoh/wMA "J โ€“ Try It Online") * `1#.` Sum of applying the following to each element... * `2&|` Remainder when divided by 2 * `*` Times... * `<:` Number decremented by 1 [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ยณ&6 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=syY2&input=WzMsIDYsIDEsIDIsIDUsIDIsIDVd) Saved 2 bytes using [Arnauld's formula](https://codegolf.stackexchange.com/a/200429/58974) so be sure to `+1` him if you're `+1`ing this. ## Original, 5 bytes ``` fu xร‰ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZnUgeMk&input=WzMsIDYsIDEsIDIsIDUsIDIsIDVd) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 29 28 26 bytes ``` /3|5/{x+=$0-1}END{print+x} ``` [Try it online!](https://tio.run/##SyzP/v9f37jGVL@6QttWxUDXsNbVz6W6oCgzr0S7ovb/f2MuMy5DLiMuUxAGAA "AWK โ€“ Try It Online") *-1 byte thanks to Jo King* *-2 bytes thanks to user41805* `+x` is needed so that inputs with no odd numbers still return 0. [Answer] # [PHP](https://php.net/), ~~55~~ ~~53~~ 51 bytes ``` fn($a)=>array_sum(array_map(fn($v)=>$v%2*~-$v,$a)); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7Py1PQyVR09YusagosTK@uDRXA8LKTSzQAMmVAeVUylSNtOp0Vcp0gEo1rf@nJmfkK6ikaUQb65jGAvkA "PHP โ€“ Try It Online") -2 bytes thanks to @RGS [Answer] # [Haskell](https://www.haskell.org/), 23 bytes ``` f x=sum[n-1|n<-x,odd n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NDc6T9ewJs9Gt0InPyVFIS/2f25iZp5tQVFmXolKbmKBQppCdLSxjoIpGBnF6kSb6SgY6iiY6CgAGcZAPlDSCIwMwSRUyAzGN4WQsbH/AQ "Haskell โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~40~~ ~~33~~ 32 bytes Saved 7 bytes thanks to [RGS](https://codegolf.stackexchange.com/users/75323/rgs)!!! ``` lambda d:sum(i%2*~-i for i in d) ``` [Try it online!](https://tio.run/##XZNBa4QwEIXv/opBKGhxoU5iWBbssb@gt@0ebI1U2HUXzUKL2L9ujSHpqxfJ8yVvvhnN7dt8XjsxN@XbfK4u73VF9WG4X5L2gR9/di01155aajuq09nowQxlEiXHPKP8lNFTmjnBKMQi2AuJTrEI6YUKDmMaYxpjGmMaYxpjmnBp7AWjEOGMcGnBsWnKCxUciWwS2SSySWSTyCaRrXBp0gtGIQJB4dKCY9P2XqjgKGRTyKaQTSGbQjaFbGo7RJyJbQlxbfPo2y@NZYqwfx/GiLRi3Z/j/MSm3naKvDn/VyIPDTiMf92L9SSvHm9@AOXfFu7ps9KoL8fX/q4PcTXEGb1U52FZd1dDi54ieylMpu21WO/EIaJb33YmaeLRTLR7prFJTDrR2B/toiz1aSL9ddMfRtdxOv8C "Python 3 โ€“ Try It Online") This turns out to be a total rip off of [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s Python answer so update him instead. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` Tr[(Mod[#,2]#//.0->1)-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6QoWsM3PyVaWccoVllfX89A185QU9cwVu1/QFFmXomCQ7pDtbGOgpmOgqGOgpGOgimErP3/HwA "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 20 bytes ``` a=>a.Sum(x=>x--%2*x) ``` [Try it online!](https://tio.run/##ldQxa8MwEIbhPb/CS8EuccAn3S2JvRQ6ZevQORgHBK0CsUMNpb/dxQnt/N5y0ydxPEhfP9b9mJbXW@4PxzROh5Snblusszi3y6ntTru322c5t91c10/yPFfLfrN5ueTx8jHs3q9pGo4pD@W5zMNX8X/Fd7Mtmp@q2rOo8Gjg0cijyqMGo8IFhAsIFxAuIFxAuEDgAoELBC4QuEDgAoELRC4QuUDkApELRC4QuYByAeUCygWUCygXUC5gXMC4gHEB4wLGBczXA67Hpb6/4Krv6HsPrk0aV@H5yiG4BH2fWVx7@1jszrI2hqu35bHVfTqO2d8Zfcz15PIL "C# (Visual C# Interactive Compiler) โ€“ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~50~~ 48 bytes Saved 2 bytes thanks to [xibu](https://codegolf.stackexchange.com/users/90181/xibu)!!! ``` s;f(l,p)int*p;{for(s=0;l--;)s+=*p%2*~-*p++;l=s;} ``` [Try it online!](https://tio.run/##Xc/dCoIwFAfw@57iEATbPCPdh10MexHrIgwjMBu5O7FXt@XSWjDG4H/O75xV/FJV49iZmjRo6bV1zJq@vj9IV6Sm4dzQLimY3Qj25MwmiWmKzgzj7XRtCe1XvgFcVspj0SsEgZANBrYMUmDblX34uCbrTwJ8D5vzoV0j1ESiyyg1ARCl8oBE0NMRwcgi5JtGjkInFkeWuXdyPwvBD/UPGSjxK0V5hGl0csHUhMlpdzG1iMVTf5tFJRGZo1MLqctdIPO5WId7/nCs/ldF8A6dfsPD@AI "C (gcc) โ€“ Try It Online") Inputs an integer array pointer preceded by its length. [Answer] # [Java (JDK)](http://jdk.java.net/), ~~47~~ 45 bytes ``` r->{int s=0;for(int i:r)s+=i%2*~-i;return s;} ``` First time code golfing, hope I posted this right. -2 Bytes by removing unneeded curly brackets [Try it online!](https://tio.run/##VZDLTsMwEEXX7VdcRUKKyUMVEpua8Ad00yViMXHTyiV1KtspQpX59TB2KIjN3Hkce0b3SBeqjrv3SfXkHF5Im@sS0MZ3dk@qwyaWqQGVc3x9gxaSe2HJYQODZrLV8zUCrlnJ/WAjBr22whWNvnu4/6q0tJ0frYGTYZLx4Xlse63gPHmWy6B3OPHufOutNgdeQvbgxLz79iWhwUqCigJPDR6lSNOZ@aPamWr/U5Fb3BCVEJUIBngCbD@d7071MPr6zCf43uSEAlmZcWx/MxWzNTKwmu4jGZaL2tQqj@Vs0BVUoi0ZDoK9WoSfE2YNybwwfQM "Java (JDK) โ€“ Try It Online") [Answer] # TI-BASIC, ~~13~~ 12 bytes I found some 12 byte solutions ``` Ans-1:sum(Ansnot(fPart(Ans/2 ``` The previous is the same byte count as below due to the line separator costing a byte ``` sum((Ans-1)2fPart(Ans/2 ``` The above solutions use NfPart(Ans/N as a modulus operation to judge even/odd, giving us a list of dice that can have petals. Multiplying that by the original list -1 restores the petal counts to the list which can then be summed ``` 2sum(Ans=3)+4sum(Ans=5 ``` The original 13 byte solution simply compared the list once against 3 and separately against 5 before summing those results independently to get the petal count All the above solutions take input as a list in Ans [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~66~~ ~~60~~ ~~44~~ 42 bytes *Two bytes saved by [Jo King](https://codegolf.stackexchange.com/users/76162)* ``` ({(({}[()])<>)<>{<({}[()])><>([{}])<>}{}}) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo1pDo7o2WkMzVtPGDoiqbWBcOxs7jejqWpB4bXVtreb///9N/xv9NwaShgA "Brain-Flak (BrainHack) โ€“ Try It Online") This challenge seems to ellude a straight forward solution in Brain-flak. It was quite fun to golf. [Answer] # [Julia 1.0](http://julialang.org/), ~~23~~ 16 bytes ``` l->sum(l.^3 .&6) ``` [Try it online!](https://tio.run/##XZLBaoUwEEX3fsWsioJ9NJNkeBtLP6I7sVDos1ishRqhf2@NIdPbuBBvbubmzJiPbZ5ezc8@dvt8/7hun/V8ebF0uZNmD7c1rF1d1b1pyQwtPTRtEozCHoKzcOj4Q7gsRB3GNMY0xjTGNMY0xjSb0jgLRmG1xqY0dWKaZCHqOGRzyOaQzSGbQzaHbD6luSwYhVUCn9LUiWnXLEQdQTZBNkE2QTZBNkE2KYeIM4ktIW5sHv34p/EYr/uvOkakted@g/OzxXnlFLmo/zvCaAMJ41/39qzk0@PiAkhe9emds5pqW6flnZ6PC1@NX98UaFrovP4VHc9T/KSxDr0ZGuo6Cj0P1W15238B "Julia 1.0 โ€“ Try It Online") -7 Bytes thanks to [Maria Miller](https://codegolf.stackexchange.com/users/92689/maria-miller) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes ``` ร‰ร<O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cOfhfhv///@jjXUUzHQUDHUUjHQUTCFkLAA) *-7 byes thanks to Expired Data* *-1 byte thanks to Grimmy* As promised, someone who knows 05AB1E better than I came and golfed it somehow. ## 11 bytes ``` ฮต2%}Iฮต1-}*O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3FYj1VrPc1sNdWu1/P//jzbWUTDTUTDUUTDSUTCFkLEA "05AB1E โ€“ Try It Online") I'm sure someone who knows 05AB1E better than I do will come along and golf this somehow. Really simple: ``` ฮต2%} # Map the code 2% (mod 2) to each element of the implicit input Iฮต1-} # Map the code 1- (sub 1) to each element of the explicit input *O # Multiply the two lists and sum ``` [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 15 bytes ``` $\+=$_%2*$_&6}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWJV7VSEslXs2stvr/f2MuMy5DLiMuUxD@l19QkpmfV/xftyAHAA "Perl 5 โ€“ Try It Online") Takes the input list as one entry per line. [Answer] ## [Roj](https://github.com/RojerGS/Roj), ~~134~~ ~~92~~ ~~88~~ ~~86~~ 65 bytes Considerably easier than the previous challenge. Takes numbers in separate lines and end input with the input `0`. Outputs via return value. (Dramatically saved 42 bytes by using dynamic input) ``` O=0;i=1;while i do readint i;if i==3 or i==5 do O=O+i-1 end end;O ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytesSBCS ``` +/โŠข|ยฏ2|โŠข ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1v/UdeimkPrjWqA9P@0R20THvX2Peqb6un/qKv50HrjR20TgbzgIGcgGeLhGfw/TcFQwVjBVMEEiI250hTMFIzA0FjBBAA "APL (Dyalog Unicode) โ€“ Try It Online") A port of [xnor's double modulo trick](https://codegolf.stackexchange.com/a/200407/78410). ### How it works ``` +/โŠข|ยฏ2|โŠข ยฏ2|โŠข โ Input modulo -2; 0 if even, -1 if odd โŠข| โ That modulo input; 0 if even, n-1 if odd +/ โ Sum ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytesSBCS ``` 2โˆ˜|+.ร—-โˆ˜1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@hRx4wabb3D03WBDMP/aY/aJjzq7XvUN9XT/1FX86H1xo/aJgJ5wUHOQDLEwzP4f5qCsYIxV5qCoYKRgomCGZBlCmSZAtnGAA "APL (Dyalog Unicode) โ€“ Try It Online") ### How it works ``` 2โˆ˜|+.ร—-โˆ˜1 -โˆ˜1 โ Decrement input +.ร— โ Dot product with 2โˆ˜| โ Input modulo 2 ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 13 bytes ``` {+/(2!x)*x-1} ``` [Try it online!](https://tio.run/##Lc87DoMwEEXRrThVIBGKPL8i7IeGghYJZe2OLjPNK3zm53059jG27/X@TPI459e59N/YnlNvfW29CaGEEU7E2gQVVFBBBRVUUUUVVVRRRQ011FBDDTXUUUcdddRRRwMNNNBAA43am3O8pue9VjPysedxdYVmQ@2XtKqNuzfyCwLmb/UWoaj5PP4 "K (oK) โ€“ Try It Online") Essentially same as [Jonah's J solution](https://codegolf.stackexchange.com/a/200395/75681) [Answer] # [W](https://github.com/A-ee/w), 5 [bytes](https://github.com/A-ee/w/wiki/Code-Page) ``` โ–บSโ‰ก5u ``` Uncompressed: ``` (S2m*J ( % Decrement input S % Swap a copy of the input up 2m % Modulo the value by 2 * % Multiply them J % Find their sum ``` ``` [Answer] # [Icon](https://github.com/gtownsend/icon), 50 bytes ``` procedure f(a) n:=0&n+:=!a-1=(2|4)&\z return n end ``` [Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNI1GTK8/K1kAtT9vKVjFR19BWw6jGRFMtpoqrKLWktChPIY8rNS8FSUtuYmaehiaXAhCUF2WWpGqkaUQb6iiYxmpiCppgCBoDVYKREYaUmY4CSIuOApBhjE0jRIERRDvURpDbAA "Icon โ€“ Try It Online") ## Explanation: ``` procedure f(a) # the argument a is the list n:=0 & # sets the sum to 0 and n+:=!a-1=(2|4) & # add to n (n+:=) each element of a decreased by one (!a-1), # if it now equals 2 or 4 (=(2|4)) and \z # loop (in fact checks if a variable z exists - since it # doesn't, backtracks to get the next element of a, if any) return n # returns the sum end ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 8 bytes A port using Arnauld's formula. ``` โŒ 3โฟ6&โŒกMฮฃ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9RzwLjR437zdQe9Sz0Pbf4//9oQx0jHeNYAA "Actually โ€“ Try It Online") [Answer] # Excel, 34 bytes ``` =SUMIF(A:A,3)/3*2+SUMIF(A:A,5)/5*4 ``` `SUMIF` does much of the work for us. Feel like there should be a solution using `SUMPRODUCT`, but have not found it yet. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes ``` psf{2.%}?d++ ``` [Try it online!](https://tio.run/##VZG7DoJAEEV7v4KQGAvByOzshGQT/AMbS7UxYizQ@AiV4dvRmcUrNuTmsmfODhzaR1M/723dN9fLa5aFsNumeZWGkO/72/P0osW0Wx3n835z7tp1X2RJkeRVspx8EiE5TaSJ0XlNrEliR2AJLIElsASWwLqBJU2E5OI5N7DWGSuaJHYML8PL8DK8DC/D6weWNRGSiw4/sNYZW2qS2Am8Aq/AK/AKvPK3L1bRi8GuN8cb/eCY43/HSlsafmfHCizsxqP/1qYxMxpY2DWj7reDM4DsBY3/hnwrH59xxBs "Burlesque โ€“ Try It Online") ``` ps # Parse input to array f{2.%} # Filter for mod2 == 1 ?d # Decrement each ++ # Sum ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/4944/edit). Closed 7 years ago. [Improve this question](/posts/4944/edit) Your challenge, should you choose to accept it, is to create a function or a program that outputs "yes" if a given number is divisible by 13 and outputs "no" if it isn't. **Rules:** - You're not allowed to use the number 13 anywhere. - No cop-out synonyms for 13 either (like using 15 - 2). - Bonus points will be awarded for not using modulus, additional bonus for not using division. **Scoring:** - Your score will be the number of bytes in your code (whitespace *not* included) multiplied by your bonus. - If you didn't use modulus, that bonus is 0.90; if you didn't use division, that bonus is 0.90. - If you didn't use either, that bonus is 0.80. - The lower your score, the better. The input will always be an integer greater than 0 and less than 2^32. Your output should be a simple "yes" or "no". **Clarifications:** - Using some roundabout method of generating the number 13 for use is acceptable. Simple arithmetic synonyms like (10 + 3) are not allowed. - The function or program must *literally output* "yes" or "no" for if the given number is divisible by 13. - As always, clever solutions are recommended, but not required. [Answer] ## Java (score 60.8 59.2) ``` void t(int n){System.out.print(Math.cos(.483321946706122*n)>.9?"yes":"no");} ``` Score: (76 - 2 whitespace) chars \* 0.8 = 59.2 [Answer] **ASM - 16 bit x86 on WinXP command shell** executable - 55 bytes \* 0.8 = 44 source - 288 characters \* 0.8 = 230.4 The number 13 doesn't even appear in the assembled .com file. Assemble using A86. ``` mov si,82h xor ax,ax xor cx,cx a: imul cx,10 add cx,ax lodsb sub al,48 jnc a inc cx h: mov dl,a and 255 c: loop g sub dl,a and 255 jz e mov dl,4 e: add dl,k and 255 mov dh,1 mov ah,9 int 21h ret g: inc dl cmp dl,c and 255 jne c jmp h k: db 'yes$no$' ``` [Answer] # Python 3.x: 54 \* 0.8 = 43.2 It may be a cop-out to have a string of length 13, but here it goes: ``` print('no' if any((' ' * int(input())).split(' ')) else 'yes') ``` It works by building a string of n spaces (the choice of delimiter is arbitrary, but I chose space for obvious reasons), and splitting away 13-space substrings until you're left with a string containing n%13 spaces. [Answer] ## GolfScript, 32 chars ``` ~){.14base{+}*.@<}do('no''yes'if ``` I wanted to try something different from everyone else, so my solution calculates the base 14 [digital root](http://en.wikipedia.org/wiki/Digital_root) of the number, by repeatedly converting the number to base **14** and summing the digits until the result no longer gets any smaller. This is essentially the same as calculating the remainder modulo 13, except that the result will be in the range 1 to 13 instead of 0 to 12. Since checking whether the digital root equals 13 would be difficult without using the number 13 itself (or some lame workaround like 12+1), what I actually do is I increment the input number by one before the loop and decrement the result afterwards. That way, the result for numbers divisible by 13 will in fact be zero, which is much easier to check for. Here's a commented version of the program: ``` ~ # evaluate the input, turning it from a string to a number ) # increment by one { # start of do-loop . # make a copy of the previous number, so we can tell when we're done 14 base # convert the number to base 14 { + } * # sum the digits . @ < # check if the new number is less than the previous number... } do # ...and repeat the loop if so ( # decrement the result by one 'no' 'yes' if # output 'no' if the result is non-zero, 'yes' if it's zero ``` This program will actually handle *any* non-negative integer inputs, since GolfScript uses bignum arithmetic. Of course, extremely large inputs may consume excessive time and/or memory. The code does not use either modulos or division directly, although it does use GolfScipt's base conversion operator, which almost certainly does some division and remainder-taking internally. I'll leave it for GigaWatt to decide whether this qualifies me for the bonus or not. [Answer] ## C, 68 \* 0.8 = 54.4 After 24 answers, no one came up with this obvious algorithm yet: ``` f(x){puts("no\0yes"+3*((x*330382100LL>>32)-(~-x*330382100LL>>32)));} ``` [Answer] ## JavaScript (27.9) Current version (31 characters \* 0.90 bonus = 27.9). ``` alert(prompt()*2%26?'no':'yes') ``` Demo: <http://jsfiddle.net/9GQ9m/2/> **Edit 1:** Forgo second bonus by using modulus to lower score considerably and avoid `for` loop. Also eliminate `~~` and save two chars (thanks `@copy`). --- Older version (48 characters \* 0.80 bonus = 38.4) ``` for(n=~~prompt()*2;n-=26>0;);alert(n?'no':'yes')โ€‹ ``` [Answer] ## BrainFuck Score: 200 \* 0.8 = 160 ``` >++++++[>++++++++<-]>>,[<[-<+>>-<]<[->+<]>>>[->++++++++++<]>[-<+>]<<[->+<],]++++ +++++++++>[>+<-<-[>>>]>>[[-<<+>>]>>>]<<<<]>[<<<[-<++>]<++++++++++++++.+.>]<<[[-< ++++++<++++++++>>]<-----.<---.>------.>] ``` Reads froms stdin. Probably not the most clever solution, but getting anything that works in BF is nice. It's quite compact though. [Answer] **Scala (38 \* 0.9 = 34.2)** Similar to `0xD`(hex) or `015`(oct). **ASCII** value of `CR` is 13. ``` def t(n:Int)=if(n%'\r'==0)"yes"else"no" ``` [Answer] ## Haskell, 28 \* 0.8 = 22.4 ``` f x|gcd 26x>2="yes"|1<3="no" ``` [Answer] Python: ``` f=lambda n:1==pow(8,n,79) ``` E.g. ``` [i for i in range(100) if f(i)] ``` gives ``` [0, 13, 26, 39, 52, 65, 78, 91] ``` [Answer] ## C, 54.4 == 68 \* .8 ย  80 \* .8 ``` char*f(c){char*s=" yes\0\rno";while(c&&*s++);return c>0?f(c-*s):++s;} ``` [Answer] ### ECMAScript 6, 25 ร— 0.9 = 22.5 Yeah, it's a boring way of getting 13. ``` n => n % ' '.length ? 'no' : 'yes' ``` [Answer] ## APL ((21 - 1) ร— 0.8 = 16) ``` 'yes' 'no'[1=โŽ•โˆจโŒŠโŸ9*6] ``` `โŽ•IO` should be set to 0 for this to work properly in Dyalog APL. To generate 13, we take the floor (`โŒŠ`) of the natural logarithm (`โŸ`) of 9 to the power of 6 (`9*6`). After that, we find the GCD (`โˆจ`) of our input (`โŽ•`) and 13, and we then test if that equals 1. This is used to index (`[...]`) the vector of answers. If anyone wants to be pedantic about the mention of *bytes* in the scoring specification, the score for the UTF-8 encoded version of this is `(29 - 1) ร— 0.8 = 22.4`. :) [Answer] ## C, 88 Fibonacci trick. ``` f(n){return n<2?n:f(n-1)+f(n-2);}main(x){printf("%s",x%f(7)?"No":"Yes",scanf("%d",&x));} ``` [Answer] ## Perl - 44 ร— 0.8 = 35.2 ``` #!perl -p map$_+=4*chop,($_)x10;$_=chop^$_*3?'no':yes ``` Counting the shebang as one byte. I'm a bit late to the game, but I thought I'd share the algorithm, as no other posts to this point have used it. This works under the observation that if *n* is divisible by *13*, then โŒŠ*n/10*โŒ‹+*n%10\*4* is also divisible by *13*. The values *13*, *26* and *39* cycle onto themselves. All other multiples of *13* will eventually reach one of these values in no more than *log10 n* iterations. --- **In Other Bases** Admittedly, `chop` is a bit of a cop-out. With a base 10 representation, it's equivalent to `divmod`. But the algorithm works prefectly well in other bases, for example base 4, or 8. Python style pseudo-code of the above algorithm (base 10): ``` def div13(n): while n > 40: q, r = n // 10, n % 10 n = q + 4*r return n in [13, 26, 39] ``` In base 2: ``` def div13(n): while n > 40: q, r = n >> 1, n & 1 n = q + 7*r return n in [13, 26, 39] ``` In base 4: ``` def div13(n): while n > 40: q, r = n >> 2, n & 3 n = q + 10*r return n in [13, 26, 39] ``` In base 8: ``` def div13(n): while n > 40: q, r = n >> 3, n & 7 n = q + 5*r return n in [13, 26, 39] ``` etc. Any base smaller than 13 works equally well. [Answer] ## Javascript: 59\*0.8 = 47.2 (?) [fiddle](http://jsfiddle.net/9aeCU/2/): ``` function r(n){ for(c=0;n>c;n-=12,c++); return n==c?'yes':'no'; } ``` --- Including mellamokb's improvement (57\*0.8 = 45.6): ``` function r(n){ for(c=0;n>c;n-=12,c++); return n-c?'no':'yes' } ``` [Answer] **Perl: (51-4 spaces)\*0.9 = 42.3** ``` say+<>%(scalar reverse int 40*atan2 1,1)?'no':'yes' ``` > > 40\*atan2(1,1) -> 31.41592 (PI\*10) > > > [Answer] # Perl (19.8) 21 bytes \* .9 ``` say2*<>%26?"no":"yes" ``` *note:* My first Perl program ever. Weakly typed is good for golf i guess. [Answer] **in C (K&R): 47 \* 0.8 = 37.6** ``` f(i){for(;i>0;i-=__LINE__);puts(i?"no":"yes");} ``` EDIT1: okay removed all dependencies on external functions, the above will work as long as you put this line on the 13th line of the file! :) If `__LINE__` is okay to be replaced by say `0xd` then can save a further 5 characters (score: 33.6) [Answer] ## J - 22.4 = 28 \* 0.8 Based on [mxmul's](https://codegolf.stackexchange.com/users/2289/mxmul) clever [cyclic method](https://codegolf.stackexchange.com/a/4956/46). ``` f=:<:{('yes',~12 3$'no ')$~] ``` Examples: ``` f 13 yes f 23 no f 13*513 yes f 123456789 no ``` [Answer] # JavaScript (108 less 0 for whitespace) => 108, x 0.8 (no modulus, no division) = 86.4 `b=b=>{a=z,a=a+"";return+a.slice(0,-1)+4*+a.slice(-1)};z=prompt();for(i=99;i--;)z=b();alert(b()-z?"no":"yes")` This method uses the following algorithm: 1. Take the last digit, multiply it by four, add it to the rest of the truncated number. 2. Repeat step 1 for 99 iterations... 3. Test it one more time using step 1, if the resulting number is itself, you've found a multiple of 13. Previous update, removed `var`, and reversed logic at the alert to remove more chars by using subtraction-false conditional. Technically, the end result is that you'll eventually reach a two digit number like 13, 26, or 39 which when run through step 1 again will give 13, 26, or 39 respectively. So testing for iteration 100 being the same will confirm the divisibility. [Answer] # Cheddar, 20 bytes (noncompeting) ### Score is 20 \* 0.9 = 18 ``` n->n*2%26?'no':'yes' ``` A straightforward answer. [Answer] # Common Lisp (71 bytes \* 0.8) = 56.8 Simple recursion, really. `(defun w(x)(if(> x 14)(w(- x 13))(if(> 14 x 12)(print'yes)(print'no))))` Ungolfed: ``` (defun w (x) (if (> x 14) (w (- x 13)) (if (> 14 x 12) (print 'yes) (print 'no)))) ``` [Answer] ## Ruby (50 48 \* 0.9 = 43.2) Smart way to use `eval` ``` eval x="p gets.to_i*3%x.length == 0? 'yes':'no'" ``` [Answer] ## D 56 chars .80 bonus = 44.8 ``` bool d(double i){ return modf(i*0,0769230769,i)<1e-3; } ``` this might have been a cop-out with using 1/13 and a double can store any 32 bit number exactly edit: this works by multiplying with 1/13 and checking the fractional part if it's different from 0 (allowing for rounding errors) or in other words it check the fractional part of i/13 [Answer] ## Python 2.7 (20 - 1 whitespace) \* 0.9 (no division) = **17.1** ``` print input()%015==0 ``` yes/no instead of true/false: 31 \* 0.9 (no division) = **27.9** ``` print'yneos'[input()%015!=0::2] ``` takes advantage of python's `int` to convert other bases from strings into base 10 integers. you can see in both versions they use a different (yet same character length) base edit: 1 char save in yes/no version edit2: another 2 chars shaved! edit3: thanks again to comments! even more characters shaved off by using python's builtin octal representations (`015` == `13`...) instead of int's base translation [Answer] ## Perl, 95 \* 0.8 = 76 ``` $_=<>; while($_>0){ $q=7*chop; $d=3*($m=chop$q); chop$d; $_-=$d+$m} if($_){print"no"} else{print"yes"} ``` The line breaks were added for clarity. I could have probably made this answer a lot shorter, but I feel that this answer represents a unique way of approaching the problem. [Answer] # Python - score 27.9 **(31 characters \* 0.90)** -- forgoes some bonus for shorter code. ``` print'yneos'[2*input()%26>0::2] ``` **older version:** (47 characters \* 0.80) -- complete rip-off of mellamokb's Javascript answer, but in Python. ``` n=2*input() while n>0:n-=26 print'yneos'[n<0::2] ``` **older version:** (60 characters \* 0.80) ``` n=input() while n>12: for _ in'x'*12+'!':n-=1 print'yneos'[n>0::2] ``` **older version:** (105 characters \* 0.80) ``` n=abs(input()) while n>12:n=abs(sum(int(x)*y for x,y in zip(`n`[::-1],n*(1,-3,-4,-1,3,4)))) print'yneos'[n>0::2] ``` [Answer] ## In Q: ``` d:{$[0=x mod "I"$((string 6h$"q")[1 2]);`yes;`no]} 50*.9=45 ``` [Answer] # **Right Linear Grammar - โˆž points** ``` S->ฮต S->1A S->0S S->9I S->3C S->5E S->4D S->2B S->7G S->6F S->8H F->3K K->0F A->2L K->1G A->5B A->0J B->7A J->5A G->6K G->8S H->9K F->5S K->2H I->6E I->5D J->4S D->8I B->6S K->9B F->6A G->9A K->6L K->4J C->1E L->8K E->5C B->4K C->0D J->2K D->2C A->9F J->7C C->6J C->8L E->0K L->0C B->9C E->2S L->6I I->0L J->0I B->2I I->3B H->1C I->7F C->4H F->1I G->4I I->0G C->3G F->8C D->0A E->3A I->9H A->7D C->2F H->7I A->8E F->9D E->8F A->6C D->6G G->0E D->5F E->9G H->2D D->7H H->3E I->2A K->3I C->9S C->7K E->4B D->1B L->1D J->9E I->1S E->1L J->8D D->9J L->2E J->3L B->5L B->8B L->7J L->9L G->1F A->4A K->5K B->3J H->6H E->7E J->1J D->4E G->2G J->6B D->3D E->6D H->4F I->4C C->5I F->0H H->5G K->7S G->3H L->5H H->8J A->3S H->0B B->1H G->7L K->8A F->2J F->7B L->4G F->4L A->1K B->0G G->5J L->3F ``` Then depending on how you choose to 'run' it, it will output 'yes' or 'no'. Not a serious entry, just some fun ;) **EDIT:** Perhaps I should explain a bit. A [grammar](http://en.wikipedia.org/wiki/Formal_grammar) is a set of rules (productions) which define a [language](http://en.wikipedia.org/wiki/Formal_language). A language can be thought of as all of the possible strings formed by an alphabet, that conform to the rules of it's grammar. Here the alphabet is the set of all decimal digits. The grammar's rules are that all strings must form decimal integers that are divisible by 13. We can use the grammar above to test whether a string belongs to our language. The rules of the grammar contain terminal symbols (which are elements in the language) as well as non-terminal symbols which are replaced recursively. It's easier to explain what's going on with an example: Lets say for example that the string we are testing is 71955. There is always a start symbol (which is non-terminal), in the case of the grammar above this is 'S'. At this point we have not read any characters from our string: ``` current pattern symbol read S ฮต ``` Now, we read the first symbol in our string which is '7', then we look for a rule in the grammar which has any of the non-terminals in our current pattern in the left hand side of the '->' and that has our symbol in the right hand side of the '->'. Luckily there is one (S->7G), so we replace the non-terminal symbols in our current pattern with the right hand side of the new rule: ``` current pattern symbol read 7G 7 ``` Now we have the non-terminal 'G' in our pattern, and the next symbol to be read is '1', So we look for a rule in our grammar that begins with 'G->1". We find there is one (G->1F), so we replace the non terminal with the RHS of our new rule: ``` current pattern symbol read 71F 1 ``` Keep repeating this process: Next rule: F->9D ``` current pattern symbol read 719D 9 ``` Next rule: D->5F ``` current pattern symbol read 7195F 5 ``` Next rule: F->5S ``` current pattern symbol read 71955S 5 ``` At this point we have no more symbols in our string, but we have another non-terminal symbol in there. We see from the first rule in the grammar that we can replace 'S' with the empty string (ฮต): S->ฮต Doing so gives us the current patter: 71955ฮต which is the equivalent to 71955. We have read all of the symbols in our string, and the pattern contains no non-terminal symbols. Which means that the string belongs to the language and therefore 71955 is in fact divisible by 13. I.e. the goal is to have pattern = string. If you are left with any non-terminal symbols, after reading all of the symbols in your string, the string doesnt belong to the language. Likewise, if you still have more symbols in your string to read, but there are no rules in the grammar allowing you to go forward, then the string does not belong to the language. ]
[Question] [ Write some statement(s) which will count the number of ones in an unsigned sixteen-bit integer. For example, if the input is `1337`, then the result is `6` because `1337` as a sixteen bit binary number is `0000010100111001`, which contains six ones. [Answer] # 80386 Machine Code, 4 bytes ``` F3 0F B8 C1 ``` which takes the integer in `cx` and outputs the count in `ax`, and is equivalent to: ``` popcnt ax, cx ; F3 0F B8 C1 ``` And here is an **~~11~~ 10** byte solution not using POPCNT: ``` 31 C0 D1 E9 10 E0 85 C9 75 F8 ``` which is equivalent to: ``` xor ax, ax ; 31 C0 Set ax to 0 shr cx, 1 ; D1 E9 Shift cx to the right by 1 (cx >> 1) adc al, ah ; 10 E0 al += (ah = 0) + (cf = rightmost bit before shifting) test cx, cx ; 85 C9 Check if cx == 0 jnz $-6 ; 75 F8 Jump up to shr cx, 1 if not ``` [Answer] # Python 2, 17 bytes ``` bin(s).count('1') ``` The `bin` built-in returns the integer converted to a binary string. We then count the `1` digits: ``` >>> s=1337 >>> bin(s) '0b10100111001' >>> bin(s).count('1') 6 ``` [Answer] ## J (5 characters) J has no explicit types. This does the right thing for all integers. ``` +/@#: ``` * `+/` the sum * `@` of * `#:` the base two representation [Answer] # C,21 ``` for(n=0;x;n++)x&=x-1; ``` you said "write some statements" (not "a function") so I've assumed the number is supplied in `x` and the number of 1's is returned in `n`. If I don't have to initialize `n` I can save 3 bytes. This is an adaptation of the famous expression `x&x-1` for testing if something is a power of 2 (false if it is, true if it isn't.) Here it is in action on the number 1337 from the question. Note that subtracting 1 flips the least significant 1 bit and all zeroes to the right. ``` 0000010100111001 & 0000010100111000 = 0000010100111000 0000010100111000 & 0000010100110111 = 0000010100110000 0000010100110000 & 0000010100101111 = 0000010100100000 0000010100100000 & 0000010100011111 = 0000010100000000 0000010100000000 & 0000010011111111 = 0000010000000000 0000010000000000 & 0000001111111111 = 0000000000000000 ``` EDIT: for completeness, here's the naive algorithm, which is one byte longer (and quite a bit slower.) ``` for(n=0;x;x/=2)n+=x&1; ``` [Answer] ## [Jelly](http://jelly.tryitonline.net/#code=QlM&input=&args=MjM), 2 bytes ``` BS ``` Jelly is a new language written by @Dennis, with J-like syntax. ``` implicit: function of command-line arguments B Binary digits as list S Sum ``` Try it [here](http://jelly.tryitonline.net/#code=QlM&input=&args=MjM). [Answer] # Pyth, 4 bytes ``` sjQ2 ``` The program takes the number whose hamming weight is to be found on STDIN. [Answer] # R, 24 bytes ``` sum(intToBits(scan())>0) ``` `scan()` reads input from stdin. `intToBits()` takes an integer and returns a vector of type `raw` containing the zeroes and ones of the binary representation of the input. `intToBits(scan())>0` returns a logical vector where each element is `TRUE` if the corresponding binary vector element is a 1 (since all elements are 0 or 1 and 1 > 0), otherwise `FALSE`. In R, you can sum a logical vector to get the number of `TRUE` elements, so summing the vector of logicals as above gets us what we want. Note that `sum()` can't handle `raw` input directly, hence the workaround using logicals. [Answer] # Julia, ~~29~~ ~~27~~ 19 bytes ``` n->sum(digits(n,2)) ``` This creates an anonymous function that accepts a single argument, `n`. To use it, assign it to something like `f=n->...` and call it like `f(1337)`. The `digits()` function, when called with 2 arguments, returns an array of the digits of the input in the given base. So `digits(n, 2)` returns the binary digits of `n`. Take the sum of the array and you have the number of ones in the binary representation of `n`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~8~~ 3 bytes ``` +/โŠค ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1v/UdeS/2mP2iY86u171NX8qHfNo94th9YbP2qb@KhvanCQM5AM8fAM/p@mYMCVpmAIxEZAbAzEJiC@sbE5AA "APL (Dyalog Extended) โ€“ Try It Online") -5 from Adรกm. ``` โŠค convert to base 2 +/ sum ``` [Answer] # [Rust](https://www.rust-lang.org/), 15 bytes ``` u16::count_ones ``` [Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6GpUM2lAAQ5qSUKaaV5yQq2/0sNzayskvNL80ri8/NSi/@DpK3BigqKMvNKcvIUNZSqa5V0wOo1DI2NzYE6NDWxKoHK6iGM0wCprP0PAA "Rust โ€“ Try It Online") Rust is better than C because `count_ones` is shorter than `__builtin__popcount` :) Every built-in integer type (unsigned or signed, 8/16/32/64/128 bits) supports this method. Since the challenge specifically asks for unsigned 16 bit integers, we use `u16` here. Also, while the method is usually called in the form of `some_number.count_ones()`, `u16::count_ones(some_number)` is also a valid syntax for calling the same function. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` bโˆ‘ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJi4oiRIiwiIiwiMTMzNyJd) # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 1 byte ``` b ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiYiIsIiIsIjEzMzciXQ==) [Answer] # CJam, 6 bytes ``` ri2b:+ ri "Read the input and convert it to integer"; 2b "Convert the integer into base 2 format"; :+ "Sum the digits of base 2 form"; ``` [Try it online here](http://cjam.aditsu.net/#code=ri2b%3A%2B&input=253) [Answer] # [Joe](https://github.com/JaniM/Joe), 4 bytes ``` /+Ba ``` This is an anonymous function. `Ba` gives the binary representation of a number and `/+` sums it. ``` (/+Ba)13 3 (/+Ba)500 6 ``` [Answer] # Ruby, 18 bytes `n.to_s(2).count'1'` [Answer] # Forth, ~~48~~ 49 bytes ``` : c ?dup if dup 1- and recurse 1+ then ; 0 1337 c ``` If an actual function is needed then the second line becomes ``` : c 0 swap c ; ``` and you call it by "1337 c". Forth's relatively verbose control words make this a tough one (actually, they make a lot of these tough). Edit: My previous version did not handle negative numbers correctly. [Answer] # Mathematica, ~~22~~ 18 bytes *Thanks to alephalpha for reminding me of `DigitCount`.* ``` DigitCount[#,2,1]& ``` [Answer] # ES6 (~~34~~ ~~22~~ 21 bytes): This is a simple recursive function that can be shortened a bit more. It simply takes a bit and runs itself again: ``` B=n=>n&&(1&n)+B(n>>1) ``` Try it on <http://www.es6fiddle.net/imt5ilve/> (you need the `var` because of `'use strict';`). I can't believe I've beaten Fish!!! The old one: ``` n=>n.toString(2).split(1).length-1 ``` --- # ES5 (39 bytes): Both functions can be easily adapted to ES5: ``` function B(n){return n?(1&n)+B(n>>1):0} //ungolfed: function B(number) { if( number > 0 ) { //arguments.callee points to the function itself return (number & 1) + arguments.callee( number >> 1 ); } else { return 0; } } ``` Old one: ``` function(n){return n.toString(2).split(1).length-1} ``` --- [@user1455003](https://codegolf.stackexchange.com/users/8055/user1455003) gave me a really great idea, that 'triggered' the smallest one: ``` function B(n,x){for(x=0;n;n>>=1)x+=n&1;return x} ``` I've adapted it to ES6 and made it recursive to shorten a lot! [Answer] # Python, ~~72~~ 26 bytes Thanks to [mathcat](https://codegolf.stackexchange.com/users/96037/mathcat) for ~~-12~~ ~~-27~~ -36 bytes through various simplifications! ``` lambda a:bin(a).count('1') ``` Well, you said *statements*... [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 24 bytes + 2 = 26 ``` 0$11.>~n; 2,:?!^:2%:{+}- ``` The program just does repeated mod 2, subtract and divide until the input number becomes zero, then prints the sum of the mod 2s. Test with the `-v` flag, e.g. ``` py -3 fish.py ones.fish -v 1337 ``` [Answer] # PHP (38 bytes): This uses the same aproach as my [ES6 answer](https://codegolf.stackexchange.com/a/47896/14732) ``` <?=count(split(1,decbin($_GET[n])))-1; ``` This is a full code, you only need to put it in a file and access it over the browser, with the parameter `n=<number>`. # PHP <4.2 (32 bytes): This is a little shorter: ``` <?=count(split(1,decbin($n)))-1; ``` This only works reliably on PHP<4.2 because the directive [`register_globals`](http://php.net/manual/en/ini.core.php#ini.register-globals) was set to `Off` by default from PHP4.2 up to PHP5.4 (which was removed by then). If you create a `php.ini` file with `register_globals=On`, this will work. To use the code, access the file using a browser, with either POST or GET. # [@ViniciusMonteiro](https://codegolf.stackexchange.com/users/12700/vinicius-monteiro)'s suggestion (38/45 bytes): He gave 2 really good suggestions that have a very interesting use of the function `array_sum`: 38 bytes: ``` <?=array_sum(str_split(decbin(1337))); ``` 45 bytes: ``` <?=array_sum(preg_split('//', decbin(1337))); ``` This is a really great idea and can be shortened a bit more, to be 36 bytes long: ``` <?=array_sum(split(1,decbin(1337))); ``` [Answer] # C#, 45 bytes ``` Convert.ToString((ushort)15,2).Sum(b=>b-48); ``` <https://dotnetfiddle.net/kJDgOY> [Answer] # Japt, 3 bytes (non-competitive) ``` ยขยฌx ``` [Try it here.](http://ethproductions.github.io/japt?v=master&code=oqx4&input=MTMzNw==) [Answer] # [beeswax](http://rosettacode.org/wiki/Category:Beeswax), ~~31~~ 27 bytes Non-competing answer. Beeswax is newer than this challenge. This solution uses Brian Kheriganโ€™s way of counting set bits from the โ€œBit Twiddling Hacksโ€ website. it just runs through a loop, incrementing the bit count, while iterating through `number=number&(number-1)` until `number = 0`. The solution only goes through the loop as often as there are bits set. I could shave off 4 bytes by rearranging a few instructions. Both source code and explanation got updated: ``` pT_ >"p~0+M~p d~0~@P@&< {@< ``` Explanation: ``` pT_ generate IP, input Integer, redirect >" if top lstack value > 0 jump next instruction, otherwise continue at next instruction p redirect if top lstack value=0 (see below) ~ flip top and 2nd lstack values 0+ set top lstack value to 0, set top=top+2nd M decrement top lstack value ~ flip top and 2nd lstack values p redirect to lower left < redirect to left & top=top&2nd @ flip top and 3rd lstack values @P increment top lstack value, flip top and 3rd values ~0~ flip top and 2nd values, set top=0, flip top and 2nd again d redirect to upper left >"p~0+M..... loop back p if top lstack = 0 at " instruction (see above), redirect 0 set lstack top to zero (irrelevant instruction) < redirect to the left @ flip top and 3rd lstack values { output top lstack value as integer (bitcount) ``` Clone [my GitHub repository](https://github.com/m-lohmann/BeeswaxEsolang.jl) containing the beeswax interpreter, language spec and examples. [Answer] # 05AB1E, 3 bytes ``` bSO ``` [Try it online!](http://05ab1e.tryitonline.net/#code=YlNP&input=MTMzNw) [Answer] # [Factor](https://factorcode.org/), 9 bytes ``` bit-count ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoZeUWVKeWZyqUFCUWlJSWVCUmVeiYM3FZWhsbP4fKKebnF@aV/Jf7z8A "Factor โ€“ Try It Online") [Answer] # [Python](https://www.python.org) 3.10+, 13 bytes ``` int.bit_count ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZrM_NK9JIyS-KT80vzSiBi6wqKgKIaaRqGxsbmmpoQwQULIDQA) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~10~~ 7 bytes ``` {+/2\x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW1jeKqajl4kpTMDQ2NlfQV9C1UzADAE6DBZE=) *Thanks @coltim for -3 bytes by suggesting me that I can just take the sum instead of the count of `1`s* Cast the integer into base 2, then sum. [Answer] # [BitCycle](https://github.com/dloscutoff/Esolangs/tree/master/BitCycle), 5 bytes ``` ?+ ! ``` [Online Interpreter](https://dloscutoff.github.io/Esolangs/BitCycle/?p=c2esc6rc3iAsrqAnrBnrnc2wcw&i=MDAxMQ__) Kind of cheaty, as it inputs in binary and outputs in unary. These are the only two I/O formats this language really can handle, but it's also pretty trivial. --- Explanation: `?` Take input `+` Send all 0 bits up (deleting them) and all 1 bits down. `!` Output all bits that arrive here. [Answer] # Java, 17 bytes Works for `byte`, `short`, `char`, and `int`. Use as a lambda. ``` Integer::bitCount ``` [Test here](http://ideone.com/i2lxn0) Without using built-ins: **42 bytes** ``` s->{int c=0;for(;s!=0;c++)s&=s-1;return c} ``` [Test here](http://ideone.com/Jggf9B) [Answer] # [Clip](http://esolangs.org/wiki/Clip), 6 2 ways: ``` cb2nx1 ``` This is a straightforward translation of the requirement: the count of ones in the base-2 representation of number. ``` r+`b2n ``` Another method, which takes the sum of the digits of the base-2 representation. ]
[Question] [ Let's say I have this string: ``` s = "Code Golf! I love Code Golf. It is the best." ``` I want to replace all the [vowels](https://en.wikipedia.org/wiki/Vowel) with repeated "aeiou". Notes: * Uppercase vowels should be replaced by an uppercase letter, and lowercase vowels should be replaced by a lowercase letter. * Consonants (all alphabet characters except for "aeiou") and non alphabetical characters should be kept the same. Desired output: ``` Cade Gilf! O luva Cedi Golf. Ut as the bist. ``` As you can see, the vowels are replaced in repetitive order of "aeiou". Another example: ``` s = "This is a test! This is example number two." ``` Output: ``` Thas es i tost! Thus as eximplo numbar twe. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # [C (clang)](http://clang.llvm.org/), 65 bytes ``` i;f(*s){for(i=0;*s++^=2130466>>*s&*s>64?i*5^5%++i^*s&30:0;i%=5);} ``` [Try it online!](https://tio.run/##PczLCoJAGIbhfVfxN2DMIcXysGjQFi0i6A4iwcyxgUnDf6iFeOtNRtDu44H3q/zKlG3jnJaKcmSD6nqqs1ByFKLI1qsojNM0zzkuOOZpvNU8KRJPCF1MFIWbUGovS5gc3b3ULWUwzAB0awFtfzpDBkey66417Duj5nAA0z1r@EsABwsawd5quNRoAyKnXNEpZt/16KcrRYlnkCzhp6N7V8qUDTr/9QE "C (clang) โ€“ Try It Online") ## How? ### Detecting vowels We determine whether the current character at `*s` is a vowel with: ``` 2130466 >> *s & *s > 64 ``` The value \$2130466\$ is a bitmask describing the positions of vowels: ``` 000001000001000001000100010 ^ ^ ^ ^ ^ zyxwvutsrqponmlkjihgfedcba ``` The shift amount is interpreted modulo 32 (to my knowledge, this is true for at least Intel and ARM processors). This means that we just have to make sure that the character is a letter (with `*s > 64`) and can use the same expression for lower and upper case. ### Turning them into different vowels An interesting thing about vowels is that all their ASCII codes are odd: ``` A | 65 | 1000001 a | 97 | 1100001 E | 69 | 1000101 e | 101 | 1100101 I | 73 | 1001001 i | 105 | 1101001 O | 79 | 1001111 o | 111 | 1101111 U | 85 | 1010101 u | 117 | 1110101 || | || '--> always 1 |'-------> 'case' bit '--------> always 1 ``` To turn a vowel of a given case into another vowel with the same case, only bits #1 to #4 (0-indexed) need to be modified. This can be represented with the bitmask \$00011110\_2=30\_{10}\$. Hence a possible formula: ``` new_vowel = old_vowel XOR (x XOR (old_vowel AND 30)) ``` where \$x\in\{0,4,8,14,20\}\$ (for A,E,I,O,U respectively). Given \$i\in[0\dots4]\$, we get \$x\_i\$ with: $$x\_i=(i\times 5)\operatorname{xor}(5 \bmod (i+1))$$ | i | i \* 5 | 5 mod (i+1) | xor | | --- | --- | --- | --- | | 0 | 0 | 0 | 0 | | 1 | 5 | 1 | 4 | | 2 | 10 | 2 | 8 | | 3 | 15 | 1 | 14 | | 4 | 20 | 0 | 20 | As C code, this gives: ``` *s ^= i * 5 ^ 5 % ++i ^ *s & 30 ``` which, conveniently, is incrementing \$i\$ at the same time. ### Putting everything together ``` i; // i is a counter for vowel replacement f(*s) { // s is the input string for( // main loop: i = 0; // start with i = 0 *s++ ^= // update the character *s: 2130466 >> *s // if this looks like a vowel & *s > 64 ? // and really is a letter: i * 5 ^ // turn it into a different vowel 5 % ++i ^ // and increment i afterwards *s & 30 // : // else: 0; // leave it unchanged // (NB: we stop when the result is NUL) i %= 5 // make sure to keep i in [0..4] ); // end of loop } // ``` [Answer] # [R](https://www.r-project.org), ~~94~~ ~~81~~ 79 bytes *Edit: -2 bytes thanks to pajonk* ``` \(i){u=match(i,v<-el(strsplit("aAeEiIoOuU","")),0) i[!!u]=v[1:5*2-u[!!u]%%2] i} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGa5MrknNSy_PLUnGLbpaUlaboWN_1jNDI1q0ttcxNLkjM0MnXKbHRTczSKS4qKC3IySzSUEh1TXTM98_1LQ5V0lJQ0NXUMNLkyoxUVS2Nty6INrUy1jHRLwVxVVaNYrsxaqLERyYklGkjWaaAY6pyfkqrgnp-TpqjgqZCTX5aqABfRU_AsUcgsVijJSFVISi0u0YNYq6lTnFpgC2RBzF-wAEIDAA) Input & output as character vectors. (Splitting-up an input string and reassembling one for the output costs about +36 bytes, for comparison with any alternative approaches that directly use strings). [Previous 94-byte version](https://ato.pxeger.com/run?1=TY2xCsIwFEX3fMUzU0Krs0sGEZVOLgqCVlrjqwaCCU1SEfFLXOrg5g_5N7ZUxOmee4d77o-yfsmL1FiZM2onnsEX_eF7u2GKX7MoEw3Ekh9KtIyuR5Nkvkxp3E4kCBVNiVqraJGKqoGQCm-CtViytnCibqQSTuYnFlPKSQ4ICgwE8rWsZO7Zn52hZs6XzmrlGR2bPcLM6KIHCWhTIfyWASQelAN_RNih8wPaCjiPHVrRUPdf111-AA) (using `grep` and `toupper`) [Answer] # Excel (ms365), ~~183~~, 164 bytes -19 bytes thanks to @[jdt](https://codegolf.stackexchange.com/users/41374/jdt) [![enter image description here](https://i.stack.imgur.com/eoqgJ.png)](https://i.stack.imgur.com/eoqgJ.png) Formula in `B1`: ``` =LET(x,MID(A1,ROW(A:A),1),y,"uaeio",r,SEARCH(x,y),z,SCAN(0,r,LAMBDA(a,b,IF(ISERR(b),a,a+1))),w,MID(y,MOD(z,5)+1,1),CONCAT(IFERROR(IF(r*(CODE(x)<97),UPPER(w),w),x))) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` โŸ‘A[kvยฅi$โ€ข&โ€บ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLin5FBW2t2wqVpJOKAoibigLoiLCIiLCJUaGlzIGlzIGEgdGVzdCEgVGhpcyBpcyBleGFtcGxlIG51bWJlciB0d28uIl0=) If I had a nickel for every time I'd answered a vowel-related challenge with an 11 byte Vyxal answer in the last 2 weeks, I'd have 2 nickels, which isn't a lot but it's weird that it's happened twice. Outputs as a list of characters (add the `s` flag if you want a string object). ## Explained ``` โŸ‘A[kvยฅi$โ€ข&โ€บ โŸ‘ # To each character: A[ # if it is a vowel: kvยฅi # get the (register)th item of the string "aeiou" - wraps around if the register > 5 $โ€ข # and give it the same case of the current character &โ€บ # increment the register to get the next vowel ``` [Answer] # [Python](https://www.python.org), ~~109 106 104~~ 98 bytes ``` f=lambda s,i=0:s and((c:=s[0])in(v:='uaeioUAEIO')and[v[:5],v[5:]][c<'a'][i:=-~i%5]or c)+f(s[1:],i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY4xCsIwGEav8luQJNiWOhRKMIOISCcnp5AhbRMaqElp0oKLF3HponfyNjpU1-_xeN_j1d9C6-w8P8egk-JdadbJa9VI8LFhGfUgbYNxTZnnmSDG4okyNEpl3GV_LM-IfDmfOM1FPPGcCsHrHZJIcENZcjfrXLgBarLR2PMtFbEhS6noB2MD1jg6uEbByXV6BSV0blLwX1IoAxgPoVVQKR_SiCz-7_EH) * -6 thanks to Steffan # [Python](https://www.python.org), ~~117 116 112~~ 111 bytes ### (not valid - this is just for fun) ``` lambda s:re.sub('[aeiou]',g,s,0,2) i=0 def g(c):global i;i=-~i%5;return['uaeio','UAEIO'][c[0]<'a'][i] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY07CsJAFEX7rOIpyCQwhiAIoqYQEUllZRVTTMyb-GDMhPkINm7EJiC6J3ejoljdw4HDvT7aszvoprvJdHf3Tg4nT63EsawE2KnB2PoyZLlA0r5gvOaWJ3wUBZQmQYUS6nAfTWulS6GAZpQOLzQYzww6b5qc-U_HONsuVtmGFfk-T4o5E2-iIqBjq40Dg7_bSWuocaEM-0tdIay1kj3IQOkTwt_EkDkgC-6AUKJ1cT-Kvn3XffcF) * -4 thanks to Steffan * -1 thanks to pxeger Just wanted to try with a Regex-based approach. The function isn't reusable so it's not a valid solution. [Answer] # JavaScript (ES6), 59 bytes ``` s=>s.replace(/[aeiou]/gi,c=>"aAeEiIoOuU"[i++%5*2|c<{}],i=0) ``` [Try it online!](https://tio.run/##XYzBCoJAFEX3fcVzINA0jaBdChERrtrUSlxM01MnRp84owXVt0@2qEVwN/dyzr3ygWvRydbMG7qgLWKr40SHHbaKC3SjjKOkPo9KGYg4YXyDO5nSoT@xTPr@dDVbPsX68coDGS88K6jRpDBUVLqFy7bjJexJFQ6koGhA@C0hpAakBlMhnFGbkHne5E8/ViMwhoMZCQe@He@8bhVC09dn7MDc6GPbNw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Python](https://www.python.org), ~~80~~ 74 bytes * -6 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! ``` V=v='UuAaEeIiOo' for c in input():print(end=c[c in V:]or(v:=v[2:]+V)[c>V]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3vcJsy2zVQ0sdE11TPTP989W50vKLFJIVMvOAqKC0REPTqqAoM69EIzUvxTY5GiwRZhWbX6RRZmVbFm1kFasdphmdbBcWqwkxEWrwgps6zvkpqQru-TlpigqeCjn5ZakKcBE9Bc8ShcxihZKMVIWk1OISPYgmAA) Full program. --- # [Python](https://www.python.org), ~~85~~ ~~81~~ 78 bytes * -4 thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)! * -3 thanks to xnor! ``` lambda s,v='uUaAeEiIoO':''.join(c[c in v:]or(v:=v[2:]+v[:2])[c<'a']for c in s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY0xDoJAEEV7TzHSLESloDIbKYwxhkYbrZBigd2wBnYILKuexYbE6J28jShK8pPJ_Dd__u1ZXnWGqr0L__hotJjNX9ucFXHKoJ4anzQHtuRrGeCOUELcE0plJ2ECUoGhEVa2ob4JPRpNTEi9yAmTBWEkEljB96h2fl_LspJK28K2Vphy2GAuxhBAjobD4LgQaJA16IxDzGvtWo4zGoL7rEOdGOiOjeG_8wsrypyDaoqYV6DP-Mn1vW3bzzc) [Answer] # [Raku](https://raku.org/), 44 bytes ``` {$!=0;S:g:ii[<[aeiou]>]=<a e i o u>[$!++%*]} ``` [Try it online!](https://tio.run/##PchBC4IwHIbxr/JOrEGGdOpgzkuH8Fw3EZn0Xw5mE52ViJ99eSl4Ls@vo94cfTthqyD8HDJxOF2TR6J1kRaStB3LrBSpBEHDYsyKkEXRZlcufpATgrCCyDArhNUSQNke/GzvhIs1iiGHsS/CX2LkDnqAawg1DS7me/Bbs8qahFuJ4ff0kW1nCM@xramHe9uY@y8 "Perl 6 โ€“ Try It Online") Most of the magic here is in the `samecase` flag on the substitution, whose short form is `ii`. It makes the match case-insensitive, and furthermore carries the case information forward into the substituted text. [Answer] # [Pip](https://github.com/dloscutoff/pip), 37 21 bytes *- 14 bytes of mostly DLosc, and jezza\_99 getting ninja'd* *- 2 bytes thanks to jezza\_99* ``` aR-XV{YVW@UvaNz?yUCy} ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhUi1YVntZVldAVXZhTno/eVVDeX0iLCIiLCJcIkNvZGUgR29sZiEgSSBsb3ZlIENvZGUgR29sZi4gSXQgaXMgdGhlIGJlc3QuXCIiLCIiXQ==) I'm bad at golfing in pip lol. ``` aR-XV{YVW@UvaNz?yUCy} aR-XV{ } Replace (case-insensitive) vowels with ... YVW@Uv Set y to the (vth*1) vowel aNz?yUCy Copy case to y ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r\v@Tยฐg`aeiล’`c^H*XรจXu ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clx2QFSwZ2BhZWmMYGNeSCpY6Fh1&input=IkNvZGUgR29sZiEgSSBsb3ZlIENvZGUgR29sZi4gSXQgaXMgdGhlIGJlc3QuIg) ``` r\v@Tยฐg`aei`c^H*XรจXu :Implicit input of string r :Replace \v :RegEx /[aeiou]/gi @ :Pass each match X through the following function Tยฐ : Postfix increment T (initially 0) g : Index into `aei` : Compressed string "aeiou" c : Map charcodes ^ : Bitwise XOR with H* : 32 multiplied by Xรจ : Count the occurrences in X of Xu : X uppercased ``` [Answer] # [Haskell](https://www.haskell.org), 93 bytes ``` (%"aAeEiIoOuU") (x:r)%u@(v:t:w)|elem x u=c:r%(w++[v,t])|1>0=x:r%u where c|x>'Z'=v|1>0=t o%_=o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY07CsJAGIR7TzEuLib4QDsJrA9EJJWVjRokxj8kuLoh2U1S5CY2goheydsoKlYD8w3fnO-Rnx1IyseadYIkYd41FJub0WFn8PQszvwJzWJXLcyS2TWrdFKbm7GVO9op7IokHVHCiMBJuVW0Wuu8rT276g974j3lBkVEKSGoymFz1RT5h-ia4luhfiejox-fIJCk8UmjgRBsqvaEuZJhHS6kygn_pgtXI86gI8KOMt1lX83l8s0X) Prettified: ``` import Data.Char g vowels@(vowel:vOWEL:rest) (char:chars) | char `elem` vowels = mappedChar : g rotatedVowels chars | otherwise = char : g vowels chars where rotatedVowels = rest ++ [vowel, vOWEL] mappedChar | isUpper char = vOWEL | otherwise = vowel g _ "" = "" ``` ``` g "aAeEiIoOuU" ``` [Answer] # Python 3.8+, ~~183 156 127 117~~ 111 bytes -29 bytes thanks to ElPedro -10 bytes thanks to Neil -6 bytes thanks to help from the Discord (mainly by dzaima and me) ``` def x(n):m,j='aeiou',0;return''.join([((m,m.upper())[i<'a'][j%5],j:=j+1)[0]if i.lower()in m else i for i in n]) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~130~~ ~~122~~ 120 bytes ``` p=print v='aeiou' n=0 for i in input(): if i.lower()in v:p(end=[v[n],v[n].upper()][i.isupper()]);n=-~n%5 else:p(end=i) ``` [Try it online!](https://tio.run/##PYvBCsIwEETv@Yr1IG1AgyBelJw8SL@h9KB0SxfC7tKkES/@emxBhWFg3mP0lUbhYynqdSJOJvvqjiRzZdgfzCATEBAv0TnV9myABiAX5IlTbReRz1oj977NLXe7tdysusquJUfxN@yF/f7N25MBDBG/L7KlXKVHuEkYNtBAkIzwJw6aBBQhjQgPjMl9AA "Python 3 โ€“ Try It Online") *-8 bytes thanks to myself* *-2 bytes thanks to The Thonnu* [Answer] # [Pyth](https://github.com/isaacg1/pyth), 25 bytes ``` sm?}r0dK"uaeio"r@K=hZrId1 ``` [Try it online!](https://tio.run/##K6gsyfj/vzjXvrbIIMVbqTQxNTNfqcjB2zYjqsgzxfD/fyXn/JRUBff8nDRFBU@FnPyyVAW4iJ6CZ4lCZrFCSUaqQlJqcYmeEgA "Pyth โ€“ Try It Online") ### Explanation ``` sm?}r0dK"uaeio"r@K=hZrId1dQ # implicitly add dQ to the end # implicitly assign Q = eval(input()) K"uaeio" # assign K to "uaeio" s # sum of m Q # map lambda d over Q ?}r0dK # ternary, if lowercase(d) in K: r rId1 # map case to d of @K # (looping) index K at =hZ # increment Z, and assign it to the increment d # else: d ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ร˜ciโฑฎรฐแธŸ0ร˜ฤ—แนล’s>5$}ยก"ฦŠลผ@ล“p ``` [Try it online!](https://tio.run/##y0rNyan8///wjOTMRxvXHd7wcMd8g8Mzjkx/uLPx6KRiO1OV2kMLlY51Hd3jcHRywf/D7Y@a1kT@/6/knJ@SquCen5OmqOCpkJNflqoAF9FT8CxRyCxWKMlIVUhKLS7RU9JRUArJAIoAUaJCCVBIUQHGT61IzC3ISVXIK81NSi1SKCnP11MCAA "Jelly โ€“ Try It Online") Jelly isn't great at [string](/questions/tagged/string "show questions tagged 'string'") challenges. Full program, as we take advantage of Jelly's smash printing. ## How it works ``` ร˜ciโฑฎรฐแธŸ0ร˜ฤ—แนล’s>5$}ยก"ฦŠลผ@ล“p - Take a string S on the left ร˜c - Yield "AEIOUaeiou" โฑฎ - For each character C in S: i - Get the index of C in "AEIOUaeiou", or 0 if not found รฐ - Begin new dyadic chain, with vowel indices V on the left and S on the right แธŸ0 - Remove zeros from V, call that V' ฦŠ - Group the previous 3 links into a monad f(V'): ร˜ฤ— - Uppercase vowels; "AEIOU" แน - Repeat to the same length as V' " - For each pair (v, i) with v a vowel and i an index in V': ยก - Repeat: $ - Iteration count: } - Is i... >5 - ...greater than 5? ล’s - Action: Swapcase ล“p - Partition S at the the indices in V ลผ@ - Zip the partition and the vowels, with reversed @rguments ``` [Answer] # [Factor](https://factorcode.org), ~~87~~ 86 bytes ``` [ EBNF[=[ r=([aeiouAEIOU]=>[[96 > 0 -32 ? 0 inc 0 get 1 - 5 mod "aeiou"nth +]]|.)*]=]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY_LTsMwEEX3-Ypbr3goEQ-BeCjlpVJlUxZQNpYXTjppLGI7xA6w4DvYdJMNfAL_0r_BJQJpNFf3zNyRZvVVysLbtl9_zO-z2fQMRmpyjSzIQUtfwdFzR2Zjn6g1VKOhZUK5KaEszqOI3dgFYWrrcoQMtX0h_JMEmYdy8BUhJ-cTFrGHKoBQEj6QEf48vUnd1ATT6Zxa-Fe72WafnS_jk_Ujx-R6dstTjjbd4pKU7a4m2d1cpGPOT48xxh7iwwNcBFWmCH1JHvuIcQRtF2C_EWbCR7tCvCfbOyIVYrj-zdG0yngIFFY31hF8qy6HYd8P-gM) * `[ ... ]` Define a quotation, or anonymous function, that takes a string as input from the data stack and leaves a string as output on the data stack. * `EBNF[=[ ... ]=]` Define an anonymous EBNF parser that automatically runs on an input and produces an output. * `r=` Name the topmost EBNF rule. There has to be at least one rule, so here it is. * `(...|.)*` Match any number (`*`) of ... or (`|`) anything (`.`). The `.` matches consonants which will remain the same. * `[aeiouAEIOU]` Match any vowel. * `=>[[...]]` An EBNF action. The code inside the double brackets will run on each token before being added to the parse tree. * `96 > 0 -32 ?` Is the vowel we matched lowercase? Push `0` on the data stack if so; otherwise, push `-32` on the data stack. * `0 inc` Increment the value stored at `0`. In Factor, any value (such as `0`) can be used as a variable (key) to store a value in an implicit hierarchy of hash tables. If `0` contains `f`, which all uninitialized variables do by default, `inc` will cause the value to become `1`. * `0 get` Get the value stored at `0`. * `1 -` Subtract one. We do this because it's shorter than initializing `0` to `0`. * `5 mod` Modulo five. * `"aeiou"nth` Get the nth letter in `"aeiou"`. * `+` Add this letter to the `0` or `-32` from earlier. This is what capitalizes the letter or keeps it lowercase. [Answer] # [Java (JDK)](http://jdk.java.net/), 125131 bytes ``` s->{String v="aeiouAEIOU",r="";int j=0,p;for(var c:s.toCharArray()){p=v.indexOf(c);r+=p>=0?v.charAt((p>4?5:0)+j++%5):c;}return r;}; ``` [Try it online!](https://tio.run/##PY9RS8MwEMff@ynOgpDQLTSgL6vtCENlD7KH4ZP4kLXpltolIUmLY@yz1xtTA8f9Lvcj/NPJUc675mvSR2d9hA5nNkTds3YwddTWsJdfKJKk7mUI8Ca1gXOSALhh1@saQpQR22h1A0dckm302uw/PkH6faDoAp6/d55u29mtVdBCOYV5db7NMJapVNoO4nm9eU9nvkzTQhtMVuYzV7TWk1F6qBeBRbs6SC@8lydC6dmVI9OmUd@bltS08FnpqjJfjqy@WpEQVz0sHxc5zbosu3@ki7q4eBUHb8AXl2K6ZtyeQlRHZofIHKaJvSEtk871J5KubKPg1fbtHayht6OC/xsG6wg6QDwo2KkQWUppgZ@@JJdpyrMcS2DxSSALZIHMkTkyR84ZOgwdhg6yQBbIHJkjc8Z/AA) (Edited to add some lambda boilerplate.) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~82~~ 54 bytes ``` i`[aeiou] a$& ,Y0`a`v`a. T`v`V`.[AEIOU] 1,2,i`[aeiou] ``` [Try it online!](https://tio.run/##RYxBCsIwFET3OcUUVFyUYL2BiJSs3KggpZBf/NJA2pT2t3r7mI0KA8N7DDOyuJ6KuN6WNjpbEbsw14pWG5Xfd5bsYkmrS6qb1dXhZM7XWhX5Pv9vYzyGB6MM/pnBwIeF8TMaRuAmSMtoeJL01SZMIUjiDF/mN3WDZ/Rz1/AIeQX9AQ "Retina โ€“ Try It Online") Link includes test cases. Explanation: ``` i`[aeiou] a$& ``` Prefix `a`s to all of the vowels, both lower and upper case. ``` ,Y0`a`v`a. ``` Cyclically transliterate only the new `a`s to vowels. ``` T`v`V`.[AEIOU] ``` Uppercase the new vowels that precede old uppercase vowels. ``` 1,2,i`[aeiou] ``` Delete alternate vowels i.e. the old vowels. If the input had all been in (say) lowercase, then it could have been done in 11 bytes: ``` Y`v`a Y`a`v ``` [Try it online!](https://tio.run/##PcjLDYAgEEXRPVU8GyCxHHcMOgoJHwMj2j2y0eRuzi0sPtHc@2KaIbUYMq33NW@MI4d9gkfIjfEfDS/wFeIYlqtoJW5wRJDhCZ/5oXgGRrqi5QK5s34B "Retina โ€“ Try It Online") Link includes test cases. Explanation: Simply cyclically transliterates all the lowercase vowels to `a`s and back to vowels. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` โ‰”uaeioฮธโญ†๏ผณโŽ‡โ„–ฮธโ†งฮนยงโŽ‡โ„–ฮฑฮนโ†ฅฮธฮธ๏ผฌโŠž๏ผฏฯ…ฮนฮน ``` [Try it online!](https://tio.run/##VY3BCsIwDIbvPkXcKYW5F9hp7CAFxYH6AHWLW2G0W5tOffraoQheEvJ/X5J2UK61aoyx8l73BrOgSNssh1mUm8Zpw3jm1PqjmlCaKfBnRJHDhZxR7oW1DUmbczjYB7lWeUItEq9Ymo6e@O@pHHSC12n6urNYv6VtMj0P2AQ/nBJTbB2GVV5vrbWMsbYdwd6O9y1IGO1C8EsKkAzaAw8EN/JcbOJuGd8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` โ‰”uaeioฮธ ``` Get the vowels into a string to reduce repetition, but start with `u` because they need to be 1-indexed. ``` โญ†๏ผณโŽ‡โ„–ฮธโ†งฮนยงโŽ‡โ„–ฮฑฮนโ†ฅฮธฮธ๏ผฌโŠž๏ผฏฯ…ฮนฮน ``` Loop over the input characters, replacing letters whose lowercase can be found in the string of vowels with letters cyclically chosen from the string or its uppercase according to the number of matches so far. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 33 bytes ``` s/[aeiou]/$&&a|(<A E I O>||U)/ige ``` [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@F@tHJ6Zm5pfG6quoqSXWaNg4KrgqeCr429XUhGrqZ6an/v@flg8Caf4gAAA "Perl 5 โ€“ Try It Online") [Answer] # [Dart (2.18.4)](https://dart.dev/), 139 bytes ``` r(s,[j=0,v='aeiouAEIOU',t,i=0])=>[for(var c=(l)=>v[(l?0:5)+j++%5];i<s.length;i++)if(v.contains(t=s[i]))c(t.codeUnitAt(0)>96)else t].join(); ``` * [Try it online](https://tio.run/##TY1Ba8JAEIXv/RXjoWSXhJCLhTZdi0gpnrzoKeSwmrEZWXdld5IKpb893Vgtwlze8L73NdrzMHgRsuqgiqxXiUZy3fx9udokGWekilqqWbV3XvTaw04JE3NfCfNWvExlekjTx2ld0mvIDdpPbktKU0l70ec7Z1mTDYJVqKiWcic4PhvcWOI5i0LOnp8kmoDAdX5wZIUsh95RA0c9Bvh@ADh5siy8SBaRhA9n9hNYgnE9wv8nhyUDBeAWYYuB80SCUpAs9FigEVmB6XoNC2zoimwY9BWhC1Le29Zt3IungePgBG4Zz/p4Mgi2O27RA3@5m2zdxjmMJWD3R3RhNOCZIuEuhB4JvLh@hl8). * [Full source](https://github.com/alexrintt/algorithms/tree/master/codegolf/replace-all-vowels-with-repeated-aeiou/dart-2.18). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 25 bytes Anonymous tacit prefix function. ``` ร—ร—(โ‰ขโดvโจ)@(|โˆŠ(vโ†'aeiou')โจ) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn///D0w9M1HnUuetS7pexR7wpNB42aRx1dGmWP2iaoJ6Zm5peqa4KE/6cBBR719j3qan7Uuwao@NB640dtEx/1TQ0OcgaSIR6ewf/TFNSd81NSFdzzc9IUFTwVcvLLUhXgInoKniUKmcUKJRmpCkmpxSV66gA "APL (Dyalog Extended) โ€“ Try It Online") `ร—`โ€ƒthe case of the lettersโ€ฆ `ร—`โ€ƒimposed as case ontoโ€ฆ `(`โ€ฆ`)@(`โ€ฆ`)`โ€ƒamend the characters **at** the following locations: โ€ƒ`|`โ€ƒwhere the casefolded charactersโ€ฆ โ€ƒ`โˆŠ(`โ€ฆ`)โจ`โ€ƒare members of the following constant: โ€ƒโ€ƒ`vโ†'aeiou'`โ€ƒthe vowels (which are assigned to `v` โ€ฆ withโ€ฆ โ€ƒ`โ‰ข`โ€ƒthe count of such located vowels โ€ƒ`โด`โ€ฆ`โจ`โ€ƒcyclically **r**eshaping the following constant: โ€ƒโ€ƒ`v`โ€ƒthe previously created `v` [Answer] # [Ruby (2.5.5)](https://www.ruby-lang.org/en/), 113 bytes ``` ->(x){p,i='aeiou',0;x.chars.map{|t|(p.include?t.downcase)?(r=p[i%5];o=(t==t.upcase)?(r.upcase):r;i+=1;o):t}.join} ``` [Try it online!](https://tio.run/##PY1Nb4JAEIbv/RUjSSOkumkPvUi2HjgYT73Yk/GwwBDGALOBWaVRfztdqpjMYT7e55nWpb9DoYflV9hHF7sgPTdI7OaL97hXWWnaTtXGXq5yDa2iJqtcjmtROZ@bzHQYrcNW2z29fh5i1qFoLcrZ6TK1qzamN/0Rc7SSmzoyNbfBQrEPg4RzhA1XxQy2UPEJ4blRsBWgDqRESLETFUQH0BqCxIwJGplvqNzJQII5PZgfAfNgaGRe7n92pTf5MiBeNYNpxt7UtkJoXJ1iC3Lm55td6UXoUyB8R1w3urEnj/A/YkYEVTD8AQ "Ruby โ€“ Try It Online") [Answer] # [Zsh](https://zsh.sourceforge.io/), 87 bytes [Try it Online!](https://tio.run/##PYxNC4JAGITv/orJDBTB8FCQJRER4alLnaSD1rv42YquGcn@dtuIhLnMwzzzbpKBmVavZf7Q@ZfdITi1EaV8zXiNHKbRm43nWa60@oIEMts3@nweGt117kqtqtOHYBiR0YXZbGGb03yzcreut7SuUg50SzikpjHoe34nHHnBJghQ8CdhJA4CgbSBSAgxNcLRv8I5UUglglBsgn@nV1RWBeHRljHVEB3/7S/g2IHU@0E5J7RI9eED) ย  ~~[123 bytes](https://tio.run/##PYxNa8JAGITv@RVjTGGXFHVLrDU0FClScvJST@Ih1nfJl64km6Qk7G9Pt5QKc5mHZ6av01EyPoxtxBYI8AIR4GnBkUcBuiihTDWbbbzbO1JVKMC8gdVhyIXhQ0kauR95QzE/eN1xLoxzq7Krlrgja0@5x1gfTYvXtXh7Xobr1WPvt4f8YemLI@fGmJG@UgXjOBLuuzoTPlQpJ4hRqpZwJzPEGlkNnRJOVOuZ@zv4TC2ySaAtm@C/03dyuZWEa3M5UQXdqT9/D4UNyL5v7WaHBpk7/gA)~~ ย  ~~[133 bytes](https://tio.run/##PYzBToNAAETvfMWUYrMbtJU2tIIS0xhjOHmwHgzhAHXJAluWwIIGgr@ONI0mc5mXN9PVfEwI7cfWI1sbWwe7DXYO7mx6n3k3lpbICjmI0ZPadak10D4IYOSugPeDIGKpbEKE4WJBiGlmlGpllRYqgdHnq2D/7L@@X5zV9DCnBiGdN88fHOvx1t2srzuzDbIr27RCSodhGNmRSwyalkB/kp8ML1IkM/gQsmX4J0v4CmkNxRliVqulfh4c@ISmRFATm@Gvs@/oVAqGojnFrIL6khf/QzYVRFMc@dnai5JHMVN4k02pj78)~~ ``` w=UAEIOuaeio;for k (${(s::)1}){let j+=${k/[$w]/1} printf ${k/[$w]/$w[j%5+(#k<91?1:6)]}} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ลพMIlรฅร…รลพMยพรจยผs.uiu ``` I/O as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//6D5fz5zDSw@3Hu4HMg/tO7zi0J5KvdLM0v//o5WclXSU8oE4BYhTgVgBiN2hYjlAnAbEilBxTyidA5UvQ9JDjDl6SOaUQNmZQFwMZYPEMpD0J0HZxVA5PaVYAA) or [verify all test cases](https://tio.run/##PcoxCsIwGAXgvad47WxzhVIqSAUnpc4p/tJA2ohJrRVXXQXvIHgBN3Fo8CJeJGZReMP7Hk9pXgpyx12fRPicr4iSfj6O3Ps109Le7MlefB1e9j48NWtF6yJWTEdseLhMrQgTJdchcki1I/wXhtxAaJiKUJI2LFhUnj4cxjvEz7Tn9UYSmrYuaQvTKRakzQopFv6HpTAVMr4RhksUqiOpmYvjRsWSH/ov). **Explanation:** ``` ลพM # Push string "aeiou" I # Push the input-list l # Convert each letter to lowercase รฅ # Check for each letter if it's in the vowels-string ร…ร # Apply on the truthy indices of the (implicit) input-list: ลพM # Push string "aeiou" again ยพรจ # Get the (modular) 0-based `ยพ`'th vowel ยผ # Then increase `ยพ` by 1 s # Swap so the current character is at the top .ui # Pop, and if it's uppercase: u # Uppercase the indexed vowel as well # (after which the list of characters is output implicitly as result) ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), 58 bytes ``` "uoiea">ir[s<l'ZLsf:l' *+fsp~[p' *sp:l-s>pl<psprlr00]pp>o] ``` [Try it online!](https://tio.run/##y6n8/1@pND8zNVHJLrMoutgmRz3KpzjNKkddQUs7rbigLroAyCousMrRLbYryLEpKC4oyikyMIgtKLDLj/3/3zk/JVXBPT8nTVHBUyEnvyxVAS6ip@BZopBZrFCSkaqQlFpcogcA "Ly โ€“ Try It Online") I thought this would be a "minor" variation on another answer I coded earlier this week. I was wrong. :) The code uses one stack to hold a list of vowels. They are rotated each time one of them is used. And it uses a second stack as a "burndown" list of the input characters (codepoints). It copies one input character at a time to the vowel stack, searches for it, and if found substitutes the "next" vowel for the top of the burndown stack. Then it switches back to the burndown stack and prints the top codepoint as a character. The upper/lowercase logic adds a bunch of code to the program and chaos of temporary stack entries... ``` "uoiea">ir - setup... "uoiea" - push vowels onto the stack >ir - switch to a new stack, read STDIN into the stack and reverse [s<l'ZLsf:l' *+fsp~[...if vowel...]pp>o] - process each char [ ] - loop until empty s<l - copy char to vowel stack 'ZL - upper case? s - save result f: - pull char forward, duplicate l - retrieve upper case 1|0 ' *+ - map to lowercase if appropriate f - pull original char forward sp - save it and delete ~ - search for lower case char [...if vowel...] - if it's a vowel, do this block pp - clean up the stack >o - switch stack, print top entry p' *sp:l-s>pl<psprlr00 - code block run if we find a vowel p - delete "if" test var ' * - calculate "should uppercase" delta sp - save and delete from stack : - duplicate current vowel l - load "uppercase" delta - - convert case if called for s> - save vowel to print, switch stacks pl - delete original vowel, load replacement < - switch back to rotating vowel stack p - clean-up stack sprlr - move vowel on top of stack to the bottom 00 - push entries on stack to match non-vowel state ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` fโ‚ฌร˜cร˜ฤ—แนศฏ"ล’lโบi$}ยก" ``` [Try it online!](https://tio.run/##y0rNyan8/z/tUdOawzOSD884Mv3hzsYT65WOTsp51LgrU6X20EKl/4fbgdKR//8rOeenpCq45@ekKSp4KuTkl6UqwEX0FDxLFDKLFUoyUhWSUotL9JR0FJRCMoAiQJSoUAIUUlSA8VMrEnMLclIV8kpzk1KLFErK8/WUAA "Jelly โ€“ Try It Online") Was originally `eโ‚ฌร˜cร„แป‹ร˜ฤ—a@ฦฒoโธO|O&32ฦŠแปŒ`, but that eventually turned into this with some inspiration from caird's answer. ``` โ‚ฌ For each character of the input, f ร˜c filter it to AEIOUaeiou, producing a mix of empty and length-1 strings. ร˜ฤ—แน Mold AEIOU to the same shape as that. ศฏ" Replace empty strings with corresponding characters from the input. " For each pair of such corresponding elements: ล’l lowercase the result ยก if โบ } the original lowercased (and wrapped in a string) i$ contains the original. ``` [Answer] # [Zsh](https://www.zsh.org/) `--extendedglob`, 63 bytes ``` v=aeiouAEIOU <<<${1//(#m)[$v]/$v[$[#MATCH>91?1+i++%5:6+i++%5]]} ``` [Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/ElaahqfG/zDYxNTO/1NHV0z@Uy8bGRqXaUF9fQzlXM1qlLFZfpSxaJVrZ1zHE2cPO0tDeUDtTW1vV1MoMQsfG1v7X5EpTUHLOT0lVcM/PSVNU8FTIyS9LVYCL6Cl4lihkFiuUZKQqJKUWl@gp/QcA "Zsh โ€“ Try It Online") [Thanks to @roblogic for the answer without `--extendedglob`](https://codegolf.stackexchange.com/a/255786/86147) which kicked this off. I've got basically the same logic, just using `(#m)`+`$MATCH` to keep track of the upper/lower case within a single PE. [Answer] # [Arturo](https://arturo-lang.io), 79 bytes ``` $=>[i:0v:"aAeEiIoOuU"map&'c[(v=v--c)?->c[x:(c>`^`)?->0->1v\[x+i%10]'i+2]]|join] ``` [Try it](http://arturo-lang.io/playground?ujcLPQ) [Answer] # [Scala](http://www.scala-lang.org/), 147 bytes Golfed version. [Try it online!](https://tio.run/##XY8xa8MwFIT3/IqLoSDRYNqhS4wKJUMJFDok6VI6KMlzrFa2jPScuIT8dle20w4FDe@k@@6ewk5b3bntJ@0Yb@5EdlWYnHGeAHvKUWpTCe0PYY4n7/X3@4q9qQ4fco5NZRgK56735aKdj09SnY/aQ9QzI5VINBnXJLM7mbVpqWvB6tHkok53ruKYHQSn7F5isZcyghZe1cLcPMisF05FM6cmbOo6Onz0DhPIBoLPzK26z9xlUCzT8mvc4dLF9YE6zmwrkYtk4faEZ2fzKZaw7kj4u0mxZJgALghbCpwmEkohWejeYHrkFbY5aixob67IhqGviBmQ/4XrIkbGo8Exc4pfTa0ua0uomnIb/8En99u3LmIiRRPYjUQT@hJqTSTcQOieoLHuMrl0Pw) ``` def f(x:String)={var (p,i)=("aeiou",0);x.map(t=>if(p.contains(t.toLower)){val r=p(i%5);val o=if(t.isUpper)r.toUpper else r;i+=1;o}else t).mkString} ``` Ungolfed version. [Try it online!](https://tio.run/##XZDBasMwEETv/oqpoWBTMO2hl0ACJYcSKPSQpJfSg5LIsVrZEvI6cQn@dndt2W4ICLSa3TcjttwLLdrW7L7lnvBhzlKvM5USLgFwkClyoYpIuGM5w4tz4vdzTU4Vx694hm2hCPN@EjgJjXQG38V8MVWI6lGOO92Pe8ByOxRSmSqcVAfF6uPwrpNcWFzAQYtBAlSKyCZ7UxB/rowoIfPGP3dxPLmPCY69bKRwj@f4pmW41TlRosqttYzDsVNfQupSwl0RCg9zPF0JZqobP30dTf/NoWqS/MdvIfByf1kWSBdRGoVLc5B4NTq9wwranCQmJcGKoEpQJrGTJSUhb5I3txTdgOqQd@jqJLCUBzUgW4IYENUjt4GbjC35CBB73mF8y1rkVksUVb7jTdDZjHmbjB0lD4GMJ6qyC5G1YsL0hOgI6eOaoAna9g8) ``` object VowelShift { def main(args: Array[String]): Unit = { val f: String => String = (x: String) => { val p = "aeiou" var i = 0 x.map { t => if (p.contains(t.toLower)) { val r = p(i % 5) val o = if (t.isUpper) r.toUpper else r i += 1 o } else { t } }.mkString } println(f("Code Golf! I love Code Golf. It is the best.") == "Cade Gilf! O luva Cedi Golf. Ut as the bist.") println(f("This is a test! This is example number two.") == "Thas es i tost! Thus as eximplo numbar twe.") } } ``` ]
[Question] [ **Task:** Given an array of numbers as input (you can choose what subset, such as integers or natural numbers), replace all items with the number of times they appear within the array. As an example, `[1, 2, 2, 1, 4, 8, 1]` would become `[3, 2, 2, 3, 1, 1, 3]`. You can take input/produce output as arrays, lists, tuples, or any other reasonable representation of some numbers. **Test cases:** ``` [1] [1] [1, 2] [1, 1] [1, 1] [2, 2] [1, 4, 4] [1, 2, 2] [4, 4, 2] [2, 2, 1] [4, 4, 4, 4] [4, 4, 4, 4] [10, 20, 10, 20] [2, 2, 2, 2] [1, 2, 2, 4, 4, 4, 4] [1, 2, 2, 4, 4, 4, 4] [1, 2, 2, 1, 4, 8, 1] [3, 2, 2, 3, 1, 1, 3] ``` **Other:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer (in bytes) per language wins! [Answer] # [Python 2](https://docs.python.org/2/), 23 bytes ``` lambda l:map(l.count,l) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKjexQCNHLzm/NK9EJ0fzf3lGZk6qgqFVQVFmXolCmkZmXkFpiYam5v9ow1iuaEMdBSMIBeWZABGQZQJmGcFZUGFDA6AgEENoqH4wQlIGAA "Python 2 โ€šร„รฌ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` &=s ``` [Try it online!](https://tio.run/##y00syfn/X822@P//aEMdBSMwAjJMdBQsgIxYAA) Or [verify all test cases](https://tio.run/##y00syfmf8F/Ntvi/S8j/aMNYrmhDHQUjCAXlmQARkGUCZhnBWVBhQwOgIBBDaKh@MEJVBhOFGGgBMh0A). ### Explanation ``` % Implicit input: numeric row vector &= % Matrix of all pairwise equality comparisons s % Sum of each column % Implicit display ``` [Answer] # JavaScript (ES6), 36 bytes ``` a=>a.map(x=>a.map(y=>t+=x==y,t=0)|t) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKMCxqi0tSvRtq2wta3UKbE10Kwp0fyfnJ9XnJ@TqpeTn66RphFtGKuAATQ1FfT1FYBSXOiKdRSMYnEo1lHAqt4Qh3ojkFFY1JsAUSx287FqMQFrMYrFYQU2V0G0oFoE1YIkheE2A6BxQAyhYzEtwuUjiBSSyag@QpH6DwA "JavaScript (Node.js) โ€šร„รฌ Try It Online") [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 6 bytes [SBCS](https://github.com/abrudz/SBCS) ``` +/โ€šร รฒ.=โ€šรงยฎ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=09Z/1DFDz/ZR7woA&f=S1MwVDACQkMFEwULBUMA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f) ``` +/โ€šร รฒ.=โ€šรงยฎ dfn submission โ€šร รฒ.= product table using equality โ€šรงยฎ applied to the input on the left and the right +/ reduce by addition / sum ``` [Answer] # [Factor](https://factorcode.org/), 28 bytes ``` [ dup histogram substitute ] ``` [Try it online!](https://tio.run/##ZU8xDsIwDNz7intB1UYMCB6AWFgQE2IIwdCqtA2xM6Cqbw9pBSgIW7LuztbZvmojvQuH/Xa3WaEh19Edmrk3jFZLlbNoqVnqyK0jkad1dSdgenjqDDHW2ZAhxoAS4xepBKf6IuaHTVj9sLRbFlDFu6a@6n9yVifv5bxrDEdcvEUV7@5vTrdgf44viBfCKbTaIn5lmjy8AA "Factor โ€šร„รฌ Try It Online") It's a bit shorter than the version for squares: ``` [ dup [ '[ _ = ] count ] with map ] ``` ## Explanation: It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence on the data stack as output. Assuming `{ 1 4 4 }` is on the data stack when this quotation is called... * `dup` Duplicate an object. **Stack:** `{ 1 4 4 } { 1 4 4 }` * `histogram` Create a histogram from a sequence. **Stack:** `{ 1 4 4 } H{ { 1 1 } { 4 2 } }` * `substitute` Take a sequence and an associative array and substitute elements in the sequence that have keys in the assoc with their values. **Stack:** `{ 1 2 2 }` [Answer] # Ruby, 27 bytes ``` f=->*a{a.map{|e|a.count e}} ``` Testing: ``` p f[4,3,4] #=> [2, 1, 2] ``` [Answer] # [Raku](http://raku.org/), 10 bytes ``` {.Bag{$_}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Ws8pMb1aJb629n9xYqWCkkq8gq2dQnWaAlBISSEtv0jBxtBOB0goGEEoKM9EwQTEAFIQCRADKmZooGBkoAAm7az/AwA "Perl 6 โ€šร„รฌ Try It Online") `.Bag` generates a Bag (a set with multiplicity) from the input argument `$_`. Then `{$_}` slices into that Bag with the original list, producing a list of the multiplicities of the elements of that list, in order. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` โ€šร รฃ;?{โ€šร ร ยทยตร }ยทโˆ‚รบ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/486uq3tqx91dDzc2lH7cNuc//@jow1jdRSiDXUUjKA0jG8CRCCmCZhphGDCJAwNgMJADKFhpoARksJYAA "Brachylog โ€šร„รฌ Try It Online") [Generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output through the output variable. ``` โ€šร รฃ; Pair some element of the input with ? the input. { }ยทโˆ‚รบ In how many ways is โ€šร ร ยทยตร  the element an element of the input? ``` Using `ยทยชรง` comes out one byte longer: # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` โ€šรผยฎยทยชรงโ€šรผยฎโ€šร รฃhโ€šรผยฉโ€šร รฃโ€šรผยฉt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/4/mr3i4uxdIPurozng0fyWQApIl//9HRxvG6ihEG@ooGEFpGN8EiEBMEzDTCMGESRgaAIWBGELDTAEjJIWxAA "Brachylog โ€šร„รฌ Try It Online") Also [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output through the output variable. ``` โ€šร รฃ Choose an element of the input. โ€šรผยฎ hโ€šรผยฉ It is the first element of โ€šร รฃ an element of โ€šรผยฎยทยชรง โ€šรผยฉ the list of pairs [element of input, how many times it occurs in input] t the last element of which is the output. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ฦ’รฃโ€šยฑร† ``` [Try it online!](https://tio.run/##y0rNyan8//9I96ON6/4fbn/UtObopIc7ZwDpyP//o6MNY3W4og11FIygNIxvAkQgpgmYaYRgwiQMDYDCQAyhYaaAEYrCWAA "Jelly โ€šร„รฌ Try It Online") ## How it works ``` ฦ’รฃโ€šยฑร† - Main link. Takes a list L on the left โ€šยฑร† - For each element in L ฦ’รฃ - Count the times it appears in L ``` [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda l:[*map(l.count,l)] ``` [Try it online!](https://tio.run/##bU7dDoIgFL7Wpzh3QjGn5pVbb9EdcUGlkw2RGdR6ekJx60cY7Ox8v@iX6Ud1cB0c4ewkHy43DrKhu4FrJPPraJUhEjP37IVs4TTZtkkT4dXtg0sklLYG4fyupTAoYxmmBdvPM030JJRBgkCHBMaOlgxix@MpLQlULMYRWOmYm1azbaFrf1nEvSrqRbGpWAJCRVBsYr5xX1R4vX9hsr@Yz2/C8hsZxd8 "Python 3 โ€šร„รฌ Try It Online") -5 bytes (indirectly) [thanks to xnor](https://codegolf.stackexchange.com/a/224134/66833)! [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` /LQ ``` [Test suite](http://pythtemp.herokuapp.com/?code=%2FLQ&test_suite=1&test_suite_input=%5B1%5D%0A%5B1%2C+2%5D%0A%5B1%2C+1%5D%0A%5B1%2C+4%2C+4%5D%0A%5B4%2C+4%2C+2%5D%0A%5B4%2C+4%2C+4%2C+4%5D%0A%5B10%2C+20%2C+10%2C+20%5D%0A%5B1%2C+2%2C+2%2C+4%2C+4%2C+4%2C+4%5D&debug=0) Explanation: ``` /LQ | Full program /LQQ | with implicit variables -----+------------------------------------- L Q | replace each element d in input with / Q | the count of d in input ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes ``` vO ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=vO&inputs=%5B1%2C%202%2C%202%2C%201%2C%204%2C%208%2C%201%5D&header=&footer=) Wow y'all using unicode in your golfing languages while I'm chilling in the ASCII zone. ## Explained ``` vO # vectorise count over the input # essentially, [input.count(n) for n in input] ``` [Answer] # JavaScript (ES2021), 35 bytes (not quite reasonable I/O) ``` a=>a.map(n=>a[++(a[n]||=[0])[0],n]) ``` Accept an array of ~~1 element array of~~ *negative* numbers. Return an array of 1 element array... ``` f([-1, -2, -2, -1, -4, -8, -1]) // [[3], [2], [2], [3], [1], [1], [3]] f([[-1], [-2], [-2], [-1], [-4], [-8], [-1]]) // [[3], [2], [2], [3], [1], [1], [3]] ``` ~~Just consider input / output as column vectors...~~ --- # JavaScript (ES2021), 42 bytes Add an extra `.flat()` to make it reasonable would cost +7 bytes (42 bytes in total) ``` a=>a.map(n=>a[++(a[n]||=[0])[0],n]).flat() ``` That's too long. [Answer] # [Racket](https://racket-lang.org/), 42 bytes ``` (ล’ยช(b)(map(ล’ยช(y)(count(ล’ยช(x)(= x y))b))b)) ``` [Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE5nBppKSmZealKqT91zi3WyNJUyM3sQDEqtTUSM4vzSsBsSs0NWwVKhQqNTWTwOi/JhcXSJ1CmoK6hoahJpcCDGgYKhihctFkTRRMkAWAXFQNIAE0NYYGCkYGCmASzSYgxKYeLAGyygJoO9C1AA "Racket โ€šร„รฌ Try It Online") [Answer] # [J](http://jsoftware.com/), 6 bytes ``` 1#.=/~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1bPXr/mtyKXClJmfkK6QpaOgYasLYhgpGCKaJggmCYwhjAkURikwgEK7MQMHIAEIimQiE6OrAgiAbLIAGK8DAfwA "J โ€šร„รฌ Try It Online") # [K (oK)](https://github.com/JohnEarnest/ok), 9 bytes ``` {+/x=\:x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWlu/wjbGqqL2f5q6ho6htYKhghGIALNMFEysQQRIyAQCgcIGCkYGEBKsGggRcmAuSKOFgqHmfwA "K (oK) โ€šร„รฌ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 27 bytes ``` f a=[sum[1|y<-a,y==x]|x<-a] ``` [Try it online!](https://tio.run/##bU7bCsIgGL7fU/xEsI3ssNhVze6D3kD@CyFX0ubGZqDQu5vbgk6K8ut39Mr7m6gq50rglPX3mmUPWyw5sZQafBh/RVdzqei5iSCRpEmLZVnzFjSX1apvuUrWNMY4LeaHi9AnqUQEldBgaCf4OZGLxQxn6W7Hjkrj3o4o@Ky2k0onpddRSwyxaQRDj2MZQmh5PGIZgS2GOAIvOuRm28E20rnfGHC/FPmo@KsYA6aKSfEX84n7oo3X@zNN/Il5/2Z6fEcG8Sc "Haskell โ€šร„รฌ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` ยฌยข ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0KL//6MNdRSMwAjIMNFRsAAyYgE "05AB1E โ€šร„รฌ Try It Online") Beats all other answers. ``` ยฌยข # full program ยฌยข # number of times... # (implicit) each element in... # implicit input... ยฌยข # appears in... # implicit input # implicit output ``` [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 22 bytes ``` s/\S+/grep$_==$&,@F/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZYWz@9KLVAJd7WVkVNx8FNPz31/39DBSMgNFQwUbBQMPyXX1CSmZ9X/F@3IBEA "Perl 5 โ€šร„รฌ Try It Online") [Answer] # Excel 17, bytes ``` =COUNTIF(A1#,A1#) ``` Assuming `A1 = { .... }` then this works. It's a longer, less flexible formula if the data in entered in individual cells. [Answer] # Java, 58 bytes ``` l->l.stream().map(x->java.util.Collections.frequency(l,x)) ``` [Try it online!](https://tio.run/##tZI9a8MwEEB3/wqNUrGPJGQoJPVSKBTayWPpoDqykStLinQOMSW/3ZU/kg7t0IBzSAjdHU8PThU/8KTafXaytsYhqcIdGpQKXqTHTfQr7dEJXsPdH6Wi0TlKo/tiZJsPJXOSK@49eeVSk6@IhJjyHjmG42DkjtShSjN0Updv74S70rOxt4@nCbrtfbbPGkUpXBqTbPC4JFJSPHQqSc@ClEHNLT0m6Y/fo1FKDDAPhRP7Rui8pSo@MtZtLg9mrUdRg2kQbFBCpWkB3FrV0l4BTEGXjEE@wugENc4Dmr6BMsauo8VkNTdwdsN1WLMy1wNzdQPm7KrLRRANezxnn/2wbqV@5o8jvP/3zzhFp@4b) # Java, 56 bytes ``` l->l.stream().map(x->l.stream().filter(y->y==x).count()) ``` This only works for integers in the Integer Cache (-128 to 127, by default). [Try it online!](https://tio.run/##tZLBasMwDIbveQof7dGYtvQwaJLLYFDoTjmOHTzXCU4d29hKaRh99sxO2sHYDhukQkZYkn99IDfsxNLmcBxka40D1IQ77UAqupcetsmPtAcnWEsffilVneYgjY7FxHbvSnLEFfMevTCp0UeCgl3zHhiEcDLygNpQxSU4qevXN8Rc7cnUG@35KppFnmynQdTCFQtUjhzZ3ui6KFCVDyotbnSY0JZZfP6WqaQC4XCfFn2enwnlptOACRm2X7PK3oNoqemA2kADSuOKMmtVj@N0aiq8IvGlUoIDfpqicZ6CiQ1BjfxPbYHWcwvOTrgJPqvmZtRc30FzdtTVMoCGM8XZdz/6vdBv@tMKH//8My7JZfgE) [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 2 \log\_{256}(96) \approx \$ 1.65 bytes ``` ec ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhaLUpMhDCh_wdZoQx0FIzACMkx0FCyAjFiIJAA) ``` ec : implicit input array e : map the input to the following: c : count the occurrences of the number in the input : implicit output ``` Thought I'd try an easy and short problem for my first Thunno answer. [Answer] # [Julia 1.0](http://julialang.org/), ~~24~~ 21 bytes ``` [[emailย protected]](/cdn-cgi/l/email-protection)(==(a),[a]) ``` [Try it online!](https://tio.run/##bZGxCoMwEIb3PMWBi4KURh26BFx8g25yQyhCW2wtTaROvnp6JhRieuFCjvzf/fkh93m8abk4t2rVHi7T/LS5Urkuyl5j4TLoFv14jYNozXX6wNrLEipf1DQlnKhBITI4D8Ya0WpjhrfdOARmKQWkxBh5IY955x0peXLLk5CUrEHWM4UbD1fI2yYZApyab3CkxEmO5EE7nPhnziQPt7uHouQ7hRuMfiUM1j@l9iJVjcJ9AQ "Julia 1.0 โ€šร„รฌ Try It Online") -3 bytes thanks to MarcMush: replace `Ref(a)` with `[a]` [Answer] # [R](https://www.r-project.org/), 26 bytes ``` ave(a,a<-scan(),FUN=table) ``` [Try it online!](https://tio.run/##K/r/P7EsVSNRJ9FGtzg5MU9DU8ct1M@2JDEpJ1Xzv6GCERAaKpgoWCgY/gcA "R โ€šร„รฌ Try It Online") `ave` takes a vector `x`, an arbitrary number of grouping variables `...`, and a function `FUN`, and replaces each element of `x` with the result of applying `FUN` to the group containing that element. I've also found a number of 26 byte variants with `FUN=sum`; they differ only in the way they generate a vector of ones with length `length(a)`. ``` ave(a^0,a<-scan(),FUN=sum) ave(a,a<-scan(),FUN=sum)/a ave(a|1,a<-scan(),FUN=sum) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ยฌยฃโˆšยฎยฌโ€ขX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o%2bilWA&input=WzEsMiwyLDEsMyw0LDQsMl0tUQ) maps input by returning number of occurrence in input [Answer] # [PHP](https://php.net/), 56 bytes ``` fn($a)=>array_map(fn($e)=>array_count_values($a)[$e],$a) ``` [Try it online!](https://tio.run/##dU/NCoMwDL73KXLooYWCU7w5tweRIGWreJgu6Crs6bs62fCnLSmBfH8JteTOV2qJMd5ACa7pBdeyvOhh0O@60yTmiflPbk/bv@pJP6wZZ2bFDSrfXcHYpIf6bjsSvBFVinB4UhaQJOCxHVdBhjGuggA9jdGz2epAz31hxD2gyL@KDGMBx5UWxTbmp1hhu8VO3sv/pWMgJnzNAqxsd9dsMPcB "PHP โ€šร„รฌ Try It Online") As usual, those "array\_" PHP prefixes are ruining the golfing :P [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 32 bytes Nothing special ``` a=>a.Select(x=>a.Count(y=>x==y)) ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXEh2ro@Dpmleam1qUmJSTChKys1NIA8oq2Cr8T7S1S9QLTs1JTS7RqACxnfNL80o0Km3tKmxtKzU1/1tzOefnFefnpOqFF2WWpPpk5qVqFJcUZeal63nlZ@ZpKOko6YBN08hLLY@OVahWMFSo1dTUJEOfgY6CERCDaXLNAGoFIyDDREfBQgfmmv8A "C# (Visual C# Interactive Compiler) โ€šร„รฌ Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes Right language, right time. ``` ล’ยฎ๏ฃฟรนรฏโ€  ``` [Try it online!](https://tio.run/##y0vNzP3//9yKD3OnLvj/P9pQwQgIDRVMFCwUDGMB "Neim โ€šร„รฌ Try It Online") Explanation: ``` ล’ยฎ # Apply next token to all in list ๏ฃฟรนรฏโ€  # Count element in list ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~84~~ \$\cdots\$ ~~81~~ 75 bytes Saved 6 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` b;i;j;f(*a,l){for(i=-1;++i<l;printf("%d ",b))for(b=j=l;j--;)b-=a[i]!=a[j];} ``` [Try it online!](https://tio.run/##dZPrboMwDIX/8xQeUiXSglauRUvZHmSrJnqhCsroVKrdEK8@ZpK0UG@roA7@Tk4sy9l4G5lX@65bc8FLXjjT3JWsKQ5HR2Sez2czsZT89SiqU@HYky3Y7pqxHq@zMpO89DzO1l6WP4rVDf6XK952bwexBbXHwRem@fGYf7rQr@WuYlZjAf7QBBQXkMGcY1j2mAOeyaCBy6H1ZGvj7gcb7DsbV8oOz2McWqu1rN7jJReVc3buE6ddfXqeP67Qu/FbPuR8k3MhGKeDS/pKHV7SET5jEmkSKXJlFY8J3ZYYwzluwlfHsWAx1Keev21SotIFpqr66x5IrazF1@5QOLot7NZ8Ts23C2PuE@4THhAeEB4SHhIeER4RHhMeE54QnhC@IHxBeEp4yoamTVXXat003R3XDI6JgYmhiZGJsYmJiQsTU2M@zHu13X2YmVfL5bi6@rq4mqkL0euYstEjPlSLRrpipVnxMQZpKE4BxefrZTOSc04uSPZbCN49jMXFf8Kn6izD69l9bwqZ7@vOe/8B "C (clang) โ€šร„รฌ Try It Online") Inputs a pointer to an array and its length (because array pointers in C don't carry any length info) and prints the occurrence counts. [Answer] # [Zsh](https://www.zsh.org/), 23 bytes ``` xargs -I. grep -c . f<f ``` [Try it online!](https://tio.run/##qyrO@G@X9r8isSi9WEHXU08hvSi1QEE3WUFPIc0m7f9/Qy4jIDTkMuGy4DL8DwA "Zsh โ€šร„รฌ Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), 2 bytes ``` ฦ’รชโ€ฆรฎ ``` [Try it online!](https://tio.run/##K6gs@f//yISTU/7/jzbUUTACIyDDREfBAsiIBQA "Pyt โ€šร„รฌ Try It Online") ``` ฦ’รช implicit input; duplicate โ€ฆรฎ for each item in input, count occurrences in input; implicit print ``` ]
[Question] [ # Challenge Write the shortest snippet of code possible such that, when N copies of it are concatenated together, the number of characters output is N2. N will be a positive integer. For example if the snippet was `soln();`, then running `soln();` would print exactly 1 character, and running `soln();soln();` would print exactly 4 characters, and running `soln();soln();soln();` would print exactly 9 characters, etc. Any characters may be in the output as long as the total number of characters is correct. To avoid cross-OS confusion, `\r\n` newlines are counted as one character. **Programs may not read their own source or read their file size or use other such loopholes.** Treat this like a strict [quine](/questions/tagged/quine "show questions tagged 'quine'") challenge. The output may go to stdout or a file or a similar alternative. There is no input. Comments in the code are fine, as is exiting mid-execution. Any characters may be in the program. The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. [Answer] # TECO, 4 bytes ``` V1\V ``` `V` prints the contents of the current line in the text buffer. `1\` inserts the string representation of the number 1 at the current position. So on the *N*th iteration of the program, the first `V` will output *N - 1* copies of the character `1`, then add another `1` to the text, then output *N* `1`s. [Answer] # Brainfuck, ~~17~~ 16 bytes ``` [>+>-..+<<-]-.>+ ``` You can test it [here](http://copy.sh/brainfuck/). Just use the fact that `n2+2n+1=(n+1)2`. [Answer] # Brainfuck, 11 I saw the first Brainfuck answer and thought it's way too long :) ``` [.<]>[.>]+. ``` The output may be easier to see if you replace the plus with a lot more pluses. On the Nth iteration, each loop outputs N - 1 copies of the character with ASCII value 1, and then one more with `+.`. [Answer] # Python 2, 22 ``` a='';print a;a+='xx';a ``` Prints the empty string, then two `x`'s, then `x`' four and so on. With the newline after each string, this comes out to `n*n` characters. One copy: `"\n"` (1 char) Two copies: `"\nxx\n"` (4 chars) Three copies: `"\nxx\nxxxx\n"` (9 chars) In order to stop the initial variable `a` from being reinitialized each run, I end the code with a `;a`, which is benign on its own, but combined with the next loop to create the scapegoat `aa` to be assigned instead. This trick isn't mine; I saw it in a previous answer. I'd appreciate if someone could point me so I could give credit. [Answer] # CJam, 6 bytes ``` LLS+:L ``` Uses the fact that `n2 + n + (n+1) = (n+1)2`. ``` L "Push L. Initially this is an empty string, but its length increases by 1 with each copy of the snippet."; L "Push another L."; S+ "Add a space to the second copy."; :L "Store the lengthened string in L for the next copy of the snippet."; ``` [Answer] # [///](http://esolangs.org/wiki////), 21 bytes I'm sure there is a really short and twisted way to solve this in **///** but I couldn't find anything, beyond the "straightforward" way yet: ``` 1/1\//112\///2\//1\// ``` This is based on the approach of printing consecutive odd numbers. The snippet consists of a `1` at the start which is printed, and two replacements which add two more `1`s to that first part of each consecutive copy of the snippet. Let's go through this for `N = 3`. The following should be read in groups of 3 or more lines: 1. the current code, 2. the processed token(s), 3. (and following) a comment what the above token does. ``` 1/1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\// 1 is printed /1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\// /1\//112\// replaces all occurrences of 1/ with 112/. This affects the starts of all further snippets but not the substitution commands, because the slashes in those are always escaped. It is necessary to put a 2 in there, because otherwise the interpreter goes into an infinite loop replacing the resulting 1/ again and again. /2\//1\//112/1\//112\///2\//1\//112/1\//112\///2\//1\// /2\//1\// Replace all occurrences of 2/ with 1/, so the the next snippets substitution works again. 111/1\//112\///2\//1\//111/1\//112\///2\//1\// 111 is printed /1\//112\///2\//1\//111/1\//112\///2\//1\// /1\//112\// add two 1s again /2\//1\//11112/1\//112\///2\//1\// /2\//1\// turn the 2 into a 1 again 11111/1\//112\///2\//1\// 11111 print 11111 /1\//112\///2\//1\// the last two substitutions have nothing to substitute so they do nothing ``` Interestingly, it works just as well if we move the `1` to the end: ``` /1\//112\///2\//1\//1 ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 14 bytes ``` 1:na*a*';'10p! ``` Uses the "sum of consecutive odd integers starting from 1" idea. It starts off with 1 and multiplies it by 100 each time, increasing the length of the output progressively by increments of 2. For example, appending 5 copies gives ``` 1100100001000000100000000 ``` I tested by piping the output to a file, and didn't see a trailing newline. ## Breakdown ``` 1 Push 1, skipped by ! every time except the first :n Copy top of stack and output as num a*a* Multiply by 10 twice ';'10p Modify the source code so that the first : becomes a ; for termination ! Skip the next 1 ``` [Answer] # CJam, ~~10~~ 9 bytes ``` ],)_S*a*~ ``` This prints N2 spaces where `N` is the number of copies of the code. **Code eexpansion**: ``` ], "Wrap everything on stack and take length"; )_ "Increment and take copy"; S* "Get that length space string"; a* "Wrap that space string in an array and create that many copies"; ~ "Unwrap so that next code can use to get length"; ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # Python 2, 20 bytes ``` g=0 print'g'*g;g+=2# ``` [Answer] # Java - 91 bytes ``` {String s=System.getProperty("a","");System.out.println(s);System.setProperty("a","xx"+s);} ``` This solution is equivalent to [this other one](https://codegolf.stackexchange.com/a/45381) in Python. It surely won't win, but it was fun :) [Answer] ## Perl, 14 bytes ``` print;s//__/; ``` This needs to be run with Perl's `-l` command switch, which causes `print` to append new lines. It prints the default variable `$_`, then prepends two underscores via substitution. Example: ``` $ perl -le 'print;s//__/;print;s//__/;print;s//__/;print;s//__/;' __ ____ ______ ``` [Answer] # Brainfuck, 10 chars Both previous Brainfuck solutions were *waaay* too long (16 and 11 chars) so here is a shorter one: ``` +[.->+<]>+ ``` In the `n`-th block it prints out `2*n-1` characters (with codepoints from `2*n-1` to `1`) [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), ~~18~~ 12 bytes ``` ^1+(9!1-)#2+ ``` This prints N2 tabs. It assumes a standard-compliant interpreter which prints characters instead of numbers, so if you use [the Python interpreter](https://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) you'll need to set `NUMERIC_OUTPUT` to `False`. The idea is simply to use the top of the stack (which is initially 0) as `2(N-1)`, and print `2N-1` tabs, then increment the top of the stack by 2. Hence each repetition prints the next odd number of tabs. [Answer] ## Java - 59 / 44 (depending on requirements) ``` static String n="1"; static{System.out.print(n);n+="11";}// ``` Apparently we're allowed to assume code runs in a class. If it can go inside a main method: ``` String n="1"; System.out.print(n);n+="11";// ``` [Answer] # C, 87 bytes ``` #if!__COUNTER__ #include __FILE__ main(a){a=__COUNTER__-1;printf("%*d",a*a,0);} #endif ``` This uses two magic macros. `__COUNTER__` is a macro that expands to `0` the first time it is used, `1` the second, etc. It is a compiler extension, but is available in both gcc, clang, and Visual Studio at least. `__FILE__` is the name of the source file. Including a file in C/C++ is literally the same as pasting it directly into your source code, so it was a little tricky to make use of. It would still be possible to use this technique without `__COUNTER__`. In that case, the standard guard against using code twice could be used for the `#if` statement, and `__LINE__` could be used to count the number of characters needed. [Answer] # Dyalog APL, ~~20~~ 19 bytes A matrix based solution. ``` {โบโ‰ขโต:โตโชโต,โบโ‹„โˆŠโบ}โจโช'a' ``` [Try it here](http://tryapl.org/). Returns a string of `N2` repetitions of `a`. Explanation by explosion for `N = 2`: ``` {โบโ‰ขโต:โตโชโต,โบโ‹„โˆŠโบ}โจโช'a'{โบโ‰ขโต:โตโชโต,โบโ‹„โˆŠโบ}โจโช'a' โช'a' Wrap 'a' into a 1x1 matrix. 'a'{ }โจ Binary function: bind 'a' to โต and the matrix to โบ. โบโ‰ขโต: The arguments are not identical, โตโชโต,โบ so add to the matrix 1 column and 1 row of 'a's. โช Identity function for a matrix. { }โจ Unary function: bind the matrix to both โต and โบ. โบโ‰ขโต: The arguments are identical, โˆŠโบ so flatten the matrix into the string 'aaaa'. ``` [Answer] ## STATA 20 ``` di _n($a) gl a=$a+2 ``` There is a trailing new line to make sure that the display (di) statement works. First display the current number in $a newlines (and one additional from the default of display). Then add 2 to $a. Uses the even numbers approach (i.e. odd numbers approach minus 1) with an extra newline every time. [Answer] ## T-SQL 117 ``` IF OBJECT_ID('tempdb..#')IS NULL CREATE TABLE #(A INT)INSERT INTO # VALUES(1)SELECT REPLICATE('a',COUNT(*)*2-1)FROM # ``` Note the trailing space to ensure that the if condition is properly checked every time. Uses the odd numbers approach. Not sure if there's a newline on select statements. Not sure if there's a shorter way to create a table if it doesn't exist. [Answer] # PostScript, 35 chars ``` count dup 2 mul 1 add string print ``` Each pass "leaks" one thing on the stack, so `count` goes up by 1 each time. Then it justs uses the sum of odd numbers trick. The bytes output are all `\000` because that's the initial value of strings. [Answer] # Haskell, 72 ``` putStr$let a="1";aputStr=(\n->take(n^2)$show n++cycle" ").(+1).read in a ``` ## Explanation The apply operator `$` acts as if you place surrounding parentheses around the rest of the line (there are exceptions to this, but it works in this case). `aputStr` is a function that takes a string with the format "abc ...", where "abc" is the square root of the length of the string, including abc. It will parse the string as an integer, and return a string starting with abc+1 and having that length squared. Because of the `$` operator, this will get called recursively on "1" N times. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` :I,โ‡ง ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI6SSzih6ciLCIiLCIiXQ==) -2 thanks to lyxal. Note: output is in spaces + newlines. [Answer] # Pyth, 8 bytes ``` *d*2Z~Z1 ``` This relies on the fact that N2 is equal to the sum of `N` odd numbers. Now Pyth auto prints an new line, so I have to just print `Z * 2` characters in each code where `Z` goes from `0` to `N - 1`. **Code Expansion**: ``` *d "Print d whose value is a space character" *2Z "2 * Z times where Z's initial value is 0" ~Z1 "Increment the value of Z"; ``` [Try it online here](http://pyth.herokuapp.com/) [Answer] # Golflua, 23 bytes ``` X=2+(X|-2)w(S.t("&",X)) ``` outputs a combination of `&` and `\n` characters. ### Equivalent Lua code ``` X = 2 + (X or -2) -- initialize X to 0 the first time, add 2 ever other time print(string.rep("&", X)) ``` Each time the code snippet runs it produces 2 more characters of output than the last time, starting with 1 character. The `print` function appends a newline, so I initialize X to 0 instead of 1. [Answer] ## ActionScript - 27 / 26 bytes ``` var n="" trace(n);n+="11"// ``` or ``` var n=1 trace(n);n+="11"// ``` How it works: ``` var n="" trace(n);n+="11"//var n="" trace(n);n+="11"// ``` It simply comments out the first line. Note: `trace` adds a newline. Or maybe all the IDE's I use do that automatically. [Answer] # GML, 27 ``` a=''show_message(a)a+='xx'a ``` [Answer] # [Nim](https://nim-lang.org/), 24 bytes ``` var s="" echo s s&="ss"# ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY7yhKLFIptlZS4UpMz8hWKuYrVbJWKi5WUIdJQVTDVAA) [Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3K8oSixSKbZWUuFKTM_IVirmK1WyViouVlGktDrEf6gyYcwA) [Answer] # [Zsh](https://www.zsh.org/), 12 bytes ``` <<<$n n+=.. ``` [Try it online!](https://tio.run/##TY7BqsIwFET39ysGvZKEYrEuY/MV2QpSSvsMSNqXpG9h6LfXYhXe7nCGGeYZ74s1Yqnrmj35wpQlLYKs4Wx1pY/VTGNwPuEYsLPDFNpOg7P8LZSdd0T9EOAgc1WW59OsLpkAe3OFYbtS99c8IHqppODVCiVotcOUxikZlv0F7/EeWgF7sIRCTMGNESk07uH8D@LYtF38V8sb6NP7Hb4T4qNxiFff3psQNxTgLQHvN6B5eQE "Zsh โ€“ Try It Online") Same \$ n^2 = \sum\_{k=1}^n 2k + 1 \$ as has been used elsewhere. The TIO test has to do some extra work because naively capturing the output in `$(f)` removes trailing newlines, and would output `0`, `3`, `8`, `15`, etc. Instead, we insert a `printf :` to add a character after the last newline, then `${output:0:-1}` to remove it. [Answer] # [Pyt](https://github.com/mudkip201/pyt), 10 bytes ``` 0วฐฤ…ลโปโˆšโบยฒโ‘ดวฐ ``` [Try it online!](https://tio.run/##AR4A4f9weXT//zDHsMSFxYHigbviiJrigbrCsuKRtMew//8 "Pyt โ€“ Try It Online") ``` 0 pushes 0 วฐ วฐoins stack with no delimiter ฤ… convert to ฤ…rray of characters ล get the ลength โป decrement โˆš square root โบ increment ยฒ square โ‘ด array of (top of stack) 1s วฐ วฐoin array with no delimiters (implicitly prints at end of code) ``` ]
[Question] [ Suppose a new [fairy chess piece](https://en.wikipedia.org/wiki/Fairy_chess_piece) named the Wazir is introduced to chess. Wazirs can move from a position (*x*, *y*) to: โ€ƒ(*x*+1, *y*) โ€ƒ(*x*, *y*+1) โ€ƒ(*x*-1, *y*) โ€ƒ(*x*, *y*-1) That is, they move orthogonally like the rook, but only one step at a time like the king. How many such wazirs can be placed on an Nร—N chessboard so that no two wazirs can attack each other? โ€ƒOn a 1ร—1 board, there can be only 1 such piece. โ€ƒOn a 2ร—2 board, there can be 2 such pieces. โ€ƒOn a 3ร—3 board, there can be 5 such pieces. Given N, return the number of wazirs that can be placed on an Nร—N chessboard. This is [OEIS sequence A000982](https://oeis.org/A000982). ### More test cases `7` โ†’ `25` `8` โ†’ `32` `100` โ†’ `5000` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 45 bytes ``` ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgYuTi5MTTAMpLgUgkwvIAwoqgAFQjBNIcAJl/v83BQA "Whitespace โ€“ Try It Online") By the way, here is a proof that the โŒˆnยฒ/2โŒ‰ formula is correct. * **We can always place at least โŒˆnยฒ/2โŒ‰ wazirs**: just lay them out in a checkerboard pattern! Assuming the top-left tile is white, there are โŒˆnยฒ/2โŒ‰ white tiles and โŒŠnยฒ/2โŒ‹ black tiles on the *n ร— n* board. And if we place wazirs on the white tiles, no two of them are attacking each other, as every wazir only โ€œseesโ€ black tiles. Hereโ€™s how we place 13 wazirs on a 5 ร— 5 board (each W is a wazir). ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€[![13 wazirs on a 5 ร— 5 board](https://i.stack.imgur.com/qkqQJ.png)](https://i.stack.imgur.com/qkqQJ.png) * **We canโ€™t do any better**: letโ€™s arbitrarily tile the checkerboard with 2 ร— 1 domino pieces, optionally using a 1 ร— 1 piece for the final corner of an odd-length chessboard, like so: ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€[![domino cover of a 5 ร— 5 board](https://i.stack.imgur.com/pXhxf.png)](https://i.stack.imgur.com/pXhxf.png) We need โŒˆnยฒ/2โŒ‰ dominoes to cover the chessboard. Clearly, putting two wazirs on one domino makes it so that they can attack one another! So each domino can only contain at most one wazir, meaning we canโ€™t *possibly* place more than โŒˆnยฒ/2โŒ‰ wazirs on the board. [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 3 bytes ``` k>v ``` [Try it online!](https://tio.run/##y08sziz@/z/bruz///@GBgYA "Oasis โ€“ Try It Online") square - increment - integer halve [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~22~~ 19 bytes Saved 3 bytes thanks to *Kevin Cruijssen* ``` X*Y:-Y is(X*X+1)/2. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0Ir0ko3UiGzWCNCK0LbUFPfSO//f3OtCD0A "Prolog (SWI) โ€“ Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~9~~ ~~7~~ 6 bytes Now uses [Mr. Xcoder's formula.](https://chat.stackexchange.com/transcript/message/40310179#40310179) This is an anonymous prefix tacit function which takes N as argument. ``` โŒˆ2รทโจร—โจ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zkxNzWn@FHbhEc9HUaHtz/qXXF4OpD4/18BDCDSCoZcKFwjVK4xKtcclWuByjU0MAAA "APL (Dyalog Unicode) โ€“ Try It Online") `ร—โจ`โ€ƒsquare N (lit. multiplication selfie, i.e. multiply by self) `2รทโจ`โ€ƒdivide by 2 `โŒˆ`โ€ƒceiling (round up) [Answer] # JS (ES6) / C# polyglot, 11 bytes ``` n=>n*n+1>>1 ``` ### Test cases ``` let f = n=>n*n+1>>1 console.log(f(7)) console.log(f(8)) console.log(f(100)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes Straight implementation of the formula given by [A000982](https://oeis.org/A000982) ``` n;รฎ ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVvk/z/rwuv@VSof3Wykc3q@k89@Qy4jLmMuEy5TLjMucy4LLksvQAIgMAA "05AB1E โ€“ Try It Online") **Explanation** ``` n # square ; # divide by 2 รฎ # round up ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 6 bytes ``` 2^2~+p ``` `2^`: square; `2~`: divide by 2, pushing the quotient then the remainder; `+p`: add the remainder to the quotient & print. [Try it online!](https://tio.run/##S0n@b/7fKM6oTrvg/38A "dc โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 17 bytes 1 byte thanks to @ovs. ``` lambda x:x*x+1>>1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqkKrQtvQzs7wf0FRZl6JRpqGoaYmF4xthMQ2RmKbaGr@BwA "Python 2 โ€“ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~23~~ ~~18~~ 17 bytes * Saved a byte thanks to [Tahg](https://codegolf.stackexchange.com/users/74459/tahg); golfing `n/2+n%2` to `n+1>>1`. ``` f(n){n=n*n+1>>1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82TytP29DOztC69n9uYmaeRpZmdVp@kUaWraF1lo2hgXWWtrZmQVFmXkmahpJqSkyekk4aUI0mUDkA "C (gcc) โ€“ Try It Online") # [C (gcc)](https://gcc.gnu.org/), 22 bytes (not using undefined behavior) ``` f(n){return n*n+1>>1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuii1pLQoTyFPK0/b0M7O0Lr2f25iZp5GlmZ1Wn6RRpatoXWWjaGBdZa2tmZBUWZeSZqGkmpKTJ6SThpQjSZQOQA "C (gcc) โ€“ Try It Online") Some people really do not like exploiting a certain compiler's undefined bahavior when using specific compiler flags. Doing so does save bytes, though. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ^โ‚‚/โ‚‚โŒ‰โ‚ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@5RU5M@ED/q6XzU1Pj/v/n/KAA "Brachylog โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 19 bytes ``` lambda x:-(-x*x//2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCSldDt0KrQl/fSPN/QVFmXolGmoahpiYXjG2ExDZGYptoav4HAA "Python 3 โ€“ Try It Online") ``` lambda x:-(-x*x//2) # Unnamed function lambda x: # Given input x: x*x # Square - # Negate //2 # Halve and Floor (equivalent of Ceil) -( ) # Negate again (floor -> ceil) ``` -1 byte thanks to Mr. Xcoder [Answer] # x86\_64 machine language (Linux), ~~9~~ 8 bytes ``` 0: 97 xchg %eax,%edi 1: f7 e8 imul %eax 3: ff c0 inc %eax 5: d1 f8 sar %eax 7: c3 retq ``` To [Try it online!](https://tio.run/##FUrdDoIgFL7nKc5sbRzNpuuimtqTcMMOYCzDJrSxmq8e4cX3/1E9EqW0s46mt9K9D8rOx/uN0ex8ALrLBUozFCJezyKaDH3JakSkRkTVZp8znYqOWRfgKa3j@GUAZl741tih7cD2bZO5qhC2DeC15M3wYq@EKw7AtysvkSMa5Baxy6@VrSn9yExy9Kn@6KjJB0mPPw "C (gcc) โ€“ Try It Online"), compile and run the following C program. ``` #include<stdio.h> const char *f="\x97\xf7\xe8\xff\xc0\xd1\xf8\xc3"; int main() { for(int i=1; i<10; i++) { printf("%d\n", ((int(*)())f)(i)); } } ``` [Answer] # [J](http://jsoftware.com/), 8 bytes Anonymous tacit prefix function. ``` 2>.@%~*: ``` [Try it online!](https://tio.run/##y/r/P9nWyshOz0G1TssKyFEw5EpWMAJiYyA2B2ILIDY0MAAA "J โ€“ Try It Online") `*:`โ€ƒsquare `>.`โ€ƒceiling (round up) `@`โ€ƒafter `2`โ€ฆ`%~`โ€ƒdividing by two [Answer] # [Actually](https://github.com/Mego/Seriously), 3 bytes ``` ยฒยฝK ``` **[Try it online!](https://tio.run/##S0wuKU3Myan8///QpkN7vf//twAA "Actually โ€“ Try It Online")** [Answer] # Mathematica, 12 bytes ``` โŒˆ#^2/2โŒ‰& ``` [Answer] # [R](https://www.r-project.org/), ~~22~~ 21 bytes ``` cat((scan()^2+1)%/%2) ``` [Try it online!](https://tio.run/##K/r/PzmxREOjODkxT0MzzkjbUFNVX9VI87@hgpGCsYKJgqmCmYK5goWCpYKhwX8A "R โ€“ Try It Online") Square, increment, integer divide. Easy peasy. Input from stdin; it can take space or newline separated input and it will compute the max wazirs for each input boardsize. Output to stdout. *-1 byte thanks to plannapus* [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` .E**.5 ``` **[Try it online!](https://tio.run/##K6gsyfj/X89VS0vP9P9/cwA "Pyth โ€“ Try It Online")** [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 bytes ``` Xhe ``` **[Try it here!](http://pyke.catbus.co.uk/?code=Xhe&input=7&warnings=0&hex=0)** ## How? ``` X - Square. h - Increment. e - Floor halve. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~14~~ 12 bytes -2 bytes thanks to Emigna ``` n=>(n*n+1)/2 ``` [Try it online!](https://tio.run/##hco9C8IwEIDhPb/ixsSPii4K2i6Ck04ODuIQzrQc1AvkTlGkvz3Gzc13eKcHZYoxhYy9F4GneRtRr4TwiHSFgycGK5qIu/MFfOrEFQKl40s03KrdnXFDrBMoa6CFOnPdWB7xeO5mi7z@xdvIEvtQnRJp2BMH29qlc3/N6msGM@QP "C# (.NET Core) โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 16 bytes ``` $_=0|$_*$_/2+.5 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tagRiVeSyVe30hbDyhg8S@/oCQzP6/4v66vqZ6BocF/3QIA "Perl 5 โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` UH/Xk ``` [Try it online!](https://tio.run/##y00syfn/P9RDPyL7/38LAA "MATL โ€“ Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 11 bytes ``` Iu*:^\)2,O@ ``` Heheh, `:^\)` [Try it online!](https://tio.run/##Sy5Nyqz4/9@zVMsqLkbTSMff4f9/UwA "Cubix โ€“ Try It Online") Expands to the following cube: ``` I u * : ^ \ ) 2 , O @ . . . . . . . . . . . . . ``` Which is the same algorithm that many use. * `^Iu` : read in input as int and change directions * `:*` : dup top of stack, multiply * `\)` : change direction, increment * `2,` : push 2, integer divide * `O@` : print output as int, end program. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 bytes ``` Xhe ``` [Try it here!](http://pyke.catbus.co.uk/?code=Xhe&input=8&warnings=1&hex=0) ``` X - input ** 2 h - ^ + 1 e - floor_half(^) ``` [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes ``` ยฒยฝฤฑ ``` [Try it online!](https://tio.run/##y8/INfr//9CmQ3uPbPz/3xwA "Ohm v2 โ€“ Try It Online") `ยฒ` squares, `ยฝ` halves, `ฤฑ` ceils. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes -1 thanks to Mr. Xcoder. Based on [my APL solution](https://codegolf.stackexchange.com/a/144234/43319). ``` ยฒHฤŠ ``` [Try it online!](https://tio.run/##y0rNyan8///QJo8jXf///zc0MAAA "Jelly โ€“ Try It Online") `ยฒ`โ€ƒSquare `H`โ€ƒ**H**alve `ฤŠ`โ€ƒ**C**eiling (round up) [Answer] # [Japt](https://github.com/ETHproductions/japt/), 4 bytes Been sitting on these since the challenge was closed. ``` ยฒร„ z ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ssQgeg==&input=OQ==) **Explanation:** Square, add 1, floor divide by 2 --- ## Alternative ``` ยฒร„ร1 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ssTBMQ==&input=OQ==) **Explanation:** Square, add 1, bit-shift right by 1. [Answer] # [,,,](https://github.com/totallyhuman/commata), 7 bytes ``` 2*1+1ยป ``` [Try it online!](https://tio.run/##S87PzU0sSfz/30jLUNvw0O7///@bAwA ",,, โ€“ Try It Online") Yay, commata works for something! Fudge, I didn't implement ceiling... [Answer] # [Gaia](https://github.com/splcurran/Gaia), 3 bytes ``` sแธฅโŒ‰ ``` [Try it online!](https://tio.run/##S0/MTPz/v/jhjqWPejr//zcHAA "Gaia โ€“ Try It Online") `s` squares, `แธฅ` halves, `โŒ‰` ceils. [Answer] # [Commentator](https://github.com/SatansSon/Commentator), 19 bytes ``` //{-//-}! {-# -}<! ``` [Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/19fv1pXX1@3VlGhWldZQUG31kbx////pgA "Commentator โ€“ Try It Online") Who needs golfing languages? I've got confusing languages! Ungolfed version: ``` 5//{-8}//{5-} print(10!= 5) x={-1,3,4} # Smiley :-} print(5<!=10)*/ # Weird comparision. ``` [Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/99UX79a16IWSJrq1nIVFGXmlWgYGijaKphqclXYVusa6hjrmNQqKCsE52bmpFYqWMFVmdoo2hoaaGrpAyXDUzOLUhSS83MLEosyizPz8/T@A40GAA "Commentator โ€“ Try It Online") How does it work? I'll explain, with input 5 ``` // - Take input. Tape: [5 0 0] {-//-}! - Square the input. Tape: [25 0 0] {- - Move one along the tape // - Copy the input to the tape. Tape: [5 5 0] -} - Move one back along the tape ! - Take the product of the tape. Tape: [25 5 0] <space> - Increment the tape head. Tape: [26 5 0] {-# -}<! - Halve the tape head (floor division). Tape: [13 2 0] {- - Move one along the tape # - Set the tape head to 2. Tape: [26 2 0] -} - Move one back along the tape <! - Reduce the tape by floor division. Tape: [13 2 0] ``` [Answer] # [OCaml](http://www.ocaml.org/), 19 bytes ``` let f n=(n*n+1)/2;; ``` [Try it online!](https://tio.run/##y09OzM35/z8ntUQhTSHPViNPK0/bUFPfyNr6f0FRZl5JPBAraKQpmGsCRQA "OCaml โ€“ Try It Online") I'm a bit bummed the name got changed from "camels" to "wazirs" before I managed to write this, but I figured I'd post it anyway. ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. The challenge: > > Make a function that finds the longest palindrome inside a string. > > > Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules"). [Answer] ## Python ``` def longest_palindrome(s): return 'racecar' ``` Example usage: ``` >>> print longest_palindrome('I like racecars!') racecar ``` Note: this may only work for certain strings. [Answer] # Go The following solution in Go employs the hidden powers of concurrency, closures and recursivity to find the longest palindrome inside a given string: ``` func lp(s string) string { for i, l := 0, len(s); i < l; i++ { if s[i] != s[l-i-1] { a, b := make(chan string), make(chan string) go func() { a <- lp(s[:l-1]) }() go func() { b <- lp(s[1:]) }() c, d := <-a, <-b if len(c) > len(d) { return c } return d } } return s } ``` Additionally, it relies entirely on language primitives and built-in types โ€“ no standard library โ€“ that's how you recognize true quality software. You might want to turn your thread, memory and stack size limits up a bit for larger input strings โ€“ this is because this solution is so fast that your OS will get all jealous on it. Edit โ€“ Perks: * totally useless on multibyte character strings. * will not omit punctuation or whitespace characters. * omits upper/lower-case equality. * runs in a hard to calculate time โ€“ very slow, though. * spawns lots and lots of goroutines, depending upon input. * gets killed for memory exhaustion after couple of seconds on my machine with ~~over 16000~~ 2049186 goroutines spawned for the input `"345345ABCDEabcde edcbaDEABC12312123"` [Answer] Clearly, checking for Palindromes is hard. So the solution is pretty simple - generate a set of every single possible Palindrome as large as the string you're testing, and see if your string contains it. C# ``` string largest = String.Empty; for(int i=0; i < myString.lenght; i++) { //Don't use the newfangled stringbuilder. Strings are awesome char[] testString = new char[i]; for (int charPosition=0; charPosition < i/2; charPosition++) { for (char c = 'A'; c <= 'Z'; c++) { if ((charPosition/i) == i/2) { //middle one testString[i] = c; } else { //do one for that position, and the lenght-position testString[i] = c; testString[testString.length - i] = c; } if (myString.Contains(testString.ToString()) { //yaay largest = testString.ToString(); } { } } } } ``` (I might need to check my code for correctness, but otherwise its a wonderfully horribly inefficient way to check for Palindromes) [Answer] # Perl Does everything asked for. It is actually better, because it takes into account every possible *subsequence*. What's the catch? It operates in exponential time, so each additional character in the string doubles the running time. Give it more than 20 characters, and it will take all day. ``` $inputstring = <>; @arrayofcharacters = split("",$inputstring); for(0..2**length($inputstring)-1){ $currentsubsequence = ""; @choice=split("",sprintf("%b",$_)); for(0..$#arrayofcharacters){ $currentsubsequence .= "$arrayofcharacters[$_]" x $choice[$_]; if($currentsubsequence eq reverse($currentsubsequence)){ $palindromes{length($currentsubsequence)} = $currentsubsequence; $palindromes[~~@palindromes] = length($currentsubsequence); } } } print($palindromes{@{[sort(@palindromes)]}[$#palindromes]}) ``` Input: `iybutrvubiuynug`. Output: `ibutubi`. Input: `abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba`. Output: won't happen [Answer] Your problem is easily solved by regular expressions, just like in the picture below (but I decided to use java instead). This happens because regex is always the best tool that may be used for anything that involves extracting or analyzing text. ![I know regular expression](https://i.stack.imgur.com/uTnIf.png) ``` package palindrome; import java.util.regex.Pattern; import javax.swing.JOptionPane; public class RegexPalindrome { private static String next(String now) { if (now.isEmpty()) return "a"; String prefix = now.length() == 1 ? "" : now.substring(0, now.length() - 1); if (now.endsWith("z")) return next(prefix) + "a"; return prefix + String.valueOf((char) (now.charAt(now.length() - 1) + 1)); } public static void main(String[] args) { String text = JOptionPane.showInputDialog(null, "Type some text:"); String bestPalindromeFound = ""; for (String searchText = "a"; searchText.length() <= (text.length() + 1) / 2; searchText = next(searchText)) { String reverse = new StringBuilder(searchText).reverse().toString(); if (searchText.length() * 2 - 1 > bestPalindromeFound.length()) { Pattern p = Pattern.compile(".*" + searchText + reverse.substring(1) + ".*"); if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse.substring(1); } if (searchText.length() * 2 > bestPalindromeFound.length()) { Pattern p = Pattern.compile(".*" + searchText + reverse + ".*"); if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse; } } JOptionPane.showMessageDialog(null, "The longest palindrome is \"" + bestPalindromeFound + "\"."); } } ``` --- This code is evil because: * It runs in exponential time to the size of the given text. It runs by enumerating all the strings in the form a-z, creating two regexes for each generated string and testing the input against each regex. * Further, it fails if the palindrome contains uppercase letters, numbers, non-ascii text, punctuation, etc. * And of course, regex is clearly not the right tool for that. [Answer] # **Python** This takes the string, and reorganises it to the longest possible palindrome available. For example: Input : Hello Ouput : lol ``` def get_palindrome(string): if len(string) == 0: return "I didn't catch that" list_of_characters = [] occurances = [] for character in string: if not character in list_of_characters: list_of_characters.append(character) occurances.append(1) else : occurances[list_of_characters.index(character)] +=1 #check if a palindrome is possible if sum(occurances) == len(occurances): #no double letters, so only a one character palindrome return list_of_characters[0] first_half = '' second_half = '' middle_character = '' for index, character in enumerate(list_of_characters): number_of_occurances = occurances[index]/2 first_half += character * number_of_occurances second_half = (character * number_of_occurances)+ second_half if (occurances[index]%2 != 0):#if there are an odd number, there will be one spare, #so put it in the middle middle_character = character return first_half + middle_character + second_half print(get_palindrome(raw_input("String containing palindrome:"))) ``` [Answer] ## Python ``` def get_substrings(a_string): """Get all possible substrings, including single character substrings""" for start_index in range(len(a_string)): for end_index in range(start_index + 1, len(a_string) + 1): yield a_string[start_index:end_index] def get_longest_palindrome(a_string): """Find the longest palindrome in a string and return its index or -1""" # Initialise variables longest_palindrome = get_longest_palindrome.__doc__[5:27] palindromes_list = [] # Search string for all palindromes for substring in get_substrings(a_string): if reversed(substring) == substring: palindromes_list.append(substring) # There should always be palindromes in non-empty strings (single characters), # but it's good practice to check anyway if len(palindromes_list) > 0: longest_palindrome = max(palindromes_list, key=len) return a_string.find(longest_palindrome) ``` The string "the longest palindrome" is extracted from the docstring into `longest_palindrome`. The [`reversed()`](http://docs.python.org/2/library/functions.html#reversed) function returns an iterator, so `reversed(substring) == substring` will never be true and `longest_palindrome` will never be overwritten. Hence, the function will literally find "the longest palindrome" inside a string. [Answer] ### bioinformatics interpretation Very cool question dude! Palindromes in normal language are not entirely clearly specified, for example if spaces are allowed or not. So it is not clear if these should be allowed as palindromes or not: * Do geese see God? * A man, a plan, a canal--Panama! Anyway, I think you are referring to the better specified scientific meaning of palindrome: For a nucleotide sequence to be considered as a palindrome, its complementary strand must read the same in the opposite direction. Both the strands i.e the strand going from 5' to 3' and its complementary strand from 3' to 5' must be complementary (see [here](http://en.m.wikipedia.org/wiki/Palindromic_sequence)). There is some research done for palindrome sequence recognition and I think you should really read at least [this](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3602881/). To solve your problem you can pretty much just copy their approach! The professor even sends out the source code if you ask him. Well, now to the problem at hand. Suppose you have a nucleotide sequence given as a character string. The best way to find palindromes in such a sequence is by using standard algorithms. I think your best bet is probably using this online tool: <http://www.alagu-molbio.net/palin.html> Since you are required to provide a function that does the task, you need to think about how to get your string into this app? Well, there the fun begins. I think you could use [selenium](http://www.seleniumhq.org/projects/webdriver/) for that. Since I don't want to do your homework, i just give you the basic idea. In Java you world start like this: ``` package testing; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.phantomjs.PhantomJSDriver; public class PalindromeService { public static void main(String[] args) { WebDriver d1 = new PhantomJSDriver(); d1.get("http://www.alagu-molbio.net/palin.html"); String sequence = "AAGTCTCGCGAGATCTCGCGAGATCTCGCGAGATCTCGCGAGAAA"; WebElement txtArea = d1.findElement(By.tagName("textarea")); txtArea.sendKeys(sequence); WebElement send = d1.findElement(By.cssSelector("input[type=submit]")); send.click(); String result = d1.findElement(By.tagName("body")).getText(); Pattern p = Pattern.compile(".*capitalized\\.[^agctACGT]*([agctACGT]+).*"); Matcher m = p.matcher(result); if (m.find()){ result = m.group(1); } //now you have all palindromes in upper case! //I think you can take it from here, right? System.out.println(result); d1.quit(); } } ``` In case you are interested in language palindromes you can use the same technique with other web services like <http://www.jimsabo.com/palindrome.html> or <http://calculator.tutorvista.com/math/492/palindrome-checker.html> ### code-trolling technics * omit the truely helpful sources like <http://rosettacode.org/wiki/Palindrome_detection> * interesting but unhelpful blah about bioinformatics * deliberately misunderstanding this as bioinformatics task * cheating - to solve the problem a web service is used [Answer] # Javascript Oh, thats easy ;). Here ya go: ``` function () { var palidrome = "Star? Not I! Movie โ€“ it too has a star in or a cameo who wore mask โ€“ cast are livewires. Soda-pop straws are sold, as part-encased a hot tin, I saw it in mad dog I met. Is dog rosy? Tie-dye booths in rocks. All ewes lessen ill. I see sheep in Syria? He, not I, deep in Syria, has done. No one radio drew old one. Many moths โ€“ I fondle his; no lemons are sold. Loot delis, yob, moths in a deli bundle his tin. Pins to net a ball I won โ€“ pins burst input. I loot to get a looter a spot paler. Arm a damsel โ€“ doom a dam. Not a base camera was in a frost, first on knees on top spot. Now a camera was a widened dam. Ask: Cold, do we dye? No, hot โ€“ push tap, set on to hosepipe. Nuts in a pod liven. A chasm regrets a motto of a fine veto of wars. Too bad โ€“ I all won. A sadist sent cadets โ€“ a war reign a hero derides. A bad loser, a seer, tossed a cradle โ€“ he begat to cosset โ€“ a minaret for Carole, Beryl, Nora. Weโ€™re not as poor to self. I risk cold as main is tidal. As not one to delay burden, I donโ€™t set it on โ€œhotโ€. A foot made free pie race losses runnier. As draw won pull, eye won nose. Vile hero saw order it was in โ€“ even a moron saw it โ€“ no, witnessed it: Llama drops โ€“ ark riots. Evil P.M. in a sorer opus enacts all laws but worst arose. Grab a nosey llama โ€“ nil lesser good, same nicer omen. In pins? No, it is open. If a top spins, dip in soot. Madam, as I desire, dictates: Pull aside, damsels, I set a rag not for a state bastion. A test I won e.g. a contest I won. Kidnap, in part, an idle hero. Megastars, red, rosy, tied no tie. Blast! A hero! We do risk a yetiโ€™s opposition! He too has a wee bagel still up to here held. Demigods pack no mask, cap nor a bonnet, for at last a case is open โ€“ I left a tip โ€“ it wets. A dog wets too. Radios to help pay my tip, pull a tip. Ale, zoo beer, frets yon animal. Can it? New sex arose but, we sots, not to panic โ€“ itโ€™s ale โ€“ did I barrel? Did I lose diadem, rare carrot in a jar of mine? Droop as tops sag โ€“ unseen knots. A cat ate straw as buck risk cud; evil foe, nil a red nag ate? Bah! Plan it โ€“ silage. Model foot in arboreta. I, dark Satanist, set fire โ€“ voodoo โ€“ to slat. I design a metal as parrot, I deem it now. One vast sum is no ten in set โ€“ amen! Indeed, nine drag a yam, nine drag a tie. Dame nabs flower; can we help man? Woman is worse nob. Mud level rose, so refill a rut. A nag of iron I made to trot I defied โ€“ I risk leg and its ulnae. Can a pen I felt to bid dollar or recite open a crate, open a cradle, his garret? Sample hot Edam in a pan. Iโ€™m a rotten digger โ€“ often garden I plan, I agreed; All agreed? Aye, bore ensign; Iโ€™d a veto โ€“ I did lose us site. Wool to hem us? No, cotton. Site pen in acacias or petals a last angel bee frets in. I met a gorilla (simian); a mate got top snug Noel fire-lit role. Manet, Pagnol, both girdle his reed bogs. Flan I reviled, a vet nods to order it, Bob, and assign it. Totem users go help mates pull as eye meets eye. Son โ€“ mine โ€“ pots a free pie, yes? No. Left a tip? Order a dish to get. A ring is worn โ€“ it is gold. Log no Latin in a monsignor, wet or wise. Many a menu to note carrot. Cat in a boot loots; As I live, do not tell! A bare pussy, as flat on fire, I know loots guns, fires a baton, nets a hero my ale drop made too lax. If it is to rain, a man is a sign; I wore macs, no melons rot. I use moths if rats relive, sir, or retire. Vendor pays: I admire vendee, his pots net roe. Nine dames order an opal fan; Iโ€™ll ask cold log fire vendor to log igloo frost. Under Flat Six exist no devils. Marxist nods to Lenin. To Lenin I say: โ€œMama is a deb, besides a bad dosser.โ€ Gen it up to get โ€œovaโ€ for โ€œeggโ€. I recall a tarot code: yell at a dessert side-dish sale. Yes/nos a task cartel put correlate: E.S.P. rocks a man. I am a man, am no cad, Iโ€™m aware where itโ€™s at! Fire! Its an ogre-god to help, man, as I go. Do not swap; draw, pull a troll! Itโ€™s not a cat I milk โ€“ calf, for a fee, sews a button โ€“ knit or tie damsel over us. Mined gold lode I fill until red nudes I met in a moor-top bar can. I sit, I fill a diary โ€“ trap nine men in ten-part net โ€“ oh, sir, I ask, cod nose? No, damp eel. So, to get a name! I say, Al! I am Al! Last, I felt, to breed, deer begat. To can I tie tissue โ€“ damp โ€“ or deliver Omani artist โ€“ a man of Islam. In a den mad dogs lived on minis a signor who lived afore targets in at. As eremites pull, I, we, surf, fantasise, mend a bad eye. No hero met satyr; Tony, as I stressed, wonโ€™t, so cosset satyr. A vet on isles made us sign it, a name. Foe man one sub. Aside no dell I fret a wallaby; metal ferrets yodel, like so. On a wall I ate rye. Bored? No, was I rapt! One more calf? O.K., calf, one more, bossy! No! Lock cabin, rob yam, sip martini. Megastar was in a risk. Cat? No, Iโ€™m a dog; Iโ€™m a sad loyal pet. A design I wore โ€“ kilts (a clan); if net drawn, I put it up. Royal spots snag โ€“ royal prevents rift. Composer, good diet, are both super, God โ€“ label it a love of art, lustre. Video bored, no wise tale e.g. a mini tale โ€“ no sagas seen. Knack: cede no foes a canal. Pay โ€“ as I sign I lie; clear sin it is; e.g. โ€œAmadeusโ€ sign I โ€“ lira for ecu, decimal โ€“ sin as liar. Trad artistes pull a doom, a drawer wonโ€™t. Is it sold loot? No, I suffered loss. A man is god; Amen! I came nice Tahiti (sic). Itโ€™s ale for a ban if for a fast โ€“ is role to help mash turnip? Use zoo? No โ€“ grasp order โ€“ use no zoos. Warts on time did sag. No grade โ€œXโ€ โ€œAโ€ Level? Oh, โ€œAโ€! Iโ€™d a โ€œBโ€ or a โ€œCโ€. So โ€“ pot? No, we lop. Date? Take no date! Bah! Play L.P. Miss (a lass, all right?) flew to space in NASA era. Rose no (zero) cadets ate raw. As a wise tart I fined rags red Lenin, we help pay bet โ€“ a risk โ€“ cash to Brian. I put a clam in a pool โ€“ a pool wets. Mahdi puts a stop to harem โ€“ miss it in one vote, lost in one, veto of none. Post-op, no tonsil; I ate; no tastier, eh? We sleep at noon time so I dare not at one; no time stops as I time tides. A bed: under it, roll; in a mania, panic! In a pond I did as Eros as Lee felt tenrec. โ€œInkโ€ โ€“ list it under โ€œIโ€. Termites put pen in a way. Democrats wonder, I too. To slay moths a dog did. I saw elf; elf, far now, is a devilish taboo, rag-naked. I hid a bootleg disc. I, saboteur, toss it in. Oops! No legs! Laminated, a cask, conker in it, negates all if it is simple. Hot pages are in a mag, nor will I peer, familiar tat, so lewd, native rot. Toner, ewe wore no trace; vagabond ewes do. Oh, Ada! Have pity! A pitiable eel โ€“ โ€œOh wet am I!โ€ โ€“ to save, note: bite gill as I do. Call a matador minor, eh? As I live, donโ€™t! Is torero no rigid animal debaser if tipsy? Ale drew esteem in a matador. A bolero, monks I rate play or go dig rocks; a can I step on. Go! Gas โ€“ it evades a bedsit โ€“ set a roost on fire. Boss sent a faded eclair to green imp or dog, Iโ€™d don a belt to boot it; if Ada hid a boot, panic. I mock comic in a mask, comedian is a wit if for eventide. Vole no emu loved is not a ferret, so pet or witness a weasel if not. I hired less, am not so bossy, as yet amateur. To stir evil, Edna can impugn a hotel: bad loos, hot on Elba: I may melt. Tart solicits it rawer, gets it rare. Push crate open; I ram buses, use no trams. Did I say, not to idiot nor a bare ferret, to trap rat, strap loops rat? Stewpot was on. Hot? I was red! Lessen it! Fine man on pot? No, pen inside by a bad law. So I made rips โ€“ nine delays. Some Roman items in a.m. ordered โ€œIs room for a ban?โ€ โ€œIt is,โ€ I voted: I sat pews in aisle. Beryl, no tiro to my burden, made off for a contest, I won kiss. I may raid fine dales. I raid lochs if I to help am. Forecast for Clare v. Essex: If no rain, a man is ref. Fusspots net foxes. Senor is a gnome, latinosโ€™ bad eyesore. Help misses run to border, Casanova, now, or drab hotel. Ma has a heron; I sleep, petโ€™s on nose, sir! Rev. I rag loved art live โ€“ fine poser. Ultra-plan: I feign, I lie: cedar to disperse โ€“ last one? No, last six. Enamel bonnet for a dark car to toss a snail at. In it all, Eve lost; Sethโ€™s a hero slain on a trap โ€“ Rise, Sir Ogre Tamer. Upon Siamese box I draw design. I, knight able to help, missed an alp seen in Tangier of fine metal pots. Tin I mined rages โ€“ order nine, melt ten. Tone radios; tones are not to concur. Ten-tone radar I bomb โ€“ best fire-lit so hostel side meets eerie mini red domicile. A gulf to get is not a rare tale; no time to nod. Row on, evil yobs, tug, pull. If dogs drowse, fill a rut. An eraโ€™s drawers draw. Put in mid-field in a band I dig a tub deep. Staff on a remit did refill a minaret. Samโ€™s a name held in a flat, or, sir, bedsit. I wonder, is it illicit ore? No ties? A bit under? Retarded? Is โ€˜owt amiss? Iโ€™m on pot; not so Cecil, a posh guy a hero met. A red date was not to last so Cecil sat. Tip? An iota to pay, a dot; sad, I drop item. Iโ€™d ask, call, Odin, a Norsemanโ€™s god: โ€œPay payee we owe radio dosh o.n.o.โ€ I to me? No, I to media. Peril in golf โ€“ is ball a โ€œforeโ€? K.O.! Vexed I am re my raw desires. Alto has eye on nose but tone-muser pianist is level-eyed. I lost a tie. Blast! In uni no grades are musts. Avast! Never port! Sea may be rut. Part on rose? โ€“ Itโ€™s a petal. Define metal: Tin is . (I gulp!) can! I am a fine posse man, I pull a ton. Ron, a man I put on, I made suffer of evil emuโ€™s sadism. Leoโ€™s never a baron โ€“ a bad loss but evil โ€“ topple him, Leoโ€™s lad. Assign a pen, can I? A pal is note decoding. Is damp mule tail-less? No, ill; I breed for its tone. Radio speed, to grower, grew. Open a lot? No, stamp it; if for a free peso โ€“ not ecu -deign it. Times ago stone rates, e.g. at Scilly, display a wont. No wish to get a design I, Sir Des, Iโ€™ve let? No bus sees Xmas fir. O.K. โ€“ cab โ€“ tart it up; tie lots โ€“ diamond, log or tinsel; first end errata edit. So โ€œle vin (A.C.)โ€, Martini, Pils lager, one tonic. I pegged a ball up to here when I got a top star role, Beryl. Gun is too big โ€“ wonโ€™t I menace? Yes? No? Ill? A cold? Abet icecapโ€™s nip. U.S.A. meets E.E.C. inside tacit sale โ€“ see! Beg a cotton tie, ma! No trial, so dodo traps exist. Arabs under-admire card label good hood stole. In rage erupted Etna. Will a rotunda, bare villa, to tyro. Lack car? Non-U! Get a mini! My, my, Ella, more drums per gong; get a frog โ€“ nil less. Rod, never ever sneer. Got to? I disperse last pair of devils (ah!) here today or else order cash to breed emus. Said I: โ€œAre both superlative?โ€ C.I.D. assign it lemon peel still. I wore halo of one bottle from a ref (football) โ€“ a tip; so hit last ego slap a mate got. Late p.m. I saw gnu here (non-a.m.) or an idea got a dog to nod โ€“ I made felt to boot. Fill in a lad? Nay, not all, Edna โ€“ lash to buoy. Did you biff one Venus? Not I! โ€œBroth, girl!โ€ ladies ordered โ€“ โ€œNo, with gin!โ€ โ€“ a fine plate, maybe suet; no carton I made rots in it. Med: a hill, Etna, clears in it. Ali, Emir, to slap in/slam in. All in all I made bad losers sign it โ€“ alibi. Set a lap for a level bat. A bed, sir, eh? To put cat now? Drat! Such an idyll of a dogโ€™s lair! That`s it, open it โ€“ a cage! Big nit sent rat! Some day (A.D.) send ewe. No, draw a pot now, do! Of wary rat in a six ton tub. Edna, ask satyr: โ€œTel. a.m.?โ€ No, tel. p.m.; Israeli tuner is damp. Use item: โ€œAnna Reginaโ€. No! Dye main room (โ€œsalleโ€) red! Nice caps for a sea cadet in U.S.A. โ€“ Now I, space cadet, am it, sea vessel rep. Pin it on Maria, help Maria fondle her fine hotpot. No! Meet; set up to net, avoid a lesion. Set acid arena: Bruno one, Reg nil. Like it to sign in? Even I am nine-toed! I vote votes. Oh, can a nose-rut annoy? No, best is Dorset. I know, as liar, to snoop, malign. โ€œIโ€™ll order it to get a bedroom door,โ€ began a miser I fed. Am I to peer, fan? Is a door by metal? Ere sun-up, drowse, nod, lose magnet. Food? Buns? Iโ€™ll ask. Corn? Iโ€™ll ask. Corn โ€“ I snack. Cats snack (cold rat). Sum for a bag: nil. First, is remit โ€œtraps in netโ€? Yes, on a par. Coots yell over a dam I made. Bared nudist went a foot, I made roots. I tip a canon: โ€œRow, sir, at same tide; man one: row tug.โ€ Sewer of denim axes a wide tail โ€“ a terror recipe to hero made manic. I, to resign? I ? Never! โ€œOFT I FELT ITS SENSUOUSNESSโ€ โ€“ title fit for evening is erotic; I named a more hot epic โ€“ error retaliated โ€“ I was examined for eweโ€™s gut, wore no named item. A star is worn on a cap, it is too red. Am I too fat? Newts Iโ€™d under a bed. Am I mad? Are volleys too crap? A nosey tennis part-timer sits rifling a bar of mustard. Lock cans, stack cans in rocks, all in rocks, all I snub. Do often games, old ones, word-pun use; relate, my brood, as in a free pot I made fires, I manage brood. Moor debate got tired rolling, I lampoon, so trail saw on kites. Rod sits, ebony on nature, so Nana chose to veto video. Ten in main evening is O.T.T. i.e. killing; Ere noon, urban eradicates noise, lad, I ovate not. Put esteem on top (to hen, if reheld). No fair ample hair โ€“ am not I nipper-less? Eva estimated ace caps I won as united. A Caesar of space, Cinderellaโ€™s moor, Niamey Don (a Niger-an name), ties up mad sire, nut! I, Lear, simpleton male, try tasks โ€œAโ€ and โ€œEโ€ but not โ€œXIโ€. Sanitary raw food won top award one Wednesday โ€“ a demo. Start nesting, I beg a cat. I? Nepotist? Ah, trials, God! A folly, Dinah, custard wonโ€™t act up; other is debatable. Velar: of palate; sibilating is โ€œsโ€. Resold: a bed, a mill, an ill animal โ€“ snip, also trim. Eilat in Israel can tell I had โ€˜em. Tin I stored (am I not raconteuse?) by a metal pen. If a night, I wondered, rose, Iโ€™d all right orbit on sun, even off. I buoy, did you? Both Sal and Ella, Tony and Alan (โ€œIll if too bottle-fed, am I?โ€) do not. God! A toga! Ed in a Roman one, rehung! Was I, M.P. et al., to get a map? Also get salt? I, hospital lab to offer, am, or felt to be, no fool โ€“ a hero. Will it sleep? No, melting is sad ice. Vital re-push to be raid, I assume. Deer, both sacred roes, Leroy (a doter, eh?) has lived for. I, apt sales repโ€™s idiot to greens, revere vendors selling or fat egg-nog reps. Murder Oโ€™Malley, my mini mate โ€“ gun on rack. Calory total: liver, a bad nut or all I wanted (โ€œet puree garnieโ€): lots. โ€œDo, oh do, ogle bald racer,โ€ Iโ€™m dared โ€“ N.U.S. bar at six. Esparto, dodoโ€™s lair to name it, not to cage bees, elasticated, is nice. Esteem, as up in space, cite bad local lions, eye can emit now. G.I. boots in ugly rebel or ratโ€™s potato gin (eh?) were hot. Pull a bad egg โ€“ epic, I note, no regal slip in it. Ram can . (Iโ€™ve lost idea!) Tarred nets, rifles, nitro, gold โ€“ no maid stole it. Put it, rat, back or if Sam (โ€œXโ€) sees sub on televised rising, I sedate Goths. I wonโ€™t โ€“ no way. Alps, idyllic stage set, are not so gas-emitting, I educe. To nose, peer, far off, I tip mats onto lane. Power grew or got deep so I dare not stir. Of deer, billions sell. I ate lump โ€“ mad sign, I do cede โ€“ tonsil a pain, acne pang is sad also. Elm I help pot, live โ€“ tubโ€™s sold; a ban or a bar, even so, elms, Iโ€™d assume, live for. Effused am I not, up in a manor, not all up in a mess. Open if a main A.C. plug is in it. Late men I fed late โ€“ pasties or not. โ€œRaptureโ€ by a maestro prevents a vast sum erased. Argon in units, albeit at solid eye level, sits in a . (I presume not) . tube, son. No eyes: a hot laser โ€“ is Ed wary? Mermaid, ex- evoker of all A.B.s, I flog. Nil I repaid. Emotion! Emotion, oh so do I dare, woe! Wee yap-yap dogโ€™s nameโ€™s Ron. An idol lacks a dime tip, or did, as today a potato in a pitta slice costs a lot โ€“ tons. A wet adder ate more hay. Ugh! So, pal, ice cost on top? No, miss, Iโ€™m a two-sided rat, erred nut, I base it on erotic ill; It is I, red now; it is debris, rot. Alf, an idle he-man as โ€œmaster animal liferโ€ did time, ran off at speed, but a G.I. did nab an idle if dim nit. Upwards rewards are natural lifeโ€™s words, God. Fill up guts, boy, live now or do not emit one later. A rat on site got flu. Gaelic, Iโ€™m odd Erin, Iโ€™m Eire, esteemed islet. So hostile rifts ebb. Mob, I.R.A., dare not net R.U.C. โ€“ no cotton. Erase not, so I dare not nettle men in red rose garden โ€“ Iโ€™m in it. Stop late men if foreign at nine. Esplanades, simple hotel, bath, gin โ€“ king is Edward IX; obese; Ma is no pure mater. Go! Rise, sir; part anon. I also rehash tests โ€“ โ€˜Oโ€™ Level Latin, Italian. S.A.S., so, to track radar. Often nobleman exists alone โ€“ not sales reps โ€“ I do. Trade ceiling, i.e. final part, lures open if evil trade. Volga River rises on no steppe. Elsinore has a hamlet โ€“ Oh, Bard, row on Avon! A sacred robot nurses simple heroโ€™s eye; dabs on it a lemon. Gas, iron, Essex often stops, suffers in a mania. Ron fixes several crofts, acer of maple. Hot, I fish; cold, I arise laden; if diary amiss, I know it set no car off. Foe-damned ruby motor, it only rebels. Ian I swept aside to visit, in a bar of moorside red, Romanis met in a more mossy ale den. Inspired am I, Oswald. A bay bed is nine p on top. No name, niftiness- elder saw it. Oh no! Saw top wet starโ€™s pool โ€“ part star, part otter. Refer a baron to idiot, Tony, as I did. Smart ones use submarine. Poet, arch-super-artiste, grew artistic. I lost rattle; my amiable, not oh so old, able to hang up, mina, can deliver it, so true. โ€œTa, matey!โ€ โ€“ says so Boston (Mass.) elder I hit. On file S.A.E. was sent โ€“ I wrote poster re fat on side, volume one โ€“ loved it, never off it, I was in. Aide mocks a manic; I mock comic, I nap: too bad I had a fit, I too. Bottle ban odd, I go drop mine, ergo trial ceded a fatness, sober if not so, or a test is debased. A vet is agog โ€“ no petโ€™s in a cask โ€“ corgi dog, royal pet, a risk no more. Lob a rod at a man I meet. Sewer delays pit fires โ€“ a bedlam in a dig โ€“ iron ore rots it. No devil is a hero โ€“ Nimrod. At a mall a cod is all I get. I bet on Eva, so Tim ate whole eel bait, I pay tip, Eva had a hood sewed. No B.A. gave car to Nero, we were not to rev it and we lost a trail; Iโ€™m a free pill, I wrong a man. I erase gap; to help miss it, I fill a set. A gent in ire knocks a cadet. Animalsโ€™ gel on spoon โ€“ it is so true to basics โ€“ Iโ€™d gel; too bad I hide kangaroo baths โ€“ I lived as I won raffle, flew as I did go, dash, to my, also too tired now, star comedy: A wan, inept, upset Iโ€™m retired, nut; its ilk, nicer. Nettle feels a sore; sad, I did no panic in a pain, am an ill or tired, nude, based item; it is a spot. Semitone, not a tone, radios emit; no, on tape; elsewhere itโ€™s a tone. Tail is not on; pots open on foot, even on it, so let oven (on, it is) simmer โ€“ a hotpotโ€™s a stupid ham stew. Loop a loop, animal โ€“ cat up in air. Both sacks I rate by apple hewn in elderโ€™s garden if it rates, I was aware โ€“ tasted a core. Zones or areas, Annie, cap, so twelfth girl, lass, alas, simply (alpha beta) done, Kate. Tadpole won top Oscar, Obadiah, โ€œOโ€ Level axed. Argon gas did emit no straw, so ozone sure drops argon, oozes up in Ruthโ€™s ample hotel or sits afar off in a bar โ€“ of elastic, is it? I hate cinema; cinema dogs in a mass. Older effusion to old โ€“ lost, is it now? Reward: a mood. All upsets it. Radar trails an Islamic educer of a riling issue, damages it in Israel. Ceiling is, I say, a plan, a case of one deck. Can knees sag as one Latin image elates, I wonder? Oboe diverts ultra foe, volatile bald ogre โ€“ push to berate; Iโ€™d do, ogre. So, p.m., Oct. first, never play organโ€™s stops โ€“ lay or put it up in ward ten. Final cast like rowing โ€“ I sedate play, old as am I, God! Am I! On tacks I ran; I saw rats. A Gemini tramp is May born. I back colonyโ€™s sober omen of lack of lace. Rome, not Paris, a wonder. Obey retail law โ€“ a noose killed oyster. Reflate my ball, a water-filled one. Disabuse no name of emanating issue. Damsels, I note, vary tastes so cost now desserts. I say no! Try taste more honeyed. A bad nemesis at naff ruse will upset. I, mere Satanist, e.g. rater of a devil โ€“ (Oh wrong is a sin!) โ€“ Iโ€™m no devilโ€™s god, damned. Animals, if on a mat, sit. Rain, a more vile drop, made us site it in a cottage. Breed deer โ€“ bottle fits a llama. I lay, as I emanate, go to sleep, mad ones on docks โ€“ air is hot. Entrap, net, nine men in party raid โ€“ all if it is in a crab-pot room, an itemised, under-lit, nullified old log den โ€“ Iโ€™m sure voles made it rot in knot. Tubas we see far off lack limit. A cat on still or tall upward paws to no dog is an ample hot-dog, ergo nastier if tastier, eh? We, raw amid a conman, a mama in a mask, corpse et al., err. Octuple tracks at a sonโ€™s eyelash side distressed a tall eye doctor, a tall ace, rigger of a vote: got put in egress; odd, abased, is ebbed, as I am, Amy, asinine lot! Nine lots! Donโ€™t six rams live? Donโ€™t six exist? Alfred, nuts or fool gigolo, trod never if gold locks all in a flap on a red rose; made nine or ten stops. I heed never, Iโ€™m Daisy, a prod never, I terrorise viler starfish. To me suitors, no lemons, came rowing. Is a sin a mania? Rot! Sit! I fix a looted amp or delay more, hasten not. A baser if snug stool, wonkier, if not โ€“ Alf says โ€“ super, a ballet to no devil, is a stool too. Ban it, actor, race to no tune. May names I wrote wrong (Is no man in it, a long old log?) sit in row, sign irate Goths; I dare drop it. At felonโ€™s eye I peer, fast open โ€“ Iโ€™m nosey, esteem eyes. All upset, ample hogs resume totting. Is sad nabob tired? Roots donโ€™t evade liver in Alfโ€™s gob. Deers I held right; oblong, apt enamel or tile rifle on gun spot to get a man โ€“ aim is all. I rogate, minister. Feeble gnats, alas late, prosaic, a canine pet is not to consume hot. Loo, wet, issues old idiot; evading, I sneer, obey a deer, gall a deer, gain alpine dragnet for egg Iโ€™d net to ram in a pan I made to help master. Rags I held, arcane poet, arcane poetic error, all odd; I bottle fine panacean lust. Iโ€™d nag elks I ride if editor toted a minor. I fog a natural life. Roses, or level dumb ones โ€“ rows in a mown, ample, hewn acre. Wolfsbane made it a garden in May, a garden indeed. Nine mates, nine tons I must save now on time โ€“ editor raps a late man. G.I.s edit also, too. Do over if tests in a task radiate. Rob ran; I, too, fled. โ€œOmegaโ€ โ€“ list in alphabet. A gander, a line of live ducks, irk cubs. A wart, set at a cast on knee, snug as spots. A poor denim for a janitor, racer, armed aide, solid idler โ€“ rabid; Iโ€™d elastic in a pot, tons to sew. Tubes or axes went in a clam, in an oyster. Free booze โ€“ lap it all up. Pity, my apple hot, so Iโ€™d a root stew. God, a stew! Tip it at feline! Posies, a catโ€™s altar often, no baron packs. A monk caps dog โ€“ I meddle here โ€“ hot? Pull its leg! A bee was a hoot, eh? No, it is opposite. Yaks I rode wore hats, albeit on deityโ€™s orders. Rats age more held in a trap, nip and I know it โ€“ set no cage now. Itโ€™s eta; no, itโ€™s a beta โ€“ Tsar of Tonga rates isles. Mad Ed is all upset at cider, is Ed? Is a madam too? Snip? Iโ€™d snip, spot a fine position, snip nine more cinemas. Do ogres sell in a mall? Yes, on a barge so rats row tubs. Wall last canes up or Eros, an imp, lives to irk, rasp or dam all tides sent. I wonโ€™t โ€“ I was no Roman โ€“ even I saw tired row โ€“ a sore. He lives on. โ€œNo!โ€ we yell. Up, now! Wards are in nursesโ€™ sole care. I, peer, fed, am too fat? Oh, not I, test no dined ruby ale; dote not on salad itโ€™s in โ€“ I am sad. Locks I rifle so troops atone re war. Only rebel or a crofter animates so cottage beheld arcades, so trees are sold, abased. I redo, rehang, I err โ€“ a wasted act; nests Iโ€™d โ€“ as an owl โ€“ laid. A bootโ€™s raw foot, even if a foot to master, germs (ah!) can evil do. Pan is tune-pipe โ€“ so hot notes, paths up to honeydew. Odd locks, a maddened (I was aware) macaw on top, spot no seen knots, rifts or fan, I saw. Are maces a baton, madam? Oodles, madam? Rare laptops are too late โ€“ got too lit up. Nits rub โ€“ snip now, Iโ€™ll abate, not snip, nits I held. Nubile Danish tomboys I led to old loser as no melons I held; no fish to my name. Nod lower, do I dare? No, one nods a hairy snipe. (Edit: one hairy snipe, eh?) See silliness, else weโ€™ll ask cornish to obey deityโ€™s or godโ€™s item. I, God, damn it! I was in it! To Hades, acne trap, sad loser! As warts pop, a dosser I โ€“ we โ€“ vile rat, sack! Same row, oh woe! Macaroni, rats, as a hoot, tie. I vomit on rats."; return '$system> KERNEL ERROR (DOES. NOT. EXCIST)' } ``` :) [Answer] # Ruby - The (Optimized and Monkeymized!) Brute Force I find the best way to do this is through the well known Monkey Algorithm, you can probably find it in BOOST. They always had ways of making you talk... ``` def palindrome?(in)#IMPORTANT if in.reverse == in return true else return false end def getMonkeys(in)#don't forget to interface with C in case of MaxMonkeys = 0 MonkeyTalk = "" MonkeySpeed = in.length (0..MonkeySpeed).each do |monkeyA| (monkeyA..MonkeySpeed).each do |monkeyB|#optimized! if palindrome?(in[monkeyA..monkeyB]) do if in[monkeyA..monkeyB].length > MaxMonkeys do MonkeyTalk = in[monkeyA..monkeyB] end end end end MonkeyTalk end ``` This is extremely inefficient, but rather cute and ruby-like if you rename everything to their original names: MaxMonkeys = len; MonkeyTalk = result, MonkeySpeed = strlen; monkeyA : a; monkeyB : b; getMonkeys: getMaxPalindrome. This is of no value to the OP and risks him deciding to actually interface with C, and we all know how that ends... [Answer] # Python 2.7 I refuse to use the standard functions, as they are inefficient. Everyone knows that the best way to look up a length is to have a table to reference, so I create a table of all of the possible palindromes, and sort them using a pythonic bogosort, but in order to improve efficiency, I remove duplicates first. At that point, I compute all of the items which are palindromes, and sort them by lengths. You can then simply take the last length in the list, which has an O(n) lookup by iterating the list. ## Code: ``` from itertools import chain, combinations from random import * stringToTest = "abba" #Don't forget to reference code taken from stackoverflow. (http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) def FindAllSubsetsOfAString(StringToFindASubsetOf): return chain(*map(lambda x: combinations(StringToFindASubsetOf, x), range(0, len(StringToFindASubsetOf)+1))) listOfPermutations = [] #get the length of the string we are testing, as the python function is not portable across platforms lengthOfStringToCheck = 0 for currentCharacterInString in stringToTest: lengthOfStringToCheck = lengthOfStringToCheck + 1 lengthOfStringToCheckMinusOne = lengthOfStringToCheck - 1 #Always iterate backwards, it is more efficient for cache hits and misses for stringBeginningIndex in range(lengthOfStringToCheck, 0, -1): listOfPermutations.append(stringToTest[stringBeginningIndex:lengthOfStringToCheckMinusOne]) #To save from errors, we must not operate directly on the list we have, that would be inefficient. We must copy the original list manually. # The built in functions again aren't portable, so we must do this manually, with a deep copy. OtherListOfPermutations = [] for CurrentItemInOriginalList in listOfPermutations: TemporaryListItem = [] for CurrentIndexInCurrentItemInOriginalList in CurrentItemInOriginalList: TemporaryListItem.append(CurrentIndexInCurrentItemInOriginalList) OtherListOfPermutations.append(''.join(TemporaryListItem)) #Get all of the possible strings into the OtherListOfPermutations List. # Use Generators, and itertools. It's more efficient and more pythonic for OriginalString in listOfPermutations: for CurrentPermutationInCurrentString in FindAllSubsetsOfAString(OriginalString): OtherListOfPermutations.append(''.join(list(CurrentPermutationInCurrentString))) #Sort the list ListOfStringsSortedByLength = OtherListOfPermutations while not all(len(ListOfStringsSortedByLength[i]) <= len(ListOfStringsSortedByLength[i+1]) for i in xrange(len(ListOfStringsSortedByLength)-1)): shuffle(ListOfStringsSortedByLength) #Remove all of the duplicates in the sorted list ListOfStringsSortedByLengthWithoutDuplicates = [] for CurrentStringWorkingWith in OtherListOfPermutations: HaveFoundStringInList = False for CurrentTemporaryString in OtherListOfPermutations: if CurrentStringWorkingWith == CurrentTemporaryString: HaveFoundStringInList = True if(HaveFoundStringInList == True): ListOfStringsSortedByLengthWithoutDuplicates.append(CurrentStringWorkingWith) #Use the ListOfStringsSortedByLengthWithoutDuplicates and check if any of the strings are palindromes ListOfPotentialPalindromes = [] for TemporaryStringToUseForPalindromes in ListOfStringsSortedByLengthWithoutDuplicates: lengthOfStringToCheck = 0 for currentCharacterInString in TemporaryStringToUseForPalindromes: lengthOfStringToCheck = lengthOfStringToCheck + 1 if lengthOfStringToCheck != 0: TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1] if TemporaryStringToUseForPalindromesReversed == TemporaryStringToUseForPalindromes: ListOfPotentialPalindromes.append(TemporaryStringToUseForPalindromes) #Remove any duplicates that might have snuck in there ListOfPotentialPalindromesWithoutDuplicates = [] for CurrentPotentialPalindrome in ListOfPotentialPalindromes: HaveFoundStringInList = False for CurrentTemporaryPalindrome in ListOfPotentialPalindromes: if CurrentPotentialPalindrome == CurrentTemporaryPalindrome: HaveFoundStringInList = True if(HaveFoundStringInList == True): ListOfPotentialPalindromesWithoutDuplicates.append(CurrentStringWorkingWith) lengthOfPalindromes = [] for CurrentPossiblePalindrome in ListOfPotentialPalindromesWithoutDuplicates: CurrentPossiblePalindromeLength = 0 for currentCharacterInPossiblePalindrome in CurrentPossiblePalindrome: CurrentPossiblePalindromeLength = CurrentPossiblePalindromeLength + 1 lengthOfPalindromes.append(CurrentPossiblePalindromeLength) while not all(lengthOfPalindromes[i] <= lengthOfPalindromes[i+1] for i in xrange(len(lengthOfPalindromes)-1)): shuffle(lengthOfPalindromes) #find the last value in the list: currentValue = 0 for currentPalindromeLength in lengthOfPalindromes: currentValue = currentPalindromeLength print currentValue ``` ## Note Not really suitable for strings longer than 4 characters. Does "abba" fine, but I went and bought coffee and cooked lunch before it did abcba ## Issues: Insane variable naming (and inconsistent too) Ludicrous algorithm choice ( Calculate all possible permutations of every substring of the given string, check if they're palindromes, sort them by length and lookup last value) Actually contains the solution to the problem ``` TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1] ``` Stupid sorting algorithm (bogosort) and a nutjob method of ensuring the list is sorted. Also, there's an indentation error in the duplicate checking which actually does nothing at all, it's just a waste of time. [Answer] **C** Finding palindromes is an PNP\* hard operation, so it must be done with highly optimized code. Here are five optimization tricks which will help find the solution faster. 1. Start with the right language. As everyone knows, 'C' is fastest. 2. Use a fast algorithm. [BoyerMoore](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) is the world record holder for string searching, so we will use that. We will also search for the longest substrings first so we have the best chance of finding a long match. 3. Know your processor. Modern computers are horribly slow at branches of the `if this else that` form. (As you go further in your career, you should master Branch Prediction if you want to be a true code ninja.) This code avoids the `if` branching problem by using `for` statements instead, which gives you 3 instructions for the price of one. 4. Pay attention to the "Big-O". This algorithm uses no curly braces inside the function bodies, thereby preventing any nested loops. So the runtime must be O(N). 5. Don't forget the micro-optimizations. By using the well-known technique of removing all inter-statement whitespace, I was able reduce the compiler's workload and gain another 10% speedup. But don't skimp on variable names, readability is important. \* Palindrome-Not Palindrome ``` #define OFFSET 0XFF #define ln(s) strlen(s) //macro to avoid runtime overhead char* boyermore(char* needle, char* haystack){ int i,k[OFFSET]; for(i=0;i<OFFSET;i++)k[i]=ln(haystack); for(i=1;i<ln(haystack);i++)k[haystack[i]]=ln(haystack)-i; for(i=2;ln(needle)>=ln(haystack);needle+=k[needle[ln(haystack)]]) for(i=ln(haystack)-1;needle[i]==haystack[i];i--)if(!i)return needle; return 0xFF-OFFSET; } char* reverse(char*src,char*dest,int loops){ for(*(src+loops)=0;loops;src[--loops]=*(dest++)); return src; } #define imax(a,b) ((a>b)?a:(b)) int main(int i, char*in[2]){ char* is,*begin,*maybe,max=-1; char* end=in[-max],*start=end+ln(end); for(begin=malloc(start-end);--start>end;) for(i=start-end;i>0;i--) for(maybe=reverse(begin,start-i,i);boyermore(in[1],maybe);*maybe=1) for(;i>max;max=imax(i,max))is=start-i; for(maybe="found";max>0;max=-max) puts(reverse(begin,is,max)); } ``` --- Besides the obvious trolling in the commentary, there are several other issues. The search algorithim is a valid implementation of Boyer-Moore-Horspool, but it never stores the string lengths, instead calling strlen something like N\*M times, making it much slower than a simple search. "Searching for the longest string first" is true, but after that it does not search by length order, so an early exit would give a wrong answer, if it was implemented. But is is not, so it searches all the N! possibilities anyway. And almost all the parameter names (needle/haystack; src/dest) are reversed from their standard meanings. [Answer] This is what I have so far in VB6: ``` Public Function strLongestPalindrome(ByVal strInput as String) as String strLongestPalindrome = "" Dim a as Integer Dim b as Integer For a = 1 To Len(strInput) For b = 1 to a Dim c as Integer Dim d as Integer c = a d = b Do If Mid$(strInput, c, 1) = Mid$(strInput, d, 1) Then c = c + 1 d = d - 1 If c >= d Then strPalindrome = Mid$(strInput, a, b-a+1) If Len(strLongestPalindrome) < Len(strPalindrome) Then strLongestPalindrome = strPalindrome End If Exit Do End If Else Exit Do End If Loop Next Next End Function ``` But I don't think it works, and I think I can make it better. [Answer] Here's a Java solution for you: ``` public String findLongestPalindrome(String s){ if(s.equals("the longest palindrome")){ return "the longest palindrome"; }else{ throw new IllegalArgumentException(); } } ``` [Answer] # AutoHotkey ``` ;msgbox % longest_palindrome_in_string("racecar abcdedcba alkdf") longest_palindrome_in_string(str){ l := Strlen(str) , max := 1 loop % l { p := A_index loop % l-p { s := Substr(str, p, A_index+1) , k := "" loop, parse, s k := A_LoopField k if k = %s% if (sl:=Strlen(s)) > max out := s , max := sl } } return out } ``` The function returns spaces too as they are part of a palindrome sequence in string. So the above returns `<space>abcdedcba<space>`. [Answer] # Polyglot This is trolling because it asks to "find the longest palindrome in a string", so it is finding the longest palindrome in "a string" ``` String palindrome(){ return null; //There are no palindromes in "a string" } ``` [Answer] I never knew strings could contain palindromes, can you show me where you learned this? And if you need the longest palindrome, please visit this site: <http://www.norvig.com/pal2txt.html> [Answer] Iterate through each character of the string. Then check the characters before and after that character. Then the characters two before and two after that character. Keep repeating until you get to characters that are not the same. This will allow you to identify the length of each palindrome in the word. However this method will only work for palindromes of odd length. To check for palindromes of even length, check the character at position i and i-1, then i+1 and i-2, then i+2 and i-3, etc. Hope this helps!! [Answer] The obvious answer is to compare the string with its own inverse and compute the longest common sequence. The following Perl program does just that. You may need to download the Acme::DonMartin module, it is not usually installed by default. ``` use Acme::DonMartin; sklush klikrunk skroik hee doodle shompah sproingdoink varoom hushle fwiskitty twop pok zich frack gleep shloop zgluk zlitz faroolana deebe fump kachoo zock fween boong pitooie oggock gahoff glip fwask padap fut ooga chukkunk shkaloink kazash splosh sklizzorch fak ahh doom twop beedoop gak wee fitzrower shkwitz shklik fweep spla gring glink splurp thomp fwoof thoom kipf ging krunch blib ga kikatik bash dap thork huff katoonk fak shik stoof dimpah skapasch skronch kachunka arargh sprat gonk yip inkle blink fagwoosh fowm splapple blamp doomp ploom gishklork shwik fomp plortch skroik gashplutzga plortch da goyng shtork borfft zwot ping puffa trump thlip dig blonk thhhut splatch doonk sklizzorch sprazot pwof slapth spashle kreek eck kik dit foing glukkle glikity spazoosh plapf gashklitz mabbit boong sklortch swipadda sknikle phelop skloshitty zat dokka splazitch tika zikka fling shooka glangadang brrrapp fwizz gasploosh doop swish dikka splesh shooka blut galink yeech caw tink sklitch shash tffp skrink poffisss oont spazoosh blort aarh ting ho shpikkle shompah tood shkalink gloople skloshitty ``` [Answer] # Lua/Python Lua is a very fast language (which you need, because there are a lot of substrings to be checked!), but Python is better with string handling. So why not use both? Because I've heard it's good to have local variables, I have one. Also, I've separated the function calls from their arguments, because too many arguments make expressions cluttered and unreadable. Also, I think this will work with any strings you want to try, there probably will not be any problems with strange inputs whatsoever. ``` function is_palindrome() if os.execute("python -c 'exit(\"" .. is_palindrome_argument .. "\"==\"" .. is_palindrome_argument .. "\"[::-1])'") == true then return false else return true end end function longest_palindrome() local longest -- very important to use local variables for length = 1, #longest_palindrome_argument do for start_index = 1, #longest_palindrome_argument - length + 1 do is_palindrome_argument = string.sub(longest_palindrome_argument, start_index, start_index + length - 1) if is_palindrome() then longest = is_palindrome_argument end end end return longest end longest_palindrome_argument = "foo racecar" print(longest_palindrome()) ``` (BTW, you won't believe how long this took me to make it work.) [Answer] Python one-liner: ``` s = "here goes your string" print max(p for p in [s.lower()[j:i] for i in range(len(s) + 1) for j in range(len(s) + 1) if ' ' not in s[j:i] and s[j:i] != '' and len(s[j:i]) > 2] if p == p[::-1]) ``` [Answer] # Python - 126 Characters Here's my go at this: ``` k=[] for i in range(len(p)): for j in range(i,len(p)): if p[i:j]==p[j:i:-1]: k.append(p[i:j+1]) k.sort(key=len) k=k[-1] ``` This works in both Python 2.x and 3.x, I believe. The variable k holds the answer. EDIT: I forgot to say, the variable p should hold the string to check for palindromes. This is a legit implementation, so it'll work for any string. [Answer] Java Obviously if `aString` is itself a palindrome then `aString` is the longest palindrome inside `aString`. You can tell it is working by the assertion statement. Do not think too much about the first line of executable code. That is just standard java boilerplate. ``` public CharSequence findLongestPalindromeInside(String aString) { aString=new StringBuilder(aString).append(new StringBuilder(aString).reverse()); assert isPalindrome(aString); return aString; } public boolean isPalindrome(CharSequence charSequence) { return charSequence.toString().equals(new StringBuilder(charSequence).reverse().toString()); } ``` [Answer] ## Game Maker Language ``` var str,length,i,out,char; str=argument0 out="" length=string_length(argument0) for(i=0;i<string_length(argument0);i+=1){ char=string_char_at(str,length-i) out+=char } return argument0+out; ``` [Answer] ## Fortran Strings are too tough to work with in Fortran, so I opted to use `iachar` to convert them all to integers: ``` program long_palindrome implicit none character(len=100) :: string integer, dimension(100) :: fwd,rev integer :: i,j,fs,fe,rs,re print *,"enter string with palindrome hidden in it (max 100 characters)" read(*,*) string fwd = 0 ! convert characters to ASCII integers do i=1,len(trim(string)) fwd(i) = iachar(string(i:i)) enddo ! reverse whole array j=len(trim(string)) do i=1,len(trim(string)) rev(i) = fwd(j) j = j-1 enddo ! match strings of fwd and rev rs = 1; re = len(trim(string)) fs = 1; fe = len(trim(string)) ! test to see if whole thing is a palindrome if(all(fwd(fs:fe)==rev(rs:re))) then print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1 stop endif ! nope? oh well, guess we have to loop through and find it fs = 0 do fs = fs+ 1 do fe = len(trim(string)),fs+1,-1 do rs=1,fs re = fe-rs+1 if(all(fwd(fs:fe)==rev(rs:re))) then print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1 stop endif enddo enddo if(fs==len(trim(string))-1) exit enddo print *,"hmm, doesn't look like there was a palindrome of length > 1..." end program long_palindrome ``` It doesn't exactly work. Given the string `aabbaac` it says the longest is `aa`, but given the string `acasdabbbaabb`, it says the longest is `abbba`. Close enough. [Answer] You can't compete in today's market by just doing what is asked. This code will also find the shortest palindrome and is case insensitive: ``` def flp(s): lp = 'the longest palindrome' sp = 'the shortest palindrome' return lp if lp in s.lower() else sp if sp in s.lower() else '' >>> flp('xxxxthe longest palindromexxxx') 'the longest palindrome' >>> flp('xxxxthe shortest palindromexxxx') 'the shortest palindrome' ``` [Answer] Lua ``` function findPalendromes(str) str=str.." " ret_s="" for s in str:gmatch"(%w+)[ ]" do if s==s:reverse() and s:len()>ret_s:len() then ret_s=s end end return ret_s end ``` [Answer] **Most efficient Python implementation that trumps all other efforts:** ``` def find_the_longest_palindrome(s): print "'the longest palindrome' found at : " + str(s.find("the longest palindrome")) ``` **Notes:** This will always find "the longest palindrome" It is case sensitive. With some modifications it can also be made to find other strings. However, you will need to create a class, add an appropriate method and then subclass it for each string to be found. This function could be improved by porting to FORTRAN 77 or hard-coding into Intel 8008 machine code. [Answer] This is my first code trolling answer. It isn't a particularly brutal troll, it just struck me as a silly way to answer the question ``` private static String findLongestPalindrome(String input) { String longest = null; for (int i = 1; i <= input.length(); i++) { Matcher m = pattern(i).matcher(input); if (m.find()) { longest = m.group(); } } return longest; } private static Pattern pattern(int len) { int size = len / 2; StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append("(.)"); } if (len != size * 2) { sb.append("."); } for (int i = size; i > 0; i--) { sb.append("\\").append(i); } return Pattern.compile(sb.toString()); } ``` Trolls are: * Manually creating the same Pattern every time * Using expensive backreferences to find palindromes * Iterating from 1 to input.length() (doing it in reverse you would be guaranteed that the first match you find is the longest. Doing it the above way is dumb) [Answer] # Python 3 ``` from itertools import takewhile def common_part(s1, s2): return sum(takewhile(bool, (a==b for a, b in zip(s1, s2)))) def palindromes(s): for i in range(1, 2*len(s)): m = i//2; n = i - m common = common_part(s[n-1::-1], s[m:]) p = s[n-common:m+common] if p: yield p string = input('> ') print('Longest palindrome is', repr(max(palindromes(string), key=len))) ``` Very efficient program. It searches long palindroms with center in sequential positions (on char and between) and select longest ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/5562/edit). Closed 1 year ago. [Improve this question](/posts/5562/edit) ## The Challenge Implement [tetration](http://en.wikipedia.org/wiki/Tetration) (aka Power Tower or Hyperexponentiation) with the least amount of characters. ## The Conditions * Don't use the 'power' operator or its equivalents (such as `pow(x,y)`, `x^y`, `x**y`, etc.) * Input given as: `x y` (separated by a space) * `x` is exponentiated by itself `y` times. * Your method must be able to compute at least `4 3` (4 exponentiated by itself 3 times) ## The Scoring * **Lowest score wins:** (# of characters) * Bonus deduction if you do not use the multiplication operator (-5 points). * No Speed/Memory requirements. Take as long as you want. ## Examples ``` x, 0 -> 1 2, 2 -> 2^2 = 4 2, 4 -> 2^(2^(2^2)) = 65536 4, 3 -> 4^(4^4) = 4^256 = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096 ``` Open to suggestions/alterations/questions [Answer] # J, score is 7 (12 chars - 5 points for avoiding multiplication) `+/@$/@$~/@$~` usage: ``` 4 +/@$/@$~/@$~ 3 1.34078e154 t=.+/@$/@$~/@$~ NB. define a function 4 t 3 1.34078e154 2 t 2 4 ``` Just few nested folds: * Using multiplication it would be `*/@$~/@$~` * Using power it would be `^/@$~` where `$~` creates array, `/` is a fold function. [Answer] ## Haskell, ~~87~~ 85 - 5 == 80 ~~82~~ ``` import Data.List t x=genericLength.(iterate(sequence.map(const$replicate x[]))[[]]!!) ``` Uses neither of exponentiation, multiplication or addition (!), just list operations. Demonstration: ``` Prelude> :m +Data.List Prelude Data.List> let t x=genericLength.(iterate(sequence.map(const$replicate x[]))[[]]!!) Prelude Data.List> t 2 2 4 Prelude Data.List> t 2 4 65536 Prelude Data.List> t 4 3 ``` ... ahm... you didn't say anything about performance or memory, did you? But given enough billions of years and some petabytes of RAM, this would still yield the correct result (genericLength can use a bigInt to count the length of the list). [Answer] ## GolfScript, ~~15~~ 18 chars ``` ~])*1\+{[]+*{*}*}* ``` Yes, one of the `*`s is a multiplication operator (exercise: which one?) so I don't qualify for the 5 char bonus. Still, it's just barely shorter than [Peter's solution](https://codegolf.stackexchange.com/a/5563). This earlier 15-char version is otherwise the same, but produces no output when the second argument is 0. Thanks to r.e.s. for spotting the bug. ``` ~])*{[]+*{*}*}* ``` [Answer] ## J, 16 19 12 characters ``` */@$~/1,~$~/ ``` or as a verb (17 characters): ``` h=:[:*/@$~/1,~$~/ ``` usage: ``` h 2 4 65536 ``` or taking input from keyboard (24 27 20 characters): ``` */@$~/1,~$~/".1!:1]1 ``` with thanks to [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl) for pointing out my stupidity. :-) **Explanation:** J is read from right to left, so using `2 4`: `/` is used to insert the verb `$~` between each pair of items in the list. `$~` takes the left item and shapes it `$` using the right item (the `~` reverses the arguments) - so this would be equivalent to `4 $ 2` which gives you a list of `2`s which is four items long `2 2 2 2`. Now we append 1 to the list `1,~` and then do the same thing again; `/` insert a verb `*/@$~` between each pair of items in the list. This verb starts in the same way `$~` but this time it `/` inserts a `*` between each item of the newly generated list. The `@` just makes sure that the `*/@$~` works as one verb instead of two. This gives `2` multiplied by itself enough times to be equivalent to `2^4`. [J's vocabulary page](http://jsoftware.com/help/dictionary/vocabul.htm) - I find solving problems with J fun just because of the different way it sometimes does things. Adding one further iteration to remove the `*` operator has 2 problems * It comes out at 17 characters (`+/@$~/,@$~/1,~$~/`) which, even with the -5 bonus, is too long * It runs out of memory if the number gets too large so doesn't meet the requirement of being able to calculate `4 3` [Answer] ## GolfScript (24 chars - 5 = 19 points) ``` ~\1{1{0{+}?}?}{@\+@*}:?~ ``` is insanely slow. ## (or 20 chars) ``` ~\1{1{*}?}{@\+@*}:?~ ``` is much faster. [Answer] ## Python, 70 This uses nested `eval` calls, eventually producing a string `"a*a*a*a...*a"` which gets evaluated. Almost half of the score is wasted on getting the arguments... though I've noticed that a few other solutions don't bother with that. ``` a,b=map(int,raw_input().split()) exec"eval('*'.join('a'*"*b+'1'+'))'*b ``` [Answer] # Br\*\*nfuck, 128-5=123 bytes ``` +<<+<<,<,[>[>+>>+<<<-]>[<+>-]>[>[>>+>+<<<-]>>>[<<<+>>>-]<<[>[>+>+<<-]>>[<<+>>-]<<<-]>[-]>[<<+>>-]<<<<-]>>[<<+>>-]+<[-]<<<<-]>>>. ``` Input is in the form of characters with code points of the numbers desired as inputs. Output is the same. An explanation is ~~coming when I have the time~~ below. Do I get bonus points for not using exponentiation, multiplication, OR even addition? ``` Cell 3 (0-indexed) is the running total x. This calculates the nth tetration of a. +<<+<<,<, Initialize tape with [n, a, 0, 1, 0, 1] [ While n: >[>+>>+<<<-]>[<+>-] Copy a 3 cells to right: [n, a, 0, x, a, 1] >[ While x: >[>>+>+<<<-]>>>[<<<+>>>-] Copy a 2 cells to right: [n, a, 0, x, a, 1, a, 0] <<[>[>+>+<<-]>>[<<+>>-]<<<-] Cell 7 = prod(cell 5, cell 6) >[-]>[<<+>>-]<<<<-] Move this value to cell 5. End while. >>[<<+>>-]+<[-]<<<<-] Update x to result of exponentiation. End while. >>>. Print the result! ``` This works (tested) for `x 0`, `0 x`, `x 1`, `1 x`, `x 2`, `2 3`, and `2 4`. I tried `3 3`, but it ran for several hours without finishing (in my Java implementationโ€”probably not optimal) (EDIT: in @Timwi's [EsotericIDE](https://github.com/Timwi/EsotericIDE) [It's great! Y'all should try it] as well. No luck.). In theory, this works up to the cell size of the specific implementation. [Answer] ### Scala:110 ``` type B=BigInt def r(a:B,b:B,f:(B,B)=>B):B=if(b>1)f(a,r(a,b-1,f))else a def h(a:B,b:B)=r(a,b,r(_,_,r(_,_,(_+_)))) ``` ungolfed: ``` type B=BigInt def recursive (a:B, b:B, f:(B,B)=>B): B = if (b>1) f (a, recursive (a, b-1, f)) else a recursive (2, 3, recursive (_, _, recursive (_, _, (_ + _)))) ``` explanation: ``` type B=BigInt def p (a:B, b:B):B = a+b def m (a:B, b:B):B = if (b>1) p (a, m (a, b-1)) else a def h (a:B, b:B):B = if (b>1) m (a, h (a, b-1)) else a def t (a:B, b:B):B = if (b>1) h (a, t (a, b-1)) else a ``` plus, mul, high(:=pow), tetration all work in the same manner. The common pattern can be extracted as recursive method, which takes two BigInts and a basic function: ``` def r (a:B, b:B, f:(B,B)=>B):B = if (b>1) f(a, r(a, b-1, f)) else a r (4, 3, r (_,_, r(_,_, (_+_)))) ``` The underlines are placeholder for something which gets called in this sequence, for example the addition plus(a,b)=(a+b); therefore (*+*) is a function which takes two arguments and adds them (a+b). unfortunately, I get issues with the stack size. It works for small values for 4 (for example: 2) or if I reduce the depth for one step: ``` def h(a:B,b:B)=r(a,b,r(_,_,(_*_))) // size -7, penalty + 5 def h(a:B,b:B)=r(a,b,r(_,_,r(_,_,(_+_)))) ``` The original code is 112 characters and would score, if valid, 107. Maybe I find out how to increase the stack. The expanded algorithm can be transformed to tailrecursive calls: ``` type B=BigInt def p(a:B,b:B):B=a+b import annotation._ @tailrec def m(a:B,b:B,c:B=0):B=if(b>0)m(a,b-1,p(a,c))else c @tailrec def h(a:B,b:B,c:B=1):B=if(b>0)h(a,b-1,m(a,c))else c @tailrec def t(a:B,b:B,c:B=1):B=if(b>0)t(a,b-1,h(a,c))else c ``` The tailrecursive call is longer than the original method, but didn't raise a stackoverflow in the long version - however it doesn't yield a result in reasonable time. t(2,4) is fine, but t(3,3) already was stopped by me after 5 min. However, it is very elegant, isn't it? ``` // 124 = 119-5 bonus type B=BigInt def r(a:B,b:B,c:B,f:(B,B)=>B):B=if(b>0)r(a,b-1,f(a,c),f)else c def t(a:B,b:B)=r(a,b,1,r(_,_,1,r(_,_,0,(_+_)))) ``` And now the same as above: use stinky multiplication (we even profit while rejecting the bonus of 5, because we save 7 characters: win=4 chars:) ``` // 115 without bonus type B=BigInt def r(a:B,b:B,c:B,f:(B,B)=>B):B=if(b>0)r(a,b-1,f(a,c),f)else c def t(a:B,b:B)=r(a,b,1,r(_,_,1,(_*_))) ``` invocation: ``` timed ("t(4,3)")(t(4,3)) t(4,3): 1 scala> t(4,3) res89: B = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096 ``` runtime: 1ms. [Answer] ## Python, 161 - 5 (no \* operator) = 156 ``` r=xrange def m(x,y): i=0 for n in r(y):i+=x return i def e(x,y): i=1 for n in r(1,y+1):i=m(i,x) return i def t(x,y): i=1 for n in r(y):i=e(x,i) return i ``` invoke: ``` t(2, 4) ``` [Answer] ## Perl, 61 chars here's a bizarre one ``` sub t { ($x,$y,$z)=@_; $y>1&&t($x,$y-1,eval$x."*$x"x($z-1||1))||$z } ``` usage: ``` print t(2,4,1) ``` [Answer] ## *Mathematica*, ~~40~~ 33 This doesn't quite conform to the rules but it is not in contention for the shortest code anyway, and I hope that it will be of interest to someone. ``` m@f_:=Fold[f,1,#2~Table~{#}]&; m[m@Sum] ``` This builds a "tetration" function when it is run, but the arguments must be given in reverse order. Example: ``` m[m@Sum][3, 4] ``` > > 1340780792994259709957402499820584612747936582059239337772356144372176 > 4030073546976801874298166903427690031858186486050853753882811946569946 > 433649006084096 > > > [Answer] ## Haskell: ~~58~~ 51 chars, with or without multiplication. ``` i f x 1=x;i f x n=f$i f x$n-1 t=i(\o n->i(o n)n)(+)4 ``` Ungolfed: ``` bump op n a = iterate (op n) n !! (fromIntegral $ a-1) tetrate = iterate bump (+) !! 3 ``` Shorter definition comes from inlining โ€œbumpโ€, and defining a custom version of โ€œiterateโ€. Unfortunately the result is impossibly inefficient, but starting with (\*) instead of (+) gives decent speed. In `ghci`: ``` Prelude> let i f x 1=x;i f x n=f$i f x$n-1 (0.00 secs, 1564024 bytes) Prelude> let t=i(\o n->i(o n)n)(*)3 (0.00 secs, 1076200 bytes) Prelude> t 4 3 13407807929942597099574024998205846127479365820592393377723561443721764030073546 976801874298166903427690031858186486050853753882811946569946433649006084096 (0.01 secs, 1081720 bytes) ``` [Answer] ## Ruby ~~66~~ 59 characters ``` def e(x,y) r=1 (1..y).each{t=x (2..r).each{t*=x} r=t} r end ``` [Answer] ## Rockstar, 233 bytes Rockstar is a quite new computer programming language, designed for creating programs that are also song lyrics. Rockstar is heavily influenced by the lyrical conventions of 1980s hard rock and power ballads. The solution takes two inputs, one per each line (string manipulation is very limited). It uses multiplication operator, so no bonus to apply for :/ ``` P takes A,B N is 1 C is 1 While C is as low as B Let N be N of A Build C up Give back N T takes E,F If F is empty Give back 1 Else Knock F down Let G be T taking E,F Give back P taking E,G Listen to X Listen to Y Say T taking X,Y ``` Ungolfed, here's a more lyric version (comments are in parentheses, which are standard comments in Rockstar). Variable names may take up more words, and all words count ('my power' is different from 'the power' and from 'Power') ``` Power takes the force and the cross (function def, two parameters: 'the force', 'the cross') Build my arm up ('my arm' := 1) (literally: 'my arm'++, but my arm was initialized with 0) Build my faith up ('my faith' := 1) While my faith is as weak as the cross (While loop, condition: 'my faith' <= 'the cross') Let my arm be the force of my arm ('my arm' := 'the force' * 'my arm' ) Build my faith up ('my faith' ++ ) (empty line to terminate While block) Give back my arm (return 'my arm') (empty line to terminate function block) Tower takes the force and the enemy (function def, two parameters: 'the force', 'the enemy') If the enemy is nowhere (If, condition: 'the enemy' == 0) (literally: 'the enemy' == NULL, but NULL is considered 0 in arithmetics) Build Victory up (Victory := 1, this is a bit diffeerent from the golfed version) Give back Victory (return Victory) Else (else) Knock the enemy down ('the enemy' -- ) Let the defense be Tower taking the force and the enemy ('the defense' := Tower ('the force', 'the enemy')) Give back Power taking the force and the defense (return Power ('the force', 'the defense')) (empty line to terminate If block) (empty line to terminate Function block) Listen to us (input: 'us') Listen to your enemy (input: 'your enemy') Scream Tower taking us and your enemy (output: Tower('us', 'your enemy')) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes *Have some BigInts* ``` a=>g=b=>b--?(P=n=>n--?a*P(n):1n)(g(b)):1n ``` [Try it online!](https://tio.run/##PU1LCsIwEN3nFIMgJDaV1s/GmnqFnqCQ9EekTKSN3Yhnj5OKbt5neO/NXS96bib78Cm6tgu9ClqVgzKqNGl645VCVSIpvas4ikuOgg/ciKhC/8TGW4fgu9lzLcEIeDFoHM5u7PajG/hm20JdA6Ei2EiIKQk91yKuFOzN2NrOUEKGdFhd/re9m4AvegJLCzkWxFc4R04Swb6fDxS2v@qJzJGa4QM "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes - 5 (no multiplication) = 4 ``` xxxSยฅ/ยฅ@/ ``` [Try it online!](https://tio.run/##y0rNyan8/7@ioiL40FL9Q0sd9P///2/03wQA "Jelly โ€“ Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes - 5 (no multiplication, but cheats by using the list product atom) = 1 ``` xxPยฅ@/ ``` [Try it online!](https://tio.run/##y0rNyan8/7@iIuDQUgf9////G/03AQA "Jelly โ€“ Try It Online") [Answer] ## Python, 112 chars The numbers should be the 1st and 2nd argument: `python this.py 4 3` `**` operator not used. `*` used. It's quite trivial to implement, exactly like `**`, but costs more than 5 chars. ``` import sys p=lambda y:y and x*p(y-1)or 1 t=lambda y:y>1 and p(t(y-1))or x x,y=map(long,sys.argv[1:]) print t(y) ``` [Answer] ## C, 117 105 99 chars EDIT: Merged the two functions `p` and `r` into one, saving some chars. Of 99 chars, 52 do the actual calculation (including variable definitions). The other 47 are for handling input and output. BUG: Badly handles powers of 0 (e.g. `0 2`). Should find a minimum cost fix. This isn't a bug, I forgot that `0 2` is undefined. Successfully handles `4 3`, and even gives an exact result. However, can be inaccurate for some smaller numbers. Prints the number with a trailing `.000000`. ``` x,y,z; double R(){return--y?!z?y=R(),R(z=1):x*R():x;} main(){ scanf("%d%d",&x,&y); printf("%f\n",R()); } ``` [Answer] ## Factor, 187 characters ``` USING: eval io kernel locals math prettyprint sequences ; IN: g :: c ( y x o! -- v ) o 0 = [ x y * ] [ o 1 - o! y x <repetition> 1 [ o c ] reduce ] if ; contents eval( -- x y ) swap 2 c . ``` Before golf: ``` USING: eval io kernel locals math prettyprint sequences ; IN: script ! Calculate by opcode: ! 0 => x * y, multiplication ! 1 => x ^ y, exponentiation ! 2 => x ^^ y, tetration :: calculate ( y x opcode! -- value ) opcode 0 = [ x y * ] [ ! Decrement the opcode. Tetration is repeated exponentiation, ! and exponentiation is repeated multiplication. opcode 1 - opcode! ! Do right-associative reduction. The pattern is ! seq reverse 1 [ swap ^ ] reduce ! but a repetition equals its own reverse, and 'calculate' ! already swaps its inputs. y x <repetition> 1 [ opcode calculate ] reduce ] if ; contents eval( -- x y ) ! Read input. swap 2 calculate . ! Calculate tetration. Print result. ``` I did not remove the multiplication operator `*`. If I did so, then I would need to add some logic expressing that the sum of an empty sequence is 0, not 1. This extra logic would cost more than the -5 bonus. --- *Rule breaker, 124 + 10 = 134 characters* ``` USING: eval kernel math.functions prettyprint sequences ; contents eval( -- x y ) swap <repetition> 1 [ swap ^ ] reduce . ``` This program has a lower score, but the exponentiation operator `^` breaks the rules. The rules say "(# of characters) + (10 \* (# of 'power' operators))", so I applied the +10 penalty. However, the rules also say "Don't use the 'power' operator", so any program taking this penalty does break the rules. Therefore, this program of 134 characters is not a correct answer, and I must present my longer program of 187 characters as my answer. [Answer] ## Haskell 110 - 5 = 105 Tetration Peano Style. This is the most insanely slow solution possible, just a warning, but also avoids even addition. ``` data N=Z|S N a&+Z=a a&+S b=S$a&+b _&*Z=Z a&*S b=a&+(a&*b) _&^Z=S Z a&^S b=a&*(a&^b) _&>Z=S Z a&>S b=a&^(a&>b) ``` This relies on you having the patience to type out Peano numbers (and won't show the answer, If you actually want to run it, add these few lines (90 chars): ``` f 0=Z f a=S$f$a-1 t Z=0 t(S a)=1+t a main=interact$show.f.(\[x,y]->x&>y).map(f.read).words ``` [Answer] # Ruby, 47 46 45 `t=->x,n{r=x;2.upto(n){r=([x]*r).inject :*};r}` [Answer] ## Lua: 133 chars, multiplication-less ``` a,b=io.read():match"(%d+) (%d+)"a,b,ba=a+0,b+0,a for i=1,b-1 do o=1 for i=1,a do o=o+o for i=1,ba-b do o=o+o end end a=o end print(o) ``` I was originally going to use string repetition hacks to do fake multiplication, but it likes to fail on large values. I could possibly use dynamic compilation and loadstring to make it smaller, but it's getting late here... I need sleep. Entering "4 3" into stdin outputs: ``` 1.3407807929943e+154 ``` [Answer] # VBA, 90 Chars \*Perhaps the no multiplication bonus is not good enough. I think the no multiplication answer is much more interesting, but this is code golf, so it's not the best. Here's an answer without `*`, and a better (shorter, and better scoring) answer with it: ## 90 chars, no power operators, uses multiplication = 90 ``` Sub c(x,y) f=IIf(y,x,1):For l=2 To y:b=x:For j=2 To f:b=b*x:Next:f=b:Next:MsgBox f End Sub ``` ## 116 chars, no power operators, no multiplication bonus (-5) = 111 ``` Sub c(x,y) f=IIf(y,x,1):For l=2 To y:b=x:For j=2 To f:For i=1 To x:a=a+b:Next:b=a:a=0:Next:f=b:Next:MsgBox f End Sub ``` **NOTE:** VBA has issues printing the number when the result is very large (i.e. `4, 3`), but it does calculate correctly, so if, for example, you wanted to USE that number, you would be good to go. Also, even BIGGER numbers overflow (i.e. `3, 4`). [Answer] # [Perl 6](http://perl6.org/), 32 bytes ``` ->\a,\b{(1,{[*] a xx$_}...*)[b]} ``` [Try it online!](https://tio.run/##NcndCkAwAIbhW/nSEprlZzliNzJaW9kRESc0u/YhOXp6e9dxm5own4gtupCLXtPeuKSkTmYDNI6DKM8Yy1JpBh92fSIiCp2As7ieF8EuG9oShaBoq4/6r@qDv3DUItw "Perl 6 โ€“ Try It Online") `(1, { [*] a xx $_ } ... *)` is a lazy sequence that generates the power tower, each element being the a list which consists of the first input parameter `a` replicated (`xx`) a number of times equal to the previous element (`$_`), that list then being reduced with multiplication (`[*]`). From that sequence we simply pluck out the `b`-th element. [Answer] # Lambda calculus, 10-5 (using [Church encoding](https://en.wikipedia.org/wiki/Church_encoding#Calculation_with_Church_numerals) and [De Bruijn indeces](https://en.wikipedia.org/wiki/De_Bruijn_index)) `ฮปฮป(1ฮป13)ฮป1` ## Explanation Without De Bruijn indeces: `ฮปa,b.(b ฮปc.ca)ฮปc.c`: ``` ฮปa,b. define the anonymous function f(a,b)= (b apply the following function b times ฮปc. the anonymous function g(c)= ca) apply c to a because of church encoding this is equal to a^c ฮปc.c the identity function, 1 in church encoding ``` If you define `exp_a(x)=a^x` this program defines `aโ†‘โ†‘b=exp_a^b(1)` where `^b` denotes function itteration. I'm not sure if this is allowed because `ca` is technically equivalent to `a^c` how ever it is not a real built-in and only a side effect of the way integers are encoded in lambda calculus. [Answer] **Python - 151 bytes** ``` Python 3.0: r=range def exp(a,b): if b=0: a=1 else: r1=a for i in r(1,b): s=s*a def tet(a,b): r1=0 if b=0: a=1 else: r1=a for i in range(1,b): r1=exp(a, result) ``` Here's how the new *new* version works. 1: Exponentiation is initialized (multiplies a by a b times), as well as tetration (in terms of our exp function). 2: a is stored in result of the tetration function. 3: Then we exponentiate a to result (as tetration does), and store that in result 4: Repeat step 3 b times. Feel free to tell me I suck. (With *huge* credits to the commenters and Googology Wiki) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes (27 characters) ``` a๏’กNest[Nest[a#&,1,#]&,1,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/H9pIV@qcUl0WAiUVlNx1BHORZK/g8oyswriU6LroiNNoiN5YJxjWKBCIVrgsQ1iY02jo39DwA "Wolfram Language (Mathematica) โ€“ Try It Online") Input curried as `f[x][y]`. --- Without `*`: **35 bytes** (33 characters) ``` a๏’กa+#&~n~0~n~1~n~1 n=Nest~Curry~3 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/H9pIWJ2spqdXl1BkBsCMJcebZ@qcUldc6lRUWVdcb/A4oy80qi06IrYqMNYmO5YFyjWCBC4ZogcU1io41jY/8DAA "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] **Javascript: 116 chars** ``` function t(i){y=i.split(' ');a=y[0];b=y[1];return+b&&p(a,t(a+' '+(b-1)))||1}function p(a,b){return+b&&a*p(a,b-1)||1} ``` t('4 3') Outputs: ``` 1.3407807929942597e+154 ``` [Answer] ### Python ~~(111)~~ (113) no \* ``` r=lambda x,y:(x for _ in range(y));t=lambda x,y:reduce(lambda y,x:reduce(lambda x,y:sum(r(x,y)),r(x,y)),r(x,y),1) ``` [6\*\*\*3](https://gist.github.com/3148384) - 36k digits)) Upd: Have to add initial value, to fit t(X,0)=1 [Answer] ## Haskell: 88-5 chars without multiplication, 59 chars with multiplication Without multiplication: ``` h x y=foldr(\x y->foldl(\x y->foldl(+)0(replicate x y))1(replicate y x))1(replicate y x) ``` There are probably ways that I could golf that down a little. With multiplication: ``` h x y=foldr(\x y->foldl(*)1(replicate y x))1(replicate y x) ``` And finally, the ungolfed program: ``` mult x y = foldl (+) 0 (replicate x y) expo x y = foldl (mult) 1 (replicate y x) h x y = foldr (expo) 1 (replicate y x) ``` This is probably the simplest way to do this problem, which is defining multiplication as repeated addition, exponentiation as repeated multiplication, and tetration as repeated exponentiation. ]
[Question] [ Print or return the following string: ``` R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* *....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......* R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R ``` This represents all the possible positions of a rook on an 8x8 chessboard and for each the possible moves it can make. * Standard I/O methods apply, you can output as a string, list of lines, matrix of characters, etc. * The characters used must be exactly as shown, you cannot substitute them for others. * Trailing whitespace is permitted on each line, and trailing newlines are permitted, but otherwise the output and spacing must be exactly as shown. * This is code golf, the shortest code in bytes wins. [Answer] # [J](http://jsoftware.com/), 29 27 24 23 bytes ``` ' .*xR'{~*/~,0,.~1+=i.8 ``` [Try it online!](https://tio.run/##VYwxC8IwFAb3/oqXDD6bPL80BMQEuyg4iUN2J2lRF1ehkL8eo5vDTXfcs0aV/HWrUmTuNHimMRGT0ECpsQEd8/lUmWDemZdiXJFBULwdH9jVvrscQAyTqcm1IKwEvdPBOu1d@TZ/RdjDtkOkuEAh/Px0u79orh8 "J โ€šร„รฌ Try It Online") My initial observation was that the output is essentially a row-wise function table of the 8x8 identity matrix with itself, where each evaluation is simply an ordinary addition table: `row_i +/ row_j`. This can be simplified further by flattening the identity matrix first, as follows: * `1+=i.8` 8 by 8 identity table, plus 1: ``` 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 ``` * `0,.~` Add a column of zeros ``` 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 ``` * `,` Flatten: ``` 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 ``` * `*/~` Multiplication table with self: ``` 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0 4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2 0 2 2 2 4 2 2 2 2 0 2 2 2 2 4 2 2 2 0 2 2 2 2 2 4 2 2 0 2 2 2 2 2 2 4 2 0 2 2 2 2 2 2 2 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * `' .*xR'{~` Convert to ascii. This returns the required pattern. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~67~~ 66 bytes *-1 byte thanks to @G B* A function that returns a list of lists. ``` ->{(a=0..70).map{|x|a.map{'.*R '[x%9|_1%9<8?1[x%10]+1[_1%10]:3]}}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3nXTtqjUSbQ309MwNNPVyEwuqaypqEsEMdT2tIAX16ApVy5p4Q1VLGwt7QyDH0CBW2zAaKABkWBnH1tbWQkzanhYdC9amUFBaUqwQb6igpaCurgCVXbAAQgMA) ### [Ruby](https://www.ruby-lang.org/), 69 bytes Alternatively, outputting the string to STDOUT takes two extra bytes. ``` 71.times{|x|71.times{$><<'.*R '[x%9|_1%9<8?1[x%10]+1[_1%10]:3]};puts} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN13NDfVKMnNTi6trKmrgbBU7Gxt1Pa0gBfXoClXLmnhDVUsbC3tDIMfQIFbbMBooAGRYGcfWWheUlhTXQgyDmgkzGwA) [Answer] # [Python](https://www.python.org), 77 bytes (@xnor) ``` f=lambda*_:[[" ",I[i%10<1]][i%9<8]for i in range(71)] I=f(I:='.*'),f(I:='*R') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fdNscxJzk1ISteKtoqOVFJR0PKMzVQ0NbAxjY4EMSxuL2LT8IoVMhcw8haLEvPRUDXNDzVguT9s0DU8rW3U9LXVNHQhTK0hdE2qoYkFRZl6JhlZuYoGGkpJeVn5mHlCRpqZOcWqBrXpMHkwhzBUA) ### Previous [Python](https://www.python.org), 79 bytes ``` J=[] f=lambda I=J:[" "[~i%9:]or I[i%10<1]for i in range(71)] J+=f('.*'),f('*R') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3_b1so2O50mxzEnOTUhIVPG29rKKVFJSi6zJVLa1i84sUPKMzVQ0NbAxj04CcTIXMPIWixLz0VA1zQ81YLi9t2zQNdT0tdU0dIK0VpK4JNVaxoCgzr0RDKzexQENJSS8rPzMPqEJTU6c4tcBWPSYPphDmDgA) ### Previous [Python](https://www.python.org), 80 bytes ``` J=[] f=lambda I=J:sum(zip(*8*[iter(8*(I+7*I[1:]))],8*' '),()) J+=f('R*'),f('*.') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3A7xso2O50mxzEnOTUhIVPG29rIpLczWqMgs0tCy0ojNLUos0LLQ0PLXNtTyjDa1iNTVjdSy01BXUNXU0NDW5vLRt0zTUg7SAXCCtpaeuCTVXsaAoM69EQys3sUBDSUkvKz8zD6hCU1OnOLXAVj0mD6YQ5hAA) This uses the good old grouper to create lots of 8 and to mix in the separators. [Answer] # [Python](https://www.python.org), ~~86~~ ~~83~~ ~~82~~ 81 bytes ``` lambda r=range(71):[[" .*R"[i%9|j%9<8and(i%10<1)-~(j%10<1)]for i in r]for j in r] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwdI0BVuFmKWlJWm6FjcDcxJzk1ISFYpsixLz0lM1zA01raKjlRT0tIKUojNVLWuyVC1tLBLzUjQyVQ0NbAw1des0siCs2LT8IoVMhcw8hSIwMwvChBqsXFCUmVeioZWbWKChpKSXlZ-Zp6OQpqGpqaNQnFpgqx6Tp64JUbpgAYQGAA) -1 byte thanks to [@loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~34 32 30 24~~ 20 bytes ``` ".*R"a+\:a:,/|+|3,=8 ``` [Try it online!](https://ngn.codeberg.page/k#eJxT0tMKUkrUjrFKtNLRr9GuMdaxtQAAMmAE/g==) idea from [jonah's solution](https://codegolf.stackexchange.com/a/251105/24908) `=8` identity matrix `3,` prepend a 3 `|` reverse `+` transpose (this will extend the 3 to eight copies) `|` reverse again `,/` raze `a:` assign to `a` `a+\:` add-each-right, i.e. make a matrix in which element i,j is `a[i]+a[j]` `".*R"` index into this string. out-of-bounds indices generate `" "`-s in the result. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~26~~ ~~25~~ ~~24~~ ~~21~~ 20 bytes ``` '.*xR '8XyQO9Y(le&*) ``` [Try it online!](https://tio.run/##y00syfn/X11PqyJIQd0iojLQ3zJSIydVTUvz/38A "MATL โ€šร„รฌ Try It Online") -3 bytes thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) ### Explanation Port of [@Jonah answer](https://codegolf.stackexchange.com/a/251105/91267) to MATL ``` '.*xR '8XyQO9Y(le&*) 8Xy % 8 x 8 identity matrix Q % add one O9Y( % add a row of zeros to the end le % flatten &* % multiply with itself '.*xR ' ) % convert numbers to required codepoints ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 125 bytes ``` s/^/Rssssssss/ s/.*/&&&&&&&&/ s/.{8}$// s/.{8}/& /g y/s/*/ h y/R*/*./ H;H;H;H;H;H;H;H g;H;H;H;G;G s/.{584}/&\n/g s/.{1244}$// ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3a4v14_SDiqFAn6tYX09LXw0KwNxqi1oVfRhLX01BP52rUr9YX0ufKwPICNLS19LT5_KwRoFc6VCWu7U7WKephQlQb0weUDOIa2hkYgIyFeIIqFsWLOSCMAA) [Answer] # [C (GCC)](https://gcc.gnu.org), 102 bytes ``` main(i,k){for(i=9;++i<82;puts(""))for(k=9;++k<82;)putchar(k%9&&i%9?i%10|k%10?i%10&&k%10?46:42:82:32);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjfTchMz8zQydbI1q9PyizQybS2ttbUzbSyMrAtKS4o1lJQ0NUHi2WDxbJC4JlAiOSMRKKZqqaaWqWppn6lqaFCTDSTALDU1MNPEzMrEyMrCyMrYSNO6FmIb1FKY5QA) # [C (GCC)](https://gcc.gnu.org), ~~111~~ ~~109~~ 107 bytes ``` #define F(X,c)for(X=0;++X<9;putchar(c)) main(i,j,k,l){F(i,10)F(j,10)F(k,32)F(l,i-j|k-l?i-j&&k-l?46:42:82);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjezlVNS0zLzUhXcNCJ0kjXT8os0ImwNrLW1I2wsrQtKS5IzEos0kjU1uXITM_M0MnWydLJ1cjSr3YBMQwNNN40sCJWtY2wEpHJ0MnWzarJ1c-yBtJoaiGFiZmViZGVhpGldC7ESajPMBQA) [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 80 bytes ``` ;=i~1W>8=i+1i;=j~1;W>8=j+1j;=x~1;W>8=x+1xO+I?j iS*'*'8xT'R'S*'.'8xT'*'' \'O''O'' ``` [Try It Online!](https://tio.run/##lVj7U9vGFv69f4XQTbHWEsLOdHobC8EklHSYNiY30GZubSderda2iCw5eoBTW/nX23NWr5VfpAzDSNpvz2u/81ju6QONWeQtkpMgdPnfzKdxrPwaeNNZchVFYaTwZcIDN1bE2yrLAW9pFPPmurSnRL1Lg8SbP427TSJO5ysWBnESpSwJI42SVTLzYjMO04hxm2aw4i3ez7yExwvKuFasz2nCZtrpB20wHA0Hwxi@Z72Rvv7P4MMwGLW1YbB@Rkj7lGQLzj/BasSTNAoUSfigM1qvg9T3s1yYYzC7Q1Y@TxRqOyZfcqZJcGIVInCLbdv0Ah96MsSWns04dcB2jYIa0@fBNJkRgw7YiGRJCI57wXSnVVkmwqHc/f/t1a09GFl5qP6gfspXcUITjykLPAXNISvH3AqPNYEoPtAIfOhY9EyIKfRbVNdz/5gtvg/oyCxlWd5EY6Swh2WSr1mUBiLsUfioBPwxZ0Tmcied7vi@xzshxKwXAddP5w6P9uDKRcC9CkOf02APsFrNClb9BsGIqF8RLw/dBsnidIHSDSHqo0sTClzLHZWU7HCmeK/37fKkeG@CttwoP8gw/tlH8woEVTywmgaMh5Pca8mN42PJeOBj/lRGAYVXIShCssWfkut1Nt29HpHBy5M/R@1To1tRnh4f4wGjTE29U1Ebydx0vqicGZfOPBP5mZFx5iez2pWj2tbjY9o4tqmMU2TcUROY5WRepPFMw6/EylPlqv/H9bub/pur/p29yoqEuXZ5kGxw4Cn3B/Tkr48j/Ns5efERQrAZACEUjM0OsclDELCpGR@x1Zt4gMtDlOMwUGCuNw1QjuTJoMaMKmrmBu9BYQY/hJ6rdI7wfErLrTpB5bqsjX8PPgXhY6B4lWVKq2Faa9yMuXCBlPGVovut9Bq6@nZIIaBFulCySapioeYUdV2JK@X@mjM6lUoHyaAGH4SfNOHz1D8Ibzfhrvcge1kv4Uk0DqEU9YYmMxN4EzBJ6in4ve@Q1EsaBGGigCo4E8X5ovzFo1AFU0P3X@quFX5Pn9QH4lM/lPQtwsfD@mrx6/WRRs865Jucb7e/wXu@XIQBkpQmXBikJCHUxoBPgW8PXAHjeARG@nsqyZl8bnvrzXkD1SB@Tfs@NMTDvJeqd0X8flFSSc55FNIoIWUFwXa7kQMqgjWiHuoMQl7h/BOhZOEczORii6lWwfiXu@Tg4LcyOtAcnwwOUsixqdRz1NaIwBwXD29H7Qsy7J4azwWtMBrALEcmEmjAYSUfYqiZD3cIVlvYlth63VJb@EBql@qhFYseWDX3AmCSq3xOQyAUD1iY4mfu9pRnK5qNd7V0YX8zj4xuh6zXnY2aVQwIh2oWOjEuAIXC7dKDoFqXGfEFp9B75Ar0BOOrUesg4yuUfKjwseiusIu6t18C1qOZHfHPqRdxTZ3EKjFWOCKLJUdaYjPPdz8uopDxGFGvf@9f3l3f9G/r3vwaasCh1iyxJD9gmMwrMQNH6nTipKVZ1ZJ4ddETWaevTXKaM4bjPI3zMb64MB@7Z6ycjd1yNp7YwiKzNAWVHU320OmNB707mCo0mqZzHDierVy9mymgRJmgl9BRHWykFs8DOyGZdMYYCI0ZjsE3Rgr4xDbGChRn0/w5oHNuO/kzqI5ttj27ig2aaZoVqqoseRVXUXvihYGm6pXUKjyOUo6cYivVbdVQVN0xcxlVF9fVrdp049xzlpheLPhrwLiUTQpVSsSnXpxw4SJZQWi72KvKC9LGXUJT@2CSMk9hyHMgUZeUJf4XBXqBwmY0gjeYWfwwmEJNsmqC0JHtSBohMFXnko@2SDK4gWqOlAdErj31GJXfN6ydNFD7ofKAkqFQpr6LtgoV7hHUSimrMODEqEKgvlUNjdjnxZVMVQ3HfpVOJjwyqe@HTIMB3A0xSFTrACM6MJEbQHkHrpTEAcM/WUwHVx8h47jWhS4sVsRNzsTceu9B4qvDQCWE2cyMfQ9uiB1DOakn@7LSMJLJlr3LLWu07okfgq8/PH/xw4sf//v8xY9t8TWigRvOMWzy/ivVoPY5how2QltDWi9bCKkSPQ9vYZUjdzcw4KI0M5dkTqJwfgkMuAxdGDSLuxPplebKx2myAvcywZlNNvKVMJLKny7zT8XlUvyVl8diuepDTef2OKr@T2wqCqLJl95mFZewR5UCcddqXoAayN8qJHosG1Imk4z@Gbl1Xo1vjWCXlsWJG6aJ@RhB4waBeZ4TgzZidtMUVGstpKnDobgeFmQDpl3skV@yESCktxMzxt743ZgY1cwkW6IDRbGI1MeFjbbwreH8yRYS7wW7kO0tJPblXcjTLaS4DexAfr8tM9xt54ctpJi6dyDPKmRFlXILTgTVFnnP@f490317LvbvwZK/c89xtUejZV43/k9zUWzrNTJv/eQ22nO2M9KStuWrxq6A2RKsUVvwSrteg0rpet9MZGoW93PHrvQ7DeHvK@Er7J5WI2ktspFuO8l8nYuApm@f053BYtu@/yJtEkGr7TacxiXNwPIvvZYVjJb/pUQh67WqNqN2WyhwhYpy0xOqXNvd1lyBy1aPY/0F1WGqLE2ADkd0ptcm6S724rphfG3JFa95dQccRKesIjCxPAyeQyf8G34s2/vafX/@k@3pXc@y7792LXy717v3lr0s3pZ6d3mjX1/cK95tu9Vu/bS8a71rwaMpHtutljJs3bTw9x8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 8โ€šร…ยบโˆšรฆj-โ€šร„รฒโˆšรณโˆšรฆ`ยทยชรฃโ€šร„รบ.* R โ€šร„รน ``` A niladic Link that yields a list of the lines of characters. The empty lines have trailing spaces. **[Try it online!](https://tio.run/##ASoA1f9qZWxsef//OOKBvMO@ai3igJjDl8O@YOG7i@KAnC4qIFIg4oCd/8KiWf8 "Jelly โ€šร„รฌ Try It Online")** (Footer joins with newlines) ### How? Implements [Jonah's brilliant method](https://codegolf.stackexchange.com/a/251105/53748). ``` 8โ€šร…ยบโˆšรฆj-โ€šร„รฒโˆšรณโˆšรฆ`ยทยชรฃโ€šร„รบ.* R โ€šร„รน - Link: no arguments 8 - 8 โˆšรฆ - ([1..8]) table ([1..8]) with: โ€šร…ยบ - is equal? - - -1 j - join โ€šร„รฒ - increment all values ` - use as both arguments of: โˆšรฆ - table with: โˆšรณ - multiply โ€šร„รบ.* R โ€šร„รน - ".* R " ยทยชรฃ - index into (1-indexed and modular, so 0 gives ' ') ``` [Answer] # [gbz80](https://rgbds.gbdev.io/docs/v0.5.2/gbz80.7) [machine code](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html), 73 72 70 bytes ``` 21 00 C0 06 00 0E 00 16 00 1E 00 36 00 78 B9 20 01 34 7A BB 20 01 34 AF BE 28 08 3C BE 28 08 3E 52 18 06 3E 2E 18 02 3E 2A 22 3E 08 1C BB 20 DB 36 20 23 14 BA 20 D2 36 0A 23 0C B9 20 C9 36 0A 23 04 B8 20 C0 76 ``` As an ASM rookie, I gladly accept. The string is returned in $C000-$D247 ($1248 long, nice). You may check it by copying that range using an emulator debugger (it finishes very quickly, you'll know it's done if the program counter is on or after the halt) into a text file and opening it with a text editor that supports LF. The emulator I used is BGB. This code can be placed anywhere in a ROM and jumped to from the entrypoint, or called as a routine if the $76 (halt) at the end is replaced with a $C9 (ret). Source, which may be assembled with [RGBDS](https://rgbds.gbdev.io): ``` section "Header", ROM0[$100] jr GenerateMetaTable ; the generated binary could be placed anywhere because of the lack of calls and jps ds $150 - @, 0 ; Make room for the header GenerateMetaTable: ld hl, LotsaSpace ld b, 0 ; meta-line tracker. each of these hardcoded zeroes is necessary because all of these registers change .outermost: ld c, 0 ; sub-line tracker .mediumOuter: ld d, 0 ; meta-row tracker .mediumInner: ld e, 0 ; sub-row tracker .innermost: ld [hl], 0 ; we're out of registers (besides a which is used for comparing), but we have this convenient value we're pointing to that will get overwritten anyway. ld a, b cp a, c ; meta-line == sub-line -> rook move or rook position jr nz, .skipFirstInc inc [hl] .skipFirstInc: ld a, d cp a, e ; meta-row == sub-row -> rook move or rook position jr nz, .skipSecondInc inc [hl] .skipSecondInc: xor a, a cp a, [hl] jr z, .period ; [hl] == 0 -> neither rook position nor rook move inc a cp a, [hl] jr z, .star ; [hl] == 1 -> rook move ld a, "R" ; [hl] == 2 -> rook position jr .write .period: ld a, "." jr .write .star: ld a, "*" .write: ld [hl+], a .innermostEnd: ld a, 8 inc e cp a, e jr nz, .innermost ld [hl], " " inc hl .mediumInnerEnd: inc d cp a, d jr nz, .mediumInner ld [hl], "\n" inc hl .mediumOuterEnd: inc c cp a, c jr nz, .mediumOuter ld [hl], "\n" inc hl .outermostEnd: inc b cp a, b jr nz, .outermost HangMachine: db $76 ; directly encoded halt, saves one byte over "halt", which automatically adds a nop ; this is here to prevent the program from repeating endlessly. that may not seem problematic, but if a tester stops it while [hl] is being used to hold the match count, they'll copy a bad output. ; to make GenerateMetaTable a function, just replace this with "ret" section "Memory", WRAM0 LotsaSpace: ; we need $1248 of space, but we can't just ds it because WRAM0 is $1000 long. no formalism for you. we don't bank-switch ever, so it's not a problem. ``` Edit 1: "ld a, 0" -> "xor a, a", -1 byte Edit 2: rearranging character loading jumps allowed removal of one, -2 bytes [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 64 bytes ``` R7*$(9*$*R)7*$(ยฌโˆ‚9*$($*7*$(9*.$*)ยฌโˆ‚)R7*$(9*$*R %8,9,`. 8,9,`.+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/nyvIXEtFw1JLRStIE8Q6tA3I1lDRgojqqWhpHtqmiVDDpWqhY6mToMelwAVhaHP9/w8A "Retina โ€šร„รฌ Try It Online") Explanation: ``` R7*$(9*$*R)7*$(ยฌโˆ‚9*$($*7*$(9*.$*)ยฌโˆ‚)R7*$(9*$*R ``` Replace the empty input with the pattern of `R`s, `*`s and `.`s. Note that `*` is Retina 1's string repetition operator so actual `*`s have to be quoted as `$*`. ``` %8,9,`. ``` Clear out every ninth column. ``` 8,9,`.+ ``` Clear out every ninth row. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ร”ยบโ€ขโ€šร…โˆ‘ยฌฯ€โ€šโ‰ รœโ€šร…โˆ‘ยฌฯ€ยฌรŸ .*Rโ€šร รŸร”ฯ€โ„ขโ€šรครฏล’ฯ€โ€šร…ฯ€โ€šร รŸร”ฯ€โ„ขโ€šรครฏล’ยชโ€šร…ฯ€โ€šรครฏโ€šร…โˆซยฌยจร”ฯ€โ„ขล’ฯ€ล“รกยฌยจร”ฯ€โ„ขล’ยชล“รก ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDD3FBHIbgEyE2H8RxLPPNSUis0lBT0tIKUgPy8FA3f/JTSnHwNz7zkotTc1LyS1BSNTE0dBUtNnNI5UGlksYCc0mINv/wSmPpMHQVDA02gIiSxHIgYDFj///9ftywHAA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` โ€šร…โˆ‘ยฌฯ€ Literal integer `71` ร”ยบโ€ข Map over implicit range โ€šร…โˆ‘ยฌฯ€ Literal integer `71` โ€šโ‰ รœ Map over implicit range and join .*R Literal string ` .*R` ยฌรŸ Indexed by ล’ฯ€ Current row โ€šรครฏ Incremented ร”ฯ€โ„ข Modulo โ€šร…ฯ€ Literal integer `9` โ€šร รŸ Logical And ล’ยช Current column โ€šรครฏ Incremented ร”ฯ€โ„ข Modulo โ€šร…ฯ€ Literal integer `9` โ€šร รŸ Logical And ล’ฯ€ Current row ร”ฯ€โ„ข Modulo ล“รก Predefined variable `10` ยฌยจ Logical Not โ€šร…โˆซ Plus ล’ยช Current column ร”ฯ€โ„ข Modulo ล“รก Predefined variable `10` ยฌยจ Logical Not โ€šรครฏ Incremented Implicitly print ``` Actually using ASCII art drawing commands seems to take 51 bytes: [Try it online!](https://tio.run/##jY7BDoIwEETP8BWbPbWmGnoi6o1w0RNRfoCUqg3QmgJqYvj2igjBxIunzUxm3qy4ZFaYrHTuKJsoE8XZmlbnBFdIt/7JWCAhhek@fW/fVtfUkFRVsiaKAQ8og48qBtXXvMg8COcMkrKtCR5wSqwZ4ALpO9P5v9CAQSyFlZXUjczHjZ2eHdVvrYe6l1ilmzGC0C@EfPBH1F8cBsGM2sTmrqdHv4idc255K18 "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 69 bytes ``` f()=matrix(71,,i,j,Vec(".*R ")[if(i%9&&j%9,(i%10==1)+(j%10==1)+1,4)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN13TNDRtcxNLijIrNMwNdXQydbJ0wlKTNZT0tIIUlDSjM9M0MlUt1dSyVC11gCxDA1tbQ01tjSwYy1DHRDNWE2LYvuiCosy8Eo3ikqKs_Mw8jSJNTYUahSIFG10FoC2xEEUwmwE) [Answer] # Rust, 171 bytes ``` ||(0..71).any(|x|(0..72).map(|y|(x/9,y/9,x%9,y%9,y/71+1)).any(|(x,y,a,b,l)|print!("{: <1$}",if a>7||b>7{' '}else if x==a&&y==b{'R'}else if x==a||y==b{'*'}else{'.'},l)>())) ``` [Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a188ba240a058efcb579ddd6aab4447c) [Answer] # [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 131 bytes ``` _=>{T[]F<T>(T x,T y,T z)=>new T[72].Select((_,i)=>i%10<1?x:i%9<8?y:z).ToArray();return F(F("R","*"," "),F("*","."," "),new[]{""});} ``` [Try it online!](https://tio.run/##7ZhPa4MwGIfvfoqXQCERl667bKt/ujHmYYwdnLCDSBGbjkAbR7SttfSzu2js2HnboYMEgk@i78@gz@nNy4u85G24EblXVpKLdwf0NUmTNFj67dwPDnGShl4c4BhqJ4a9mg3xA8F2ECfXVyl9ZSuWVxjPHa72@Why6U1m9ZSPbr2b2X7aEBoX91Jme0xcyaqNFBDiEKMIOchWExBx1LJDOixVeJIeEDoS99i6lj4TsPpDvYgtwLfuUGTrAXZ0goEUaOqgpx460qBoADuybKoHUPsEAynQ1EFPPXSkQdEA1DY5/yznz4KMiEagsziQEdEIZEQ0ApkPZEQ0AhkRjUAm59xFND/MiPgrEZFrWdtMQgM@LDFC5NSOqsEPhmYWfShEnqktQmPJ15gQVTQeq92yWDH6JnnFnrlgeHj8qeACP4otl4VYM1HRF7br7jvQdKU/qgPf/@pffcuIWLboI4jbfgI "C# (Visual C# Interactive Compiler) โ€šร„รฌ Try It Online") --- Makes use of an inline generic function: ``` _ => { /* both the characters within each row and the rows in the whole string follow the same pattern a default string, a different string at every 10th string, and a space string at every 9th string, starting at 8 e.g. R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R the default string is "*", the special character is "R" and the space is " " for the whole result string, the default string is "*....... .*...... [...]" the special string is "R******* *R****** [...]" and the space is either "" or " " (both work) */ // generic function (defines T as the generic type), inputs of type T T[] F<T> (T specialChar, T defaultChar, T space) => // create a new T[] of length 72, and set each element according to its index new T[72] .Select((_, i) => // special char every 10th element i % 10 < 1 ? specialChar : // space every 9 starting at 8, otherwise default i % 9 < 8 ? defaultChar : space ).ToArray(); // construct rook (special) row string var a = F("R", "*", " "); // construct default row string var b = F("*", ".", " "); // correctly typed space for next func call var c = new string[] { "" }; // construct whole string using default, special and space strings return F(a, b, c); }; ``` [Answer] # [Haskell](https://www.haskell.org), ~~99~~ ~~90~~ 89 bytes ``` [[" R*."!!((f(i%10)+f(k%10)+1)*f(k%9*i%9))|k<-r]|i<-r] (%)=mod f=fromEnum.(>0) r=[10..81] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8HOal1lBR9HP_dQR3dXBeeAAAVl3VquRAXbmKWlJWm6Fjcjo6OVFIK09JQUFTU00jQyVQ0NNLXTNLLBtKGmFohpqZWpaqmpWZNto1sUW5MJIrk0VDVtc_NTuNJs04ryc13zSnP1NOwMNLmKbKMNDfT0LAxjIRbszE3MzFOwVSgoLQkuKVJQUSjNy8nMSy1WSITIL1gAoQE) [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` q["",q" .*",q" *R"] q l=[l!!(0^m 10-0^m 9+1)|m<-mod<$>[10..80]] ``` [Try it online!](https://tio.run/##y0gszk7NyflflFpsG/O/MFpJSadQSUFPC0xpBSnFchUq5NhG5ygqahjE5SoYGuiCKEttQ82aXBvd3PwUGxW7aEMDPT0Lg9jY/7mJmXkKtgq5iQW@CgWlJcElRT55CkCj//9LTstJTC/@r5tcUAAA "Haskell โ€šร„รฌ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~140~~ 102 bytes ``` #define a(z,y)for(int z=8;z--;putchar(y+10)) main(){a(i,)a(j,)a(k,22)a(l,i-j|l-k?i==j|l==k?42:46:72);} ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIVGjSqdSMy2/SCMzr0ShytbCukpX17qgtCQ5I7FIo1Lb0EBTkys3MTNPQ7M6USNTRzNRIwtEZOsYGQGpHJ1M3ayaHN1s@0xbWyDD1jbb3sTIysTMytxI07r2/38A "C (gcc) โ€šร„รฌ Try It Online") ``` #define a(z,y) for (int z=8; z--; putchar(y+10)) main() { a(i,) // 10 = space a(j,) a(k, 22) // 22+10 = 32, space a(l, (i - j) | (l - k) ? // subtract is quicker than != here i == j | l == k ? 42 : // if the x matches xor the y matches, print asterisk 46 : // if neither match, print dot 72); // if both match, print R, only the last number has 10 added in the macro, so 82 } ``` [Answer] # [Uiua](https://uiua.org), 24 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` โ€šรครจโ€šรครปโˆšรณ.โ€šรกรฅโ€šรดโ‰ โ€šรขยฐ'โ€šรคร‡0+1โ€šรครป=.โ€šรกยฐ8" .*xR" ``` [Try it!](https://uiua.org/pad?src=ZiDihpAg4oqP4oqew5cu4oeM4pmt4omhJ-KKgjArMeKKnj0u4oehOCIgLip4UiIKCuKJoSZwIGY=) Port of @Jonah's [J answer](https://codegolf.stackexchange.com/a/251105/97916). Tip: when looking at the output on the Uiua pad, set the font size to the smallest by clicking the gear in the upper right so you can see the output without line wrapping. ``` โ€šรครจโ€šรครปโˆšรณ.โ€šรกรฅโ€šรดโ‰ โ€šรขยฐ'โ€šรคร‡0+1โ€šรครป=.โ€šรกยฐ8" .*xR" " .*xR" # place ascii replacements on the stack โ€šรครป=.โ€šรกยฐ8 # 8x8 identity matrix +1 # increment โ€šรขยฐ'โ€šรคร‡0 # add column of zeros โ€šรดโ‰  # deshape โ€šรกรฅ # reverse โ€šรครปโˆšรณ. # outer product โ€šรครจ # select ``` [Answer] # [Factor](https://factorcode.org/) + `math.matrices`, 97 bytes ``` [ 8 identity-matrix 1 m+n [ 0 suffix ] map concat dup outer [ "\0"" .*R"zip substitute ] map ] ``` [Try it online!](https://tio.run/##LYy/CsIwGMRRnHyKI6NiqZvoA4iLg@JUO8T0Kw1Nk5o/oL58/Coux3F3v2ulis7n2/V0Pu4xyNgVLF4rCgj0TGQn15O3ZCBDcCpAOxxyhR10Qzbq@N78kBe2GNYWFUqE1LYc1Pw4QjmrZFw2aYRLkTwvxL2czRdCoFhdxEePDDwCX3H9h@qspDHTVMDonjB6bSOXJFWXvw "Factor โ€šร„รฌ Try It Online") A straight translation of @Jonah's excellent [J answer](https://codegolf.stackexchange.com/a/251105/97916). * `8 identity-matrix` Make an 8x8 identity matrix. * `1 m+n` Add 1 to each element of the matrix. * `[ 0 suffix ] map` Add a column of 0s to the far right end of the matrix. * `concat` Flatten the matrix into a list. * `dup outer` Take the outer product with itself. * `[ "\0"" .*R"zip substitute ] map` Convert the resulting matrix to the required code points. [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 42 bytes ``` iRยฌโˆ‘* 7o*ยฌโˆ‘. {7โˆšยฑโˆšยง}$FR7jdpbโˆšยฑGโˆšร˜{7โˆšยฑโˆšยงGGkdd{p ``` [Try it online!](https://tio.run/##K/v/PzPo0HYtBWnzfK1D2/UUpKvND288vESsVsUtSMw8K6Ug6fBG98PrIaLu7tkpKdUF//8DAA "V (vim) โ€šร„รฌ Try It Online") Hexdump: ``` 00000000: 6952 b72a 201b 376f 2ab7 2e20 1b7b 37f1 iR.* .7o*.. .{7. 00000010: e416 7d24 4652 1637 6a64 7062 f147 ef7b ..}$FR.7jdpb.G.{ 00000020: 37f1 e447 476b 6464 7b70 7..GGkdd{p ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/) (REPL), 24 bytes ``` " .*xR"โ€šรครจร€รบโˆšรณโ€šรฅรบร€รบโ€šโ€ขรคโ€šร รฆโ€šรผรบ0ร€รฒ1+=โ€šรฅรบร€รบโ€šรœรฏ8 ``` Outputs a 2D array of characters. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=IiAuKnhSIuKKj8ucw5fijJzLnOKliuKIvuKfnDDLmDErPeKMnMuc4oaVOA==) ### Explanation Ports [Jonah's J solution](https://codegolf.stackexchange.com/a/251105/16766), which you should upvote. ``` " .*xR"โ€šรครจร€รบโˆšรณโ€šรฅรบร€รบโ€šโ€ขรคโ€šร รฆโ€šรผรบ0ร€รฒ1+=โ€šรฅรบร€รบโ€šรœรฏ8 โ€šรœรฏ8 Range(8) =โ€šรฅรบร€รบ Equality table with self (8x8 identity matrix) 1+ Add 1 to each (main diagonal is 2s, rest is 1s) โ€šร รฆโ€šรผรบ0ร€รฒ Append 0 to each row โ€šโ€ขรค Deshape into a flat list โˆšรณโ€šรฅรบร€รบ Multiplication table with self โ€šรครจร€รบ Use each element of that 2D array to index into " .*xR" this string ``` --- Just for fun, here's a different solution (27 bytes) that outputs a 2D array of 2D arrays of characters (feels appropriate, but goes against the challenge's I/O requirements and also is longer): ``` {".*R"โ€šรครจร€รบr(+ยฌยฅ๏ฃฟรนรฏยฎโ€šร„รธ๏ฃฟรนรฏยฉ=โ€šรฃร )โ€šรฅรบr}โ€šรฅรบร€รบrโ€šรœรชโ€šรœรฏ8 ``` [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=eyIuKlIi4oqPy5xyKCvCtPCdlajigL/wnZWpPeKLiCnijJxyfeKMnMuccuKGkOKGlTg=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` 8โˆšรปโ€šรฑยฐโ€šร„โˆซ0j:v*` โ€šร‡ยจxR`ฦ’โˆž ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI4w57ilqHigLowajp2KmAg4oKseFJgxLAiLCLhuaDigYsiLCIiXQ==) Another port of Jonah's answer. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 36 bytes ``` VJU71sm@>".*R "+!%NT!%dT_<7.|%d9%N9J ``` [Try it online!](https://tio.run/##K6gsyfj/P8wr1NywONfBTklPK0hBSVtR1S9EUTUlJN7GXK9GNcVS1c/S6///f/kFJZn5ecX/dVMA "Pyth โ€šร„รฌ Try It Online") [Answer] # [JShell](https://docs.oracle.com/javase/9/jshell/introduction-jshell.htm#JSHEL-GUID-630F27C8-1195-4989-9F6B-2C51D46F52C8) (Java), ~~191~~ 188 bytes ``` void f(String x){System.out.print(x);}int i,j,x,y;for(j=0;j<8;j++){for(y=0;y<8;y++){for(i=0;i<8;i++){for(x=0;x<8;x++){int X=i^x,Y=j^y;f(X*Y<1?X+Y<1?"R":"x":".");}f(" ");}f("\n");}f("\n");} ``` Or, expanded: ``` void f(String x) { System.out.print(x); } int i, j, x, y; for (j = 0; j < 8; j++) { for (y = 0; y < 8; y++) { for (i = 0; i < 8; i++) { for (x = 0; x < 8; x++) { int X = i ^ x; int Y = j ^ y; f(X * Y < 1 ? X + Y < 1 ? "R" : "x" : "."); } f(" "); } f("\n"); } f("\n"); } ``` [Answer] # Dart, 173 bytes ``` main(){var l=[0,1,2,3,4,5,6,7],s="R"+"*"*7+"*......."*7,p=" "*7+"\n",i,j,k,m;print([for(i in l)...[for(j in l)for(k in l)...[for(m in l)s[(k^m)*8+i^j],p[k]],"\n"]].join());} // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 //345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123 ``` Pretty-printed: ``` main() { var l = [0, 1, 2, 3, 4, 5, 6, 7], s = "R" + "*" * 7 + "*......." * 7, p = " " * 7 + "\n", i, j, k, m; print([ for (i in l) ...[ for (j in l) for (k in l) ...[for (m in l) s[(k ^ m) * 8 + i ^ j], p[k]], "\n" ] ].join()); } ``` [Answer] # [Perl 5](https://www.perl.org/), 100 bytes ``` print$_%72?$_/72%9?$_%9?($v=1==$_%72%10)&($h=1==$_/72%9-$_/648)?R:$v|$h?'*':'.':$":'':$/for 73..5184 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCVe1dzIXiVe39xI1RJIAwkNlTJbQ1tbsIyqoYGmmoZKBkQArEgXSJuZWGjaB1mplNWoZNira6lbqeupW6koWakDSf20/CIFc2M9PVNDC5P////lF5Rk5ucV/9f1BVqXmp5aBAA "Perl 5 โ€šร„รฌ Try It Online") [Answer] # [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), 151 145 137 bytes ``` for(int y=0,x,a,b;++y<72;){var s="";for(x=1;x<72;s+=x++%9*(y%9)<1?' ':a+b<1?'R':a*b<1?'*':'.'){a=~-x%10;b=~-y%10;}System.out.println(s);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc5NroIwFAXguau4MSGlFIm8iT-lcQVOnkPj4OJfahAMLaQN4c1dgxMSdVHuxvJ0dL6cewfn9jhhjd0ruVRpJrewzVApWKLMoRl8O6VRu6gLuYOzu_grXcr8uN4AlkdFoXlW-jCavq6HovRlrsGKcWhCDFPOmE0mP5w2NZagxHDI-x8jYm76XjFhGPNmgW-9GU3iBQEyR5b2-nUK_hWQOYkIbVD8jYwXj3nqYHu0K6v0_hwVlY4ubpPOcl9R3n4G3dvBV133yTc) Link is to a "normal" Java version, as I don't know if the link to the online JShell will stay valid. [Jeffrey's answer](https://codegolf.stackexchange.com/a/251116/92572) made me aware of JShell, which saves a couple of bytes compared to a lambda function or an interface. **EDIT** It also reminded me that ternary `if`s don't always need parentheses. Thanks! -8 bytes thanks to @ceilingcat! [Answer] # [Uiua](https://uiua.org), 21 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` โ€šยจรถ@ โ€šรครจโ€šรครป+.โ€šรดโ‰ โ€šรคโ€ โ€šรคร‡โ€šรครป=.โ€šรกยฐ.8".*R" ``` [Try it online!](https://www.uiua.org/pad?src=YSDihpAg4oqP4oi2IiAuKnhSIuKKnsOXLuKHjOKZreKJoSfiioIwKzHiip49LuKHoTgKYiDihpAg4qyaQCDiio_iip4rLuKZreKKoOKKguKKnj0u4oehLjgiLipSIiAjIDIxCuKJhSBhIGI=) A port of ngn's [K answer](https://codegolf.stackexchange.com/a/251115/78410), which is also based on Jonah's J but adds a deliberate out-of-bounds indexing trick. With size 4 instead of 8, the following vector is generated: ``` [1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4] ``` and its self outer product by addition gives ``` โ€šรฏโ‰ โ€šรฎร„ โ€šรฏโˆ‘ 2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4 2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5 5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8 โ€šรฏร˜ ``` In this matrix, 0, 1, 2 correspond to `.*R` respectively, and anything larger is a space, so "index into `".*R"` with any out-of-bounds indexes mapped to spaces" gives the correct matrix of characters. Any number >= 3 works for the padding; reusing 8 saves a byte over hardcoding any other number (which requires a space between the two numbers). ``` โ€šยจรถ@ โ€šรครจโ€šรครป+.โ€šรดโ‰ โ€šรคโ€ โ€šรคร‡โ€šรครป=.โ€šรกยฐ.8".*R" โ€šรครป=.โ€šรกยฐ 8 identity matrix of size 8 โ€šรดโ‰ โ€šรคโ€ โ€šรคร‡ . append 8 to each row and flatten โ€šรครป+. self outer product by addition โ€šรครจ ".*R" select; convert 0, 1, 2 into ".*R"... โ€šยจรถ@ and all others to spaces ``` ]
[Question] [ Surprisingly, I don't think we have a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question for determining if a number is [semiprime](https://en.wikipedia.org/wiki/Semiprime). > > A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. > > > Simple enough, but a remarkably important concept. Given a positive integer, determine if it is a semiprime. Your output can be in any form so long as it gives the same output for any truthy or falsey value. You may also assume your input is reasonably small enough that performance or overflow aren't an issue. Test cases: ``` input -> output 1 -> false 2 -> false 3 -> false 4 -> true 6 -> true 8 -> false 30 -> false (5 * 3 * 2), note it must be EXACTLY 2 (non-distinct) primes 49 -> true (7 * 7) still technically 2 primes 95 -> true 25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784406918290641249515082189298559149176184502808489120072844992687392807287776735971418347270261896375014971824691165077613379859095700097330459748808428401797429100642458691817195118746121515172654632282216869987549182422433637259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133844143603833904414952634432190114657544454178424020924616515723350778707749817125772467962926386356373289912154831438167899885040445364023527381951378636564391212010397122822120720357 -> true, and go call someone, you just cracked RSA-2048 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 [bytes](https://github.com/JCumin/Brachylog/wiki/Code-page) Basically a port from [Fatalize's answer](https://codegolf.stackexchange.com/a/135298/53748) to the Sphenic number challenge. ``` ยทโˆรฃฦ’รค ``` **[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7iNd//@bWP4HAA "Brachylog โ€šร„รฌ Try It Online")** ### How? ``` ยทโˆรฃฦ’รค - implicitly takes input ยทโˆรฃ - prime factorisation (with duplicates included) ฦ’รค - is a couple ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 [bytes](https://github.com/barbuz/Husk/wiki/Codepage) Look ma no Unicode! ``` =2Lp ``` **[Try it online!](https://tio.run/##yygtzv7/39bIp@D///8mlgA "Husk โ€šร„รฌ Try It Online")** ### How? ``` =2Lp - a one input function p - prime factorisation (with duplicates included) L - length =2 - equals 2? ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 4 bytes ``` q2lP ``` **[Test suite](http://pyth.herokuapp.com/?code=q2lP&input=36&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A6%0A30%0A49%0A95&debug=0).** --- # How? ``` q2lPQ - Q is implicit input. q2 - Is equal to 2? lPQ - The length of the prime factors of the input. ``` [Answer] # Mathematica, 16 bytes ``` PrimeOmega@#==2& ``` `PrimeOmega` counts the number of prime factors, counting multiplicity. [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda n:0<sum((n%x<1)+(x**3==n)for x in range(2,n))<3 ``` [Try it online!](https://tio.run/##FctBCsIwEAXQq8xGmNS/aJJWbElOoi4iGi3YaYkV4ulj3D5463d7LmJL9OfyCvP1FkjG1r0/M7PsstNqz7lprPei4pIo0ySUgjzubCBKuVory59PGgYWHQ44wrboBgw9tOkv45om2YgFkWsqPw "Python 3 โ€šร„รฌ Try It Online") The [previous verson](https://tio.run/##FcvRCoIwFAbgV9mNcCY/5Nm0UmYvUl0saiXkUZaBPv1atx9887a8JrEp9Jf09uPt7pV0UpbEO6sLPlXu8x1JitVxmKJa1SAqenk@yEC0dnlmlj@fGQYWNfY4wlaoW7QN2DTXbo6DLIoEgXJKhx8) had some rounding issues on large cube numbers (`125`,`343`,etc) This calculates the amount of divisors (not only primes), if it has `1` or `2` it returns `True`. The only exception is when a number has more than two prime factors but only two divisors. In this case it is a perfect cube of a prime (its divisors are its cube root and its cube root squared). `x**3==n` will cover this case, adding one to the cube root entry pushes the sum up to a count of 3 and stops the false-positive. thanks Jonathan Allan for writing with this beautiful explanation [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56~~ 48 bytes ``` ->x{r=c=2;0while x%r<1?(x/=r;c-=1):x>=r+=1;c==0} ``` [Try it online!](https://tio.run/##BcHRCkAwFAbgV9mNIoyp3Zh/HkQuWBZF6ZQcsWef76NrfqJHLC2/BIfG1Pe67YvghDrVp1yBjCuhspYtKIcyDqhDTJWUWmfymM734@8UAxfCDzyOIf4 "Ruby โ€šร„รฌ Try It Online") ### How it works: ``` ->x{ # Lambda function r=c=2; # Starting from r=2, c=2 0 while # Repeat (0 counts as a nop) x%r<1? ( # If x mod r == 0 x/=r: # Divide x by r c-=1 # decrease c ): # else x>=r+=1 # increase r, terminate if r>x ); c==0 # True if we found 2 factors } ``` Thanks Value Ink for the idea that saved 8 bytes. [Answer] # Mathematica, ~~31~~ 29 bytes ``` Tr[Last/@FactorInteger@#]==2& ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 4 bytes ``` ๏ฃฟรนรชรจ๏ฃฟรนรชโ€ขล’ยฅ๏ฃฟรนรฎยบ ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCf1AvPTclg9zp@z5/9/SFAA "Neim โ€šร„รฌ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` lambda k:f(k)==2 f=lambda n,k=2:n/k and(f(n,k+1),1+f(n/k,k))[n%k<1] ``` [Try it online!](https://tio.run/##LcjLDoIwEEbhvU8xG5M2/Am24IXGeRJkUUOKZHQghAU@fWXh7nxn/q6vSX0e@JHf8fPsI0lIRiyzPyT@L4WwD1oKRe1NMrsLZ@GKPUuBWNvqUe6uy2laaKNRqXXwqFDjghuqE@oGzbkL8zLqSoPZbL7@AA "Python 2 โ€šร„รฌ Try It Online") ***-10 bytes thanks to @JonathanAllan!*** Credit for the Prime factorization algorithm goes to [Dennis](https://codegolf.stackexchange.com/a/104591) (in the initial version) [Answer] ## JavaScript (ES6), 47 bytes Returns a boolean. ``` n=>(k=1)==(d=n=>++k<n?n%k?d(n):d(n/k--)+1:0)(n) ``` ### Demo ``` let f = n=>(k=1)==(d=n=>++k<n?n%k?d(n):d(n/k--)+1:0)(n) console.log( [...Array(200).keys()].filter(f).join`, ` ) ``` [Answer] # Mathematica 32 bytes Thanks to ngenesis for 1 byte saved ``` Tr@FactorInteger[#][[;;,2]]==2& ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby) + `prime`, 34 bytes ``` :prime_division|:*&:pop|:sum|:==&2 ``` [Try it online!](https://tio.run/##HcbRCoMgFADQ9/sVUlAw7qLSIoW@JCK2ZcxB6jIHI/t2BztP53X192/c5NurTZLcbmqVOcDSR/H/NKuPcsroIC6ZsMYG4fwaRN9ndRwqrJEiwxY7pCUyjrwZC3l7PMlsSNABCLF@dyRJD30Kkh7LoIvdTGo8E5B6jhXUQIFBCx3QEhgH3vwA "J-uby โ€šร„รฌ Try It Online") [Answer] # Regex (ECMAScript or better), ~~24~~ 23 bytes ``` (?=((x(x*))\2+)\1+$)\3^ ``` *-1 byte [thanks to Grimmy](https://chat.stackexchange.com/transcript/message/50001768#50001768)* [Try it online!](https://tio.run/##Tc89b8IwFIXhv0KjCu4lTUgo6oBrmDqwMLRjaSUrXJzbGseyDaR8/PYUhkqdnyMdvV9qr0Ll2cUsOF6T3zb2m346Ly0deq@kX1oHcJSz0bCDuQRooR0irsYprsr0HlePn91wdMQ8Nm/Rs9WAeTBcETw9ZBNEEWQhDjUbAjDSk1obtgSId9LujMGTliYPznCEQTZAwRsAK3VuyOpY42x8PnNYqiWwdMoHWtgI@r34QPwD@g92Vs7L6Y0x1r45JAu7V4bXPa@spmkvSY3YNB4EP0sSnKZ4PUzaJPfkSEVgzLcqVjV4xFPo9901KcKtohRuF0P014m4XLoimxTFLw "JavaScript (SpiderMonkey) โ€šร„รฌ Try It Online") - ECMAScript [Try it online!](https://tio.run/##NY7NasMwEAbvfopF5LAb/yAlOdkRfRDbhdAqjYq6MiuVOk/vRim9Ld8wwy73fIt83PzXEiVDuqdGXPOZIg8gVpRSG75YxBXXPdF0qGky9Y6m4@v2YKPpWzMP4K2urlEggOfS6FJ@99xXEGzo0hJ8RtUqqsBfITjGQOdDD2E0sw2jnisoMhdZLvzh0HPGAqj5u8xMtaFHrwTEdcld5O2G0oBa1Z6fpCDfwyJFoedgzfD/TfzO3Y/47DBlQSbadHvS@hc "Python 3 โ€šร„รฌ Try It Online") - Python [Try it online!](https://tio.run/##PY5Bb8IwDIXv@xVeNYkEVivtdiJEqIIK7cIktlvLok2EEikKVRpEd9lf7xLYONiSn9/3bHf6@h4cCNioRvUtWnWGZfFeoFOfu8erOJ2@rNavm3JRvJUctGAczgdtFBjRKN/dAeg9mCrNtkIktU14WJiKIab5loOyu@AICnat0Z6M0hH9Q9Ao2/gDobM8MFXgA3ZD9kcHFrSFKKI/Sk0yRhGj8TYG3yWLJH0ythTEDzgeBX0f/2xPvrvkxb@zMDttPdj/E7HHkrJcL6UcyFwQ0pN@TGmdT2idTR5o/fQxDCx9ZuwX "Ruby โ€šร„รฌ Try It Online") - Ruby Takes its input in unary, as a string of `x` characters whose length represents the number. This regex is based on the 18 byte "Is it prime?" regex `(?=(x(x*))\1+$)\2^`, which unlike its semiprime version above, is longer than the shortest known, the 16 byte `^(?!(xx+)\1+$)xx`. But like `^(?=(xx+?)\1*$)\1$` (also 18 bytes), it has the interesting attribute of implicitly rejecting 0 and 1 as prime numbers, whereas the 16 byte regex must explicitly reject them (the `xx` at the end). ``` # tail = N = input number; there's no need to anchor here, # because a start anchor is used at the end of this regex (?= ( # \1 = largest proper divisor of N that is >=2 (x(x*)) # \2 = largest proper divisor of \1; \3 = \2 - 1 \2+ # Assert that \2 is a proper divisor of \1 ) \1+$ # Assert that \1 is a proper divisor of N ) \3^ # Assert that \3==0, and thus \2==1, meaning the largest proper # divisor of the largest proper divisor of N is 1, meaning N is # semiprime ``` # Regex (Perl / Java / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 23 bytes ``` ^(?>((x(x*))\2+)\1+$)\3 ``` [Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzV1bmjh8MU2t4F592tvqghMLgUy7pEIlZF@9xk7Yy@Wec/@cX3eyZjl@34BYAd5cjgcDpBBRynK7ed9UAdqLpcRJJspKoAfdRoW@s/rcw6w5z0SA2kjXGd3TJE8yd/1yfTxRWc4zjqefx9L632XRxxVRKB6/XEw82NqUC/S1@eB7GSvbi2eufkqiSzmNY5em6HULlCZDAgPEJUSQv1AQW6Anbj6f4Ca2CM7FHyvRIoSg1Ntuq9T4SdcVpQMdXhCbRYoNTwk2r@PI8iVjdw "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##bVLvb9MwEP2@v@KIQLXbzkuH@IIXJkAgITFA28e2SG7itO6cS7CdNdu0v72c0/BjUvPlcnfP7/yeb6vu1Om2uN2bqqldgC3lwtRiLOH/ShuMPVpzeq076pw07cqaHHKrvIcrZRAeYaj5oAKFu9oUUFGH3QRncA3Krf18ySFsXL3z8KnLdRNMTSdPAD4bq6HMUO/6X5aIvC60oH7C5Ye2LLXTxbVWhXaw6mHPi@zPySEtOZfDXD8NcreJ/Iz5bEUaVPHVoGacv8iwtZabknmhf7XKepacjcfjhPPH59ADA2PhKMEjMYS/DERwRgwrwt1KP8lGCxzFGOTTofb0Q4WgHYLLhj9SWzVxgOeS3FjVtdUK4SEriVFLuMkVIkk32LQBMohqhxq7ufdBV8IglzDo7GFio/w33QW6Zm8xwGCIpbsTxwGEhBgkDv35Eiy1I0r4xprAklN6BMIHwJQ6XzDQGjjRKOc1JczO0yWfAs6ONoXVuA6bi3O4hIiEtxRmS2LMN8rNl92gp89wtpTw3jl170VprGXddNSNelMAytpFbXSNDFMJeJHhjMJkQgKvVMg35FBFbE5Uh4z1m4u04B@J/LAxYudUw4YRed3cfy@vFa41TUqnyHlUWgKraDwW5F182wc@mFyTYztngmbxUbl8yIJr4/v8azfkYShZ8sonZAmXT/E7iVu1/8ku3zHWsW7M@eJ8whezyUu@eL2PC7NPT9@k6W8 "Java (JDK) โ€šร„รฌ Try It Online") - Java [Try it online!](https://tio.run/##XVBda4MwFH3vrwghYG7VVl27UVLXl21QGHvY9la7YF2sMhtDTEEo/e3uWva0h1zu1znn5pjKDOuNqQxhlqSEzimZEWPVUVplmrxQ3JvPphspq7xxsmhPpm6UzXgGInufd15APHwlNuVRjQvaKe06LuXL9vVZSghIDEiJxGJS61p2ynFqCqtmh7z4cRaDbOpT7WhA6CJZLVb3D8lqSUFMytZyVqeRYE1aInvHPz6ftm8g4ELqkrNm1znbKI0ZhPE@TWmmKeBydz7gBNtBFIQxjHjVm6b9VpyGNMB1gfiiPWs3YtcJgnZIgDHaiwkhN2X9VzO9Tm9zzHwfUJrwm0On3BUVZzZAsdEulTvu9V7ANACQy3hiDaqo2vEuQfArsSBjTZgWV5S5/rOVgxi@@OaR8573U4As8SGLfQbZ3TBE4TKKfgE "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##NY7NasMwEAbvfopF5LAb/yAl5GLH7YPYLoRWSVTUlVmp1Hl6N3Lpbdlhhm9@pHvg4@q@5iAJ4iNWYm92qT5j4A6kF6XU@oavL4gLLnui8VDSaModjcf1yQbT1mbqwPW6uAYBD45zponpw3FbgO99E2fvEqpaUQHuCt4yejofWvCDmXo/6KmALHOW5cI3i44TZkDV32UmKg09ezmwTWyivcj7HaUCtag9bzBT18Is2aLt0Zvuf1D4Ts2PuGQxJkEmWnV90voX "Python 3 โ€šร„รฌ Try It Online") - Python `import regex` [Try it online!](https://tio.run/##RY/RaoQwFER/ReSCyaZZ4pa@bEi70Od@gVoQe7cG0huJWZSVfLvVltLHMwyHmcFPGMYenVshmCrgJ87N@Uw4sUuxvrOXZ8ZmNh84r0@C16UAXj@uxeUhf/Vfg3X4kXMNd6P01Qdsu56ByyxlYGm4Rb5Aa8DJcXA25jLX9sqgPXb@RlG6mJ32gjDQVqpJm4ABmcpSbH4SDSQd/nG5sxB82R3h@NbGrseRFXNxAOK/8Z0vU7ARZe/HmLZZpf7nTJLffjlLmAGllFYln5T6Bg "PowerShell โ€šร„รฌ Try It Online") - .NET This is a direct port of the "ECMAScript or better" regex above, using an atomic group instead of an atomic lookahead. It is much faster on most regex engines, as the `^` start-anchor test is done first instead of last. # Regex (Perl / Java / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 23 bytes ``` ^((x+)\2*(?=\2$)){2}+x$ ``` [Try it online!](https://tio.run/##RY7NasMwEIRfZQlLrK1tLBtyqazEgfTaU291ItISg0BJHMkFF6G@uqu4gV6Wndmf@fqTNavp/A1oBXhz/TwawEJEKevd9m27DtBdLUMnuajXgjzoLiryvdWXARbtZSECNEa63uiBJXmSua8PN8QTleVlVtLpdl/a/Ls8@vSMisT9l4uJR9uYuiLfmPdyL2Ple/HI1Q@JupbzOHZpSl53wFgyJjBCXCIC@QMF2oI8uuVyhpvZIngp/lhRixCCUi@vO6WmA2NjSm31xDayrZDIVyEdcZp4vuL8Fw "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGSVHUC7GWqUWzDBgxYu6F9TDNAseVErUx7kty4KfLbM8rxPgrULzTJ01F34r16VGf3xcPBVE3tAtxTLkwtxhL@r7TB2FdrTq91R52Tpl1Zk0NulfdwpQzCMww1H1Sg8FibAirqsNvgDK5BubVfLDmEjau3Hj53uW6CqenkCcAXYzWUGept/8sSkdeFFtRPuPzYlqV2urjRqtAOVj3sZZH9OTmkJedymOunQW43kZ8xn61Igyq@GdSM8zcZttZyUzIv9K9WWc@S8/F4nHD@/BJ6ZGAsvErwTAzhLwMRnBPDinAP0k@y0R2OYgxyf6ztf6gQtENw2fBHaqsmDvBckhururZaIeyykhi1hNtcIZJ0g00bIIOodqix2ycfdCUMcgmDzh4mNspf6y7QNXuLAQZDLN2dOI4gJMQgcegvlmCpHVHCN9YElpzRIxA@AKbU@YqB1sCJRjmvKWF2kS75FHD2alNYjeuwuZjDJUQkvKcwWxJjvlFusewGPX2Gs6WED86pJy9KYy3rpqNu1JsCUNYuaqNrZJhKwIsMZxQmExJ4pUK@IYcqYnOiOmas31ykBf9E5MeNEVunGjaMyOvm6Xt5o3CtaVI6Rc6j0hJYReOxIO/i2@74YHJNjm2dCZrFR@VylwXXxvf5127Iw1Cy5K1PyBIu9/E7iVt1@MlYN@F38zG7zO7mp8Q930@600NcmEN69i5NfwM "Java (JDK) โ€šร„รฌ Try It Online") - Java [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaK5NtRbdkFh82QbC2MO2N@tC7VJbVtOQRiiIv727lT3tIZf7dc65Obayw2ZrK0uYIymhc0pmxDp9Uk7bJi80D@az6VapKm@8KtqzrRvtMp6BzN7nXSBIgK/EpjrpccF4bXzHlXrZvT4rBYIsACmRWE5qU6tOe05t4fTsmBc/3mFQTX2uPRWELpP1cv3wmKxXFOSkbB1ndRpL1qQlsnf84/Np9wYSrqQuOWv2nXeNNphBtDikKc0MBVzuLkecYFvEIlrAiNe9bdpvzWlEBa5LxBftxfgRu0kQtEcCjPFBTgi5K5u/mplNep9jFoaA0oTfHTrnvqg4cwLFRrt07nnQB4IZACDX8cQadFG1412S4FcWkow1YUbeUOb2z1YOcvjivA8hS6Z8m2YJA7gmt7BnwxBHqzj@BQ "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##NY7NasMwEAbvfopF5LAb/2C59GJX5EEcF0KrJCrqyqwU6lD67G7k0tuywwzffE/XwE@r@5yDJIj3WIm92KX6iIEHECNKqfUVcSnp2O3xYI7djui7@ymX3fpgo@5rPQ3gTFucg4AHxznTxPTuuC/AG9/E2buEqlZUgDuDt4yeXroe/Kgn48d2KiDLnGU58cWi44QZUPV36YlKTY9eDmwTm2hP8nZFqUAtas8bzNT1MEu2aHsYPfwPCrfUfIlLFmMSZKK1rZ/b9hc "Python 3 โ€šร„รฌ Try It Online") - Python `import regex` This is a port of the now-obsoleted 24 byte "ECMAScript or better" regex, using a possessive quantifier instead of an atomic lookahead to disable backtracking. ``` ^ # tail = input number ( (x+) # \2 = largest strict divisor of tail # = tail / {smallest prime factor of tail} \2*(?=\2$) # Assert that \2 is a strict divisor of tail; tail = \2 ){2}+ # Execute the loop exactly 2 times, with backtracking disabled x$ # assert tail == 1 ``` ### \$\large\textit{Expressions with interactive input}\$ # [R](https://www.r-project.org/), ~~59~~ ~~58~~ 54 bytes ``` grepl('^((.+)\\2*(?=\\2$)){2}+.$',strrep(1,scan()),,1) ``` [Try it online!](https://tio.run/##ZczLCoMwEIXhfZ5D8EwNYtILdSF9ERFEQhEkDTNSCuKzR9ed1YGPw89ZuvBLHETmT8SW3xzSgnIA6or63l/w6s4piDa/V3VRWln5/MBZmcYIImsd5Z1M4jmuCN9xgRAZZ/7FK7kquSl5KHnqTqNDraL2ng8 "R โ€šร„รฌ Try It Online") - test cases only ### \$\large\textit{Anonymous functions}\$ # [R](https://www.r-project.org/), ~~63~~ ~~62~~ ~~58~~ 53 bytes ``` \(n)grepl('^((.+)\\2*(?=\\2$)){2}+.$',strrep(1,n),,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BasMwEEX3PcVgAp5p5GAZAqVC9ALdd2G7YBrJFQjVaJRNgk_STVrIEXqY3qYS6Wrm8ef_P59f8fJt9fWYbPPwux8w0BzN4rF-RdxtaRi6e3zSeWyIzt263W1qwSnmG5QikBCS_s0_rFsFJ22dN1hxOrhQkQL7EdGDC8DHZYmG-WWKwYWZMZrp8OyCYTxRDr8D8KAhh_PiXUIvoGoq6ns5jgqcBfQmzOkdPWktCXzfjdpnNRtLiSslhR-LQtmBFh0RnPPG9DYlrIdQk2ItFRR0tK635y_Xttm37Q3-AA) *-1 byte [thanks to Giuseppe](https://codegolf.stackexchange.com/questions/248690/is-it-a-valid-list/248747#comment555846_248747)* *-4 bytes by using `grepl()` instead of `sum(grep())` or `any(grep())`* *-5 bytes by using a new anonymous function syntax introduced in R v4.1.0* The old **58 byte** R v3.5.2 function: [Try it online!](https://tio.run/##FU3LasMwELz3KxYT8G4jB8vQixXRH@i9B9sF00iuQKhCqxya4G93pdPMMK902Gt3xPSXxtHilkz02H4hXs40z8MrvusCJ6LnsJ8vp1ZwTiWDUgQSQhIdrHsFD22dN9hwvrnQkAL7m9CDC8D3GJNh/lxTcGFjTGa9fbhgGB9UZl8APGgosxy9y@gFNF1D0ySXRYGzgN6ELf@gJ60lgZ@GRfvilmI9cfWk6rE6VBpo0RHBszCm7zVjO4eWFGupoEpH@3703Vvf/wM "R โ€šร„รฌ Try It Online") # [Ruby](https://www.ruby-lang.org/), ~~37~~ 36 bytes ``` ->n{?x*n=~/(?=((x(x*))\2+)\1+$)\3^/} ``` [Try it online!](https://tio.run/##PY7RDoIwDEXf/YpKTNgkGwN9w8mHAJoYAZcshcCIGKO/joWoD23a23tu2g2Xx1TpSRzxmY5b1O@QpZqxkY1bzvM44HkUbHi@O4WvyWiVwP1mbAlW16XrVwCmApuJqNDay9FL6GAzJaWIiwRKvJKDFNm31jjmC59/EWlLrN2N8UNMTEY8YX@kajpAMAizKF1zNixSXMrZ@F/Jt2RVGRJIg1nP/7WD65cc0nREe2fQAf6i5041KbFX6gM "Ruby โ€šร„รฌ Try It Online") [Try it online!](https://tio.run/##FcZLDoIwFADA/TtFARctRJCPRjSVg4gSP0VJyNPYEitNvXrF1cxrOH9cy918h6bSIfJvQitOqaY6ZKzOIlan0YzV@TGx7n3vekGQ34SSMImxejTdloy83eMByHNQkviBQbshgfG80RI@ZYwv/UlK@6/1QeDVpZBBDgWsYA35AooSyuUP "Ruby โ€šร„รฌ Try It Online") - test cases only # [PHP](https://php.net/), 62 bytes ``` fn($n)=>preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$n)) ``` [Try it online!](https://tio.run/##LY89b4MwEIb3/AoLWeKumMQgdTJOlixdurRbSKOU2AHJNRYQqRLit9Nz1OV0X8@974U2rNUhtIFxq1frgXvU@zCY@@XnOjUtpLsvgG2GdfkCB12XHHEul2zLd6kYp@ESrjdIU0EYrmpj@wF4p6XiTtu7mUb4@Dy@vaPCmXUWuDsR4wzJOMyLs9ZJ7ROk5fHxTRNqCynyAiNvfoPrbwaSPBG0rohv@oefIluVBJ3oAEV5VhvGnsr@v@a@0s85ZVmGJM2A2/gbsjn66NA0bR/FFSO/hWKxZtyrZVll/irlHw "PHP โ€šร„รฌ Try It Online") # JavaScript (ES6), ~~46~~ 45 bytes ``` n=>/(?=((.(.*))\2+)\1+$)\3^/.test(Array(n+1)) ``` [Try it online!](https://tio.run/##Tc3BTsJAEIDhV0FiYMZNS4ueWKfEIxdewGqysdt2dJ1udhcIAZ691oOJ5y/5/09zNPEjsE9Z9NzY8D3Ilz2PLY1C1Qq2BJBD/oBYrxXWpbrH@vF9lScbE7yEYM4gqkQcIxX61LOzAI6CNY1jsYB4R3JwDi8duTx6xwmW2RI1twBCXe6sdKnHan29ctybPTB5E6LdSYLutXhD/AP7H6Qqt@XmlzH1YTjNd3I0jptZMNLZzWyunG6HAJqfyWpWCqdhC4x4iYuFDzxVUEcqtT@kmMIk@nYbi@ypKH4A "JavaScript (SpiderMonkey) โ€šร„รฌ Try It Online") # Java 8, 61 bytes ``` n->new String(new char[n]).matches("((.+)\\2*(?=\\2$)){2}+.") ``` [Try it online!](https://tio.run/##bVDLbtswELznKxZCCi/9IGQDuYRWguRQoEDbi4@2DoxCWXTplUBS8SPIt7sryW0OLS/L5cwOd2an3/Rs9/rrYvdN7SPsuJdttE6WLRXR1iTHCv4Bx@qmcDoE@KEtwfsNQNO@OFtAiDpyeavtK@wZw1X0lrbrHLTfBtFTAb5etZffKJqt8dPnunZG0wOUkF1o9kDmAMMkdtei0n5NuZB7HYvKBEwQ5URsNosxPmZcboV4X3xMZCIuin94GeTgnJXaBaNgVWgi48FS00bIoNcf3nB1CtHspSWh4FBZZwB7mqx0@GmOEcWftYeNwFkyrDGQiBnf@QF5@q9Xx3DHkqFxNmIySxi1FIFSRq6mZaN9MNygW6e5mALN/wtKZ2gbq@UCHqFjwj2Xec6KfSz58epnCGmeK3jyXp@CLK1zeJyOjiOh@v3L2nfeeI2MUgW0zGjOZTJhg7YELKVuGndC4jRtiWdxjaZmnwdvo8HRhljsnEXfdql@wg07jyUmX0LCRoT66M4lnd2l6W8 "Java (JDK) โ€šร„รฌ Try It Online") [Try it online!](https://tio.run/##hZHPagIxEMbvfYpBPMxUDHarUhHbJ9CLR/Uwxliju5NlEy0i@@xr7HqVQIb58xu@@SBHvnDflUaOu1Ojc/Ye5mzl9gZgJZhqz9rA4tECbJ3LDQtojAiEpnFax4jPBw5WwwIEZtBI/1vMHyxDZeUXH6U@cLWSDamCgz4Yjx1E1aP1OnvHn1lMXaJbVvdUh5ppK1met3mUfCpfnN1BEZ1hq7raAFNra3n1wRTKnYMqIwq5oCiNH/Rv8CXPEvwzwYcJPk7wr9T9QcrAJLEwGdHzj@rmDg "Java (OpenJDK 8) โ€šร„รฌ Try It Online") - test cases only # Java 11, 51 bytes ``` n->"x".repeat(n).matches("((x+)\\2*(?=\\2$)){2}+x") ``` [Try it online!](https://tio.run/##bZBPb9swDMXv/RSEsSFS/ghOgF2muMV2GDBg2yXHxAfVlWNlCi1IdOOk6GfP6CTtDpsuBPmeHvjjzjyb2e7p99ntQxsJdtyrjpxXdYcVuRbVWMM/4ljfVd6kBD@NQ3i5Awjdo3cVJDLE5bl1T7BnTawoOtyuSzBxm@TFCvDtlr38jmS3Nk6/tq23Bu@hhuKMs/usz1S0wRoSKNXeUNXYJDIh@oncbBZj8VBw@SDly@J10mfyrDn38RoCp6I2PlkNq8og2ggOQ0dQANrD20ysjonsXjmUGg6N8xbExaYak37ZnoR8W/ZKAN6h5YyrCdnxgweCf78TepYHl0rBOxLZLGPVIQHmrNxQVTAxWW6EX@elnALO/ysqb3FLzXIBDzA44TOXecmJVWPiuuxvPJcO56WGLzGaY1K1817001E/kvqyf93GgY3XKDDXgMsC51wmEwZ0NYhamRD8kQ8tuRcneTtNy5yH6MiK0QY57FRQ7Iar/pUDk1Mtso8pYxCpX4d3zmef8vwP "Java (JDK) โ€šร„รฌ Try It Online") ### \$\large\textit{Full programs}\$ # [Retina](https://github.com/m-ender/retina), ~~30~~ 29 bytes ``` .+ $* ^(?>((1(1*))\2+)\1+$)\3 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK07D3k5Dw1DDUEtTM8ZIWzPGUFtFM8b4/39DLiMuYy4TLjMuCy5jAy4TSy5LUwA "Retina 0.8.2 โ€šร„รฌ Try It Online") - test cases only # [PHP](https://php.net/), 64 bytes ``` <?=preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$argv[1])); ``` [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdP05DQ09bM8ZIS8PeNsZIRVOz2qhWW09FX12nuKQoviAxRUNdXUclsSi9LNowVlPT@v///yaWAA "PHP โ€šร„รฌ Try It Online") - tests one number at a time # [PHP](https://php.net/) `-F`, 61 bytes ``` <?=preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$argn)); ``` [Try it online!](https://tio.run/##VY89b8IwFEXn8ituXRcnBEMK6uQENqRODB2hRW7skKjBiUykVhB@e@rwIVQPlt590n3nfMl91lotFbhVYAw2itjm@lgbzePK6u1mJ@sk89j40/NGgb@eDLx5vJ5Q3z9OTsGIjtlwX9tNJZXH2JBKuzW@L9pbT08nWQluQKglrBvI2hDBMENSKi2gf3WC6az/IrD7TvO0xFLgJ8sLjbfFe4wrIIqmWV16CoIPoUqkpYXnwcSEHotnwsngRARMdJ6fBi44EbggCOCIVNl7OLNQI/43S0RYomkcSl4L5ClWoNLd0gjdpTrT5hI@gh9AD7esa5v1pyLNBQ6x47@rGtItkOY9VRon2f1oUGUV@OIs7vyXd3nehvw1DP8A "Bash โ€šร„รฌ Try It Online") - tests ranges of numbers [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdP05DQ09bM8ZIS8PeNsZIRVOz2qhWW09FX12nuKQoviAxRUNdXUclsSg9T1PT@v9/E8t/@QUlmfl5xf913QA "PHP โ€šร„รฌ Try It Online") - tests one number at a time [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` โˆšรœfL=2 ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5qPrdH/w@2Pmtb8/x9tqKNgpKNgrKNgoqNgqqNgBmQbxAIA "Jelly โ€šร„รฌ Try It Online") # Explanation ``` โˆšรœfL=2 Main link โˆšรœf Prime factors L Length = Equals 2 2 ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 4 bytes ``` ol2= ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/z8/x8j2/38TSwA "Actually โ€šร„รฌ Try It Online") [Answer] # 05AB1E, 4 bytes ``` โˆšรญg2Q ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8KR0o8D//00sAQ) **How?** ``` โˆšรญ prime factors list (with duplicates) g length Q equal to 2 2 ``` [Answer] # MATL, 5 bytes ``` Yfn2= ``` **[Try it online!](https://matl.suever.net/?code=Yfn2%3D&inputs=49&version=20.2.2)** # Explanation * `Yf` - Prime factors. * `n` - Length. * `2=` - Is equal to 2? [Answer] # Dyalog APL, 18 bytes ``` โ€šรฉรฏCY'dfns' 2=โ€šรขยข3pcoโ€šรฉรฏ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepcRraPOhcZFyTnAwVBKv6DlXAZcnFBGEYwhjGMYQJjmMGlDOByljCWpSkA) **How?** `โ€šรฉรฏCY'dfns'` - import `pco` `3pcoโ€šรฉรฏ` - run `pco` on input with left argument 3 (prime factors) `2=โ€šรขยข` - length = 2? [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 bytes ``` ยทโˆรงl2= ``` 4 bytes seems to be a common length, I wonder why... :P [Try it online!](https://tio.run/##S0/MTPz//@GO3hwj2///LU0B "Gaia โ€šร„รฌ Try It Online") ### Explanation ``` ยทโˆรง Prime factors l Length 2= Equals 2? ``` [Answer] # [Python](https://docs.python.org/) with [SymPy 1.1.1](http://www.sympy.org), ~~57~~ 44 bytes -13 bytes thanks to alephalpha (use 1.1.1's `primeomega`) ``` from sympy import* lambda n:primeomega(n)==2 ``` **[Try it online!](https://tio.run/##HYxBDsIgFAXX9hRvVzBfo60a2wRP4gYjaBM/EMqGND07oqt5s3gTcnp71xer7uWj@fHUcGOIExvP5qWFk0p1jY2eMWcOGRMHH9O2WB@RzJwwOYgjoSP0hBPhQrjWfagyEIazHJtNDbok2mXF7oZlbff1zTqJX4Bg/5RSli8 "Python 3 โ€šร„รฌ Try It Online")** [Answer] # [R](https://www.r-project.org/), 67 bytes ``` c=0;n=scan();for(p in(1:n)[-1:-2]-1)while(n%%p<1){c=c+1;n=n/p};c==2 ``` [Try it online!](https://tio.run/##ZcxNCsIwEEDhfU7hpjCDFDvxB9s4JxEXJUQMlGlIRIXSs0fXzvaD93ItHD4ph1LiLLBUz50TLn4UQHefM6RNFKBB8NrS0NpbS/h@xCmANE26EC6e/ZZ@jezS6jyzrSualKM8IbzGCQqiIfMvVsleyUHJSclZfzo96hX1x/oF "R โ€šร„รฌ Try It Online") [Answer] # Java 8, ~~69~~ 61 bytes ``` n->{int r=1,c=2;for(;r++<n;)for(;n%r<1;n/=r)c--;return c==0;} ``` -8 bytes thanks to *@Nevay*. [Try it here.](https://tio.run/##hZFNC8IwDIbv/opchBbddH7hqPUf6MWjeKi1SnVLR9YJIvvts35cpZBAkie8eSFXdVeJqwxeT7dOF6quYaMsPnsAFr2hs9IGtu8W4OhcYRSCZgEBchGmbcgQtVfeatgCgoQOk/XzvUIyG2o5EWdHTNBgsELBPzX2aZUJHEniOkkEGd9Q0JVyLNpOfCWr5lgEyZ/y3dkTlMEZ23myeNkfQPGvrd2j9qZMXePTKiBfIMNUs4x/DP7lkwifRvgswhcRvozdH8cM5JGFfM5/P2q7Fw) [Answer] # [Ruby](https://www.ruby-lang.org/), 35+8 = 43 bytes Uses the `-rprime` flag to unlock the `prime_division` function. ``` ->n{n.prime_division.sum(&:pop)==2} ``` [Try it online!](https://tio.run/##Hc1NCsIwEEDh/ZxiaEV00aBtFVuIF1EJSFM7YJOQH0VCrm6Urh98z4b7J4/8mquziooZS7MUA73IkVbMhXmz7o02W87rlN8TPSUq5PiQ3jGvBQGgCd5hUUaVeizjeFmJpdxSAVINeQ81NNDCEU7Q7KDtoDt8tfF/3@XKLscf "Ruby โ€šร„รฌ Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` ยซรชยทโˆยขโ€šร‡ร‰ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsIseQ4bii4oKDIiwiO1rGm2AgPT4gYGo74oGLIiwiWzEsMiwzLDQsNiw4LDMwLDQ5LDk1XSJd) [Answer] # [Factor](https://factorcode.org/) + `math.primes.factors`, 22 bytes ``` [ factors length 2 = ] ``` [Try it online!](https://tio.run/##NcyxCsIwFEDRPV9xvyCorWIVZ3FxESdxCOXVik2MyXMQ8dtjEZzv4Xau1Xsqx8Nuv13hnfY2pquXbLtfyWR5PCW0krlJCjIQk6i@RhWUtTFvpsyoqFmwpJpQNzRzPqac@D8GCRftR7bhXLyL2PIF "Factor โ€šร„รฌ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ 65 bytes ``` lambda n:g(n)==2 g=lambda n,i=2:n/i and[g(n,i+1),1+g(n/i)][n%i<1] ``` [Try it online!](https://tio.run/##NcvLCsIwEIXhfZ/ibISGDtTEC7Q4TxKziNTWATsGm41PH4Pg7uM/nPTJj5e6MvO1PON6myJ0XFo1zK5Z@J9I2I3aC6JOvs4knTVku8peTPC6k4sNJd@3vIHhLcERDoQj4VyxrxoIwyk0TXqLZqwxtTPh9zDlCw "Python 2 โ€šร„รฌ Try It Online") All credit to [xnor's answer](https://codegolf.stackexchange.com/a/104632) for the original prime factorization code. [Answer] # C#, 112 Bytes ``` n=>{var r=Enumerable.Range(2,n);var l=r.Where(i=>r.All(x=>r.All(y=>y*x!=i)));return l.Any(x=>l.Any(y=>y*x==n));} ``` With formatting applied: ``` n => { var r = Enumerable.Range (2, n); var l = r.Where (i => r.All (x => r.All (y => y * x != i))); return l.Any (x => l.Any (y => y * x == n)); } ``` And as test program: ``` using System; using System.Linq; namespace S { class P { static void Main () { var f = new Func<int, bool> ( n => { var r = Enumerable.Range (2, n); var l = r.Where (i => r.All (x => r.All (y => y * x != i))); return l.Any (x => l.Any (y => y * x == n)); } ); for (var i = 0; i < 100; i++) Console.WriteLine ($"{i} -> {f (i)}"); Console.ReadLine (); } } } ``` Which has the output: ``` 0 -> False 1 -> False 2 -> False 3 -> False 4 -> True 5 -> False 6 -> True 7 -> False 8 -> False 9 -> True 10 -> True 11 -> False 12 -> False 13 -> False 14 -> True 15 -> True 16 -> False 17 -> False 18 -> False 19 -> False 20 -> False 21 -> True 22 -> True 23 -> False 24 -> False 25 -> True 26 -> True 27 -> False 28 -> False 29 -> False 30 -> False 31 -> False 32 -> False 33 -> True 34 -> True 35 -> True 36 -> False 37 -> False 38 -> True 39 -> True 40 -> False 41 -> False 42 -> False 43 -> False 44 -> False 45 -> False 46 -> True 47 -> False 48 -> False 49 -> True 50 -> False 51 -> True 52 -> False 53 -> False 54 -> False 55 -> True 56 -> False 57 -> True 58 -> True 59 -> False 60 -> False 61 -> False 62 -> True 63 -> False 64 -> False 65 -> True 66 -> False 67 -> False 68 -> False 69 -> True 70 -> False 71 -> False 72 -> False 73 -> False 74 -> True 75 -> False 76 -> False 77 -> True 78 -> False 79 -> False 80 -> False 81 -> False 82 -> True 83 -> False 84 -> False 85 -> True 86 -> True 87 -> True 88 -> False 89 -> False 90 -> False 91 -> True 92 -> False 93 -> True 94 -> True 95 -> True 96 -> False 97 -> False 98 -> False 99 -> False ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 17 bytes ``` n->bigomega(n)==2 ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLikzPT83NT1RI0/T1tbof1p@kUaegq2CoY6CoYGBjkJBUWZeCVBESUHXDkikAZVpav4HAA "Pari/GP โ€šร„รฌ Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 45 bytes ``` .+ $* ^(11+)(\1)+$ $1;1$#2$* A`\b(11+)\1+\b ; ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK07D0FBbUyPGUFNbhUvF0NpQRdkIKOyYEJMElokx1I5J4rL@/9@Qy4jLmMuEy4zLgsvYgMvEksvSFAA "Retina โ€šร„รฌ Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` ^(11+)(\1)+$ $1;1$#2$* ``` Try to find two factors. ``` A`\b(11+)\1+\b ``` Ensure both factors are prime. ``` ; ``` Ensure two factors were found. [Answer] # Python 2, 90 bytes ``` def g(x,i=2): while x%i:i+=1 return i def f(n,l=0): while 1%n:l+=1;n/=g(n) return l==2 ``` `f` takes an integer `n` greater than or equal to `1`, returns boolean. [Try it online!](https://tio.run/##Rc1NCsIwEAXgfU/xNgWDAzbxBxvJScSdiR0IaYkR4@njdKOzmoHvvVk@ZZqTae3uAx6bSuyMsh3eE0eP2rPlrdMdsi@vnMDd6oK46Ia/0321Udyl7pyUqJ@PzpkW5ozinwWccNUEQ9gTDoQT4Sz7IMdIGI83KZRZMqciT9aMal8) Test cases: ``` >>> f(1) False >>> f(2) False >>> f(3) False >>> f(4) True >>> f(6) True >>> f(8) False >>> f(30) False >>> f(49) True >>> f(95) True ``` ]
[Question] [ Shortest answer wins. It must be sorted, and in 24hr time. The final line does not have a comma. Output should be as follows: ``` '00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:00', '05:30', '06:00', '06:30', '07:00', '07:30', '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30' ``` [Answer] # Pyth, 26 bytes ``` Pjbm%"'%02d:%s0',"d*U24"03 ``` [Demonstration.](https://pyth.herokuapp.com/?code=Pjbm%25%22%27%2502d%3A%25s0%27%2C%22d*U24%2203&debug=0) We start with the cartesian product of `range(24)` (`U24`) with the string `"03"`. Then, we map these values to the appropriate string formating substitution (`m%"'%02d:%s0',"d`). Then, the resultant strings are joined on the newline character (`jb`). Finally, we remove the trailing comma (`P`) and print. [Answer] # Befunge-93, 63 bytes ``` 0>"'",:2/:55+/.55+%.":",:2%3*v ^,+55,","<_@#-*86:+1,"'".0. < ``` ย  ![animation](https://i.stack.imgur.com/gRVfh.gif) *(animation made with [BefunExec](https://github.com/Mikescher/BefunExec))* [Answer] # Bash: ~~58~~ ~~47~~ 46 characters ``` h=`echo \'{00..23}:{0,3}0\'` echo "${h// /, }" ``` [Answer] # CJam, ~~31 30~~ 29 bytes ``` 24,[U3]m*"'%02d:%d0', "fe%~7< ``` This is pretty straight forward using printf formatting: ``` 24, e# get the array 0..23 [U3] e# put array [0 3] on stack m* e# do a cartesian product between 0..23 and [0 3] array e# now we have tuples like [[0 0], [0 3] ... ] etc "'%02d:%d0', "fe% e# this is standard printf formatting. What we do here is e# is that we format each tuple on this string ~7< e# unwrap and remove comma and new line from last line e# by taking only first 7 characters ``` [Try it online here](http://cjam.aditsu.net/#code=24%2C%5BU3%5Dm*%22%27%2502d%3A%25d0%27%2C%0A%22fe%25%7E7%3C) [Answer] # Python 2, ~~58~~ 56 bytes ``` for i in range(48):print"'%02d:%s0',"[:57-i]%(i/2,i%2*3) ``` Like [sentiao's answer](https://codegolf.stackexchange.com/a/49742/21487) but using a `for` loop, with slicing to remove the comma. Thanks to @grc for knocking off two bytes. [Answer] # Java - 119 bytes I started with Java 8's StringJoiner, but that means including an import statement, so I decided to do it the old way: ``` void f(){String s="";for(int i=0;i<24;)s+=s.format(",\n'%02d:00',\n'%02d:30'",i,i++);System.out.print(s.substring(2));} ``` Perhaps this can be improved by getting rid of the multiple occuring `String` and `System` keywords. [Answer] # Ruby, ~~94~~ ~~61~~ ~~56~~ 51 ``` $><<(0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*", " ``` Thanks to @blutorange (again) for his help in golfing! [Answer] # Perl, ~~52~~ ~~50~~ ~~48~~ 45B ``` $,=", ";say map<\\'$_:{0,3}0\\'>,"00".."23" ``` With help from ThisSuitIsBlackNot :) [Answer] ## JAVA ~~95~~ 94 bytes I love the fact that printf exists in Java: ``` void p(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0);} ``` Ungolfed ``` void p(){ for(int i=0;i<24;) System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0); } ``` EDIT Replaced the `','` with `44` [Answer] # Pyth, ~~32~~ 31 bytes I golfed something in python but it turned out to be exactly the same as Sp3000's answer. So I decided to give Pyth a try: ``` V48<%"'%02d:%d0',",/N2*3%N2-54N ``` It's a exact translation of Sp3000 answer: ``` for i in range(48):print"'%02d:%d0',"[:57-i]%(i/2,i%2*3) ``` It's my first go at Pyth, so please do enlighten me about that 1 byte saving. [Answer] # PHP, 109 bytes ``` foreach(new DatePeriod("R47/2015-05-07T00:00:00Z/PT30M")as$d)$a[]=$d->format("'H:i'");echo implode(",\n",$a); ``` [Answer] # Ruby, ~~54~~ 51 bytes ``` puts (0..23).map{|h|"'#{h}:00', '#{h}:30'"}.join", " ``` [Answer] # C, ~~116~~,~~115~~,~~101~~,~~100~~,~~95~~,~~74~~,~~73~~, 71 May be able to scrape a few more bytes off this... ``` main(a){for(;++a<50;)printf("'%02d:%d0'%s",a/2-1,a%2*3,a<49?",\n":"");} ``` [Answer] # T-SQL, ~~319~~ ~~307~~ 305 bytes ``` WITH t AS(SELECT t.f FROM(VALUES(0),(1),(2),(3),(4))t(f)),i AS(SELECT i=row_number()OVER(ORDER BY u.f,v.f)-1FROM t u CROSS APPLY t v),h AS(SELECT i,h=right('0'+cast(i AS VARCHAR(2)),2)FROM i WHERE i<24)SELECT''''+h+':'+m+CASE WHEN i=23AND m='30'THEN''ELSE','END FROM(VALUES('00'),('30'))m(m) CROSS APPLY h ``` Un-golfed version: ``` WITH t AS( SELECT t.f FROM(VALUES (0),(1),(2),(3),(4) )t(f) ), i AS( SELECT i = row_number() OVER(ORDER BY u.f,v.f) - 1 FROM t u CROSS APPLY t v ), h AS( SELECT i, h = right('0'+cast(i AS VARCHAR(2)),2) FROM i WHERE i<24 ) SELECT '''' + h + ':' + m + CASE WHEN i=23 AND m='30' THEN '' ELSE ',' END FROM( VALUES('00'),('30') )m(m) CROSS APPLY h ``` [Answer] # Pyth, 34 bytes ``` j+\,bmjk[\'?kgd20Z/d2\:*3%d2Z\')48 ``` This can definitely be improved. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=j%2B%5C%2Cbmjk%5B%5C%27%3Fkgd20Z%2Fd2%5C%3A*3%25d2Z%5C%27)48&debug=0) ### Explanation: ``` m 48 map each d in [0, 1, ..., 47] to: [ ) create a list with the elements: \' "'" ?kgd20Z "" if d >= 20 else 0 /d2 d / 2 \: ":" *3%d2 3 * (d%2) Z 0 \' "'" jk join by "", the list gets converted into a string j+\,b join all times by "," + "\n" ``` [Answer] # Python 2, 69 bytes ``` print',\n'.join(["'%02d:%s0'"%(h,m)for h in range(24)for m in'03']) ``` Quite obvious, but here's an explanation: * using double-for-loop * alternating between `'0'` and `'3'` in string format is shorter than a list * `%02d` does the padding for `h` * `m`doesn't need padding as the alternating character is on a fixed position * `'\n'.join()` solves the final-line requirements I have no idea if it can be done shorter (in Python 2). **by Sp3000, 61 bytes :** `print',\n'.join("'%02d:%s0'"%(h/2,h%2*3)for h in range(48))` [Answer] # Haskell, 85 bytes ``` putStr$init$init$unlines$take 48['\'':w:x:':':y:"0',"|w<-"012",x<-['0'..'9'],y<-"03"] ``` Unfortunately `printf` requires a 19 byte `import`, so I cannot use it. [Answer] # Julia: ~~65~~ ~~64~~ 61 characters ``` [@printf("'%02d:%d0'%s ",i/2.01,i%2*3,i<47?",":"")for i=0:47] ``` ### Julia: 64 characters (Kept here to show Julia's nice `for` syntax.) ``` print(join([@sprintf("'%02d:%d0'",h,m*3)for m=0:1,h=0:23],", ")) ``` [Answer] # Fortran 96 ``` do i=0,46;print'(a1,i2.2,a,i2.2,a2)',"'",i/2,":",mod(i,2)*30,"',";enddo;print'(a)',"'23:30'";end ``` Standard abuse of types & requirement only for the final `end` for compiling. Sadly, due to implicit formatting, the `'(a)'` in the final `print` statement is required. Still, better than the C and C++ answers ;) [Answer] # JavaScript (ES6), 77 86+1 bytes Didn't realize there had to be quotes on each line (+1 is for `-p` flag with node): ``` "'"+Array.from(Array(48),(d,i)=>(i>19?"":"0")+~~(i/2)+":"+3*(i&1)+0).join("',\n'")+"'" ``` old solution: ``` Array.from(Array(48),(d,i)=>~~(i/2).toFixed(2)+":"+3*(i&1)+"0").join(",\n") ``` ungolfed version (using a for loop instead of `Array.from`): ``` var a = []; // there are 48 different times (00:00 to 23:30) for (var i = 0; i < 48; i++) { a[i] = (i > 19 ? "" : "0") + // just a ternary to decide whether to pad // with a zero (19/2 is 9.5, so it's the last padded number) ~~(i/2) + // we want 0 to 24, not 0 to 48 ":" + // they all then have a colon 3*(i&1) + // if i is odd, it should print 30; otherwise, print 0 "0" // followed by the last 0 } console.log(a.join(",\n")); ``` [Answer] # [golflua](http://mniip.com/misc/conv/golflua/) ~~52~~ 51 chars ``` ~@n=0,47w(S.q("'%02d:%d0'%c",n/2,n%2*3,n<47&44|0))$ ``` Using ascii 44 = `,` and 0 a space saves a character. An ungolfed Lua version would be ``` for h=0,47 do print(string.format("'%02d:%d0'%c",h/2,h%2*3, if h<47 and 44 or 0)) end ``` The `if` statement is much like the ternary operator `a > b ? 44 : 0`. [Answer] # C# - 120 bytes ``` class P{static void Main(){for(var i=0;i<24;i++)System.Console.Write("'{0:00}:00',\n'{0:00}:30'{1}\n",i,i==23?"":",");}} ``` [Answer] # Python, ~~60 58~~ 64 bytes ``` for i in range(24):print("'%02d:00,\n%02d:30'"%(i,i)+', '[i>22]) ``` Ungolfed: ``` for i in range(24): if i <23: print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30,') else: print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30') ``` Try it online [here](http://repl.it/nBQ/5). [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ, 39 chars / 67 bytes (non-competing) ``` โ€šรœโˆซ;ยทโˆร„โ€šรŸโˆซ<ยทโˆโˆž;)ยทยตรฑ`'โ€šยถร‰ยทโˆร„<ยทโˆรฎ?0:โ€šยจร˜}โ€šยถร‰0|ยทโˆร„/2}:โ€šยถร‰ยทโˆร„%2*3}0',โ€šร„รน ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=&code=%E2%86%BA%3B%E1%B8%80%E2%A7%BA%3C%E1%B8%B0%3B%29%E1%B5%96%60%27%E2%A6%83%E1%B8%80%3C%E1%B8%94%3F0%3A%E2%AC%AF%7D%E2%A6%830%7C%E1%B8%80%2F2%7D%3A%E2%A6%83%E1%B8%80%252*3%7D0%27%2C%E2%80%9D)` *Not a single alphabetical character in sight...* [Answer] # PHP, 69 70 62 bytes ``` for($x=-1;++$x<47;)printf("'%02d:%d0', ",$x/2,$x%2*3)?>'23:30' ``` [Try it online](https://3v4l.org/j44mV) Outputting `'23:30'` at the end is a bit lame, and so is closing the php context using `?>` without opening or re-opening it. An cleaner alternative (but 65 bytes) would be: ``` for($x=-1;++$x<48;)printf("%s'%02d:%d0'",$x?", ":'',$x/2,$x%2*3); ``` [Try it online](https://3v4l.org/JfJ3C) Thank you @Dennis for the tips. Alternative inspired by the contribution of @ismael-miguel. [Answer] # Swift, 74 bytes Updated for Swift 2/3...and with new string interpolation... ``` for x in 0...47{print("'\(x<20 ?"0":"")\(x/2):\(x%2*3)0'\(x<47 ?",":"")")} ``` [Answer] # Javascript, 89 bytes ``` for(i=a=[];i<24;)a.push((x="'"+("0"+i++).slice(-2))+":00'",x+":30'");alert(a.join(",\n")) ``` [Answer] ## Python 2: 64 bytes ``` print ',\n'.join(['%02d:00,\n%02d:30'%(h,h) for h in range(24)]) ``` [Answer] **Ruby - 52 bytes** ``` puts (0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*", " ``` [Answer] # Python 2, ~~74~~ 65 bytes We generate a 2 line string for each hour, using text formatting: ``` print',\n'.join("'%02u:00',\n'%02u:30'"%(h,h)for h in range(24)) ``` This code is fairly clear, but the clever indexing and integer maths in the answer by Sp3000 gives a shorter solution. ]
[Question] [ If you express some positive integer in binary with no leading zeros and replace every `1` with a `(` and every `0` with a `)`, then will all the parentheses match? In most cases they won't. For example, 9 is `1001` in binary, which becomes `())(`, where only the first two parentheses match. But sometimes they will match. For example, 44 is `101100` in binary, which becomes `()(())`, where all the left parentheses have a matching right parenthesis. Write a program or function that takes in a positive **base ten** integer and prints or returns a [truthy](https://codegolf.meta.stackexchange.com/a/2194/26997) value if the binary-parentheses version of the number has all matching parentheses. If it doesn't, print or return a [falsy](https://codegolf.meta.stackexchange.com/a/2194/26997) value. **The shortest code in bytes wins.** [Related OEIS sequence.](https://oeis.org/A014486) Truthy examples below 100: ``` 2, 10, 12, 42, 44, 50, 52, 56 ``` Falsy examples below 100: ``` 1, 3, 4, 5, 6, 7, 8, 9, 11, 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, 43, 45, 46, 47, 48, 49, 51, 53, 54, 55, 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 ``` [Answer] # Pyth, 10 bytes ``` !uscG`T.BQ ``` Try [this test suite](https://pyth.herokuapp.com/?code=%21uscG%60T.BQ&test_suite=1&test_suite_input=2%0A10%0A12%0A42%0A44%0A50%0A52%0A56%0A1%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A11%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30%0A31%0A32%0A33%0A34%0A35%0A36%0A37%0A38%0A39%0A40%0A41%0A43%0A45%0A46%0A47%0A48%0A49%0A51%0A53%0A54%0A55%0A57%0A58%0A59%0A60%0A61%0A62%0A63%0A64%0A65%0A66%0A67%0A68%0A69%0A70%0A71%0A72%0A73%0A74%0A75%0A76%0A77%0A78%0A79%0A80%0A81%0A82%0A83%0A84%0A85%0A86%0A87%0A88%0A89%0A90%0A91%0A92%0A93%0A94%0A95%0A96%0A97%0A98%0A99&debug=0) in the Pyth Compiler. ### How it works ``` (implicit) Store the evaluated input in Q. .BQ Return the binary string representation of Q. u Reduce w/base case; set G to .BQ and begin a loop: `T Return str(10) = "10". cG Split G (looping variable) at occurrences of "10". s Join the pieces without separators. Set G to the returned string. If the value of G changed, repeat the loop. This will eventually result in either an empty string or a non-empty string without occurrences of "10". ! Return (and print) the logical NOT of the resulting string. ``` [Answer] # JavaScript (ES6), ~~55~~ ~~54~~ 51 bytes ``` n=>![...n.toString(d=2)].some(c=>(d+=c*2-1)<2)*d==2 ``` Saved bytes thanks to [@Vโ€ฆโ„ขย รบยทยฅร„โ€ฆยฅ](https://codegolf.stackexchange.com/users/40695/v%C9%AA%CA%9C%E1%B4%80%C9%B4) and [@xsot](https://codegolf.stackexchange.com/users/45268/xsot)! ## Explanation ``` n=> ![...n.toString( // convert the input to an array of binary digits d=2)] // d = current depth (+2) .some(c=> // iterate through the digits (d+=c*2-1) // increment or decrement the parenthesis depth <2 // if the depth goes negative, return false )* d==2 // if we finished at a depth of 0, return true ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 9 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ~~16 18 20 22 24~~ *Saved 2 bytes thanks to @ETHproductions* ``` !xโˆšโˆ‘W(n,ยฌยข) ``` Woah. That's short. Uses @xnor's approach. This will use the recursive replace function (`W`) which will replace all `10` equal to `()` with nothing. If the string is blank it is balanced. --- Using a version of TeaScript made after this challenge was posted this could become **7 bytes:** ``` !xโˆšโˆ‘W(n) ``` ### Ungolfed ``` !xT(2)W(n,``) ``` ### Explanation ``` ! // NOT, returns true if empty string, else false xT(2) // To binary W(n,``) // n is 10, reclusive replaces 10 or (), with nothing. ``` [Answer] # Python2, 87 bytes ``` try:exec"print 1,"+"".join(["],","["][int(c)]for c in bin(input())[2:]) except:print 0 ``` A terrible implementation that abuses syntax errors. [Answer] ## Python 2, 45 bytes ``` f=lambda n,i=1:i*n>0<f(n/2,i+(-1)**n)or n<i<2 ``` A recursive function. Reads binary digits of `n` from the end, keeping a count `i` of the current nesting level of the parens. If it falls below `0`, reject. When we reach the start, checks whether the count is `0`. Actually, we start the count at `i=1` to make it easy to check if it has fallen to `0`. The only terminal success case is `n==0` and `i==1`, checked with `n<i<2`. We force this check to happen if `n==0`, or if `i` falls to `0`, in which case it automatically fails. feersum saved two bytes by restructuring the non-recursive cases with inequalities to short-circuit. [Answer] # CJam, 11 bytes ``` ri2b"}{"f=~ ``` This is a tad unclean: For parenthifiable numbers, it will print one or more blocks. For non-parenthifiable numbers, it will crash without printing anything to STDOUT. If you try this online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri2b%22%7D%7B%22f%3D~&input=56), keep in mind that it doesn't distinguish between STDOUT and STDERR. Since non-empty/empty strings are truthy/falsy in CJam and printed output is always a string, it arguably complies with the rules. At the added cost of 3 more bytes, for a total of **14 bytes**, we can actually leaves a truthy or falsy *string* on the stack that will be printed: ``` Lri2b"}{"f=~]s ``` This still crashes for non-parenthifiable numbers, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781). ### Test runs ``` $ cjam <(echo 'ri2b"}{"f=~') <<< 52 2>&-; echo {{}{}} $ cjam <(echo 'ri2b"}{"f=~') <<< 53 2>&-; echo $ cjam <(echo 'ri2b"}{"f=~') <<< 54 2>&-; echo $ cjam <(echo 'ri2b"}{"f=~') <<< 55 2>&-; echo $ cjam <(echo 'ri2b"}{"f=~') <<< 56 2>&-; echo {{{}}} ``` ### How it works ``` ri e# Read an integer from STDIN. 2b e# Push the array of its binary digits. "}{"f= e# Replace 0's with }'s and 1's with {'s. ~ e# Evaluate the resulting string. e# If the brackets match, this pushes one or more blocks. e# If the brackets do not match, the interpreter crashes. ``` --- # CJam, 15 bytes ``` ri2bs_,{As/s}*! ``` Try [this fiddle](http://cjam.aditsu.net/#code=ri2bs_%2C%7BAs%2Fs%7D*!&input=56) in the CJam interpreter or [verify all test cases at once](http://cjam.aditsu.net/#code=q'%2C-~%5D%7B%0A%20%20Ri2bs_%2C%7BAs%2Fs%7D*!%0A%7DfR&input=2%2C%2010%2C%2012%2C%2042%2C%2044%2C%2050%2C%2052%2C%2056%0A1%2C%203%2C%204%2C%205%2C%206%2C%207%2C%208%2C%209%2C%2011%2C%2013%2C%2014%2C%2015%2C%2016%2C%2017%2C%2018%2C%2019%2C%2020%2C%2021%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%2C%2037%2C%2038%2C%2039%2C%2040%2C%2041%2C%2043%2C%2045%2C%2046%2C%2047%2C%2048%2C%2049%2C%2051%2C%2053%2C%2054%2C%2055%2C%2057%2C%2058%2C%2059%2C%2060%2C%2061%2C%2062%2C%2063%2C%2064%2C%2065%2C%2066%2C%2067%2C%2068%2C%2069%2C%2070%2C%2071%2C%2072%2C%2073%2C%2074%2C%2075%2C%2076%2C%2077%2C%2078%2C%2079%2C%2080%2C%2081%2C%2082%2C%2083%2C%2084%2C%2085%2C%2086%2C%2087%2C%2088%2C%2089%2C%2090%2C%2091%2C%2092%2C%2093%2C%2094%2C%2095%2C%2096%2C%2097%2C%2098%2C%2099). ### How it works ``` ri Read an integer from STDIN. 2b Push the array of its binary digits. s Cast to string. _, Push the string's length. { }* Do that many times: As/ Split at occurrences of "10". s Cast to string to flatten the array of strings. ! Push the logical NOT of the result. ``` [Answer] ## Python, 51 bytes ``` lambda n:eval("'0b'==bin(n)"+".replace('10','')"*n) ``` An anonymous function. Evaluates to an expression that looks like ``` '0b'==bin(n).replace('10','').replace('10','').replace('10','')... ``` Each replacement removes all `10`, which correspond to `()`. After all replacements have been made, the function returns whether what's left is just the binary prefix `0b`. It more than suffices to make `n` replacements, since a `k`-digit number takes at most `k/2` steps, and its value is most `2**k`. [Answer] # Ruby, 40 ``` ->i{n='%0b'%i;1while n.slice!'10';n<?0} ``` Simple string manipulation. Drops '10' until there is none left. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ยฌยงeA ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=pGVB&input=Mg) ``` ยฌยงeA :Implicit input of integer ยฌยง :To binary string e :Recursively replace A : 10 :Implicit output of logical NOT of final string (the empty string is falsey, all others are truthy) ``` [Answer] # JavaScript ES5, ~~118~~ ~~87~~ ~~85~~ ~~82~~ 77 bytes Interesting technique in my opinion. Minus a whole heck of a lot, thanks to @ETHproductions, and @NotthatCharles ``` function p(x){x=x.toString(2);while(/10/.test(x))x=x.replace(10,"");return!x} ``` ## JavaScript ES6, ~~77~~ ~~57~~ ~~56~~ 54 bytes -21 bytes to ETHproductions. ``` x=>[...x=x.toString(2)].map(_=>x=x.replace(10,""))&&!x ``` [Answer] ## [Seriously](https://github.com/Mego/Seriously), 17 bytes ``` ,;2@ยฌยฐ@`""9u$(โˆšรœ`nY ``` Outputs `0` for false and `1` for true. [Try it online](http://seriouslylang.herokuapp.com/link/eyJjb2RlIjoiLDsyQMKhQGBcIlwiOXUkKMOGYG5ZIiwiaW5wdXQiOiI0NCJ9). Explanation: ``` , get value from stdin ; dupe top of stack 2@ยฌยฐ pop a: push a string containing the binary representation of a (swapping to get order of operands correct) @ swap top two elements to get original input back on top `""9u$(โˆšรœ` define a function: "" push empty string 9u$ push "10" (push 9, add 1, stringify) ( rotate stack right by 1 โˆšรœ pop a,b,c: push a.replace(b,c) (replace all occurrences of "10" in the binary string with "") n pop f,a: call f a times Y pop a: push boolean negation of a (1 if a is falsey else 0) ``` [Answer] # Japt, 23 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` Us2 a e@+X?++P:P-- &&!P ``` This reminds me just how far Japt has yet to go compared to TeaScript. After revamping the interpreter in the next few days, I'd like to add in "shortcut" chars like Vโ€ฆโ„ขย รบยทยฅร„โ€ฆยฅ's. ### How it works ``` // Implicit: U = input number, P = empty string Us2 a // Convert U to base 2, then split the digits into an array. e@ // Assert that every item X in this array returns truthily to: +X? // If X = 1, ++P // ++P. ++(empty string) returns 1. :P-- // Otherwise, P--. Returns false if P is now -1. &&!P // Return the final result && !P (true if P is 0; false otherwise). // Implicit: output final expression ``` --- Shortly after this challenge, @Vโ€ฆโ„ขย รบยทยฅร„โ€ฆยฅ (now known as @Downgoat) helped me implement a recursive-replace feature, like `W` in the TeaScript answer. This means that this challenge can now be done in just 5 bytes: ``` !ยฌยขeAs // Implicit: U = input integer, A = 10 ยฌยข // Convert U to binary. eAs // Recursively remove instances of A.toString(). ! // Return the logical NOT of the result (true only for the empty string). ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=IaJlQXM=&input=NTY=) [Answer] # Octave, 48 bytes ``` @(a)~((b=cumsum(2*dec2bin(a)-97))(end)|any(b<0)) ``` [Answer] ## C++, 104 94 bytes ``` #include<iostream> int n,c;int main(){for(std::cin>>n;n&c>=0;n>>=1)c+=n&1?-1:1;std::cout<<!c;} ``` Run with [this compiler](http://ideone.com), must specify standard input before running. **Explanation** * Declarations outside of main initialize to 0. * Reading a decimal implicitly converts to binary, because this is a computer. * We check bits/parenthesis *right to left* because of `n>>=1`. * `c+=n&1?-1:1` keeps count of open parenthesis `)`. * `n&c>=0` stops when only leading 0s remain or parenthesis close more than they open. [Answer] ## Haskell, ~~49~~ 46 bytes ``` 0#l=l==1 _#0=2<1 n#l=div n 2#(l+(-1)^n) f=(#1) ``` Usage example: `f 13` -> `False`. I'm keeping track of the nesting level `l` like many other answers. However, the "balanced" case is represented by `1`, so the "more-`)`-than-`(`" case is `0`. PS: found the nesting level adjustment `l+(-1)^n` in xnor's [answer](https://codegolf.stackexchange.com/a/64018/34531). [Answer] # Python 2, ~~60~~ ~~57~~ ~~56~~ ~~55~~ ~~53~~ ~~52~~ ~~50~~ 49 bytes ``` n=input() i=1 while i*n:i+=1|n%-2;n/=2 print i==1 ``` Thanks to xnor for saving two bytes and feersum for bringing the final byte count to 49! ### Explanation The input number, `n`, is processed from its least significant bit. `i` is a counter that keeps track of the number of 0's and 1's. Note that it is initialised to `1` to save a byte. The loop will abort before `n` reaches 0 if the number of 1's exceed the number of 0's (`i<=0`). For the parentheses to be balanced, two conditions are required: * The number of 0's and 1's are equal (i.e. `i==1`) * The number of 1's never exceeds the number of 0's during this process (i.e the loop doesn't abort prematurely so `n==0`). Edit: I realised that this condition isn't necessary as `i` must be non-positive if `n!=0` so the previous condition is sufficient. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes ``` k/ล“ร‘k/ยทฯ€รฒยซรซยซรญ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=k%2F%CF%84k%2F%E1%B9%98%C7%91%C7%92&inputs=%5B2%2C%2010%2C%2012%2C%2042%2C%2044%2C%2050%2C%2052%2C%2056%2C%201%2C%203%2C%204%2C%205%2C%206%2C%207%2C%208%2C%209%2C%2011%2C%2013%2C%2014%2C%2015%2C%2016%2C%2017%2C%2018%2C%2019%2C%2020%2C%2021%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%2C%2037%2C%2038%2C%2039%2C%2040%2C%2041%2C%2043%2C%2045%2C%2046%2C%2047%2C%2048%2C%2049%2C%2051%2C%2053%2C%2054%2C%2055%2C%2057%2C%2058%2C%2059%2C%2060%2C%2061%2C%2062%2C%2063%2C%2064%2C%2065%2C%2066%2C%2067%2C%2068%2C%2069%2C%2070%2C%2071%2C%2072%2C%2073%2C%2074%2C%2075%2C%2076%2C%2077%2C%2078%2C%2079%2C%2080%2C%2081%2C%2082%2C%2083%2C%2084%2C%2085%2C%2086%2C%2087%2C%2088%2C%2089%2C%2090%2C%2091%2C%2092%2C%2093%2C%2094%2C%2095%2C%2096%2C%2097%2C%2098%2C%2099%2C%20170%2C%20172%2C%20178%2C%20180%2C%20184%2C%20202%2C%20204%2C%20210%2C%20212%2C%20216%2C%20226%2C%20228%2C%20232%2C%20240%2C%20682%2C%20684%2C%20690%2C%20692%2C%20696%2C%20714%2C%20716%2C%20722%2C%20724%2C%20728%2C%20738%2C%20740%2C%20744%2C%20752%2C%20810%2C%20812%2C%20818%2C%20820%2C%20824%2C%20842%2C%20844%2C%20850%2C%20852%2C%20856%2C%20866%2C%20868%2C%20872%2C%20880%5D&header=%CE%BB&footer=%3Bz) Fortunately, Vyxal has a remove-substring-until-fixed-point builtin. Unfortunately, it only works on strings. ``` k/ล“ร‘ Convert input to base "/\". (only string constant of length 2) ยซรซ Until it is no longer present as a substring, remove k/ "/\" ยทฯ€รฒ reversed. ยซรญ Is the result empty? ``` Originally did some fancy dancing with stack rotations in Vyxal `r`, but it turned out the same length flagless to just use `k/` twice. I'm not having the best luck putting a solution together without replacement, but it doesn't seem like it could come out shorter. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` TrueQ[And@@#~IntegerDigits~2//.1&&0:>1>0]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z@kqDQ1MNoxL8XBQbnOM68kNT21yCUzPbOkuM5IX1/PUE3NwMrO0M4gVu1/QFFmXkl0cGpOanJJdFBiXnqqg6GBgY5CWmzsfwA "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes ``` (#~IntegerDigits~2//.{x___,1,0,y___}:>{x,y})=={}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Duc4zryQ1PbXIJTM9s6S4zkhfX6@6Ij4@XsdQx0CnEsiotbKrrtCprNW0ta2uVfsfUJSZVxIdnJqTmlwSHZSYl57qYGhgoKOQFhv7HwA "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~[6](https://codegolf.stackexchange.com/revisions/260196/1)~~ 5 bytes ``` ล’โ€ โ€šร‡ร„โˆšโˆoยฌยจ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBIiwiIiwizqDigoDDuG/CrCIsIiIsIjJcbjEwXG4xMlxuNDJcbjQ0XG41MFxuNTJcbjU2XG4xXG4zIFxuNFxuNSBcbjYgXG43XG45NlxuOTdcbjk4XG45OSJd) ``` ล’โ€  # push the binary of the input โ€šร‡ร„ # push 10 โˆšโˆo # remove ^ until no change ยฌยจ # logical NOT ``` [Answer] # D, ~~209~~ 170 bytes ``` import std.stdio;import std.format;import std.conv;void main(char[][]a){string b=format("%b",to!int(a[1]));int i;foreach(c;b){i+=c=='1'?1:-1;if(i<0)break;}writeln(i==0);} ``` This does exactly what it is supposed to do without any additions or benefits. [Answer] # C, 67 bytes ``` n;main(i){for(scanf("%d",&n);n*i;n/=2)i+=1-n%2*2;putchar(48+!~-i);} ``` Pretty much a port of my python submission. [Answer] # Prolog, 147 bytes ``` b(N,[X|L]):-N>1,X is N mod 2,Y is N//2,b(Y,L). b(N,[N]). q([H|T],N):-N>=0,(H=0->X is N+1;X is N-1),q(T,X). q([],N):-N=0. p(X):-b(X,L),!,q(L,0). ``` **How it works** ``` b(N,[X|L]):-N>1,X is N mod 2,Y is N//2,b(Y,L). b(N,[N]). ``` Converts decimal number N to it's binary representation as a list (reversed). Meaning: ``` b(42,[0,1,0,1,0,1]) is true ``` Then: ``` q([H|T],N):-N>=0,(H=0->X is N+1;X is N-1),q(T,X). q([],N):-N=0. ``` Recurses over list [H|T] increasing N if head element is 0 otherwise decreasing it. If N at any point becomes negative or if N in the end is not 0 return false, else true. The cut in ``` p(X):-b(X,L),!,q(L,0). ``` Is there to prevent backtracking and finding non-binary solutions to b(N,[N]) **Testing** Try it out online [here](http://swish.swi-prolog.org/) Run it with a query like: ``` p(42). ``` [Answer] ## PowerShell, 106 Bytes ``` param($a)$b=[convert]::ToString($a,2);1..$b.Length|%{if($b[$_-1]%2){$c++}else{$c--}if($c-lt0){0;exit}};!$c ``` Not going to win any shortest-length competitions, that's for sure. But hey, at least it's beating Java? Uses the very long .NET call `[convert]::ToString($a,2)` to convert our input number to a string representing the binary digits. We then for-loop through that string with `1..$b.length|%{..}`. Each loop, if our digit is a `1` (evaluated with `%2` rather than `-eq1` to save a couple bytes), we increment our counter; else, we decrement it. If we ever reach negative, that means there were more `)` than `(` encountered so far, so we output `0` and `exit`. Once we're through the loop, `$c` is either `0` or some number `>0`, so we take the logical-not `!` of it, which gets output. This has the quirk of outputting `0` if the parens are mismatched because we have more `)`, but outputting `False` if the parens are mismatched because we have more `(`. Essentially functionally equivalent falsy statements, just interesting. If the parens all match, outputs `True`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` B-*โˆšร‘ยทฯ€ร„oยทฯ€โ„ขโˆ†รคยฌยจ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//Qi0qw4ThuYBv4bmqxorCrP/ItzIsw4dLxorigqxZ/w "Jelly โ€šร„รฌ Try It Online") ``` B Convert to binary. -* Raise -1 to the power of each digit. โˆšร‘ โˆ†รค For the cumulative sums of the resulting list: o ยฌยจ neither ยทฯ€ร„ is its maximum non-zero ยทฯ€โ„ข nor is its last element. ``` Replacement came out a bit longer: # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Bยฌยจโ‰ˆรฌยทฯ€ยฃโˆšรฒ.ยทโˆซรฉ$โˆšรชLยทฯ€รœ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//QsKsxZPhuaPDmC7huo4kw5BM4bmG/8i3MizDh0vGiuKCrFn/ "Jelly โ€šร„รฌ Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~74~~ 72 bytes ``` for($t=[convert]::ToString("$args",2);$r-ne($t=$t-replace10)){$r=$t} !$t ``` [Try it online!](https://tio.run/##RY3dToNAEIWv2adYmtFAAg00xYs2JCZ9AI30rmkaXIe2BlmcHfwJ8uw4mKoXJ/NzznzT2nckd8K6jo0lHKHK@7GyFADnO2ObNyTer1ZbWzCdm2Mwg5KObhYtwjVQ3OCUA44J27o0mCZh2APJZlA@8DgoBUwdnz51rheRThOR1OWkZaQzmTPpsxul0vk8TZKvq155gB8tGsYnuYKDjs@NvmDEI3RdzeL4fnANlQRC5e3ui03n2L7cPT7L5V7fCsYrOmPQuYnyR4zxVV8Ya4ls0fGmdPjzaVo8/OL/Q4Maxm8 "PowerShell Core โ€šร„รฌ Try It Online") ## Explanations ``` for( $t=[convert]::ToString("$args",2); # converts the given argument to a binary string $r-ne($t=$t-replace10)){$r=$t} # Until we can't find occurences of 10, remove them from the string !$t # Returns a truthy value if empty string ``` -2 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)! [Answer] # GNU Sed (with eval extension), 27 ``` s/.*/dc -e2o&p/e : s/10// t ``` Sed doesn't really have a defined idea of truthy and falsey, so here I am claiming that the empty string means truthy and all other strings mean falsey. If this is not acceptable, then we can do the following: # GNU Sed (with eval extension), 44 ``` s/.*/dc -e2o&p/e : s/10// t s/.\+/0/ s/^$/1/ ``` This outputs 1 for truthy and 0 otherwise. [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ (ESMin), 21 chars / 43 bytes ``` โˆšยฅโ€šรผยถโˆšร˜โˆšรผยทโˆร‡]ฦ’ร โ€šรกร„+$?โ€šรŸโˆซยทโˆร„:ยทโˆร„โ€šร„ยฐ)โ€šร–รฃ!ยทโˆร„) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=10&code=%C3%B4%E2%9F%A6%C3%AF%C3%9F%E1%B8%82%5D%C4%88%E2%87%80%2B%24%3F%E2%A7%BA%E1%B8%80%3A%E1%B8%80%E2%80%A1%29%E2%85%8B!%E1%B8%80%29)` Note that this uses variables predefined to numbers (specifically 2 and 0). There are predefined number variables from 0 to 256. ## 19 chars / 40 bytes, non-competitive ``` โ€šรผยถโˆšร˜โˆšรผยทโˆร‡]ฦ’ร โ€šรกร„+$?โ€šรŸโˆซยทโˆร„:ยทโˆร„โ€šร„ยฐ)โ€šร–รฃ!ยทโˆร„ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=10&code=%E2%9F%A6%C3%AF%C3%9F%E1%B8%82%5D%C4%88%E2%87%80%2B%24%3F%E2%A7%BA%E1%B8%80%3A%E1%B8%80%E2%80%A1%29%E2%85%8B!%E1%B8%80)` Decided to implement implicit output... However, previous output forms are still supported, so you get several output options! [Answer] ## Java, ~~129~~ 131 bytes ``` boolean T(int i){int j=0,k=0;for(char[]a=Integer.toString(i,2).toCharArray();j<a.length&&k>=0;j++){k+=a[j]=='1'?1:-1;}return k==0;} ``` Probably can be shortened. Explanation to come. Thanks to Geobits for 4 bytes off! [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ (very noncompetitve), 6 chars / 8 bytes ``` !โˆšร˜โ€šรฌรซฦ’ยถโ€šร–ยฉ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=11&code=!%C3%AF%E2%93%91%C4%A6%E2%85%A9)` I've decided to revisit this challenge after a very, very long time. ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ has gotten so much better. The reason this is a separate answer is because the 2 versions are almost completely different. # Explanation Converts input to binary, recursively replaces instances of 10, then checks if result is an empty string. [Answer] # C++, 61 bytes I think the current C++ answer is wrong: it returns a truthy value for all even numbers, e.g. 4. Disclaimer: I was not able to use the mentioned compiler, so I used g++ 4.8.4. The problem lies in the use of the binary AND operator instead of the logical AND which is used to break early when the number of closing parentheses exceed the number of opening parentheses. This approach could work if `true` is represented as a word with an all true bit pattern. On my system, and probably most other systems, `true` is equivalent to `1`; only one bit is true. Also, `n/=2` is shorter than `n>>=1`. Here is an improved version as a function: ``` int f(int n,int c=0){for(;c>=0&&n;n/=2)c+=n&1?-1:1;return c;} ``` ]
[Question] [ Your challenge is to, given a positive integer n, count up to each digit of it, giving the effect of converging on it. Basically, count up to the first digit of n by its place value (\$โ€šรฅรค\log\_{10}\left(x\right)โ€šรฅรฃ\$). Then do the same for each subsequent digit, but with the values of the previous digits added. Example implementation (animated): ``` function count(){ let countTo = document.getElementById('number').value.toString().split``,output = document.getElementById('x'); let numbers = [], accumulator = 0; countTo.map((value, index) => { for(let i = 0; i < +value; i++){ accumulator += 10 ** (countTo.length - index - 1) numbers.push(accumulator) } }); //document.getElementById('y').innerHTML = 'All values:<br>' + numbers.join`<br>`; (function next(){let nextVal = numbers.shift();if(nextVal){output.innerHTML = nextVal;setTimeout(next,300)}})() } ``` ``` p{font-family:monospace} ``` ``` <label for=number>Number: </label><input id=number type=number> <button onclick=count()>Count!</button><p id=x></p><p id=y></p> ``` You should just return an array of numbers - for n=47: ``` 10 20 30 40 41 42 43 44 45 46 47 ``` You may optionally have leading zeroes. IO may be strings, numbers, digit lists, etc. Testcases: ``` 4 => [1, 2, 3, 4] 16 => [10, 11, 12, 13, 14, 15, 16] 35 => [10, 20, 30, 31, 32, 33, 34, 35] 103 => [100, 101, 102, 103] 320 => [100, 200, 300, 310, 320] 354 => [100, 200, 300, 310, 320, 330, 340, 350, 351, 352, 353, 354] 1000 => [1000] 1001 => [1000, 1001] 3495 => [1000, 2000, 3000, 3100, 3200, 3300, 3400, 3410, 3420, 3430, 3440, 3450, 3460, 3470, 3480, 3490, 3491, 3492, 3493, 3494, 3495] 4037 => [1000, 2000, 3000, 4000, 4010, 4020, 4030, 4031, 4032, 4033, 4034, 4035, 4036, 4037] 84958320573493 => [10000000000000, 20000000000000, 30000000000000, 40000000000000, 50000000000000, 60000000000000, 70000000000000, 80000000000000, 81000000000000, 82000000000000, 83000000000000, 84000000000000, 84100000000000, 84200000000000, 84300000000000, 84400000000000, 84500000000000, 84600000000000, 84700000000000, 84800000000000, 84900000000000, 84910000000000, 84920000000000, 84930000000000, 84940000000000, 84950000000000, 84951000000000, 84952000000000, 84953000000000, 84954000000000, 84955000000000, 84956000000000, 84957000000000, 84958000000000, 84958100000000, 84958200000000, 84958300000000, 84958310000000, 84958320000000, 84958320100000, 84958320200000, 84958320300000, 84958320400000, 84958320500000, 84958320510000, 84958320520000, 84958320530000, 84958320540000, 84958320550000, 84958320560000, 84958320570000, 84958320571000, 84958320572000, 84958320573000, 84958320573100, 84958320573200, 84958320573300, 84958320573400, 84958320573410, 84958320573420, 84958320573430, 84958320573440, 84958320573450, 84958320573460, 84958320573470, 84958320573480, 84958320573490, 84958320573491, 84958320573492, 84958320573493] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` DLยทโˆโˆ‚Uโ€šร…ยต*xDโˆšร‘ ``` [Try it online!](https://tio.run/##y0rNyan8/9/F5@GObaGPGrdqVbgcbvn//7@FiaWphbGRgam5sYmlMQA "Jelly โ€šร„รฌ Try It Online") ``` DL Digits, length ยทโˆโˆ‚Uโ€šร…ยต* Compute [10^(n-1), โ€šร„ยถ, 10, 1] xD Use the digits as repeat counts for this array e.g. 423 -> [100, 100, 100, 100, 10, 10, 1, 1, 1] โˆšร‘ Cumulative sum: [100, 200, 300, 400, 410, 420, 421, 422, 423] ``` [Answer] # JavaScript (ES6), ~~ยฌโ€ 48ยฌโ€ ~~ 46 bytes ``` f=(n,k=1)=>n?n%k?[...f(n-k/10),n]:f(n,k*10):[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfb1lDT1i7PPk812z5aT08vTSNPN1vf0EBTJy/WKg2kQAvIsYqO/Z@cn1ecn5Oql5OfrpGmYaKpyYUqYmiGIWRsiqnKwBhTmZEBFq1YbDAwMMAmaKip@R8A "JavaScript (Node.js) โ€šร„รฌ Try It Online") ### How? Instead of going from \$0\$ to \$n\$, we go from \$n\$ to \$0\$ and store the intermediate steps in reverse order. At each step, we start with \$k=1\$ and recursively multiply \$k\$ by \$10\$ until \$n\bmod k\neq 0\$, which is a way to locate the least significant non-zero digit in \$n\$. We decrement this digit by subtracting \$k/10\$ from \$n\$ and repeat the process until \$n=0\$. --- # JavaScript (ES6), 49 bytes This version expects a string and uses a lookahead assertion to locate and decrement the least significant non-zero digit. ``` f=n=>+n?[...f(n.replace(/.(?=0*$)/,c=>c-1)),n]:[] ``` [Try it online!](https://tio.run/##bc1BDoIwEIXhvccgLmYUhqmoC5LCQQiLprZG00wJEK9fXZvZfvnz3tt93ObX17I3kh@hlGjFDmcZJyKKILSGJTkfoCUYLZ@O2NbeDr4xiLXM/TQXn2XLKVDKT4hQXSvEw5@Zu4LdTSu509ILqwPqFzPrbH5cvg "JavaScript (Node.js) โ€šร„รฌ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes *Thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) for 2 bytes off, and to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for pointing out that the input can be an integer instead of an array* ``` ฦ’ร…<Rยฌโˆžยฌฯ€โˆšร–ล’รฌล’โˆ‘O ``` Port of [Lynn's answer](https://codegolf.stackexchange.com/a/238613/36398). [**Try it online!**](https://tio.run/##yy9OTMpM/f//SKNN0KENh3Yebj03@dx2////jU1NAA) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes *Port of [Lynn's solution](https://codegolf.stackexchange.com/a/238613/43319) โ€šร„รฌ upvote that!* Anonymous prefix lambda, taking a digit list as argument and returning a numeric list. Requires 0-based indexing. ``` {+\โ€šรงยต/10*โ€šรฅฮฉโ€šรงโ‰ฅโ€šรขยขโ€šรงยต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGCo@6WxSAvIAAIM/Q/H@1dsyj3q36hgZaj3r2Purd/KhzEZBf@z8NKP2ot@9RV/Oj3jWPerccWm/8qG0iUGNwkDOQDPHwDP6fpmDClaZgqGAGJI0VTMFsAwVjMM9IwQAiClVjAIJwliFYzkTBEqwLwgKJmYD0K5gDWRYQWSANNgvIMoeqMwYA "APL (Dyalog Unicode) โ€šร„รฌ Try It Online") `{`โ€šร„ยถ`}`โ€šร„ร‰"dfn"; argument is `โ€šรงยต`: โ€šร„ร‰`+\`โ€šร„ร‰cumulative sum ofโ€šร„ยถ โ€šร„ร‰`โ€šรงยต/`โ€šร„ร‰the argument numbers replicating the respective numbers inโ€šร„ยถ โ€šร„ร‰`10*`โ€šร„ร‰ten raised to the powers ofโ€šร„ยถ โ€šร„ร‰`โ€šรฅฮฉ`โ€šร„ร‰the reversedโ€šร„ยถ โ€šร„ร‰`โ€šรงโ‰ฅ`โ€šร„ร‰indices in an array of sizeโ€šร„ยถ โ€šร„ร‰`โ€šรขยข`โ€šร„ร‰tally of elements inโ€šร„ยถ `โ€šรงยต`โ€šร„ร‰argument --- ### Old solution: ~~24~~ 17 bytes โ€šร รญ4 thanks to ovs Full program. Prompts for digit list. ``` โ€šรœรซยฌยฎ{โ€šรงโˆซ,,ยฌยฎโ€šร รฒโ€šรงยตโ€šรคร‰โ€šรฅฮฉโ€šรงโˆซ}/โ€šรงโ‰ฅยฌยฎโ€šรฉรฏ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jtomHVlQ/6t2lo3NoxaOOGY96tz7qan7UsxcoVKv/qHczULRv6n9dXV0uoPr/CmBQwGXCBWMZKpjB2cYKpkjiBgrGSDJGCgbI6hRMUFQaIMlC@IZIqk0ULJFMhvAR8iYgmxTM4XwLiHoFCwWwrUCWgrkCRJOxAgA "APL (Dyalog Unicode) โ€šร„รฌ Try It Online") `โ€šรฉรฏ`โ€šร„ร‰prompt for digit list `โ€šรงโ‰ฅยฌยฎ`โ€šร„ร‰generate 1โ€šร„ยถn for each digit `{`โ€šร„ยถ`}/`โ€šร„ร‰reduce (from the right) using this lambda: โ€šร„ร‰`โ€šรคร‰โ€šรฅฮฉโ€šรงโˆซ`โ€šร„ร‰the last element of the left argument (lit. the first of the reverse) โ€šร„ร‰`,ยฌยฎโ€šร รฒโ€šรงยต`โ€šร„ร‰prepend that to each of the left argument elements โ€šร„ร‰`โ€šรงโˆซ,`โ€šร„ร‰prepend the left argument to that `โ€šรœรซยฌยฎ`โ€šร„ร‰combine each list of lists into a matrix, zero-padding on the right [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 37 bytes ``` {[\R+] flat (10 X**^$_)Zxx.flip.comb} ``` [Try it online!](https://tio.run/##FcrNCoJAGIXhvVdxFiJlH8NM34xjhF1Eq@hPLBoIRhRroYjXPk2bw8Ph7V@DL0I7IXOoEObL9bi5wfnmi5WSOOX5Pa3X53EUzr978ezaxxJcN0BbUgWxISWZeCsjdbSU/1HEemdIS7ZURpUxMDZ@jDkBPs2EtEZ1gMjcPlnCDw "Raku โ€šร„รฌ Try It Online") An anonymous code block that takes a number and returns an array. ### Explanation: ``` { } # Anonymous code block (10 X**^$_) # Generate powers of 10 Zxx # Zip repeat each by .flip.comb # The reversed digits of the number flat # Flatten this list [ R+] # Reduce by reverse addition \ # Keeping intermediate values ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` โˆšยถยทโˆรผโ€šร…ยตยทโˆซยฐโˆ†รคโˆ†ยจINโˆšร‘ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//w6bhuJ/igbXhuqHGisasSU7DhP///zg0OTU4MzIwNTczNDkz "Jelly โ€šร„รฌ Try It Online") 9 bytes sure seems to be special here. ``` โˆ†ยจ Collect results while unique from repeating: ยทโˆซยฐ absolute difference from โˆšยถยทโˆรผโ€šร…ยต greatest less than or equal power of 10. โˆšร‘ Take the cumulative sum of IN each amount by which it decreased. ``` # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ยทยชรงโ€šร…ยตโ€šร…ยต*ยทโˆซยฐoยฌยตโˆ†ยจU ``` [Try it online!](https://tio.run/##y0rNyan8///h7t5HjVuBSOvhroX5h7YeWxP6//9/CxNLUwtjIwNTc2MTS2MA "Jelly โ€šร„รฌ Try It Online") Conceived of independently from, but very similar to, Arnauld's solution. ``` ยฌยตโˆ†ยจ Collect results while unique from repeating: ยทยชรงโ€šร…ยต How many times does 10 evenly divide it? โ€šร…ยต* Raise 10 to that power, ยทโˆซยฐ take the absolute difference, o and keep the previous value (ending the loop) if it's 0. U Reverse. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ 57 bytes ``` f=lambda n,k=1:n%k and f(n-k/10)+[n]or n*[1]and f(n,k*10) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNy3TbHMSc5NSEhXydLJtDa3yVLMVEvNSFNI08nSz9Q0NNLWj82LzixTytKINY6ESOtlaQAmIAWsKijLzSjTSNEzMNaFCMLMB) Port of Arnauld's answer. -1 thanks to @ovs # [Python 2](https://docs.python.org/2/), ~~76~~ 64 bytes ``` x=input() c=0 i=len(x) for d in x:i-=1;exec"c+=10**i;print c;"*d ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNx0qbDPzCkpLNDS5km0NuDJtc1LzNCo0udLyixRSFDLzFCqsMnVtDa1TK1KTlZK1bQ0NtLQyrQuKMvNKFJKtlbRSIOZAjVuwPNpER8E8lgvCBQA) Port of Lynn's answer. -12 thanks to @ovs --- ## [Python 2](https://docs.python.org/2/), 74 bytes ``` x=input() o=[0]*len(x) i=0 for d in x: while o[i]<d:o[i]+=1;print o i+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN70qbDPzCkpLNDS58m2jDWK1clLzNCo0uTJtDbjS8osUUhQy8xQqrLgUyjMyc1IV8qMzY21SrECUtq2hdUFRZl6JQj6XQiaQBzERavCCZdEmOgrmsRAeAA) [Answer] # [R](https://www.r-project.org/), ~~64~~ ~~52~~ 43 bytes Or **[R](https://www.r-project.org/)>=4.1, 36 bytes** by replacing the word `function` with a `\`. *Edit: -12 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` function(d)cumsum(rep(10^(sum(d|1):1-1),d)) ``` [Try it online!](https://tio.run/##fZBBS8QwEIXv@ysCUkig4kwyaa1Q/4isIK1dPWyUam/@95p5qUs96CEfZeblvdfM69RPSxo@X9@STfXYp@qmYnq0aXh5mm1yd3zNrsojd7KjO5z69SIf3bCcP5aznZ/frd7R7/GLy516dG6drLgr09@bB66Nr02ojRwPk@XmZ0y14bzjvOS8Zckn5tOoLMSdzOcT9GR5UK8sD1keIhwpXLTqSWpK6koBVp72e09wg53CU8mT/0WaqhBFBLRN1DpR@8Tye0S7NNpGvBtpL2JkShd/LTxtsSW3BJfkEg2ikKCRlEroJCglDdiCt2BXyKAH8X6dgHhDodD@WUU2MujBUMigBwMoYAQbsD2u3w "R โ€šร„รฌ Try It Online") Yet another port of [@Lynn's answer](https://codegolf.stackexchange.com/a/238613/55372). Takes input as a vector of digits. --- ### [R](https://www.r-project.org/), 49 bytes Or **[R](https://www.r-project.org/)>=4.1, 42 bytes** by replacing the word `function` with a `\`. ``` function(n)while(n>F)show(F<-F+10^(nchar(n-F)-1)) ``` [Try it online!](https://tio.run/##fZDBasMwEETv/QpBLxK1YVe7smtocvRPlBRKqHEgKJC25PNd7cgt7qE97DvsDjMjXZdpt0yf@fhxumSfw20@nd983o/hfb7c/PjUjg9MLz4f59erz@0YWg5hmbyGe7fbu2duXGycNE4Pd5Pn7ntNjeNy43LkcmUtk8p0JpO0kcUyYlPkYl5FLkUuCY4kP1rzJDMlcyWBVaTtPRLcYGeIVPP0f5GlGtSQAGuTrE6yPqk@j2iTRuuKNyvrRYxMHdKvQ6Q1tubW4Jpco0EUUjTSWgmdFKW0A3vwERwqGYwg/m9QEH@oJP2fVXQlgxGUSgYjKKCCCezA/rB8AQ "R โ€šร„รฌ Try It Online") Direct approach inspired by [@DLosc's answer](https://codegolf.stackexchange.com/a/239640/55372). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ยทโˆซรจโ€šรœยตยทฯ€รฒZvโˆ†รญยทโˆซรฃfยฌยถ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/ihrXhuZhadsaS4bqLZsKmIiwiIiwiMjA5NSJd) Jelly porting fun [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~26~~ ~~24~~ 22 bytes ``` b:DQa#b?(fa).0ALa.\,bl ``` Requires a flag for nicely formatted list output; `-p`, `-l`, and `-s` are all good options. [Replit!](https://replit.com/@dloscutoff/pip) Or, [Try it online!](https://tio.run/##K8gs@P8/ycolMFE5yV4jLVFTz8DRJ1EvRicp5////7oF/42MTQA "Pip โ€šร„รฌ Try It Online") ### Explanation A recursive full program that returns a list: ``` b:DQa#b?(fa).0ALa.\,bl a The argument number DQ Dequeue the last digit b: and assign it to local variable b (In the base case, a was empty and b is now nil) #b? If b is a digit (thus has a nonzero length): (fa) Call the main function recursively on a .0 Concatenate 0 to the end of each number in the result AL Append this list: a. Concatenate a with each of \,b Inclusive range from 1 to b Otherwise (b is nil): l Return empty list ``` [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), 51 bytes ``` INPUT n WHILE n>g g=g+10^(LEN(STR$(n-g))-2) ?g WEND ``` [Try it at Archive.org!](https://archive.org/details/msdos_qbasic_megapack) ### Explanation We can calculate which digit we want to increment by getting the length of the difference between the input number `n` and the current number `g`: ``` 1234 -1210 ===== 24 -> length 2, increment by 10^1 ``` Since QBasic's `STR$` function adds a space to the front of nonnegative numbers, the power of 10 that we need is `LEN` minus 2. Thus, we add `10^(LEN(STR$(n-g))-2)` to `g`, print `g` (`?` is a shortcut for `PRINT`), and loop until `g` and `n` are equal. [Answer] # [C (gcc)](https://gcc.gnu.org/), 74 bytes ``` a;g(x){a=0;f(x,1);}f(x,y){y<x&&f(x,y*10);for(;a+y<=x;)printf("%d ",a+=y);} ``` [Try it online!](https://tio.run/##HYvLCoAgEADvfYUEyW4PyOi2@TGLoXToQXRQxG836zTDwJjBGZMzkwOPkfVIFnyvkNLHgDEsXsrfWzUi2fMG4i4s2hNe93Y8FupmFXXPnQ5lyyWJnbdDAMbKgZqmGalK@QU "C (gcc) โ€šร„รฌ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-F`, ~~55~~ 47 bytes ``` @a=(0)x@F;map{for$b(0..shift@F){$_=$b;say@a}}@a ``` [Try it online!](https://tio.run/##K0gtyjH9/98h0VbDQLPCwc06N7GgOi2/SCVJw0BPrzgjM63EwU2zWiXeViXJujix0iGxttYh8f9/EwNj83/5BSWZ@XnF/3V9TfUMDA3@67oBAA "Perl 5 โ€šร„รฌ Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 73 bytes ``` ,[>-[-----<-<+>>]<++++<--->>>,]+<++++++++++[<]>>[-[<+[<<]>>[.>>]<[<<]]>>] ``` [Try it online!](https://tio.run/##JYpBCoAwDAQf1EbEtthC2I@EHFQQRPAg@P6Y6pxmYNZ7Oa792U6zKCChDhMHQDk47A0gavjyR1gBIWG3T4e@d/dQs5pbqWkay5xyS2Yv "brainfuck โ€šร„รฌ Try It Online") Treats this as a string processing task. At each step, we find the first digit that still needs to be incremented, increment it, and print the number. ``` Input loop ,[ Place 48 in cell while subtracting 47 from input cell >-[-----<-<+>>]<++++<--->>> Repeat until input exhausted ,] If input number was 1024 we now have 48 2 48 1 48 3 48 5 0 (0) Set up fake 0 digit at the end (to save bytes later) + Set up output LF <++++++++++ Return to first input cell [<]>> This loop always starts at the first nonzero input cell remaining Loop until done: [ Decrement digit - If cell is zero we just blanked an already "zero" digit so do nothing [ Increment corresponding output digit <+ Output entire number with LF [<<]>>[.>>] Return to input cell prior to first nonzero input cell <[<<] ] Move to first nonzero input cell >> ] ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~105~~ ~~101~~ 92 bytes ``` i=>i.indices.flatMap(e=>Seq.fill(i(e)-48)(("1"+"0"*(i.size-1-e)).toLong)).scan(0L)(_+_).tail ``` [Try it online!](https://tio.run/##bY7BqsIwEEX3fkXIaqI0pLZqFSq415UbQURincpISKsJIu/ht9e850ZId8Ph3LnXVdrorjldsfJsx/Dp0Z4dW7Ut@x08tGH1YuvvZC/lcou3/bqxlwMrOyqXJMmeqUIna6P9RreA/46syRggQJHkhQDgKR9xxYdA0tEPJmmCQkjf/L0Kh6u0BbUWcBwdA9Zkujb0eWOB1cBzLpgYfJN0GqFsElsqi7Wx6on2NCil@mAap/N5XJ2rbBbBIphFGDCZhcxn2qt7Aw "Scala โ€šร„รฌ Try It Online") [Answer] # JavaScript, 55 bytes ``` x=>eval("for(y=[x];x;)y=[x-=1+`${x}`.match`0+$`,...y]") ``` [Try it online!](https://tio.run/##NY3BjsIgFEX3fEVDuoDYEirtWGNw6Q/M0mkCVjpiECqthsb47ZVOMpuX807eu/cqn3Jove7H/CRPyuTWndXc8TnwvXpKg2DnPJr4MTS7sMML5LxYifQV3oLc5NheBF2lIiOETA3Ec@vs4Iwixv0ir@4P7VXMGCAmXsnzQRv1PdkW0Qw@xq6OeuiNHhH8sZFvskex@C894fvkmL46FDC5Om0RzBKI3434X5cPPJeg@AKsAgVlgK1pxGgopcsoACu3FSgp24A6Uh0Pqk107AM "JavaScript (Babel Node) โ€šร„รฌ Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes ``` ^ $%'ยฌโˆ‚ 1T`d`0d`.0*ยฌโˆ‚ }A`^0 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP45LRVX90DYuw5CElASDlAQ9Ay0gr9YxIc7g/38TLkMzLmNTLkMDYy5jIwMgEyhiYGAAIgy5jE0sTblMDIzNuSyALAugAlNzoJgxAA "Retina 0.8.2 โ€šร„รฌ Try It Online") Link includes test cases (sorry the output is smashed together). Explanation: ``` ^ $%'ยฌโˆ‚ ``` Duplicate the first line. ``` 1T`d`0d`.0*ยฌโˆ‚ ``` Decrement the last nonzero digit on that line. ``` A`^0 ``` Delete the first line if it's zero. ``` }` ``` Repeat until the first line had been reduced to zero. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` hrxโˆšโˆซma\m*โ€šรฎร„โˆšร–+o; ``` Input as a digit-list. [Try it online.](https://tio.run/##y00syUjPz0n7/z@jqOLwrtzEmFytR1MaDrdq51v//x9tEssVbahjBiSNdUzBbAMdYzDPSMcAIqpjAhU3AItAWIZgORMdS7AuE5AuHXMgywIipmOhAzYByDLXgagzjgUA) **Explanation:** ``` h # Push the length of the (implicit) input r # Pop and push a list in the range [0,length) x # Reverse it to (length,0] โˆšโˆซ # Convert each value in this list to 10**value ma # Wrap each inner number into a list \ # Swap so the input-list is at the top m* # Repeat each wrapped [10**v] that amount of times โ€šรฎร„ # Flatten the list of lists โˆšร– # Loop over this list, using 2 characters as inner code-block: + # Add the top two values on the stack together o # Print this number (without popping) ; # After the loop, discard the number (since MathGolf implicitly # outputs the entire stack after a program ends) ``` [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` def f(x): s=c=int("1"+~-len(str(x))*"0") while s<=x//10*10: yield s;s+=c for i in range(1,x%10+1):yield i ``` [Try it online!](https://tio.run/##JYtBCsIwEEX3nmIICEmjNIO7ag4j7cQOhFQyAdONV4@1fcv333@vZV7SrbWJAgRdzXCCDfGj51S0QmW/10hJS8nbajrllNmTz8yRQB6@9j26Dt3x/LMyxQnkLtaPuwxLBgZOkJ/pRRov9YzOohmOklv7AQ "Python 3 โ€šร„รฌ Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 56 bytes ``` ($args|%{0.."$_"-ne0|%{"$c$_"} $c+=$_;$i++})|% *ht $i 48 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9X0MlsSi9uEa12kBPT0klXkk3L9UAyFNSSQZyarlUkrVtVeKtVTK1tWs1a1QVtDJKFFQyFUws/tdycankleYmpRY5FgeXFGXmpSvYKiiZGBibK3GpqaQpOKBK/gcA "PowerShell Core โ€šร„รฌ Try It Online") Takes a number as a string using splatting in input and returns a list of numbers *-8 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)* ! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~49~~ ~~44~~ ~~43~~ 41 bytes ``` If[#<1,{0},Max[p=10#0[.1#]]~Range~#โ€šรฃร‰p]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnGUKfaoFbHN7EiusDW0EDZIFrPUDk2ti4oMS89tU75UXdzQaza/4CizLySaGVduzQH5Vi1uuDkxLy6ai4THS5DMx0uY1MgbWAMZBgZgHggYQMDAzBpCBQwsQQqMDEwNtfhsgCyLYDKTM2BosZctf8B "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") Includes one leading zero. `Range` stops before the first number greater than the maximum. For example, `Range[3.14]` yields `{1,2,3}`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 19 bytes ``` โ€šโ‰ รœล’โˆโ€šโ‰ รœร”ยบยฉล’ฯ€โ€šร…โˆซโ€šโ‰ รœโ€šรณยฎโ€šร…โˆซโ€šร„ยถล’โˆล’โˆซโ€šรครฏล’ยชร”ยบยจล’โˆล’ยฃล’ฮฉยฌโˆ‚ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKCA4zonFJRqZmjoKATmlxUiKAhJTgjLTM0o0wOLOlck5qc4Z@WDN2UDVnnnJRam5qXklqSkaOZpAAZ/UvPSSDI1CEDu4NFcjD8RQislT0gQC6///LUwsTS2MjQxMzY1NLI3/65blAAA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` ล’โˆ Input string โ€šโ‰ รœ Map over digits and join ล’ฯ€ Current digit ร”ยบยฉ Cast to integer โ€šโ‰ รœ Map over implicit range and join ล’โˆ Input string โ€šร„ยถ Truncated to length ล’โˆซ Outer index โ€šร…โˆซ Concatenated with ล’ยช Inner value โ€šรครฏ Incremented โ€šรณยฎ Right pad with spaces to ร”ยบยจ Length of ล’โˆ Input string โ€šโ‰ รœ Map over characters and join ล’ฮฉ Current character ล’ยฃ Change space to zero โ€šร…โˆซ Concatenated with ยฌโˆ‚ Literal newline ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes ``` f(n)=if(n,concat(f(n-10^valuation(n,10)),n),[]) ``` [Try it online!](https://tio.run/##HY1RC8IwDIT/SthTAymktnPzQf/IUCgDpTC6Mqrgr69XXy7fXY6kxCPZV2ntaTJfE1TWPa@xGqB1@vjE7R1r2jM2Tpklsyx3brGU7Wsy2RuVI@UKHLoZqF9ioSUIubOQHzHVA07aXY9V9a8OQbigENRPQjN4Rm2ckHo8@QE "Pari/GP โ€šร„รฌ Try It Online") Port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/238610/9288). [Answer] # [Haskell](https://www.haskell.org/), 60 bytes ``` c 0=[] c x|(d,m)<-x`divMod`10=map(*10)(c d)++map(x-m+)[1..m] ``` [Try it online!](https://tio.run/##HYpNDoIwFIT3nGKWrRTyakEwkSNwAkKEtCY2UCRqDAvvXh9u5uebuY@v6TbPMVpQ0/WJxfYVTgV5ybbB@U/7cIOmJoyrOGiSwsLJNN3rloVUdjrPQx/D6Bc0CcBDe4VYn355I4eV6AoFfVIwJTsZDkfa246J6K@aQXHmQ0GmUqg513wrK6amjz8 "Haskell โ€šร„รฌ Try It Online") --- Simple recursive solution, for example `c 345` is equal to ``` map (*10) (f 34) ++ map (340+) [1..5] ``` 34 is 345 `div` 10 5 is 345 `mod` 10 340 is 345 minus the remainder [Answer] # [Thunno](https://github.com/Thunno/Thunno) `D`, \$ 20 \log\_{256}(96) \approx \$ 16.46 bytes ``` LR10@rsZZeAuZOA*ESz( ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6Flt8ggwNHIqKo6JSHUuj_B21XIOrNCBSUBULVkYb6igY6SgYx0IEAA) Input as a digit list. ## [Thunno](https://github.com/Thunno/Thunno), \$ 22 \log\_{256}(96) \approx \$ 18.11 bytes ``` dDLR10@rsZZeAuZOA*ESz( ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbbUlx8ggwNHIqKo6JSHUuj_B21XIOrNCCSUDULFhsaGUOYAA) Input as an integer. Port of Lynn's Jelly answer. #### Explanation ``` dD # Get digits and duplicate # (Not needed in the first answer) LR # Pop one and push the length range 10@ # Pop and push 10 ** each rs # Reverse and swap ZZ # Zip with the digits of the input eAu # Map over this list: ZO # Wrap the power of ten in a list A* # And repeat it the digit times E # End map S # Flatten the list z( # And push the cumulative sums ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 11 bytes ``` ยฌยขDsCrโ€šรœรฎ~cยฌยขb- ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FusPLXIpdi561DalLvnQoiTdJcVJycVQuQU3zUy4DM24jE25DA2MuYyNDIBMoIiBgQGIMOQyNrE05TIxMDbnsgCyLIAKTM2BYsYQ7QA) Take `47` as an example. ``` ยฌยขDsCrโ€šรœรฎ~cยฌยขb- ยฌยขD Convert the input to decimal digits. 47 becomes [4, 7] s Non-deterministically choose a suffix of the list. Possible suffixes are [4, 7], [7], []. C Split the list into the head and the tail. Possible heads are 4 and 7, and the corresponding tails are [7] and []. r Range from 0 to the head minus 1. 4 becomes [0, 1, 2, 3], and 7 becomes [0, 1, 2, 3, 4, 5, 6]. โ€šรœรฎ Reverse the range. Possible results are [3, 2, 1, 0] and [6, 5, 4, 3, 2, 1, 0]. ~ Non-deterministically choose an element from the range. Possible elements are 3, 2, 1, 0, 6, 5, 4, 3, 2, 1, 0. c Join the element with the tail. Possible results are [3, 7], [2, 7], [1, 7], [0, 7], [6], [5], [4], [3], [2], [1], [0]. ยฌยขb Convert the list to a base-10 number. Possible results are 37, 27, 17, 7, 6, 5, 4, 3, 2, 1, 0. - Subtract it from the input. Possible results are 10, 20, 30, 40, 41, 42, 43, 44, 45, 46, 47. The interpreter will print all of them. ``` [Answer] # Regex (.NET), 30 bytes ``` ((?(1)\1{10}|x{9}))*x(?<=(x*)) ``` Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the list of matches' `\2` captures. [Try it online!](https://tio.run/##RY9BasMwEEX3PoUwA5aS2kix05K4IoGuewLXC@MqsUCRjKwQE1fbHqBH7EVcJdB2M8z/zHze781F2KETSs1geWXFUYz1dqvFBe@TGeMdZuSNTYz6j3HaeEIWI949czwuCJmT/UP8Yk69VOI9JiVcOS0Pxoqm7TAoJDUCqfuzIxM0HFQ69Eq6OI1LecDQZK05a5cqh1a3gyWHpqK1DwEYNK@kdvXdKUGnSvxqdtPLZfg4cbDZa@PaTgw4GZMFaHJPvpLpYqUTaWcG5wMVK/81SrUJ7ZTUAsWg0ffnFwL8R93eqU8hvs2O1pz7oVrVmRL66DpPYu/nImKPUb6OGM2jfEXDGhxK6W2wKC8266ig@dMP "PowerShell โ€šร„รฌ Try It Online") ``` # head + tail = N = input number; first match starts with head=0 and tail=N # Subtract the largest possible power of 10 from tail ( # \1 = the following, on each iteration (and on each # iteration, add it to head and subtract it from tail): (?(1) # Conditional on whether \1 is set; on the first iteration, # it is unset, and on all subsequent iterations it is set: \1{10} # if \1 is set: \1 * 10 | x{9} # if \1 is unset: 9 ) )* # Iterate the above as many times as possible without preventing # the following from matching: x # Assert tail โ€šรขโ€ข 1; head += 1; tail -= 1 (?<=(x*)) # Inside a lookbehind, \2 = head ``` # Regex (Java / .NET), 33 bytes ``` (\1{10}|(?!\2)x{9}())*x(?<=(^x*)) ``` Returns its output as the list of matches' `\3` captures. [Try it online!](https://tio.run/##bVNRT9swEH7PrzgiodptMQmFTSxkaEObNAm2CR5LJ7mp0xocO7MdGuj6uh@wn7g/0l3SbAypfej57r58vvvufMcf@MHd7H4ji9JYD3foM2lYP4H/I5WXamfMirmod2act4IX7MIoJTJvrEuCspoqmUGmuHNwxaWGFXQx57lH82DkDArMkBtvpZ4Dt3M3nlDwC2uWDj7UmSi9NPhlAPBRKgF5qsWyPZKQZWYmGOZDmryv8lxYMbsWfCYsTFvYyyD5@2Xn5pQm3b1u6JPlouEnxKVT7JPPLqUWhNK9VFdKUZkTx8T3iitHwsN@vx9SunoJ3TIQ4ncSrJDB/2NAgkNkmCLuPnGDtHere431yXobW3/l3gurwabdCbstyuYCRxNUY2qMElzDU5ojo0jgJuNaY@tSl5WHFJpuuxi5eXReFExqmkDXZwtjC@4@i9pjma3EAJ0gCmtHji1II6JrscuPJ6Aw3aCYK5X0JDzAISDeg44w80l7XBXLSm6dQIeocTShQ9DxziRTQs/94uwIzqFBwhs08QQZswW340nd9dN6Op4k8M5a/uhYLpUi9bBX91pRAHJjm96wjFRHCeizVMdoBgNs8Ir7bIEKFchmWbH1SLvDGh/BBZJvN4YtLS9Jd0Vmyscv@TXXc4E3RUNNadNpTp5oJ6tBjZZWekGaMdLkKfW2aibynC5RNZ@TcH8Gv3/@gn0XohbDTk12Z/AJhICxAjfHVco7QrHAkhT24G0YDtCyuTVVSUa00wpHRrG29rmR52fHvLmUrhkoVrnGX9As64bcxqs4Wv8g53u3R7Rena4R0a/J@VlKvtV9SjfNRm6Og/hVMDoJ4mgUjI4iPGIkiqLmLw5Gx6cnwXE0ev0H "Java (JDK) โ€šร„รฌ Try It Online") - **Java** [Try it online!](https://tio.run/##RY9BasMwEEX3PoVqBiwltZHipCVxRQpd9wSOC8ZVYoEiGVkhJq62PUCP2Iu4SqDtZpj/mfm835mzsH0rlJrA8tKKgxiqzUaLM35OJrxjI6P@A2/vdgsyjGuPCZkNePvE8dswI2RKnu/jF3PspBLvMSngwmmxN1bUTYtBIakRSN2dHBmh5qDSvlPSxWlcyD2GOmvMSbtUObS4Hsw51CWtfAjAoHkptatuTgE6VeJXs6uez8PHkYPNXmvXtKLHyZDMQJNb8oWMZyudSFvTOx@oWPGvUapNKKikFigGjb4/vxDgP@rmRn0M8U12sObU9WVeZUrog2s9ib2flhF7iPJVxGge5Qsa1uBQSq@DRflyvYqWNH/8AQ "PowerShell โ€šร„รฌ Try It Online") - .NET This adds Java support to the 30 byte version by removing the use of the conditional, and hinting how far backwards to go inside the lookbehind. # Regex (.NET), 36 bytes ``` (((?<=^\3?)x{9}|\2{10})*x(?<=(x*)))* ``` Returns its output as the list of captures on the Balancing Group `\3` stack. [Try it online!](https://tio.run/##RY/RaoMwFIbvfYogARM7JTZ2o3WhhV3vCawDcWkNpInESKUut3uAPeJexMXCtpvD@T/O@c9/On3lpm@5lDM0rDT8zMdqt1P8ig7RjBDaP7O3I93jcdq6j@N6yojD8bhgNMYY43iODg/hi750QvL3EBfwxkhx0obXTYugBEIBKFQ3WDzBmkGZ9J0UNkzCQpwQrNNGD8om0oL1MrBisC5J5bwBgoqVQtnqTgqoEsl/dbbo1cpvXBg06Wttm5b3KBqjGCp8d77h6WqE5Umre@t8qqz41yBR2v8oheIghAp8f34BiP5SN/fUl/Rs9ND1Ja3Spu7sYHjvLzap5OpsW4dD5@Y8yB4DugkyQgO6Jr71hBCylCyg@XYT5IQ@/QA "PowerShell โ€šร„รฌ Try It Online") ``` # head + tail = N = input number; first match starts with head=0 and tail=N ( # Subtract the largest possible power of 10 from tail ( # \1 = the following, on each iteration (and on each # iteration, add it to head and subtract it from tail): (?<=^\3?) # Make sure this alternative is only used on the first # iteration of this loop, by asserting that head == 0 on the # first iteration of the outermost loop, or head == \3 # on subsequent iterations of the outermost loop. x{9} # 9 | \2{10} # \2 * 10 )* # Iterate the above as many times as possible without # preventing the following from matching: x # Assert tail โ€šรขโ€ข 1; head += 1; tail -= 1 (?<=(x*)) # Inside a lookbehind, \3 = head (which is pushed onto the # Group 3 capture stack) )* # Iterate the above as many times as possible, minimum 0 ``` # Regex (Python[`regex`](https://github.com/mrabarnett/mrab-regex) / .NET), ~~41~~ 40 bytes ``` ((?=((?(3)\3{10}|x{9})))(\2))*x(?<=(x*)) ``` Returns its output as the list of matches' `\4` captures. [Attempt This Online!](https://ato.pxeger.com/run?1=bZAxboMwFIZ3n8Lygh8FZAdSNVArJ8jWjTBEAhJL1CBjJJI0aw_QtUuW9gy9StbeolvtEqmq1MHWe37f__-2X9-7vdm16vwhH7tWG9zv-0BX22rMsBaaEPI2mDq8u1BKl8IuGsM6PnJ2ehqPixMA0PUMwB_p8l7Q0Qe48l9WmvM05EWGD4KhutW4wVK5gKg3pVQpwo1oor5rpKEkJICwg5SD9EZtKyqVoU3OCgimyprBDQcrxLLGhxR32g3qZuh34kEPlbWwYTy7DlTgfT6_eEGlSuF5Af4LurDVT5h7blRLVUpTaaoDTEbiK0gnF6tc2VtuFE0g50X427DiP-vpA84XkiB-i-I54ixG8YzZ0p4wxtzGUZws5hP6DQ "Python - Attempt This Online") - **Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)** [Try it online!](https://tio.run/##RY9BasMwEEX3PoUwA5aS2siR05K4IoGuewLXC@MqsUCRjKwQE1fbHqBH7EVcJdB2McO8z8znT28uwg6dUGoGyysrjmKst1stLnifzBjveCjMyBubcuo/xmnjCSH4bUXIYsS7Z47HBSFzsn@IX8ypl0q8x6SEK6flwVjRtB0GhaRGIHV/dmSChoNKh15JF6dxKQ8Ymqw1Z@1S5dDqtrDk0FS09sEAg@aV1K6@KyXoVIlfzm@8XIaLEwebvTau7cSAkzFZgCZ35yuZLlY6kXZmcD6kyst/Rqk24U8ltUAxaPT9@YUA/6Vu76lPwb7Njtac@6Eq6kwJfXSdJ7H3cxHljxFbRzllEVvRMAaFUnprecSKzToqKHv6AQ "PowerShell โ€šร„รฌ Try It Online") - .NET This adds Python[`regex`](https://github.com/mrabarnett/mrab-regex) support to the 30 byte version, by replacing the use of the nested backreference `\1` with copying a value back and forth between two forward-declared backreferences `\2` and `\3`. # Regex (ECMAScript 2018 / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / .NET), 41 bytes ``` (?=.*?(((x+)\3{8}(?=\3$))*x$))\1(?<=(x*)) ``` Returns its output as the list of matches' `\4` captures. [Try it online!](https://tio.run/##bVDLbtswELzrKxSjAHctmxAjpw8rtE49@JJDc4wDhJBohQVNqSQdE1Z07Qf0E/sjDp3CQA69LBYzuzM7@1O8CFdb1fu56Rp5cjwvLf8h2@@hh3tvlWmpFYenE1ScTisACBluiuHrGIFN8QlxGmLZMKhuOYQp4umJOq1qCWw2ZzgjLcHSyl97ZSUQK0WjlZEEaR17L9fGS7sVcXxQpt/7ZW@7WjpHnW@UGZF2Bsj7xkzz1dByTV2vlQcyj7pqC2B4S7U0rX/G1fXrq3J34g4U74V1Z3VoH/JHxAshPxJmxSq2PNPon213mKzNi9CqSa0wrVymk0yX285CqW65LFWW4fDhvG7v6cEqLwFcRTaGLAnBTGUk/fv7Txqvc5yVgU/ChFrZx7Cg8F3uGH8MO26pDLKGgHjFudlrXR45wyH5v8WxIuk/h93D4vGS@PyBq11MeAEs1cL5tWlkyLJxHPG0SNjnpLhJWF4kxXUe24jkeX4uLCkW326SRV58eQM "JavaScript (Node.js) โ€šร„รฌ Try It Online") - **ECMAScript 2018** [Attempt This Online!](https://ato.pxeger.com/run?1=bVA9TsMwFN59CstCip0mkY1TVBKsnKAbW5qhUpzWUnAix5HSIlYOwMrSBc7AVbpyCzZsUgkhsTy9n-_nvff63h_svtOnD_XQd8bC4TBERu7klEMjDELobbRNvDoTXIgkLDDG04Js-OPqyTU2_IqQcHJhw3BxJ_AUEnIhfDluybKYVTk8CgqazsAWKu0dksHWSmcAtqJNhr5VFqMYEQA9SHuQ2eqdxEpb3Ja0ItGcOTGyYMQRoWrgMYO98YOmHYe9uDejdBLOjOWXgY6Cz-eXIJK6FkEQwb9Ab7b-MfP3Jo3StbLSYBNBNKFQk2xWccy123KrcUpKVsW_Ba3-k54fcDqjFLAbwJeAUQ74NXWp61BKfWCAp7fLGfoN "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) [Try it online!](https://tio.run/##RY/RaoMwFIbvfYogB0x0Sqzt2OpCC7veE6gX4tIaSBOJKZWKt3uAPeJexEVh3c3P@X/O@flOp2/c9C2XcgbDCsPPfKj2e8Vv@BjM@MCS8IAxHiJSZuPL5IIyA0LCwUmZ4sMbw0NIyBwcn/x3femE5J8@yeHOaH7ShtdNi0EioRAI1V0tGaFmIOO@k8L6sZ@LE4Y6afRV2VhatFkWIgZ1QavJFWBQrBDKVmuSg4ol//Pp4qPIXVwYmOSjtk3LexwMQQiKrM13Mt6MsDxudW8nR5Xm/x7FSrtHpVAc@aDQz9c3Avygblbqi6tvkrPR164vtlUiuTrbdiL@NM1bL332sp2X0szLNtSNLqGULpJ62fZ19ws "PowerShell โ€šร„รฌ Try It Online") - .NET ``` # head + tail = N = input number; first match starts with head=0 and tail=N (?= # Atomic lookahead - whatever matches first is # locked in. .*? # Subtract as little as possible from tail in # order to satisfy the following: # Assert that tail is a power of 10, and capture it in \1. ( # \1 = tail ( (x+)\3{8}(?=\3$) # Assert that 10 divides tail; tail /= 10 )* # Iterate the above as many times as necessary # (minimum 0) to satisfy the following: x$ # Assert tail == 1 ) ) \1 # head += \1; tail -= \1 # (this applies also to the next match) (?<=(x*)) # Inside a lookbehind, \4 = head ``` # Regex (ECMAScript 2018 / Java / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / .NET), 42 bytes ``` (?=.*?(((x+)\3{8}(?=\3$))*x$))\1(?<=(^x*)) ``` [Try it online!](https://tio.run/##bVDLbtswELzrKxSjAHctmxAjpw8rtE49@JJDe4xThJBohQVNqSQdE1Z0zQf0E/sjLp3CQA69LBYzuzM7@1M8C1db1fu56Rp5cjwvLf8m26@hh@/eKtNSKw6PJ6g4nVYAEDLcFMPnMQKb4gPiNMSyYVDdcvgRpoinR@q0qiWw2ZzhjLQESyt/7ZWVQKwUjVZGEqR17L1cGy/tVsTxQZl@75e97WrpHHW@UWZE2hkgbxszzVdDyzV1vVYeyDzqqi2A4S3V0rT@CVfXLy/K3Yk7ULwX1p3Vob3PHxAvhHxPmBWr2PJMo3@y3WGyNs9Cqya1wrRymU4yXW47C6W65bJUWYbDu/O6vacHq7wEcBXZGLIkBDOVkfTP6@80Xuc4KwOfhAm1so9hQeGb3DE@GXbcUhlkDQHxinOz17o8coZD8n@LY0XSfw67@8XDJfH5A1e7mPACWKqF82vTyJBl4zjiaZGwj0lxk7C8SIrrPLYRyfP8XFhSLL7cJIu8@PQX "JavaScript (Node.js) โ€šร„รฌ Try It Online") - ECMAScript 2018 [Try it online!](https://tio.run/##bVPdbtMwFL7PUxwiptptZ5K14y8LE0wgIW2Atsu2SG7qtO4cO9jOmq3qLQ/AI/Ii5aQNjEnNRezz48/n@87xkt/x4@XsdiuL0lgPS7SZNKybwP@eykt10GfFXNQHI85bwQt2YZQSmTfWJUFZTZXMIFPcObjiUsMaWp/z3ONyZ@QMCoyQG2@lngO3czeaUPALa1YOPtaZKL00eDIA@CSVgDzVYrXbkpBlZiYYxkOafKjyXFgxuxZ8JixMd2lPneTvydbMKU3ae13fJ6tFg0@IS6fIk88upRaE0meprpSiMieOiR8VV46EL7rdbkjp@mnqHoEQfxBgjQj@HwICvECEKebdJq6Xdsa606w@2ex9m2/ce2E12LTdIduibC5wNEE1psYowTU8pDkiigRuMq41Upe6rDyk0LBtfeTm3nlRMKlpAi3PXRpbcPdF1B7L3EkM0AqisHbE2CdpzGgptvHRBBSGmyzmSiU9CY@xCZjvQUcY@aw9joplJbdOoEHUKJrQPuj4YJApoed@cXYC59Bkwltc4gkiZgtuR5O65bOzdDxJ4L21/N6xXCpF6n6n7uxEAciNbbhhGamOEtBnqY5x6fWQ4BX32QIVKhDNsmJvkd0Ma3wEFwi@nxi2srwk7RWZKe@/5tdczwXeFPU1pQ3TnDzQVlaDGq2s9II0baTJQ@pt1XTkMVyiaj4n4dEMfv/8BUcuRC36rZpsafAJhIC@AifHVco7QrHAkhT2@F0Y9nBlc2uqkgxpqxW2jGJtu@dGHp8d8@ZSuqahWOUGv6AZ1i05T1n3nBBS9@h4sH69Qcd48JzSbo2/cUzOz1Lyve5Sum1GczsM4pfB4DSIo0EwOIlwi54oippfHAyGb06DYTR49Qc "Java (JDK) โ€šร„รฌ Try It Online") - Java [Attempt This Online!](https://ato.pxeger.com/run?1=bVA9asMwFN51CiEKlhzbSJVTUrvCJ8jWzXYgYDsRuLKRZXBSuvYAXbtkac_Qq2TtLbpVqgOl0OXxfr6f997re38w-06dPuRD32kDh8MQ6HpXTynUQiOE3kbThKuzjzMR-RnGeFqQgj-unmyj4FeE-JMNBcPZncCbySfkwviy5JwlIStTeBQUNJ2GLZTKWUSDqaRKAGxFGw19Kw1GISIAOpByIL1VuxpLZXCb05IEc2bFyIIRS4SygccE9toNmnYc9uJej7WVsGYsvQxU4H0-v3hBrSrheQH8C3Rm6x8zd3DUSFVJU2usA4gm5CuSzCqWubZbbhWOSc7K8Leg5X_S8wNOZxQDdgP4EjDKAb-mNrUdSqkLDPD4djlDvwE "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) [Try it online!](https://tio.run/##RY/RaoMwFIbvfYogB0x0SlLbsdWFFna9J7AOxKU1kCYSI0qLt3uAPeJexKWFbTc/5/855@c7nRmF7Vuh1AKWl1acxFRtt1qMeB8teMezeIcxnhJyyK9Psw8OORAST14ODO9eOH6fYkKWaP8QvppzJ5X4CEkBF06Lo7GibloMCkmNQOpucOQKNQeV9p2SLkzDQh4x1FljBu1S5dDqtpBwqEtazb4Ag@al1K66JwXoVIlfz24@SfzFmYPN3mrXtKLH0RTFoMm9@UKuo5VOpK3p3eypWPHvUaqN/1RJLVAIGn1/fiHAf9TNnfrs65vsZM3Q9eW6ypTQJ9fOJJznZR2wxyDfBIzmQb6ifvQJpfQmLMjXz5sf "PowerShell โ€šร„รฌ Try It Online") - .NET This adds Java support to the 41 byte version by hinting how far backwards to go inside the lookbehind. [Answer] # [Perl 5](https://www.perl.org/) -F -p, 63 bytes ``` //+push@a,map$a[-1]+$_*10**(@F-$'),1..$F[$_-1]for 1..@F;$_="@a" ``` [Try it online!](https://tio.run/##K0gtyjH9/19fX7ugtDjDIVEnN7FAJTFa1zBWWyVey9BAS0vDwU1XRV1Tx1BPT8UtWiUeKJWWX6QA5Dq4WavE2yo5JCr9/29iYGz@L7@gJDM/r/i/rtt/3QIA "Perl 5 โ€šร„รฌ Try It Online") [Answer] Unlike my other regex answer, this [outputs in reverse order](https://codegolf.stackexchange.com/questions/238607/converge-to-a-number?noredirect=1#comment571747_238607), in order to support regex engines that are incapable of outputting it in ascending order. The algorithm used here was conceived of independently from, but is very similar to, [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/238610/17216) (and therefore [pxeger's Python answer](https://codegolf.stackexchange.com/a/238615/17216)) and [Unrelated String's 2nd Jelly answer](https://codegolf.stackexchange.com/a/239627/17216). Unlike those answers, it is impossible to reverse the order of the list before outputting it. # Regex (Perl / PCRE / .NET), ~~39~~ 35 bytes ``` (?=((((?(3)\3{10}|x{9}))*x)\2*$))\2 ``` Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the list of matches' `\1` captures. [Try it online!](https://tio.run/##RU7NTgIxEL73KRrS0A6wbEtBg92yS4JXT95cskED2qQC7mJcU9ejD@Aj@iLrgCTO4cv3M/lm9uvST9rnd8pKQ4PfPaw8ZbFBaZPF/HY@a@hmVwpWWWmSmYFAM2@rvXcHwSM@qF7vqwPGxSBSAwXrl06@7aT/rkQfrlgBhrqNqLB9VWY@GUHI/J1aWkS5NOcb7iyZS@wpRtbvQ2BVt7sv3fZwLDf4ijInSZkbcvrz9c0N21pe85o58/bk/Fqg/oxZGT9C@FvllA9F1sfSKIsQwTRNUxTXN4uiaEVqBU4qNOQ6KNl81GHaAPRqyEc9BohtOybqgugJUVITPZJI0ZFSHkERPZ5OyFjqy18 "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##fZLBbtswDIbvfgrWEGqxdRI7Tjd0ipHLsqHA0A7ZbnUhuJ4Se5FlQ1aKAFmue4A94l4ko5Nuw3qYAREU@ZH8Rbgt28N01pYtMAsp@CMfhtBatZJWtTovFA9Gw4uZlGWunSyauq20shnPUGSLUReEENBZUlCuVA8Yp4zruJTvbj7MpcQQYqSW1Fh4lalkpxz328Kq4WNerJ0lI3VVV84PwR/EPgr4F7Oq2Niuasz/sa@nVEQZb9lYzqo0EkynS5LV8U@f397cosAdVEvO9H3nrFaGPBzED2nqZ8ZHgrvNI2UoHEbhIMa@Xm1b3XxR3B/4IeGC6otmY1xfOx1T0T01IBs9CA/gONk835mZpsc8eZeXCDsCgAQAP@NsnR63XOeuKGWuNWc2pNn92lXueLANQmYwZDUiAlMnWuedk8pamoJnafpxMX8vb@/kfLG4W4jn7vRyVEXZ9G8SQGuIBfR3YGYYwM/vP4ITSVJVXpSc1aQQ8g7YE57AAILh7wU9ofirmq3h/JzE/OHmvZQ3hL9QJ@tuxY@V@/2LX4fCBz5LOX0znmCW7OJo/227u94jXmwxG18wJHs4TLz4lZdceXGUeMk4IpciURT1JvaSyfWVN4mS178A "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##RU9BasMwELz7FcIsWIprI0dOS2JEAj33BUkOxlVigSwZWSEmrq59QJ/Yj7hKoO0ehp1hd3a2N1dhh1YoNYPleyvOYjxuNlpc8S6Z8ZbjUFvMyIFNBfUf47T2hCxGclgugASck91T/Gq6XirxHpMKbpxWJ2NF3bQYFJIagdT9xZEJag4qG3olXZzFlTxhqPPGXLTLlEPL@0DKod7Tow8GGDTfS@2OD6UCnSnxy4s7T9Ow0XGw@VvtmlYMOBmTBWjycL6R6WqlE1lrBudDqqL65yjTJryopBYoBo2@P78Q4L/UzSN1F@yb/GzNpR/CxVwJfXatJ7H3cxkVzxFbRQVlEVvS0AaFUnqHImLlehWVlL38AA "PowerShell โ€šร„รฌ Try It Online") - .NET ``` # on the first match, tail = N = input number (?= ( # \1 = tail (the return value) ( # \2 = the largest power of 10 that divides tail ( # \3 = the following, on each iteration (and on each # iteration, subtract it from tail): (?(3) # Conditional on whether \3 is set; on the first # iteration, it is unset, and on all subsequent # iterations it is set: \3{10} # if \3 is set: \3 * 10 | x{9} # if \3 is unset: 9 ) )* # Iterate the above as many times as possible # without preventing the following from matching: x # Assert tail โ€šรขโ€ข 1; tail -= 1 ) \2*$ # Assert that \2 divides tail ) ) \2 # tail -= \2, in preparation for the next match ``` It's impossible for regex flavors without variable-length lookbehind to output this sequence in ascending order. Emulating this with recursion and fixed-width lookbehind in Perl/PCRE doesn't work, because captures made inside a subroutine call are erased upon returning from the call. It's impossible even to guess what the capture will be before it's made using non-atomic lookahead in PCRE2, because there isn't enough room to capture that after the sequence has passed \$n/2\$. # Regex (Perl / Java / PCRE / .NET), ~~39~~ 37 bytes ``` (?=(((\3{10}|(?!\4)x{9}())*x)\2*$))\2 ``` [Try it online!](https://tio.run/##RY7BTsJAEIbvfYqVbNgdoLBLWw1uF0qCV0/eLGnQFN1khdrWWLOWow/gI/oidUASL1/@/5/JP1PkpY26lw9CS0Wc3T9uLKEThVbHq@Xdct6S7b7ktNJCxXMFjiRWV4U1NWc@G1VvD1WN42zky5GE/LWX7nqL/1RgDtc0A0XMllfYvikTG0/BJfZerjVSrNX5hjlbamJ9GqMaDsHRqt8vSrOrj@UKX5HqZAk1Y0Z@vr6ZojvNGtZQo96fjc05@sOElpMncH@rjLAxT4ZY6ic@ElTbtll2c7vKso4vNOc8DZwU7SdfXKQhNG7WcoBBA@l0QAHZdaEnL70g8qQIvGAqUGIihDhCekE4i7xQBFe/ "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##bVPBctMwEL37K7YeOpGSVLWbFKa4pgMdmGGmBaY9JjkojpwolSUjyY3bkCsfwCfyI2GdGEpn6oOl3X162n27WvJ7frSc3W1lURrrYYk2k4Z1E/jfU3mpXvRZMRf1ixHnreAFuzRKicwb65KgrKZKZpAp7hxcc6lhDa3Pee5xuTdyBgVGyK23Us@B27kbTSj4hTUrBx/rTJReGjwZAHySSkCearHabUnIMjMTDOMhTT5UeS6smN0IPhMWpjvYcyf5e7I1c0qT9l7X98lq0fAT4tIp1slnV1ILQulBqiulqMyJY@J7xZUj4XG32w0pXT@H7hkI8S8SrJHB/2NAgmNkmCLuLnG9tDPWnWb1yWbv23zj3gurwabtDqstyuYCRxNUY2qMElzDY5ojo0jgNuNaY@lSl5WHFJpqWx@5fXBeFExqmkBb5w7GFtx9EbXHNHcSA7SCKMwdOfYgjYi2xDY@moDCcINirlTSk/AIm4B4DzrCyGftcVQsK7l1Ag2iRtGE9kHHLwaZEnruF@cncAENEt7iEk@QMVtwO5rUbT07S8eTBN5byx8cy6VSpO536s5OFIDc2KY2TCPVUQL6PNUxLr0eFnjNfbZAhQpks6zYW2Q3wxofwSWS7yeGrSwvSXtFZsqHr/kN13OBN0V9TWlTaU4eaSurQY1WVnpBmjbS5DH1tmo68hQuUTWfk/BwBr9//oJDF6IW/VZNtjT4BEJAX4GT4yrlHaGYYEkKe/QuDHu4srk1VUli2mqFLaOY2@65kadnx7y5kq5pKGa5wS9ohnVLLlJCyHiwjqPND3JxMB7Sen22QVi3puOT7iuK/20zldthEL8OBqdBHA2CwUmEW/REUdT84mAwPDsNhtHgzR8 "Java (JDK) โ€šร„รฌ Try It Online") - **Java** [Try it online!](https://tio.run/##fZLBbtswDIbvfgrGEGoxdRI5Tjd0jpHLsqHA0A7ebnUhuJ4Se7FlQ1aKAFmue4A94l4ko5Nuw3rYQQRFfiR/EWqL9jhftEULzEAM7sSFMbRGraVRbZXlinuT8XAhZZFVVuZN3ZaVMilPMUqTSef54NFZUVCuVQ9oq7TtuJTvbj4spUQfAqSW1DhySl3KTlnutrlR48cs31hDRlZlXVrXB3cUuBjBv5hR@dZ0ZaP/j309pwRlnFVjOCtjEbEqXpGsjn/6/PbmFiPcQ7nirLrvrKmUJg9HwUMcu6l2keBu@0gZCvvCHwXY16tdWzVfFHdHrk94RPV5s9W2r51PqeieGpAVD5EDcJqsn@9Mz@NTnrzLS4Q9AUACgA8428SnLdeZzQuZVRVnxqfZ/dpVZrm383ym0Wc1IgJTZ7rKOiuVMTQFB3H8MVm@l7d3cpkkd0n03J1ejiovmv5NEdAaggj6OzA99uDn9x/emSSpKssLzmpSCFkH7AnPoAfe@PeCnjD6q5pt4OKCxPzhlr2UN4S/UCfrbs1PlYfDi69D4SNfxJzzNNwH4vCNLwbpDHf76wNHHO4wnQ4Zkj0eZ07wygmvnECETjgV5FJECNGbwAln11fOTISvfwE "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##RU9LasMwFNz7FKp5YCmujfxJS2JEAl33BEkWxlVigSwZWSEmrrY9QI/Yi7hKIO1meDO8NzOv1xduhpZLOYNhO8NPfDys14pf8Daa8YZhjPfFlFH3iTdP@5KM08phQhYj2ecLIB7naPscvumuF5J/hKSCK6PVURteNy0GiYRCIFR/tmSCmoFMhl4KGyZhJY4Y6rTRZ2UTaVF@W4gZ1Dt6cN4Ag2I7oezhrlSgEskfPLvxOPYXHQOTvte2afmAozFagCJ35yuZLkZYnrR6sM63yqp/jhKl/ZNSKI5CUOjn6xsB/mvd3Ft33r5JT0af@8EnppKrk20dCZ2byyB7CYplkNEiKHLqR69QSm@QBUW5WgYlLV5/AQ "PowerShell โ€šร„รฌ Try It Online") - .NET This adds Java support to the 35 byte version by removing the use of the conditional. # Regex (Perl / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE / .NET), 45 bytes ``` (?=((((?=((?(5)\5{10}|x{9})))(\4))*x)\2*$))\2 ``` [Try it online!](https://tio.run/##RY5NTsMwEIX3OYVVWbWnTVo7P6DiuEmlsmXFjlRRQSlYMm1JiggyYckBOCIXCdNSiVl8mvdm9Gb2VW2T/vmd0FoRZ3cPa0voVKHU6XJxu5h3ZLOrOW20UOlcgSO51c3emgNnAfOb1/vmgOPSD6QvoXoZFNtB9u8K9OGKlqCI2fAG09d1btMQXG7v5EojxUqdb5izpCbVpzF24zE42gyH@9psD8dwha9IdZKEmgkjP1/fTNGtZi1rqVFvT8ZWHPXnlNbTR3B/q4ywCc/HGBrkARJU13VleX2zLMueZ5pjHZnxBIrESdF9tG7WAQAvYoBRC0U4ooDs@9iTF16UeFJEXhQKbNERQhwhvSieJV4sostf "Perl 5 โ€šร„รฌ Try It Online") - Perl [Attempt This Online!](https://ato.pxeger.com/run?1=bVA9boMwFN59CsuqhB8FZAdoGxDKCbJ1IwyRgMQSNcgYiSTN2gN07ZKlPUOvkrW36Ba7RKoq1cOn5_e-Hz-_fXQ7vW3l6VM8da3SuN_1nqo21ZhilSlCyPuga__h7NNFRs2xuKAxrOIDZ8fn8TA_AgBdRQDuCKuZewMGr6Jvo8954vMixfuMobpVuMFC2pSg16WQCcJN1gR91whNiU8AYUuSlqTWclNRITVtclaAN1XGDG45GCEWNd4nuFN2UDdDv80e1VAZCxPG0-tAes7Xy6vjVbLMHMfDf4k2bPkTZncOaiFLoStFlYfJSFwJyeRilEvzyrWkHHJe-L8XVvxnPX3A6exEiN-hMEachSicMVOaDmPMAkdhNI9RxML7iX8B "Python - Attempt This Online") - **Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)** [Try it online!](https://tio.run/##PY7BasJAEIbv@xTTIOyOmGXXJC12WUSw1x5Kb0aCrWtcWNYQI6Zar32APmJfJK5p6Rw@Zn5m/n/qw9tHV4OGF1OatuLeHGE@e53x2qzWCqwWCo5b6ww4XZpmH6QNuEUsl1pHuY9U0N1CcB6PlwqMX/cC31fONozGFAnAZleDB@vDnVjyZldYJgVy3tv8z72zvQuB1SHk9FZWSwVVbX0DfkTh5@sbqIKT9tYpYFEbDT3y/fvKsxrPv3vsBFMK9JFSHA0kd8aXzZahOml5@XswgBTF0/O8KDo21SzUjVOWYZ6dpbh8tufJBRFZniIOW8zHwwEGdl1K5D1JMiJFQpKxCG1QhBA3SJKkk4ykInm4Ag "Ruby โ€šร„รฌ Try It Online") - **Ruby** [Try it online!](https://tio.run/##fZLNbtswDMfvfgrWEGoxdRI5Hxs6xchl2VBgaIdst7oQXE@JvciyITtFgCzXPcAecS@S0Um3YT3MgAiK/JH8i3Cd18fZvM5rYA5i8Ic@DKB2eq2crk2aaR4MB725UnlqWpVVZV0Y7RKeoEyWwyYIIaCzoqBa6w6wrbZtw5V6d/NhoRSGECG1pMbSK2yhGt1yv86cHjym2aZ1ZJQpyqL1Q/D7kY8S/sWczrauKSr7f@zrOSUo460qx1kRC8lMvCJZDf/0@e3NLUrcQ7HizNw3rTPakof96CGO/cT6SHCzfaQMhUMR9iPs6vWuNtUXzf2@HxIuqT6rtrbtamcjKrqnBmTFg/QATpPt853ZWXzKk3d1hbAnAEgA8AvONvFpy2XaZrlKjeHMhTS7W7tOWx7sgpBZDFmJiMD0mTZp0yrtHE3Bizj@uFy8V7d3arFc3i3lc3d6Oeosr7o3SaA1RBK6OzA7CODn9x/BmSSpOs1yzkpSCGkD7AnPYADB4PeCnlD@Vc02cHlJYv5wi07KG8JfqFNls@anysPhxa9D4SOfx5y@zs75FJPpPhKHb7v99YEey5MJYm@HyajHkOzxOPGiV9546kVi7I1HglyKCCE6E3njyfXUm4jx618 "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##RU9BboMwELzzCguthJ0UZAK0SpCVSD33BYEDok6w5NjIOAoK9bUP6BP7EWoitd3DaGe0Ozvb6xs3Q8elnMGwo@FnPta7neI3fIhmvGfY14J7XJCqmFLqPsZp6wghuMoJWY2k2qyAeJyjw1P4qi@9kPw9JCXcGS1P2vCm7TBIJBQCofqrJRM0DGQ89FLYMA5LccLQJK2@KhtLizbLwJpBc6S18wYYFDsKZeuHUoKKJf/l6cLXa79xYWCSt8a2HR9wNEYrUOThfCfTzQjL404P1vlUafnPUay0f1YKxVEICn1/fiHAf6nbR@qLt2@Ts9HXfvAXE8nV2XaOhM7NeZA@B1kRpDQLsg31rVcopQukQZZviyCn2csP "PowerShell โ€šร„รฌ Try It Online") - .NET This adds Python[`regex`](https://github.com/mrabarnett/mrab-regex) and Ruby support to the 35 byte version, by replacing the use of the nested backreference `\3` with copying a value back and forth between two forward-declared backreferences `\4` and `\5`. # Regex (Perl / ~~Java~~ / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE / .NET), 47 bytes ``` (?=((((?=(\6{10}|(?!\5)x{9}()))(\4))*x)\2*$))\2 ``` [Try it online!](https://tio.run/##RY7PTsJAEMbvfYqVbNgdSmG3fzC4XSgJXj15s6RBU3STFbDFWLPWow/gI/oidUAS5/DLfN9Mvpl9Wdmke34ntFLE2d3D2hI6Vih1ulzcLmYt2ewqTmstVDpT4Ehmdb235sBZwIb16319wHExDORQQvnSy7e9@b8r0IcrWoAiZsNrTF9XmU1DcJm9kyuNFCt1vmHOkppUn8bY@T44Wvf7@8psD8dwha9IdZKEmhEjP1/fTNGtZg1rqFFvT8aWHPXnmFbjR3B/q4ywEc98DA2yAAmqbduiuL5ZFkXH55pjIfOJk6L94POLPIHGTVsOADyPAQYN5OGAArLrYk9OvCjxpIi8KBTYoiOEOEJ6UTxNvFhEl78 "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##RY9NboMwEIX3PoVrVbKHGmTHkCoglBPkBMAiEpBYogYZL0jSbHuAHrEXoXbTql48zd/7Zjxd3Hk0atVv02gdni8zt92pWwpsS0sIWdm@ZP55rbc3Ke7vbP9UZ7DcdncGAKxOAaIF6k30DF5X76lkHsumwNdSoH60eMDaBHIyu1abHOGhHJJ5GrRjJCaAcBgyYcgezalj2jg2VKIB/og8DF4keCPWPb7meLKh4Y1@hSx@U8Pp18cn5Z1pS0pDM2APP9jwo6TXptWus8xyTBYSGcgfTkr5wd9zNExCJZv4PxHNH25NkdwilSEpFFIb4UNfEUIEkUiluwylQr1@Aw "Python 3 โ€šร„รฌ Try It Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) [Try it online!](https://tio.run/##PY7BasJAEIbv@xRjEHYn6LJrEotdFhHstYfSm5Fg66oLyxpixDTWax@gj9gXSbdp6Rw@Zn5m/n@q88tbV4GGJ7M3Tcm9ucBy8bzgldlsFVgtFFwO1hlwem/qU5B24FZjudY6yn2kgu5WgvPxZK3A@G0v8FPpbM3omCIB2B0r8GB9uBNrXh8Ly6RAznub/7l3toMQWJ5DTm9ltVRQVtbX4EcUvj4@gSpotbdOAYuaKPbIT68bzyq8/u6xFuYU6D2lOBpK7ozf1weGqtXy9vdgACmKh8dlUXRsrlmowHx6leL2zuaDPMPmOrsxRGR5ihg3mE/iIQZ2XUrklCQZkSIhyUSENihCiB9IkqSzjKQiufsG "Ruby โ€šร„รฌ Try It Online") - Ruby [Try it online!](https://tio.run/##fZLBbtswDIbvfgrGEGoxdRI5Tjp0jpHL0qHA0A7ZbnUhuJ4Se5FlQ3aKAFmue4A94l4ko5Nuw3qYAREU@ZH8RbjO6@NsXuc1MAsxuCMXhlBbtZZW1TrNFPdGw/5cyjzVrcyqsi60sglPMEqWo8bzwaOzoqBcqw4wrTJtw6W8uf2wkBJ9CJBaUuPIKUwhG9Vyt86sGj6l2aa1ZKQuyqJ1fXAHgYsR/ItZlW1tU1Tm/9jXc0pQxllVlrMiFhHT8YpkNfzT53e3dxjhHooVZ/qhaa1WhjwcBI9x7CbGRYKb7RNlKOwLfxBgV692ta6@KO4OXJ/wiOqzamvarnY2pqIHakBWPEYOwGmyebkzM4tPefIuLxH2BAAJAN7jbBOftlymbZbLVGvOrE@zu7WrtOXezvOZQZ@ViAhMnWmdNq1U1tIU7MXxx@Xivby7l4vl8n4ZvXSnl6PK8qp7UwS0hiCC7g7MDD34@f2HdyZJqkqznLOSFELaAHvGM@iBN/y9oGeM/qpmG7i4IDF/uEUn5S3hr9TJslnzU@Xh8OrXofCRz2NOH9nkah@Iwzc@7yVT3O2vD5yey5MJYn@HybjPkOzxOHGCKyecOoEInXAsyKWIEKIzgRNOrqfORIRvfgE "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##RU9BboMwELzzChethB0KMoGkSpCVSD33BSEHRJ1gydjIOAoK9bUP6BP7EepEaruH0c5od3a211duhpZLOYNhB8PPfDxut4pf8T6a8Y5hXx6r9ZRR94F3T9WKjNPGYUIIrgpCFiOplgsgHudo/xy@6q4Xkr@HpIQbo@VJG143LQaJhEIgVH@xZIKagUyGXgobJmEpThjqtNEXZRNp0fI@EDOoD/TovAEGxQ5C2eNDKUElkv/y7M7j2G90DEz6Vtum5QOOxmgBijycb2S6GmF50urBOp8qK/85SpT270qhOApBoe/PLwT4L3XzSN15@yY9G33pB38xlVydbetI6NxcBNk6yFdBRvMgX1LfeoVSeocsyIvNKiho/vID "PowerShell โ€šร„รฌ Try It Online") - .NET This attempts to add Java support to the 45 byte version by removing the use of the conditional (just like the 37 byte version does to the 35 byte version), but while it works on the other engines, it **exposes a bug** in Java's regex engine: [Try it online!](https://tio.run/##bVPBctMwEL37KxYPnUpJqtpNWqa4pgMdmGGmBaY9JjkojpwolSUjyU3akCsfwCfyI2HtGEpn4oOk3X1@2n27WvAHfrSY3m9lURrrYYE2k4Z1EvjfU3mp9vqsmInV3ojzVvCCXRmlROaNdUlQVhMlM8gUdw5uuNSwhtbnPPe4PRg5hQIj5M5bqWfA7cwNxxT83Jqlg4@rTJReGvwzAPgklYA81WLZHEnIMjMVDOMhTT5UeS6smN4KPhUWJg3spZP8/bM1c0qT9l7X88lyXvMT4tIJ1smn11ILQumrVFdKUZkTx8T3iitHwuNOpxNSun4J3TEQ4vcSrJHB/2NAgmNkmCDuPnHd9HCkD@vdJ5udb/ONey@sBpu2J6y2KOsLHE1QjYkxSnANT2mOjCKBu4xrjaVLXVYeUqirbX3k7tF5UTCpaQJtnQ2Mzbn7IlYe02wkBmgFUZg7cuxAGhFtiW18OAaF4RrFXKmkJ@ERNgHxHnSEkc/a46hYVnLrBBpEDaMx7YGO9waZEnrm5xcncAk1Et7iFo@RMZtzOxyv2noaS8fjBN5byx8dy6VSZNU7XB02ogDkxta1YRqpjhLQF6mOcet2scAb7rM5KlQgm2XFziLNDGt8BFdIvpsYtrS8JO0VmSkfv@a3XM8E3hT1NKV1pTl5oq2sBjVaWukFqdtIk6fU26ruyHO4RNV8TsKDKfz@@QsOXIha9Fo12cLgEwgBfQVOjquUd4RigiUp7NG7MOzizmbWVCWJaasVtoxibs1zI8/PjnlzLV3dUMxyg19QD@uWXKYEP1xHZ@s42vwgl69Gp3S1Pt/UUDIaUNpZ0dFJ5zXFdVvP53YQxGdB/zSIo37QP4nwiJ4oiuolDvqD89NgEPXf/AE "Java (JDK) โ€šร„รฌ Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=bVNPU9QwFL946qcIHZ1NliW0LKBYKqOoM8yAMjCe2D1ku-luME1qkrIL6179AF69cMAPhUc_iS9tBXHoocl77_d-729-3JyzC3b968mRKEptHPIiFZp2E_SvpnJCPqozfMLn_1vA_72Q_BG4dYazgu5rKXnmtLFJUFYjKTKUSWYtOmJCoQVqddYxB8eFFmNUgAWfOiPUBDEzsWdDgtzU6JlF7-YZL53Q4Bkg5COjPFV8Vl-xp6Q1O51wd2y0g8gAfqtrSuK1-3rMT3VlMt7IhzpjHgOS059ODhrtMXNTTEjypspzbvj4hLMxN2hUx3qoxH_Dt2IObpBbm7_tuWQ29XlibNMRNJGND4WC4GQlVZWUROTYUv6lYtLicL3b7YaELB5CGwaM3aMEC2BwdwxAsA4MI8B9Tuxq2hmojj9dsmx0S0gOynPcKGTS9kYzXZQ-hiUJGmktOVPoKs2BEmZ7mjGloHyhysqhFPmKWx0-vbSOF1QocGwLrWF0yuwHPneQZz2ru45ISB44GpACRFtjaz8bIglmj6K2lMLhcC0Eq1AOqQgsB8rBIhpaMmM5CFieRUPSQyp-1EglVxM33d1Ae8gj0Us44iEwZlNmzobztp5aUvEwQa-NYZeW5kJKPO915p16ngjl2vjaII1URQlSu6mK4VhdhQKPmMum0KEC2AwtGgnXj0HBE9kH8mZr6MywErchMl1efsxPmJpwiBT1FCG-0hxfkbatGno0M8Jx7OdIkqvUmcpP5N5cQtdcjsNnY_T723f0zIbQi17bTXquYfFDBLoCVsdW0lnY8AJyKMzaqzBchZNOjK5KHJO2VzAyArnV7xbfv194H4fC-oFClkv4Ar-tPyuXr724Xcd7KYYP_oPtRRwtv-K9lcEWmS92lt4DDzYJ6c7JYKP7lMC_cbvx29pcr287m0G8HfS3gjjqB_2NCK6giaLI_-Kgv7mzFWxG_ecN_g8 "Java - Attempt This Online") # Regex (ECMAScript / Boost / Python or better), ~~54~~ 52 bytes ``` (?=((|x+)\2*(?=(\2$|.*$\2))((x+)\5{8}(?=\5$))*x$))\3 ``` [Try it online!](https://tio.run/##TY9NUsJAEIX3OUWkKNKdQMwP@BcHVy7YsNClcTEFbRgdhtTMKDHA1gN4RC@CCQWlm65X773u6u@Vf3Az06K0A1OKOenlSr3R514zRWv3gYr7qgSo2fjc38MdA9hWAeaJ3@o86W5Dv5sniACtPdpc7ZogH3UR/aoZebr3z2sM7erRaqEKwNBIMSO46A@G2He9wsPMsChbL4QkAMk08bkUigDxjKl3KXFTMBmaUgoL3qCpixcAxYpQkirsAsfJdivMlE9BsJJrQxNloXiKnhFPAf0P1Di@i2/aGO1Cr9adifrgUsxdzVVBN24nkJnzstKQiVtGmQgC3Jher3y3xmrwcnX4OM4q1qk6oaaSuAWB2bEgAs/9@fp2m1Z7pG7YYMl0SBXNoGqhDlRZzWLc1H9324WjXj7Fzye6lvZs2dCcDB1KbuxEzakKgt1utx868YWTjpw4Sp00iRrZOFEUtSN20uH1yBlG6eUv "JavaScript (SpiderMonkey) โ€šร„รฌ Try It Online") - **ECMAScript** [Try it online!](https://tio.run/##bVDLbtswELzrKxTDAHctmxAluw@rtE89@JJDc4wCRJBohQVNqSQdC5Z17Qf0E/sjDpXCQA69LAYzu7M7@7N4LWxpZOsWuqnE1fI4M/yHqL93LTw4I3VNTXF6vsKWA1y6CPNkNuI8mV7obJoniAAjveq/DF7IV1PEWedLnl6fqVWyFMDmC4ZzUhPMjPh1lEYAMaKolNSCIC09dmKnnTD7wrf3UrdHt25NUwprqXWV1APSRgN5n5grvulrrqhtlXRAFt5X7gE0r6kSunYvuEkuF2nvi3uQvC2MHd2hfoyfEG@C@CjoDduy9SijezHNabLTr4WSVWgKXYt1OIlUtm8MZPIbF5mMIuw/nNccHT0Z6QSA3ZJckzUhGMmIhH9//wn9dZazrOOTbkKNaH1YkPhud/bvhgM3VHSihA7xjnN9VCo7c4Z98P8V5y0J/204PLKnW@LxA3cHn/BGGKoK63a6El0UDcOA12XAPgXpKmBxGqRJ7KFn4jgeCwvS5ddVsIzTz28 "JavaScript (Node.js) โ€šร„รฌ Try It Online") - **ECMAScript 2018** [Try it online!](https://tio.run/##RY7LTsJAFIb3fYoJOWHmUAozLfU2HSgJbl25s6RBAzrJCNhirKl16QP4iL5IPUUSN1/@y@Q/s18XLm6f3xkUmtVu97ByDMaarEkW89v5tGGbXSGgNFInU401S50p984eBA/4sHy9Lw9U58NADRWuX3rZtjf7TyXleAU5amY3oqT1VZG6JMQ6dXdqaYhyqU837MmCTcyxJuX7WEPZ7@8Luz1045q@ovTRMrAjzn6@vrmGreEVr8Dqtyfr1oL85xiK8SPWf0854yOR@jQapAERddM0eX59s8jzVsyMEB@Vj1k46HQWwsdoAFmIKEQXx/VFQ0UWA@KgImRR2048deZFsadk5EWhJEmJlLKD8qLJZexNZHT@Cw "Perl 5 โ€šร„รฌ Try It Online") - Perl [Try it online!](https://tio.run/##bVPbctowEH33V2w9ySABUWwIvTlup820M51J2k7yCDwII4OILLuSHJwQXvsB/cT@CF0bt2lm8IOlvehoz9nVit/xk9X8diezIjcOVmgzmbNuBP97SifVQZ8RC1EdjFhnBM/YRa6USFxubOQV5UzJBBLFrYUrLjVsoPVZxx0ud7mcQ4YRcuOM1AvgZmHHUwpuafK1hU9VIgonczzpAXyWSkAaa7FutsRnST4XDOM@jT6WaSqMmF8LPhcGZk3acyf5e7I1U0qj9l7bd9F6WeMTYuMZ8uTzS6kFofRFrEulqEyJZeJHyZUl/mm32/Up3TxP3SMQ4g4CbBDB/UNAgFNEmGHebWR7cWeiO/Xqou3et/3OnRNGg4nbHbLNivoCSyNUY5bnSnAND3GKiCKCm4RrjdSlLkoHMdRsWx@5ubdOZExqGkHLs0ljS26/isphmY3EAK0gCmtHjH2SxoyWYhsfT0FhuM5itlDSEf8Em4D5DnSAkS/a4agYVnBjBRpEjYMp7YMODwaZEnrhlucDeA91JrzFJZwiYrLkZjytWj6NpcNpBB@M4feWpVIpUvU7VacRBSDNTc0Ny4h1EIE@j3WIS6@HBK@4S5aoUIZohmV7izQzrPERXCD4fmLY2vCCtFckeXH/Lb3meiHwpqCvKa2ZpuSBtrLmqNHaSCdI3UYaPcTOlHVHnsIFquZS4h/P4ffPX3BsfdSi36rJVjk@AR/Ql@Hk2FI5SygWWJDMnLzz/R6ubGHysiAhbbXCllGsrXlu5OnZMZdfSls3FKvc4ufVw7oj72NCHqsenQy69X4yOHpk3aPJgFJCavdo83qLgcnoiNJuhb/JcFcP6e7MC196w5EXBkNvOAhwi54gCOpf6A3P3oy8s2D46g8 "Java (JDK) โ€šร„รฌ Try It Online") - Java [Try it online!](https://tio.run/##bVPdbtowFL7PU5zRatgEQkJKtxHSqp2q7Waq1HHRqaAoBJNYC04UO4L@cLsH2CPuQcaOk5aSbUEyPn/f@c6PozzvxVG06/ePFmzJBYPL6@uvk@Dm6tPVbfDlYvLxc3B1O7m5MI64iNJywWA8zzKp@gWL2cZK8vzMiJKwgCC/m4EPN63L9fr73C2/3d/fTpLTdUJ25Nwn5Glj0umgo@/TwfGT1TmeDiglRKuHj@@3aJgOjyntbPCYujv6N06rC53cD3LT8Q7IcORSsHB1ZvT7SCyFaE6iTEgFFc3RaBWqKAkKJstUyXFt0oQ7Z29hRR@lWoxGUVYqGI@hjT/8W1nrJFRWFOaqxEBiUytlIlYJoV7BUCdAFSXztgYXClYhF4TCowH45XdIB51JTnvOzLc9KNHHHQQKMi3pgFhfqrzoy0WMyrxUXhXfoF61GAqGYN6LTlb1gCZYRyyzAoiGfdjDxkylOEpS18ZFt85AvReW@tMhwsaJhSrjpHKwogAZEUq7IJwu5JlEc23B1ViQdq9NvT2AcNCqfd74h9WMRkIrz/@DC2blb4JDYYTJX7GqDerodIKta@lOOKYz82DFVpIpIrvQ3rQ1MeyFRKNu7j5@3wTuC93lsS8cD0yTH1ZcVb0E8kABSekkpD0VWBK2zvEabo2t4Ppowa8fP1vNuUlNmBxo6FvNrMdnTbSKXaNF1ZgDrliBXSqA276U1pzFepNwWo4WGXb8de7VLgSShUWUEG5rp261BV1cEHRDCC3d2TNLMoRfmKQp@3v7khdSUdqg@E/Rz0@hinFmr/u/j9rubwuWMsUAn7@szbXp@aXglLa7E8M5Ndyh4diu4Q5svKLGtm19OIZ78mFonNjuu9/RMg1jueulVdVBVfQf "C++ (gcc) โ€šร„รฌ Try It Online") - **Boost** - only works with small numbers [Try it online!](https://tio.run/##RY5NboQwDIX3OUUUISVhAkoI9AeEeoI5AbAYCWgjUYNCFsx0uu0BesRehCadVt1Yz35@n72c3csMejevy2wdXs@rsEOFbW0JITt7qhm7bgfeZnHQbRZd0zhqM84ZC@Pi7eHdG20RcR5vvrR698FGlYnqKnypJRpniydsILDT1fUGSoSnekrXZTKOkYRwhMMShCV7gueBGXBsamTHxU15GD8o7oPYjPhS4sUGwwf9CVX9tiDo18cnFQP0NaXBDNjjD3ZIRwO9cYNlVmCykRh4eYtRKo7@mRMwxRvVJf@N7P5Ye47UHdIFUlIjnUkv/URKGYpCOn8sUC71/Tc "Python 3 โ€šร„รฌ Try It Online") - **Python** [Attempt This Online!](https://ato.pxeger.com/run?1=bVA7boMwGN59CstCwiaAbB5tCkI9QbZugSESJrFEDTJGImm69gBdu2Rpz9CrZO0tusUukapKXX59_r-X7bePfq93nTx9ise-UxoO-8FXfMunHKpCIYTeR90Ey3OC7wuMj9OClJFncRk5x9BzyogQjO06fVo-G6JMHUK8yYwyvnq_TcyaZQGrcngoKGg6BVsopC0LB10LmQHYFm049K3QGAWIAGhF0orURm45FlLjdk0r4s_IhJEFI8YIRQMPGeyVJZp2HHbFgxq5iTBlLL8S0ne_Xl5dn8u6cF0f_hXastVPmX162AhZC80VVj5EE_IkyeYU41yZW24kZmTNquD3QKv_oucPOJ3dBLAbEKeA0RjEETXQbCildjAQJ3cpSGh8O-sv "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) [Try it online!](https://tio.run/##PY5NasMwEIX3OsXUGCS5sZDsuH9ChEC67aJ0FxuTNoojEIpxHOLmZ9sD9Ii5iKu4pZvHzDcz702ze//sG1Dwqivd1czpPcymb1PW6MVSglFcwn5trAarKt1uPVqBnceiUCrIXSA9t3POWJwUErRbDoBta2tagmNMEcBq04AD4/wdL1i7KQ0RnDI22Pz3g7O58YH1zucMVkYJCXVjXAtuhOHy9Q1YwkE5YyWQoAsiR9n2Y@FIQ4@/e@QAEwz4CWM6CgWz2lXtmlB5UOL896AXVJbPL7Oy7MlEEXLqbmmeRNc6T8ITi8I8oZSQK86OD2c/yLOQ0qjzkqd9P0biDqUZEjxFacJ96Qnn/CoCpePHDI15ev8D "Ruby โ€šร„รฌ Try It Online") - Ruby [Try it online!](https://tio.run/##fZLNbtswDMfvfgrWEGoxcRx/JPtSjFyWDgWGdsh2qwvB9ZTYiy0bslMESHPdA@wR9yIZnXQb1sMOIijyR/IvQk3eHGfzJm@AGYjBHtvgQWPUWhrVlGmmuDP2BnMp87TsZFZXTVEqk/AERbIct44LDp0VBeVa9YDulO5aLuXV9ceFlOhCgNSSGgur0IVsVcftJjPKe0izTWfIyLKois52wR4FNgr4FzMq25q2qPX/sW/nlE8Za1UbzorYF6yMVySr5Z@/vL@@QYF7KFaclXdtZ0qlycNRcB/HdqJtJLjdPlCGwq7vjgLs69WuKeuvitsj2yVcUH1Wb3XX185CKrqjBmT9e2EBnCbr5zvTs/iUJ284RNgTACQA@AVnm/i05SrtslymZcmZcWl2v3aVdtzZOS7T6LIKEYGpM12mbSeVMTQFL@L403LxQd7cysVyebsUz93p5aiyvO7fJIDWEAjo78C058DP7z@cM0lSVZrlnFWkENIW2COeQQcc7/eCHlH8Vc02cHlJYv5wi17KO8JfqJNVu@anysPhxdeh8JHPY86fdkNMwkHvJyF78gYsCRE578PT/ZsDJZIpQxzsyCTR8TixgldWNLUCP7Ki0CeXIr7v9yawosnbqTXxo9e/AA "PHP โ€šร„รฌ Try It Online") - PCRE [Try it online!](https://tio.run/##RU/LboMwELzzFRZaCRsKMhD6CLIaqed@QcgBUSdYMjYyRkFJuPYD@on9EWoitb2MdmZ3Z2d7feZmaLmUCxi2N/zEp8N2q/gZ74IFvzKMb1NEqixc6yqDWxJClRGC8SoX1@fZNaoCCAknB1W@BLsH/013vZD8wyclXBgtj9rwumkxSCQUAqH60ZIr1AxkPPRSWD/2S3HEUCeNHpWNpUXZOhAxqPf0MDsDDIrthbKHu1KCiiX/5enKo8htdAxM8l7bpuUDDqYgBEXuzhdyPRthedzqwc4uVVr@cxQr7X6WQnHkg0Lfn18I8F/q5p66c/ZNcjJ67Ad3MZFcnWw7E3@el42XPnp54aU09/KMutIplNIVUi/fvBTehuZPPw "PowerShell โ€šร„รฌ Try It Online") - .NET ``` (?= ( # \1 = tail (the return value) (|x+) # \2 = 0 or the largest number that satisfies the # following, whichever matches first \2* # tail -= \2 * {any nonnegative integer}, to # satisfy the following: (?= # Lookahead (atomic - first match is locked in) ( # \3 = tail \2$ # Assert tail == \2 | # or... .*$\2 # Assert \2 == 0 ) ) # Assert that tail is a power of 10 ( (x+)\5{8}(?=\5$) # Assert that 10 divides tail; tail /= 10 )* # Iterate the above as many times as necessary # (minimum 0) to satisfy the following: x$ # Assert tail == 1 ) ) \3 # tail -= \3, in preparation for the next match ``` Boost works fine with the previous **54 byte** version: [Try it online!](https://tio.run/##bVRbb9owFH7Przij1bC5xoV2GyGt2qnaXqZKHQ@dAEUhmMRacKLYEfTC637AfuJ@yNixaSnZFiTjc/vOdy5JlOftOIq23e7RnC@E5HB1c/N1FNxef7q@C75cjj5@Dq7vRreXzpGQUVrOOQxnWaZ0t@AxX3eSPD93oiQsIMjHU/Dhtna1Wn2f9cpv9/d3o@RslZAtufDJukEpecIThclJw57HTxNGiTFN@o/vN0bXP6a0sT6mE3axpX8j1VrQyP0gbzLvgI5ANgUPl@dOt4vUUohmJMqk0mCJDgbLUEdJUHBVploNdyZDuXH@Fpb0Uen5YBBlpYbhEOr4w79lZ5WEuhOFuS4xkLi0k3IZ64RQr@Cok6CLknsbR0gNy1BIQuHRAXzyMdJBZ5LTNpv6rgcl@vROAg2ZkUxAbC42L/oKGaMyL7Vn4yvUbZOh4AjmveiUrQcMwV3EIiuAGNiHPWzMdYrDJLvahGztMlDvhaV5TIh0cWahzgSxDp0oQEaE0hZI1oI8U2jeWXA55qTerlNvDyAZWo3PG/@wmsFAGuXFf3Chaf2bwCgMMPkrlt2hhkkn@WonjSVrsqkHS75UXBPVgvq6bohhLxQaTXP38fsmCF@aLg99yTxoNsVhxbbqBZAHCkjKJCH1icSSsHXMq7hVtkKYowa/fvysVeemDGFyoKFvDbO2mFbRLLtKi@yYA6F5gV0qQLi@Up0Zj80m4bSYETl2/HXudhcCxcMiSohwjVPLbkELFwTdEMJIY3faURzh501Slf29fSEKpSmtUPyn6OdXwcaw6ev@76M2@9ucp1xzwA@A2pl3puc3Bae02fYddub0Th3m9pzeiYtX1Liuaw7m9PofTp2@23v3O1qkYay27dRWHdii/wA "C++ (gcc) โ€šร„รฌ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 107 bytes (non-competitive) I tried to do this challenge in JS with a "functional programming approach", without any recursive call and without regex, and it has become surprinsingly long! I'm still quite new to JS, so does any of you see if this could this be shortened in some way while keeping this approach? ``` p=>[...p+=""].flatMap((a,i)=>(r=[...Array(a*=1)].map((b,j)=>(t*10+j+1)*10**(p.length-i-1)),t=t*10+a,r),t=0) ``` [Try it online!](https://tio.run/##lZDRboIwGIXvfYrGqxYrtP1bnEsw2QPsCQwXnaLTMCFIlu3pWU/dzWQkG8n/QfL3nJ7D2b/76647tf3y0uyr4VAMbbHZpmnaLor5vEwPte@ffcu5lydRbHhXYPnUdf6T@6TQokzfsH6RZ6z7RKvFeaFFeCcJb9O6uhz71@VpqYWQfRH3Xnb4VmLYNZdrU1dp3Rz5gVshWHyyjFUfbbXrqz17ZFstmZGMJLPl7KdC59@Se4WSTAeZDjodhNqGcWHyewdy0w4mDGGCEyFBcKLgRG6UQ9HNZuSCIApJFKIoGt1v1LTSqJggRgCMGse3/5GjA2ABF4FuDuUc2rnxL1bqlnB8g/rlrJ46K7EsZ1l2V8Cu3aTEABSBQoRChEKhAKABAxBgAQfkwAp4ANYRGjAAARZw40RW0eoPiewNGjAARWjAAARYwAE5sCqHLw "JavaScript (Node.js) โ€šร„รฌ Try It Online") (I can ungolf it if this needs explanations) ]
[Question] [ Implement a function diff that takes as input three integers x, y, and z. It should return whether subtracting one of these numbers from another gives the third. ``` Test cases: diff(5, 3, 2) yields True because 5 - 3 = 2 diff(2, 3, 5) yields True because 5 - 3 = 2 diff(2, 5, 3) yields True because 5 - 3 = 2 diff(-2, 3, 5) yields True because 3 - 5 is -2 diff(-5, -3, -2) # -5 - -2 is -3 diff(2, 3, -5) yields False diff(10, 6, 4) yields True because 10 - 6 = 4 diff(10, 6, 3) yields False ``` You don't have to name the function, you may implement default input methods the examples above are not a strict guideline. [Answer] ## Python 3, 21 bytes ``` lambda*l:sum(l)/2in l ``` If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like `3.0` rather than `3`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 3 bytes Thanks to [@Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) for saving two bytes! Code, uses quite the same algorithm as [@xnor's great answer](https://codegolf.stackexchange.com/a/71338/34388): ``` Sfยทโˆยง ``` Explanation: ``` S # Sum of the argument list ยทโˆยง # Double the list f # Filter, remove everything that isn't equal to the sum of the list ``` This gives `[]` as falsy, and anything else as truthy. [Try it online!](http://jelly.tryitonline.net/#code=U2bhuKQ&input=&args=MiwgMywgNQ) [Answer] ## ES6, 31 bytes ``` (a,b,c)=>a+b==c|b+c==a|c+a==b ``` Add 5 bytes if you need to name the function `diff`. Edit: Saved 2 bytes thanks to @Alex L. [Answer] # JavaScript ES6, ~~38~~ ~~34~~ 33 bytes ``` x=>x.some(a=>2*a==x[0]+x[1]+x[2]) ``` Very simple anonymous function, and borrows from the Python answer. Takes input `x` as an array; returns `true` or `false`. Bytes shaved to Molarmanful and jrich A 38-byte program, taking each number as an argument: ``` (a,b,c)=>[a,b,c].some(t=>t==(a+b+c)/2) ``` [Answer] # Oracle SQL 11.2, 49 bytes ``` SELECT 1 FROM DUAL WHERE(:1+:2+:3)/2IN(:1,:2,:3); ``` Rewrite of @xnor solution, kudos to him. [Answer] # J, 6 bytes ``` +/e.+: ``` Try it with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%2B%2Fe.%2B%3A)%202%203%205). ### How it works ``` +/e.+: Monadic verb. Argument: A +: Double the elements of A. +/ Compute the sum of the elements of A. e. Test for membership. ``` [Answer] # APL, ~~8~~ 5 bytes ``` +/โ€šร รค+โ€šรงยฎ ``` This is a monadic function train that accepts an array and returns a boolean (0/1 in APL). It uses the same algorithm as xnor's Python 3 [answer](https://codegolf.stackexchange.com/a/71338/20469). Explanation: ``` +โ€šรงยฎ โ€šรงรน Double the input (+โ€šรงยฎx is the same as x+x) โ€šร รค โ€šรงรน Test the membership of +/ โ€šรงรน The sum of the input ``` [Try it online](http://tryapl.org/?a=f%u2190+/%u220A+%u2368%u22C4f%205%203%202%u22C4f%202%203%20%AF5&run) Saved 3 bytes thanks to Dennis! [Answer] # [DUP](https://esolangs.org/wiki/DUP), 31 chars / 39 bytes ``` [2โˆšโˆ2โˆšโˆ2โˆšโˆ++2/\%3โˆšโˆ^=3โˆšโˆ2โˆšโˆ=3โˆšโˆ3โˆšโˆ=||.] ``` `[Try it here!](http://www.quirkster.com/iano/js/dup.html)` My first DUP submission ever! *Unicode is your oyster.* It's an anonymous function/lambda. Usage: ``` 5 3 2[2โˆšโˆ2โˆšโˆ2โˆšโˆ++2/\%3โˆšโˆ^=3โˆšโˆ2โˆšโˆ=3โˆšโˆ3โˆšโˆ=||.]! ``` # Explanation ``` [ {start lambda} 2โˆšโˆ2โˆšโˆ2โˆšโˆ {duplicate 3 inputnums} ++ {push sum(3 popped stack items)} 2/\% {push (popped stack item)/2} 3โˆšโˆ^=3โˆšโˆ2โˆšโˆ=3โˆšโˆ3โˆšโˆ= {for all 3 inputs, -1 if inputnum=sum/2; else 0} || {check if any of the 3 resulting values are truthy} . {output top of stack (boolean value)} ] {end lambda} ``` [Answer] ## Java 7, 81 ``` boolean d(int[]a){int s=0,t=1;for(int b:a)s+=b;for(int b:a)t*=2*b-s;return t==0;} ``` [Answer] # Perl 6, ~~20~~ 19 bytes I have two functions equal in byte count, so I'll put both. Appreciate whichever tickles your fancy. ``` {@_โ€šร รฃ@_.sum div 2} {@_โ€šร รฃ+~(@_.sum/2)} ``` Usage: assign either one to a variable from which you can call it. EDIT: Thanks @b2gills for the byte reduction [Answer] # Java 8 (lambda function), 29 bytes ``` // Lambda Signature: (int, int, int) -> boolean (a,b,c)->a+b==c|a+c==b|b+c==a ``` Java code golf solutions are usually only short when the program does not have to be a fully functional program. (\*cough cough\* class declaration, main method) [Answer] # Pyth, 6 bytes ``` /Q/sQ2 ``` [Try it online!](http://pyth.herokuapp.com/?code=%2FQ%2FsQ2&input=%5B19%2C3%2C6%5D&test_suite=1&test_suite_input=%5B5%2C3%2C2%5D%0A%5B2%2C3%2C5%5D%0A%5B2%2C5%2C3%5D%0A%5B-2%2C3%2C5%5D%0A%5B-5%2C-3%2C-2%5D%0A%5B2%2C3%2C-5%5D%0A%5B10%2C6%2C4%5D%0A%5B10%2C6%2C3%5D&debug=0) Expects input as a list of integers. Outputs 0 if no number can be built by subtracting the other two and >0 if at least one can. ### Explanation: Same algorithm as the answer of @xnor ``` /Q/sQ2 sQ # Sum all elements in the list / 2 # Divide the sum by 2 /Q # Count Occurences of above number in the list ``` [Answer] # [Kona](https://github.com/kevinlawler/kona) 16 chars ``` {((+/x)%2)_in x} ``` Takes a vector from the stack, sums them, divides by 2 and determines if it's in the vector. Returns 1 as truthy and 0 as falsey. Called via ``` > {((+/x)%2)_in x} [(2;3;5)] 1 > {((+/x)%2)_in x} [(2;3;4)] 0 ``` [Answer] # jq, 17 characters (Yet another rewrite of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python 3 answer](https://codegolf.stackexchange.com/a/71338). Upvotes should go to that one.) ``` contains([add/2]) ``` Input: array of 3 integers. Sample run: ``` bash-4.3$ jq 'contains([add/2])' <<< '[5, 3, 2]' true bash-4.3$ jq 'contains([add/2])' <<< '[2, 3, -5]' false ``` On-line test: * [[5, 3, 2]](https://jqplay.org/jq?q=contains%28[add/2]%29&j=[5%2C%203%2C%202]) * [[2, 3, -5]](https://jqplay.org/jq?q=contains%28[add/2]%29&j=[2%2C%203%2C%20-5]) ## jq, 18 characters (17 characters code + 1 character command line option.) ``` contains([add/2]) ``` Input: list of 3 integers. Sample run: ``` bash-4.3$ jq -s 'contains([add/2])' <<< '5 3 2' true bash-4.3$ jq -s 'contains([add/2])' <<< '2 3 -5' false ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 5 bytes Using [@xnor's great approach](https://codegolf.stackexchange.com/a/71338/36398): ``` s2/Gm ``` [**Try it online!**](http://matl.tryitonline.net/#code=czIvR20&input=WzIgNSAzXQ) ``` s % implicitly input array of three numbers. Compute their sum 2/ % divide by 2 G % push input again m % ismember function: true if sum divided by 2 equals some element of the input ``` --- **Brute-force approach, 12 bytes**: ``` Y@TT-1h*!s~a ``` [**Try it online!**](http://matl.tryitonline.net/#code=WUBUVC0xaCohc35h&input=WzIgNSAzXQ) ``` Y@ % input array of three numbers. Matrix with all % permutations, each one on a different row TT-1h % vector [1,1,-1] * % multiply with broadcast !s % transpose, sum of each column (former row) ~a % true if any value is 0 ``` [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ, 7 chars / 9 bytes ``` โˆšร˜โ€šรญร†โ€šรขรฎโ€šยฎโ‰ โˆšร˜/2 ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B2%2C3%2C5%5D&code=%C3%AF%E2%92%AE%E2%89%94%E2%A8%AD%C3%AF%2F2)` Meh. I'm still finding better ways. It's just @xnor's awesome algorithm. [Answer] # CJam, 10 ~~12~~ bytes ``` l~:d_:+2/& ``` 2 bytes removed thanks to @MartinBโˆšยบttner. This displays a number as truthy result, and no output as falsy result. [**Try it here**](http://cjam.aditsu.net/#code=l%7E%3Ad_%3A%2B2%2F%26&input=%5B-2%203%205%5D) ``` l~ e# read line and evaluate. Pushes the array :d e# convert array to double _ e# duplicate :+ e# fold addition on the array. Computes sum of the array 2/ e# divide sum by 2 & e# setwise and (intersection) ``` [Answer] ## Seriously, 6 bytes ``` ,;ล’ยฃยฌฮฉโˆšโ‰ u ``` Outputs 0 if false and a positive integer otherwise. [Answer] # Mathematica, ~~20~~ 19 bytes ``` MemberQ[2{##},+##]& ``` Works similarly to most of the other answers. [Answer] # Haskell, 20 bytes ``` (\l->sum l/2`elem`l) ``` Using xnor's solution. [Answer] ## Perl, 24 + 4 = 28 bytes ``` $^+=$_/2 for@F;$_=$^~~@F ``` Requires `-paX` flags to run, prints `1` as True and nothing as False: `-X` disables all warnings. ``` $ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 7' $ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 8' 1 ``` [Answer] # [R](https://www.r-project.org/), 23 bytes ``` sum(x<-scan())%in%(2*x) ``` [Try it online!](https://tio.run/##K/r/v7g0V6PCRrc4OTFPQ1NTNTNPVcNIq0Lzv6mCsYLRfwA "R โ€šร„รฌ Try It Online") Shameless port of [xnor's answer](https://codegolf.stackexchange.com/a/71338/80010). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` DO;ยฌยข ``` Using 0 as falsy and > 0 as truthy. Uses CP-1252 encoding. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 35 bytes ``` \A:-permutation([X,Y,E],A),X-Y=:=E. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P8bRSrcgtSi3tCSxJDM/TyM6QidSxzVWx1FTJ0I30tbK1lXvv6O2k7azla5CTLSjjpOOc6zef1NtY20jPS4uIyBtCqaBIkDa0EDbTNsEyNDQNdKEymnommpqa@gagwgjTagmkCBMvbEeAA "Prolog (SWI) โ€šร„รฌ Try It Online") [Answer] # Jolf, 6 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=IGh4wr11eA) ``` hxยฌฮฉux _hx the input array ยฌฮฉux has half the sum of the array ``` This is xnor's awesome solution to the problem, but in Jolf. [Answer] # [Pylons](https://github.com/morganthrapp/Pylons-lang), 8 Yet another implementation of xnor's algorithm. ``` i:As2A/_ ``` How it works: ``` i # Get command line input. :A # Initialize a constant A. s # Set A to the sum of the stack. 2 # Push 2 to the stack. A # Push A to the stack. / # Divide A/2 _ # Check if the top of the stack is in the previous elements. # Print the stack on quit. ``` [Answer] # SpecBAS - 36 bytes Uses xnors formula ``` 1 INPUT a,b,c: ?(a+b+c)/2 IN [a,b,c] ``` outputs 1 if true and 0 if false [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ;Oโ€“ยบ_O ``` -1 byte by creating a port of [*@xnor*'s Python 3 algorithm](https://codegolf.stackexchange.com/a/71338/52210). [Try it online](https://tio.run/##MzBNTDJM/f//0HZP/wt74v3//482NNAx0zGJBQA) or [verify all test cases](https://tio.run/##MzBNTDJM/X9u66GVh9b9t/a/sCfe/3/sod3/o6NNdYx1jGJ1FKKNgAxTCAMoBmLowoV0TXV0jXV04ep0waKGBjpmOiZwlnFsLAA). **Explanation:** ``` ยฌโˆ‘ # Halve every item in the input-array # i.e. [10,6,4] โ€šรœรญ [5.0,3.0,2.0] O # Sum this array # i.e. [5.0,3.0,2.0] โ€šรœรญ 10.0 โ€“ยบ_O # Output 1 if the input-array contain this sum, 0 otherwise # i.e. [10,6,4] and 10.0 โ€šรœรญ 1 ``` I'm pretty sure `โ€“ยบ_O` can be shortened, but I'm not sure which command(s) I have to use for it.. ]
[Question] [ You will be given as **input** an integer `k` in the range from `-4503599627370496` (โˆ’252) to `4503599627370496` (252). As is [well known](https://stackoverflow.com/questions/3793838/which-is-the-first-integer-that-an-ieee-754-float-is-incapable-of-representing-e), integers in this range can be represented exactly as double-precision floating-point values. You should **output** the [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight) (number of ones) of the encoding of `k` in [binary64 format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64). This uses 1 bit for the sign, 11 bits for the exponent (encoded with an offset), and 52 for the mantissa; see the above link for details. As an **example**, number `22` is represented as ``` 0 10000000011 0110000000000000000000000000000000000000000000000000 ``` Since there are `5` ones, the output is `5`. Note that endianness doesn't affect the result, so you can safely use your machine's actual internal representation of double-precision values to compute the output. ### Additional rules * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed. * Any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398) can be used. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * The input number will be in decimal. Other than that, input/output means and format are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. * Shortest code in bytes wins. ### Test cases ``` 22 -> 5 714 -> 6 0 -> 0 1 -> 10 4503599627370496 -> 5 4503599627370495 -> 55 1024 -> 3 -1024 -> 4 -4096 -> 5 1000000000 -> 16 -12345678 -> 16 ``` [Answer] # x86\_64 machine language (Linux), 16 bytes ``` 0: f2 48 0f 2a c7 cvtsi2sd %rdi, %xmm0 5: 66 48 0f 7e c0 movq %xmm0, %rax a: f3 48 0f b8 c0 popcnt %rax, %rax f: c3 retq ``` Accepts a single 64-bit integer parameter in `RDI`, converts it to a floating-point value in `XMM0`, stores those bits back in `RAX`, and then computes the hamming weight of `RAX`, leaving the result in `RAX` so it can be returned to the caller. Requires a processor that supports the `POPCNT` instruction, which would be Intel Nehalem, AMD Barcelona, and later microarchitectures. To [Try it online!](https://tio.run/##jc5RS8MwEAfwZ/cpQoeQjFXSJE1apoIO97RvYHwIadMFayprhaD41Y0ZInswBe/p@N2fu9N5p3VYWqf7t6YF1@PU2OHqcLtYNq2xrgUGegQgtG6CKwT7wXUIdShi0IMbJ6AP6gi6x6ebTPodkZ5V0uOd9ORO@q2QnvOziYdoOObo2e6rH9vSbBPiFfCirDudAwp9LC5ej7E1MLtspMvWBhKC0OYvi4IlHSe1SCorMS3rmhNBBWY13/8nVaZTBSbph/L5CcM1n1n2WzMrCWUlF9Vp@hm@tOlVN4b8vfWtHieln78B "C (gcc) โ€“ Try It Online"), compile and run the following C program: ``` #include<stdio.h> const char g[]="\xF2\x48\x0F\x2A\xC7\x66\x48\x0F\x7E\xC0\xF3\x48\x0F\xB8\xC0\xC3"; #define f(x) ((int(*)(long))g)(x) int main(int a){ printf("%d\n",f(22)); printf("%d\n",f(714)); printf("%d\n",f(0)); printf("%d\n",f(1)); printf("%d\n",f(4503599627370496L)); printf("%d\n",f(4503599627370495L)); printf("%d\n",f(1024)); printf("%d\n",f(-1024)); printf("%d\n",f(-4096)); printf("%d\n",f(1000000000)); printf("%d\n",f(-12345678)); } ``` Edit: Fixed segfault in TIO link. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~82~~ 68 bytes 9 bytes thanks to Neil. evil floating point bit level hacking ``` s;f(long n){double d=n;n=*(long*)&d;for(s=0;n;n*=2)s+=n<0;return s;} ``` [Try it online!](https://tio.run/##jY5BDoIwFETXeooGo2lRTCkFJKWewCO40RaQBD@GwopwdgQTV5bEWU3eTCajvEKpcVOCqjqdodS0uqyPj/NoRI6rGgoEpNd1d68ypCUIkO4Hu2SnRV432EgqJuxKRsxeQkpFk7VdA8iIYSyhRc9bCXg2N9KvV69msjl2tvoKziHHjBEifnHscyunVupbKQ9pECZJxOIgpjyJLv@0QnvLp8x@yFtOOE2ihbGvFiZZwMMoPs3pML4B "C (gcc) โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` 3Z%Bz ``` [Try it online!](https://tio.run/##y00syfn/3zhK1anq/38jIwA "MATL โ€“ Try It Online") Exact transliteration of my MATLAB answer. Note that input and output are implicit. -2 bytes thanks to Luis Mendo. ``` 3Z% % Typecast: changes input (implicitly taken and converted to double) to uint64 without changing underlying bits B % Convert integer to array of 1s and 0s z % Count nonzero entries ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~72~~ 71 bytes 1 byte thanks to Lynn. ``` lambda n:n and(bin(1020+len(bin(abs(n))))+bin(abs(n))).count('1')-(n>0) ``` [Try it online!](https://tio.run/##XY7LCsIwFETX9iuya4qp3LwaW6g/oi7SFxbqbWniwq@PUVHEWQzMYWBmufvLjDIM9SlM9tp0lmCFxGJHmxEpBwHbqcdXsI2jmEVtf9OunW/oacrTLKd4gCz43vnWut6RmhyFYIYrBowzpUHqsiyEkQZUWfwDzeKcYvnbFcQGh48iFlLpwuzPSTLMK0EyIvlOVclmWcf4Y3ieCg8 "Python 3 โ€“ Try It Online") ### Explanation The binary64 format consists of three components: * the first bit is the sign bit, which is `1` if the number is negative * the next 11 bits store the exponent with 1023 added * the next 52 bits store the significand, or the mantissa. [Answer] # [C (gcc)](https://gcc.gnu.org/), 47 bytes ``` f(double n){n=__builtin_popcountl(*(long*)&n);} ``` This isn't portable; it was tested with gcc 7.1.1 on x86\_64 running Linux, without compiler flags. [Try it online!](https://tio.run/##ZY/RioMwEEWfzVcMhS6JjWyMUStu90faIm3UEkgTqfGl4re7EbZU6LxcOHO5c0dGNynnucW1Ha66AUNGc6iq66C0U6bqbCftYJzGIdbW3ELyZUg5zco4uF@UwQSNKFg24JreVfLSN/3xDAcYOaeQx4ICoxBTEClL0qLIeJ7kTBTZB0m9jXHvj/5FsMUVs9csG56INMv3U4lQ0NoH4KWI8udY6eUHevVsbIvfXQh8v2C4ot692xEUBN3DJ7R4s40zXUP0C1ten8yGrt9RZwrrTA8IKdE0/wE "C (gcc) โ€“ Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 92 bytes ``` int f(long n){int s=0;for(n=Double.doubleToLongBits((double)n);n!=0;n>>>=1)s+=n&1;return s;} ``` [Try it online!](https://tio.run/##XZDNboMwEITP8BTupbIFQUD4KaLkUPVIT@kNcXDBUKewRthJVSGePbWTppVqS17tp5FnZw/0RDdiYnBoP87T8W3gDWoGKiV6oRyWMweFOjwI6BGQxXSy8PNOzBiKZ6H1zGsv5VWUWvTElcT4SgiQHO60Gna7XREQ6RRwH@QzU8cZkMzXm59UVOlyErxFo3bFezVz6Kuazr0ki21d7BWTqqGSyapGBQL2iQyu6iUM3TSIXN8N3Cj2t3GWJWG6Tf0oS8r/JC7dwA8jd3N9Iz9LNLgdjcNtFCfpw5rbllkAGn@8TIOJpia6WQPXwfjj71DewKBX7zl3HDOxtf@Sio2eOCpv0mHUAHj0OvwXgtfEfLfa@p6/AQ "Java (OpenJDK 8) โ€“ Try It Online") [Answer] # C (gcc), 63 bytes ``` f(double d){long s=0,n=*(long*)&d;for(;n;n*=2)s+=n<0;return s;} ``` This solution is based on @LeakyNun's answer, but because he doesn't want to improve his own answer, I'm posting here more golfed version. [Try it online](https://tio.run/##jY5NDoIwFITXeooGo2kRTCktSAqewCO4wRawCT4MPyvC2VEWriyJbzXvm8lklF8pNe8MqHrQBUq7Xpvm9LjMJdbNcK8LpMlYN1ChLqMeZC5eHpcctCybFkuQ4GaMdMcMUirboh9aQJ2cZgM9euYG8CJyMm43r/YjS@zs9Q0cr8SMESJ/cRxwK6dWGlgpFzQUSRKxOIwpT6LrPylhTwWU2Qf56w6nSbRS9r2VShZyEcXnxZ3mNw) [Answer] # C#, ~~81~~ ~~70~~ 68 bytes ``` d=>{unsafe{long l=*(long*)&d,s=0;for(;l!=0;l*=2)s-=l>>63;return s;}} ``` *Save 11 bytes thanks to @Leaky Nun.* *Saved 2 bytes thanks to @Neil.* [Try it online!](https://tio.run/##nY/LSsUwEIb3fYq4a@W0pGnaWmK6UBEEBVHBdWxTCaSJJOkBOfTZay94OSAY/BfDTOab/DONjXut9KRYz@0bazh4fLeO98EhALMayawF92u@vSyyjjnRgL0WLbhjQoXRV@sbWnQ9qOa81cOL5DsgtXqtQQfo1NL6sFRA0s0tuRDuUqs9N46b5GodeNI3yhV47tiwjXaWQtJpExJ5MmfylKLIxlTWdZERw91gFLBknMiR/1ExG1gtefJshOO3QvGwCxGKIvInVabYB4M@UOoD4RxmeVUVqMxKiKviHzO51zIQeV0We4MY@m2bwk/5@aMM50V5tsC/0g@ctSv847cx2OI4fQA "C# (Mono) โ€“ Try It Online") Uses `System.BitConverter.DoubleToInt64Bits` instead of the `unsafe` code as I couldn't get TIO to work with it. Full/Formatted Version: ``` namespace System { class P { static void Main() { Func<double, long> f = d => { unsafe { long l = *(long*)&d, s = 0; for (; l != 0; l *= 2) s -= l >> 63; return s; } }; Console.WriteLine(f(22)); Console.WriteLine(f(714)); Console.WriteLine(f(0)); Console.WriteLine(f(1)); Console.WriteLine(f(4503599627370496)); Console.WriteLine(f(4503599627370495)); Console.WriteLine(f(1024)); Console.WriteLine(f(-1024)); Console.WriteLine(f(-4096)); Console.WriteLine(f(1000000000)); Console.WriteLine(f(-12345678)); Console.ReadLine(); } } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes -12 bytes, thanks to @ASCII-only ``` lambda n:bin(*unpack('Q',pack('d',n))).count('1') from struct import* ``` [Try it online!](https://tio.run/##XY2xCsIwFEV3vyJbkvIqSZo0tqBf0MVZHdpKMWhfQkwHvz4Wiot3OFwOF274pIdHlbvjNb/6ebj3BNvBISsWDP34ZPRMYSt3Csg5349@wcSopHw3RT@Td4rLmIibg4@pyJOPxBGH5KIUWKlBgARtRGWapla2skI39b8wIIXSUG7UYl1I8cuqVaVNbQ@3loTocD0DWp4odMzx/AU "Python 2 โ€“ Try It Online") [Answer] # x86-64 machine code, 12 bytes for `int64_t` input # 6 bytes for `double` input Requires the [`popcnt` ISA extension](http://felixcloutier.com/x86/POPCNT.html) (`CPUID.01H:ECX.POPCNT [Bit 23] = 1`). (Or 13 bytes if modifying the arg in-place requires writing all 64-bits, instead of leaving garbage in the upper 32. I think it's reasonable to argue that the caller would probably only want to load the low 32b anyway, and x86 zero-extends from 32 to 64 implicitly with every 32-bit operation. Still, it does stop the caller from doing `add rbx, [rdi]` or something.) x87 instructions are shorter than the more obvious SSE2 `cvtsi2sd`/`movq` (used in [@ceilingcat's answer](https://codegolf.stackexchange.com/questions/136349/float-754-to-hamming/136360#136360)), and a `[reg]` addressing mode is the same size as a `reg`: just a mod/rm byte. The trick was to come up with a way to have the value passed in memory, without needing too many bytes for addressing modes. (e.g. passing on the stack isn't that great.) Fortunately, [the rules allow read/write args, or separate output args](https://codegolf.meta.stackexchange.com/a/4942/30206), so I can just get the caller to pass me a pointer to memory I'm allowed to write. Callable from C with the signature: `void popc_double(int64_t *in_out);` Only the low 32b of the result is valid, which is maybe weird for C but natural for asm. (Fixing this requires a REX prefix on the final store (`mov [rdi], rax`), so one more byte.) On Windows, change `rdi` to `rdx`, since Windows doesn't use the x86-64 System V ABI. NASM listing. The TIO link has the source code without the disassembly. ``` 1 addr machine global popcnt_double_outarg 2 code popcnt_double_outarg: 3 ;; normal x86-64 ABI, or x32: void pcd(int64_t *in_out) 4 00000000 DF2F fild qword [rdi] ; int64_t -> st0 5 00000002 DD1F fstp qword [rdi] ; store binary64, using retval as scratch space. 6 00000004 F3480FB807 popcnt rax, [rdi] 7 00000009 8907 mov [rdi], eax ; update only the low 32b of the in/out arg 8 0000000B C3 ret # ends at 0x0C = 12 bytes ``` [**Try it online!**](https://tio.run/##dVLRjtsgEHzPV8xjUjm9NHF8l4tUqVVfKvUPqsoCQxx0DlAWEvvrU8Cyrz1d/YI93pmd2YURyQvvhrVmdLnf285w1sEa22hfCxN4J2sTPHPt4j3weYH4HI/od1sYB23cJfL7p2pdlfjy9fszrkYJ2EYslfZVWXt8UDqxV5l6Up3A75txAvjphPqV9TDVrj@D/GasJG/fqSRvnARXmrmhKgsEUrqFk/4afTACNY755gyyrJEfs9IYBI71xaiU0Yu5piMDBSTrR/1gBfMSRncD/FmiMzfsthzmlD@VfohZkOaT6mPfaYY1xQH5xXiMc5rb5NZYf5rR419wud/s9odDtX3cPW7Kwz7beANWi5lqA50T800HoQo4sjPasO4/e31VMjYTJ0@4qchppUfLHGdtSptDB2uli1MowGN2GqiWvfJQbVy/JMTXpXWmkUTIP@IIfIg4zRPkg5erfx3LFL7azGCUzZ5nN1OfJZYh3o@n2q9igrTmV6V4E38Y8zIZ/SZ5aOEZxylezoRkP40R8v4H "Assembly (nasm, x64, Linux) โ€“ Try It Online") Includes a `_start` test program that passes it a value and exits with exit status = popcnt return value. (Open the "debug" tab to see it.) Passing separate input/output pointers would also work (rdi and rsi in the x86-64 SystemV ABI), but then we can't reasonably destroy the 64-bit input or as easily justify needing a 64-bit output buffer while only writing the low 32b. If we do want to argue that we can take a pointer to the input integer and destroy it, while returning output in `rax`, then simply omit the `mov [rdi], eax` from `popcnt_double_outarg`, bringing it down to 10 bytes. --- ## Alternative without silly calling-convention tricks, 14 bytes use the stack as scratch space, with `push` to get it there. Use `push`/`pop` to copy registers in 2 bytes instead of 3 for `mov rdi, rsp`. (`[rsp]` always needs a SIB byte, so it's worth spending 2 bytes to copy `rsp` before three instructions that use it.) Call from C with this signature: `int popcnt_double_push(int64_t);` ``` 11 global popcnt_double_push 12 popcnt_double_push: 13 00000040 57 push rdi ; put the input arg on the stack (still in binary integer format) 14 00000041 54 push rsp ; pushes the old value (rsp updates after the store). 15 00000042 5A pop rdx ; mov rdx, rsp 16 00000043 DF2A fild qword [rdx] 17 00000045 DD1A fstp qword [rdx] 18 00000047 F3480FB802 popcnt rax, [rdx] 19 0000004C 5F pop rdi ; rebalance the stack 20 0000004D C3 ret next byte is 0x4E, so size = 14 bytes. ``` --- # Accepting input in `double` format The question just says it's an integer in a certain range, not that it has to be in a base2 binary integer representation. Accepting `double` input means there's no point in using x87 anymore. (Unless you use a custom calling convention where `double`s are passed in x87 registers. Then store to the red-zone below the stack, and popcnt from there.) **11 bytes:** ``` 57 00000110 66480F7EC0 movq rax, xmm0 58 00000115 F3480FB8C0 popcnt rax, rax 59 0000011A C3 ret ``` But we can use the same pass-by-reference trick as before to make a 6-byte version: `int pcd(const double&d);` ``` 58 00000110 F3480FB807 popcnt rax, [rdi] 59 00000115 C3 ret ``` **6 bytes**. [Answer] # [Perl 5](https://www.perl.org/), ~~33~~ 32 + 1 (-p) = ~~34~~ 33 bytes *Saved 1 byte thanks to hobbs* ``` $_=(unpack"B*",pack d,$_)=~y/1// ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lajNK8gMTlbyUlLSQfEUEjRUYnXtK2r1DfU1///38joX35BSWZ@XvF/3QIA "Perl 5 โ€“ Try It Online") [Answer] ## JavaScript (ES6), ~~81~~ ~~80~~ ~~77~~ 76 bytes ``` f= n=>new Uint8Array(Float64Array.of(n).buffer).map(g=i=>i&&g(i&i-1,x++),x=0)|x ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o>0 ``` Edit: Saved 1 byte thanks to @Arnauld. Saved 3 bytes thanks to @DocMax. Saved 1 byte thanks to @l4m2. [Answer] ## MATLAB, 36 bytes ``` @(n)nnz(de2bi(typecast(n,'uint64'))) ``` Using the fact that `de2bi` is not only shorter than `dec2bin`, but also provides a result in ones and zeroes rather than ASCII 48, 49. [Answer] # Java (64, 61, 41 bytes) Completely straightforward using the standard library (Java SE 5+): ``` int f(long n){return Long.[bitCount](https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html#bitCount-long-)(Double.[doubleToLongBits](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#doubleToLongBits-double-)(n));} ``` Contribution by Kevin Cruijssen (Java SE 5+): ``` int f(Long n){return n.bitCount(Double.doubleToLongBits(n));} ``` Contribution by Kevin Cruijssen (Java SE 8+, lambda function): ``` n->n.bitCount(Double.doubleToLongBits(n)) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~79~~76 bytes ``` n=>n&&((g=n=>t=n.toString(2))(n)+g(t.length*2-(n<0)+2044)).split`1`.length-2 ``` [Try it online!](https://tio.run/##hY5BDoIwEEX3HoRMJTTt0FJJrJfwAhDEimmmBBqvX1nowpTEWU3en7w/z/7Vr8MyzbGicBvT3SayFyoKAGe3LVriMVzjMpEDZAyIlQ4i9yO5@DhiBXQWrEShFGN8nf0UO9l94grTEGgNfuQ@OLgDbobDLzJSZUxkRGYkNyktat22DZraCNU2/w503iIwf6bap0rsNEjxnR0N1ko35sRYegM "JavaScript (Node.js) โ€“ Try It Online") ~~First answer not relying on cast?~~ At least [this](https://codegolf.stackexchange.com/a/136411/) is earlier [Answer] Just to try a different, safer-than-[TheLethalCoder's](https://codegolf.stackexchange.com/a/136359/70347) approach, I came up with this (it's a pity C# has such long method names): # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 76+13 bytes ``` d=>Convert.ToString(BitConverter.DoubleToInt64Bits(d),2).Split('1').Length-1 ``` [Try it online!](https://tio.run/##nY/BS8MwFMbv/StyWwJrSdO0tcztoCIIE4QOPIiHmGY10CWSvA5E/NtrVzfnzeB3eIeX3/e9L9LH0jo19F6bFtXvHtRuEUVolOyE9@jB2daJ3bT5mOZBHgRoifZWN@heaIM9uDHg6RkJ13ryw50dB932Rl42tn/p1BxpAyu0RctoaJara2v2ykGysfUUhK80HHfKJTeTZWPvDBR8fPG4IXNGkvqt04Bn6Ywka2VaeI3T4Vj@pDHE204lj06DWmuj8BYzRsjiT6pMeQhGQ6A0BOI5zfKqKliZlZRXxT88eVAZyoJ@FgeDnIa1TelJYfdZxvOivPgNf0bfc/gC "C# (.NET Core) โ€“ Try It Online") Byte count includes 13 bytes for `using System;`. First I need to convert the `double` to a `long` that has the same binary representation, then I can convert it to a binary `string`, and then I count the `1`s just by splitting the string and counting the substrings minus 1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ABยฉL+โฝยกรŸB;ยฎฤ‹1_>0$a@ ``` [Try it online!](https://tio.run/##y0rNyan8/9/R6dBKH@1HjXsPLTw838n60Loj3YbxdgYqiQ7/D7c/alrz/3@0kZGOuaGJjoGOoY6JqYGxqaWlmZG5sbmBiaUZuoCpjqGBkYmOLoQ0MQCqMDSAAaCwkbGJqZm5RSwA "Jelly โ€“ Try It Online") [Answer] # dc, 79 bytes ``` [pq]su[-1r]st0dsb?dd0=u0>tsa[1+]ss[la2%1=slb1+sblad2/sa1<r]dsrxlb1022+sa0lrx+1- ``` Output is left on top of the stack. I'll add an explanation later. [Try it online!](https://tio.run/##Dcg5DoAwDATA11BFCNucBcdDogg5uEwBWZD4fWDKsaMUf14Bj685B9xkiJsZLQ@tN9SzC4BPKhUvSJEdYlKTBspzDob8/kkiDkopv47rs5Sdpe36YZw@) Note that negative numbers are preceded by `_`, not `-`. [Answer] # [Groovy (with Parrot parser)](https://github.com/danielsun1106/groovy-parser), 46 bytes ``` f=n->Long.bitCount(Double.doubleToLongBits(n)) ``` [Answer] # C, 67 bytes ``` int i;g(char*v){int j=v[i/8]&1<<i%8;return!!j+(++i<64?g(v):(i=0));} ``` control code and results ``` #define R return #define u32 unsigned #define F for #define P printf int main() {/* 5 6 0 10 5 55 3 4 16*/ double v[]={22,714,0,1 ,4503599627370496,4503599627370495,1024, -1024, -12345678}; int i; F(i=0;i<9;++i) P("%f = %d\n", v[i], g(&v[i])); R 0; } >tri4 22.000000 = 5 714.000000 = 6 0.000000 = 0 1.000000 = 10 4503599627370496.000000 = 5 4503599627370495.000000 = 55 1024.000000 = 3 -1024.000000 = 4 -12345678.000000 = 16 ``` [Answer] # Erlang 55 bytes ``` fun(X)->length([Y||<<Y:1>><=<<X:64/float>>,Y=:=1])end. ``` An anonymous function that counts all the `1`s in a number encoded as a 64 bit float. references: * <http://erlang.org/doc/programming_examples/bit_syntax.html> * <http://erlang.org/doc/programming_examples/list_comprehensions.html> [Answer] # [Husk](https://github.com/barbuz/Husk), 20 bytes ``` &->0ยฑยนฮฃS+ศฏแธ‹+1022Lแธ‹aยน ``` [Try it online!](https://tio.run/##yygtzv6fm18erPOoqfG/mq6dwaGNh3aeWxysfWL9wx3d2oYGRkY@QEbioZ3///@PNjLSMTc00THQMdQxMTUwNrW0NDMyNzY3MLE0Qxcw1QHqNdHRhZAmBkAVhgYwABQ2MjYxNTO3iAUA "Husk โ€“ Try It Online") A port of [Leaky Nun's Python 3 answer](https://codegolf.stackexchange.com/a/136411/). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ฤ€iร„bDgลฝ42+bยซ1ยขId- ``` Port of [*@LeakyNun*'s Python 3 answer](https://codegolf.stackexchange.com/a/136411/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f//SEPm4ZYkl/Sje02MtJMOrTY8tMgzRff/f10TA0szAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/yMNmYdbklzSj@41MdJOOrTa8NCiyhTd/7U6/6ONjHTMDU10DHQMdUxMDYxNLS3NjMyNzQ1MLM3QBUx1DA2MTHR0IaSJAVCFoQEMAIWNjE1MzcwtYgE). **Explanation:** ``` ฤ€i # If the (implicit) input-integer is NOT 0: ร„ # Take the absolute value of the (implicit) input-integer b # Convert it to binary Dg # Duplicate it, then pop and push its length ลฝ42+ # Add compressed integer 1022 to this length b # Convert it to binary as well ยซ # Merge the two binary-strings together 1ยข # Count the amount of 1s in this string Id # Check that the input-integer is non-negative (1 if >=0; 0 if <0) - # Subtract that from the count # (after which it is output implicitly as result) # (implicit else: output the implicit input, which is 0) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ลฝ42` is `1022`. [Answer] # [Rust](https://www.rust-lang.org/), 27 bytes ``` |n|n.to_bits().count_ones() ``` [Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6FZrcCloJCTWqKQZpWWp5FmZqKpaxdvq/C/Jq8mT68kPz4ps6RYQ1MvOb80ryQ@Py8VyPlvDdSSWFycWlQSn1qoqGGsk6ZhaGBkoqepiSZjApTRxS5lAJQyAAvX/gcA "Rust โ€“ Try It Online") An anonymous function that takes in an f64 and outputs a u32. The `to_bits` function reinterprets the bits of an f64 into a u64, where I can use the convenient `count_ones` function to trivialize the problem. ]
[Question] [ Take a positive integer **n** as input, and output a **n-by-n** checkerboard matrix consisting of **1** and **0**. The top left digit should always be **1**. **Test cases:** ``` n = 1 1 n = 2 1 0 0 1 n = 3 1 0 1 0 1 0 1 0 1 n = 4 1 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 ``` Input and output formats are optional. Outputting the matrix as a list of lists is accepted. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes 52 seconds! ``` +โ‚ฌแธถแธ‚ ``` [Try it online!](https://tio.run/##y0rNyan8/1/7UdOahzu2PdzR9P//fxMA "Jelly โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` :otYT ``` Try it at [**MATL online!**](https://matl.io/?code=%3AotYT&inputs=4&version=20.2.1) ### Explanation Consider input `4` as an example. ``` : % Implicit input, n. Push range [1 2 ... n] % STACK: [1 2 3 4] o % Parity, element-wise % STACK: [1 0 1 0] t % Duplicate % STACK: [1 0 1 0], [1 0 1 0] YT % Toeplitz matrix with two inputs. Implicit display % STACK: [1 0 1 0; % 0 1 0 1; % 1 0 1 0; 5 0 1 0 1] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` ร†ร‡+X v ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=xscrWCB2&input=NSAtUQ==) (Uses `-Q` flag for easier visualisation) ### Explanation ``` ร† ร‡ +X v UoX{UoZ{Z+X v}} // Ungolfed // Implicit: U = input number UoX{ } // Create the range [0...U), and map each item X to UoZ{ } // create the range [0...U), and map each item Z to Z+X // Z + X v // is divisible by 2. // Implicit: output result of last expression ``` An interesting thing to note is that `v` is *not* a "divisible by 2" built-in. Instead, it's a "divisible by X" built-in. However, unlike most golfing languages, Japt's functions do not have fixed arity (they can accept any number of right-arguments). When given 0 right-arguments, `v` assumes you wanted `2`, and so acts exactly like it was given `2` instead of nothing. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~16~~, 15 bytes ``` ร€i10ร€ยญรฑร™xรฑรŽร€lD ``` [Try it online!](https://tio.run/##K/v//3BDpqGB9OGGQ2sPbzw8swJI9B1uyHH5//@/OQA "V โ€“ Try It Online") Hexdump: ``` 00000000: c069 3130 1bc0 adf1 d978 f1ce c06c 44 .i10.....x...lD ``` [Answer] ## [Haskell](https://www.haskell.org/), ~~50~~ ~~41~~ ~~39~~ 38 bytes *Thanks to nimi and xnor for helping to shave off a total of ~~9~~ 10 bytes* ``` f n=r[r"10",r"01"]where r=take n.cycle ``` Alternately, for one byte more: ``` (!)=(.cycle).take f n=n![n!"10",n!"01"] ``` or: ``` r=flip take.cycle f n=r[r"10"n,r"01"n]n ``` Probably suboptimal, but a clean, straightforward approach. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 8 bytes ``` ~2|โณโˆ˜.+โณ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24Q6o5pHvZsfdczQ0wbSQLFDK4C0CQA "APL (Dyalog Unicode) โ€“ Try It Online") ### Explanation Let's call the argument `n`. ``` โณโˆ˜.+โณ ``` This creates a matrix ``` 1+1 1+2 1+2 .. 1+n 2+1 2+2 2+3 .. 2+n ... n+1 n+2 n+3 .. n+n ``` Then `2|` takes modulo 2 of the matrix (it vectorises) after which `~` takes the NOT of the result. [Answer] ## JavaScript ES6, ~~55~~ ~~54~~ ~~51~~ 46 bytes *Saved 1 byte thanks to @Neil* *Saved 2 bytes thanks to @Arnauld* ``` n=>[...Array(n)].map((_,i,a)=>a.map(_=>++i&1)) ``` [Try it online!](https://vihan.org/p/tio/?l=javascript-node&p=y0ktUUizVciztYvW09NzLCpKrNTI04zVy00s0NCI18nUSdS0tUuEcbOAnLpM7Sw1Q01NLq7k/Lzi/JxUvZz8dI00DaCQNZqQEaaQMaaQCVDoPwA) This outputs as an array of arrays. JavaScript ranges are pretty unweildy but I use `[...Array(n)]` which generates an array of size `n` [Answer] ## Mathematica, 25 bytes ``` 1-Plus~Array~{#,#}~Mod~2& ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~33~~ 30 bytes ``` .+ $* 1 $_ยถ 11 10 T`10`01`ยถ.+ยถ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEsl/tA2LkNDLkMDrpAEQ4MEA8OEQ9v0tA9t@//fFAA "Retina โ€“ Try It Online") Explanation: The first stage converts the input to unary using `1`s (conveniently!) while the second stage turns the value into a square. The third stage inverts alternate bits on each row while the last stage inverts bits on alternate rows. Edit: Saved 3 bytes thanks to @MartinEnder. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes -2 bytes thanks to Emigna ``` LDรˆD_โ€šรจ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx@Vwh0v8o4ZZh1f8/28MAA "05AB1E โ€“ Try It Online") ### Explanation ``` LDรˆD_โ€šsรจยป Argument n LD Push list [1 .. n], duplicate รˆD Map is_uneven, duplicate _ Negate boolean (0 -> 1, 1 -> 0) โ€š List of top two elements of stack รจ For each i in [1 .. n], get element at i in above created list In 05AB1E the element at index 2 in [0, 1] is 0 again ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` :t!+2\~ ``` [Try it online!](https://tio.run/##y00syfn/36pEUdsopu7/fxMA "MATL โ€“ Try It Online") **Explanation:** ``` % Implicit input (n) : % Range from 1-n, [1,2,3] t % Duplicate, [1,2,3], [1,2,3] ! % Transpose, [1,2,3], [1;2;3] + % Add [2,3,4; 3,4,5; 4,5,6] 2 % Push 2 [2,3,4; 3,4,5; 4,5,6], 2 \ % Modulus [0,1,0; 1,0,1; 0,1,0] ~ % Negate [1,0,1; 0,1,0; 1,0,1] ``` Note: I started solving this in MATL *after* I posted the challenge. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` ^โ‚‚โŸฆโ‚%โ‚‚แต;?แธโ‚Žpแต.\ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@5RU9Oj@cseNTWqAlkPt06wtn@4o/dRU18BkK0X8/@/6f8oAA "Brachylog โ€“ Try It Online") ### Explanation ``` Example Input: 4 ^โ‚‚ Square: 16 โŸฆโ‚ 1-indexed Range: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] %โ‚‚แต Map Mod 2: [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0] ;?แธโ‚Ž Input-Chotomize: [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]] pแต. Map permute such that.. .\ ..the output is its own transpose: [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]] ``` [Answer] ## Clojure, 36 bytes ``` #(take %(partition % 1(cycle[1 0]))) ``` Yay, right tool for the job. [Answer] # [J](http://jsoftware.com/), 9 bytes ``` <0&=$&1 0 ``` [Try it online!](https://tio.run/##y/r/P03B1krBxkDNVkXNUMGAiys1OSNfIU3B5P9/AA "J โ€“ Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~80~~ 77 bytes -3 bytes thanks to Kevin Cruijssen ``` j->{String s="1";for(int i=1;i<j*j;s+=i++/j+i%j&1)s+=1>i%j?"\n":"";return s;} ``` [Try it online!](https://tio.run/##LU69asMwEJ6dpzgELXbdqBgyVbG7FTp0yth2UB3ZnKqchHQKhOBndwXJdN8/Z/VZb30wZI9/a8i/DkcYnU4JPjXSdVPdtcSayzl7PMKpOPWBI9L89QM6zqkpwcqWKZkZnZwyjYye5Psd7D@IzWziM9xqA0zQr3Y7XG8cUi86oSYfayQG7DuFe/tkVWp7bNsX2@KDfeyaQruhwDfxTeJVCBUN50iQ1LJWlSpPHC6JzUn6zDKUZXZUT1KH4C71rmlKYtks6z8 "Java (OpenJDK 8) โ€“ Try It Online") Oh look, a semi-reasonable length java answer, with lots of fun operators. lambda which takes an int and returns a String. Works by using the row number and column number using / and % to determine which value it should be, mod 2; Ungolfed: ``` j->{ String s="1"; for(int i=1; i<j*j; s+= i++/j + i%j&1 ) s+= 1>i%j ? "\n" : ""; return s; } ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes ``` แต’+โ†’2% ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fisfbp2k_ahtkpHqkuKk5GKo6ILlhlxGXMZcJhAuAA) ``` แต’+โ†’2% แต’+ Create an (input x input) matrix where the element at (i,j) is i+j โ†’ Increment 2% Mod 2 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes ``` โŸฆโ‚Rg;Rz{z{++โ‚%โ‚‚}แต}แต ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGoPSrYOqqquqtbWBHNVHTU21D7dOAOH//03@RwEA "Brachylog โ€“ Try It Online") [Answer] # Charcoal, 8 bytes ``` ๏ผต๏ผฏ๏ผฎ10ยถ01 ``` [Try it online!](https://tio.run/##ARwA4/9jaGFyY29hbP//77y177yv77yuMTDCtjAx//81 "Charcoal โ€“ Try It Online") Explanation: This roughly translates to the following verbose code (unfortunately the deverbosifier is currently appending an unnecessary separator): ``` Oblong(InputNumber(), "10\n01"); ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` VQm%+hdN2 ``` [Try this!](https://pyth.herokuapp.com/?code=VQm%25%2BhdN2&input=10&debug=0) another 9 byte solution: ``` mm%+hdk2Q ``` [Try it!](https://pyth.herokuapp.com/?code=mm%25%2Bhdk2Q&input=10&debug=0) [Answer] # [///](https://esolangs.org/wiki////), 87 bytes + input ``` /V/\\\///D/VV//*/k#D#k/k#D&k/k&DVk/k\D/SD/#/r DSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&[unary input in asterisks] ``` [Try it online!](https://tio.run/##FcohCsAwEERR32ssRNT8RMfuDQKjYioKhVQl9yfdDswbM@u91nOvvRG9d8CR4GSY2/hNYXKF3WmOMQ9vY1ByDMUTsinLs0o5qlIV10kjnZG9Pw "/// โ€“ Try It Online") (input for 4) ## Unary input in `1`s, 95 bytes + input ``` /V/\\\///D/VV//&1/k#&D&|D/#k/k#D&k/k&DVk/k\D/SD/#/r DSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&&[unary input in ones]| ``` [Try it online!](https://tio.run/##LYoxCsQwEAP7@4Zh2/HWafcHBlVuUgQOnMpu83dniwg0EkLrPtf/Wnsjeu9AIIE5o1jYE5SRNSxpoWQPWq7MX7Qx8JqBh6EyVeo8pJqWH8rrpGHmn569Xw "/// โ€“ Try It Online") (input for 8) ### How does this work? * `V` and `D` are to golf `\/` and `//` respectively. * `/*/k#/` and `/&1/k#&//&|//` separate the input into the equivalent of `'k#'*len(input())` * `/#k//k#//&k/k&//\/k/k\//` move all the `k`s to the `/r/S/` block * `S`s are just used to pad instances where `k`s come after `/`s so that they don't get moved elsewhere, and the `S`s are then removed * `#`s are then turned into `r\n`s * The string of `k`s is turned into an alternating `1010...` string * The `r\n`s are turned into `1010...\n`s * Every pair of `1010...\n1010\n` is turned into `1010...\01010...;\n` * Either `0;` or `1;` are trimmed off (because the `01010...` string is too long by 1) [Answer] # Mathematica, 23 bytes ``` ToeplitzMatrix@#~Mod~2& ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 24 bytes ``` @(n)~mod((a=(1:n))+a',2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjT7MuNz9FQyPRVsPQKk9TUztRXcdI83@ahonmfwA "Octave โ€“ Try It Online") --- Or the same length: ``` @(n)mod(toeplitz(1:n),2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzM3P0WjJD@1ICezpErD0CpPU8dI83@ahonmfwA "Octave โ€“ Try It Online") [Answer] # [R](https://www.r-project.org/), ~~38~~ 37 bytes ``` n=scan();(matrix(1:n,n,n,T)+1:n-1)%%2 ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTWiM3saQos0LD0CpPBwRDNLWBTF1DTVVVo/8m/wE "R โ€“ Try It Online") -1 byte thanks to Giuseppe Takes advantage of R's recycling rules, firstly when creating the matrix, and secondly when adding 0:(n-1) to that matrix. [Answer] ## Swi-Prolog, 142 bytes. ``` t(0,1). t(1,0). r([],_). r([H|T],H):-t(H,I),r(T,I). f([],_,_). f([H|T],N,B):-length(H,N),r(H,B),t(B,D),f(T,N,D). c(N,C):-length(C,N),f(C,N,1). ``` Try online - <http://swish.swi-prolog.org/p/BuabBPrw.pl> It outputs a nested list, so the rules say: * `t()` is a toggle, it makes the 0 -> 1 and 1 -> 0. * `r()` succeeds for an individual row, which is a recursive check down a row that it is alternate ones and zeros only. * `f()` recursively checks all the rows, that they are the right length, that they are valid rows with `r()` and that each row starts with a differing 0/1. * `c(N,C)` says that C is a valid checkerboard of size N if the number of rows (nested lists) is N, and the helper f succeeds. Test Cases: [![enter image description here](https://i.stack.imgur.com/8AH2d.png)](https://i.stack.imgur.com/8AH2d.png) [Answer] # C, ~~69~~ ~~67~~ 63 bytes *Thanks to @Kevin Cruijssen for saving two bytes and @ceilingcat for saving four bytes!* ``` i,j;f(n){for(i=n;i--;puts(""))for(j=n;j;)printf("%d",j--+i&1);} ``` [Try it online!](https://tio.run/##Zcy7CoAwDIXh3aeQgpKgGbxswYeRSiUFq3iZxGevEXTyTD/fcCyN1sYopWcHAU83ryBdYCHi5dg3MAbxQa/oGZdVwu7AZIMpPVEheYV8RcV06iUAJmeS6hyofwf8Uv2n5k@t1hVv) [Answer] # [Arturo](https://arturo-lang.io), ~~39~~ 36 bytes ``` $[n][map..1n'x->map..1n'y->%x+y+1 2] ``` [Try it](http://arturo-lang.io/playground?MhWhVe) -3 thanks to alephalpha's simpler method Prettified and rearranged for clarity: ``` $[n][ ; a function taking an argument n map 1..n 'x -> ; map over 1..n, assign current elt to x map 1..n 'y -> ; map over 1..n again, assign current elt to y (x+y+1)%2 ; what it looks like ] ; end function ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` สโˆท:v= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgeKItzp2PSIsIiIsIjQiXQ==) *-3 thanks to @lyxal* *-1 thanks to @emanresuA* #### Explanation ``` สโˆท:v= implicit input ส range(input) โˆท mod 2 : duplicate v= equals, vectorised over the top list (generates a nested list) ``` Old: ``` ษพโˆทแบ‹โฝโ€ แบ‡ implicit input ษพ range(1, input+1) โˆท mod 2 แบ‹ repeated input times แบ‡ apply to every 2nd item: โฝโ€  vectorised not ``` ``` ส:โˆท:โ€ $"$ฤฐ implicit input ส: range, duplicate โˆท: mod 2, duplicate โ€  vectorised not $" swap and pair $ฤฐ swap and index in ``` [Answer] # TI-Basic, ~~30~~ 29 bytes ``` identity(Ansโ†’[A] Fill(1,[A] cumSum([A] 2fPart(.5(Ans+Ansแต€+[A] ``` Takes input in `Ans`. -1 byte thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 19 bytes ``` [:|?[b|?(a+c+1)%2'; ``` ## Explanation ``` [:| FOR a = 1 to b (b is read from cmd line) ? PRINT - linsert a linebreak in the output [b| FOR c = 1 to b ?(a+c+1)%2 PRINT a=c=1 modulo 2 (giving us the 1's and 0's '; PRINT is followed b a literal semi-colon, suppressing newlines and tabs. Printing numbers in QBasic adds one space automatically. ``` [Answer] # [PHP](https://php.net/), 56 bytes Output as string ``` for(;$i<$argn**2;)echo++$i%2^$n&1,$i%$argn?"":" ".!++$n; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkomT9Py2/SMNaJdMGLKSlZWStmZqcka@trZKpahSnkqdmqANkgSXtlZSslLiU9BSBknnW//9/zcvXTU5MzkgFAA "PHP โ€“ Try It Online") # [PHP](https://php.net/), 66 bytes Output as 2 D array ``` for(;$i<$argn**2;$i%$argn?:++$n)$r[+$n][]=++$i%2^$n&1;print_r($r); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkomT9Py2/SMNaJdMGLKSlZQRkq4LZ9lba2ip5mipF0UAqNjrWFsjNVDWKU8lTM7QuKMrMK4kv0lAp0rT@//9rXr5ucmJyRioA "PHP โ€“ Try It Online") ]
[Question] [ Here's a nice easy challenge: > > Given a string that represents a number in an unknown base, determine the lowest possible base that number might be in. The string will only contain `0-9, a-z`. If you like, you may choose to take uppercase letters instead of lowercase, but please specify this. You must output this lowest possible base in decimal. > > > Here is a more concrete example. If the input string was "01234", it is impossible for this number to be in binary, since 2, 3, and 4 are all undefined in binary. Similarly, this number cannot be in base 3, or base 4. Therefore, this number *must* be in base-5, or a higher base, so you should output '5'. Your code must work for any base between base 1 (unary, all '0's) and base 36 ('0-9' and 'a-z'). You may take input and provide output in any reasonable format. Base-conversion builtins are allowed. As usual, standard loopholes apply, and the shortest answer in bytes is the winner! # Test IO: ``` #Input #Output 00000 --> 1 123456 --> 7 ff --> 16 4815162342 --> 9 42 --> 5 codegolf --> 25 0123456789abcdefghijklmnopqrstuvwxyz --> 36 ``` [Answer] # Python, ~~27~~ 22 bytes ``` lambda s:(max(s)-8)%39 ``` This requires the input to be a bytestring (Python 3) or a bytearray (Python 2 and 3). *Thanks to @AleksiTorhamo for golfing off 5 bytes!* Test it on [Ideone](http://ideone.com/YXmMBD). ### How it works We begin by taking the maximum of the string. This the code points of letters are higher than the code points of digits, this maximal character is also the maximal base 36 digit. The code point of **'0' โ€“ '9'** are **48 โ€“ 57**, so we must subtract **48** from their code points to compute the corresponding digits, or **47** to compute the lowest possible base. Similarly, the code points of the letters **'a' โ€“ 'z'** are **97 โ€“ 122**. Since **'a'** represents the digit with value **10**, we must subtract **87** from their code points to compute the corresponding digits, or **86** to compute the lowest possible base. One way to achieve this is as follows. The difference between **97** and **58** (**':'**, the character after **'9'**) is **39**, so taking the code points modulo **39** can achieve the subtraction. Since **48 % 39 = 9**, and the desired result for the character **'0'** is **1**, we first subtract **8** before taking the result modulo **39**. Subtracting first is necessary since otherwise **'u' % 39 = 117 % 39 = 0**. ``` c n n-8 (n-8)%39 0 48 40 1 1 49 41 2 2 50 42 3 3 51 43 4 4 52 44 5 5 53 45 6 6 54 46 7 7 55 47 8 8 56 48 9 9 57 49 10 a 97 89 11 b 98 90 12 c 99 91 13 d 100 92 14 e 101 93 15 f 102 94 16 g 103 95 17 h 104 96 18 i 105 97 19 j 106 98 20 k 107 99 21 l 108 100 22 m 109 101 23 n 110 102 24 o 111 103 25 p 112 104 26 q 113 105 27 r 114 106 28 s 115 107 29 t 116 108 30 u 117 109 31 v 118 110 32 w 119 111 33 x 120 112 34 y 121 113 35 z 122 114 36 ``` [Answer] # Python, 25 bytes ``` lambda x:int(max(x),36)+1 ``` Defines a lambda that takes the string `x`. Finds the largest digit in the string (sorted with letters above digits, by python's default), and converts to base 36. Adds 1, because `8` is not in base 8. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แน€ร˜Bi ``` Requires uppercase. [Try it online!](http://jelly.tryitonline.net/#code=4bmAw5hCaQ&input=&args=J0NPREVHT0xGJw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmAw5hCaQrDh-KCrEc&input=&args=JzAwMDAwJywgJzEyMzQ1NicsICdGRicsICc0ODE1MTYyMzQyJywgJzQyJywgJ0NPREVHT0xGJywgJzAxMjM0NTY3ODlBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWic). ### How it works ``` แน€ร˜Bi Main link. Arguments: s (string) แน€ Yield the maximum of s. ร˜B Yield "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz". i Find the 1-based index of the maximum in that string. ``` [Answer] ## Haskell, 34 bytes ``` f s=length['\t'..maximum s]`mod`39 ``` Uses the `mod(ord(c)-8,39)` idea from Dennis. **41 bytes** ``` g '0'=1 g 'W'=1 g x=1+g(pred x) g.maximum ``` --- **45 bytes:** ``` (`elemIndex`(['/'..'9']++['a'..'z'])).maximum ``` Outputs like `Just 3`. [Answer] # [Cheddar](http://cheddar.vihan.org/), ~~34~~ ~~29~~ 21 bytes *Saved 8 bytes thanks to Dennis!!!* ``` s->(s.bytes.max-8)%39 ``` Uses lowercase letters [Try it online](http://cheddar.tryitonline.net/#code=cy0-KHMuYnl0ZXMubWF4LTgpJTM5&input=JzBmZic) ## Explanation ``` s -> ( // Input is `s` s.bytes // Returns array of char codes .max // Get maximum item in array ) % 39 // Modulus 39 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), 6 bytes ``` {ยค36รถ> ``` Takes letters in upper case. **Explanation** ``` { # sort ยค # take last 36รถ # convert from base 36 to base 10 > # increment ``` [Try it online](http://05ab1e.tryitonline.net/#code=e8KkMzbDtj4&input=Q09ERUdPTEY) [Answer] # [Actually](http://github.com/Mego/Seriously), 6 bytes ``` M6ยฒ@ยฟu ``` [Try it online!](http://actually.tryitonline.net/#code=TTbCskDCv3U&input=J0NPREVHT0xGJw) [Answer] # Julia, 22 bytes ``` !s=(maximum(s)-'')%39 ``` There's a BS character (0x08) between the quotes. [Try it online!](http://julia.tryitonline.net/#code=IXM9KG1heGltdW0ocyktJwgnKSUzOQpwcmludCghIjEyMyIp&input=) [Answer] ## JavaScript (ES6), ~~41~~ 37 bytes ``` s=>parseInt([...s].sort().pop(),36)+1 ``` Edit: Saved 4 bytes thanks to @edc65. [Answer] ## Haskell, ~~55~~ 40 bytes ``` f=(\y->mod(y-8)39).Data.Char.ord.maximum ``` Thanks @Dennis for his approach. (take that, @xnor ;)) [Answer] # Perl 6: 18 bytes ``` {:36(.comb.max)+1} ``` Defines a lambda that takes a single string argument, and returns an integer. It splits the string into characters, finds the "highest" one, converts it to base 36, adds 1. ``` {(.ords.max-8)%39} ``` This one uses the modulo approach from Dennis. Same length. [Answer] ## [Retina](https://github.com/m-ender/retina), 28 bytes ``` O`. .\B {2` $` }T01`dl`_o . ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApPYC4KLlxCCgp7MmAKJGAKfVQwMWBkbGBfbwou&input=MDAwMDAKMTIzNDU2CmZmCjQ4MTUxNjIzNDIKNDIKY29kZWdvbGYKMDEyMzQ1Njc4OWFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6) (The first line enables a linefeed-separated test suite.) ### Explanation ``` O`. ``` This sorts the characters of the input. ``` .\B ``` This removes all characters except the last, so the first two stages find the maximum character. ``` {2` $` }T01`dl`_o ``` These are two stages which form a loop. The first one duplicates the first character and the second one "decrements" it (replacing e.g. `x` with `w`, `a` with `9` and `1` with `0`). The latter stage encounters a zero as the first character, it removes it instead. This is a standard technique for generating a range of characters, given the upper end. Hence, this generates all "digits" from `0` to the maximum digit. ``` . ``` Finally, we simply count the number of digits, which gives us the base. [Answer] # R, ~~99~~ ~~89~~ 85 bytes Look ! Less than 100 bytes ! Look ! *10* bytes off ! Look ! *4* bytes off ! ``` ifelse((m=max(strsplit(scan(,''),"")[[1]]))%in%(l=letters),match(m,l)+10,strtoi(m)+1) ``` **Ungolfed :** ``` l=letters #R's built-in vector of lowercase letters n=scan(what=characters()) #Takes an input from STDIN and convert it to characters m=max(strsplit(n,"")[[1]]) #Splits the input and takes to max. #`letters` are considered > to numbers (i.e. a>1) ifelse(m%in%l,match(m,l)+10,strtoi(m)+1) #If the max is in `letters`, #outputs the matching position of `m`in `letters` + 10 (because of [0-9]). #Else, outputs `m` (as a number) + 1. ``` As often, this answer makes use of the `ifelse` function : `ifelse(Condition, WhatToDoIfTrue, WhatToDoElse)` [Answer] # Scala, 25 bytes `print((args(0).max-8)%39)` Run it like: `$ scala whatbase.scala 0123456789abcdefghijklmnopqrstuvwxyz` [Answer] # PHP, ~~51~~ 38 bytes (From Dennis) ^^ ``` <?=(ord(max(str_split($argv[1])))-8)%39; ``` Other proposal without Dennis' trick ``` <?=($a=max(str_split($argv[1])))<a?$a+1:ord($a)-86; ``` * Takes input as argument $argv[1]; * Take max character (using ASCII) values * If it is a number (inferior to < 'a' ascii value) then output number+1 * Else output ascii value -86 (97 for 'a' in ascii, -11 for 'a' is 11th base-digit) [Answer] # Octave, 20 bytes ``` @(a)mod(max(a)-8,39) ``` [Answer] ## Pyke, 6 bytes ``` Seb36h ``` [Try it here!](http://pyke.catbus.co.uk/?code=Seb36h&input=%22123456f%22&warnings=0) ``` Se - sorted(input)[-1] b36 - base(^, 36) h - ^ + 1 ``` [Answer] # Java 7, ~~67~~ 61 bytes ``` int c(char[]i){int m=0;for(int c:i)m=m>c?m:c;return(m-8)%39;} ``` `(m-8)%39` is thanks to [*@Dennis*' amazing answer](https://codegolf.stackexchange.com/a/90719/52210). **Ungolfed & test code:** [Try it here.](https://ideone.com/6m93TS) ``` class Main{ static int c(char[] i){ int m = 0; for(int c : i){ m = m > c ? m : c; } return (m-8) % 39; } public static void main(String[] a){ System.out.println(c("00000".toCharArray())); System.out.println(c("123456".toCharArray())); System.out.println(c("ff".toCharArray())); System.out.println(c("4815162342".toCharArray())); System.out.println(c("42".toCharArray())); System.out.println(c("codegolf".toCharArray())); System.out.println(c("0123456789abcdefghijklmnopqrstuvwxyz".toCharArray())); } } ``` **Output:** ``` 1 7 16 9 5 25 36 ``` [Answer] ## C89, ~~55~~ ~~53~~ ~~52~~ 50 bytes ``` f(s,b)char*s;{return*s?f(s+1,*s>b?*s:b):(b-8)%39;} ``` *`-8%39` shamelessly stolen from Dennis* ### Test ``` test(const char* input) { printf("%36s -> %u\n", input, f((char*)input,0)); } main() { test("00000"); test("123456"); test("ff"); test("4815162342"); test("42"); test("codegolf"); test("0123456789abcdefghijklmnopqrstuvwxyz"); } ``` ### Output ``` 00000 -> 1 123456 -> 7 ff -> 16 4815162342 -> 9 42 -> 5 codegolf -> 25 0123456789abcdefghijklmnopqrstuvwxyz -> 36 ``` *Saved 2 bytes thanks to Toby Speight* *Saved 2 bytes thanks to Kevin Cruijssen* [Answer] # C, 55 bytes This answer assumes that the input is in ASCII (or identical in the numbers and letters, e.g. ISO-8859 or UTF-8): ``` m;f(char*s){for(m=0;*s;++s)m=m>*s?m:*s;return(m-8)%39;} ``` We simply iterate along the string, remembering the largest value seen, then use the well-known modulo-39 conversion from base-{11..36}. # Test program ``` int printf(char*,...); int main(int c,char **v){while(*++v)printf("%s -> ",*v),printf("%d\n",f(*v));} ``` # Test results ``` 00000 -> 1 123456 -> 7 ff -> 16 4815162342 -> 9 42 -> 5 codegolf -> 25 0123456789abcdefghijklmnopqrstuvwxyz -> 36 ``` [Answer] # Mathematica, ~~34~~ 32 bytes *2 bytes saved thanks to Martin Ender* ``` Max@Mod[ToCharacterCode@#-8,39]& ``` I decided the different method deserved a new answer. method ~~stolen~~ inspired by Dennis' solution [Answer] # Mathematica, ~~34~~ 32 bytes *saved 2 bytes thanks to Martin Ender* ``` Max@BaseForm[Characters@#,36]+1& ``` Defines a pure function that takes a string as input. Splits the input into characters, converts them to base 36 numbers, and returns the maximum +1. [Answer] ## C# REPL, 17 bytes ``` x=>(x.Max()-8)%39 ``` Just ported @Dennis's answer to C#. [Answer] ## CJam, 10 bytes *Thanks to Martin Ender for saving me a few bytes!* Uses [Dennis's formula](https://codegolf.stackexchange.com/a/90719/53880) ``` q:e>8-i39% ``` [Try it online](https://codegolf.stackexchange.com/a/90719/53880) ## CJam, ~~18~~ 16 btyes Alternative solution: ``` A,s'{,97>+q:e>#) ``` [Try it online](http://cjam.aditsu.net/#code=A%2Cs'%7B%2C97%3E%2B%20%20%20%20%20%20%20e%23%20Push%20the%20string%20%220123456789abcdefghijklmnopqrstuvwxyz%22%0A%20%20%20%20%20%20%20%20%20%20q%20%20%20%20%20%20e%23%20Get%20the%20input%0A%20%20%20%20%20%20%20%20%20%20%20%3Ae%3E%20%20%20e%23%20Find%20the%20highest%20character%20in%20the%20input%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%20e%23%20Find%20the%20index%20of%20that%20character%20in%20the%20string%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)%20e%23%20Increment&input=543a) ``` A,s'{,97>+ e# Push the string "0123456789abcdefghijklmnopqrstuvwxyz" q e# Get the input :e> e# Find the highest character in the input # e# Find the index of that character in the string ) e# Increment ``` [Answer] ## R, ~~62~~ 54 bytes ``` max(match(strsplit(scan(,''),"")[[1]],c(0:9,letters))) ``` Ungolfed: ``` max( match( # 2: Finds the respective positions of these characters strsplit(scan(,''),"")[[1]], # 1: Breaks the input into characters c(0:9,letters)) # 3: In the vector "0123...yz" ) ``` Update: shaved off 8 bytes due to the redundancy of `na.rm=T` under the assumption of input validity. A 39% improvement in size compared to [Frรฉdรฉric's answer](https://codegolf.stackexchange.com/a/90759/49439). Besides that, it runs a wee bit faster: 0.86 seconds for 100000 replications versus 1.09 seconds for the competing answer. So the one of mine is both smaller and more efficient. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes ``` kr$GแธŸโ€บ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=kr%24G%E1%B8%9F%E2%80%BA&inputs=codegolf&header=&footer=) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Prompts for uppercase input. ``` โŒˆ/โžโณโจโŽ•D,โŽ•A ``` `โŒˆ/` maximum `โž` characters of input `โณโจ` 1-indexed into `โŽ•D,` all digits followed by `โŽ•A` all characters [TryAPL online!](http://tryapl.org/?a=%7B%u2308/%u2375%u2373%u2368%u2395D%2C%u2395A%7D%A8%2700000%27%20%27123456%27%20%27FF%27%20%274815162342%27%20%2742%27%20%27CODEGOLF%27%20%270123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ%27&run) [Answer] # BASH 70 ``` grep -o .|sort -r|head -c1|od -An -tuC|sed s/$/-86/|bc|sed s/-/39-/|bc ``` Input letters are lowercase. [Answer] # JavaScript, ~~57~~ ~~50~~ 48 bytes *7 bytes saved thnks to @kamaroso97* *2 bytes saved thanks to @Neil* ``` n=>Math.max(...[...n].map(a=>parseInt(a,36))+1) ``` Original answer: ``` n=>n.split``.map(a=>parseInt(a,36)).sort((a,b)=>b-a)[0]+1 ``` [Answer] ## Powershell, 62 bytes ``` function t($s){(($s[0..$s.Length]|measure -Max).Maximum-8)%39} ``` %39 @Dennis, of course :) ]
[Question] [ Given an integer array and two numbers as input, remove a certain amount of the first and last elements, specified by the numbers. The input can be in any order you want. You should remove the first *x* elements, where *x* is the first numerical input, and also remove the last *y* elements, where *y* is the second numerical input. The resulting array is guaranteed to have a length of at least two. ## Examples: ``` [1 2 3 4 5 6] 2 1 -> [3 4 5] [6 2 4 3 5 1 3] 5 0 -> [1 3] [1 2] 0 0 -> [1 2] ``` [Answer] # Haskell, ~~55~~ ~~39~~ ~~33~~ 29 bytes *Saved 16 bytes thanks to Laikoni* *Saved 6 more bytes thanks to Laikoni* *Saved 4 more bytes thanks to Laikoni* Am sure this could be improved, but as a beginner, gave it my best shot. ``` r=(reverse.).drop a#b=r b.r a ``` ## Usage ``` (5#0) [6,5,4,3,2,1,3] ``` [Try it online!](https://tio.run/##VcxBCoMwFATQvaeYRRcRvsFE4y4nCVkIRiq1Kl/p9dMYEdpZzcBjnv3@CvMcI1vB4RN4D7KUA69bMVohuZQibY7vflpgMawFNp6WAw@MUNBwijQ11JKhzgOoKrg8/a@sYeC6JNtkDSlqfJZn@Xd1fjyf7lxO@/gF) [Answer] # Mathematica, 17 bytes ``` #[[#2+1;;-#3-1]]& ``` **input** > > [{1, 2, 3, 4, 5, 6}, 2, 1] > > > [Answer] # Octave, 20 bytes ``` @(a,x,y)a(x+1:end-y) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNRp0KnUjNRo0Lb0Co1L0W3UvN/Yl6xRrSZgpGCiYKxgqmCoYJxrI6pjoHmfwA "Octave โ€šร„รฌ Try It Online") [Answer] # [Python](https://docs.python.org/3/), ~~28~~ 26 bytes *-2 bytes thanks to @Rod* ``` lambda a,n,m:a[n:len(a)-m] ``` [Try it online!](https://tio.run/##HY3BDoMgEETv/Yo5Ls020WI9kPRLkANNJTWR1SiXfj0Ce5qXN5Pd/@m3ic7hPeXVx8/Xw7NwNN6KWWchrx7R5bAdSPOZsAgs2Z7xZGjGwHgxRte4VwyyY8tD08WVqnYtdU3XaeGusjM3lNuPRRIFutcPSuUL "Python 3 โ€šร„รฌ Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 55 54 bytes ``` using System.Linq;(a,x,y)=>a.Skip(x).Take(a.Count-x-y) ``` [Try it online!](https://tio.run/##vVBNSwMxEL33Vww9JZANra29tN1LUVEUhAqeY5yW0GyiSbbuUva3x2xYFHoQT32HYZhM3sdIX0jrMNZemT1sWx@w4o/KfC5HI0iQWngPz87unajy5JRrDx9EUBKOVr3Dk1CG0J@n36UeA@1tbeRq6DdWa5RBWeP5HRp0SiZZH1bKhJJBqkP5Y//@xtQVOvGmMX8rYQfrUSSCNayl61Lw7UF9kIbyF3FAIhJJbULRFC2NQ7wzh5tEbzXyV6cCpisg8cGlw/AHm@KN2ZjBjhj8gv@kgBNMGVwxmDGYM7hmsIAuD6aU0uUl9BdZbp4tJP1kZ9ZbSO3kUhb6E/Sak3PNLnddjMUxFl5/Aw "C# (.NET Core) โ€šร„รฌ Try It Online") Uses a `List<int>` as input. * 1 byte saved thanks to TheLethalCoder! [Answer] # [Neim](https://github.com/okx-code/Neim), 3 bytes ``` ๏ฃฟรนรฏรฒโ€šร‡ร‰๏ฃฟรนรฏรด ``` [Try it here](http://178.62.56.56:80/neim?code=%F0%9D%95%98%E2%82%83%F0%9D%95%99&input=2%0A%5B1%202%203%204%205%206%5D%0A1) Thanks to Okx for [encouraging me](https://chat.stackexchange.com/transcript/message/38375386#38375386) to do this...:) [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 32 bytes ``` (l,i,j)->l.subList(i,l.size()-j) ``` [Try it online!](https://tio.run/##jY/BasMwDIbveQodbVBM0za9tCvsUhhspx7HDm7qBHtOYmynkI08e6Y0YWy3GoylX/r0y0beZNo61Zjr56hr1/oIhjTRRW3Fqw5xnyxyiDLq4k/12XvZByHD3Oa6i6V6YWUI8CZ1850A6CYqX8pCwQmmHGBqPryQXCl/BOmc7dl/zeKEgZ4fw/fEDXQXg2WPW6uvUJMNO0evm@r9A6SvAl9sTlDC08gsajQ8PVoRustkwzRSrL8U46nhI9zP/o6c@xBVLdouCkcTo21YKeYF5z@yDNe4wS3muOMIa4SM80fZHbFbonPMcEN0jrB6nCZnYla/zJAM4w8 "Java (OpenJDK 8) โ€šร„รฌ Try It Online") If we really restrict to arrays, then it's 53 bytes: ``` (a,i,j)->java.util.Arrays.copyOfRange(a,i,a.length-j) ``` [Try it online!](https://tio.run/##pc9Pa8MgFADwez7FO0Z4kaZtegkb7NJbKazHsYNLTaozKmo6Qslnz8wfGOxaQZ4@nr/3lOzOMmO5ltfvUbTWuAAy5mgXhKJvzrHel4ntvpSooFLMezgxoR8JgNCBu5pVHI4w3efMxycwa1WfrmeckiCWIEkZ64a4V9AHFmK4G3GFNrLpJTihm@mhazxZ2SPU8DKmDAVKkr3@H49Wxvbn@p3phs9FjCqum3DLJBlhXuXsXHofeEtNF6iNbYLS6SoEszROa7pMr/nP8ptHjlvc4R4LPAwIW4ScEPKEd4jePooF5riLYoGweU6ME0Zn8@cMyTD@Ag "Java (OpenJDK 8) โ€šร„รฌ Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 21 bytes 19 bytes of code + `-ap` flags. ``` $_="@F[<>..$#F-<>]" ``` [Try it online!](https://tio.run/##DYoxCoAwEAT7e8V6SZuQqJdGDVb5hIpY2IkE/w/xmh1m2Hp/jzTTVSVcvZo9F17LNmfvrSluzge3CfaEX8D7yy2ix4ARgkQ9RUrqoxZBxEBCgfShG34 "Perl 5 โ€šร„รฌ Try It Online") Uses `-a` to autosplit the input inside `@F`, then only keep a slice of it according to the other inputs: from index `<>` (second input) to index `$#F-<>` (size of the array minus third input). And `$_` is implicitly printed thanks to `-p` flag. [Answer] ## JavaScript (ES6), 27 bytes ``` (a,n,m)=>a.slice(n,-m||1/m) ``` A negative second parameter to `slice` stops slicing `m` from the end, however when `m` is zero we have to pass a placeholder (`Infinity` here, although `(a,n,m,o)=>a.slice(n,-m||o)` also works). [Answer] ## Rust, 29 bytes ``` |n,i,j|&n[i..<[_]>::len(n)-j] ``` Call it as follows: ``` let a = &[1, 2, 3, 4, 5, 6]; let f = |n,i,j|&n[i..<[_]>::len(n)-j]; f(a, 2, 1) ``` I had a lot of fun fighting with the borrow checker figuring out what the shortest approach was in order to have it infer the lifetime of a returned slice. Its behavior around closures is somewhat erratic, as it will infer the lifetimes, but only if you do not actually declare the parameter as a reference type. Unfortunately this conflicts with being required to define the argument type in the signature as the n.len method call needs to know the type it's operating on. Other approaches I tried working around this issue: ``` fn f<T>(n:&[T],i:usize,j:usize)->&[T]{&n[i..n.len()-j]} // full function, elided lifetimes let f:for<'a>fn(&'a[_],_,_)->&'a[_]=|n,i,j|&n[i..n.len()-j] // type annotation only for lifetimes. Currently in beta. |n:&[_],i,j|n[i..n.len()-j].to_vec() // returns an owned value |n,i,j|&(n as&[_])[i..(n as&[_]).len()-j] // casts to determine the type |n,i,j|&(n:&[_])[i..n.len()-j] // type ascription (unstable feature) |n,i,j|{let b:&[_]=n;&b[i..b.len()-j]} // re-assignment to declare the type ``` [Answer] # TIS-100, ~~413~~ 405 Bytes 472 cycles, 5 nodes, 35 lines of code ``` m4,6 @0 MOV 0 ANY S:MOV UP ACC JEZ A MOV ACC ANY JMP S A:MOV RIGHT ACC L:JEZ B MOV DOWN NIL SUB 1 JMP L B:MOV 0 RIGHT MOV RIGHT NIL @1 MOV RIGHT LEFT MOV LEFT DOWN MOV RIGHT DOWN MOV DOWN LEFT @2 MOV UP ACC MOV UP LEFT MOV ACC LEFT @4 MOV 0 RIGHT MOV UP NIL S:MOV LEFT ACC JEZ A MOV ACC RIGHT JMP S A:MOV UP ACC L:JEZ B MOV RIGHT NIL SUB 1 JMP L B:MOV 0 UP K:MOV RIGHT ACC MOV ACC DOWN JNZ K @7 MOV UP ANY ``` The m4,6 at the top is not part of the code, but signals the placement of the memory modules. [![enter image description here](https://i.stack.imgur.com/ZTSGJ.jpg)](https://i.stack.imgur.com/ZTSGJ.jpg) Play this level yourself by pasting this into the game: ``` function get_name() return "ARRAY TRIMMER" end function get_description() return { "RECIEVE AN ARRAY FROM IN.A", "RECIEVE TWO VALUES A THEN B FROM IN.T", "REMOVE THE FIRST A TERMS AND LAST B TERMS FROM IN.A", "ARRAYS ARE 0 TERMINATED" } end function get_streams() input = {} trim = {} output = {} arrayLengths = {} a = math.random(1,5) - 3 b = math.random(1,7) - 4 arrayLengths[1] = 9+a arrayLengths[2] = 9+b arrayLengths[3] = 8-a arrayLengths[4] = 9-b s = 0 trimIndex = 1 for i = 1,4 do for k = 1,arrayLengths[i] do x = math.random(1,999) input[k+s] = x output[k+s] = x end input[s + arrayLengths[i] + 1]= 0 output[s + arrayLengths[i] + 1]= 0 a = math.random(0,3) b = math.random(0,arrayLengths[i]-a) trim[trimIndex] = a trim[trimIndex+1] = b trimIndex = trimIndex + 2 s = s + arrayLengths[i] + 1 end s = 1 trimIndex = 1 for i = 1,4 do for i = s,s+trim[trimIndex]-1 do output[i]=-99 end for i = s + arrayLengths[i] - trim[trimIndex+1], s + arrayLengths[i]-1 do output[i]=-99 end trimIndex = trimIndex +2 s = s + arrayLengths[i] + 1 end trimmedOut = {} for i = 1,39 do if(output[i] ~= -99) then table.insert(trimmedOut, output[i]) end end return { { STREAM_INPUT, "IN.A", 0, input }, { STREAM_INPUT, "IN.T", 2, trim }, { STREAM_OUTPUT, "OUT.A", 1, trimmedOut }, } end function get_layout() return { TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_MEMORY, TILE_COMPUTE, TILE_MEMORY, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, } end ``` So I suppose this also counts as a lua answer... [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` QJi-h) ``` [Try it online!](https://tio.run/##y00syfn/P9ArUzdD8/9/Qy4jrmhDBSMFYwUzBQsFSwXjWAA "MATL โ€šร„รฌ Try It Online") Input is given as 1) number of elements to trim from the start; 2) number of elements to trim from the end; 3) array. Explanation ``` Q % Implicit input (1). Increment by 1, since MATL indexing is 1-based. Ji- % Complex 1i minus real input (2). In MATL, the end of the array is given by `1i`. h % Concatenate indices to get range-based indexing 1+(1):end-(2). ) % Index into (implicitly taken) input array. Implicit display. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` โ€šรœรฌโ€šรœรฌ_ ``` [Try it online!](https://tio.run/##yygtzv7//1HbZCCK////v@H/aEMdIx1jHRMdUx2z2P9GAA "Husk โ€šร„รฌ Try It Online") ### Explanation ``` | 1 [1,2,3,4,5,6] 2 _ -- negate y | -1 [1,2,3,4,5,6] 2 โ€šรœรฌ -- drop y from end (negative argument) | [1,2,3,4,5] 2 โ€šรœรฌ -- drop x from beginning | [3,4,5] ``` [Answer] # C#, 62 bytes ``` using System.Linq;(l,x,y)=>l.Where((n,i)=>i>=x&i<=l.Count-y-1) ``` Takes a `List<int>` as input and returns an `IEnumerable<int>`. --- This also works for 64 bytes: ``` using System.Linq;(l,x,y)=>l.Skip(x).Reverse().Skip(y).Reverse() ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` tniQwi-&:) ``` [Try it online!](https://tio.run/##y00syfn/vyQvM7A8U1fNSvP//2hDBSMFYwUTBVMFs1guIy5DAA "MATL โ€šร„รฌ Try It Online") ## Explanation: It's a bit long for just 11 bytes, but I'm writing it out in detail, to learn it myself too. ``` ---- Input ---- [1 2 3 4 5 6] 2 1 ----- Code ---- % Implicit first input t % Duplicate input. % Stack: [1 2 3 4 5 6], [1 2 3 4 5 6] n % Number of elements % Stack: [1 2 3 4 5 6], 6 i % Second input % Stack: [1 2 3 4 5 6], 6, 2 Q % Increment: [1 2 3 4 5 6], 6, 3 w % Swap last two elements % Stack: [1 2 3 4 5 6], 3, 6 i % Third input % Stack: [1 2 3 4 5 6], 3, 6, 1 - % Subtract % Stack: [1 2 3 4 5 6], 3, 5 &: % Range with two input arguments, [3 4 5] % Stack: [1 2 3 4 5 6], [3 4 5] ) % Use as index % Stack: [3 4 5] % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ยทฯ€รฑยฌยฐยทโˆรคโ€šร…ยฅยฌยฐ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4bmWwqHhuIrigbTCof///1sxLCAyLCAzLCA0LCA1LCA2Xf8y/zE "Jelly โ€šร„รฌ Try It Online") [Answer] # Dyalog APL, 16 bytes ``` {(โ€šรงยตโ€šรœรฌโ€šรงยฎโ€šรคร‰โ€šรงโˆซ)โ€šรœรฌโ€šรงยฎ-โ€šรงโˆซ[2]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGqNR71bH7VNftS74lFX86PeXZoQji6QGW0UW/v/v5GCoUIaEBspGCuYKJgqmHGZKhgARcyAIiZAMVOgnDGXAVgMqAoA) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~8~~ 7 bytes ``` โ€šรฅฮฉโ€šรฉรฏโ€šรœรฌโ€šรฅฮฉโ€šรฉรฏโ€šรœรฌโ€šรฉรฏ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKMdSPTsfdQ39VHbZASjbypI6n86l6GCkYKxgomCqYIZlxGXIVc6lxlQxAQoZqpgqGDMZcplwAVWBaQNAA "APL (Dyalog Unicode) โ€šร„รฌ Try It Online") This takes the array as the first input, followed by the two numbers separately. ### Explanation ``` โ€šรฉรฏ from the input array โ€šรฉรฏโ€šรœรฌ drop the first input elements โ€šรฅฮฉ reverse the array โ€šรฉรฏโ€šรœรฌ drop first input elements โ€šรฅฮฉ reverse again to go back to the original array ``` [Answer] # PHP>=7.1, 59 bytes ``` <?[$a,$b,$e]=$_GET;print_r(array_slice($a,$b,$e?-$e:NULL)); ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/aea18f7a87853a03a8772dd5b7dfaf37540ecd92) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 60 bytes ``` (()()){({}<{({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>>[()])}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU0NTs1qjutYGQtTaRWtoxmrWVtdqRMdqVgMpoKidpo0diFsLYsMV/P9vzMVlyGXEZcxlwmXKxWUAAA "Brain-Flak โ€šร„รฌ Try It Online") Input is in this format: ``` x a r r a y y ``` Where `x` is the number to take from the front, `y` is the number to take from the back, and the array is just however many numbers you want, separated by newlines. Here are my first two (longer) attempts: ``` ({}<>)<>{({}<{}>[()])}([])<>({}<><{{}({}<>)<>([])}{}><>){({}<{}>[()])}{}([]){{}({}<>)<>([])}<>{} {({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>{({}<{}>[()])}{}([]){{}({}<>)<>([])}<> ``` And here is an explanation: ``` #Two times: (()()){({}< #Remove *n* numbers from the top of the stack {({}<{}>[()])}{} #Reverse the whole stack ([]){{}({}<>)<>([])}{}<> >)[()]}{} ``` [Answer] # [R](https://www.r-project.org/), ~~32~~ ~~31~~ 30 bytes *-1 byte thanks to Rift* *-1 byte thanks to Jarko Dubbeldam* ``` pryr::f(n[(1+l):(sum(n|1)-r)]) ``` Evaluates to an anonymous function: ``` function (l, n, r) n[(1 + l):(sum(n|1) - r)] ``` `1+l` is necessary since R has 1-based indexing. `sum(n|1)` is equivalent to `length(n)` but it's a byte shorter. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRydPp0gzL1rDUDtH00qjuDRXI6/GUFO3SDP2f5qGkY6hlZmOoSZXmoYBkGmkY6D5HwA "R โ€šร„รฌ Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` (โ€šรฅฮฉโ€šรœรฌ)/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBI1HPXsftU3W1Od61DcVyE8DUtiZ//8bKhgpaIAIYwUTBVMFM00uAyClYQYUMQGKmSoYKhiDxAzAqjQB "APL (Dyalog Classic) โ€šร„รฌ Try It Online") --- Input format is `y x A` **Explanation** `/` is Reduce, which inserts the function to the left between each pair of elements of the argument `(โ€šรฅฮฉโ€šรœรฌ)` is a function train equivalent to `{โ€šรฅฮฉโ€šรงโˆซโ€šรœรฌโ€šรงยต}`, which removes the first `โ€šรงโˆซ` elements of the array `โ€šรงยต` and then reverses the array. (`โ€šรงโˆซ` is the left argument and `โ€šรงยต` is the right argument) Thus, `(โ€šรฅฮฉโ€šรœรฌ)/y x A` is equivalent to `โ€šรฅฮฉyโ€šรœรฌโ€šรฅฮฉxโ€šรœรฌA`, which is what is needed. [Answer] # [Ruby](https://www.ruby-lang.org/), 17 bytes ``` ->a,b,c{a[b..~c]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knuToxOklPry45tvZ/gUJadLShjpGOsY6JjqmOWSyQaRjLBRY2A7JNgBKmOoY6xrFAyiD2PwA "Ruby โ€šร„รฌ Try It Online") [Answer] # C++, ~~50~~ ~~48~~ 46 bytes ``` #define f(a,x,y)decltype(a)(&a[x],&*a.end()-y) ``` [Try it online!](https://tio.run/##RY7LCoMwEEX3@YpBQZIyFmofCw3@SOkiJLEENBGNRRG/PbUptAcuDPcMw8i@z59ShpAq3RiroaECZ1yY0rL1S6@pYDQT9/mB2UEctVWU5QsLqbGynZQGbtzoBy26mvy7l5beDTUx1kMnjKWMrAR2Rq/K8mv5LmsQ6wkLPOMFr3jbKhK3GjdQEJN3YMr4UIEFY1F9@A3xmnSTB87B7EkgqcgW3g "C++ (gcc) โ€šร„รฌ Try It Online") [Answer] # C++, ~~96~~ 95 bytes *Thanks to @Tas for saving a byte!* ``` #import<list> int f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();} ``` [Try it online!](https://tio.run/##VY3dCsMgDIWv51OEDoaCLXR/F9XtVUaxdgi2imawrfTZO2uvlouT5MvhRHlfPpValr0ZvAsorYl4J2ZE6GnErmlWINN@P1i@4nfWD5t6F6itgo7mq9OQGys/TLzLUjBbeecffXAjUibmlD8q@@o0SOMiBt0O25ehNSNlZCKQ6v8hoI4IN5hqDkcOJw5nDhcO11lkd09XQ77VbEMbdwHomm2gyRmM7HKyci8EKRNPUkAhyLz8AA) # C++ (MinGW), 91 bytes ``` #import<list> f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();} ``` [Answer] # [Kotlin](https://kotlinlang.org), 30 bytes ``` {a,s,e->a.drop(s).dropLast(e)} ``` [Try it online!](https://tio.run/##dY1NCsIwEIX3nmKWGZhKa2sXpQZcCgUXniBgU4IxLUkUpPTsMY3gSmfx5u99M7fRa2WCfBi4C2WYsINr4GiteLUXb5UZOMK8gRhPoUE2wDrlfHsynhNETYKQcfjO4QBhFuSoz7jYXu04MYcpd8J51uMS1ntTvO61YZLpSJ4lKwh2BCVBRbAnqDH1BeLmp71O6yoR0R7pElOV/yPWB9GSfyxLeAM "Kotlin โ€šร„รฌ Try It Online") Takes `List<Int>` as input and drops from begin and then from end. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 10 bytes ``` {(-z)_y_x} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pDt0ozvjK@ojbaUMFIwVjBRMFUwczayNow9v9/AA "K (oK) โ€šร„รฌ Try It Online") Port of my q/kdb+ answer... [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~11~~ 10 bytes ``` kbโ€šร‡รงB&t;Bkโ€šร‡รง ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/PzvpUVOvk1qJtVM2kPH/f7SRjkK0kaGOgpExEJsCsTkQW@ooGBvG6igYxv6PAgA "Brachylog โ€šร„รฌ Try It Online") Takes input as [x, A, y] where A is the array to trim. *(-1 byte thanks to @Fatalize.)* [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` oW UsV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=b1cgVXNW&input=WzEgMiAzIDQgNSA2XQoyCjEKLVE) ``` sVWnUl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=c1ZXblXK&input=WzYgMiA0IDMgNSAxIDNdCjUKMAotUQ) ``` oW UsV :Implicit input of array U and integers V=x & W=y oW :Remove the last W elements of U, mutating the original UsV :Slice U from 0-based index V ``` ``` sVWnUโˆšรค :Implicit input of array U and integers V=x & W=y sV :Slice U from 0-based index V to index Wn : Subtract W from Uโˆšรค : Length of U ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Fยฌยถ}sFยฌยฎ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7dCy2mK3Qyv@/zfiijbUMdIx1jHRMY3lMgQA "05AB1E โ€šร„รฌ Try It Online") ``` F } # For 0 .. number of elements to remove from front ยฌยถ # Remove the first element s # Get the next input F # For 0 .. number of elements to remove from back ยฌยฎ # Remove the last element ``` ]
[Question] [ Sona is in her house with her 10 year old daughter. She needs to go to school to bring back another child from school, as school is over at 2 pm. It's hot outside, so she wants to leave her younger child at home. She gave a bunch of strings to her child to keep her busy while she is gone. She asked her to reverse the words in the string. There are lot of strings, so you need to help her daughter in solving this huge task. So, given a string that contains words separated by single space, reverse the words in the string. You can assume that no leading or trailing spaces are there. The string will only contain `[a-zA-z ]`, so you don't need to handle punctuation. You will be given a string as an input, and you should output a string. ### Sample Test Cases: ``` Input: Man bites dog Output: dog bites Man Input: The quick brown fox jumps over the lazy dog Output: dog lazy the over jumps fox brown quick The Input: Hello world Output: world Hello ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Answer] ## [Retina](https://github.com/m-ender/retina), 7 bytes ``` O$^`\w+ ``` [Try it online!](https://tio.run/nexus/retina#@@@vEpcQU679/79vYp5CUmZJarFCSn46AA "Retina โ€“ TIO Nexus") Match all words (`\w+`) sort them with sort key empty string (`O$`) which means they won't get sorted at all, and then reverse their order (`^`). [Answer] ## Haskell, 21 bytes ``` unwords.reverse.words ``` [Try it online!](https://tio.run/nexus/haskell#@59mW5pXnl@UUqxXlFqWWlScqgfm/c9NzMxTsFUoKMrMK1FQUUhTUPJNzFNIyixJLVZIyU9X@g8A "Haskell โ€“ TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` print(*input().split()[::-1]) ``` [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqGVmVdQWqKhqVdckJMJpKOtrHQNYzX///dNzFNIyixJLVZIyU8HAA "Python 3 โ€“ TIO Nexus") [Answer] # Bash + common Linux utilities, 21 ``` printf "$1 "|tac -s\ ``` Leaves a trailing space in the output string - not sure if that's OK or not. [Answer] # JavaScript (ES6), 31 bytes ``` s=>s.split` `.reverse().join` ` ``` --- ## Try it ``` f= s=>s.split` `.reverse().join` ` o.innerText=f(i.value="Man bites dog") oninput=_=>o.innerText=f(i.value) ``` ``` <input id=i><pre id=o> ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` แน‡โ‚โ†”~แน‡โ‚ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wZ/ujpsZHbVPqIKz//5V8E/MUkjJLUosVUvLTlf5HAQA "Brachylog โ€“ TIO Nexus") ### Explanation ``` แน‡โ‚ Split on spaces โ†” Reverse ~แน‡โ‚ Join with spaces ``` Note that both "split on spaces" and "join wth spaces" use the same built-in, that is `แน‡โ‚`, just used in different "directions". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` แธฒแนšK ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx6aHO2d5////3zcxTyEpsyS1WCElPx0A "Jelly โ€“ TIO Nexus") Explanation: ``` แธฒ Splits the input at spaces แนš Reverses the array K Joins the array, using spaces ``` [Answer] # R, 19 bytes ``` cat(rev(scan(,''))) ``` reads the string from stdin. By default, `scan` reads tokens separated by spaces/newlines, so it reads the words in as a vector. `rev` reverses, and `cat` prints the elements with spaces. [Try it online!](https://tio.run/nexus/r#@5@cWKJRlFqmUZycmKeho66uqan53zcxTyEpsyS1WCElP/0/AA) [Answer] # C#, 58 bytes ``` using System.Linq;s=>string.Join(" ",s.Split().Reverse()); ``` [Answer] # C, ~~54~~ 48 bytes **Using arguments as input, 48 bytes** ``` main(c,v)char**v;{while(--c)printf("%s ",v[c]);} ``` [*Try Online*](https://tio.run/nexus/c-gcc#@5@bmJmnkaxTppmckVikpVVmXV2ekZmTqqGrm6xZUJSZV5KmoaRarKCkUxadHKtpXfv////cxLz/qYklxf9T8tMB) ``` > ./a.out man bites dog ``` **Using pointers, 84 bytes** ``` f(char*s){char*t=s;while(*t)t++;while(t-s){while(*t>32)t--;*t=0;printf("%s ",t+1);}} ``` *Use* ``` main(){ f("man bites dog"); } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` #Rรฐรฝ ``` Note: Will only work for 2 or more words. +1 byte if this is not OK. [Try it online!](https://tio.run/nexus/05ab1e#@68cdHjD4b3///sm5ikkZZakFiuk5KcDAA "05AB1E โ€“ TIO Nexus") [Answer] # [GNU Make](https://www.gnu.org/software/make/), 62 bytes ``` $(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 74 bytes ``` ,[>++++[<-------->-],]<[>++++[->--------<]+>[[<]>[+>]<]<-[<]>[.>]<[[-]<]<] ``` [Try it online!](https://tio.run/nexus/brainfuck#@68TbacNBNE2ulBgpxurE2sDFQXyoMAmVtsuOtom1i5a2y7WJtZGF8zWA7Kjo3VBArH//7vkpyskZZakFivkJuYBAA "brainfuck โ€“ TIO Nexus") This code creates the number -32 in two different places, but that seems to be fewer bytes than trying to maintain a single -32. ### Explanation ``` ,[ input first character >++++[<-------->-] subtract 32 from current character (so space becomes zero) ,] repeat for all characters in input < go to last character of last word [ while there are more words to display: >++++[->--------<] create -32 two cells right of last letter +> increment trailing space cell (1 right of last letter) so the next loop works [[<]>[+>]<] add 32 to all cells in word and trailing space cell <- subtract the previously added 1 from the trailing space [<]> move pointer to beginning of word [.>]< output word (with trailing space) [[-]<] erase word < move to last character of previous word ] ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 48 bytes Almost gave up on this one, but finally got there. ``` oU_;SW;@?ABu>):tS-?;\0$q^s.$;;<$|1osU!(;;...<#(1 ``` [Try it online!](https://tio.run/nexus/cubix#@58fGm8dHG7tYO/oVGqnaVUSrGtvHWOgUhhXrKdibW2jUmOYXxyqqGFtraenZ6OsYfj/f0lRfmlSTqpCRqpCZjEA "Cubix โ€“ TIO Nexus") This maps onto a cube with a side length of three as follows ``` o U _ ; S W ; @ ? A B u > ) : t S - ? ; \ 0 $ q ^ s . $ ; ; < $ | 1 o s U ! ( ; ; . . . < # ( 1 . . . . . . ``` The general steps are: * Get all input `A` and reverse `B` stack * Move the negative `q` to the bottom, add a counter `0` to the stack. bit of jumping around in here. * Find space/end loop, also puts stack in correct print order. + Increment counter `)` and fetch the counter item from the stack `t` + Is it a space or EOI `S-?` + Repeat if not * Print word loop + Decrement counter `(` + Exit loop if counter `!U` is 0 + Swap `s` counter with character on stack + Print `o` character and pop it from the stack `;` + Repeat loop * Get the length of the stack `#` and decrement `(` * Check `?` if 0 and exit `@` if it is 0 * Otherwise print a space `So` clean up `;;` and go back to the first loop. I've skipped a number of superfluous steps, but you can see it [Step By Step](https://ethproductions.github.io/cubix/?code=ICAgICAgbyBVIF8KICAgICAgOyBTIFcKICAgICAgOyBAID8KQSBCIHUgPiApIDogdCBTIC0gPyA7IFwKMCAkIHEgXiBzIC4gJCA7IDsgPCAkIHwKMSBvIHMgVSAhICggOyA7IC4gLiAuIDwKICAgICAgIyAoIDEKICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=aGVyZSB0aGV5IGFyZQ==&speed=10) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ ~~10~~ ~~7~~ 4 bytes My first attempt at Japt. ``` ยธw ยธ ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=uHcguA==&input=Ik1hbiBiaXRlcyBkb2ci) * Saved 3 bytes thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) --- ## Explanation ``` :Implicit input of string U ยธ :Split on <space> w :Reverse ยธ :Join with <space> ``` --- Please share your Japt tips [here](https://codegolf.stackexchange.com/q/121253/58974). [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` lambda s:' '.join(s.split()[::-1]) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbKWuoK6XlZ@Zp1GsV1yQk1mioRltZaVrGKv5v6AoM69EIU1D3TcxTyEpsyS1WCElP11d8z8A "Python 2 โ€“ TIO Nexus") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` jd_c ``` [Try it online!](http://pyth.herokuapp.com/?code=jd_c&input=%22Man%20bites%20dog%22&test_suite=1&test_suite_input=%22Man%20bites%20dog%22&debug=0) [Answer] # PHP, 47 Bytes ``` <?=join(" ",array_reverse(explode(" ",$argn))); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJNzFNIyixJLVZIyU9Xsuayt/tvY2@blZ@Zp6GkoKSTWFSUWBlflFqWWlScqpFaUZCTn5IKlgHr19TUtP7/HwA "PHP โ€“ TIO Nexus") [Answer] # k, 9 bytes ``` " "/|" "\ ``` [Try it in your browser of the web variety!](http://johnearnest.github.io/ok/?run=%22%20%22%2F%7C%22%20%22%5C%22Man%20bites%20dog%22) ``` " "\ /split on spaces | /reverse " "/ /join with spaces ``` [Answer] # [J-uby](http://github.com/cyoce/J-uby), 23 bytes ``` :split|:reverse|~:*&' ' ``` ### Explanation ``` :split # split by spaces | # then :reverse # reverse | # then ~:*&' ' # join with spaces ``` [Answer] ## Mathematica, 35 bytes ``` StringRiffle@Reverse@StringSplit@#& ``` [Try it online!](https://tio.run/nexus/mathics#S7P9H1xSlJmXHpSZlpaT6hCUWpZaVJzqABEMLsjJLIlW1lFSUIpV@x8AFCpRcEhzUPJNzFNIyixJLVZIyU9X@g8A "Mathics โ€“ TIO Nexus") [Answer] # Vim, 20 bytes ``` :s/ /\r/g|g/^/m0<cr>vGJ ``` This is shorter than the other vim answer. [Try it online!](https://tio.run/nexus/v#@29VrK@gH1Okn16Trh@nn2vAVebu9f@/b2KeQlJmSWqxQkp@OgA "V โ€“ TIO Nexus") [Answer] # [Rรถda](https://github.com/fergusq/roda), ~~27~~ 25 bytes *2 bytes saved thanks to @fergusq* ``` {[[split()|reverse]&" "]} ``` [Try it online!](https://tio.run/nexus/roda#S4v5Xx0dXVyQk1mioVlTlFqWWlScGqumpKAUW/s/NzEzr5orWslRIclZIcU1TcE9wzNLKbYmjav2PwA "Rรถda โ€“ TIO Nexus") This function takes input from the input stream. ### Explanation (outdated) ``` {[[(_/" ")()|reverse]&" "]} /* Anonymous function */ (_/" ") /* Pull a value from the stream and split it on spaces */ () /* Push all the values in the resulting array to the stream */ |reverse /* And reverse it */ [ ] /* Wrap the result into an array*/ &" " /* Concatenate each of the strings in the array with a space */ [ ] /* And push this result to the output stream */ ``` [Answer] # Pyth, 3 bytes ``` _cw ``` My first Pyth answer, one byte shorter than @notjagan's answer! Explained: ``` cw # Split the input by space (same as Python's string.split()) _ # Reverses the array # Pyth prints implicitly. ``` [Answer] # [Zsh](https://www.zsh.org/), 13 bytes ``` echo ${(Oa)@} ``` [Try it online!](https://tio.run/##qyrO@J@moVn9PzU5I19BpVrDP1HTofZ/LVeaQkhGqkJhaWZytkJSUX55nkJafoVCVmluQbFCfllqkUIJUDonsapSISU//T8A "Zsh โ€“ Try It Online") [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes ``` z]Qรน ``` [Try it online!](https://tio.run/nexus/ohm#@18VG3h45///vol5CkmZJanFCin56QA "Ohm โ€“ TIO Nexus") **Explanation** ``` z Split the input on spaces. ] Dump it onto the stack. Q Reverse the stack. รน Join the stack with spaces. Implicit output. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` qS/W%S* ``` [Try it online!](https://tio.run/nexus/cjam#@18YrB@uGqz1/79vYp5CUmZJarFCSn46AA "CJam โ€“ TIO Nexus") **Explanation** ``` q e# Read input S/ e# Split on spaces W% e# Reverse S* e# Join with spaces ``` [Answer] # [TAESGL](https://github.com/tomdevs/taesgl), 7 bytes ``` ฤดS)ล˜)ฤดS ``` [**Interpreter**](https://tomdevs.github.io/TAESGL/v/1.3.1/index.html?code=XHUwMTM0UylcdTAxNTgpXHUwMTM0Uw==&input=Ik1hbiBiaXRlcyBkb2ci) **Explanation** ``` ฤดS)ล˜)ฤดS AฤดS) implicit input "A" split at " " ล˜) reversed ฤดS joined with " " ``` [Answer] # [J](http://jsoftware.com/), 6 bytes ``` |.&.;: ``` [Try it online!](https://tio.run/nexus/j#HYyxCsIwFEX3fsXFwVqoQddGRRHFQRdxlzZ9bQIxD5tXuvjvtTocuAcuZ6bSBtsCKXKsUEwsFY73/HoeP2qudDFmSSLmd9lo9Vwj1bcyoHJCETW3@oAKBjWh0RfynjFw52utH5Y6gosIjLKK7HshePdyAg4QOwmFViy4QYmhcyIUcAqtd9EiUpjUUJokZCxjh8W756lApbH7hUaTZf8NMeMX "J โ€“ TIO Nexus") This is reverse (`|.`) under (`&.`) words (`;:`). That is, split sentence into words, reverse it, and join the sentence again. [Answer] # Gema, 29 characters ``` <W><s>=@set{o;$1 ${o;}} \Z=$o ``` Sample run: ``` bash-4.4$ gema '<W><s>=@set{o;$1 ${o;}};\Z=$o' <<< 'Man bites dog' dog bites Man ``` ]
[Question] [ The task here is pretty simple. You should write a program that takes a string as input and outputs it (that is a cat program). Additionally when the \$n\$th byte of your program is removed (without replacement) the augmented program should take a string as input and remove the \$n\$th character. If the input to your augmented program is less than \$n\$ characters long it should return it as is. For example the python program ``` x = input() if "y" == "y": print(x) else: print(x[:16] + x[17:]) ``` [Try it online!](https://tio.run/##TcqxCsMgFEbh3af4yRQpFUKhBcE@QcduIeNtczGo6C01T29wy3Tg46Rd1hhurVU4cEg/GbXiD4Z9gHM9VgEpc5CxakVboRPMdrovuKDO08MuurU3FQELVsqE6xMVXTh8YYzBK0ZfsLGn/vxj9uUA "Python 3 โ€“ Try It Online") will remove the \$17\$th character if its \$17\$th byte is removed (the first `y`). ## Scoring Your answer's score will be the number of bytes for which removal does *not* cause the program to remove the corresponding byte. With better score being lower. In our example above the total length is 68 bytes, with one byte (the \$16\$th one) augmenting the program correctly. That leaves a score of 67 bytes. If the program were modfied to work in two places like so: ``` x=input() u="az" if u!="az":x=x[:13+(u<"c")]+x[14+(u<"c"):] print(x) ``` [Try it online!](https://tio.run/##NYrBCgIhFADvfsXLk7IkLNtJsi/o2G3ZQ4S1D0NFn/Tq540Nus0Mk9@0pjj1zg5jbqS0aE5eP1LgHdruh5Ydz3acBtWO8ib1MvA8Hv5mF5ELRlKse7/4SoAEqy8e9idg2ArGBxhj4JxSqPDE4LfnlUqoXw "Python 3 โ€“ Try It Online") Where removing the \$14\$th and \$15\$th characters (`a` and `z`) work properly. The score is 66 bytes or 68 - 2, since the program is 68 bytes long but two of those bytes work properly. ## Rules and clarifications * There must be at least one byte which can be removed that causes the program to remove the corresponding character in the input. This means a cat program on its own is *not* a valid submission. * Only one byte will be removed at a time. You do not have to worry about what happens when multiple bytes are removed from your program at the same time. * You should support strings using printable ascii characters in addition to all characters that appear in your program itself. Input containing anything else is undefined behavior. [Answer] # [Python 2](https://docs.python.org/2/), score: ~~56 50~~ 48 bytes - 6 = 42 This is more an attempt to allow to remove more than 1 or 2 characters than to achieve the lowest possible score. Given the scoring scheme, allowing one more byte to be removed this way would cost at least one extra byte, leaving the score unchanged at best. You may remove the 3rd to the 8th character, i.e. any digit of \$545454\$. ``` n=545454;x=input();print x[:n%11]+x[n%11+n%9/4:] ``` [Try it online!](https://tio.run/##HYVLCoQwEAWv8nAQZnAhDrpQ8RbuRCFIS7KwE5KeIZ4@fl5V8dwh2vI3JR6a@qaPg2H3k/end96wIE4d51U1F3G6v@C8LetuTi8szwBPu/0TLF9tEE2BsGrl1SrkQ8pGbQIuFYSCZCc "Python 2 โ€“ Try It Online") ### How? Removing the \$n\$th digit from \$545454\$ and applying a modulo \$11\$ results in \$n+1\$. Applying a modulo \$9\$ instead allows to figure out whether the number was changed or not. ``` pattern | x | x mod 9 | x mod 11 ---------+--------+---------+---------- 545454 | 545454 | 0 | (8) _45454 | 45454 | 4 | 2 5_5454 | 55454 | 5 | 3 54_454 | 54454 | 4 | 4 545_54 | 54554 | 5 | 5 5454_4 | 54544 | 4 | 6 54545_ | 54545 | 5 | 7 ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 584 bytes, score 0 ``` <|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</ <|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</ <|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</ ``` [Try it online!](https://tio.run/##7ZKxCgIxEER7v2IGUmiO4Ea7EEk@xtx5lYXt4a@fuT2CP2BhERjCvMxuMbDj/Hqsa1yEzwRmMLTXgd6A88KkPGiQNTiBFixVRt3g9/QIXtVY1R0c227FC1jHb@DUfG7oGwZFUfNVlDfT5G1BcV6wgTgjwW0/AonnQ6/wBxX6JfUKv6nwAQ) [Verification of perfect score](https://tio.run/##7VNfa8IwEH82n@LihDR2re18K4qyfQwpI7RpG9CkpOlEkH31Lo2tEyd73sPgCPe7P7@7S3L1yVRKLjtxqJU2oBpUa1VqdoA1aEJItzpHWG0AbwEn4xkAjmeAxRlvHPadY@scFPAcMLcyc5ofX7we4KVT5k5ywMWYa@ELYBu@BlyO@naE8QgTByOnfMsq@sSbMp5z4EEcQQ@iYBYlQW@JIFot0P8If2CEzn6mXZwEcWp/mJDGI68nwyFTrTQJeYY9l97w9UIuM5Vzj7AmE4JQShE6ClOBqm0QUVqUQrK9TSJHQoE1UCRoUoRHLQwfSWxOzgvQrXwfLFePDb6h60vdUf3kmmhuWi3tfoS1SyumGbPrMrQCZ6gviwQLVZtFIZrKHWF9gr7AlIaas9yzXanW9Lv1oC@EWNPwfgv7kDUMdmQvjH@8VUzbPEIQKpQGAUKCZrLk3s3N0X627wJ71Zj7KrtEpOCP3Dvhx0lq57spcXWlaPJ0eStLSa/gd6KHIzyKvfIJ2n0B) (note times out) The first zero score program. This is achieved by having three copies of the program on separate lines, with only non-irradiated versions being executed. The program checks for outliers (like newlines being removed), then checks each character to see if it is the same for all three lines. If one is different, we determine which line it is and offset the current index by a multiple of 195 (the length of each line). After determining which byte is irradiated (with no byte being `-1` and the first byte being `1`), we enter the output loop, decrementing the counter each time we output a character. When the counter hits zero, we skip that character, but don't reset the counter so it can be proven that only one byte of input is removed when the program is irradiated, and none when it is not. The TIO link above has the program itself in the input, so it is easy to fiddle about in yourself. Simply try removing a byte from the program itself and the same byte will be removed from the output. It shouldn't be too hard to golf, especially the loop in the middle that's just 60% no-ops, though I just want to post it since it is actually working and this isn't actually [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] # [sed](https://www.gnu.org/software/sed/), [Perl 5](https://www.perl.org/) `-p`, [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, 6 bytes, score 5 ``` #s/.// ``` [Try it online!](https://tio.run/##K0gtyjH9/1@5WF9PX///f0MjYxNTM3MLy3/5BSWZ@XnF/3ULAA "Perl 5 โ€“ Try It Online") Works as sed, Perl 5 and Perl 6 program. The 1st byte is removable. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes, score = 1 ``` แธทแธŠ ``` [Try it online!](https://tio.run/##y0rNyan8///hju0Pd3T9///fOT8lVcE9PycNAA "Jelly โ€“ Try It Online") A full program that takes a string and prints a string. [When the first byte is removed](https://tio.run/##y0rNyan8///hjq7///8756ekKrjn56QBAA), removes the first byte of the input. Achieving a lower score would mean finding a solution where removing *any* byte leads to the corresponding byte being removed from the string, which I think will be challenging. ## Explanation ``` แธท | Left argument of input string and: แธŠ | - Input string with first byte removed ``` With first byte removed: ``` แธŠ | Remove first byte ``` [Answer] # Brainfuck, 11 bytes, score = 10 ``` -+[,>],[.,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fVztaxy5WJ1pPJ/b//5LU4hIA) # Explanation ``` -+[,>] This does nothing. ,[.,] This reads and outputs the user's input until the program ends. ``` With first byte removed: ``` +[,>] Reads the first character of user input, then 'discards' it by moving to a different cell. ,[.,] This reads and outputs the user's input until the program ends. ``` [Answer] # [R](https://www.r-project.org/), 93 bytes, score=87 ``` T<-3.5->T;s=utf8ToInt(scan(,""));if(i<-match(2*T,c(0,-5,2,1,70,6,0,5),0))s=s[-i];intToUtf8(s) ``` [Try it online!](https://tio.run/##DcwxDsIwDADAv3SyKxuFogBSWvbuZkIMIRBqJFIJh/cH7gH3aU1G3m08nyTY9K35KOtcKliKBajrEINm0JHfsaYFhl4ogSP2NNCWDo725MgjOUSb7MJ6DVqqrOf/BIYt3tL9kZ@LvtoP "R โ€“ Try It Online") Like [Arnauld](https://codegolf.stackexchange.com/a/197055/86301), I tried to get a few deletable bytes rather than optimize the score, and also to use different tricks depending on the byte removed. Characters 2, 3, 4, 5, 6 and 8 can be removed. In the unaltered version, the code makes two attempts to assign a value to `T`, using both leftwards `<-` and rightwards `->` assignment. Since `T` is initialized as 1 (when coerced to integer), it can be assigned 7 different values, depending on the byte removed: * `T<-3.5->T` leads to `T=3.5` * `T-3.5->T` leads to `T=1-3.5=2.5` * `T<3.5->T` leads to `T=1`, since `1<3.5` is true (the same would occur if we removed byte 7 - I searched for a way to have different behaviours when removing bytes 3 and 7 but couldn't manage) * `T<-.5->T` leads to `T=.5` * `T<-35->T` leads to `T=35` * `T<-3.->T` leads to `T=3.` * `T<-3.5-T` leads to `T=3.5-1=2.5` The statement with `if` and `match` then removes the relevant character. The rest is the usual fluff required whenever R has to handle strings. --- It is obviously possible to make the number `3.5` longer (e.g. `43.5`) and be allowed to remove the corresponding characters. For the sake of it, here is a different way of getting more removable characters: # [R](https://www.r-project.org/), 120 bytes, score=112 ``` T<-3.5->T;s=utf8ToInt(scan(,""));if(i<-match(T+T,c(0,-5,2,1,70,6,0,5,rep(0,37),3.5,rep(0,47),-7),0))s=s[-i];intToUtf8(s) ``` [Try it online!](https://tio.run/##nY1HDsIwFETvwsoW38gQAkgJSPTeTReLEBIwJQmxqZc3XnACFrN4I72ZWClmEyNlkhKzRPEu/QIL24FEwnUCBIkExhb3EbfJ1ZHuEbEkAxdRICZkIA15CjmgYELsRbo18hj01o@ymogOxVgUxYbwrcUDycKZPkECK2fn7j3/cOSn8@UahNEtFvL@eL7en3KlWqs3mq12p9vrD4aj8WTKZvPFcrX@x1Ff "R โ€“ Try It Online") In addition to the characters listed above, bytes 46 and 94 can be removed: * byte 46: the first `T` in `T+T` becomes `+T`, which matches `3.5` * byte 94: `-7` becomes `7`, which then matches `T+T=7`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score 2, 3 bytes ``` Dยฆr ``` Look ma, (sort of) no unicode! The character to remove is the first one. [Try it online](https://tio.run/##MzBNTDJM/f/f5dCyov//S1KLSxQy8wpKSwA) Explanation: ``` D push two copies of the input onto the stack ยฆ remove the first character from the string on top of the stack. Alternatively, if D is removed, push the input with its first character removed onto the stack. r reverse the stack implicitly, output the top of the stack ``` [Answer] # [Haskell](https://www.haskell.org/), 31 - 1 = 30 *Removing the first byte works* ``` ss(x:b)=b s x=x main=interact s ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v7hYo8IqSdM2iatYocK2gis3MTPPNjOvJLUoMblEoZigAgA "Haskell โ€“ Try It Online") ## Explanation In its default state this program defines two functions `ss` which is unused, and `s` which is the identity. It then declares that interaction is handled by `s`, making it a cat. When we remove the first byte `ss` is renamed to `s`. Making it a special case of our function `s`, since this is the first declaration it takes highest precedence. So now `s` is defined such that if it can remove the first character it does so otherwise it falls back onto our old definition of `s`1 and becomes the identity. We still interact with `s` (although now modifed) so the entire program has the behavior of removing the first character if there is one. --- 1 This is important in the case of the empty string. [Answer] # [Keg](https://github.com/JonoCode9374/Keg) `-ir`, 3 bytes, score: 2 ``` #_^ ``` [Try it online!](https://tio.run/##y05N//9fOT7u/3@P1Jyc/P@6mUUA "Keg โ€“ Try It Online") ## Explanation ``` #_^ # A line comment # Copies the input to the output straightforwardly ``` ``` # Implicit reversed input _ # Discard the first character in the string ^ # Reverse the stack ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score 1, 2 bytes ``` qยฆ ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/8NCy//9LUotLFDLzCkpLAA "05AB1E โ€“ Try It Online") First byte is removable. [Answer] # [Python 3], 9097 bytes, score 6 ``` eEzfFzeEz=aAzcCzaAz=aAzbBz=bBzaAz=aAzcCz=eEzfFz=fFzaAz=eEzaAz=dDzaAz=exe=exc=xec=xecexec=aAz=aA=az=Az=aAz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#' 12; bBz=bB=bz=Bz=bBz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#' 12; cCz=cC=cz=Cz=cCz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#' 12; exe=exc=xec=exec dDz=dD=dz=Dz=dDz=aAz,bBz,aAz; eEzfFzeEz=gGzeEz=aAzcCz=aAz<cCz; eEz=eE=ez=Ez=eEz=aAz<cCz; fFz=fF=fz=Fz=fFz=aAz>cCz; eEzfFz=eEz|fFz; gGz=gG=gz=Gz=gGz=eEz|fFz; exec(dDz[gGz]) ``` This program has the general structure ``` a="payload" b="payload" c="payload" exec([a,b][b==c]) ``` where "payload" is the program we want to execute. The comparison in the `exec` call makes sure that we run an unmodified copy of the payload. Within the payload, we open the source of `__file__` and compare it to the unmodified source (which is determined using a quine). This gives us the information we need to delete the correct character from the output. The base64 encoded segments are the inputs used when making the quine. They are base64 encoded to avoid needing to escape nested quotes. The program is written so that it has no repeating characters, allowing almost any deletion to be detected. ### The 6 characters that can't be deleted are: * The parentheses and brackets in the last line (`([])`), as deleting them will cause a syntax error. * The `x` in both instances of `exec`, as this produces the variable `eec` which is not defined. If I did define `eec`, I would introduce a pair of duplicated characters, and would not be able to distinguish between those deletions. If the challenge cared about deletions of *characters* instead of *bytes* then I could define `eแต‰c` in the appropriate places to reduce the score to 4. ### Radiation Resistance tricks `eEzfFzeEz=aAzcCzaAz=...` This line defines all the variables that the program could later try to read, to avoid crashing with a NameError. `bBz=bB=bz=Bz=bBz=` when I want to be able to read a value, I define it (`bBz`) twice, and also define the mangled versions of it once each. When the variable is later accessed, at least one of the original definitions was undamaged, and damaging the later access will result in reading one of the shortened versions of the variable. No variable shorter than 2 characters is used as deleting a single variable would cause `bBz=fr='"1"#\n` This acts as a no-op when the payload is executed, and results in any radiation to the start of the string merely storing a bad value in `bBz`. * If the single quote is deleted, `"1"` is assigned, and the rest of the string is commented out. * If the last `=` is deleted, the string becomes a raw format string, but is still valid syntax. * Other deletions mangle some variable names, but redundant assignment fixes this. At the end of the strings `'#'#'` is used. As written this is the end of one string followed by a comment. If the first `'` is removed, it the next `#'` become part of the string, and the remaining 2 characters become a comment. If the first `#` is removed, then the program has 2 strings in a row, so they are concatenated. Damage to the last 2 characters is just a change to the comment text. `12;` and `;` are added to allow the deletion of newlines to join statements without issue. `dDz=aAz,bBz,aAz;` This line stores the A and B in a tuple. If either comma is deleted, we still store a tuple of size two. The 3rd tuple element will never be accessed. Deleting the `=` has no effect, as `dDzaAz` was initialized to the same value as `aAz`. `a != c` is converted to `e = a<c; f = a>c; g = e|f` so that characters in the comparison operator can be deleted without crashing the program. Then redundant comparisons are added so that damaging any one of the comparisons produces the right result. `exec(dDz[gGz])` we can execute a known-good payload by indexing into a tuple. [Answer] # [Python 3](https://docs.python.org/3/), 33 - 1 = 32 bytes The removable byte is the 23rd one (`~`). ``` x=input();print(x[:22-~0]+x[23:]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8I2M6@gtERD07qgKDOvRKMi2srISLfOIFa7ItrI2CpWE7sSY2QlAA "Python 3 โ€“ Try It Online") This sort of evolved out of [Arnauld's answer](https://codegolf.stackexchange.com/a/197055/56656), but only seeks to get one removable character. ## Explanation In python `~` is a "bitwise not", which basically subtracts the value from 1. So `~0` is equivalent to `-1`. This makes `22-~0` the same as `23`. So normally our program takes everything up to the 23rd character and then adds everything after. However when we remove the `~` `22-~0` becomes `22-0` equivalent to `22`. This makes us take the first *22* characters and everything after the 23rd, skipping the 23rd character. [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 236 bytes, score 235 -16 bytes thanks to Jo King. New lines added for readability. Byte 196 can be removed. Exits with error but the output is correct. ``` ,.Ajax,.Page,. Act I:.Scene I:. [Exeunt][Enter Ajax and Page] Ajax:Open mind. Page:You be the sum ofyou a cat. Be you as big as the square ofthe sum ofa big big big big cat a big pig? If soLet usScene VI. Scene VI:. Ajax:Speak mind.Let usAct I. ``` [Try it online!](https://tio.run/##5Y9NCsJADIWv8g5Q5gCzEYUuCoJCQZDSRdqmtf5Mx84M1NPX@UH0Di5CXpIvIc/o@7pmYnulJRNHGtjr1qKQomxZcRBVvrBTtq5yZXlGQEGqQ6DrUMmDZoXHqLp4QZ4nh4ZhLwzjHpj6l28QWrJix4iFQTMOIUXo6Whmz303KM5/w28jdfU4bIoeZtqzhTPpz1MhPkJGN7LUTLf0VQKjL/Ffbt8 "Shakespeare Programming Language โ€“ Try It Online") Page reads bytes from input and outputs them, one at a time. Ajax is a counter indicating how many bytes have been read. Page's `if` statement tests `Ajax == 196`. In the basic version, the `if` statement is useless: in all cases, we proceed to Scene VI. If byte 196 has been removed, the statement becomes `If soLet usScene I.` so we skip Scene VI and the corresponding input does not get output. This uses the fact that SPL doesn't require scenes to use consecutive numbers. Looking for other strategies, I checked all the words allowed in SPL: the only useful pair of words which are one deletion apart is `Helen`/`Helena`, which are both legal characters. I might try to use this to get a solution where two different bytes can be removed. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes, score 5 ``` ฮฆ๏ผณโปฮบยฑโด ``` [Try it online!](https://tio.run/##S85ILErOT8z5///csvd7Nj9q3H1u16GNjxq3YAgAAA "Charcoal โ€“ Try It Online") Explanation: ``` ๏ผณ Input string ฮฆ Filtered ฮบ Current index โป Subtract โด Literal `4` ยฑ Negated ``` Since adding 4 to the index is always a truthy result, this is a cat program. Removing the `ยฑ` at index `4` results in the following program: ``` ฮฆ๏ผณโปฮบโด ``` [Try it online!](https://tio.run/##S85ILErOT8z5///csvd7Nj9q3H1u16PGLcjcQxuBAgA "Charcoal โ€“ Try It Online") It deletes the character at index `4` (0-indexed). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~54~~ 53 bytes, score ~~52~~ 51 Bytes 27 or 28 (from the first `++c`), or both, may be removed. **Explanation:** There is a counter that increments by 2 each iteration (one in the loop condition, one in the body) in the unmodified program, but removing one of the `+`s turns the first increment into a no-op. As the only way to get an odd number is in the modified program, only it will remove the 27th byte. Both bytes can be removed because `+c` is the same as `c`. ``` c;main(a){for(;a=~getchar(++c);)++c-27&&putchar(~a);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/ZOjcxM08jUbM6Lb9IwzrRti49tSQ5I7FIQ1s7WdNaE0jqGpmrqRWUQkTrEjWta8nU9i85LScxvfi/bjkA "C (gcc) โ€“ Try It Online") [Answer] # GNU Sed 7 bytes, score=6 [Full program](https://tio.run/##K05N0U3PK/3/P8m6WF9PX///f0MjYxNTAA) `b;s/.//` [Program with first byte removed](https://tio.run/##K05N0U3PK/3/37pYX09f//9/QyNjE1MA) `;s/.//` Input is a printable ASCII string, with no newlines. [Answer] # JavaScript, 52 bytes, score 51 The 37th byte, `1`, is removable. ``` s=prompt() console.log(s.slice(0,36+01)+s.slice(37)) ``` --- # JavaScript, 56 bytes, score 55 The 24th byte, `1`, is removable. ``` s=prompt() console.log(01?s:s.replace(/^(.{24})./,'$1')) ``` [Answer] # [Symbolic Python](https://github.com/FTcode/Symbolic-Python), 11 bytes, score 10 ``` __=_[_==_:] ``` [Try it online!](https://tio.run/##K67MTcrPyUzWLagsycjP@/8/Pt42Pjre1jbeKvb///9KJanFJUoA "Symbolic Python โ€“ Try It Online") The first `_` is removable. Basically, the program sets `__` to the input without the first character, which doesn't affect the IO variable `_`, so it outputs what is inputted. If you remove the `_`. it does set the variable, so the first character is removed. [Try it online!](https://tio.run/##K67MTcrPyUzWLagsycjP@/8/3jY@Ot7WNt4q9v///0olqcUlSgA "Symbolic Python โ€“ Try It Online") [Answer] # [J](http://jsoftware.com/), 14 - 1 = 13 bytes ``` 1(]}.~1-1-:[)] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DTVia/XqDHUNda2iNWP/a3Kl2@qhCHFxpSZn5CukKahnpObk5KtDuOmoXHVdXV11hEIkRVgVOLm6Big4@fsHIBQihP4DAA "J โ€“ Try It Online") Removing the first byte works. # how * `1(...)]` A fork with the constant `1` as the left tine and the input as the right `]`. * `(]}.~1-1-:[)` One minus `1-` the value "does the input equal the left fork tine?" `1-:[`. + This will always be 0 in the unaltered program. + It will always be 1 in the program-with-byte1-removed. No string matches the integer `1`. + This works because removing that first `1` turns the fork into a hook, which is like a fork whose left tine is the original input. * `]}.~` Remove from the beginning `}.~` of the original input `]` that number of characters -- ie, the 1 or 0 calculated in the previous step. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), score 1 ``` ,แธข ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIs4biiIiwiIiwiSGVsbG8sIHdvcmxkISJd) ``` , # Print แธข # Remove first character, ignored แธข # Remove first character, implicitly printed ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 2 bytes - Score: 1 ``` &t ``` [Try it online!](https://tio.run/##K6gsyfj/X63k/3@loNTc/LJUhZKMVAXD4hKF5IzEosTkktQiJQA "Pyth โ€“ Try It Online") This implicitly expands to: `imp_print((tail(Q) and Q))` Removing the '&' let's the tail function print (All but the first element) [Answer] # [Python 3](https://docs.python.org/3/), score = 27, 262 bytes ``` x="a,b=sorted(x,key=len);d=[3,123][x!=(a,b)];n=sum(i is j for i,j in zip(a,b) );s=input();print(s[:d+n]+s[d+n+(a!=b):]) ","a,b=sorted(x,key=len);d=[3,123][x!=(a,b)];n=sum(i is j for i,j in zip(a,b) );s=input();print(s[:d+n]+s[d+n+(a!=b):]) " exec(max(x,key=len)) ``` [Try it online!](https://tio.run/##xVI7b9swEN75Ky6aJEgx6maToa3dunYyhIAmz86l4iN8BEqL/nb3SDlBx26deDwevxfp39KTsw9X5TTCBE3TXNepkcNpii4k1O06/MC3aUHbHfR0fBj2nx/m43o3tTzTzQc7xWxaAorwDGcXgIZnIAs/ydcJ6A5xIutzaruDD2RTG4@j7u3cxyMvfSvvplM3zh00w3/iFbiiao1c/yLtrhzFcT/e72chEq6Jw7nBicdacGOR5qTlCOVcCOFy4v7UNELjGR431rUbBcBlcSe5wDbB@61giJXvVfryAMOvpkI3I2wcAzQVpTRq8Rs6seE2JxkRxmb4wJqqjk6IqFwoj/lJ1GBKLEHaC7ZsrPJ09/uqKoW3sgB8KDiONPe1oH4/zgP8k6ICIWPEkG5ibloKGvRbWfFEoVLo00a7Ce2nvXg3tXWKq1qxmes3Xg2Q5/cG7RZ2FCmBNMhalLMRVcKUA0hNnqIiewFciA8jar4ASDkap1mF8SUOq0iTzjYBh7bIUyHEtEEjGHmxEuRCL1nu4HsCtGQYGwyV4pW30gzwkvnjWRdTyLqkFxQlmchZyAv/CuU25DJEkQpThSTPw4CShRvW5DYDTJV28KVAypwQKGRWsnktb4c@4BNajYGNc@PVLdkzHbIcdgrI0YOiZXlPiA1lOOcLyQS2CAIvA29y2MHXmj/mEiNn4JSSqHhOZU9apnKDXfjgSKMtKZakmFTlxcviG9z5TIokaOQXL6fGLUWGLAERxxFvuWaz@wM "Python 3 โ€“ Try It Online") redundancy is good ]
[Question] [ [Powerball](http://www.powerball.com/) is an American lottery that has recently gained attention because the current jackpot (as of January 11, 2016) is the [largest lotto prize in history](http://money.cnn.com/2016/01/06/luxury/largest-lottery-jackpots/), at about $1.5 billion ([USD](http://www.x-rates.com/table/?from=USD&amount=1400000000)). Powerball players choose 5 distinct numbers from 69 numbered white balls, and 1 one "Powerball" number from 26 numbered red balls. They [win](http://www.powerball.com/powerball/pb_prizes.asp) the jackpot if their five white ball choices match what was drawn in any order, *and* if they chose the correct "Powerball" number. So the chances of winning the jackpot are 1 in `(69 choose 5)*(26 choose 1)` or `((69*68*67*66*65)/(5*4*3*2*1))*26`, which is **1 in 292,201,338** No one won the jackpot in the [most recent drawing](https://www.youtube.com/watch?v=rhobr3rXV1k) on January 9, 2016, but perhaps someone will win the next drawing on January 13, 2016, 10:59 pm ET. # Challenge Write a program or function that simulates a Powerball drawing, taking no input but outputting 5 *distinct* random numbers from 1 to 69 inclusive, and then one random "Powerball" number from 1 to 26 inclusive (which could be a repeat of one of the 5 initial numbers). The "Powerball" number should always be the last number in the output, but otherwise the order of the first 5 numbers does not matter. The 6 numbers should be output **in decimal**, either space separated or newline separated, with an optional single trailing newline. Commas, brackets, and other characters are not allowed in the output. So these would be valid outputs (using the numbers from the [last drawing](https://www.youtube.com/watch?v=rhobr3rXV1k)): ``` 32 16 19 57 34 13 ``` ``` 32 16 19 57 34 13 ``` **All 292201338 possible outcomes should be possible with uniform probability.** You may use built-in pseudo-random number generators and assume they meet this standard. Here is an ungolfed reference implementation that works in Python 2 or 3: ``` import random print(' '.join(map(str, random.sample(range(1,70), 5) + [random.randint(1, 26)]))) ``` **The shortest code in bytes wins.** --- Note that I have no affiliation with Powerball and don't really suggest that you play. But if you win anything from numbers generated by one of the programs here, I'm sure we'd love to hear about it. :D [Answer] ## Dyalog APL, 10 bytes ``` (5?69),?26 ``` Dyadic `?` is โ€šรงโˆซ distinct random numbers in [1,โ€šรงยต], and monadic `?` is a single random number. Try it [here](http://tryapl.org/?a=%285%3F69%29%2C%3F26&run). [Answer] ## CJam, 16 bytes ``` 69,mr5<26mr+:)S* ``` ``` 69, range(69) mr shuffle the generated array 5< first 5 elements 26mr random number 0..25 + concat to array :) increment each array element S* join with spaces ``` [Try it online.](http://cjam.tryitonline.net/#code=NjksbXI1PDI2bXIrOilTKg) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` 69 5Zr26Yr ``` Uses [current version (9.2.0)](https://github.com/lmendo/MATL/releases/tag/9.2.0) of the language/compiler. ### Example With compiler run on Matlab: ``` >> matl > 69 5Zr26Yr > 66 59 64 56 29 12 ``` With compiler run on Octave: ``` >> matl > 69 5Zr26Yr > 2 69 41 44 23 22 ``` The first five numbers are separated by space, not by newline. This is due to Octave's underlying `randsample` function behaving differently from Matlab's (and has been corrected in a new version of the compiler). Anyway, newline and space are both allowed by the challenge. *Edit (April 4, 2016)*: [**Try it online!**](http://matl.tryitonline.net/#code=NjkgNVpyMjZZcg&input=) ### Explanation ``` 69 5Zr % randsample(69,5), without replacement by default. Gives a 5x1 column vector 26Yr % randi(26). Gives single number % implicit display ``` See relevant Matlab functions: [`randsample`](http://es.mathworks.com/help/stats/randsample.html) and [`randi`](http://es.mathworks.com/help/matlab/ref/randi.html). [Answer] # Ruby, ~~33~~ 32 ``` p *[*1..69].sample(5),rand(26)+1 ``` Ruby happens to have a built-in method, sample, that selects random values from an array without replacement. Thanks to QPaysTaxes for pointing out that I don't need the parens. [Answer] # R, ~~30~~ 29 bytes ``` cat((s=sample)(69,5),s(26,1)) ``` The `sample` function performs simple random sampling from the input. If a single integer is given as the first argument, sampling is done from 1 to the argument. The sample size is the second argument. We're employing the default option of sampling without replacement. [Try it online](http://www.r-fiddle.org/#/fiddle?id=CIVD9Col) [Answer] ## Python 3.5, 63 bytes ``` from random import* print(*sample(range(1,70),5),randint(1,26)) ``` It's basically the reference implementation golfed. Note that 3.5 is necessary to splat in a non-last argument. [Answer] # Octave, ~~35~~ 32 bytes Calvin's Hobbies confirmed that `ans =` was OK when using a function, so: ``` @()[randperm(69)(1:5),randi(26)] ``` It has similarities to Memming's [answer](https://codegolf.stackexchange.com/a/69239/31516), but it uses direct indexing that's only possible in Octave, and it's ~~5~~ 7 bytes shorter, so I figured it was worth posting anyway. `randperm(69)` creates a list with a random permutation of the numbers 1-69. It's possible to directly index the list (not possible in MATLAB) to only get the first 5 numbers like this `(1;5)`. The list is followed by `randi(26)` which returns a single number between 1 and 26. **Old:** ``` disp([randperm(69)(1:5),randi(26)]) ``` The resulting list is displayed using `disp`. [Answer] ## PowerShell v2+, ~~31~~ 27 bytes ``` 1..69|Random -c 5;Random 27 ``` Requires version 2 or newer, as `Get-Random` wasn't present in v1 (the `Get-` is implied, and `-Maximum` is positional). Output is newline separated. ### Ungolfed: ``` Get-Random -InputObject (1..69) -Count 5 Get-Random -Maximum 27 ``` [Answer] # Shell + coreutils, 31 ``` shuf -i1-69 -n5 shuf -i1-26 -n1 ``` [Answer] ## MATLAB, 40 ``` x=randperm(69);disp([x(1:5) randi(26)]) ``` I know. It's the boring solution. [Answer] ## PHP, 69 bytes ``` <?foreach(array_rand(range(1,69),5)as$k)echo$k+1," ";echo rand(1,26); ``` Pretty straight forward answer. Generate a 1-69 `range`, then use `array_rand` to grab 5 random keys from the array, and echo out the `$k+1` value (0-indexed), then echo a random int from 1-26. [Answer] ## C#, ~~153 bytes~~ 140 bytes Thanks to "McKay": ``` string.Join(" ",Enumerable.Range(1,69).OrderBy(e=>Guid.NewGuid()).Take(5).Concat(Enumerable.Range(1,26).OrderBy(e=>Guid.NewGuid()).Take(1))) ``` 153 bytes solution: ``` string.Join(" ",Enumerable.Range(1,69).OrderBy(e=>Guid.NewGuid()).Take(5))+" "+string.Join(" ",Enumerable.Range(1,26).OrderBy(e=>Guid.NewGuid()).Take(1)) ``` Simple solution using Linq and shuffling using GUID. [Answer] # Pyth - ~~13~~ ~~14~~ 13 bytes Major golfing possible, this was just a FGITW. ``` jb>5.SS69hO26 ``` [Try it online here](http://pyth.herokuapp.com/?code=jb%3E5.SS69hO26&debug=0). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 40 bytes ``` 1:5e,68{I`random(I)+1=Z`Z=w," "w}\;25:1& ``` ### Explanation Brachylog doesn't have a built-in for random numbers (yet...) so we have to use an SWI-Prolog predicate for that: [`random/1`](http://www.swi-prolog.org/pldoc/man?function=random/1). We can input SWI-Prolog code in Brachylog using backquotes. ``` 1:5e, \ ยฌรŸ Enumerate from 1 to 5 using \ (backtrack), which ยฌรŸ evaluates to false and thus constructs a loop 68{ } ยฌรŸ Declare sub-predicate 1 and call it with 68 as input I`random(I)+1=Z` ยฌรŸ Z is the arithmetic expression 'random(I) + 1' where ยฌรŸ I is the input of the sub-predicate Z=w, ยฌรŸ Evaluate Z and write it "\n"w ยฌรŸ Write a new line ; ยฌรŸ Else (we will reach this after the 5th iteration of ยฌรŸ the enumeration, since \ is always false) 25:1& ยฌรŸ Call the sub-predicate 1 with 25 as input ``` [Answer] # JavaScript (ES6), ~~106~~ ~~86~~ 84 bytes ``` F=(s=new Set,r=Math.random)=>s.size<5?F(s.add(r()*69+1|0)):[...s,r()*26|0+1].join` ` ``` Since we can't uniquely sample randoms in JavaScript, this works by creating a Set (which only holds unique values), recursively adding randoms (1-69) until there are 5 unique ones, appending a random number (1-26), then joining and returning it all out. [Answer] # [Elixir](http://elixir-lang.org), 83 Bytes ``` Enum.reduce Enum.take_random(1..69,5)++[Enum.random(1..26)],fn(x,a)->"#{a} #{x}"end ``` When just `IO.puts`ing an array of integers, Elixir will interpret the integers as characters and therefore output some string instead of the desired powerball numbers. So, we have to reduce the integer array down to a string. [Answer] ### Ruby, ~~47~~ ~~43~~ 39 bytes ``` puts *(1..69).to_a.sample(5),rand(26)+1 ``` I think it can be golfed more, but I'll work on that once I'm done admiring how pretty this code looks, considering. It works pretty much the same way as everything else: Take an array of the numbers 1 to 69, shuffle them, get the first five, output those, then output a random number between 1 and 26. I went through a few iterations before posting this: ``` puts (1..69).to_a.shuffle.first(5).join(' ')+" #{rand(26)+1}" #61 puts (1..69).to_a.shuffle[0..5].join(' ')+" #{rand(26)+1}" #58 puts (1..69).to_a.shuffle[0..5].join('<newline>'),rand(26)+1 #52 puts *('1'..'69').to_a.shuffle[0..5],rand(26)+1 #47 puts *('1'..'69').to_a.sample(5),rand(26)+1 #43 ``` (where `<newline>` is replaced with an actual newline) EDIT: Whoops, didn't see the preexisting Ruby answer. I stumbled on `sample` and was scrolling down to edit my answer, but then I saw it... Oh well. My final score is 43 bytes, but I'll keep golfing a little to see how well I can do. [Answer] # Mathematica, 64 bytes ``` StringRiffle@Append[Range@69~RandomSample~5,RandomInteger@25+1]& ``` Quite simple. [Answer] # Perl 5, 59 bytes ``` {say for(sort{-1+2*int rand 2}1..69)[0..5];say$==1+rand 25} ``` It's a subroutine; use it as: ``` perl -M5.010 -e'sub f{...}f' ``` [Answer] ## PHP, 65 bytes ``` <?=join(' ',array_rand(array_flip(range(1,69)),5))." ".rand()%26; ``` Thanks to the other PHP answer on this page. I wrote up a program on my own, and it turned out to be the exact same answer as the one written by Samsquanch, which drove me to take it a step further to save a few bytes. If anyone can figure out a way to append one array to another in here that's less than the 5 bytes it takes me to join the powerball number on after, I would greatly appreciate it, cause it's driving me nuts! The best I could come up with would be after `array_rand` and before `join`, having a statement something like `+[5=>rand()%25]`, but that's an extra byte over just concatenating it on after. ``` <?= // This represents an inline 'echo' statement range(1,69) // Get an array of all numbers from 1 to 69 inclusive array_flip( ) // Swap the keys and values. array_rand( ,5) // Get a random subset of five keys. join(' ', ).rand()%26 // Concatenate the array with spaces, along with the powerball number ``` Run it through the command line. Sample: ``` C:\(filepath)>php powerball.php ``` Output: ``` 12 24 33 67 69 4 ``` [Answer] ## PARI/GP, ~~71~~ 70 bytes ``` apply(n->print(n),numtoperm(69,random(69!))[1..5]);print(random(26)+1) ``` It generates a random permutation of [1..69], then takes the first 5. Unfortunately this is an inefficient user of randomness, consuming an average of 87 bytes of entropy compared to the information-theoretic ideal of 3.5. This is mainly because the entire permutation is generated instead of just the first 5 members, and also because the perms are ordered (losing lg 5! =~ 7 bits). Further, `random` uses a rejection strategy rather than using arithmetic coding. (This is because PARI uses Brent's xorgen, which is fast enough that the overhead from more complicated strategies is rarely worthwhile.) There are three 'obvious' changes which do not work under the current (2.8.0) version of gp. `random` and `print` could be stored in variables, and `print` could be called directly rather than via the anonymous `->` function: ``` r=random;apply(p=print,numtoperm(69,r(69!))[1..5]);p(r(26)+1) ``` Together these would save 9 bytes. Unfortunately both functions are valid without arguments, and hence are evaluated immediately rather than stored, so these do not compute the desired output. [Answer] ## Intel x86 Machine code, 85 bytes ``` ยฌรธI ยฌยฑโ€šร„โˆžโˆšโˆ1โˆšรญยฌยชE โˆšโˆ‘โˆšโ‰ฅBโ€šร„โˆžโˆšรชโˆšยฎ+ โ€šร„โˆžโˆšรฆโˆšรซโˆšรŸโˆšโˆ‘โˆ†รญโˆšรกโˆšรฆโˆšรขโ€šร„รปโˆšรขuโˆšยขโ€šร„โˆžโˆšโˆ1โˆšรญยฌยช โˆšโˆ‘โˆšโ‰ฅBโ€šร„โˆžโˆšรชโˆšยฎ 0โˆšยงโˆšรงยฌโˆ โˆšรงยฌยฑโˆšยดโˆšรœโˆšรฎ 00โ€šร„โ€ โˆšร‘ร€รœโˆšยฃยฌยฅโˆšรงร€รœโˆšรฒโˆšรงยฌโˆž โˆšรงโˆšร‰ ``` Well it does sometimes print the same numbers if so, just try again by pressing a key. Compile with: ``` nasm file.asm -o file.bin ``` Make sure to align it to a floppy size (add zeros at the end) in order to mount it to a vm (it does not need any operating system). Disassembly: ``` BITS 16 ORG 0x7c00 mov di,73 ;starting seed mov cl,5 ;we need five numbers loop: mov ax,di xor dx,dx mov bx,69 div bx inc dx mov ax,dx call print_rnd_number mov si,di shl di,1 add di,si add di,7 dec cl test cl,cl jne loop mov ax,di xor dx,dx mov bx,26 div bx inc dx mov ax,dx call print_rnd_number xor ah,ah int 0x16 mov ax,0x0002 int 0x10 mov cl,5 jmp loop print_rnd_number: aam add ax,0x3030 xchg al,ah mov bl,ah mov ah,0x0E int 0x10 mov al,bl int 0x10 mov al,' ' int 0x10 ret ``` [Answer] # C, 142 bytes ``` i,x[6],n;main(j){for(srand(time(0));i<6;n-i?0:printf("%d ",x[i]),i++)for(x[n=j=i]=(69-i/5*43)*(rand()/2147483647.)+1;i<6&&j--;)i-=x[i]==x[j];} ``` Not terribly happy with this solution as it feels like there should be more golfing opportunity. I'll look at it again tomorrow with fresh eyes. Try it [here](https://ideone.com/cIn9p8). [Answer] # Swift, 165 bytes ``` import UIKit;var a=[Int]();for i in 0...5{func z()->Int{return Int(arc4random_uniform(i<5 ?68:25)+1)};var n=z();while i<5&&a.contains(n){n=z()};a.append(n);print(n)} ``` Can quickly be run in an Xcode Playground. **EDIT:** Current problem here is that it's theoretically possible for this to run forever in the while loop if arc4random\_uniform somehow keeps pulling the same number. The odds of that happening, for any significant length of time, are probably better than the odds of winning the Powerball. [Answer] # [Perl 6](http://perl6.org), ~~ยฌโ€ 32ยฌโ€ ~~ยฌโ€ 31 bytes ``` # space is necessary so that the parens denote a list # rather than being part of the call to `put` put (pick(5,1..69),(1..26).pick) # 32 bytes # 25 35 57 67 62 24โ€šรชยง ``` --- Turning it into a function that returns a string, I can remove 4 bytes (`putโ€šรชโ€ `) while only adding 3 (`{~` `}`) ``` {~(pick(5,1..69),(1..26).pick)} # 31 bytes ``` Usage: ``` say {...}().perl; # use .perl to prove it returns a string # "25 35 57 67 62 24" ``` --- ### If a function were allowed to return a list of the values, the following would also work. ( Otherwise it would be the same as above but within `{ }` ) * function that returns a single flat list ``` {|pick(5,1..69),(1..26).pick} # 29 bytes # (25,35,57,67,62,24) ``` * function that returns a list with the first 5 numbers in a sub list ``` {pick(5,1..69),(1..26).pick} # 28 bytes # ((25,35,57,67,62),24) ``` * function that returns a list with the first 5 in a sub list, and the Powerball in another sub list ``` {pick(5,1..69),pick 1,1..26} # 28 bytes # ((25,35,57,67,62),(24,)) ``` [Answer] # Seriously, 35 bytes My first attempt at an answer in a golfing language. Feels longer than it should have to be. The repetition could likely be removed with **W**, but it seems to be broken in the online interpreter and I don't want to post untested code. Too bad **{** doesn't work on lists. **Code:** ``` :70:1xi J{. J{. J{. J{. J{.:26:Ju. ``` **Hex dump:** ``` 3a37303a317869204a7b2e204a7b2e204a7b2e204a7b2e204a7b2e3a32363a4a752e7f ``` **Explanation:** ``` :70:1x # Push a list of the numbers 1-69 i # Explode list J{. # rotate stack random(len(stack)) times and pop/print J{. J{. J{. J{. # same thing 4 more times :26:Ju. # print random number in 1-26 # (7F) unprintable, terminate without explicit printing ``` [Online interpreter](https://seriouslylang.herokuapp.com/) [Answer] # Lua, 96 Bytes A simple solution, using a table as a set by putting the value inside it as `table[value]=truthy/falsy`to be able to check if they are inside it or not. I lose 5 bytes because I have to set the first value of my table, else I won't go inside the `while(o[n])`loop and will simply output `n` before using the random function. As Lua uses 1-based tables, I also have to force it to put its first value to the cell `[0]`, otherwise I couldn't output a `1`. ``` m,n,o=math.random,0,{[0]=0}for i=1,5 do while(o[n])do n=m(69)end o[n]=0 print(n)end print(m(26)) ``` ### Ungolfed: ``` m,n,o=math.random,0,{[0]=0} for i=1,5 do while(o[n]) do n=m(69) end o[n]=0 print(n) end print(m(26)) ``` [Answer] ## C++, 252 bytes ### Golfed: ``` #include<iostream> #include <random> int main(){std::random_device rd;std::mt19937 gen(rd());std::uniform_int_distribution<> dis(1,69);for(int c=0;c<=5;c++){std::cout<<dis(gen)<<" ";}int x=dis(gen);while(x>26||x<1){x=dis(gen);}std::cout<<x;return 0;} ``` ### Ungolfed: ``` #include<iostream> #include <random> int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 69); for(int c = 0; c <= 5; c++){ std::cout<<dis(gen)<<" "; } int x = dis(gen); while (x > 26 || x < 1){ x = dis(gen); } std::cout<<x; return 0; } ``` ]
[Question] [ The [van der Corput sequence](https://en.wikipedia.org/wiki/Van_der_Corput_sequence) is one of the simplest example of [low-discrepancy sequence](https://en.wikipedia.org/wiki/Low-discrepancy_sequence). Its `n`-th term is just `0.(n written in base 10 and mirrored)`, so its first terms are : `0.1`, `0.2`,`0.3`,`0.4`, `0.5`,`0.6`,`0.7`, `0.8`,`0.9`, `0.01`, `0.11`,`0.21`,`0.31`, `0.41`,`0.51`,`0.61`, `0.71`,`0.81`,`0.91`, `0.02`, `0.12`,`0.22`,`0.32`, `0.42`,`0.52`,`0.62`, `0.72`,`0.82`,`0.92`, ... # The challenge Write a program or a function in any programming language that takes as input a positive integer `n` less than `10^6` and returns or print the first `n` terms of the van der Corput sequence. The output format can be a list of floating point numbers, a list of strings of the form `0.digits`, or a unique string where the terms are separated by commas and/or whitespaces, newlines. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. The shortest source code wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes Code: ``` >GNโˆšรปR, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=PkdOw55SLA&input=MzA) Explanation: ``` > # Increment, pushes input + 1 G # For N in range(1, input + 1): N # Push N โˆšรป # Convert to double, which appends `.0` at the end of an integer R # Reverse top of the stack , # Pop and print with a newline ``` Uses CP-1252 encoding. [Answer] # Oracle SQL 11.2, ~~64~~ ~~62~~ 58 bytes ``` SELECT REVERSE(LEVEL||'.0')FROM DUAL CONNECT BY LEVEL<=:1; ``` Old version ``` SELECT '0.'||REVERSE(TRIM(LEVEL))FROM DUAL CONNECT BY LEVEL<=:1; ``` Concatenating '' to a number casts it to a string. It is 2 bytes shorter than using TRIM(), which is shorter than TO\_CHAR(). Since concatenating a string to a NUMBER results in a string, it is possible to use that string to manage the '0.' part of the result. [Answer] ## CJam, ~~14~~ 11 bytes *Thanks to Sp3000 for saving 3 bytes.* ``` ri{)d`W%S}/ ``` [Test it here.](http://cjam.aditsu.net/#code=ri%7B)d%60W%25S%7D%2F&input=20) ### Explanation ``` ri e# Read input and convert to integer N. { e# For each i from 0 to N-1... ) e# Increment. d e# Convert to double. ` e# Get string representation (which ends in ".0"). W% e# Reverse. S e# Push a space. }/ ``` [Answer] # Perl 6, ~~24~~ ~~22~~ 20 bytes ``` {"0."X~(^$_)ยฌยช.flip} ``` Thanks [Aleks-Daniel Jakimenko-A.](https://codegolf.stackexchange.com/users/49921/aleks-daniel-jakimenko-a) for yet another two bytes **old version** ``` {("0."~.flip for ^$_)} # Alternate below, same byte count {map ^$_: "0."~*.flip} ``` EDIT: Thanks raiph for extra 2 bytes **usage** ``` > my &f = {"0."X~(^$_)ยฌยช.flip} -> ;; $_? is raw { #`(Block|333498568) ... } > f(25) (0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 0.51 0.61 0.71 0.81 0.91 0.02 0.12 0.22 0.32 0.42) ``` [Answer] # Mathematica, 40 bytes ``` "0."<>StringReverse@ToString@#&~Array~#& ``` --- **Test case** ``` %[20] (* {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.01,0.11,0.21,0.31,0.41,0.51,0.61,0.71,0.81,0.91,0.02} *) ``` [Answer] # JavaScript (ES6), 58 An anonymous function returning a string with comma separated values ``` n=>[...[...Array(n)].map(_=>n--+'.0')+''].reverse().join`` ``` **TEST** ``` f=n=>[...[...Array(n)].map(_=>n--+'.0')+''].reverse().join`` function test() { R.textContent = f(+I.value) } test() ``` ``` N:<input id=I type=number value=20 oninput="test()"><br><pre id=R></pre> ``` [Answer] # Pyth, 8 bytes ``` m_`cd1SQ ``` [Try it online.](http://pyth.herokuapp.com/?code=m_%60cd1SQ&input=20&debug=0) This is really just a combination of [this](https://codegolf.stackexchange.com/a/71542/30164) and [this](https://codegolf.stackexchange.com/a/71547/30164) answer. Therefore I'm making it a community wiki. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` :0re:""rcr:"0."rcw,@Sw\ ``` This takes a number as input and outputs the result to STDOUT, separated by spaces. Fairly straightforward. Unfortunately we have to concatenate the number with an empty string to convert this number to a string (`:""rc`), because there is no built-in conversion predicate yet. The conversion to string is necessary, because if we reverse the digits of the number, then the leading zeros (e.g. `10` becomes `01`) would be lost. [Answer] # Pyth, 11 bytes ``` m+"0."_`dSQ ``` [Try it here!](http://pyth.herokuapp.com/?code=m%2B%220.%22_%60dSQ&input=20&debug=0) ### Explanation ``` m+"0."_`dSQ # Q = input m SQ # Map the range(1,Q) to... + # ...the concatenation of: "0."_`d # "0." and the reversed element ``` [Answer] # Pyth - 10 bytes ``` _M+R".0"SQ ``` [Try it online here](http://pyth.herokuapp.com/?code=_M%2BR%22.0%22SQ&input=20&debug=0). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` :"'0.'@VPh ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiInMC4nQFZQaA&input=MjI) ``` : % implicit input. Generate vector [1,2,...,input] " % for each '0.' % push string '0.' @ % push loop variable (that is, 1,2,3,... in each iteration) V % convert to string P % reverse h % concatenate horizontally % implicit end of loop % implicit display of all stack contents ``` [Answer] # Haskell, ~~36~~, 27 bytes ``` f n=reverse.show<$>[1.0..n] ``` Two bytes saved by nimi and an additional 7 by Lynn. [Answer] ## Python 3, ~~47~~ 44 bytes ``` lambda n:[f'{i+1}.0'[::-1]for i in range(n)] ``` a shorter solution with Python 2 ``` lambda n:['0.'+`i+1`[::-1]for i in range(n)] ``` Edit: gain 3 bytes using f-string interpolation from python 3.6, now we are even with python 2 solution. **Test case** ``` >>> f(25) ['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '0.01', '0.11', '0.21', '0.31', '0.41', '0.51', '0.61', '0.71', '0.81', '0.91', '0.02', '0.12', '0.22', '0.32', '0.42', '0.52'] ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~[22](https://codegolf.stackexchange.com/revisions/233333/2)~~, 16 bytes *4 bytes saved by JoKing* ``` IFS" 0."LPWaSDn| ``` [Try it online!](https://tio.run/##S8/PScsszvj/39MtWEnBQE/JJyA8Mdglr@b/fyNLQwA "Gol><> โ€šร„รฌ Try It Online") [Answer] ## PowerShell, 52 bytes ``` while($a++-$args[0]){"0."+-join"$a"["$a".Length..0]} ``` A little longer than I'd like, but uses a couple of neat tricks. The `while` loop is obvious, but the conditional is a little tricky - we have `$a` (which starts as `$null` when first referenced) and then subtract our input number `$args[0]`. In PowerShell, math operations on `$null` treat it as zero, so for input `20` for example this will result in `-20`. Since any non-zero number is `$true`, the loop conditional will be `$true` right up until `$a` equals our input number (at which point the subtraction will equal `0` or `$false`). The trick comes from the post-increment `++`, which doesn't execute until *after* the subtraction is calculated, so handling input of `1` will correctly output `0.1` and then stop the loop on the next iteration. Each time in the loop, we just create a string literal which gets left on the pipeline and output accordingly. We construct this from `"0."` concatenated with the result of the unary `-join` operator that has acted on the char-array created from taking the string `"$a"` backwards (by indexing via the range `"$a".length..0`). ### Test Runs ``` PS C:\Tools\Scripts\golfing> .\van-der-corput-sequence.ps1 1 0.1 PS C:\Tools\Scripts\golfing> .\van-der-corput-sequence.ps1 20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 0.51 0.61 0.71 0.81 0.91 0.02 ``` [Answer] # Bash, 36 bytes ``` for i in `seq $1`;do rev<<<$i.0;done ``` Takes a number as a command line argument, and outputs each term on a separate line. For example: ``` $ ./vdc.sh 12 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 ``` [Answer] # Japt, 12 bytes ``` Uโˆšโ‰ค1 ยฌร†+".0" w ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=VfIxIK4rIi4wIiB3&input=MjAw) ### How it works ``` // Implicit: U = input integer Uโˆšโ‰ค1 ยฌร† // Create the inclusive range [1..U], and map each item Z to: +".0" w // Z + ".0", reversed. // Implicit: output last expression ``` [Answer] # [beeswax](http://esolangs.org/wiki/Beeswax), ~~57~~ 53 bytes Working on the binary digit output problem for rosettacode I noticed that I could use the same short division algorithm for the van der Corput sequence, just using division and modulo by 10 instead of 2. The output is reversed in both cases. Golfed down by 4 bytes, by mirroring the code: ``` `.0` XfE@~@L#; { %X<#dP@T~P9_ q<# N >:'bg?b ``` Hexagonal prettyprint, for easier orientation: ``` ` . 0 ` X f E @ ~ @ L # ; { % X < # d P @ T ~ P 9 _ q < # N > : ' b g ? b ``` Explanation of one cycle through the program, using the original code: ``` ;#L@~@EfX `0.` _9P~T@Pb#>X% { N #>p d?gd':< lstack gstack _9P [0,0,10]โ€šร„ยข create bee, set top to 10 ~T [0,10,n]โ€šร„ยข flip top and 2nd, enter n @P [n,10,1]โ€šร„ยข flip top and 3rd, increment top b redirect to upper left [n,10,1]โ€šร„ยข E [n,10,1]โ€šร„ยข (2)clone bee in horizontal direction flip lstack 1st/3rd [1,10,n]โ€šร„ยข @ f [n,10,1]โ€šร„ยข [1]โ€šร„ยข push lstack top on gstack flip lstack 1st/2nd [1,n,10]โ€šร„ยข ~ X clone bee in all directions flip 1st/3rd [10,n,1]โ€šร„ยข @ `0.` print "0." to STDOUT skip if 1st>2nd [10,n,1]โ€šร„ยข L > (1)redirect if 1st<2nd, del. bee # X clone bee in all directions (if 1st>2nd, terminate program) ; % { [n,10,1]โ€šร„ยข 1st=1st%2nd, output lstack 1st to STDOUT >p redirect < redirect : [n,10,0]โ€šร„ยข 1st=1st/2nd ' skip next instr. if 1st=0 d redirect to upper right, loop back to (1) g [n,10,1] [1]โ€šร„ยข push gstack top on lstack 1st d? []โ€šร„ยข pop gstack, redirect to upper right N print newline to STDOUT P [n,10,2] increment lstack 1st E looped back to (2) ``` Example: ``` julia> beeswax("vandercorput.bswx",0,0.0,Int(20000)) i300 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 . . . 0.492 0.592 0.692 0.792 0.892 0.992 0.003 Program finished! ``` [Answer] # R, 59 Bytes ``` example(strsplit);cat(strReverse(sprintf('%s.0',1:scan()))) ``` *explanation* `example(strsplit)` creates the function `strReverse` (then it should be obvious) Using `IRanges::reverse`, this could be golfed to 47 bytes ``` cat(IRanges::reverse(sprintf('%s.0',1:scan()))) ``` [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ, 12 chars / 15 bytes ``` โ€šยฉยงโ€šร…ฮฉ1โˆšร˜โ€šรญยฎโˆšรผ)ฦ’รฑโ€šรงรป.0ยทยฅรด ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=10&code=%E2%A9%A4%E2%81%BD1%C3%AF%E2%92%A8%C3%9F%29%C4%96%E2%8D%9E.0%E1%B4%99)` It's... okay. # Explanation `โ€šยฉยงโ€šร…ฮฉ1โˆšร˜โ€šรญยฎ` creates a range `[1,โˆšร˜]` to map over, `โˆšรผ)` converts mapitem (number) to string, `ฦ’รฑโ€šรงรป.0` concats `.0` to the end, and `ยทยฅรด` reverses the whole string. [Answer] # Python 2, 54 Bytes ``` def f(i): for i in range(1,i):print("."+str(i)[::-1]) ``` **Explanation:** Iterate through the set `[1,input)` and appends the reversed `i` to `.`. *Still an be golfed more.* [Answer] # PHP, ~~45~~ 41 bytes ``` for(;$i++<$argv[1];)echo strrev(",$i.0"); ``` Takes the input argument from CLI. Run like this: ``` php -r 'for(;$i++<$argv[1];)echo strrev(",$i.0");' 100 ``` * Saved 3 bytes by concatenating the string before reversing [Answer] # Retina, 39 bytes ``` 1 1$`0. (1)+ $#1 +`(\d)0\.(\d*) 0.$2$1 ``` Takes input in unary. [Try it online here.](http://retina.tryitonline.net/#code=MQoxJGAwLiAKKDEpKwokIzEKK2AoXGQpMFwuKFxkKikKMC4kMiQx&input=MTExMTExMTExMTExMTExMTExMTExMQ) [Answer] # Gema, 45 characters ``` *=@set{i;0}@repeat{*;@incr{i}0.@reverse{$i} } ``` Sample run: ``` bash-4.3$ gema '*=@set{i;0}@repeat{*;@incr{i}0.@reverse{$i} }' <<< 12 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 ``` [Answer] ## APL, 7 ``` โ€šรฅฮฉโ€šรงรฉโ€šรฅฮฉ1โ€šรงรฏโ€šรงโ‰ฅโ€šรฉรฏ ``` Explanation: ``` โ€šรงโ‰ฅโ€šรฉรฏ creates a vector of numbers from 1 to user input 1โ€šรงรฏโ€šรงโ‰ฅโ€šรฉรฏ formats these numbers like ##.0 โ€šรฅฮฉ inverts the whole string โ€šรฅฮฉโ€šรงรฉ transforms back to numbers and inverts order ``` [Answer] # [Julia](http://julialang.org), ~~50~~ ~~38~~ ~~33~~ 31 bytes I went for a different output format to shorten the code by 12 bytes. The function returns an array of strings now. Shortened by 5 more bytes. Thanks to *Alex A.* for reminding me of string interpolation and using an anonymous function (getting rid of 2 more bytes). ``` n->["0."reverse("$i")for i=1:n] ``` or alternatively ``` n->[reverse("$(i/1)")for i=1:n] ``` Test ``` julia> @time f(10000) 0.002260 seconds (60.01 k allocations: 2.823 MB) 10000-element Array{ASCIIString,1}: "0.1" "0.2" "0.3" "0.4" "0.5" "0.6" "0.7" "0.8" "0.9" "0.01" "0.11" "0.21" "0.31" "0.41" "0.51" "0.61" "0.71" "0.81" "0.91" "0.02" "0.12" "0.22" "0.32" โ€šรฃร† "0.8799" "0.9799" "0.0899" "0.1899" "0.2899" "0.3899" "0.4899" "0.5899" "0.6899" "0.7899" "0.8899" "0.9899" "0.0999" "0.1999" "0.2999" "0.3999" "0.4999" "0.5999" "0.6999" "0.7999" "0.8999" "0.9999" "0.00001" ``` [Answer] # Python 2, 40 bytes ``` lambda n:[`i+1.`[::-1]for i in range(n)] ``` Example: ``` >>> f=lambda n:[`i+1.`[::-1]for i in range(n)] >>> f(30) ['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '0.01', '0.11', '0.21', '0.31', '0.41', '0.51', '0.61', '0.71', '0.81', '0.91', '0.02', '0.12', '0.22', '0.32', '0.42', '0.52', '0.62', '0.72', '0.82', '0.92', '0.03'] ``` Algebraic solving: ``` corput(x) = reversed(str(float(x+1))) = reversed(str(x+1.)) = str(x+1.)[::-1] = `x+1.`[::-1] ``` [Answer] # jq 1.5, ~~40~~ 35 characters (34 characters code + 1 character command line option.) ``` range(.)|"\(.+1).0"/""|reverse|add ``` Sample run: ``` bash-4.3$ jq -r 'range(.)|"\(.+1).0"/""|reverse|add' <<< 12 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 ``` [On-line test](https://jqplay.org/jq?q=range%28.%29%7C%22%5C%28.%2B1%29.0%22/%22%22%7Creverse%7Cadd&j=12) (Passing `-r` through URL is not supported โ€šร„รฌ check Raw Output yourself.) The same with links to documentation: ``` [range](https://stedolan.github.io/jq/manual/#range%28upto%29,range%28from;upto%29range%28from;upto;by%29)([.](https://stedolan.github.io/jq/manual/#.)) [|](https://stedolan.github.io/jq/manual/#|) "[\(](https://stedolan.github.io/jq/manual/#Stringinterpolation-%5C%28foo%29). [+](https://stedolan.github.io/jq/manual/#Addition-+) 1[)](https://stedolan.github.io/jq/manual/#Stringinterpolation-%5C%28foo%29).0" [/](https://stedolan.github.io/jq/manual/#Multiplication,division,modulo-*,/,and%) "" | [reverse](https://stedolan.github.io/jq/manual/#reverse) | [add](https://stedolan.github.io/jq/manual/#add) ``` As a more readable alternative, the above could be also written like this ([on-line](https://jqplay.org/jq?q=range%28.%29%20|%20.%20%2B%201%20|%20tostring%20|%20.%20%2B%20%22.0%22%20|%20split%28%22%22%29%20|%20reverse%20|%20join%28%22%22%29&j=12)): ``` range(.) | . + 1 | tostring | . + ".0" | split("") | reverse | join("") ``` [Answer] # Dyalog APL, 6 ``` โ€šรฅฮฉยฌยฎ1โ€šรงรฏยฌยฎโ€šรงโ‰ฅ ``` This is an anonymous function that takes one argument, i.e.: ``` โ€šรฅฮฉยฌยฎ1โ€šรงรฏยฌยฎโ€šรงโ‰ฅ 20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 0.51 0.61 0.71 0.81 0.91 0.02 fโ€šรœรชโ€šรฅฮฉยฌยฎ1โ€šรงรฏยฌยฎโ€šรงโ‰ฅ f 20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 0.51 0.61 0.71 0.81 0.91 0.02 ``` Explanation: ``` โ€šรงโ‰ฅ โ€šรงรน get the integers from 1..n 1โ€šรงรฏยฌยฎ โ€šรงรน format each with 1 decimal โ€šรฅฮฉยฌยฎ โ€šรงรน reverse each string ``` [Answer] # BBC BASIC, ~~89~~ ~~88~~ 87 bytes ``` 0T=1:REP.P."0."FNR(STR$T):T=T+1:U.0 1DEFFNR(S$)IFS$="":=""EL.=FNR(MI.S$,2))+LE.S$,1) ``` Used abbreviations to shorten things as much as possible. Compatible with both Brandy Basic and BASIC 2 on the original machine. For modern BBC BASICs you could also leave off the line numbers to save two more bytes. ]
[Question] [ On the Mathematica Stack Exchange, [100xln2 asks](https://mathematica.stackexchange.com/questions/288024/how-can-i-define-a-sequence-of-integers-which-only-contains-the-first-k-integers): > > I need a list of integers [โ€šร„ยถ] The list contains integers and is characterized by [three] parameters, lets call them k and j [and listmax], which should be variable. > > > If `k=1` and `j=1` then the list would look like this: {1,3,5,7,9,11,....until listmax} > > > If `k=2` and `j=3` then the list would look like this: {1,2,6,7,11,12,16,17,.....until listmax} > > > Generally speaking, the List contains the first k integers, then doesn't contain the next j integers, then contains the next k integers, then doesn't contain the next j integers and so on and so on. > > > Let's help them out! (I hope they're okay with Jelly, Vyxal, or Befunge code instead of Mathematicaโ€šร„ยถ) Given three positive integers \$(k, j, \text{listmax})\$, make a list of integers as described above, sorted in increasing order. For \$(3,2,6)\$ you should return `[1,2,3,6]` rather than `[1,2,3]` or `[1,2,3,6,7,8]`. You can imagine you're generating an infinite โ€šร„รบinclude 3, skip 2โ€šร„รน list, and taking elements from it as long as they're โ€šรขยง 6. # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Write the shortest possible answer, measured in bytes. Standard I/O methods apply, which means valid submissions include: * a three-parameter function that returns a list of numbers, * a three-parameter function that prints each number in the list, * a full program that reads inputs and prints each number in the list, * [and so on](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). # Tests In the format `k j listmax --> output`: ``` 1 1 11 --> [1, 3, 5, 7, 9, 11] 2 13 19 --> [1, 2, 16, 17] 2 13 16 --> [1, 2, 16] 1 4 49 --> [1, 6, 11, 16, 21, 26, 31, 36, 41, 46] 2 4 22 --> [1, 2, 7, 8, 13, 14, 19, 20] 2 10 13 --> [1, 2, 13] 5 15 10 --> [1, 2, 3, 4, 5] 1 13 27 --> [1, 15] 7 4 31 --> [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29] 99 99 1 --> [1] ``` [Answer] # [Python](https://www.python.org), ~~53~~ ~~48~~ 47 bytes ``` lambda k,j,l:[x+1for x in range(l)if x%(k+j)<k] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY39XMSc5NSEhWydbJ0cqyiK7QN0_KLFCoUMvMUihLz0lM1cjQz0xQqVDWytbM0bbJjodpcCooy80o00jQMdYDQUFOTCyZgpGOsY2iJJGCuY6JjjKzC0lIHiIAiELMWLIDQAA) -5 by Lynn -1 by Ethan C [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` โˆšรฒ+xยทฯ€ร…M ``` [Try it online!](https://tio.run/##y0rNyan8///wDO2Khzsbff8fXq50dNLDnTMeNa2J/P8/2lBHwTBWRyHaCEgbozCAMiZQARhtaABimAIZplAVhmApc6gSS0sdBUvL2P@GIBkg29AMKAGkjcCGgvQD2UDFxiB5AA "Jelly โ€šร„รฌ Try It Online") Takes input as `[k, j]` on the left, and `listmax` on the right. -1 byte thanks to Lynn pushing me to save a byte! ## How it works ``` โˆšรฒ+xยทฯ€ร…M - Main link. Takes [k, j] on the left, listmax on the right โˆšรฒ+ - [1, -1] x - Repeat 1 k times and -1 j times ยทฯ€ร… - Mold this list of length k+j to length listmax M - Maximal indices, i.e. indices of the 1s ``` [Answer] # [J](https://www.jsoftware.com), ~~12~~ 11 bytes ``` >:@I.@$1-I. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVHLSsRAEMTrfEUjwrIwCememWQn4LIgCAuevEpOYhAvXvRrvMSDJ7_AX_FHvFo9D8kipBmq-lHVnbf3p-XrvKXNTJcjbSx1NCKalq5ub64_Xl_mZve5Hw_H9nDBzbHNzPfZz9Y83D8-EzPNxMQFRSAhdgX2J9DHVOszEknJgtjl0q7ADjAQh1I7ZJUyyKno8NcKECM-Y5J5w1rK1DR7umNLzlKwNFiKFvRk1JA6rXkB3SOGmupPUxMGejVfWS3m3CRahNepDl6P1_c6yOuCqznQ36EHZtgj4EW6JNip5lrQTUY318yKRiP6gppBPQ5ScwwOt9Cj_C9PZiHNstIOdWEEPAl4AS8h7yLgRfk4mXRXqpMns83_f1ny-ws) Takes input as `listmax f (k, j)`. -1 byte thanks to ngn by taking `k,j` instead of `j,k`. ``` >:@I.@$1-I. I. k copies of 0 and j copies of 1 1- change 0 to 1 and 1 to 0 $ take listmax cyclically I.@ convert each occurrence of 1 to its index (0-based) >:@ add 1 ``` # [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes ``` {1+&x#~&y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxtUEEKAjEMvPcVAWEvdrFJ26214EeWXvcNiujbnXTdtYKHkGEmySRZLg8+DrfDa7g/jVlm5sLEVVEuQuwbnHYYMvSgSARkQ+xVdg26Eolj05NOak2eS/qUlpwp52rMyUAlZhrHK81syVuKlpKlbEFXo47EedcF9IRImzT9ShUDA4Vvgxbz2iRahOzVBzkgh0kHBRLp58D/jB4swwGBXcQ1Q6eevSEu01NV6Wg0oi/qMqiXtGv6FDwBK/wpb8vCmqXzjtvBCOwk4AW8xPUWAS/K45vtqbRNrm/gGVrj) Takes input as `f[listmax;k,j]`. Pretty much a built-in-to-built-in translation of the J solution above. [Answer] # [R](https://www.r-project.org), ~~32~~ 31 bytes ``` \(k,j,m)which((1:m-1)%%(k+j)<k) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZFfSgMxEMbx1VMslEKC38LO5N-mWC-ifRKk3VAotqVn6Bn6sj6Ix-g9PI1To2u2koHAfL_5ZiY5vb32H2mbVptu_r7fvdTt-UkldFjrw3L1vFSKZuua9HSq0l2n75PO1OfNMVcpghzS1aSq64fqkWDgEBAlubj9YRhkQLGAJONB4YrwV8QgEyxsWS_FdLFgAT2MdPWwQvnC0YJ5ZBjQfrexMgu4KZs3Ioybm0F2IIlmJBtxd8V4YsuhIOhPDIIa-l8tOwQQ_07k8ouAWrCYyfDushoHsGTiYBcjJAq_Rf6Rvs_3Fw) Indexes of elements of `0..(listmax-1)` that are less than `k` after modulo-`(k+j)`. [Answer] # Dyalog APL, 6 bytes Thanks [@Lynn](https://chat.stackexchange.com/users/136994) for -6 ``` โ€šรงโˆ1=โ€šรงยฅโ€šร รฒโ€šรงโˆยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร…โ„ขโ€šร…โ„ขโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  โ€šรงโˆ # โ€šร„รฉโ€šร…ยฐAt what indices โ€šรงโˆ # โ€šร„รฉโ€šร…ยขis the list of k 1's and j 2's โ€šรงยฅ # โ€šร„รฉโ€šร…ยฃcycled to length listmax 1= # โ€šร„รฉโ€šร…ยงequal to 1? ๏ฃฟรผรญรฉ ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). left argument listmax, right argument pair of k and j [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 30 bytes ``` @(k,j,m)find(mod(0:m-1,k+j)<k) ``` [Try it online!](https://tio.run/##TY3RCoJAEEXf/Yr7Eu7SJs5qiW5C/1E9RLqg4hoqgf28jYbQzDxczhxmuuf4eJezzYMgmC@iUbVqpa1cIdquEGHWHkg1@1qeGzmP5TAOyHElcJOBBkWgdAsnwzxGvIIYWq@LkHcGRxBPuBis6sQgYSXiI2m6DN2NZ7seju9TNlSfUqzvFEkPXBNz@0PCMVTYsv7LkZRm1e2rr9xoBSn4uwq@wsTaRv2b86VXumL@Ag "Octave โ€šร„รฌ Try It Online") ### Explanation ``` @(k,j,m)find(mod(0:m-1,k+j)<k) @(k,j,m) % Define anonymous function of k, j, m 0:m-1 % Range [0 1 2 ... m-1] mod( ,k+j) % Modulo k+j (element-wise) <k % Less than k? (element-wise) find( ) % (1-based) Indices of true entries ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 54 bytes ``` i;f(a,b,m){for(i=0;i<m;i++%(a+b)<a&&printf("%d ",i));} ``` [Try it online!](https://tio.run/##DchBCoAgEADAc75CgmQXNygKOmw9xgxjD1pEdJHebs1xfLt7X4pwAEcrRczhuECWjmWOLNY24OyKszPmvCTdAepm0zUJIr/lDx2dJHgO2VBlVQWYSI@khx5ZveUD "C (gcc) โ€šร„รฌ Try It Online") [Answer] # C (gcc), 62 bytes ``` i,j;f(a,b,m){for(i=j=0;m/++i;j-->b&&printf("%d ",i))j=j?:a+b;} ``` [Try It Online!](https://tio.run/##DclRCsIwDADQb3uKMnAkNEXFgWConqXtqCTQTcbYz9jZq@/3Zf/JuTUh5QKRElXcy7yABA1XrhfnhNX7V@r77yLTWqA7j7YjQdSg72d0iY/2D1ujTLDNMqLZzanAg@xA9n5DNkf7AQ) Ungolfed: ``` i,j; f(a,b,m) { for(i=j=0;m/++i;j-->b&&printf("%d ",i)) j=j?:a+b; } ``` `i` is the counter, and the loop ends when it's greater than `m`, which is the maximum value. `j` is initialized to `0`, but is reinitialized to `a+b` before it is read from. It's decremented once for each iteration of the loop, and `i` is only printed when `j` is greater than `b`, so only the first `a+b` - `b` = `a` values are printed. When `j` reaches 0 after `b` more iterations, it's set to `a+b` again. [Answer] # [Zsh](https://www.zsh.org/), 59 bytes ``` for ((;i<$1&&i++<$3;))l+=({$i..$3..$[$1+$2]}) echo ${(on)l} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwao0DU2N4tQSBd2KpaUlaboWN63T8osUNDSsM21UDNXUMrW1bVSMrTU1c7RtNapVMvX0VIyBOFrFUFvFKLZWkys1OSNfQaVaIz9PM6cWakSSJleagiEIGgIZRgqGxgqGlnCWGVjSRMEEImSiYGQEkTMASgNZpgqGQGQAMcJYwcgcyDIHKjMGGWZpCUKGXBCbFiyA0AA) I really think there's some gains to be had from another method, but that method eludes me. This loops, iterating the starting point of a brace expansion `{$start..$end..$skip}` until it reaches the first or third argument (j or listmax). Each brace expansion is appended to the list `l`. Finally, the `(on)` flag sorts the list numerically. **-8 bytes** if the output does not need to be sorted. (`<<<$l`) [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ยทฯ€ร…โ€šรœรซยฌโ‰ฅCยทโˆยฃโ€šร…โˆž+ ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///huYHihpHCs0PhuKPigbAr////N/8zMf80 "Husk โ€šร„รฌ Try It Online") Same approach as [my Nibbles answer](https://codegolf.stackexchange.com/a/263319/95126). Takes arguments in order `k`,`listmax`,`j`. ``` ยทฯ€ร…โ€šรœรซยฌโ‰ฅCยทโˆยฃโ€šร…โˆž+ C # cut ยทโˆยฃโ€šร…โˆž # the range from 1..middle argument # into sublists of length + # sum of other arguments ยทฯ€ร… # then map over this list-of-lists โ€šรœรซ # taking ยฌโ‰ฅ # first-arg elements from each ยทฯ€ร… # and flatten the result ``` --- **Alternative approach, also 7 bytes** ``` fยฌยขยทฯ€รฒโ€šร…โˆžยทโˆรฃ2ยทโˆยฃ ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//9mwqLhuZjigbDhuIsy4bij////WzcsNF3/MzE "Husk โ€šร„รฌ Try It Online") Takes arguments in order `[k,j]`,`listmax`. ``` fยฌยขยทฯ€รฒโ€šร…โˆžยทโˆรฃ2ยทโˆยฃ ยทฯ€รฒ # repeat ยทโˆรฃ2 # the binary digits of 2 (so: [1,0]) โ€šร…โˆž # each by number given in arg 1 ยฌยข # and repeat this list infinitely; f # now use this to filter elements of ยทโˆยฃ # 1..arg 2 ``` [Answer] # Excel, 68 bytes ``` =LET(a,TOROW(SEQUENCE(,A1)+(A1+B1)*SEQUENCE(C1,,0)),FILTER(a,a<=C1)) ``` `k`, `j` and `listmax` in `A1`, `B1` and `C1` respectively. Outputs a horizontal array. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes ``` |,_-@%-$~+@ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq2t04nUdVHVV6rQdICJQiRXR5jomOsaGsVA-AA) Find all numbers \$n\$ from \$1\$ to \$m\$ such that \$(n-1) \bmod (k+j) < k\$. ``` |,_-@%-$~+@ | filter , range _ max number by the following value being strictly positive: - subtract @ k (number of elements to keep) % modulo - ~ subtract 1 from $ the element + add @ k (number of elements to keep) j (number of elements to drop) ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles) ``` +.`/+@$,_<@ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq7X1EvS1HVR04m0cICJQiRXR5jomOsaGsVA-AA) Different approach to [xigoi's Nibbles answer](https://codegolf.stackexchange.com/a/263316/95126), but still 5.5 bytes... ``` +.`/+@$,_<@ `/ # make chunks of size +@$ # sum of first two arguments ,_ # from the range 1..third argument . # then, for each chunk <@ # take first arg elements + # and flatten the list of chunks ``` [Answer] # JavaScript (ES6), 46 bytes Expects `(k)(j)(listmax)`. ``` k=>j=>g=m=>m--?m%(k+j)<k?[...g(m),m+1]:g(m):[] ``` [Try it online!](https://tio.run/##bU9dT4MwFH3nV9wsMWmz0q0FhkxhT/royx4ZD8gK8lGYwEyM8bfj7ZbNmRhoLpyPe06r9CMdsr48jHbb7dWUh1MdRlUYFaEOI23bG31H6nlFH@tNzDkviKZMz0WyNl/rOJl69X4se0Vm@TCjvFfp/rls1PazzciS8rHbjn3ZFoTy4dCUI5ntWpTlXf@UZm9kgDCCLwugUSPEUDOoGGhIIISB63REyWK3ny8Kin8H8nLUr6qnD2jIunboGsWbriA5qSmpKBZC6ptOAvARYNsRxIKBw8Bj4DMIGMKJJUE4IIIrLxFe4fEv1OovlVgCXHB/DUYsziZpRDgdk4PTxemuzCIXpLzdg/n36MEywsWDXeTyFLg0mbeBTmJ5IDzD3MBoRJ9nyqBe@ldOIOZjnCP@kZ/KYrSQN9ne5cJ4sJNEXCIuvfNdJOLS4EFiBQHge9mc/AA "JavaScript (Node.js) โ€šร„รฌ Try It Online") ### Commented ``` k => // 1st function taking k j => // 2nd function taking j g = m => // 3rd recursive function taking m m-- ? // if m is not 0 (decrement it afterwards): m % (k + j) < k ? // if m modulo (k + j) is less than k: [...g(m), m + 1] // append the result of a recursive call, // followed by m + 1 : // else: g(m) // just do a recursive call and append nothing : // else: [] // stop ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` โˆšโˆยทโˆรคโ€šร…โˆžยทโˆซรฉTโ€šร„โˆซ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLDuOG4iuKBsOG6jlTigLoiLCIiLCJbMywgMl1cbjYiXQ==) (or 5.5 bytes if you're using vyncode) ``` โˆšโˆยทโˆรค # Perform dyadic run length decoding - creates a list of # [[list_max] * k, [0] * j] โ€šร…โˆžยทโˆซรฉ # Slice to length list_max Tโ€šร„โˆซ # Truthy indices + 1 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~41~~ 37 bytes -4 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) ``` ->k,j,m{m.times{p _1+1if _1%(k+j)<k}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3VXXtsnWydHKrc_VKMnNTi6sLFOINtQ0z04CUqka2dpamTXZtLUTxSrdoQx0THRPLWAh_wQIIDQA) [Answer] # Minecraft Function, 307 bytes ``` scoreboard players operation r d = c d execute if score c d matches 0 run scoreboard players operation j d += k d scoreboard players operation r d %= j d scoreboard players add c d 1 execute if score r d < k d run tellraw @a {"score":{"name":"c","objective":"d"}} execute if score c d < m d run function a:b ``` Must be run as a function named `b` in a data pack named `a`. The function increments `c` in a loop while `c < m`. Each iteration, if `c % (k + j) < k`, it prints `c`. `k`, `j`, and `listmax` are input as scoreboard players `k`, `j`, and `m` for objective `d`. To set up the inputs, run the commands: ``` /scoreboard objectives add d dummy /scoreboard players set k d <value> /scoreboard players set j d <value> /scoreboard players set m d <value> ``` The above commands could be considered part of the program, but since they are necessary to provide input they have not been counted. [Answer] # Swift, 40 bytes ``` {k,j,l in(1...l).filter{($0-1)%(k+j)<k}} ``` [Try it on SwiftFiddle!](https://swiftfiddle.com/z5tfmrpklfa6jkrrjdyepnogje) [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 48 bytes ``` ![i](https://$ "read a character")![:](https://$ "Duplicate the top item on the stack")![i](https://$ "read a character")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![i](https://$ "read a character")![0](https://$ "Push the number (0-9)")![v](https://$ "Change Cursor Direction")![/](https://$ "Reflect the cursor direction") ![v](https://$ "Change Cursor Direction") ![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![>](https://$ "Change Cursor Direction")![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack")![@](https://$ "Move the top elemnt of the stack back 2")![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack")![@](https://$ "Move the top elemnt of the stack back 2")![(](https://$ "Greater than, less than. Push 1 or 0 to the stack.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![;](https://$ "Halt")![:](https://$ "Duplicate the top item on the stack")![r](https://$ "Reverse the stack")![:](https://$ "Duplicate the top item on the stack")![}](https://$ "Shifts the entire stack left or right")![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack")![}](https://$ "Shifts the entire stack left or right")![$](https://$ "Move the top element of the stack back 1")![r](https://$ "Reverse the stack")![$](https://$ "Move the top element of the stack back 1")![@](https://$ "Move the top elemnt of the stack back 2")![%](https://$ "Pop 2 values of the stack then perform the given operation.")![)](https://$ "Greater than, less than. Push 1 or 0 to the stack.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.") ![\](https://$ "Reflect the cursor direction")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![:](https://$ "Duplicate the top item on the stack")![n](https://$ "output a number in decimal")![a](https://$ "Push the hexadecimal (10-15)")![o](https://$ "output a character")![\](https://$ "Reflect the cursor direction") ``` Hover over any symbol to see what it does [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTppK2kwdi9cbnYgICAxKz4kOkAkOkAoPzs6cjp9JDp9JHIkQCUpP1xuXFwxKzpuYW9cXCIsImlucHV0IjoiNyA0IDMxIiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9) Unformatted version of code if above looks broken: ``` i:i+i0v/ v 1+>$:@$:@(?;:r:}$:}$r$@%)? \1+:nao\ ``` [![enter image description here](https://i.stack.imgur.com/NSmQ2.png)](https://i.stack.imgur.com/NSmQ2.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~15~~ 12 bytes ``` ร”ยบยฉโ€šรครฏโ€šรฅรฏร”ยบยฐโ€šร„ยถโ€šโ‰ รœยฌโ‰คโ€šโ‰ รœร”ยบร†ล’ฯ€ร”ยบร†0 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzMvuSg1NzWvJDVFwy0zL8UxJ0fDuTI5J9U5I79AI7gEqDLdN7FAw0hHAcHxzCsoLfErzU1KLdLQ1FHI1AQSKGJAvpKBkiYQWP//b6hgomBi@V@3LAcA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Would have been 1 fewer byte with 0-indexing. Explanation: Now a port of @lyxal's Vyxal answer. ``` ยฌโ‰ค Literal integer `2` โ€šโ‰ รœ Map over implicit range and join ร”ยบร† Next input โ€šโ‰ รœ Map over implicit range and join ล’ฯ€ Outer value โ€šร„ยถ Cyclically extended to length ร”ยบร† Third input as a number โ€šรฅรฏร”ยบยฐ Find all occurrences of 0 Literal string `0` โ€šรครฏ Vectorised increment ร”ยบยฉ Cast to string Implicitly print ``` [Answer] # [Arturo](https://arturo-lang.io), 31 bytes ``` $[k j l]->select l=>[k>%&-1k+j] ``` [Try it!](http://arturo-lang.io/playground?wlsAym) ``` $[k j l]-> ; a function taking three args select l=>[ ; select elts in [1..l], assign current elt to & k> ; is k greater than... %&-1 ; current elt minus one modulo... k+j ; k plus j? ] ; end select ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 43 bytes ``` ![i](https://. "read a character")![i](https://. "read a character")![:](https://. "Duplicate the top item on the stack")![i](https://. "read a character")![+](https://. "Pop 2 values of the stack then perform the given operation.")![0](https://. "Push the number (0-9)")![v](https://. "Change Cursor Direction")![1](https://. "Push the number (0-9)") ![)](https://. "Greater than, less than. Push 1 or 0 to the stack.")![r](https://. "Reverse the stack")![}](https://. "Shifts the entire stack left or right")![:](https://. "Duplicate the top item on the stack")![r](https://. "Reverse the stack")![:](https://. "Duplicate the top item on the stack")![<](https://. "Change Cursor Direction")![\](https://. "Reflect the cursor direction")![v](https://. "Change Cursor Direction")![?](https://. "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![)](https://. "Greater than, less than. Push 1 or 0 to the stack.")![%](https://. "Pop 2 values of the stack then perform the given operation.")![{](https://. "Shifts the entire stack left or right")![@](https://. "Move the top elemnt of the stack back 2")![:](https://. "Duplicate the top item on the stack")![&](https://. "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![@](https://. "Move the top elemnt of the stack back 2")![:](https://. "Duplicate the top item on the stack")![$](https://. "Move the top element of the stack back 1")![}](https://. "Shifts the entire stack left or right")![:](https://. "Duplicate the top item on the stack")![&](https://. "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![;](https://. "Halt")![?](https://. "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.") ![1](https://. "Push the number (0-9)")![+](https://. "Pop 2 values of the stack then perform the given operation.")![:](https://. "Duplicate the top item on the stack")![n](https://. "output a number in decimal")![a](https://. "Push the hexadecimal (10-15)")![o](https://. "output a character")![^](https://. "Change Cursor Direction")![+](https://. "Pop 2 values of the stack then perform the given operation.")![>](https://. "Change Cursor Direction") ``` Hover over any symbol to see what it does In plaintext: ``` ii:i+0v1 )r}:r:<\v?)%{@:&@:$}:&;? 1+:nao^+> ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaWk6aSswdjFcbilyfTpyOjxcXHY/KSV7QDomQDokfTomOz9cbjErOm5hb14rPiIsImlucHV0IjoiMzEgNyA0Iiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9) ![control flow](https://i.stack.imgur.com/8kUq8.png) [Answer] # [Desmos](https://desmos.com/calculator), 36 bytes ``` l=[1...m] f(k,j,m)=l[mod(l-1,k+j)<k] ``` Uses the same modulo trick that some other answers here have done to filter for the appropriate numbers. [Try It On Desmos!](https://www.desmos.com/calculator/wxkq6chrj0?nographpaper) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/gj59pizzxr?nographpaper) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LIยฌฯ€โ€“โˆยฌยฃล’ฯ€โ€“ฮฉร€รบ ``` Inputs as \$max, [k,j]\$. [Try it online](https://tio.run/##AR8A4P9vc2FiaWX//0xJwrnQuMKjzrnQvcuc//82ClszLDJd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/30iDq27sOPQ4nM7L@w9Pee/zv/oaDOdaGMdo9hYHYVoQ0OdaEMdQwjbUifaSMfQGMIxQ@KYWIJUmYDZRkYgCQjb0BisyADCMdCJNtUxNIWoMgebC9FuDLTEHKZFJ9rSUsfSMjY2FgA). Here an alternative 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach: ``` LDIโˆšร–ล’รฌยฌฯ€โ€šร รงโˆšรจ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fx8XzcOu5yYd2PuroPdz//78ZV7SxjlEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/31cIg63npt8aN2jjt7D/f8Pr9f5Hx1tphNtrGMUG6ujEG1oqBNtqGMIYVvqRBvpGBpDOGZIHBNLkCoTMNvICCQBYRsagxUZQDgGOtGmOoamEFXmYHMh2o2BlpjDtOhEW1rqWFrGxsYCAA). **Explanation:** ``` L # Push a list in the range [1, first (implicit) input `max`] I # Push the second input-pair [`k`,`j`] ยฌฯ€โ€“โˆ # Repeat it the first input amount of times as list ยฌยฃ # Split the first list into parts of those sizes, # containing empty trailing lists if it's out of bounds ล’ฯ€ # Uninterleave this list of lists into two parts โ€“ฮฉ # Pop and only keep the first part ร€รบ # Flatten it # (after which the result is output implicitly) ``` ``` L # Push a list in the range [1, first (implicit) input `max`] D # Duplicate this list I # Push the second input-pair [`k`,`j`] โˆšร–ล’รฌ # Pop the top two lists, and run-length decode it, # resulting in `k` amount of 1s followed by `j` amount of 2s ยฌฯ€โ€šร รง # Shorten/extend it to a length equal to the first input `max` โˆšรจ # Only leave the values in the ranged list at the truthy positions # (only 1 is truthy in 05AB1E) # (after which the result is output implicitly) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 71 bytes Output is an IntStream if that's acceptable. ``` (k,j,l)->java.util.stream.IntStream.range(1,l+1).filter(i->--i%(k+j)<k) ``` [Try it online!](https://tio.run/##fVLNjtowEL7vU4wsVXIUx8ImQNNtqTj2UPXQva32YIJBDiaksYOKqj321kdoX25fhE5@oCyEJrHsjGa@nxlnaqeibLE@FNXcmhRSq5yDz8rk8OPuDsDkXpdLlWqYYQDwybCCV95Y7nyp1YZ/yv3X5gRLiumwZnUVZO1mg3sse66xnFceKWZg4QMc6JplzAbR9DYgL1W@0lQwG4qAL41FLdRE0ygyb@g6zIL36@BwX0N36juG3dYsQO@UbfQUqlQb0appzvLsPGSAXCZfgf5e6NTrRdD57MKldpX1KNg1/2a5P8mjli/pEf2I3KIGjWsE2TuvN3xbeV5gubc5pUcirr9VyjraMgQfycvvn0DekZc/v4AEYRc@de@1xU5dj6j/zMcdvZXaV2V@NspZWaq9437b4lLHN6p42H6ZZ1RHU0JCHfBSL6pUU0IYVWyOg1PhPCSMBNwV1nhaH2/JbSaywVtFW4LHJ1Dl6qSnmRWAYPiKOsBwkUdsK85nxGDCIGEgxBMB6DrblUgmhkwk5yU4BDHGNbmVPb7Kvs4ULGZx8kpKjSlabFkX4j6sFeIe4x6P@/hiJiVc8KGbt4iD1kSMC53JQa/WAcq91Dq8zhwxgd/gIhPhEX3UZw2p5eQ8XfSkTVD7UEA/atMN9CHkmZHRsfG40KDEuMS4HLXNkhiXdTy5JksShp/4R3ZKwcv0fPgL "Java (JDK) โ€šร„รฌ Try It Online") --- If that's not acceptable, then here's a more classic solution with an array as output (**81 bytes**) : ``` (k,j,l)->{var r="";for(int i=0;i<l;)r+=i++%(k+j)<k?i+",":"";return r.split(",");} ``` [Try it online!](https://tio.run/##dVJLbtswEN3nFAMBASSIEUxasqsobuADdNVlkAVr0wEl@lOKMhoEXnbXI7SXy0Xcp5/r2KokgsLozfsMlcu9vMuXxXFXfTN6QQsjy5K@SL2ht5sbIr1xyq7kQtEcBcL11Vm9eXl6ppWPj1SwGkN5u5kgA@hQd5ZOOhDOydDs6BcsZya4@/y2l5bszPOy1dY2BHo2yvSDyQIbznQY3vpFmAcPxaMOPebdA2iVq@yGbFTujHY@qkF2OGa1Rme6k9pv9ZLUXpqGdyetXPPWVvMuzt7HrMtB6sdOLZxaBh/ikVVlZRzNKMeAosppE82tla9l5LYtxDfRyu9FeoGWPGimAK7X0ql1tK1ctEOLMxvf7/Ui9b2SpvRboeDRe//9k5D3/c8v8oKwK5@mOZB0jUPyT6ch7UvZZ2hmQMQZbl4XGJb3BJ/InTCaMkoZcf7sEXVWuxbB@Jjx9LwFqfgEa/o/9OQKfY3kLGZx@sFKzclbblE3Yh/XDrHH2OPJkF7MhKALPaT5BB5E4zEWkonRoNcR7F56HV8jE8bxjC6QoAd7MhQN0mJ6DucDsCm8jzkNszbTQA4uzoIk/eCxEFCgLlAXSTssgbqo6@m1WJoyPPyf2AmCn@lw/As "Java (JDK) โ€šร„รฌ Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 48 bytes ``` (k,j,l)=>for(i<-0 until l if i%(k+j)<k)yield i+1 ``` [Try it online!](https://tio.run/##dVLBboJAED2Xr5hLk924jewiUoyY9NhDT6Ynw4EKmoUtWlibmsZvpzOoSSMr2WGS2Xnz3hto15nJut1HWawtvGW6hl/P@84MVG2l9@UM2GttBVxfHJIF5rz4KfJl8bXCUgpJxypRCsOTxWbXMD1/8uFQW23AgN6AfmTVqOTzih91YXLQI9nlxQY@kY1lzbadwUvTZMfV0ja63qZ8Bu@1tpCgFMDnYY9la2p2lsSkADqSc4DxeHew@4NtAVZYDASEAiIBMTWk3i1UYRl7ZIzYGyhdTTGi@6jpHdQQgTcTPLFDInHIM5eiAZgDUo55QrCpkx@nKeWYpnq3zxeBE7KGRd/twac2t4dgiMBFSgrfiQh6TaHTOmlR0RAmHe1RPyeQbm8Xln5r2CnVP6Ph9YNh4AIUkdKawvNSFdYV1eMhaYxLopC3GlP84U7eqfsD) Same modulo trick. [Answer] # [Bash](https://www.gnu.org/software/bash/)+coreutils, 41 bytes ``` seq 1 $3|xargs -n$[$1+$2]|cut -d\ -f1-$1 ``` [Try it online!](https://tio.run/##Xc5NCgIxDAXgvad4iy4UKTRNndKzqIvxp7oSnCoI1rPXFIRpJVl95CU5jOla4nL1RknnOwiK82ucLgn6praK1sru8/H5gD7tAB1JKyqfRYQFI3jkKUnICLDQgAaoFjVQIxT@YegiDq6fcLC2AzIgnmEDkjbdWXnFz@BlB7d/hFCbflC@ "Bash โ€šร„รฌ Try It Online") ~~[59 bytes](https://tio.run/##Xc69DsIgEAfw3af4Dwxt0KQH2AYp8UGMgxKJpENjGbXPjjQxaTF30@8@77f4TL6q30jOMmn8OFVVsGRCb50J3DLiTNS5Hh8vsAB2GWzgjA60H3p3Hk7uauY07zwEJHSHzxRBaDLITC02QEvQBpYR0v/QFiMKquxQEKIAakByhSMoZ1Ocza90K3R5h9z@ofWS9IP0BQ "Bash โ€šร„รฌ Try It Online")~~: `c=$3;for((i=1;i<=c;i+=$1+$2)){ seq $i $[k=i+$1-1,k<c?k:c];}` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 46 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.75 bytes ``` โ€šร‡ร„fยทโˆซรฃfยทโˆซรฉTโ€šร„โˆซ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4oKAZuG6i2bhuo5U4oC6IiwiIiwiWzMsIDJdXG42XG4iXQ==) Vyncode!!! ## Explained ``` โ€šร‡ร„fยทโˆซรฃfยทโˆซรฉTโ€šร„โˆซยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  โ€šร‡ร„fยทโˆซรฃ # โ€šร„รฉโ€šร…ยฐA list of [[1] * k, [0] * j] f # โ€šร„รฉโ€šร…ยขflattened ยทโˆซรฉ # โ€šร„รฉโ€šร…ยฃwith the first listmax items taken, wrapping if needed Tโ€šร„โˆซ # โ€šร„รฉโ€šร…ยงtruthy indices + 1 ๏ฃฟรผรญรฉ ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Go](https://go.dev), 79 bytes ``` func(k,j,n int)(o[]int){for i:=0;i<n;i++{if i%(k+j)<k{o=append(o,i+1)}} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVLNSsNAEAaP-xRjQUjMVjOTTdKo9RX0XnIItZG1Nikh9VL6JF6K4EPp0_hta2tSZHcY-Ga-nyV5_3iut1_ny2I6L55ntChspexiWTft1aBctAP1VjRU0vhz1ZbD0ddDuaqm3ly_6Ips1fpePcldX5d1Q_ZmHN7au-rWBsHalmQvvHnw4t_N1_W4WC5n1ZNXaxuwv9moZtaummqzl_0-M0535-75tFbXl4oJh2k4vKcJa4o0xZpSTZkGnCshjoiz41wAJ6j0MEr6oxyChswfwS3zniRuCT1yPugG3SROyJBIVwf-I3AQhg0KWSTcGYbOs2sY5Somjt2kA4MIXuzCYF_S44yBpbCL-J_1XVhYs3S848ODUcgkwAW4xPu3CHBxeJarLCPcg3KuLq_VY4Ov9lp5pccah32_A4mGC2f_YEkPY220OV0zWuSUGYLcw2KN_ByeqMFB0h6WQi7qh8syjeuw359nu933Hw) Port of [@SanguineL's answer](https://codegolf.stackexchange.com/a/263314/77309). [Answer] # [Nim](https://nim-lang.org/), 60 bytes ``` proc r(k,j,m:int)= for n in 1..m: if(n-1)%%(j+k)<k:echo n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3bQqK8pMVijSydbJ0cq0y80o0bbkU0vKLFPIUMvMUDPX0cq24FBQy0zTydA01VVU1srSzNW2yrVKTM_IV8iBmrCzSMNcx0TE21ITwYWYDAA) ]
[Question] [ ![figure and ground](https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Cup_or_faces_paradox.svg/300px-Cup_or_faces_paradox.svg.png) Source: [Wikipedia](https://commons.wikimedia.org/wiki/File:Cup_or_faces_paradox.svg) For this challenge, you should write two programs which resemble the [figure and ground](https://en.wikipedia.org/wiki/Figure%E2%80%93ground_(perception)) of the above image, such that one of them prints `figure` and the other prints `ground`. Specifically: 1. Write a program which takes no input and prints the string `figure`. The only allowed [whitespace characters](https://en.wikipedia.org/wiki/Whitespace_character#Unicode) in your program are spaces (code point 0x20) and newlines (carriage returns, 0x0D, linefeeds, 0x0A, or a combination of both). 2. Ignoring the newlines, the number of space characters (code point 0x20) and non-space characters has to be the same. For example, this would be a valid program (in a hypothetical language): ``` ab c d e f ``` Note that there is a trailing space on the first line. 3. If you swap the **n**th space character with the **n**th non-whitespace character, the program should print `ground` instead. For the above example the program would look like this: ``` a b cde f ``` Note that there are trailing spaces on the second and third lines. Both the *figure* and the *ground* solutions should be full programs in the same language which print to STDOUT. You may print a single optional trailing newline in either case. You may output anything you want to STDERR, as long as STDOUT is correct. 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. ## Helper Script You can use [this CJam script](http://cjam.tryitonline.net/#code=cV9OLV8sXCcgZT0yKi1nW3tfTi1TLVx7TlMrI1t7Tn17KH17U31dPX5cfS99ezsiTm90IGVub3VnaCBzcGFjZXMhIn17OyJUb28gbWFueSBzcGFjZXMhIn1dPX4&input=YWIgYyAKICAgZgpkIGU) to convert between a *figure* and *ground* program. Simply paste one of the two into the *Input* field and run the program. It will also tell you if there the number of spaces and non-spaces doesn't match up. ## Leaderboard ``` function answersUrl(a){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"http://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&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(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.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(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery("<a>"+g+"</a>").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101275,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=8478,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:350px;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] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ### Figure ``` โ€œยฆฤ ศฎโ€œยฉแปฅdยป แน‚ ``` Nine trailing spaces. [Try it online!](http://jelly.tryitonline.net/#code=4oCcwqbEoMiu4oCcwqnhu6Vkwrsg4bmCICAgICAgICAg&input=) ### Ground ``` โ€œ ยฆฤ ศฎโ€œยฉแปฅdยปแน‚ ``` No trailing spaces. [Try it online!](http://jelly.tryitonline.net/#code=ICAgICAgICAg4oCcIMKmxKDIruKAnMKp4bulZMK74bmC&input=) ### How it works First, note that spaces aren't atoms, so the space characters outside the string literals do not affect the program in any way. The string literals use Jelly's built-in dictionary-based [string compression](https://codegolf.stackexchange.com/a/70932/12012) to produce the desired words. A compressed string literal begins with `โ€œ`, ends with `ยป`, and uses `โ€œ` internally to create an array of strings. In the **figure** program, `โ€œยฆฤ ศฎโ€œยฉแปฅdยป` yields the string pair **(โ€œfigureโ€, โ€œgroundโ€)**, and the atom `แน‚` selects the lexicographical minimum, i.e., **โ€œfigureโ€**. In the ground program, `โ€œ ยฆฤ ศฎโ€œยฉแปฅdยป` yields the string pair **(โ€œlogicallyAbacsโ€, โ€œgroundโ€)** instead. The lexicographical minimum is now **โ€œgroundโ€**, which `แน‚` selects dutifully. In both cases, the interpreter automatically prints the last return value โ€“ i.e., the selected minimum โ€“ to STDOUT. [Answer] # Python 2, 53 bytes Replace `ยท` with space in both answers: ``` ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท print'ยทยทยทยทยทยทfigureground'[6:12]# ``` Prints `figure`. ``` print'figureground'[ ยทยทยทยทยทยท6:12]#ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท ``` Prints `ground`. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes ### **Figure** ``` 'ล ร‚,'รญยถ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=ICfFoMOCLCfDrcK2ICAgICAg&input=) ### **Ground** ``` ' ล ร‚,'รญยถ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=JyAgICAgICDFoMOCLCfDrcK2&input=) Uses the **CP-1252** encoding. Note the trailing spaces. In the **Figure** program, it's a normal program without errors. It decompresses the following words: ``` 'ล ร‚ -> figure 'รญยถ -> ground ``` The comma prints pops and prints the `figure` word with a newline. Since something has been printed, the top of stack is not printed anymore. In the **Ground** program, there are some errors which is convenient in this case. The following part: ``` '<space> ``` pushes a space character on top of the stack. The `ล ` rotates the stack, which has an arity **3**. There is just one element on the stack and no input, so this gives an exception, clearing the stack. The `ร‚` bifurcates the top of the stack, but this has the same story as the rotate operator. So basically the `,` command prints nothing. That means that the program will still output the top of the stack which is `'รญยถ`. Resulting into `ground`. [Answer] # [Retina](http://github.com/mbuettner/retina), 31 bytes ### Figure: ``` | figure |ground ``` ### Ground: ``` |figure | ground ``` [Figure](http://retina.tryitonline.net/#code=fCAgICAgICAKZmlndXJlCiB8Z3JvdW5kCiAgICAgIA&input=) and [Ground](http://retina.tryitonline.net/#code=IHxmaWd1cmUKICAgICAgCnwgICAgICAgCmdyb3VuZA&input=). Both programs require that STDIN be left empty to be valid figure or ground programs. [Answer] # Pyth, 30 bytes ### Figure ``` "figure" "ground ``` 14 trailing spaces. [Test](https://pyth.herokuapp.com/?code=%22figure%22+%22ground++++++++++++++&debug=0) ### Ground No trailing spaces ``` " figure""ground ``` [Test](https://pyth.herokuapp.com/?code=++++++++%22+++++++figure%22%22ground&debug=0) ### How it works Rather helpfully, a space supresses printing in Pyth, while string literals with no closing `"` are implicitly closed. The first program therefore consists of two strings, `"figure"` and `"ground "`. The first string is implicitly printed, and the printing of the second is supressed, meaning that just `figure` is printed. The second program consists of two strings, `" figure"` and `"ground"`. The printing of the first is supressed, and the second is implicitly printed, meaning that just `ground` is printed. [Answer] # [MATL](http://github.com/lmendo/MATL), 37 bytes ### First program ``` 'figure' %x'ground' ``` Each line has 9 trailing spaces. [Try it online!](http://matl.tryitonline.net/#code=J2ZpZ3VyZScgICAgICAgICAKJXgnZ3JvdW5kJyAgICAgICAgIA&input=) ### Second program ``` 'figure'% x'ground' ``` There are no traling spaces here. [Try it online!](http://matl.tryitonline.net/#code=ICAgICAgICAnZmlndXJlJyUKICAgICAgICAgIHgnZ3JvdW5kJw&input=) ### Explanation Nothing terribly fancy... * Spaces and newlines between statements are ignored by MATL. * `%` is the comment symbol, which ignores the rest of the line. * `x` deletes the top of the stack. * The stack is implicitly printed at the end of the program. [Answer] ## Java, 180 bytes Replace `.` with space. Prints "figure": ``` class A{public static void main(String[]a){System.out.println( //"ground" // ..... ........ ...... .... ................................... .. ........ .......... .... "figure");}} ``` Prints "ground": ``` ..... ........ ...... .... ................................... .......... .. class A{public static void main(String[]a){System.out.println( // "ground" //"figure" );}} ............ ``` [Answer] ## Befunge, 54 bytes **Figure** ([Try it online!](http://befunge.tryitonline.net/#code=I3YgImVydWdpZiJ2ICAgICAgICAgID4KICAgICAgOiMsX0A-ICAgICAgICAgCiJkbnVvcmci&input=)) ``` #v "erugif"v > :#,_@> "dnuorg" ``` Ten trailing spaces on the second line. **Ground** ([Try it online!](http://befunge.tryitonline.net/#code=ICAjICAgICAgICAgdiJlcnVnaWYidiAKPjojLF9AICAgICAgPiJkbnVvcmciCiAgICAgICAg&input=)) ``` # v"erugif"v >:#,_@ >"dnuorg" ``` One trailing space on the first line and eight spaces on the third line. [Answer] # Mathematica, ~~50~~ 34 bytes Uses a REPL environment. (Adding a `Print[]` wrapper with an equal number of spaces would increase the byte count by 14.) The two programs are ``` 01figure+0 1ground ``` (with 16 trailing spaces) and ``` 0 1figure+01ground ``` The key here is that Mathematica treats digit concatentation without spaces as a single number, but intervening spaces are interpreted as neighborly multiplication, as is the concatenation of numbers and arbitrary variable names. So the first expression evaluates to `1*figure+0*1*ground`, which is `figure`; the second expression evaluates to `0*1*figure+1*ground`, which is `ground`. [Answer] # PHP, ~~44~~ 42 bytes figure: (16 trailing spaces, 5 spaces between figure & ;) ``` echo''?ground:figure ; ``` ground: (20 leading spaces) ``` echo' '?ground:figure; ``` Pretty simple really, works because `''` is falsey and `' '` is truthy. Use like: ``` php -r "echo''?ground:figure ; " php -r " echo' '?ground:figure;" ``` edit: 2 retrospectively obvious bytes saved thanks to Martin Ender [Answer] # Haskell, ~~96~~ ~~94~~ ~~88~~ ~~82~~ 77 bytes First program, prints `"figure"`: ``` main = putStr$idid"ground" idid _ ="figure" ``` Second program, prints `"ground"`: ``` main=putStr$id id"ground" idid _="figure" ``` Calls one of two differently named constant functions [Answer] ## Haskell, ~~88~~ 65 bytes ``` main=putStr ...........-- .."figure".......... --"ground"........ ``` and ``` ........... main=putStr.. --........"figure"-- .........."ground" ``` `.` indicates a space. Just some line comment (-> `--`) juggling. [Answer] ## Python 2, 52 bytes ``` ........................ print"figure" an d "ground" ``` `.`s indicate spaces. The last three lines are split up to error out without having a `SyntaxError` which would prevent the code from running in the first place. The ground version just uses `and` to make the second string be printed. --- Alternative (longer) attempts: ``` ....... print(#"ground")# "figure")................... print"figure"""and"ground" ............. ............. ``` [Answer] ## JavaScript (ES6), 56 bytes ``` alert('figure' //&&'ground' ) alert('figure'// &&'ground') ``` The figure has no trailing spaces. [Answer] ## [Rail](http://esolangs.org/wiki/Rail), 56 bytes **Figure** ``` $'main' -[figure]o - [ground]o ``` There are 16 trailing spaces on the second line. The program terminates with an error. [Try it online!](http://rail.tryitonline.net/#code=JCdtYWluJwogLVtmaWd1cmVdbyAgICAgICAgICAgICAgICAKLSAgICAgICAgICBbZ3JvdW5kXW8&input=) **Ground** ``` $ 'main'-[figure]o -[ground]o ``` There are 7 spaces on the first line and 9 trailing spaces on the last line. This program also terminates with an error. [Try it online!](http://rail.tryitonline.net/#code=ICAgICAgIAokICAgICAgICAgICdtYWluJy1bZmlndXJlXW8KIC1bZ3JvdW5kXW8gICAgICAgICA&input=) ### Explanation Rail looks for a line starting with (regex notation) `\$.*'main'` to find an entry point. The train (instruction pointer) then starts from the `$` moving south-east. Things that aren't reachable by the train can be ignored completely for the program. This includes anything on the same line as the entry point. Since, the `-` south-east of the `$` immediately turns the train east, both programs simply reduce to: ``` -[figure]o ``` ``` -[ground]o ``` `[...]` denotes a string literal and `o` prints it. Normally, you need a `#` to end the rail, but if you omit it, the program terminates anyway (but complains on STDERR that the train crashed). [Answer] ## [><>](http://esolangs.org/wiki/Fish), 39 bytes Using `ยท` to represent spaces. **Figure** ``` vยท "ยทdnuo eยท rยท uยท gยทยท iยทยท fยทยทยท "ยท >ยทoยท ``` [Try it online!](http://fish.tryitonline.net/#code=diAKIiBkbnVvCmUgCnIgCnUgCmcgIAppICAKZiAgIAoiIAo-IG8g&input=) **Ground** ``` ยทv ยท"ยทยทยทยท ยทd ยทn ยทu ยทoe ยทru ยทgif ยท" ยท>ยทo ``` [Try it online!](http://fish.tryitonline.net/#code=IHYKICIgICAgCiBkCiBuCiB1CiBvZQogcnUKIGdpZgogIgogPiBv&input=) Both programs terminate with an error. ### Explanation By writing the code vertically, I was able to reuse the `g` and the `r` between both solutions, as well as the quotes and the `>` and `o` for the output loop. In both cases, the only bit that gets executed is the column below the `v`, which pushes the letters of the required word onto the stack in reverse order. Then `>` redirects the instruction pointer to the right, where it loops through the `o`, printing the characters until the stack is empty. [Answer] ## [Fission](http://github.com/C0deH4cker/Fission), 37 bytes Using `ยท` to represent spaces. **Figure** ``` Dยท "ยทยทยท fยทยท iยทยท gยท uยท rยท eยทound "ยท ;ยท ``` [Try it online!](http://fission2.tryitonline.net/#code=RCAKIiAgIApmICAKaSAgCmcgCnUgCnIgCmUgb3VuZAoiIAo7IA&input=) **Ground** ``` ยทD ยท"fi ยทgu ยทre ยทo ยทu ยทn ยทdยทยทยทยท ยท" ยท; ``` [Try it online!](http://fission2.tryitonline.net/#code=IEQKICJmaQogZ3UKIHJlCiBvCiB1CiBuCiBkICAgIAogIgogOw&input=) ### Explanation Works basically the same as [my ><> answer](https://codegolf.stackexchange.com/a/101440/8478) (although I actually found this one first). The only differences are that `"` prints the characters immediately in Fission, which is why the words aren't written upside down and why we only need to terminate the program with `;` at the end. [Answer] # [Brian & Chuck](http://github.com/mbuettner/brian-chuck), ~~55~~ 53 bytes **Figure** ``` erugif?dnuorg }<.<.<.<.<.<. ``` There are 13 trailing spaces on each line. [Try it online!](http://brian-chuck.tryitonline.net/#code=ZXJ1Z2lmP2RudW9yZyAgICAgICAgICAgICAKfTwuPC48LjwuPC48LiAgICAgICAgICAgICA&input=) **Ground** ``` erugif?dnuorg }<.<.<.<.<.<. ``` [Try it online!](http://brian-chuck.tryitonline.net/#code=ICAgICAgICAgICAgIGVydWdpZj9kbnVvcmcKICAgICAgICAgICAgIH08LjwuPC48LjwuPC4&input=) ### Explanation Ah, it's been a while since the last time I used Brian & Chuck. As a short reminder, Brian and Chuck are two Brainfuck-like instances, which use each others' source code as their tape. Only Chuck can use the printing command `.`, `?` switches between the two instances conditionally, and `}` is sort of like `[>]` in Brainfuck. Unknown commands are simply ignored. Since the spaces at the beginning of the programs are ignored, the two programs are almost identical. The only difference comes from the fact that after the switching command `?`, the instruction pointer moves *before* executing the next command. Hence, the first command on Chuck's tape is always skipped. So the only real difference is that the ground program executes the `}` whereas the figure program doesn't. So here is how the code works: ``` ? Switch control to Chuck. } GROUND PROGRAM ONLY: Move the tape head on Brian to the end of the tape. <. Move the tape head left and print the character there. ... Do the same another five times to print the remainder of the string. ``` [Answer] # reticular, 46 bytes ``` "ground""figure"" "?$$o; ``` [Try it online!](http://reticular.tryitonline.net/#code=ICAgICAgICAgICAgICAgICAgICAgICJncm91bmQiImZpZ3VyZSIiICI_JCRvOw&input=) This prints `ground`. ``` "ground""figure"""?$$o ; ``` [Try it online!](http://reticular.tryitonline.net/#code=Imdyb3VuZCIiZmlndXJlIiIiPyQkbyAgICAgICAgICAgICAgICAgOyAgICAgIA&input=) This prints `figure`. ## ground Relevant code: ``` "ground""figure"" "?$$o; ................ push these two strings " "?$ pop " " off (since " " is truthy, `?` executes `$`) $ pop TOS ("figure") o; output and terminate ``` ## figure Relevant code: ``` "ground""figure"""?$$o; ................ push these two strings ""?$ doesn't activate $ pop "" o; output and terminate ``` [Answer] # WinDbg, 74 bytes ### Ground ``` ea2000000" groundfigure";;;da 2000006 L6 ``` ### Figure ``` ea2000000"groundfigure ";;;da 2000006 L6 ``` Figure has 2 trailing spaces. I feel like at least 2 or 4 bytes ought to be golfable... It works by writing a string to memory and showing 6 chars from it. The chars in the string are re-arranged so the shown chars change between the programs: ``` * Ground: ea 2000000 " groundfigure"; * Write string " groundfigure" starting at 2000000 ; * No-op ; * No-op da 2000006 L6 * Print 6 ascii chars, from 2000006, ie- ground * Figure: ea 2000000 "groundfigure "; * Write string "groundfigure " to memory ; * No-op ; * No-op da 2000006 L6 * Print 6 ascii chars, ie- figure ``` Output: ``` 0:000> ea2000000" groundfigure";;;da 2000006 L6 02000006 "ground" 0:000> ea2000000"groundfigure ";;;da 2000006 L6 02000006 "figure" ``` ]
[Question] [ #### The Collatz Conjecture The famous [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) (which we will assume to be true for the challenge) defines a sequence for each natural number, and hypothesizes that every such sequence will ultimately reach 1. For a given starting number N, the following rules are repeatedly applied until the result is 1: While N > 1: * If N is even, divide by 2 * If N is odd, multiply by 3 and add 1 ### Collatz Encoding For this challenge, I have defined the **Collatz encoding** of a number, such that the algorithm specified in the conjecture may be used to map it to another *unique* number. To do this, you start with a 1 and at each step of the algorithm, if you divide by 2 then append a `0`, otherwise append a `1`. This string of digits is the binary representation of the encoding. As an example we will compute the Collatz Encoding of the number 3, with the appended digits marked. The sequence for 3 goes (1) 3 ->1 10 ->0 5 ->1 16 ->0 8 ->0 4 ->0 2 ->0 1. Therefore, our encoding is `208` (11010000 in binary). ### The Challenge Your challenge is to write a function or program which takes an integer (**n>0**) as input, and returns its Collatz encoding. This is a code golf challenge, so your goal is to minimize the number of bytes in your answer. * For the edge case n=1, your solution should return `1`, because no iterations are computed and every encoding starts with a `1`. * Floating point inaccuracies in larger results are acceptable if your language cannot handle such numbers accurately (encodings on the order of 10^40 as low as 27) ### Test Cases I have written a reference implementation ([Try It Online!](https://tio.run/##fVBda8JAEHzvrxgOhLs2qJdAH0Kvf6QUiWajW8JeOE@Ktf72mA8/0AfnYWFnZwZ2mn3ceMnatqQKK1/XRfxbkKx8SVpM/oIOw8qyhsOXsup7IH83XBMEn7CjqgdXHTNBCucwv9E9BDOH9I665E6LpiEptZorcxVQvaXHBIfsVfAG@zzGnmOGsWQpwn6xjWH8QKnpj2fRF9coDRR3QcAS9Z0hQWraygdwd0MoZE3aJrDv52qa0FsqdeA8O@Ifh4cK2eQfR2XaEw)) which generates the encodings of the first 15 natural numbers: ``` 1 | 1 2 | 2 3 | 208 4 | 4 5 | 48 6 | 336 7 | 108816 8 | 8 9 | 829712 10 | 80 11 | 26896 12 | 592 13 | 784 14 | 174352 15 | 218128 ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` f=lambda n,x=1:1/n*x or f(n/2-n%2*~n,x-n%2*~x<<1) ``` [Try it online!](https://tio.run/##JY3NbsJADITveQpfKnZRgHjzt0Hss1RBbUokcFZhEalU9dXTcTnN2J89E7/TZRK3rkO49rfzR0@SL4GPfJDtQtNMg5GD28mb2/6CvMxyOrFdB1ChUWju5evTcE7c2GOGTcxpeqRIgW59NKOkHDfPd4BHMnZ/j9cxmQ390MbajOKMC/QAWwrh/3UlYnDOiBzUQUvVwsNVcBW0VtVFA1OWDVyrT4X3rIPHoLhTdV3LiOFChwJG813jO1yydtSdYm1pPdJZW7itylrXWuXYs/N/ "Python 2 โ€šร„รฌ Try It Online") ### Explanation Notice the following: if `n` is odd, `3*n+1` must be even. This means that in the odd case, we can combine two steps into one, with `(3*n+1)/2`. Although it seems more complicated, the formula actually becomes much shorter: ``` [n/2,(3*n+1)/2][n%2] [n/2,n+n/2+1][n%2] n/2+[0,n+1][n%2] n/2+n%2*(n+1) n/2+n%2*-~n n/2-n%2*~n ``` Then, to calculate the Collatz encoding, we'll append `[0]` if `n` is even, and `[1, 0]` if `n` is odd. Working on integers, we see that `x` becomes `[x*2,x*4+2][n%2]`. This can be further reduced to `x-n%2*~x<<1` (proof is left as an exercise to the reader). # [Python 2](https://docs.python.org/2/), 50 bytes ``` f=lambda n,x=1:1/n*x or f(n/2-n%2*~n<<n%2,x*2+n%2) ``` [Try it online!](https://tio.run/##HY3NTsQwDITvfQpf0CYlsLX7l642z4KKoEul3TQqWVEkxKuXMadv7LFn0nf@WKLs@xSu4@31baTotsAnPsZyo2WlycSjPMUHKX/j@Qy6rZRH0O4T7EhzpHWMl3fDjrizpwKb5Gi550SBbmMyc8wON18vMO7Z2OfPdJ2zOdAPHawtKK24QBFsSyH8v@5EDJ8LIgEFrJWVh2qgGrBV6qKDqOsOqtenynvWwWNQe1DK0DNiuNKhgtB86fyAS9aOdlBbW3qPdNYW7pu61bVWCXsW/wc "Python 2 โ€šร„รฌ Try It Online") The "obvious" method to compute the next term would be `[n/2,3*n+1][n%2]`, but we can do better with a little bit magic: `n/2-n%2*~n<<n%2`. It can be derived by working backwards: ``` [n/2,3*n+1][n%2] [n/2,(3*n+1)/2][n%2]<<n%2 n/2+[0,n+1][n%2]<<n%2 n/2+n%2*(n+1)<<n%2 n/2+n%2*-~n<<n%2 n/2-n%2*~n<<n%2 ``` [Answer] # JavaScript (ES6), 41 bytes ``` f=(n,o=1)=>n>1?f(n&1?n*3+1:n/2,2*o|n&1):o ``` [Try it online!](https://tio.run/##DYyxDoJAEAV7vmIrc8uBZDE24MG3EOCMhrwlQGyUbz@3mskU8x4@wz5ur/UoodOcUgwOhQbh0KGTPjpcpEd@89Kgqos6158VbjRF3RwokLQEehjvJt4zfTOiUbHrMl8XfdqPbMOcnekP "JavaScript (Node.js) โ€šร„รฌ Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input o = 1 // o = output, initialized to 1 ) => // n > 1 ? // if n is still greater than 1: f( // do a recursive call: n & 1 ? // if n is odd: n * 3 + 1 // use 3n + 1 : // else: n / 2, // use n / 2 2 * o | n & 1 // append the parity bit of n to the output ) // end of recursive call : // else: o // we're done: return the output ``` [Answer] # FRACTRAN, 11 fractions (72 bytes) and reversible $$\frac{7}{13},\frac{11}{17},\frac{247}{35},\frac{338}{441},\frac{104}{21},\frac{425}{209},\frac{153}{44},\frac{85}{49},\frac{169}{22},\frac{17}{7},\frac{195}{11}$$ The input is \$11\cdot 2^{n-1}\$ and the output is \$11\cdot 5^{k-1}\$ where \$k\$ is the Collatz encoding of \$n\$. (Note: it doesn't halt there. It will go on to generate all the other redundant encodings of this technically multivalued function, for every number of \$4,2,1\$ cycles.) If you replace all the instructions with their reciprocals and give it \$11\cdot 5^{k-1}\$ as input, it will compute \$11\cdot 2^{n-1}\$. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 55 bytes ``` f=lambda n,e=1:e*(n<2)or f(n*3//(6-5*(c:=n%2))+c,2*e+c) ``` [Try it online!](https://tio.run/##DcrRCsIgFADQ977iMgjudcbS1QiZ/YuZlrDuRPYSa99uO88nf5f3zP0tl1qjndzn8XTAMlhlgkAeNc0FIrLouw6H01WgN5aPmqj1UovQeqpxLwkSQ3H8CqikGsgcYJdL4gVjsyZz7zf4wRoxkRkv5w0aqn8 "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") This one uses an extra byte to do integer division since otherwise the answers accrue floating point innacuracy. I decided to submit the one with the extra `/` because Python can handle arbitrarily large integers according to your memory. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 31 bytes ``` 2/1 :':2!(1<){(-2!x;1+3*x)2!x}\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJwtzDsOwjAURNE+qxhXSYhQPM+/sWEpdCipKSgsobB2UtDd5ty92Uq0sZmbeJ8/09Vcv3EJlz6fdTyGYeuv7fluhMG8EBGFEDLoJWYIslpokIdl1YxUDUURLDGkE1E0/TfffeTimH5Y7Br3) [Answer] # x86 32-bit machine code, 20 bytes ``` 41 D1 E9 73 0A 6B C9 06 83 C1 04 0F 29 C0 F9 D1 D0 E2 ED C3 ``` [Try it online!](https://tio.run/##XVFNT8MwDD3Hv8IUTUr2pbEhDhvjgsSNCyckhqY0TdugLJ2aFDJN/HWKuzIh8MFx3vPHk632@0mhVNteGqdsk2m89SEz1bS8gz@QNel/rDau6DDQMejaYXKf4HG7lYGYtAl6u@U8lz4oaa0QaFzAnHdeihW@VyZDz8XqE6TfIcenhMO0sFUqLebgl4wmoVYRmC/rLhjjFbA3AiUws2tsj90Ak1nWx9fApukhaJzF2QPkS@abFLUkhhz1CQrkktXK9iC1s1W1Rw@s1gFEgmIF0AncSeN6pXWhxqhKWeNwSJ93AUdAso6MuMbZGA/dszqhH6WxGvloFPF2jYu5OKGd7WlZIefJwODkDgdm45IxkoacRyH64nPKxj1KVRqnUVWZXiY/dPwdk1V4PGfjYDZ/pl6HNeeN86ZwOjsJHgovXuJo9EorPgs74AU1ifeLfyORk65uc170wn54WktDh6Wxn9C2Xyq3svDtZLeYk6Ozralc228 "C++ (gcc) โ€šร„รฌ Try It Online") Uses the `fastcall` calling convention โ€šร„รฌ argument in ECX, result in EAX. In assembly: ``` s: inc ecx # Add 1 to restore the value of ECX. shr ecx, 1 # Shift ECX right by 1; the low bit goes into CF. jnc a # Jump if CF=0 (the number was even). imul ecx, 6 # Multiply ECX by 6. add ecx, 4 # Add 4 to ECX, producing 3n+1 where n is the original value .byte 0x0F # Effectively skip an instruction by making it part of a harmless "movaps xmm0, xmm0". f: sub eax, eax # (Start here.) Set EAX to 0. stc # Set CF to 1. a: rcl eax, 1 # Append CF to the bits of EAX. loop s # Subtract 1 from ECX and jump if it's nonzero. ret # Return. ``` [Answer] # [Haskell](https://www.haskell.org), ~~55~~ ~~53~~ 49 bytes *-2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334)* ``` a?n|n<2=a|p<-mod n 2=(2*a+p)?(6^p*n`div`2+p) (1?) ``` The solution is the anonymous function `(1?)`. [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN80T7fNq8myMbBNr8lNSFPJsNYy0ErUNNe01jLXygHRNio0uUMQ2xT4ls0whT8GIK9VWw9BeE6J9T25iZp6CrUJBUWZeiYJGbmKBQqpCtKGenqFBLFQJzCYA) ### Explanation Port of my BQN solution, essentially. We define an infix function `?` that takes an accumulator `a` and a number `n`: ``` a ? n ``` When `n` is 1, just return the accumulator: ``` | n < 2 = a ``` Otherwise, calculate `n` mod 2 and assign to `p` (for "parity"): ``` | p <- mod n 2 ``` Compute the new accumulator and number, and recurse: ``` = (2 * a + p) ? (6 ^ p * n `div` 2 + p) ``` The new accumulator is simply twice the current accumulator plus the parity (`2 * a + p`). The Collatz function calculation is a little more involved: ``` 6^p*n`div`2+p 6^p 6 to the power of the parity (1 if even, 6 if odd) *n Times n (n if even, 6*n if odd) `div`2 Int-divided by 2 (n `div` 2 if even, 3*n if odd) +p Plus the parity (n `div` 2 if even, 3*n+1 if odd) ``` Then our solution is simply `?` with a first argument (initial accumulator value) of 1. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~27~~ 26 bytes ``` Wa>1Io.:Y%aa:6Ey*a/2+y;FBo ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuha7whPtDD3z9awiVRMTrcxcK7US9Y20K63dnPIhCqDqFkebx0KZAA) ### Explanation ``` Wa>1Io.:Y%aa:6Ey*a/2+y;FBo a is first cmdline input; o is 1 (implicit) W While a>1 a is greater than 1: %a Parity of a (0 if even, 1 if odd) Y Yank into y variable o.: Concatenate to o in-place I If new value of o is truthy (which is always the case): 6Ey 6 to the power of y (1 if a is even, 6 if odd) *a Times a /2 Divided by 2 (a/2 if even, 3*a if odd) +y Plus y (a/2 if even, 3*a+1 if odd) a: Assign that result back to a ; (Needed for parsing) FBo Convert the final value of o from binary Autoprint ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` e;f(n){for(e=1;~-n;n=n%2?++e,3*n+1:n/2)e+=e;n=e;} ``` [Try it online!](https://tio.run/##XZDRToMwFIbv9xQnJEvKKNlaBhQremF8CreLpTtMonYLJZG44KOLB4Zkk6SF/uc/Xzm/CQ/GdB3qgln/XBwrhrnQ36HVNrdz@RgEyKOFDcSdXUofgxypgLrtSlvDx660zIfzDOjphRpd7V62kMNZcJAcIg5rDjGHhEPKQXHIOIgVLaoLMghyCLKIuNUTBpsTmhr31yS5UgNrTa8oSnqKUiIZmEpmaQ9TBJaJykiNMzqnqien6yjuAUIJqcZbzNG6GszrrlrQjuYNq8tl3qZ5lpsme6IVexyuz5E3dlNMwPofLe0eG2pb6fHzHlz5hceC/Y3gL0dhMSkagmBw@wPskt6UINEuKQ6Wrb6pOqoWrPZvVSR1iux/26kiS8G8@R7CB6B97jaWBqs5OD7N7vIctyO2nbXdjynedwfXhZ@/ "C (gcc) โ€šร„รฌ Try It Online") Inputs an integer. Returns its Collatz encoding. [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` ยทโˆรฃ:1m%2โ€šรœรซโ€šรœรชยฌยฐ?oโ€šรœรญ*3ยฌฮฉ%2 ``` [Try it online!](https://tio.run/##ASwA0/9odXNr/23igoHhuKMxNf/huIs6MW0lMuKGkeKGkMKhP2/ihpIqM8K9JTL//w "Husk โ€šร„รฌ Try It Online") Should be golfable. Ties `ยทโˆรฃ:1hm%2Uยฌยฐ?oโ€šรœรญ*3ยฌฮฉ%2` courtesy of @Razetime. ``` ยฌยฐ Infinitely iterate on the argument: ? %2 if even, ยฌฮฉ halve, else oโ€šรœรญ*3 3n+1. โ€šรœรซโ€šรœรช Take while != 1, m%2 map mod 2, :1 prepend 1, ยทโˆรฃ convert from binary. ``` Only reason I thought to use Husk for this is this *almost* works: # [Husk](https://github.com/barbuz/Husk), 19 bytes ``` ยทโˆรฃ:1โ€šรœรฎtยทโˆรฃโ€šร‡ยจล’ยฃยฌยฐยทฯ€ร…ยฌรŸeDo/3โ€šรœรช;1 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxYam/x/u6LYyfNQ2pQTIeNS05tziQwsf7mw8tDzVJV/f@FHbBGvD//8B "Husk โ€šร„รฌ Try It Online") Unfortunately manages to give 3840 instead of 829712 for 9, by virtue of not actually caring about the paths deterministically chosen (takes 28 to 85 as well as 14). ``` ยฌยฐ Infinitely iterate ;1 starting from [1] ยทฯ€ร… concat-map ยฌรŸe \n -> [ , ] D 2*n o/3โ€šรœรช n-1/3 , ล’ยฃ concatenate the iterations, โ€šร‡ยจ find the first 1-index of the input in them, ยทโˆรฃ convert to binary, t remove the leading 1, โ€šรœรฎ reverse, :1 put the leading 1 back, ยทโˆรฃ and convert from binary. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~53~~ ~~52~~ ~~48~~ 46 bytes ``` *|{$[1=n:*x;:x;*p;1+3*n;-2!n],2/|p:2 0!'x}/|1, ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs9KqqVaJNrTNs9KqsLaqsNYqsDbUNtbKs9Y1UsyL1THSrymwMlIwUFSvqNWvMdTh4srTUU9z0LfKszLUVjQ14AIASPYQlQ==) Pretty straightforward stab at this. Recurse with accumulator carrying both the number and the encoding. -1 found a byte by using encode -4 trying to remember lessons coltim passed on. (use tacit) -2 donโ€šร„รดt need list syntax [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 50 bytes ``` f=lambda n,x=0:4//n*x/2or f(1-6*n//(l:=n^-n),~x*l) ``` [Try it online!](https://tio.run/##HU3RboMwEHvnK@6tCaJLLoEQkPIrk5g2NiR6RDSVmFT119ndnuyzfXb@LT8b@Zj385zTOt0@Pieg5kh2bI2h@jBu22FWeA01GaPWMdH7lXTzOupVnzObBAvBPtH3l8IGMOixYiU3sD1KhgS3KauFSiPioyj9ds/rUtQFnnDRuoK8swtq5lDWkNL/nz4BkBNYAThGx@gFbWTWMmsZO0ERAhPvA7NenmyMKEfkQ@xB0A09cg1aOSwT6XchDpxE2egGsWWlj9yOsoJ96zuRZcphRBf/AA "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") Returns a float (+1 byte for int). Test harness from @dingledooper or whoever they nicked it from ;-) How? Straight-forward recursion with one twist: Group n steps down, 1 step up into one iteration. This avoids branching at the expense of a slightly more complicated body. Detail: Recall that `n^-n` clears the lowest set bit in `n` and sets all above including the sign bit, so this is effectively the same as `-2 * (n&-n)` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~72~~ 68 bytes ``` .+ $*1;1 {+`^(1+)\1;(1+) $1;$2$2 ^1;(1+) $.1 (1+);(1+) 1$1$1$1;1$2$2 ``` [Try it online!](https://tio.run/##K0otycxL/K@nzaWixWXIZaiScGgbl3uCHpeqhm@CIUTc0NqQq1o7IU7DUFszxtAaRHGpGFqrGKkYccXB@HqGXCAGhGeoAobWhiA1//8bmgIA "Retina 0.8.2 โ€šร„รฌ Try It Online") Link is to test suite that computes the results from `1` to `n`. Explanation: ``` .+ $*1;1 ``` Convert `n` to unary and pair it with an initial output value of `1`. ``` {` ``` Repeat while the input is paired. ``` +`^(1+)\1;(1+) $1;$2$2 ``` While `n` is even, halve it and double the output value. ``` ^1;(1+) $.1 ``` If `n` is `1`, then delete it and convert the output to decimal. ``` (1+);(1+) 1$1$1$1;1$2$2 ``` Otherwise, triple `n`, double the output, and increment both of them. After porting to [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1, it's possible to golf the answer down to 53 bytes, but for some reason it becomes inordinately slow: ``` .+ _;$&* +`(_+);(_+)\2(_?) $1$1$3;$2$.3*$(4*_5*$2 \G_ ``` [Try it online!](https://tio.run/##FcQ7CoAwEAXA/p1jlXwguJsoQgrLXCKwsbCwsRDvH5WBuY/nvHbugymtBw/NNDr4ZtTb/FfF6GZB/ImZhEJ0ZJLT2ZGgFu2dIYhImLFgBU9gAccX "Retina โ€šร„รฌ Try It Online") Link includes faster test cases. Explanation: ``` .+ _;$&* ``` Convert `n` to unary and pair an initial output value of `1` with it. ``` +`(_+);(_+)\2(_?) $1$1$3;$2$.3*$(4*_5*$2 ``` While `n` is greater than `1`, perform a Collatz step on it, updating the output value appropriately. Here `$1` is the previous output value, `$2` is `n//2` (integer division) and `$3` is `n%2`, thus `n` is replaced by `n//2+n%2*(n//2*5+4)` which computes equal to `n*3+1` when `n` is odd. ``` \G_ ``` Convert the output value to decimal and delete `n`. [Answer] # [Haskell](https://www.haskell.org), 107 bytes ``` s d 0=0 s(a:q)n=a*2^n+(s q$n-1) f n|n<2=[]|even n=0:f(div n 2)|1>0=1:f(n*3+1) r 1=1 r n=s(1:f n)$length$f n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCoMwFET3OcVfuEgUIdFNkf5epLQQMFbRjtVYV96kGzelt-g9epsGxFkMw2Ng5vWprW9d163r-zlV6eHXeipJsxZe2mJQYBtnVyTS0xAhNUpUhAXHjM-Xxc0OBNZFJctmJlCmFnPSbAJAnCehPZJhExzsZcAEFXUOt6mOQt4mv3fbgMueBO16jA0mkiPlSmyl_d8f) I am new to Haskell golf, so I apologize for any bits of this that are outrageously ungolfed. [Answer] # [Factor](https://factorcode.org/) + `math.extras project-euler.014`, 59 bytes ``` [ collatz [ < ] monotonic-count rest 1 prefix 48 v+n bin> ] ``` [Try it online!](https://tio.run/##JYwxD4IwFIR3fsXtCrEJJkaNq3FxMU6EoTQPxUBbXx8E/fMVZLlc7vJ9tTbiON5vl@t5D8/uRUZS6lvibKNydFqe/8hoFNYBgd49WUNhWb3mQLz0gWZXmCwk8vHcWFkO1vYxAYckUVsUal2VsYBxbavliwJHlOicdeJsY1Lj@oljCgI1q@pmRL7DsLKoGntCGTvtkcUf "Factor โ€šร„รฌ Try It Online") There is no way Factor would be competitive using the mathy recursive algorithm. Too many symbols means too much whitespace. So we take advantage of the fact that Factor has a built-in collatz sequence word and a simple way to detect increases in a sequence. ## Explanation ``` ! 3 collatz ! { 3 10 5 16 8 4 2 1 } [ < ] monotonic-count ! { 0 1 0 1 0 0 0 0 } (did it increase? then 1) rest 1 prefix ! { 1 1 0 1 0 0 0 0 } (change first element to 1) 48 v+n ! { 49 49 48 49 48 48 48 48 } (add 48 [equivalent to "11010000"]) bin> ! 208 (convert from binary) ``` [Answer] # [Re:direction](https://esolangs.org/wiki/Re:direction), ~~42~~ 38 bytes ``` ++v v> < +>+ >v +> > v +> >> > >v + >> ``` [Try it online!](https://tio.run/##K0rVTcksSk0uyczP@/9fW7uMq8yOy4ZL206by64MSCnYcUEoOy4gAWQCWf//mwMA "Re:direction โ€šร„รฌ Try It Online") The following notation will be used for the contents of the queue: a number means that many `โ€šรฑโˆซ`s, and `|` means one `โ€šรฑยบ`. If the input number is N, the initial queue is `N|`, but for the purpose of this program, it's better to view it as `N|0`. This program works through the Collatz iterations, while having the second number be 1 less than a number containing the result bits. It does two iterations at a time for odd numbers greater than 1. The possibilities are as shown: [![Execution path for 1](https://i.stack.imgur.com/NVUwG.png)](https://i.stack.imgur.com/NVUwG.png) [![Execution path for 2N](https://i.stack.imgur.com/jYwu5.png)](https://i.stack.imgur.com/jYwu5.png) [![Execution path for 2N+1](https://i.stack.imgur.com/399Jy.png)](https://i.stack.imgur.com/399Jy.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ร”ยบร†ล’โˆโ€šรครปล“ร–ยฌฯ€ร”ยบโˆ‘โ€šรครฑล’โˆโ€šรขรฎโ€šรฉรกโ€šรœยฎโ€šร…โˆžโ€šรครปร”ยบร˜ล“ร–ร”ฯ€โ„ขล’โˆยฌโ‰คโ€šรครฏโˆšรณยฌโ‰ฅล’โˆโˆšโˆ‘ล’โˆยฌโ‰คล’โˆร”ยบยฉโ€šรœยฎยฌโ‰คล“ร– ``` [Try it online!](https://tio.run/##RY67DsIwDEV3vsKjIwUJyoQ6AV068Bj6A6G1aKQ0aZ2kiK8PqYrEZtnnHt@2V9w6ZVKq7RjDLQ5PYpxEuXlE32OUsM/zu9eGACtqmQaygbqMCDh5r18WG2Kr@INn5Ql3EpbkfSRWwfFiuLouGoeThEIIIaG2f02jB/J4kDCtl1DpWXf0g5d1bsLaBrwoH9YXhYSYRWVKx7SdzRc "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` ร”ยบร†ล’โˆ ``` Input `n`. ``` โ€šรครปล“ร–ยฌฯ€ ``` Start with a Collatz encoding of `1`. ``` ร”ยบโˆ‘โ€šรครฑล’โˆ ``` Repeat until `n=1`. ``` โ€šรขรฎโ€šรฉรกโ€šรœยฎโ€šร…โˆžโ€šรครปร”ยบร˜ล“ร–ร”ฯ€โ„ขล’โˆยฌโ‰คโ€šรครฏโˆšรณยฌโ‰ฅล’โˆโˆšโˆ‘ล’โˆยฌโ‰คล’โˆ ``` Save `n%2` to the encoded value, and switch on that to halve or increment and triple `n` as appropriate. (Note that in order to avoid floating-point inaccuracy, I've used an integer halve, which is a byte longer than a floating-point halve.) ``` ร”ยบยฉโ€šรœยฎยฌโ‰คล“ร– ``` Output the encoded value converted from base 2. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` โˆšรณ3โ€šร„รฒ$Hยทโˆร‡?โ€šร„รดโˆšรชยฌรธยทโˆร‡ยทฯ€รด-ยทโˆร‘ ``` [Try it online!](https://tio.run/##y0rNyan8///wdONHDTNUPB7uaLJ/1DDz8IRD@4HMhztn6j7c0fLf@nC7pvv//4amAA "Jelly โ€šร„รฌ Try It Online") ## How it works ``` โˆšรณ3โ€šร„รฒ$Hยทโˆร‡?โ€šร„รดโˆšรชยฌรธยทโˆร‡ยทฯ€รด-ยทโˆร‘ - Main link. Takes n on the left โˆšรชยฌรธ - While loop, collecting each iteration i: โ€šร„รด - Condition: i > 1 ? - Body: If: ยทโˆร‡ - Condition: Bit; i % 2 $ - True: โˆšรณ3 - 3i โ€šร„รฒ - 3i+1 H - False: Halve ยทโˆร‡ - Bit of each i ยทฯ€รด- - Rotate the final 1 to the front ยทโˆร‘ - Convert from binary ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~36~~ 31 bytes *-5 bytes inspired by [ovs](https://codegolf.stackexchange.com/users/64121/ovs)* ``` 1โ€šรคโˆ{a๏ฃฟรนรฏรค1:a;(p+2โˆšรณ๏ฃฟรนรฏยฎ)๏ฃฟรนรฏรคp+๏ฃฟรนรฏยฉโˆšโˆ‘2โˆšโˆ‘6โ€šรฃรœpโ€šรœรช2|๏ฃฟรนรฏยฉ} ``` Anonymous function that takes an integer and returns its Collatz encoding. [Try it at BQN online](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKKuHth8J2VijE6YTsocCsyw5fwnZWoKfCdlYpwK/CdlanDtzLDtzbii4Zw4oaQMnzwnZWpfQoKRsKoIDEr4oaVMTU=) ### Explanation ``` 1โ€šรคโˆ{a๏ฃฟรนรฏรค1:a;(p+2โˆšรณ๏ฃฟรนรฏยฎ)๏ฃฟรนรฏรคp+๏ฃฟรนรฏยฉโˆšโˆ‘2โˆšโˆ‘6โ€šรฃรœpโ€šรœรช2|๏ฃฟรนรฏยฉ} { } Function of two arguments (right argument is the number, left argument calculates the answer): a๏ฃฟรนรฏรค1: Given left argument a and right argument 1, a return a ; Otherwise, ๏ฃฟรนรฏรค call this function recursively with new right argument: 2|๏ฃฟรนรฏยฉ Current number mod 2 pโ€šรœรช Store that value in p (for parity) 6โ€šรฃรœ 6 to that power (1 for even numbers, 6 for odd) 2โˆšโˆ‘ 2 divided by that amount (2 or 1/3) ๏ฃฟรนรฏยฉโˆšโˆ‘ Current number divided by that (x/2 or x*3) p+ Add p (x/2+0 or x*3+1) ( ) and new left argument: 2โˆšรณ๏ฃฟรนรฏยฎ Current accumulator times 2 p+ Plus p 1โ€šรคโˆ Call that function with a left argument of 1 ``` Somewhat surprisingly, there seem to be no floating point errors from dividing by 3 until the numbers get too large to store as integers anyway. [Answer] # [Rust](https://www.rust-lang.org/), ~~77 67~~ 61 bytes -10 bytes, thanks @alephalpha. -6 bytes, thanks @Juan Ignacio Dโˆšโ‰ az ``` |mut n|{let mut b=1;while n>1{b=2*b+n%2;n=[n/2,3*n+1][n%2]}b} ``` [Try it online!](https://tio.run/##TY1LCsIwGAb3PcVvQUgfVBIXLkq8SOmigRYD7afkgWCas8cWRZzVMJsx3ro0gZZBgxUUMtqY7oZAGsSbRorLt@48jIabcWB5iHlNLK2Ld4Q1zKOjXZXk7fOm55Fw5UFJUaoKR9FCdjiJ@lyi4n23lT6qmOiPgoEGS97q11j8hh@LWUxv "Rust โ€šร„รฌ Try It Online") If overflows are not okay we can use ~~81~~ 74 (-6 bytes, thanks @Juan Ignacio Dโˆšโ‰ az) bytes instead and write ``` |mut n|{let mut b=1.;while n!=1{if n%2>0{b=2.*b+1.;n=3*n+1;}b*=2.;n/=2;}b} ``` [Try it online!](https://tio.run/##TY1BCsIwFAX3PcVvQUhaiSYuXJTvXQy0GEifUlNcpDl7TFHEWQ3zFm9eniGPoOnqICTFigrjfSaQA2ml2Jy/deMxOwSPWjQxNXsSeZ2WQFijHwJtalmr/nVzfiDUrKMbCTtzOUbLRrW2Kyv41KLTfbJtaT0ObIqnTH9IAfk7/ViqUn4D "Rust โ€šร„รฌ Try It Online") which returns the value as a float, so it doesn't overflow for an input of 27. Instead it returns 4272797808638851700000000000000000, which is 137289440854955024 too small. [Answer] # [tinylisp 2](https://github.com/dloscutoff/tinylisp2), 78 bytes ``` (d E(\(N(A 1))(?(= N 1)A(E(?(o N)(+(* 3 N)1)(/ N 2))(+(o N)A A ``` Try it at [Replit](https://replit.com/@dloscutoff/tinylisp2): enter the above definition, and then on the next line call it like `(E 7)`, or test multiple arguments with something like `(map E (1to 10))`. ### Ungolfed/explanation Another port of my BQN answer. ``` (def encode ; Define encode (lambda ; as a lambda function (num (accum 1)) ; that takes a number and an accumulator that defaults to 1: (if (= num 1) ; If num is 1, accum ; return accum (encode ; Else, do a recursive call with these arguments: (if (odd? num) ; First argument: if num is odd, (+ (* 3 num) 1) ; 3 * num + 1 (/ num 2)) ; else num / 2 (+ (odd? num) ; Second argument: add 1 if num is odd, 0 otherwise accum ; to accum accum))))) ; and accum again--thus, 2 * accum + (num mod 2) ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 47 bytes ``` f(n,i=1)=if(n<2,i,f(if(n%2,3*n+1,n/2),2*i+n%2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN_XTNPJ0Mm0NNW0zgSwbI51MnTQNEFPVSMdYK0_bUCdP30hTx0grUxsopKkJ1aaSll-kkadgq2Coo2BoqqNQUJSZVwIUUFLQtQMSQP2aMLUwqwA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [D#โˆšรชโˆšรขi3*>โˆšยด;])โˆšรขโˆšร…2ล’โ‰ค ``` [Try it online](https://tio.run/##yy9OTMpM/f8/2kX58ITDnZnGWnaHV1vHah7uPNxodG7T///GAA) or [verify all test cases](https://tio.run/##ATQAy/9vc2FiaWX/MTVFTj8iIOKGkiAiP04i/1tEI8OQw4lpMyo@w6s7XSnDicOBMs6y/yIuViz/). **Explanation:** ``` [ # Loop indefinitely: D # Duplicate the current value # (which will be the implicit input in the first iteration) # # If it's equal to 1: stop the infinite loop โˆšรช # Triplicate the current value โˆšรขi # Pop one, and it it's odd: 3* # Multiply the value by 3 > # And add 1 โˆšยด # Else (it's even instead): ; # Halve it ] # Close the if-else statement and loop ) # Wrap all values on the stack into a list โˆšรข # Check for each value whether it's odd โˆšร… # Rotate the list once towards the right 2ล’โ‰ค # Convert it from a binary-list to an integer # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 58 bytes ``` f=function(n,o=1,m=n%%2)`if`(n>1,f((5*m+1)*n/2+m,2*o+m),o) ``` [Try it online!](https://tio.run/##LczLCcAgDADQaYREAyWCl4KdxSIVBE2kn0Ont5e@Ad45s7Z2SI6zxPJIvqsKCGlk6lGM8ZhqSSAbUwEItjtGK4t3nbxV15EU57WP0V7glQP9H84P "R โ€šร„รฌ Try It Online") Recursive function. --- # [R](https://www.r-project.org/), 58 bytes ``` function(n){while(n>1){T=T*2+(m=n%%2) n=(5*m+1)*n/2+m} +T} ``` [Try it online!](https://tio.run/##K/qfnJ@Tk5qXbPs/rTQvuSQzP08jT7O6PCMzJ1Ujz85QszrENkTLSFsj1zZPVdVIkyvPVsNUK1fbUFMrT99IO7eWSzuk9n9xYkFBTqWGoZWhqQ7UPM3/AA "R โ€šร„รฌ Try It Online") Non-recursive approach, same length. [Answer] # [Desmos](https://www.desmos.com), ~~83~~ 80 bytes ``` i->i+si+sk,n->(floor(n/2)+kn+k)(k+1)s s=max(0,sign(n-1)) k=mod(n,2) i=1 n=\ans_0 ``` [Try it on Desmos!](https://www.desmos.com/calculator/iknrh8ko9z) *-3 bytes thanks to Aiden Chow* [Answer] # C, ~~75~~ 54 bytes Edit: 54 bytes, credit to ceilingcat. ``` c(n,x){for(x=1;n>1;n=n%2?x++,n*3+1:n/2)x+=x;return x;} ``` Works with gcc and clang. Test main: `main(){for(int i=1;i<16;i++) printf("%d\n",c(i));}` Takes and returns int16\_t. Beware of the dreaded integer overflow. **81 chars, not conforming to requirements, but no overflow:** ``` #define P putchar(4 c(n){P 9);for(;n>1;){if(n%2){n=n*3+1;P 9);}else{n/=2;P 8);}}} ``` Prints as binary to stdout. [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tOi9eJzPeyjDWytYTyLEx0snUSYsGMn3zU6LzdIxibW0NdYzztA118vSNYnWMMrVhErGx/13yowOKMvNKgHwFJQVdOwUlHQWgIbGxOgrVQCFDIDKtjf0PAA) ``` f[n_,i_:1]:=If[n<2,i,f[If[Mod[n,2]==1,3n+1,n/2],2i+Mod[n,2]]] ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 16 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` โ€šรฎยฅโˆšโ‰ค_โ€šรฑโ€ _@<\_โ€šรฎยฅโ€šรœรชยฌยจ]yโ€šรฑรซโˆšโ€ข ``` [Try it online.](https://tio.run/##y00syUjPz0n7///RlC2HN8U/mrYg3sEmJh7Ie9Q24dCa2MpH0yYeXvr/vyGXEZcxlwmXKZcZlzmXBZcll6EBl6Ehl6ERl6Exl6EJl6EpAA) Unfortunately there seem to be some bugs in MathGolf with the `โ€šร„ยบ` and `โˆšยง` builtins, since this should have been possible in 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) instead: `โ€šรฎยฅโˆšยฅ_โ€šรฑโ€ โ€šร„ยบ<_โ€šรฎยฅโ€šรœรชยฌยจ]โˆšยง`.. **Explanation:** ``` โ€šรฎยฅ # Check if the (implicit) input is equal to 1 โ€šรœรช # While false with pop, โˆšโ‰ค # execute the following 6 characters as inner code-block: _ # Duplicate the current value โ€šรฑโ€  # Pop the copy, and push its Collatz value _ # Duplicate that Collatz value @ # Triple-swap the top three values on the stack: a,b,b โ€šรœรญ b,a,b < # Pop the top two and push a<b \ # Swap the top two values _ # Duplicate the top value โ€šรฎยฅ # Pop the copy, and check if it's equal to 1 ยฌยจ # Rotate the stack once, so this duplicated 1 is at the front ] # Wrap the entire stack into a list y # Join it together to a number โ€šรฑรซ # Convert it to a string โˆšโ€ข # Convert it from a binary-string to an integer # (after which the entire stack is output implicitly) ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 41 bytes ``` 1{J2dv{2./}{3.*+.}IE}C~J1Fi.+1+]m{2.%}2ug ``` [Try it online!](https://tio.run/##FY0xC8IwFIR3f0UWESzGvJe2SegoChZ3py6iSEFBK3FJ41@P76bv7l1yd4nT4/Z5x1tJq7nrNsM0Fko9X7@J9TYnq9eVzsd93v16Ooy6omp4SrTMHO8lvvL5VJQiNStaKMVCFlrQeFG1qFrYgDi0IqxtRTl8Mt4TjBeDOIAcHEkNGRgjAv3c@iAvCRtNQIwV56WdsEKutg3OmGLyxP4P "Burlesque โ€šร„รฌ Try It Online") ``` 1 # Continuation takes last (1) value from stack { J # Duplicate 2dv # Divisible by two {2./} # Halve {3.*+.} # *3+1 IE # If else }C~ # Continue infinitely J # Duplicate 1Fi # Find index of 1 .+ # Take that many 1+] # Prepend 1 m{2.%} # Map mod 2 2ug # Read as binary digits ``` [Answer] # Batch, 152 bytes ``` @if %1==1 echo 1&exit/b0 @set n=%1&set s=1 :l @set/at=%n%%%2,s=%s%*2 @if %t%==1 (set/an=%n%*3+1,s=%s%+1)else set/an=%n%/2 @if %n% gtr 1 goto:l @echo %s% ``` ]
[Question] [ I once had a beautiful rectangular array. It was very symmetrical, but unfortunately it has fallen apart and now I only have the top left corner. Your task will be to rebuild the original array. Your program will receive a 2 dimensional array of integers. For ease of parsing, you may assume they are all between 1 and 9. Your task is to reverse the array's columns, its rows, and both, stitch together the resulting corners, and return the resulting array. You can assume the array dimensions will be at least 1x1. Test cases: ``` Input: 1 2 3 4 5 6 Output: 1 2 3 3 2 1 4 5 6 6 5 4 4 5 6 6 5 4 1 2 3 3 2 1 ``` --- ``` Input: 1 Output: 1 1 1 1 ``` --- ``` Input: 9 9 9 Output: 9 9 9 9 9 9 9 9 9 9 9 9 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Answer] # [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` โ•ฌ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTZD,i=JTVCJTI3MTIzJTI3JTJDJTI3NDU2JTI3JTJDJTI3Nzg5JTI3JTVE,v=1) Outputs as a multiline string [Answer] ## Haskell, ~~25~~ 24 bytes ``` r=(++)<*>reverse r.map r ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8hWQ1tb00bLrii1LLWoOJUrzbZILzexQKHof25iZp6CrUJKPpeCQkFRZl6JgopCmkJ0tKGOkY5xrE60iY6pjllsLLoshoglUC0Ex/4HAA "Haskell โ€“ Try It Online") [Answer] # Python 3, 38 bytes ``` lambda a:[b+b[::-1]for b in a+a[::-1]] ``` [Try it online!](https://tio.run/##LYwxDoMwDEVncgpvFOEOlLYSljiJ68ERREVqA4IsnD40oYP1/Z/037KH9@zb6PpX/OjXDgpKbGvLRNdG3LyChcmD1noSiWHcwgY9sCmYG7xhK8h3fOBTBDP7Z/fj54kRk1RpmmxZQaZY1smHS2pYUokuv1UVDw "Python 3 โ€“ Try It Online") Takes a list of lists and returns a list of lists. Explanation: ``` lambda a: # anonymous lambda function for b in a+a[::-1] # for each row in the array and the upside-down array b+b[::-1] # the row with its reverse appended [ ] # return in a list ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~7~~ 6 bytes Coincidentally, [Erik](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) had posted the [exact same code in the Husk chatroom](https://chat.stackexchange.com/transcript/message/43218478#43218478) about a minute before I posted this. ``` โ€ผoTS+โ†” ``` [Try it online!](https://tio.run/##yygtzv7//1HDnvyQYO1HbVP@//8fHW2oY6RjHKsTbaJjqmMWGwsA "Husk โ€“ Try It Online") Pervious version, [**7 bytes**](https://tio.run/##yygtzv7/PzdY@1HbFDDx////6GhDHSMd41idaBMdUx2z2FgA "Husk โ€“ Try It Online"): ``` mS+โ†”S+โ†” ``` [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes ``` \%`$ $^$` Vs` ``` [Try it online!](https://tio.run/##K0otycxLNPz/P0Y1QYVLJU4lgSusOOH/f0MjYy4TUzMA "Retina โ€“ Try It Online") ### Explanation ``` \%`$ $^$` ``` On each line (`%`), match the end of the line (`$`), and insert the reverse (`$^`) of the entire line (`$``) and print the result with a trailing linefeed (`\`). This does the reflection along the vertical axis and prints the first half of the output. ``` Vs` ``` This just reverses the entire string, which is equivalent to a 180ยฐ degree rotation, or in our case (due to the horizontal symmetry) a reflection along the horizontal axis. This way this works is that `V`'s (reverse) default regex is `(?m:^.*$)`, which normally matches each line of the string. However, we activate the singleline option `s`, which makes `.` match linefeeds as well and therefore this default regex actually matches the entire string. The result of this is printed automatically at the end of the program, giving us the second half of the output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` โˆžโˆŠ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//Uce8Rx1d//9HqxsaGavrqJuYmgFJcwtL9VgA "05AB1E โ€“ Try It Online") --- ``` # Input:Array of String | ['12','34'] ---#-----------------------+------------------------------------------ โˆž # Mirror horizontally. | [12,34] -> [1221,3443] โˆŠ # Mirror vertically. | [1221,3443] -> [1221\n3443\n3443\n1221] ``` --- Credit for [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) pointing out that arrays of string may count as 2D arrays and [Pavel](https://codegolf.stackexchange.com/users/60042/pavel) for confirming it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` mโ‚ฌ0m0 ``` [Try it online!](https://tio.run/##y0rNyan8/z/3UdMag1yD////R0cb6igY6SgYx@ooRJvoKJjqKJjFxgIA "Jelly โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` ,tPv! ``` [Try it online!](https://tio.run/##y00syfn/X6ckoEzx//9oQwUjBWNrBRMFUwWzWAA "MATL โ€“ Try It Online") Explanation: ``` (implicit input) , # do twice: t # dup top of stack P # flip vertically v # vertically concatenate ! # transpose (implicit output) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~33~~ 29 bytes *Thanks to @Giuseppe for golfing four bytes!* ``` @(A)[B=[A;flip(A)] fliplr(B)] ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQcNRM9rJNtrROi0nswDIiVUAMXKKNJw0Y/@nKdgqJOYVW3NxpWlEGyoYKRhbK5gomCqYxWpCRAytFYAEhGdprQBCsZr/AQ) [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes ``` ->a{r=->b{b+b.reverse} r[a].map &r} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xushW1y6pOkk7Sa8otSy1qDi1lqsoOjFWLzexQEGtqPZ/gUJadHS0oY6RjnGsTrSJjqmOWWxsLBdUGMG0BMpCcGzsfwA "Ruby โ€“ Try It Online") A lambda accepting a 2D array and returning a 2D array. It's straightforward, but here's the ungolfed version anyway: ``` ->a{ r=->b{ b+b.reverse } # r is a lambda that returns the argument and its reverse r[a].map &r # Add the array's reverse, then add each row's reverse } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~62~~ ~~55~~ ~~49~~ 46 bytes ``` A=>(j=x=>[...x,...[...x].reverse()])(A).map(j) ``` [Try it online!](https://tio.run/##HcZRCoMwDADQ6yQQAzrnj1TwHCUfpYtiqVbaId6@k/08XnCXKz5v57c50kfrYupsJgjmNpNl5pse/hHOemkuCigIM/LuTghYR5@OkqJyTCssYO2LOmqF7EBv6kUQ6w8 "JavaScript (Node.js) โ€“ Try It Online") Because `Array.prototype.reverse()` reverses the array in place, I have to make a shallow copy somewhere first. `A=>(j=x=>[...x,...x.reverse()])(A).map(j)` does not work. [Answer] # [J](http://jsoftware.com/), 12 bytes ``` (,|.)@,.|."1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXRq9DQddPRq9JQM/2tyKXClJmfkK6QpGCkYqxiCSAUTBVMFM4iwuq4CEKrD1BgqGKoYYpUxBspY4pAxUbGzytQzNOL6DwA "J โ€“ Try It Online") ## Explanation ``` |."1 - reverse each row ,. - and stitch them to the input ( )@ - and ,|. - append the rows in reversed order ``` [Answer] # awk, 88 bytes ``` {s="";for(i=NF;i>0;i--)s=" "$i s" "$i;a[FNR]=s;print s}END{for(i=NR;i>0;i--)print a[i]} ``` [Answer] # [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 31 bytes ``` ...)... ..IEM.. .DRs+}. DRs+... ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTxOIufT0PF19QbRLULF2rR4XiAKK//8fHW2oo2Cko2Acq6MQbaKjYKqjYBYbCwA "Triangularity โ€“ Try It Online") ## Explanation Removing the characters that make up for the padding, here is what the program does: ``` )IEMDRs+}DRs+ โ€“ Full program. Takes a matrix as a 2D list from STDIN. ) โ€“ Push a 0 onto the stack. I โ€“ Take the input at that index. E โ€“ Evaluate it. M } โ€“ For each row... DR โ€“ Duplicate and replace the second copy by its reverse. s+ โ€“ Swap and append. DR โ€“ Duplicate the result and replace the second copy by its reverse. s+ โ€“ Swap and append. ``` [Answer] # [R](https://www.r-project.org/), 57 bytes ``` function(m)rbind(N<-cbind(m,m[,ncol(m):1]),N[nrow(N):1,]) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNXsygpMy9Fw89GNxnMyNXJjdbJS87PAUpZGcZq6vhF5xXll2v4AXk6sZr/0zRyE0uKMis0LHVA4rbGYMW2hpqaXHApQysziKQRRNJYJ6kSxA0JCnXV1PwPAA "R โ€“ Try It Online") [Answer] # APL+WIN, 11 bytes Prompts for a 2d array of integers. ``` mโชโŠ–mโ†m,โŒฝmโ†โŽ• ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` :mm:m ``` [Run and debug it online](https://staxlang.xyz/#c=%3Amm%3Am&i=%5B%22123%22%2C%22456%22%5D%0A%5B%221%22%5D%0A%5B%229%22%2C%229%22%2C%229%22%5D&a=1&m=2) `:m` means mirror, which is `input.concat(reverse(input))`. `m`, in this context means output each line after applying... So, mirror the array of rows, and then mirror each row and output. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` mรช1 รช1 ``` [Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=beoxIOox&input=W1sxLDIsM10sWzQsNSw2XV0KLVI=) --- ## Explanation ``` :Implicit input of 2D array m :Map รช1 : Mirror sub array รช1 :Mirror main array ``` [Answer] # [Mathematica](https://www.wolfram.com/mathematica/), 29 bytes ``` (g=#~Join~Reverse@#&)@*Map[g] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPdVrnOKz8zry4otSy1qDjVQVlN00HLN7EgOj32f0BRZl5JdJqCg0J1taGOgpGOgnGtjkK1iY6CqY6CWW1t7H8A "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 2 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) *-1 byte thanks to dzaima.* ``` โ•ฌรธ ``` [Try it here!](https://dzaima.github.io/SOGLOnline/comp/index.html?code=JXUyNTZDJUY4ZiUwQSV1MjE5MmY_,inputs=JTIyMTIzJTVDbjQ1NiUyMg__,v=0.12) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 7 bytes ``` โชโˆ˜โŠ–โจโŠข,โŒฝ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dko95VjzpmPOqa9qh3xaOuRTqPevb@/18ClKh@1Lv1UeeiIiAz7VHvLiv1tMTMHHUgCyhe9Ki7RT0/W72WS@NR20QNQwUjBWNNDRMFUwUzTc0SuBAQGikYQiWA0FTBBI2DrAxoVu8qQ5h2Q00wARa0VABCiASIgZMAAA "APL (Dyalog Classic) โ€“ Try It Online") [Answer] # Java 8, ~~140~~ 131 bytes ``` m->{String r="";for(int a=m.length,b=m[0].length,i=a+a,j;i-->0;r+="\n")for(j=b+b;j-->0;)r+=m[i<a?i:a+a+~i][j<b?j:b+b+~j];return r;} ``` **Explanation:** [Try it online.](https://tio.run/##lVDLboMwELznK1acQDYofUqN4@QLmkuPrg@GOKldbJAxqSrk/Do1gd5bafewOzPamdXiIvKmlVYfP8eqFl0Hr0LZYQWgrJfuJCoJh2kEePNO2TNUaUQYZxxMRiIQYsfqvPCqggNYoDCafDcsfEeThJwaN8lAUFPU0p79By6pYWv@OykqkMCaqDzfrYlDNHm3STbJNC1RSfRtn0XAMLUVe7WJfHRVnOltudebyEFXzYmTvncWHAkjmY21fVlHY4u/S6OOYGLEdLbHuMiWeN@dl6Zoel@0EfG1TW1RpVZ@wRJ4GO7wPX4IeHjET/g5hOz2gD9K/0d/iVfmXmRhFcYf) ``` m->{ // Method with integer-matrix parameter and String return-type String r=""; // Result-String, starting empty for(int a=m.length, // Amount of rows of the input-matrix b=m[0].length, // Amount of columns of the input-matrix i=a+a,j; // Index integers i-->0; // Loop over double the rows r+="\n") // After every iteration: append a new-line to the result for(j=b+b;j-->0;) // Inner loop over double the columns r+= // Append the result with: m[i<a? // If `i` is smaller than the amount of rows i // Use `i` as index in the input-matrix : // Else: a+a+~i] // Use `a+a+i-1` as index instead [j<b? // If `j` is smaller than the amount of columns j // Use `j` as index in the input-matrix : // Else: b+b+~j]; // Use `b+b+j-1` as index instead return r;} // Return the result-String ``` [Answer] # [J](http://jsoftware.com/), 11 bytes Anonymous tacit prefix function. ``` |:@(,|.)^:2 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/a6wcNHRq9DTjrIz@a3IpcKUmZ@QrpCkYKRirGIJIBRMFUwUziLC6rgIQqsPUGCoYqhhilTEGyljikDFRsbPK1DM04voPAA "J โ€“ Try It Online") `|:`โ€ƒtranspose `@(โ€ฆ)`โ€ƒthe result of: โ€ƒ`,`โ€ƒthe argument followed by โ€ƒ`|.`โ€ƒits reverse `^:2`โ€ƒand all this done twice [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~119~~ 113 bytes ``` T =TABLE() I X =X + 1 I =INPUT :F(D) OUTPUT =T<X> =I REVERSE(I) :(I) D X =X - 1 OUTPUT =GT(X) T<X> :S(D) END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/nzNEwTbE0cnHVUOTy5MzQsE2QkFbwZCL01PB1tMvIDSE08pNw0WTi9M/NATIA6q1ibADSikEuYa5BgW7anhqcloBCS4XiF5dkF6YWvcQjQhNBZAOTqtgkCmufi6c//8bGhlzmZiaAQA "SNOBOL4 (CSNOBOL4) โ€“ Try It Online") Takes input as strings on STDIN, without spaces. This only works because the digits are `1-9` and would fail otherwise. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~114~~ 111 bytes * Saved three bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen); inverting the loops. ``` j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)printf("%d,",A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]);} ``` [Try it online!](https://tio.run/##dY1BCsIwEEXXeoyAMGOmYFsVbFpLz1G6kEpMAtZSK1mU9OoxdSG4kNl8/vuPaaNb23pvSAsJFVlSqLtxW4lJPgbQheJK6Cg670T/Gp/AGOICTGG5FeYDsB@CIoFtrsSoqkHnqtRZMPmscWs5mNyWJgsGnw02KJy/X3QHOK1XEiDIdYNTTAmltKcDHV0ICX4/ip@Zo5jiP/BE4ZZBGnrn3w "C (gcc) โ€“ Try It Online") # [C (gcc)](https://gcc.gnu.org/), 109 bytes (abusing ease of parsing) * Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for suggesting to only allow one-digit input integers; saved two bytes. ``` j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)putchar(A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]+48);} ``` [Try it online!](https://tio.run/##dY3NCoJAFIXX9Riu7nWukD9FOZr4HNJCBJs7kIUZs5Dx1aexRdAizuZyvu9yuujadc5pYtlDTYYU8jCFtZz7@whcKqEkR9F5Jx@v6QlBgLgCXRphpP4A9KRT7Qh1A1yoinP/JBbG0AjQhal07mWxaLyI7IjSulvLA@C83fQAfq254BxTQilltKeD9UeC3z35o1mKKf4DT@SzCqnvrXsD "C (gcc) โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` ฮธโ€–๏ผฃโ†’โ†“ ``` [Try it online!](https://tio.run/##ASkA1v9jaGFyY29hbP//zrjigJbvvKPihpLihpP//1tbJzEyMycsJzQ1NiddXQ "Charcoal โ€“ Try It Online") Thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for a better input format. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 30 bytes ``` D,f,@,bUโ‚ฌ{r}B]{r} D,r,@,dbR+ ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQScp9FHTmuqiWqdYIMHlolMEFEtJCtIGSqdkFhfkJFbqOFjpcHEaGjirlHBxJoV6lZVxcVan1YLYXJwgzVn5mXm1eVxAzSAWUD9EytjIOYuLSwVqip39//9K0dGWsTpcCgoIKlbpX35BSWZ@XvF/Xd2y1KJiINPWRM8QAA) The footer simply transforms the nested array into the format in the question. Defines a function `f`, which expects a matrix (nested array) as an argument. [Answer] # [Uiua](https://uiua.org), 9 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` โฅ(โ‰โŠ‚โˆถโ‡Œ.)2 ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4o2lKOKNieKKguKItuKHjC4pMgoKZltbMSAyIDNdCiAgWzQgNSA2XV0KCmZbWzFdXQoKZltbOV0KICBbOV0KICBbOV1dCg==) ``` โฅ(โ‰โŠ‚โˆถโ‡Œ.)2 โฅ( )2 # run a function twice . # duplicate โ‡Œ # reverse โŠ‚โˆถ # prepend โ‰ # transpose ``` [Answer] # [Julia 0.6](http://julialang.org/), ~~55~~ 49 bytes ``` ~i=i:-1:1 !x=[x x[:,~end];x[~end,:] x[~end,~end]] ``` [Try it online!](https://tio.run/##yyrNyUw0@/@/LtM200rX0MqQS7HCNrpCoSLaSqcuNS8l1roiGkTrWMUqQFlg4dj/DsUZ@eUKitGGCkYKxtYKJgqmCmaxXDBRS2sgRHANY7m4/gMA "Julia 0.6 โ€“ Try It Online") `~(i)` is a function to create slice from `i` down to `1`. So `~end` gives the slice `end:-1:1` `!(x)` is the function to do the rebuilding of the array. [Answer] # [V](https://github.com/DJMcMayhem/V), 12 bytes ``` yGรฆGPรŽy$รฆ_|P ``` [Try it online!](https://tio.run/##K/v/v9L98DL3gMN9lSqHl8XXBPz/b2hkzGViasZlbmEJAA "V โ€“ Try It Online") Explanation: ``` yG " Yank every line รฆG " Reverse the order of the lines P " Paste what we yanked รŽ " On every line: y$ " Yank the whole line รฆ_ " Reverse the whole line | " Move to the beginning of the line P " Paste what we yanked ``` ]
[Question] [ Take a look at this chamomile flower: [![](https://i.stack.imgur.com/VuneQ.png)](https://i.stack.imgur.com/VuneQ.png) Pretty, isn't it? Well, what if I told you that this wasn't actually one flower? A lot of flowers (including sunflowers, chamomiles, daisies and others) actually consist of many very small flowers (the black dots on sunflowers) on a flower head. These miniature flowers are called *florets*, and they are arranged in a very special way. Basically, the nth floret's position on a flower head is (in polar coordinates): [![](https://i.stack.imgur.com/lgVI1.png)](https://i.stack.imgur.com/lgVI1.png) [![](https://i.stack.imgur.com/FW3Wx.png)](https://i.stack.imgur.com/FW3Wx.png) where c = 1 (Note that 137.508 degrees = golden angle. You don't have to use this exact precision.) This causes the florets to be formed in a spiral called Fermat's Spiral. The positioning of the florets also is connected with Fibonnaci numbers, but that's a tale for another time. So, here's the challenge. Given an integer n as input, calculate the positions of the first n florets and **plot them**. This is [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'"), so I do actually want you to display the points in either a window of some sort or outputted as data in some common image format to STDOUT or a file. Other than that, this challenge should be fairly straightforward. It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. GLHF! Here is a sample picture of what an output might look like: [![](https://i.stack.imgur.com/xQk4x.png)](https://i.stack.imgur.com/xQk4x.png) [Answer] # TI-BASIC, 34 bytes For the TI-83+/84+ series of calculators. ``` Input N 2ฯ€e^(-2sinhโปยน(.5โ†’ฮธstep AnsNโ†’ฮธmax "โˆš(ฮธโ†’rโ‚ Polar ;Displays polar mode graphs to graph screen Dot ;Prevents lines from connecting points DispGraph ;Displays graph screen ``` This considers the dot at the origin to be the 0th dot. Thanks to the one-byte `sinhโปยน(` token, `2ฯ€e^(-2sinhโปยน(.5` is a short way of getting the golden angle in radians. This is derived from the fact that `e^(sinhโปยน(.5` is the golden ratio. Here are screenshots for N=50. (Yes, that's a [96x64 monochrome display](https://xkcd.com/768/) on a TI-84+. The newer color calculators have a resolution upgrade, but still have only 3.7% the pixels of an iPhone.) [![Without coordinates displayed](https://i.stack.imgur.com/N7H20.png)](https://i.stack.imgur.com/N7H20.png) Press `TRACE` to step through each point. [![With coordinates](https://i.stack.imgur.com/Uql7F.png)](https://i.stack.imgur.com/Uql7F.png) [Answer] # Python 2, ~~85~~ ~~82~~ 81 bytes ``` from pylab import* for i in arange(0,input(),2.39996):polar(i,sqrt(i),'o') show() ``` Shortened by one byte by marinus. Using the golden angle in radians. Byte length is the same if I used 137.508 instead, but somehow doesn't look as good. Generates a polar plot using pylab. Below is when 300 (for the older version) is the input and 7000 (for the newer version) is the input. Could round the angle up to 2.4 to lower the number of bytes to 77. [![Older version when input is 300](https://i.stack.imgur.com/fbodi.png)](https://i.stack.imgur.com/fbodi.png) [![Newer version when input is 7000](https://i.stack.imgur.com/Pj77A.png)](https://i.stack.imgur.com/Pj77A.png) Here's a longer version that produces a cleaner look by removing the grid and axis: ``` from pylab import * def florets(n): for i in arange(0, n, 2.39996):polar(i, sqrt(i), 'o') grid(0)#turn off grid xticks([])#turn off angle axis yticks([])#turn off radius axis show() ``` The reason for the different colors is because each point is plotted separately and treated as its own set of data. If the angles and radii were passed as lists, then they would be treated as one set and be of one color. [Answer] ## [Blitz 2D/3D](http://www.blitzbasic.com/), 102 bytes (The very FIRST EVER Blitz 2D/3D answer on this site!) ``` Graphics 180,180 Origin 90,90 n=Input() For i=1To n t#=i*137.508 r#=Sqr(t) Plot r*Cos(t),r*Sin(t) Next ``` An input of `50` fills the window. (Yes, I could shave off two bytes by doing `Graphics 99,99`, but that's not nearly so visually interesting or useful.) [![50 florets](https://i.stack.imgur.com/vqPUM.png)](https://i.stack.imgur.com/vqPUM.png) Prettier version (and exits more nicely): ``` Graphics 400,400 Origin 200,200 n=Input("How many florets? ") For i = 1 To n t# = i * 137.508 r# = Sqr(t) Oval r*Cos(t)-3,r*Sin(t)-3,7,7,1 Next WaitKey End ``` [![200 florets example](https://i.stack.imgur.com/j1HKh.png)](https://i.stack.imgur.com/j1HKh.png) [Answer] # Mathematica, ~~43~~ 42 bytes ``` ListPolarPlot@Array[(2.39996#)^{1,.5}&,#]& ``` This is an unnamed function taking an integer argument, e.g. [![enter image description here](https://i.stack.imgur.com/d0Qfq.png)](https://i.stack.imgur.com/d0Qfq.png) The screenshot uses an older version, but the output looks the same. Mathematica actually has a built-in `GoldenAngle` for even more accurate results, but that's longer than `2.39996`. [Answer] # MATLAB, 42 bytes ``` t=2.39996*(1:input(''));polar(t,t.^.5,'.') ``` Gets the input number, creates a range from 1 to that number. Multiplies the range by the golden angle in radians (the value used is closer to the true value than 137.508 degrees to 6 s.f.). Then simply plots **theta** vs. **r** on a polar coordinates chart using dots. Here shown with 2000 points [![Polar](https://i.stack.imgur.com/DT9P0.png)](https://i.stack.imgur.com/DT9P0.png) A slightly prettier looking graph (no grid lines) would be this code: ``` t=2.39996*(1:input(''));[x,y]=pol2cart(t,t.^.5);plot(x,y,'.');axis equal ``` Though that is at the expense of 31 bytes. Again here is it shown with 2000 points [![Plot](https://i.stack.imgur.com/F825k.png)](https://i.stack.imgur.com/F825k.png) [Answer] # R, ~~58~~ ~~55~~ 54 bytes ``` x=2.39996*1:scan();plotrix::radial.plot(x^.5,x,rp="s") ``` This requires the `plotrix` package to be installed, but the package doesn't have to be imported because we're referencing the namespace explicitly. Ungolfed: ``` # Read a number of STDIN n <- scan() x <- 2.39996*(1:n) # The rp.type = "s" option specifies that we want to plot points rather # than lines (the default) plotrix::radial.plot(lengths = sqrt(x), radial.pos = x, rp.type = "s") ``` Example output for *n* = 1500: [![enter image description here](https://i.stack.imgur.com/VvIsD.png)](https://i.stack.imgur.com/VvIsD.png) Saved 3 bytes thanks to plannapus! [Answer] # R, ~~55~~ 54 bytes ``` t=1:scan()*2.39996;r=t^.5;plot(r*cos(t),r*sin(t),as=1) ``` Here is the result for n=1000: [![enter image description here](https://i.stack.imgur.com/jIbLI.png)](https://i.stack.imgur.com/jIbLI.png) Edit: Saved 1 byte using partial matching of arguments (`as` instead of `asp`) thanks to @AlexA.! [Answer] # R, ~~48~~ 47 bytes I think this is sufficiently different from the other R solutions so far. This one uses complex vectors to construct the coordinates. the sqrt of t and t are put into the modulus and argument parameters and the x, y are taking from the real and imaginary. Thanks to @AlexA. for the byte. ``` plot(complex(,,,t^.5,t<-1:scan()*2.39996),as=1) ``` [![enter image description here](https://i.stack.imgur.com/UPNOK.png)](https://i.stack.imgur.com/UPNOK.png) [Answer] # Html+JavaScript 179 ``` <canvas id=C></canvas><script>n=1500,C.width=C.height=400,T=C.getContext('2d');for(n=prompt(M=Math);n--;)r=M.sqrt(t=n*2.4)*9,T.fillRect(M.cos(t)*r+200,M.sin(t)*r+200,2,2)</script> ``` [Answer] # Jolf, 25 bytes ``` yG@@KyoฮœzXDyOUH*HmยฐyT'.} ``` [![enter image description here](https://i.stack.imgur.com/qUecQ.png)](https://i.stack.imgur.com/qUecQ.png) (output for n = 5000) [Try it online. (note that the resulting spiral is small)](http://conorobrien-foxx.github.io/Jolf/#code=eUdAwpZAS3lvzpx6WER5T1VIKkhtwrB5VCcufQ) Non-competing since Jolf was created after this challenge. This is 25 bytes when encoded with ISO-8859-7, and it contains one unprintable (here's a hexdump): ``` 0000000: 7947 4096 404b 796f cc7a 5844 794f 5548 yG@[[emailย protected]](/cdn-cgi/l/email-protection) 0000010: 2a48 6db0 7954 272e 7d *Hm.yT'.} ``` ## Explanation ``` yG@@KyoฮœzXDyOUH*HmยฐyT'.} yG@@K goto (150,75) (center of the canvas) yo set current location as the origin MzX map over range 1...input D start of function yO goto polar coordinates .... UH radius: square root of argument *Hmยฐ angle: argument times golden angle yT'. draw a dot there } ``` [Answer] # [K (oK) + `iKe`](https://github.com/JohnEarnest/ok), 37 bytes ``` {(80+(%t)*(cos;sin)@\:t:x*2.4;;1)}'!: ``` [Try it online!](https://johnearnest.github.io/ok/ike/ike.html?key=FBTqO-Y_) a function which takes n on the right. Uses the approximate 2.4 radian measure. -8 bytes from JohnE. ## Explanation ``` {draw::{(80+(%t)*(cos;sin)@\:t:x*2.4;;1)}'!x} draw:: globally set draw to: { } the following function '!x run on range 0..input-1 ( ) create an array: t:x*2.4 multiply right arg by 2.4, set to t (cos;sin)@\: apply cos and sin on each (%t)* multiply by sqrt(t) 80+ add 80 (for compatibility with any size, change to ((w;h)%2)+) ``` [Answer] # Python 2, 74 bytes ``` from pylab import* i=arange(1,input(),2.39996) polar(i,sqrt(i),'o') show() ``` [Answer] # Tcl/Tk, 114 ``` grid [canvas .c] proc P n {time {incr i .c cr o [lmap h {cos sin cos sin} {expr sqrt($i*2.4)*$h\($i*2.4)+99}]} $n} ``` Example of usage: ``` P 1024 ``` and outputs the window [![enter image description here](https://i.stack.imgur.com/I4sgg.png)](https://i.stack.imgur.com/I4sgg.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` :2.4*tX^wJ*Ze*'.'&XG ``` Try it at [**MATL Online!**](http://matl.io/?code=%3A2.4%2atX%5EwJ%2aZe%2a%27.%27%26XG&inputs=250&version=20.4.2) The golden angle, `137.708`deg = `pi*(3-sqrt(5))`rad = `2.39996...`rad is approximated as `2.4`rad. The following version (**25 bytes**) uses the exact value, up to `double` floating-point precision: ``` :YPI5X^-**tX^wJ*Ze*'.'&XG ``` Try it at [**MATL Online!**](http://matl.io/?code=%3AYPI5X%5E-%2a%2atX%5EwJ%2aZe%2a%27.%27%26XG&inputs=250&version=20.4.2) ]
[Question] [ I figured an "arch" was the best way to describe this pattern of numbers: ``` 1234567887654321 1234567 7654321 123456 654321 12345 54321 1234 4321 123 321 12 21 1 1 ``` Formally defined, each line consists of the numbers 1 through `9-n`, `(n-1)*2` spaces, and the numbers `9-n` through 1 (where `n` is the current line). Your task is to write, using the shortest code possible, a small script/program that prints the above pattern subject to the following restrictions: 1. You may not hardcode the entire pattern. You may only hardcode a single line of the pattern at most. 2. Your program must print a newline (any combination of `\n` or `\r`) at the end of each line. Ready... set.... go! [Answer] ## Python 2, ~~65~~ ~~55~~ ~~53~~ 51 ``` s=12345678 while s:r='%-8d'%s;print r+r[::-1];s/=10 ``` Shortened using some of [ugoren's](https://codegolf.stackexchange.com/a/11645/7911) ideas. [Answer] ## GolfScript (25 chars) ``` 8,{.~10,<1>\' '*.2$-1%n}/ ``` [Answer] ## APL (18) ``` k,โŒฝkโ†โ†‘โ†‘โˆ˜(1โ†“โŽ•D)ยจโŒฝโณ8 ``` Explanation: * `1โ†“โŽ•D`: the string of digits ("0123456789") minus its first element * `โ†‘โˆ˜(1โ†“โŽ•D)ยจโŒฝโณ8`: select the first [8..1] characters ('12345678', '1234567'...) * `โ†‘`: format as matrix (filling the unused characters with blanks) * `k,โŒฝkโ†`: store in `k`, and display `k` followed by the vertical mirroring of `k` [Answer] # Ruby: ~~61~~ 50 characters ``` s="87654321";s.chars{|c|puts s.reverse+s;s[c]=" "} ``` Sample run: ``` bash-4.2$ ruby -e 's="87654321";s.chars{|c|puts s.reverse+s;s[c]=" "}' 1234567887654321 1234567 7654321 123456 654321 12345 54321 1234 4321 123 321 12 21 1 1 ``` [Answer] ## Befunge - 3 x 18 = 54 I felt I had to do something with befunge, it's been too long since I last used it. This problem felt the most appropriate for the language. It is horrendously slow due to the print loop that takes about 8 actions per character (counting styles differ). ``` 80v >#v"12345678"< >5 *^ >,#$:_$:1-:v ^2< 0p0+7\*48\_@#< ``` [Answer] # JavaScript, 71 ``` s='1234567887654321',i=10;while(--i)console.log(s=s.split(i).join(' ')) ``` [Answer] ## C, 83 chars ``` main(a,b,n){ for(a=12345678,n=1e8,b=n-a-1;a;a/=10) printf("%-8d%8d\n",a,b), b%=n/=10; } ``` [Answer] # Python 2, 75 62 It won't beat Volatility's answer, but here's another approach using python's mutable strings (`bytearray`): ``` s=bytearray('1234567887654321') for i in range(8):s[8-i:8+i]=i*' ';print s ``` **Edit** I found a shorter version, using `str.replace`: ``` s='1234567887654321' for c in s[8:]:print s;s=s.replace(c,' ') ``` [Answer] # Perl, 41 plus `-E` switch. Total characters on the command line: **50** requires at least perl5, version 10. ``` perl -E'say@!=1..8-$_,$"x(2*$_),reverse@!for-0..7' ``` [Answer] # Mathematica 92 85 67 54 51 **Method #1**: (54 chars) Makes array using row#, col#, and distance from left-right edge. ``` Grid@Array[If[#2<9,#2,17-#2]/.x_/;x+#>9:>" "&,{8,16}] ``` --- **Method #2**: (67 chars) Pad ever-shortening ranges. ``` Print@@@Table[Join[k = PadRight[Range@i, 8, " "], Reverse@k], {i, 8, 1, -1}]; ``` --- **Method #3**: (85 chars) Selectively fill each row of an array. Start with list of 8 space characters. Replace positions 1 and 16 with "1"; replace "2" at positions 2 and 15, etc. ``` p = 0; q = 16; Print @@@Reverse@Rest@NestList[ReplacePart[#, {++p -> p, q-- -> p}]&,Array[" "&,q], 8]; ``` --- **Method #4**: (86 chars) Selectively empty each row of an array. ``` p=8;q=9; Print@@@NestList[ReplacePart[#,{p---> " ",q++-> " "}]&,Join[k=Range@8,Reverse@k],7]; ``` --- **Method #5**: Using strings (92 chars) ``` p=8;s="12345678"; Print[#,StringReverse@#]&/@NestList[StringReplace[#,ToString@p-- -> " "]&,s,7]; ``` [Answer] ## PHP, 68 (Inspired by HamZa's answer) `for($n=8;$n;$r[]=$n--)echo str_replace($r," ","1234567887654321\n");` Plays on the fact that PHP's str\_replace can accept an array for search and a string for replace, it'll replace every item in the array with the given string. After each iteration, the current number is added to the search array, removing it from the next loop. Example of the code in action: <http://ideone.com/9wVr0X> [Answer] # [Marbelous](https://github.com/marbelous-lang/marbelous.py) 165 ``` @0 08 >0 LN -- @0 :LN }0}0}0}0 ..SAPSSD0A {0 :PS }0 ~~09 ..// <<@0 \\>0 &0// --@1 @020 &0/\&0 @1 :SA @0 }0 >0!! --00@1 @0++// +O/\@1 +O :SD }0@0 \\>0\/ --/\+O @0..+O ``` Pseudocode: ``` MB(): for x in 8..1: LN(x) LN(x): SA(x) PS(x) SD(x) print "\n" PS(x): print " "*(8-x)*2 SA(x): for n in 1..x: print n SD(x): for n in x..1: print n ``` [Answer] ## Python 2.x - ~~73~~ ~~65~~ ~~63~~ 61 chars ``` c=1;s='87654321' while c<9:print s[::-1]+s;s=' '*c+s[c:];c+=1 ``` [Answer] ## PHP, 76 ``` for($i=9;$i>1;){$r[]=$i--;echo str_replace($r,' ','1234567887654321')."\r";} ``` [Answer] # K, 28 ``` -1_a,'|:'a:8$'{-1_x}\,/$1+!8 ``` . ``` k)-1_a,'|:'a:8$'{-1_x}\,/$1+!8 "1234567887654321" "1234567 7654321" "123456 654321" "12345 54321" "1234 4321" "123 321" "12 21" "1 1" ``` You could generalise it for 36: `{-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x}` ``` k){-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x} 5 "1234554321" "1234 4321" "123 321" "12 21" "1 1" q)k){-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x} 15 "123456789101112131415514131211101987654321" "12345678910111213141 14131211101987654321" "1234567891011121314 4131211101987654321" "123456789101112131 131211101987654321" "12345678910111213 31211101987654321" "1234567891011121 1211101987654321" "123456789101112 211101987654321" "12345678910111 11101987654321" "1234567891011 1101987654321" "123456789101 101987654321" "12345678910 01987654321" "1234567891 1987654321" "123456789 987654321" "12345678 87654321" "1234567 7654321" "123456 654321" "12345 54321" "1234 4321" "123 321" "12 21" "1 1" ``` [Answer] # GoRuby 2.1 ### 36 chars ``` 8.w(1){|x|a=[*1..x].j.lj 8;s a+a.rv} ``` ### Ungolfed ``` 8.downto(1) do |x| a = [*1..x].join.ljust(8) puts a + a.reverse end ``` [Answer] **K 20** ``` {x,'|:'x:|x$,\$1+!x} q)k){x,'|:'x:|x$,\$1+!x}8 "1234567887654321" "1234567 7654321" "123456 654321" "12345 54321" "1234 4321" "123 321" "12 21" "1 1" ``` [Answer] # Javascript, 67 chars Insipired by steveworley's answer (I would comment if I could): ### Code snippet ``` a='1234567887654321\n',b='',c=10;while(--c)b+=a=a.split(c).join(' ') ``` ``` <a href="#" onclick="javascript:document.getElementById('output').innerHTML = b;">Display</a> <pre id="output">...</pre> ``` The presence of the last newline does follow the rules. update: cut 2 chars by removing parentheses (operator precedence) and 1 by removing an unneeded space It seemed like it's trolling me, because no matter how many different ways I tried to shorten or simplify by un-hardcoding a segment of code, the length stayed the same until I let the "I think this counts" rule written below apply. *(If printing counts as what comes back when this is executed in the chrome console)* [Answer] # Brainfuck: 542 Bytes ``` -[----->+<]>--.+.+.+.+.+.+.+..-.-.-.-.-.-.-.>++++++++++.[->+++++ <]>-.+.+.+.+.+.+.+[-->+<]>++++..----[->++<]>-.-.-.-.-.-.-.>++++++++++.[->+++++ <]>-.+.+.+.+.+.[-->+<]>+++++....-----[->++<]>.-.-.-.-.-.>++++++++++.[->+++++ <]>-.+.+.+.+.--[--->++<]>--......-----[->++<]>-.-.-.-.-.>++++++++++.[->+++++ <]>-.+.+.+.-[--->++<]>--........++[-->+++<]>+.-.-.-.>++++++++++.[->+++++ <]>-.+.+.[--->++<]>--..........++[-->+++<]>.-.-.>++++++++++.[->+++++ <]>-.+.--[--->++<]>............[-->+++<]>++.-.>++++++++++.[->+++++ <]>-.-[--->++<]>..............[-->+++<]>+. ``` [Answer] ## *Mathematica*, 59 61 using my own ideas: ``` Grid[Clip[#~Join~Reverse@#&@Range@8,{1,9-#},{," "}]&~Array~8] ``` Or 59, borrowing from David's answer: ``` Grid@Array[Join[k=PadRight[Range[9-#],8," "],Reverse@k]&,8] ``` [Answer] ## R: 52 ``` for(i in 8:1)cat(1:i,rep(" ",16-2*i),i:1,"\n",sep="") ``` [Answer] ## Haskell, 84 A starting point for someone to improve: ``` mapM_ putStrLn[let l=take(8-i)"12345678"++replicate i ' 'in l++reverse l|i<-[0..7]] ``` Most likely part would be to make the `l++reverse l` point free, letting us get rid of the `let`-statement, but I'll I could find was `ap`, which requires imports. [Answer] ## Tcl: 91 characters ``` set i 10 set n 1234567887654321 while {[incr i -1]} {puts [set n [string map "$i { }" $n]]} ``` [Answer] # PostScript: 105 characters String handling is not easy in PS but can make for relatively simple code: ``` 0 1 7{(1234567887654321)dup 8 3 index sub( )0 6 -1 roll 2 mul getinterval putinterval =}for ``` A slightly longer version at 120 chars but can generate different number arches by replacing the 8 at the start of the second line with any number in the range 1 to 9: ``` /D{dup}def/R{repeat}def/P{=print}def 8 D -1 1{1 1 index{D P 1 add}R pop 2 copy sub{( )P}R D{D P 1 sub}R pop()=}for pop ``` [Answer] ## TSQL, 148 Edit: down to 148 with manatwork's suggestion and tweak to ORDER BY. Readable: ``` WITH t AS( SELECT 1n, CAST(1 AS VARCHAR(MAX)) o UNION ALL SELECT n+1,o+CHAR(n+49) FROM t WHERE n<8 ) SELECT o + SPACE(16-2*n) + REVERSE(o) FROM t ORDER BY 1 DESC ``` Golfed: ``` WITH t AS(SELECT 1n,CAST(1AS VARCHAR(MAX))o UNION ALL SELECT 1+n,o+CHAR(n+49)FROM t WHERE n<8)SELECT o+SPACE(16-2*n)+REVERSE(o)FROM t ORDER BY 1DESC ``` Output: ``` 1234567887654321 1234567 7654321 123456 654321 12345 54321 1234 4321 123 321 12 21 1 1 ``` [Answer] ## Haskell, 79 ``` r n x|x>n=' '|True=x t="87654321" main=mapM(putStrLn.(`map`("12345678"++t)).r)t ``` This works by replacing characters > n with `' '`, where characters n are sourced from "87654321" (which happens to be the tail of the string to perform substitution on). [Answer] # k, 33 chars ``` {|:{x,'|:'x}a$,/'$:{1+'!x}'1+!a:x}9 ``` [Answer] # PHP: 61 chars (or 60 chars if you replace the \n by a real ASCII newline) (Inspired by GigaWatt's and HamZa's answer) ``` for($n=9;$n;$r[$n--]=" ")echo strtr("1234567887654321\n",$r); ``` <http://ideone.com/FV1NXu> [Answer] # PowerShell: 38 **Golfed code** ``` 8..1|%{-join(1..$_+" "*(8-$_)+$_..1)} ``` **Walkthrough** `8..1|%{`...`}` pipe integers from 8 to 1 into a ForEach-Object loop. `-join(`...`)` joins output of the nested code into a single string with no delimiters. `1..$_` outputs integers ascending from 1 to the current integer in the loop. `+" "*(8-$_)` adds a double-space, multiplied by the difference between 8 and the current integer, to the output. `+$_..1` adds integers, descending from the current integer to 1, to the output. [Answer] ## Javascript with lambdas, 147 ``` (s="12345678")[r="replace"](/./g,i=>s[r](RegExp(".{"+(i-1)+"}$"),Array(i*2-1).join(" ")))[r](/\d{1,8} */g,m=>m+(Array(m%10+1).join(m%10+1)-m)+"\n") ``` Can be checked in Firefox. ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/204969/write-a-microwave-timer) Sometimes when I use my microwave, I do a little trolling and enter times such as `2:90` instead of `3:30` because they end up being the same time anyway. The microwave happily accepts this and starts counting down from `2:90`, displaying times like `2:86` and `2:69` until it gets back to a stage where it can count down like a normal timer. Y'all's task today is to simulate this behaviour by returning a list of all times displayed by the microwave when given a starting time. ## An Example Say I input `2:90` into the microwave. It starts at `2:90` and then shows `2:89`, `2:88`, `2:87`, `2:86`, ..., `2:60`, `2:59`, `2:58`, `2:57`, ..., `2:00`, `1:59`, `1:58`, `1:57`, ..., `0:05`, `0:04`, `0:03`, `0:02`, `0:01`, `END`. As you can see, where the seconds are less than `60`, it acts as normal. But where the seconds are greater than `60`, it decrements the seconds without impacting the minute count. ## Rules * Input can be taken in any convienient and reasonable format, including, but not limited to: + `[minutes, seconds]` + `[seconds, minutes]` + `minutes` on one line, `seconds` on the next + `seconds` on one line, `minutes` on the next + a single integer which is a [minutes, seconds] pair divmod 100 (e.g `130` represents `1:30`). * Output can be given in any convienient and reasonable format, including, but not limited to: + `[[minute, second], [minute, second], [minute, second], ...]` + `["minute second", "minute second", "minute second", ...]` + `minute second\n minute second\n ...` + `[[second, minute], [second, minute], [second, minute], ...]` * The outputted times can be returned in any order - they don't need to be sorted. * The seconds will never be greater than `99`. * Including `[0, 0]` or `0:00` is optional. Make sure to include how you're outputting the times in your answer. ## Sample IO Input here is given as `[minutes, seconds]`. Output is given as a list of `[minute, seconds]` ``` [0, 90] => [[0, 90], [0, 89], [0, 88], [0, 87], [0, 86], [0, 85], [0, 84], [0, 83], [0, 82], [0, 81], [0, 80], [0, 79], [0, 78], [0, 77], [0, 76], [0, 75], [0, 74], [0, 73], [0, 72], [0, 71], [0, 70], [0, 69], [0, 68], [0, 67], [0, 66], [0, 65], [0, 64], [0, 63], [0, 62], [0, 61], [0, 60], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]] [1, 20] => [[1, 20], [1, 19], [1, 18], [1, 17], [1, 16], [1, 15], [1, 14], [1, 13], [1, 12], [1, 11], [1, 10], [1, 9], [1, 8], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]] [2, 90] => [[2, 90], [2, 89], [2, 88], [2, 87], [2, 86], [2, 85], [2, 84], [2, 83], [2, 82], [2, 81], [2, 80], [2, 79], [2, 78], [2, 77], [2, 76], [2, 75], [2, 74], [2, 73], [2, 72], [2, 71], [2, 70], [2, 69], [2, 68], [2, 67], [2, 66], [2, 65], [2, 64], [2, 63], [2, 62], [2, 61], [2, 60], [2, 59], [2, 58], [2, 57], [2, 56], [2, 55], [2, 54], [2, 53], [2, 52], [2, 51], [2, 50], [2, 49], [2, 48], [2, 47], [2, 46], [2, 45], [2, 44], [2, 43], [2, 42], [2, 41], [2, 40], [2, 39], [2, 38], [2, 37], [2, 36], [2, 35], [2, 34], [2, 33], [2, 32], [2, 31], [2, 30], [2, 29], [2, 28], [2, 27], [2, 26], [2, 25], [2, 24], [2, 23], [2, 22], [2, 21], [2, 20], [2, 19], [2, 18], [2, 17], [2, 16], [2, 15], [2, 14], [2, 13], [2, 12], [2, 11], [2, 10], [2, 9], [2, 8], [2, 7], [2, 6], [2, 5], [2, 4], [2, 3], [2, 2], [2, 1], [2, 0], [1, 59], [1, 58], [1, 57], [1, 56], [1, 55], [1, 54], [1, 53], [1, 52], [1, 51], [1, 50], [1, 49], [1, 48], [1, 47], [1, 46], [1, 45], [1, 44], [1, 43], [1, 42], [1, 41], [1, 40], [1, 39], [1, 38], [1, 37], [1, 36], [1, 35], [1, 34], [1, 33], [1, 32], [1, 31], [1, 30], [1, 29], [1, 28], [1, 27], [1, 26], [1, 25], [1, 24], [1, 23], [1, 22], [1, 21], [1, 20], [1, 19], [1, 18], [1, 17], [1, 16], [1, 15], [1, 14], [1, 13], [1, 12], [1, 11], [1, 10], [1, 9], [1, 8], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]] ``` As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the aim of the game is to get your byte count as low as possible [Answer] # [Haskell](https://www.haskell.org/), 43 bytes *Doesn't output `0:0`* ``` 0?0=[] n?0=(n,0):(n-1)?59 n?m=(n,m):n?(m-1) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/38DewDY6lisPSGnk6RhoWmnk6Rpq2ptaAoVyQUK5mlZ59hq5QMH/uYmZeQq2CrmJBb7xCgVFmXklCioKhgr2CmZG/wE "Haskell โ€“ Try It Online") This is very simple. Decrements the second hand unless it's zero, in which case it decrements the minute unless it's zero in which case it ends. # [Haskell](https://www.haskell.org/), 46 bytes *Outputs `0:0`* ``` n?m=(n,m):[n?(m-1),[(n-1)?59|n>0]>>=id]!!(0^m) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P88@11YjTydX0yo6z14jV9dQUydaIw9I2Zta1uTZGcTa2dlmpsQqKmoYxOVq/s9NzMxTsFXITSzwjVcoKMrMK1FQUTBUsFcwM/oPAA "Haskell โ€“ Try It Online") This one is a bit more complicated than the last. It employs two special tricks for cheaper branching. To check the second hand `m`. We do `0^m` which gives \$1\$ when `m` is \$0\$ and \$0\$ otherwise. We can use this to index a list to switch between the two options. To check the minute hand `n`. We use a list comprehension trick. `[(n-1)?59|n>0]` is empty when `n` is zero and `[(n-1)?59]` otherwise. We use `>>=id` to concat away the wrapping list and then we get `(n-1)?59` when `n>0` and `[]` otherwise. [Answer] # [R](https://www.r-project.org), 41 bytes ``` f=\(m,s,`~`=rbind)t(m~s:0)~if(m)f(m-1,59) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGykszc1CLbpaUlaboWNzXTbGM0cnWKdRLqEmyLkjLzUjRLNHLriq0MNOsy0zRyNYFY11DH1FITomE1WLeGkY6lAVRkwQIIDQA) Makes a 2-column matrix of the minutes and seconds...zero. Then, if the minutes are non-zero, appends the matrix from a recursive call to itself with `m-1` minutes and 59 seconds. [Answer] # [C (gcc)](https://gcc.gnu.org/), 43 bytes ``` f(n){printf("%d ",n);n&&f(n%100?n-1:n-41);} ``` [Try it online!](https://tio.run/##LYxBCoMwFETXzSk@ASUflSbSjU2lBxEXJW1KFn5F001Dzp4m0M0wvDeM6d7GpGQFYdh2R94KXj2Bt4Sa6jrzSkl5p05dqbso1DEtD0cCIbC8Bm@mGUYIg2xB9Tn6QUbN7LqDKN6NUoODGxzu@1qt8AbP/5o1Ztc05etU1OTmTLaPPwTnqFlkMf0A "C (gcc) โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 11 bytes ``` ศท2แธ41*แบกยตยนรยฟ ``` [Try it online!](https://tio.run/##y0rNyan8///EdqOHO3pNDLUe7lp4aOuhnYcnHNr/X@fhjlagxOH2FCCZ9ahpzaOGuVZch5fre2tG/v8fbaCjYGkQq6MQbaijYARmGIFFAA "Jelly โ€“ Try It Online") *-1 thanks to Zion mycelia adamancy, and another -1 with inspiration from their suggestion* Uses flat integer I/O. Could almost be 10 (`แบก41$โ€™แป?ฦฌศท2`), but that fails for inputs under 41. ``` ยตยนรยฟ Collect results to (and through) 0 from: 41* raise 41 to the power of ศท2แธ if the number is divisible by 100, แบก and take its absolute difference with that. ``` [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` f=lambda m,s:m+1and[[m,s]]+f(m-0**s,(s or 60)-1)or[] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVen2CpX2zAxLyU6GsiOjdVO08jVNdDSKtbRKFbIL1IwM9DUNdTML4qO/V9QlJlXopGmYaSjYGmgqfkfAA "Python 3 โ€“ Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` (|/){x-$[*|x;!2;1 -59]}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9Ko0desrtBVidaqqbBWNLI2VNA1tYytjeHiSlMwULA0AFKGCkYgygjIAwAuVwsm) -1 byte thanks to @dzaima! -3 bytes thanks to @coltim! ## Explanation Input is *l*. * `(|/){...}\` while *l* is not `0 0` (keeping intermediate results)... + `x-...` decrement the timer by... - `$[*|x;...;...]` if seconds > 0... * `!2` equivalent to `0 1`, so `[x[0]-0, x[1]-1]` * `1 -59` otherwise reset seconds, so `[x[0]-1, x[1]-(-59)]` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` โฝโŒŠฮปโ‚แธŠ40*โ€บ-;ล€ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb3ijIrOu+KCgeG4ijQwKuKAui07xYAiLCIiLCIxMjAiXQ==) Port of Jelly answer. Takes single integer and outputs list of ints. [16 bytes taking second and minute](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgHZcIuKBsOKAucqAxps2MMqBdlwiO8OeZkoiLCIiLCI5MFxuMiJd). [Answer] # [C (GCC)](https://gcc.gnu.org), 78 bytes ``` main(h,m){for(scanf("%d%d",&h,&m);h+m;m?--m:--h&(m=59))printf("%d %d\n",h,m);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6Fjf9chMz8zQydHI1q9PyizSKkxPz0jSUVFNUU5R01DJ01HI1rTO0c61z7XV1c610dTPUNHJtTS01NQuKMvNKwCoVVFNi8pR0QEZY10JMhRq-YImRgqUBhA0A) [Answer] # Rust, ~~113~~ 100 bytes ``` |t:(u8,u8)|(0..t.0*60+t.1).scan(t,|t,_|Some((*t,*t=match t{(n,0)=>(*n-1,59),(m,s)=>(*m,*s-1)}).0)); ``` Had to increase it to follow rules more strictly. Skips the (0,0) at the end. [Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9d972ee65f42024a93f290b27fce2a6a) [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 36 bytes ``` ,+>,+<[->[-<.>.]>----[<+>----]<---<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fR9tOR9smWtcuWtdGz04v1k4XCKJttMF0rA2QsIn9/z8pEQA "brainfuck โ€“ Try It Online") There are no separators and output is just `hours minutes hours minutes ...` in form of bytes. Separator `-1` can be added at the cost of 7 bytes (totaling 43 bytes): ``` ->,+>,+<[->[-<.>.<<.>>]>----[<+>----]<---<] ``` Explanation: ``` ,+ load hours >,+ load minutes <[- loop through all hours >[- loop through all minutes <.>. print hours and minutes ] >----[<+>----]<---< set minutes to 60; constant is take from esolangs wiki ] ``` [Answer] # [HBL](https://github.com/dloscutoff/hbl), 15.5 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md) ``` 1'.(?,('?.(-,)).('?(-.)(-'-*))? ``` Takes the minutes and seconds as separate arguments to the main program; outputs a list of two-number lists. [Try it here!](https://dloscutoff.github.io/hbl/?f=0&p=MScuKD8sKCc/LigtLCkpLignPygtLikoLSctKikpPw__&a=MQo3MA__) ### Explanation ``` 1'.(?,('?.(-,)).('?(-.)(-'-*))? 1 Cons '. the argument list to: (? If , the second argument (is nonzero): ('? ) Recursive call . with the same first argument (-,) and a decremented second argument Else if . the first argument (is nonzero): ('? ) Recursive call (-.) with a decremented first argument and a second argument of (- ) the difference between '- 64 * and 5 Else: ? Empty list ``` [Answer] # JavaScript (ES6), ~~42~~ 41 bytes Expects `(m)(s)`. Returns a list of `[minutes, seconds]` pairs. ``` m=>g=s=>~m?[[m,s],...g(s?s-1:m--&&59)]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/X1i7dttjWri7XPjo6V6c4VkdPTy9do9i@WNfQKldXV03N1FIz1io69n9yfl5xfk6qXk5@uoZXsL@fXnFJUWZeemZapUaahoGmhqWBpqaCtoJ6TJ66JhdexYaaGkZEKzaCmKz5HwA "JavaScript (Node.js) โ€“ Try It Online") [Answer] # Javascript, 49 bytes ``` let g=a=>([b,c]=a,(b+c)?[g([b-!c,c?c-1:59]),a]:a) ``` A recursive function that takes in an array like `[minutes, seconds]`, and repeatedly appends it to the array that contains the next values. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 40 bytes ``` n#m=(n,r m)?(r$n-1,r 59) r n=anyOf[0..n] ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9POddWI0@nSCFX016jSCVP1xDINrXU5CpSyLNNzKv0T4s20NPLi/2fm5iZp2CrYKSgrGBp8B8A "Curry (PAKCS) โ€“ Try It Online") This is a non-deterministic function whose return values are the all the ouputs. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [=ร_#ั‚ร–40*>- ``` I/O as integers. Outputs everything on a separated line to save bytes. [Try it online](https://tio.run/##yy9OTMpM/f8/@vAEZZeLTYenmRho2enW2mj@/29kafBfVzcvXzcnsaoSAA) or [verify all test cases](https://tio.run/##yy9OTMpM/f8/2vbwhHjli02Hp5kYaNnp/v9vZGnwX1c3L183J7GqEgA). **Explanation:** ``` [ # Loop indefinitely: = # Print the current number with newline (without popping) # (which will be the implicit input-integer in the first iteration) ร # Triplicate the value _ # Pop one, and if it's 0: # # Stop the infinite loop ั‚ร– # (Else) Pop another, and check if it's divisible by 100 40* # Multiply that by 40 > # Increase that by 1 - # Decrease the value by this ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes ``` {(x,'!y+1),+!x,60} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqNBRV6zUNtTU0Vas0DEzqOXiSos2sLY0iAXShtZGYNoIxAcAA50LJw==) Uses the fact that *outputted times can be returned in any order*. Using the descending order would costs 2 bytes: [`{(x,'|!y+1),|+!x,60}`](https://ngn.codeberg.page/k#eJxLs6rWqNBRr1Gs1DbU1KnRVqzQMTOo5eJKizawtjSIBdKG1kZg2gjEBwAsYgwf). [Answer] # [\*><>](https://github.com/redstarcoder/go-starfish), 64 bytes ``` c5*& 1+\ /!?)0:C31-1 < \r:?!;1-r~&:&/ >r:r:{ao\ R no" "n/ ``` [Try it online!](https://tio.run/##Ky5JLErLLM74/z/ZVEtNAQIMtWO49BXtNQ2snI0NdQ0VFGy4Yoqs7BWtDXWL6tSs1PS57IqsiqyqE/NjuIIU8vKVFJTy9P///5dfUJKZn1f8XzfT1kjB0gAA "*><> โ€“ Try It Online") I'd like to believe this could be golfed more, mostly in the output section, but this is as good as I could get it. Using the `-i` flag, the stack is initialize with `[<minutes>, <seconds>]`. Throughout the program, the "canon" seconds can be considered to be at the top of the stack, and minutes right below that. ``` Main loop: c5*& Push 60 onto the stack, and then pop it into a register 1+ Add 1 to the seconds, this way our starting time is printed correctly \ Mirror the IP down < Change IP direction to the left -1 Subtract one from our seconds C31 Go to the print function : Duplicate our seconds 0 Push 0 onto the stack ) Check if the seconds is greater than 0 !? If it is, IP continues left, wrapping back to our < instruction / Else, mirror the IP down \ Mirror the IP to the right r: Put the minutes on top of the stack and duplicate it ?!; If the minutes and the seconds are 0, end execution 1- Else, subtract one from the minutes r Put the seconds back on top of the stack ~ Remove the seconds &:& Take 60 out of the register, duplicate it, and pop that duplicate back into the register / Mirror the IP up into the < on line 2 Print function: > Change the IP direction to the right r: Reverse the stack, and duplicate the top value r: Repeat { Shift the stack to the left. Stack should look like [m, s, s, m] ao Print a newline \ mirror the IP down / Mirror the IP to the left n Pop the top of the stack, print it as a number o" " Print a space n Pop the top of the stack, print it as a number R Return the IP to where it was, maintaining current direction ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` โ†‘ฮฃยก?-41โ†ยฆ100 ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///ihpHOo8KhPy00MeKGkMKmMTAw////Mjkw "Husk โ€“ Try It Online") Port of [unrelated string's answer](https://codegolf.stackexchange.com/a/249147/95126): upvote that. Inputs & outputs as simple integers (so, no separator between minutes & seconds). ``` โ†‘ฮฃยก?-41โ†ยฆ100 ยก # apply function repeatedly, collect values in infinite list: ? # if: ยฆ100 # it's divisible by 100 -41 # then: subtract 41 โ† # else: decrement โ†‘ # finally, get longest prefix where function gives truthy result: ฮฃ # sum (of secs, mins) ``` --- Previous approach: # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` โ†‘ฮฃยก?ลผ-แธ‹2ศฏe59โ†โ†’โ† ``` [Try it online!](https://tio.run/##yygtzv7//1HbxHOLDy20P7pH9@GObqMT61NNLR@1TXjUNglI/v//P9rSQMcoFgA "Husk โ€“ Try It Online") Outputs as [[secs,mins]...], omitting [0,0] at the end. ``` ยก # apply function repeatedly, collect values in infinite list: ? # if: โ† # the first element is nonzero ลผ-แธ‹2 # then: zip-subtract 1,0 (binary digits of 2) ศฏe59 # else: make a 2-element list of 59 and โ†โ†’ # the last element, decremented โ†‘ # finally, get longest prefix where function gives truthy result: ฮฃ # sum (of secs, mins) ``` [Answer] # [J](http://jsoftware.com/), 25 24 bytes ``` (,.i.,])(,,/)60,"0/&i.~[ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXT0MvV0YjU1dHT0Nc0MdJQM9NUy9eqi/2ty@TnpKYClHeysNHXqTO0cdByqHazB0lypyRn5ChoGCmkKlgaa1hqGQIYRiGEEEfkPAA "J โ€“ Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~79~~ 74 bytes ``` \d+ $* \G1 1$'ยถ 1>`:.* :59$* %(r`1\G ยถ$`1 O^` (1*):(1{10})*(1*) $.1:$#2$.3 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLK8bdkMtQRf3QNi5DuwQrPS0uK1NLoLCqRlGCYYw716FtKgmGXP5xCVwahlqaVhqG1YYGtZpaIA6Xip6hlYqykYqe8f//xlZmlgA "Retina 0.8.2 โ€“ Try It Online") Takes input in `m:ss` format. Output includes both start and end times. Explanation: ``` \d+ $* ``` Convert to unary. ``` \G1 1$'ยถ ``` Count down to `0` minutes. ``` 1>`:.* :59$* ``` Subsequent minutes count down from `59`. ``` %(` ``` Apply the rest of the script to each minute individually. ``` r`1\G ยถ$`1 O^` ``` Count down to `0` seconds. ``` (1*):(1{10})*(1*) $.1:$#2$.3 ``` Convert to decimal. [Answer] # Rust, 67 bytes ``` |mut h,mut m,f:fn(u8,u8)|while h+m>0{f(h,m);if m<1{h-=1;m=60};m-=1} ``` This one takes a function pointer, and outputs by calling that function. [Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=da13f6662148b9c4400a82e6aeabd68f) ([without gist](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=fn%20main()%20%7B%0A%20%20%20%20let%20f%20%3D%20%7Cmut%20h%2Cmut%20m%2Cf%3Afn(u8%2Cu8)%7Cwhile%20h%2Bm%3E0%7Bf(h%2Cm)%3Bif%20m%3C1%7Bh-%3D1%3Bm%3D60%7D%3Bm-%3D1%7D%3B%0A%0A%20%20%20%20for%20((h%2C%20m)%2C%20expected_result)%20in%20%5B%0A%20%20%20%20%20%20%20%20((0%2C%2090)%2C%20vec!%5B(0%2C90)%2C%20(0%2C%2089)%2C%20(0%2C%2088)%2C%20(0%2C%2087)%2C%20(0%2C%2086)%2C%20(0%2C%2085)%2C%20(0%2C%2084)%2C%20(0%2C%2083)%2C%20(0%2C%2082)%2C%20(0%2C%2081)%2C%20(0%2C%2080)%2C%20(0%2C%2079)%2C%20(0%2C%2078)%2C%20(0%2C%2077)%2C%20(0%2C%2076)%2C%20(0%2C%2075)%2C%20(0%2C%2074)%2C%20(0%2C%2073)%2C%20(0%2C%2072)%2C%20(0%2C%2071)%2C%20(0%2C%2070)%2C%20(0%2C%2069)%2C%20(0%2C%2068)%2C%20(0%2C%2067)%2C%20(0%2C%2066)%2C%20(0%2C%2065)%2C%20(0%2C%2064)%2C%20(0%2C%2063)%2C%20(0%2C%2062)%2C%20(0%2C%2061)%2C%20(0%2C%2060)%2C%20(0%2C%2059)%2C%20(0%2C%2058)%2C%20(0%2C%2057)%2C%20(0%2C%2056)%2C%20(0%2C%2055)%2C%20(0%2C%2054)%2C%20(0%2C%2053)%2C%20(0%2C%2052)%2C%20(0%2C%2051)%2C%20(0%2C%2050)%2C%20(0%2C%2049)%2C%20(0%2C%2048)%2C%20(0%2C%2047)%2C%20(0%2C%2046)%2C%20(0%2C%2045)%2C%20(0%2C%2044)%2C%20(0%2C%2043)%2C%20(0%2C%2042)%2C%20(0%2C%2041)%2C%20(0%2C%2040)%2C%20(0%2C%2039)%2C%20(0%2C%2038)%2C%20(0%2C%2037)%2C%20(0%2C%2036)%2C%20(0%2C%2035)%2C%20(0%2C%2034)%2C%20(0%2C%2033)%2C%20(0%2C%2032)%2C%20(0%2C%2031)%2C%20(0%2C%2030)%2C%20(0%2C%2029)%2C%20(0%2C%2028)%2C%20(0%2C%2027)%2C%20(0%2C%2026)%2C%20(0%2C%2025)%2C%20(0%2C%2024)%2C%20(0%2C%2023)%2C%20(0%2C%2022)%2C%20(0%2C%2021)%2C%20(0%2C%2020)%2C%20(0%2C%2019)%2C%20(0%2C%2018)%2C%20(0%2C%2017)%2C%20(0%2C%2016)%2C%20(0%2C%2015)%2C%20(0%2C%2014)%2C%20(0%2C%2013)%2C%20(0%2C%2012)%2C%20(0%2C%2011)%2C%20(0%2C%2010)%2C%20(0%2C%209)%2C%20(0%2C%208)%2C%20(0%2C%207)%2C%20(0%2C%206)%2C%20(0%2C%205)%2C%20(0%2C%204)%2C%20(0%2C%203)%2C%20(0%2C%202)%2C%20(0%2C%201)%2C%20(0%2C%200)%5D)%2C%0A%20%20%20%20%20%20%20%20((1%2C%2020)%2C%20vec!%5B(1%2C%2020)%2C%20(1%2C%2019)%2C%20(1%2C%2018)%2C%20(1%2C%2017)%2C%20(1%2C%2016)%2C%20(1%2C%2015)%2C%20(1%2C%2014)%2C%20(1%2C%2013)%2C%20(1%2C%2012)%2C%20(1%2C%2011)%2C%20(1%2C%2010)%2C%20(1%2C%209)%2C%20(1%2C%208)%2C%20(1%2C%207)%2C%20(1%2C%206)%2C%20(1%2C%205)%2C%20(1%2C%204)%2C%20(1%2C%203)%2C%20(1%2C%202)%2C%20(1%2C%201)%2C%20(1%2C%200)%2C%20(0%2C%2059)%2C%20(0%2C%2058)%2C%20(0%2C%2057)%2C%20(0%2C%2056)%2C%20(0%2C%2055)%2C%20(0%2C%2054)%2C%20(0%2C%2053)%2C%20(0%2C%2052)%2C%20(0%2C%2051)%2C%20(0%2C%2050)%2C%20(0%2C%2049)%2C%20(0%2C%2048)%2C%20(0%2C%2047)%2C%20(0%2C%2046)%2C%20(0%2C%2045)%2C%20(0%2C%2044)%2C%20(0%2C%2043)%2C%20(0%2C%2042)%2C%20(0%2C%2041)%2C%20(0%2C%2040)%2C%20(0%2C%2039)%2C%20(0%2C%2038)%2C%20(0%2C%2037)%2C%20(0%2C%2036)%2C%20(0%2C%2035)%2C%20(0%2C%2034)%2C%20(0%2C%2033)%2C%20(0%2C%2032)%2C%20(0%2C%2031)%2C%20(0%2C%2030)%2C%20(0%2C%2029)%2C%20(0%2C%2028)%2C%20(0%2C%2027)%2C%20(0%2C%2026)%2C%20(0%2C%2025)%2C%20(0%2C%2024)%2C%20(0%2C%2023)%2C%20(0%2C%2022)%2C%20(0%2C%2021)%2C%20(0%2C%2020)%2C%20(0%2C%2019)%2C%20(0%2C%2018)%2C%20(0%2C%2017)%2C%20(0%2C%2016)%2C%20(0%2C%2015)%2C%20(0%2C%2014)%2C%20(0%2C%2013)%2C%20(0%2C%2012)%2C%20(0%2C%2011)%2C%20(0%2C%2010)%2C%20(0%2C%209)%2C%20(0%2C%208)%2C%20(0%2C%207)%2C%20(0%2C%206)%2C%20(0%2C%205)%2C%20(0%2C%204)%2C%20(0%2C%203)%2C%20(0%2C%202)%2C%20(0%2C%201)%2C%20(0%2C%200)%5D)%2C%0A%20%20%20%20%20%20%20%20((2%2C%2090)%2C%20vec!%5B(2%2C%2090)%2C%20(2%2C%2089)%2C%20(2%2C%2088)%2C%20(2%2C%2087)%2C%20(2%2C%2086)%2C%20(2%2C%2085)%2C%20(2%2C%2084)%2C%20(2%2C%2083)%2C%20(2%2C%2082)%2C%20(2%2C%2081)%2C%20(2%2C%2080)%2C%20(2%2C%2079)%2C%20(2%2C%2078)%2C%20(2%2C%2077)%2C%20(2%2C%2076)%2C%20(2%2C%2075)%2C%20(2%2C%2074)%2C%20(2%2C%2073)%2C%20(2%2C%2072)%2C%20(2%2C%2071)%2C%20(2%2C%2070)%2C%20(2%2C%2069)%2C%20(2%2C%2068)%2C%20(2%2C%2067)%2C%20(2%2C%2066)%2C%20(2%2C%2065)%2C%20(2%2C%2064)%2C%20(2%2C%2063)%2C%20(2%2C%2062)%2C%20(2%2C%2061)%2C%20(2%2C%2060)%2C%20(2%2C%2059)%2C%20(2%2C%2058)%2C%20(2%2C%2057)%2C%20(2%2C%2056)%2C%20(2%2C%2055)%2C%20(2%2C%2054)%2C%20(2%2C%2053)%2C%20(2%2C%2052)%2C%20(2%2C%2051)%2C%20(2%2C%2050)%2C%20(2%2C%2049)%2C%20(2%2C%2048)%2C%20(2%2C%2047)%2C%20(2%2C%2046)%2C%20(2%2C%2045)%2C%20(2%2C%2044)%2C%20(2%2C%2043)%2C%20(2%2C%2042)%2C%20(2%2C%2041)%2C%20(2%2C%2040)%2C%20(2%2C%2039)%2C%20(2%2C%2038)%2C%20(2%2C%2037)%2C%20(2%2C%2036)%2C%20(2%2C%2035)%2C%20(2%2C%2034)%2C%20(2%2C%2033)%2C%20(2%2C%2032)%2C%20(2%2C%2031)%2C%20(2%2C%2030)%2C%20(2%2C%2029)%2C%20(2%2C%2028)%2C%20(2%2C%2027)%2C%20(2%2C%2026)%2C%20(2%2C%2025)%2C%20(2%2C%2024)%2C%20(2%2C%2023)%2C%20(2%2C%2022)%2C%20(2%2C%2021)%2C%20(2%2C%2020)%2C%20(2%2C%2019)%2C%20(2%2C%2018)%2C%20(2%2C%2017)%2C%20(2%2C%2016)%2C%20(2%2C%2015)%2C%20(2%2C%2014)%2C%20(2%2C%2013)%2C%20(2%2C%2012)%2C%20(2%2C%2011)%2C%20(2%2C%2010)%2C%20(2%2C%209)%2C%20(2%2C%208)%2C%20(2%2C%207)%2C%20(2%2C%206)%2C%20(2%2C%205)%2C%20(2%2C%204)%2C%20(2%2C%203)%2C%20(2%2C%202)%2C%20(2%2C%201)%2C%20(2%2C%200)%2C%20(1%2C%2059)%2C%20(1%2C%2058)%2C%20(1%2C%2057)%2C%20(1%2C%2056)%2C%20(1%2C%2055)%2C%20(1%2C%2054)%2C%20(1%2C%2053)%2C%20(1%2C%2052)%2C%20(1%2C%2051)%2C%20(1%2C%2050)%2C%20(1%2C%2049)%2C%20(1%2C%2048)%2C%20(1%2C%2047)%2C%20(1%2C%2046)%2C%20(1%2C%2045)%2C%20(1%2C%2044)%2C%20(1%2C%2043)%2C%20(1%2C%2042)%2C%20(1%2C%2041)%2C%20(1%2C%2040)%2C%20(1%2C%2039)%2C%20(1%2C%2038)%2C%20(1%2C%2037)%2C%20(1%2C%2036)%2C%20(1%2C%2035)%2C%20(1%2C%2034)%2C%20(1%2C%2033)%2C%20(1%2C%2032)%2C%20(1%2C%2031)%2C%20(1%2C%2030)%2C%20(1%2C%2029)%2C%20(1%2C%2028)%2C%20(1%2C%2027)%2C%20(1%2C%2026)%2C%20(1%2C%2025)%2C%20(1%2C%2024)%2C%20(1%2C%2023)%2C%20(1%2C%2022)%2C%20(1%2C%2021)%2C%20(1%2C%2020)%2C%20(1%2C%2019)%2C%20(1%2C%2018)%2C%20(1%2C%2017)%2C%20(1%2C%2016)%2C%20(1%2C%2015)%2C%20(1%2C%2014)%2C%20(1%2C%2013)%2C%20(1%2C%2012)%2C%20(1%2C%2011)%2C%20(1%2C%2010)%2C%20(1%2C%209)%2C%20(1%2C%208)%2C%20(1%2C%207)%2C%20(1%2C%206)%2C%20(1%2C%205)%2C%20(1%2C%204)%2C%20(1%2C%203)%2C%20(1%2C%202)%2C%20(1%2C%201)%2C%20(1%2C%200)%2C%20(0%2C%2059)%2C%20(0%2C%2058)%2C%20(0%2C%2057)%2C%20(0%2C%2056)%2C%20(0%2C%2055)%2C%20(0%2C%2054)%2C%20(0%2C%2053)%2C%20(0%2C%2052)%2C%20(0%2C%2051)%2C%20(0%2C%2050)%2C%20(0%2C%2049)%2C%20(0%2C%2048)%2C%20(0%2C%2047)%2C%20(0%2C%2046)%2C%20(0%2C%2045)%2C%20(0%2C%2044)%2C%20(0%2C%2043)%2C%20(0%2C%2042)%2C%20(0%2C%2041)%2C%20(0%2C%2040)%2C%20(0%2C%2039)%2C%20(0%2C%2038)%2C%20(0%2C%2037)%2C%20(0%2C%2036)%2C%20(0%2C%2035)%2C%20(0%2C%2034)%2C%20(0%2C%2033)%2C%20(0%2C%2032)%2C%20(0%2C%2031)%2C%20(0%2C%2030)%2C%20(0%2C%2029)%2C%20(0%2C%2028)%2C%20(0%2C%2027)%2C%20(0%2C%2026)%2C%20(0%2C%2025)%2C%20(0%2C%2024)%2C%20(0%2C%2023)%2C%20(0%2C%2022)%2C%20(0%2C%2021)%2C%20(0%2C%2020)%2C%20(0%2C%2019)%2C%20(0%2C%2018)%2C%20(0%2C%2017)%2C%20(0%2C%2016)%2C%20(0%2C%2015)%2C%20(0%2C%2014)%2C%20(0%2C%2013)%2C%20(0%2C%2012)%2C%20(0%2C%2011)%2C%20(0%2C%2010)%2C%20(0%2C%209)%2C%20(0%2C%208)%2C%20(0%2C%207)%2C%20(0%2C%206)%2C%20(0%2C%205)%2C%20(0%2C%204)%2C%20(0%2C%203)%2C%20(0%2C%202)%2C%20(0%2C%201)%2C%20(0%2C%200)%5D)%2C%0A%20%20%20%20%5D%20%7B%0A%20%20%20%20%20%20%20%20f(h%2C%20m%2C%20print)%3B%0A%20%20%20%20%20%20%20%20let%20answer%20%3D%20unsafe%20%7B%20%26mut%20ANSWER%20%7D%3B%0A%20%20%20%20%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20answer)%3B%0A%20%20%20%20%20%20%20%20answer.push((0%2C%200))%3B%20%20%2F%2F%20(0%2C%200)%20at%20the%20end%20is%20optional%0A%20%20%20%20%20%20%20%20assert_eq!(answer%2C%20%26expected_result)%3B%0A%20%20%20%20%20%20%20%20answer.clear()%3B%0A%20%20%20%20%7D%0A%7D%0A%0Astatic%20mut%20ANSWER%3A%20Vec%3C(u8%2C%20u8)%3E%20%3D%20Vec%3A%3Anew()%3B%0Afn%20print(h%3A%20u8%2C%20m%3A%20u8)%20%7B%0A%20%20%20%20unsafe%20%7B%20%26mut%20ANSWER%20%7D.push((h%2C%20m))%3B%0A%7D%0A)), for which I ruthlessly plagiarised [mousetale's test harness](https://codegolf.stackexchange.com/a/249148/43394). Without that, I probably wouldn't've written this answer. There's a shorter (60 byte) version, if you replace the `while h+m>0` with `loop`. That only works in debug mode, though โ€“ in which it exits the loop by panicking โ€“ so I don't know that it counts. [Answer] # [Zsh](https://www.zsh.org/), 46 bytes ``` m=({$1..0}) echo $m[1]:{$2..0} ${^m:1}:{59..0} ``` [Try it online!](https://tio.run/##qyrO@J@moanxP9dWo1rFUE/PoFaTKzU5I19BJTfaMNaqWsUIJKagUh2Xa2VYa1Vtagni/9fk4uJKUzBQMDQAUoYKlpb/AQ "Zsh โ€“ Try It Online") The `^` flag sets the `RC_EXPAND_PARAM` flag for that expansion. The list is needed because `{a..b}` never expands to zero arguments, while `${^foo}` does. [Answer] # [Factor](https://factorcode.org/) + `math.unicode pair-rocket`, 60 bytes ``` [ [ .s dup last 0 = 1 => -59 "\0"? v- dup ฮฃ 0 > ] loop . ] ``` [Try it online!](https://tio.run/##JcuxCsIwFEZhXPsUP91T6iCi0jqKi4s41Q4hvWJpTGJyWxDxaXwfXynWOh4@zkUqtj6ejvvDbg3nifnhfGsYHXlDGoHuPRlFAU62XnirOmLcJF@zgX5v@EdvWmUbmgKbJHlijmWOV6xQIQtoegctAyNHMVJRQixWSM/5LN1iEJN/3qOWqKGtdchQRyW1jl8 "Factor โ€“ Try It Online") Outputs times to standard output in the format `{ minutes seconds }`, one per line, in the order they would be seen on the microwave display. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` ๏ผฉ๏ผฅโŠ•ฮธ๏ผฅโŽ‡โ€นฮน๏ผฉฮธโถโฐโŠ•ฮทโŸฆฮนฮป ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQMMzL7koNTc1ryQ1RaNQU0cBJBaSWpSXWFSp4ZNaXKyRqaMAVlyoCZQ1M9BRQNaRARKMBirJidUEAuv//40VzCz/65blAAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes minutes and seconds as separate input and outputs a list of lists of lists of minute and second pairs in ascending order. Explanation: ``` ฮธ First input โŠ• Incremented ๏ผฅ Map minutes over implicit range ฮน Current minute โ€น Is less than ฮธ First input ๏ผฉ Cast to integer โŽ‡ If true then โถโฐ Literal integer `60` else ฮท Second input โŠ• Incremented ๏ผฅ Map seconds over implicit range โŸฆฮนฮป Minute and second as a list ๏ผฉ Cast to string Implicitly print ``` [Answer] # [Perl 5](https://www.perl.org/) `-a`, 43 bytes ``` do{say"@F";@F=(--$_,59)if!$F[1]--}until$_<0 ``` [Try it online!](https://tio.run/##K0gtyjH9/z8lv7o4sVLJwU3J2sHNVkNXVyVex9RSMzNNUcUt2jBWV7e2NK8kM0cl3sbg/38jBUuDf/kFJZn5ecX/dRP/6/qa6hkYGgAA "Perl 5 โ€“ Try It Online") Minutes and seconds are space separated in both input and output. [Answer] # [Julia](http://julialang.org/), 39 bytes ``` m>s=show((m,s))~s<1 ? -1<m-1>60 : m>s-1 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P9eu2LY4I79cQyNXp1hTs67YxlDBXkHX0CZX19DOzEDBSgGoQtfwv6GdpeV/AA "Julia 1.0 โ€“ Try It Online") Takes input as two arguments (`1>90`), prints the values as tuples and ends with an error [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` WsQQ=?eAQ,GtH,tG59 ``` [Try it online!](https://tio.run/##K6gsyfj/P7w4MNDWPtUxUMe9xEOnxN3U8v//aEMdS4NYAA "Pyth โ€“ Try It Online") Doesn't include [0,0] ``` WsQQ=?eAQ,GtH,tG59 (Q implicitly initialized as the input) WsQ While sum(Q) > 0: Q Output Q AQ Set [G,H] = Q (minutes and seconds, respectively) = Update Q to the following: ?e Q If (seconds) > 0: ,GtH [(minutes), (seconds) - 1] Else: ,tG59 [(minutes) - 1, 59] ``` --- If single-integer output is allowed: ### Pyth, 15 bytes ``` WQQ=-Q^41!%Q100 ``` [Try it online!](https://tio.run/##K6gsyfj/Pzww0FY3MM7EUFE10NDA4P9/Q0sDAA "Pyth โ€“ Try It Online") ]
[Question] [ What tips do people have for golfing in TeX/LaTeX? Please post one tip per answer, each at least somewhat specific to TeX/LaTeX. --- Context: I noticed [this answer](https://codegolf.stackexchange.com/a/123693/3845) and that there is no tips question for TeX/LaTeX, so I'm creating this one. There's some overlap with the narrower question [tips for golfing in TikZ](https://codegolf.stackexchange.com/questions/109429/tips-for-golfing-in-tikz) (as TikZ is a specific macro package on top of TeX/LaTeX): answers to this question will probably also apply there, but not the other way around. [Answer] **Consider internal LaTeX macros rather than the documented ones** For example, `\roman` is a documented LaTeX macro that works on LaTeX counters. To turn `42` into `XLIV` you'd have to use something like ``` \newcounter{z} \setcounter{z}{42} \roman{z} ``` Instead, by looking up how `\roman` is implemented (use `\show\roman` to get this interactively, instead of reading the source files), one can see that it's implemented in terms of a useful macro called `\@roman`, and instead use that directly: ``` \catcode`@11 \@roman{42} ``` `\catcode`@11` is the golfy way of writing [`\makeatletter`](https://tex.stackexchange.com/questions/8351/what-do-makeatletter-and-makeatother-do) (clean way in LaTeX) or `\catcode`\@=11` (clean way in plain TeX). It's needed only once at the beginning, after this you can use macro names containing `@`. [Answer] **`~` can be used as a macro** (as can other active characters) **Example** Before: ``` \def\a{...some definition...} ... use \a... ``` After: ``` \def~{...some definition...} ... use ~... ``` **Explanation**: Generally macros in TeX are โ€œcontrol sequencesโ€: you can define `\something` or `\a`. But you can go even shorter, by using an active character. The only active character that is present by default (in plain TeX / LaTeX) is `~` (used for โ€œtiesโ€, i.e. defined as `\penalty \@M \` in plain TeX (a penalty of 10000 followed by a space), and as `\nobreakspace {}` in LaTeX). But nothing stops you from redefining it for whatever purpose you need. **Further**: you can do the same with any other character by setting its catcode to `\active` (13). For example, making `Z` an active character has a "cost" of 12 bytes: `\catcode`Z13`. Then you can use simply `Z` everywhere instead of a macro like `\z`. For some characters that start out with a special meaning, the direct backtick approach doesn't work and you need one more character: `\catcode`\Z13` or `\catcode90=13`. [Answer] **`\def` can match fixed patterns** Let's say you had `\def\a #1 #2 {...some definition here...}`. Then when you call it on a string like `\a Act42, Scene26`, inside the macro the arguments may be assigned like #1 <- `Act42,`, #2 <- `Scene26` and then you'd have to do some further work to extract out the relevant parts. Instead, one could directly write ``` \def\a Act#1, Scene#2 {...some definition here...} ``` and then calling it as `\a Act42, Scene26` would directly set #1 <- `42` and #2 <- `26`. (This is basically the definition of `\def`, but it's easy to forget as one doesn't typically do this in LaTeX, preferring to pass arguments into `{}` as if they were function calls.) [Answer] **Choosing between plain TeX and LaTeX** A lot can be said about this, but in short, compare a typical plain TeX document that prints "Hello" with a typical LaTeX document for the same: ``` Hello \bye ``` versus ``` \documentclass{article} \begin{document} Hello \end{document} ``` The "cost" of LaTeX (wrt code golf) is obvious; the "benefit" of course is that LaTeX comes with a library of many pre-written macros and packages, some of which may be useful for the task at hand. [Answer] ### `\input ...` is shorter than `\usepackage{...}` For example, you can write ``` \input color ``` instead of ``` \usepackage{color} ``` which is 6 less bytes. [Answer] **If using LaTeX, use a short `documentclass`** (idea by [Chris H](https://codegolf.stackexchange.com/users/44821/chris-h)) Instead of starting with the typical ``` \documentclass{article} ``` one can choose shorter document classes like `book` or even ``` \documentclass{ecv} ``` or ``` \documentclass{tui} ``` [Answer] Creating an environment called `myenvironment` generates the commands `\myenvironment` and `\endmyenvironment`. These are used internally to begin and end the environment. In some cases they can be used as shortcuts. For example, instead of ``` \begin{itemize} \item abc \end{itemize} ``` one can do ``` \itemize \item abc \enditemize ``` Not supported, not reliable, doesn't work in all cases, use at your own peril, etc. etc. [Answer] `\usepackage{packagea,packageb,packagec}` works, so long as you're not passing options to the packages. [Answer] Run lines together. Line breaks are rarely needed in LaTeX/TeX, as compared to many long-form languages. [Answer] **Use local `{` ... `}` groups wisely** As pointed out in [this answer](https://codegolf.stackexchange.com/a/123905/71326), active characters like `~` can be used as a macro name. Unfortunately, `~` is the only active character by default, and changing the catcode for another character is expensive: `\catcode`!13` takes 12 bytes. If the new macro definition is only needed in a small region of your code, local groups can be a solution. When TeX enters a new local group opened by `{`, it creates a new grouping level on the internal save stack. This means that all current macros and registers are saved. Any modifications to them (unless explicitly marked as `\global`) are now only being active until the group is closed by `}`. This means that `~` can be redefined within a group, used there with the new definition, and the old defintion will automatically be restored after the group has finished. Here's an example: ``` \def~{abc} ~ -- {\def~{123}~} -- ~ ``` This outputs > > abc - 123 - abc > > > An interesting side effect of this grouping mechanism is that the old values are still available inside the group until they are changed there. To illustrate that, imagine we want to print a number of characters based on the value of a counter, pad them with spaces up to a fixed length, and go on with the original counter value. This could be achieved by the following: ``` \newcount\x \x=3 Print a char \the\x\ times, {\x=-\x \advance\x 10 pad with \the\x\ spaces,} and go on with x=\the\x. ``` which outputs > > Print a char 3 times, pad with 7 spaces, and go on with x=3. > > > This grouping behaviour is especially important if you want to use TeX's standard macros for looping `\loop ... \repeat` nested. These macros define internal commands and use them for determining how to proceed. Nesting them without putting the inner loop into braces will confuse the internal commands and lead to unexpected behaviour. [Answer] Some macros that you might expect to need braces round their arguments actually don't, especially when used inside another macro with `#1`-style arguments. Most macros only need braces if there's more than one token (character or control sequence) in the argument. ``` \mymacro1 % equivalent to \mymacro{1} \mymacro{12} % equivalent to \mymacro{12} \mymacro a % equivalent to \mymacro{a} \mymacro{ab} % equivalent to \mymacro{ab} \mymacro\foo % equivalent to \mymacro{\foo} \mymacro{\foo x} % equivalent to \mymacro{\foo x} ``` [Answer] If you need to use the same macro with a long name several times, you can use `\let` to define a shorter alias. ``` \let\a\mymacrowithalongname \a{foo}\a{bar}\a{qux} ``` This saves two bytes on `\def\a{\mymacrowithalongname}`, if you don't need multiple tokens in the definition. Instead of a macro name, you can have an [active character](https://codegolf.stackexchange.com/a/123905) to save on backslashes. Note that `\let` doesn't only work with macro names but also with built-in primitives. For example, if you use a lot of `\ifnum ... \fi` constructs in your code, defining `\let\i\ifnum` and instead using `\i ... \fi` could save you a few bytes. This even works for `\let` itself: `\let\l\let`. [Answer] The advancement of counters, such as ``` \advance\u by 1 \multiply\u by 3 \divide\u by 2 ``` also work as ``` \advance\u1 % \u = \u + 1 \advance\u-1 % \u = \u - 1 \multiply\u3 % \u = \u * 3 \multiply\u\u % \u = \u * \u \divide\u2 % \u = \u / 2 ``` The same principle also works for initialisation: ``` \newcount\u\u1 ``` sets the counter \u to 1. Do note that these do need a whitespace character (linebreak or space) after them (or a `\relax`, but whitespace does the same) so the next command won't be ignored. For example, ``` \u1\the\u ``` does NOT print \u, but ignores the `\the` command. [Answer] `\enddocument` instead of `\end{document}` saves two characters ]
[Question] [ Given a two dimensional matrix of 0 and 1s. Find the number of island for 1s and 0s where neighbours are only in the horizontal and vertical. ``` Given input: 1 1 1 0 1 1 1 0 output = 1 1 Number of 1s island = 1 xxx- xxx- Number of 0s island = 1 ---x ---x ------------------------------ Given input: 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 output = 2 2 Number of 1s island = 2 ---- xxxx <-- an island of 1s ---- xxxx <-- another island of 1s Number of 0s island = 2 xxxx <-- an island ---- xxxx <-- another island ---- ------------------------------ Given input: 1 0 0 0 0 0 0 0 1 output = 2 1 Number for 1's island = 2: x-- <-- an island of 1s --- --x <-- an island of 1s Number of 0's island = 1: -xx \ xxx > 1 big island of 0s xx- / ------------------------------ Given input: 1 1 0 1 0 0 output = 1 1 Number for 1's island =1 and number of 0's island = 1 ------------------------------ Given input: 1 1 1 1 output = 1 0 Number for 1's island =1 and number of 0's island = 0 ``` [Answer] # [J](http://jsoftware.com/), 57 bytes ``` ,&([:(0#@-.~~.@,)](*@[*[:>./((,-)#:i.3)|.!.0])^:_ i.@$)-. ``` [Try it online!](https://tio.run/##ZY7BCsIwEETv/YrVBpuUZE3SegkoAcGTJ6@lehCL9eIPSH89pmlSwTIkTMLb2Xm5NRYd7A0UwEGC8UcgHC/nk@Mb2hgqcytwGNBy1tLSNmVjDrillAuWmx4r9sEVypZdzQ16tIQJdCzLHvfnG5SXMNCBhhpIeCq/IJkJ0l4BqgMkoyKkYPGTxmJ25UVCrkxsuNSiQxU7hCiZ9o82AnoE/uJ3XmQuo@LomD9Z9bPzbyrqvg "J โ€“ Try It Online") This is one of those where the idea is incredibly simple (and I think fun), but executing it had some mechanical lengthiness which masks the simplicity... eg, shifting the original matrix in all directions with 0 fill is the verbose `((,-)#:i.3) |.!.0`. It's likely this mechanical lengthiness can be golfed further, and I may try tomorrow evening, but I'll post the crux of it now. Say our input is: ``` 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 ``` We start with a matrix of unique integers the same size: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` Then for each cell we find the max of all its neighbors, and multiply by the input mask: ``` 0 0 0 0 8 9 10 11 0 0 0 0 13 14 15 15 ``` We iterate this process until the matrix stops changing: ``` 0 0 0 0 11 11 11 11 0 0 0 0 15 15 15 15 ``` And then count the number of unique, non-zero elements. That tells us the number of 1-islands. We apply the same process to "1 minus the input" to get the number of 0-islands. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29~~ 28 bytes[SBCS](https://github.com/abrudz/SBCS) -1 thanks to @Adรกm ``` {โ‰ขโˆชโˆจ.โˆงโจโฃโ‰ก2>+/โ†‘|โˆ˜.-โจโธโต}ยจโŠ‚,~โˆ˜โŠ‚ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/6sfdS561LHqUccKvUcdyx/1rnjUu/hR50IjO239R20Tax51zNDTBYvueNS7tfbQikddTTp1QFEg/T8NaMKj3r5HXc2H1hsDVQNNLS5KBpIlGZnF/0uAstVATUALioDMtEe9u6yAGChS9Ki7RT0/W72WSwOoS8NQAQQNNOEMTQUMUAKSgig3UABDmHJDTUwRzRIFIwUjmOlgKQMEZYhhAUi5IcIxYJMMsDsEzTFg@w2xGImm3AAA "APL (Dyalog Unicode) โ€“ Try It Online") `โŠ‚,~โˆ˜โŠ‚` the matrix and its negation `{` `}ยจ` for each of them do `โธโต` list of pairs of coords of 1s `+/โ†‘|โˆ˜.-โจ` matrix of manhattan distances `2>` neighbour matrix `โˆจ.โˆงโจโฃโ‰ก` transitive closure `โ‰ขโˆช` number of unique rows [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 12 bytes ``` ,G@-K&1ZIugs ``` [Try it online!](https://tio.run/##y00syfn/X8fdQddbzTDKszS9@P//aEMFEDSwVoAyYgE) Or [verify all test cases](https://tio.run/##y00syfmf8F/H3UHXW80wyrM0vfh/rLqurnqES1RFyP9oQwUQNLBWgDJiuaINFMAQJmRorYAuAlRkCBEwQFAQUahZBmCTwJpB6gE). ### Explanation ``` , % Do twice G % Push input @ % Push iteration index: first 0, then 1 - % Subtract. This converts 0 and 1 into -1 and 0 in the second iteration K % Push 4 &1ZI % Label connected components of matrix using 4-connectedness. Zeros in the % matrix are background. This replaces the nonzeros by 1, 2, 3, ..., where % each number defines a connected component u % Unique values. This gives [0; 1; 2; ..., L], where L is the number of % connected components. g % Convert nonzeros to 1 s % Sum. This gives L, to be output % End (implicit). % Display stack (implicit) ``` [Answer] # JavaScript (ES7), ~~138 ... 107~~ 106 bytes Returns an array `[ones, zeros]`. ``` f=(m,X,Y,V=.5,c=[0,0])=>m.map((r,y)=>r.map((v,x)=>V-v|(x-X)**2+(y-Y)**2>1||f(m,x,y,v,r[c[v^1]++,x]=2)))&&c ``` [Try it online!](https://tio.run/##fY/LCoMwEEX3fkVWkuioidBl/AxRQgqSamnxhZag4L/bWCFYEJnNHMK5ufMudDGq4dV/grZ7lOtacdxABjmkPLyB4oIClYQnTdgUPcYDzAaGHTRMBtJAL3gKMuJ5sY/nIN@WhC1LZZImmEHDIJTQdyZ9HybJY0KI66pVde3Y1WVYd09cYYGiCAnEADEkHYQEg22ohCM4khDHOTVjQPFumsrbHE22w@nLdaZtYz36v14G/J9jP6bXpxiLWsuW/RnrFw "JavaScript (Node.js) โ€“ Try It Online") ### How? We use a recursive function. During the initial call, we look for \$0\$'s and \$1\$'s. Whenever we find such a starting point, we increment the corresponding island counter (\$c[0]\$ or \$c[1]\$) and enter the recursive phase to flood-fill the area of similar adjacent cells with \$2\$'s. To save bytes, the exact same code is used for both the root iteration and the recursive iterations, but it behaves a bit differently. During the first iteration: * We start with \$V=0.5\$ so that \$V-v\$ is rounded to \$0\$ for both \$v=0\$ and \$v=1\$, thanks to the bitwise OR. * \$X\$ and \$Y\$ are undefined and the computed quadrance \$(x-X)^2+(y-Y)^2\$ evaluates to *NaN*. It forces the inequality test to fail, no matter the value of \$(x,y)\$. During the recursive iterations: * The parameter \$c\$ is set to an integer (\$2\$) instead of an array. Because numbers are objects in JS, the expression `c[v ^ 1]++` is valid if \$c\$ is a number -- although it has no effect at all. It means that we can execute this statement unconditionally, without knowing if we're currently looking for starting points or flood-filling. ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input binary matrix X, Y, // X, Y = coordinates of the previous cell, initially undefined V = .5, // V = value of the previous cell, initially set to 0.5 // so that the integer part of V - v is 0 for v = 0 or 1 c = [0, 0] // c[] = array of counters of 1's and 0's islands ) => // (or an integer when called recursively) m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each value v at position x in r[]: V - v | // abort if |V - v| โ‰ฅ 1 (x - X) ** 2 + // or X and Y are defined and the quadrance between (y - Y) ** 2 // (X, Y) and (x, y) > 1 || // is greater than 1 f( // otherwise, do a recursive call to f: m, // leave m[] unchanged x, y, // pass the new coordinates v, // pass the new reference value r[c[v ^ 1]++, // increment c[v ^ 1] (ineffective if c is an integer) x // and set the current cell ... ] = 2 // ... to 2 ) // end of recursive call ) // end of inner map() ) && c // end of outer map(); return c ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~64~~ 62 bytes ``` Max@MorphologicalComponents[#,CornerNeighbors->1<0]&/@{#,1-#}& ``` [Try it online!](https://tio.run/##ZYzBCsMgEER/RQjkEAzRe1uE0NxSei892CBRiG4wHgLit1trmxAoc9jZtzujuZNCc6cGHjt0jj1fWQ92ljDBmODUgp7BCOOWR4FbsEbYm1CjfIFd6gs9kWfZMF9gWhehjHerjGNVx6rrIAE1DHnkPcUfkYB3F3DCBGftmCb3z/Ir/UFymPtpqyZb8bfqGM6RtKIQ3w "Wolfram Language (Mathematica) โ€“ Try It Online") Thanks to [attinat](https://codegolf.stackexchange.com/users/81203/attinat): we can write `1<0` instead of `False` and save two bytes. un-golfed version: ``` F[M_] := {Max[MorphologicalComponents[M, CornerNeighbors -> False]], Max[MorphologicalComponents[1-M, CornerNeighbors -> False]]} ``` There is, of course, a *Mathematica* builtin [`MorphologicalComponents`](https://reference.wolfram.com/language/ref/MorphologicalComponents.html) that takes an array (or an image) and returns the same with the pixels of each morphologically connected island replaced by the island index. Taking the `Max` of this result gives the number of islands (the background zeros are left at zero, and the island index starts at 1). We need to do this separately for the array (giving the number of 1-islands) and one minus the array (giving the number of 0-islands). To make sure diagonal neighbors don't count as neighbors, the option `CornerNeighbors->False` needs to be given. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~60 55 51 50~~ 46 bytes ``` {#?{|/'x*\:x}/2>+/x*x:x-\:'x:(0,#*x)\&,/x}'~:\ ``` [Try it online!](https://tio.run/##bY3dCsIwDIXvfYrCxK5zoz@XCeiDrIV5M5HJhLGLjLm9erU6hVUTSEhycr6maM@t9zWMyXG8S06ZBZqkOewlZQRUWOAEqcqTjITd5ZImPoP1PYzbcpg7qBlhdWswrerT5YqEA3bCTZu@TDULqXDpgkURDi4IFXvlItQYzQINM@7tGNbqW3Xk@RRq90GHf/UHu0IHnP7xWQmV8w8 "K (ngn/k) โ€“ Try It Online") `~:\` a pair of the input and its negation (literally: negate iterate-converge) `{` `}'` for each `,/x` flatten the arg `&` where are the 1s? - list of indices `(0,#*x)\` divmod width(input) to get two separate lists for ys and xs `x-\:'x:` per-axis distances โˆ†x and โˆ†y `x*x:` square them `+/` add โˆ†xยฒ and โˆ†yยฒ `2>` neighbour matrix `{|/'x*\:x}/` transitive closure `#?` count unique rows [Answer] # Python 3, 144 127 bytes This solution uses `cv2`'s awesome image processing power. Despite cv's less awesome, super long and readable method names, it beats both other Python answers! ### Golfed: ``` import cv2,numpy as n f=lambda b:n.amax(cv2.connectedComponents(b*255,0,4)[1]) def g(a):b=n.array(a,n.uint8);print(f(1-b),f(b)) ``` ### Expanded: ``` import cv2 import numpy as np # Finds the number of connected 1 regions def get_components(binary_map): _, labels = cv2.connectedComponents(binary_map*255, connectivity=4) # default connectivity is 8 # labels is a 2d array of the binary map but with 0, 1, 2, etc. marking the connected regions components = np.amax(labels) return components # Takes a 2d array of 0s and 1s and returns the number of connected regions def solve(array): binary_map = np.array(input_map, dtype=np.uint8) black_regions = get_components(1 - binary_map) # 0s white_regions = get_components(binary_map) # 1s return (black_regions, white_regions) ``` [Answer] # [J](http://jsoftware.com/), ~~46 44~~ 43 bytes -1 byte thanks to @miles ``` ,&#&~.&([:+./ .*~^:_:2>1#.[:|@-"1/~4$.$.)-. ``` [Try it online!](https://tio.run/##XY1BC8IwDIXv/orHVjqna9a0PQUUQfDkyetAD8MhXvwDsr9eN7spjBzykvcl7xkzKrqdFJWFWEPHy/kUK53rnvS6kS3VoE1/lZu4PefUyPtgMq77oEhRaSiWq3v7eIHBRjo4BMXjAAtMIgEObgTCAFikmgAGlpv55PvTwytOtv03XuR69Uu1c@Ygk@kUxw8 "J โ€“ Try It Online") tests and the `,&` `-.` wrapper stolen from [@jonah's answer](https://codegolf.stackexchange.com/a/188893/24908) `,&` `-.` for the input and its negation do: `4$.$.` (y,x) coordinates of the 1s as an nร—2 matrix `1#.[:|@-"1/~` manhattan distances: abs(โˆ†x)+abs(โˆ†y) `2>` neighbour matrix `[:+./ .*~^:_:` transitive closure `#&~.&(` `)` number of unique rows [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ,Cล’แนชโ‚ฌยตแบกรพ`ยงแปŠรฆ*Lแน QLยซL) ``` [Try it online!](https://tio.run/##y0rNyan8/1/H@eikhztXPWpac2jrw10LD@9LOLT84e6uw8u0fB7uXBDoc2i1j@b/w@1AeZC6GUA68v//aK7oaEMdBQMgitVRiDZAZxrGxupAlUAFESIIBJKCmAIlEQIG6AKoKpDMgBsLk4KIILsHJBILAA "Jelly โ€“ Try It Online") Adapted from [my Jelly answer](https://codegolf.stackexchange.com/a/231867/78410) to [caird's shape grouping challenge](https://codegolf.stackexchange.com/q/231864/78410). Unfortunately, handling empty lists had multiple consequences that made me use `ยง` instead of complex numbers and add `ยซL`. The outer structure was shamelessly stolen from [caird's answer](https://codegolf.stackexchange.com/a/231833/78410). ``` ,Cล’แนชโ‚ฌยตแบกรพ`ยงแปŠรฆ*Lแน QLยซL) Main link. Input = binary matrix ,Cล’แนชโ‚ฌ Classify coords of zeros and ones (ฤ  doesn't work) ยต ) Operate on each list... แบกรพ`ยงแปŠ Proximity matrix; m[i][j]==1 if two points are adjacent รฆ*L m^(length of input list) แน QL Sign (convert positives to 1) and count unique rows ยซL Handle empty list to make it 0 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 155 bytes ``` s`1(.*) ;$1a }+`(?<=(.)*)(1|;)(.*ยถ(?<-1>.)*(?(1)$))?(?!\2)[1;] ;$3; s`0(.*) :$1b }+`(?<=(.)*)(0|:)(.*ยถ(?<-1>.)*(?(1)$))?(?!\2)[0:] :$3: \W+(a*)(b*) $.1 $.2 ``` [Try it online!](https://tio.run/##hYwxDsIwEAR7vwKkK@4SYd0mnQ34GRQkkh2JgoaCpAzf4gF8zJzSUVFsM6uZ5225P0qtcwb7RlwkFPdqM6fjib00wlij2PV5GzrgbIwTQ0gkcdoPnVwRR/P66OasWyQQpt@IruFPRMNoXh/ccGm5mDJZiDx25Ltaoep0G74 "Retina 0.8.2 โ€“ Try It Online") Link includes test case. Explanation: ``` s`1(.*) ;$1a ``` If there's a `1`, change it to `;` and append an `a` to the end of the input so that it's out of the way. ``` }+`(?<=(.)*)(1|;)(.*ยถ(?<-1>.)*(?(1)$))?(?!\2)[1;] ;$3; ``` Flood fill any more adjacent `1`s with `;`s. ``` } ``` Repeat until all of the islands of `1`s have been turned into `;`s. ``` s`0(.*) :$1b ``` If there's a `0`, change it to `:` and append a `b` to the end of the input so that it's out of the way. ``` +`(?<=(.)*)(0|:)(.*ยถ(?<-1>.)*(?(1)$))?(?!\2)[0:] :$3: ``` Flood fill any more adjacent `0`s with `:`s. ``` } ``` Repeat until all of the islands of `0`s have been turned into `:`s. ``` \W+(a*)(b*) $.1 $.2 ``` Separately count the numbers of islands of `1`s and `0`s. [Answer] # [Haskell](https://www.haskell.org/), ~~228~~ ~~227~~ ~~225~~ 224 bytes ``` import Data.List z=zipWith a!b=div(max(a*a)(a*b))a l x=z(!)(z(!)x(0:x))$tail x++[0] s=(\x->length.($x).filter<$>[(>0),(<0)]).nub.(>>=id).(until=<<((==)=<<))((.)>>=id$transpose.map l).z(\i->z(\j x->2^i*j*(2*x-1))[1,3..])[1..] ``` [Try it online!](https://tio.run/##HY0xb4MwEIV3foUjMdwRsJx0q7Cnjt07ECodCg2XGgdhp7L48/RaPen7dPeGN1H8Hr3fd56Xx5rUGyXS7xxTsdmNlw9OU0GHwV75B2bKQBWhYECkwqtsNzgg/CGDec2IZSKW//HYmb6IFi65cX4MtzRpKDPqL/ZpXNvSdeAM1tAa7FGH56DBOctX1PAMib1tWwBrUYwIoPG/LdNKIS6POOqZFuVRb3DhxgnvSpbOn1zdKzhXuTkhdqf6ReteLNxn4qCsWlYOSZUqqk56U5u@FkvEcon7/Rc "Haskell โ€“ Try It Online") Explanation: The idea for this solution is as follows: Initialise the matrix with unique values in each cell, positive for `1` and negative for `0`. Then repeatedly compare each cell with its neighbours and, if the neighbour has the same sign but a number with a larger absolute value, replace the cell's number wit the neighbour's number. Once this hits a fixed point, count the number of distinct positive numbers for the number of `1` regions and the distinct negative numbers for the number of `0` regions. In code: ``` s=(\x->length.($x).filter<$>[(>0),(<0)]).nub.(>>=id).(until=<<((==)=<<))((.)>>=id$transpose.map l).z(\i->z(\j x->2^i*j*(2*x-1))[1,3..])[1..] ``` can be separated into the preprocessing (assigning numbers to cells), the iteration, and the postprocessing (counting cells) ## Preprocessing The preprocessing part is the function ``` z(\i->z(\j x->2^i*j*(2*x-1))[1,3..])[1..] ``` Which uses `z` as abbreviation for `zipWith` to shave off a few bytes. What we do here is zip the two dimensional array with integer indices at the rows and odd integer indices at the columns. We do this since we can build a unique integer from a pair of integers `(i,j)` using the formula `(2^i)*(2j+1)`. If we generate only odd integers for `j`, we can skip calculating the `2*j+1`, saving three bytes. With the unique number, we now only have to multiply in a sign based on the value in the matrix, which is obtained as `2*x-1` ## Iteration The iteration is done by ``` (until=<<((==)=<<))((.)>>=id$transpose.map l) ``` Since the input is in the form of a list of lists, we perform the neighbour comparison on each row, transpose the matrix, perform the comparison on each row again (which due to the transpose is what was the columns before) and transpose again. The code that accomplishes one of these steps is `((.)>>=id$transpose.map l)` where `l` is the comparison function (detailed below) and `transpose.map l` performs one half of the comparison and transposition steps. `(.)>>=id` performs its argument twice, being the pointfree form of `\f -> f.f` and by one byte shorter in this case due to operator precedence rules. `l` is defined in the row above as `l x=z(!)(z(!)x(0:x))$tail x++[0]`. This code performs a comparison operator `(!)` (see below) on every cell with first its left neighbour, and then with its right neighbour, by zipping the list `x` with the right shifted list `0:x` and the left shifted list `tail x++[0]` in turn. We use zeroes to pad the shifted lists, since they can never occur in the preprocessed matrix. `a!b` is defined in the row above this as `a!b=div(max(a*a)(a*b))a`. What we want to do here is the following case distinction: * If `sgn(a) = -sgn(b)`, we have two opposing areas in the matrix and do not wish to unify them, so `a` stays unchanged * If `sgn(b) = 0`, we have the corner case where `b` is padding and therefore `a` stays unchanged * If `sgn(a) = sgn(b)`, we wish to unify the two areas and take the one with the bigger absolute value (for convenience's sake). Note that `sgn(a)` can never be `0`. We accomplish this with the formula given. If the signs of `a` and `b` differ, `a*b` is less or equal to zero, while `a*a` is always greater than zero, so we pick it as the maximum and divide with `a` to get back `a`. Otherwise, `max(a*a)(a*b)` is `abs(a)*max(abs(a),(abs(b))`, and by dividing this by `a`, we get `sgn(a)*max(abs(a),abs(b))`, which is the number with the larger absolute value. To iterate the function `((.)>>=id$transpose.map l)` until it reached a fixed point, we use `(until=<<((==)=<<))`, which is taken from [this stackoverflow answer](https://stackoverflow.com/a/23924238/1115539). ## Postprocessing For postprocessing, we use the part ``` (\x->length.($x).filter<$>[(>0),(<0)]).nub.(>>=id) ``` which is just a collection of steps. `(>>=id)` squashes the list of lists into a single list, `nub` gets rid of doubles, `(\x->length.($x).filter<$>[(>0),(<0)])` partitions the list into a pair of lists, one for positive and one for negative numbers, and calculates their lengths. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~44~~ 42 bytes ``` ล’Jfโฑฎ+โ‚ฌยฅร˜.,Uลปยคล“แป‹แธขยฅฦ‡โนล“แป‹ฦ‡โ‚ฌษ—โฑฎ,ยฌ$fฦ‡โฑฎ`แบŽQ$โ‚ฌQฦŠรLโ‚ฌแบˆ ``` [Try it online!](https://tio.run/##y0rNyan8///oJK@0RxvXaT9qWnNo6eEZejqhR3cfWnJ08sPd3Q93LDq09Fj7o8adYC6Q1bTm5HSgYp1Da1TSgNyN6xIe7uoLVAGKBx7rOjzBB8h4uKvj/8PdWx7u2ATkhB1u57J@1DDn0DYFXTuFRw1zrQ@3e6twAY3bufgwyLgsoHmN@w5tO7Tt/39DBSjkMlQwAEMIyxDKMoSLwdRBmQZwmguiDyZgiMGHGA0R5oIYxwUzAiTEBbEebjRu1xiguwYA "Jelly โ€“ Try It Online") A monadic link accepting a list of lists of integers as its argument and returning a list of the number of 1 and 0 islands in that order. Thanks to @JonathanAllan for pointing out a bug in my code when there were islands that were diagonally adjoined. ## Explanation (needs updating) ### Step 1 Generate list of all matrix indices each with the indices of its neighbour to the right (unless on the right side) and down (unless at the bottom) ``` ล’J | Multi-dimensional indices (e.g. [1,1],[1,2],[1,3],[2,1],[2,2],[2,3]) ยฅ | Following as as a dyad: fโฑฎ | - Filter the indices by each of: +โ‚ฌ ยค | - The indices added to the following ร˜. | - 0,1 ,U | - Paired with itself reversed [0,1],[1,0] ลป | - Prepended with zero 0,[0,1],[1,0] ``` ### Step 2 Split these indices by whether there was 1 or 0 in input. Returns one list of indices with neighbours for 1s and another for 0s. ``` ฦ‡รพ | Filter each member of the output of stage 1 using the following criteria: ล“แป‹ $ | - Corresponding value for the multi-dimensional indices in each of the following as a monad: ,ยฌ | - The input paired with its inverse ``` ### Step 3 Merge lists with members in common and output counts ``` ฦฒรLโ‚ฌ | For each of the outputs from stage 2, do the following as a monad and repeat until no changes ยนฦ‡ | - Filter out empty lists (only needed on first pass through but included here to save a byte) fฦ‡โฑฎ` | - Take each list of indices and filter the list of indices for those containing a match for any of them $โ‚ฌ | - For each resulting list of lists: แบŽ | - Tighten (concatenate top level of lists) Q | - Uniquify Q | - Uniquify แบˆ | Finally output the lengths of the final lists ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ,Cยตล’แนชล’!ล’แน–โ‚ฌแบŽแบกฦโ‚ฌยงโ‚ฌแปŠศฆฦฒฦ‡แบˆแน‚) ``` [Try it online!](https://tio.run/##y0rNyan8/1/H@dDWo5Me7lx1dJIiiJ72qGnNw119D3ctPDYXyDy0HMTf3XVi2bFNx9of7up4uLNJ8//D3Vse7tgElAkDYiA63O7OdXTyw52LHzXuO7Tt0LbD7UDBLCjn/39DBRA04ILRXDCuAZQDxlwGYD5YEQobrNAQqtwAJAQA "Jelly โ€“ Try It Online") Somewhat of a brute force approach, times out if there are more than \$7\$ \$0\$s or \$7\$ \$1\$s ## How it works ``` ,Cยตล’แนชล’!ล’แน–โ‚ฌแบŽแบกฦโ‚ฌยงโ‚ฌแปŠศฆฦฒฦ‡แบˆแน‚) - Main link. Takes a matrix B on the left C - Complement of each element , - Pair; [B, 1-B] ยต ) - Over each matrix M: ล’แนช - Get the [x, y] coords of each element of 1 in M ล’! - All permutations โ‚ฌ - Over each permutation: ล’แน– - Get all partitions แบŽ - Tighten into a list of partitions ฦฒฦ‡ - Keep the partitions P for which the following is true: โ‚ฌ - Over each partition: ฦ - Over each overlapping pair: แบก - Absolute differences โ‚ฌ - Over each difference: ยง - Get the sums แปŠ - Insignificant; Equal to 1 or 0 ศฆ - There are no zeros anywhere here? แบˆ - Lengths of each แน‚ - Minimum ``` [Answer] # [Python 3](https://docs.python.org/3/), 167 bytes ``` def f(m): n=[0,0];i=-2 for r in m: j=0;i+=1 for c in r:n[c^1]+=1-((i>=0)*(m[i][j]==c)*(1+({*r[:j]}=={c})*({*m[i][:j]}=={c^1}))or(j>0)*(r[j-1]==c));j+=1 print(n) ``` [Try it online!](https://tio.run/##fZFBboMwEEX3nGKkbmwCkod0BXIuYjkbWlRbwkRWNhHi7NTj1sEkaVmNZ97/820ut@vX5I7r@vE5wMBG3hbgpBKV0J2RdVPAMHnwYByMYQRWis4cJIaSBj0NfOtUf0Yd2jVj5iQFL9mojFZWS9mHAx7YXHrVWr1IOfdLaM1lJFLrjAvnk2f2RGKvbI1Ryzsbt128cVfm@DowpbCifFXIACEpZnU4ac2Bvjc4QlMUxBODvww@1GLjMfG5492PiGYjNheRpfnp3x0bwIzfU2kz7X1Jxdsktyxd7O7v86T5Y8/7c3qMb/Yy/UOuvUbsdPEv/DNP@uAdX2X9Bg "Python 3 โ€“ Try It Online") --- # [Python 2](https://docs.python.org/2/), 168 bytes ``` def f(m): n=[0,0];i=-2 for r in m: j=0;i+=1 for c in r:n[c^1]+=1-((i>=0)*(m[i][j]==c)*(1+(set(r[:j])=={c})*(set(m[i][:j])=={c^1}))or(j>0)*(r[j-1]==c));j+=1 print n ``` [Try it online!](https://tio.run/##fZHBbsMgEETP4StW6gUaW2JpT7bIjyBycWMVJOOI@lJV@XaXpXWMk7Q@wfBmdsDnz@l9DGqe30499HwQDYOgjaykbZ2uFYN@jBDBBRgatvNatm6vke1I7kiOTTDdEW1Sa87dQUvxzAfjrPFW6y5tcM8/ThOPpvFWaP3VXZJISqYW8YgXIcbI/YECovE1Zr9oPQ2Ec3RhgjD33BisqGDFACBVxWKddtYKoO8JXkAxRjwx@MvgzVquPC58mXjNI0KtxJoiizY/@jVRARb8llom09yHVL7Nkla0y@r2PneeP@a83rfH/GYP29/02nrkxpf/wj/niz9l51eZvwE "Python 2 โ€“ Try It Online") -2 bytes thanks to Kevin Cruijssen +2 bytes formatting fix # Explanation A counter is kept for 0s and 1s. For each entry in the matrix, the following actions are performed: * Incrase counter for current value by 1 * If the same value exists directly above or to the left, decrease by 1 This results in a false positive for left-aligned cases like ``` 0 0 1 1 1 1 ``` or ``` 0 1 1 1 ``` If such a situation arises, the counter is decreased by 1. Return value is `[#1, #0]` [Answer] # Java 10, ~~359~~ ~~355~~ ~~281~~ ~~280~~ ~~261~~ ~~246~~ ~~240~~ 236 bytes ``` int[][]M;m->{int c[]={0,0},j=m[0].length,i=m.length*j,t;for(M=m;i-->0;c[~t&1]+=t<2?f(t,i/j,i%j):0)t=M[i/j][i%j];return c;}int f(int v,int x,int y){try{if(M[x][y]==v){M[x][y]|=2;f(v,x,y-f(v,x-f(v,x,y+f(v,x+1,y)),y));}}finally{return 1;}} ``` -74 bytes thanks to *@NahuelFouilleul*. -10 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##lVTBbpwwEL3vV4witbK7hoXcupREPfZAesjR8sEhkJiAWcFAF1H661sDrrphk2hXCI/nMfNm/DQ4k610sseXQ5zLuoZIKg39CkBpTKpUxgncje4EcAExmSwXBQ0MPKzsBy6iADYbWH8FLAGfE3joMHHistFoYu5AQwiHwrnpTTjEXIS9x7yBZWHBPeHmiX7CZ6bCwm6/ZAyDtKxIFBaBcpwbL4j5H/zsi3WI365vU4JMbTKmPmV061EMI25cwY0vgirBptIQB0MwVkvHnqFl47qf1o72WHW9SknE94J3Igxb2tv97/A6SEnL9qxzJutYbz3Ztc86Ssc3GIZUaZnnXW8r@gY6AOyah1zFUKNEY9pSPUJhdCX3WCn9ZFSUdNYUkxqJTn7903BGAXqfjY/RZwlM/jBp/0G6kZZ5p@n@f@DdiPMK@K@TvVP3fKbFOb2zT/nqQBf1ftzqJY0uRPRnEZeQfwqdRF0u97LIgu2YaViZ5Xj6JmJLCoUdvvuuxqRwywbdnZlLzDW5@qF3DW7hyjY0/oBTmtwW1JZ7Iy0zd4jboMrd71Ulu9rFch51IqlleqvYzwbnauv3CUY1xjuJUFe7MSnoB4T27MPhLw) **Explanation:** ``` int[][]M; // Integer-matrix on class-level, uninitialized m->{ // Method with integer-matrix parameter and integer-array return-type int c[]={0,0} // Counters for the islands of 1s/0s, starting both at 0 j=m[0].length, // Amount of columns i=m.length*j, // Index of the cells t; // Temp-value to decrease the byte-count for(M=m; // Set the class-level matrix to the input-matrix i-->0 // Loop over the rows ; // After every iteration: c[~t&1]+= // Increase the corresponding counter by: t<2? // If the cell's value `t` is 0 or 1: f(t,i/j,i%j) // Call the recursive flood-fill method with value `t` // And increase the counter by 1 : // Else: 0; // Keep the counter the same by increasing by 0 t=M[i/j][i%j]; // Set `t` to the value of the current cell return c;} // After the nested loops: return the counters-array as result // Recursive method with value and cell-coordinate as parameters, // This method will flood-fill the matrix, where 0 becomes 2 and 1 becomes 3 int f(int v,int x,int y){ try{if(M[x][y]==v){ // If the cell contains the given value: M[x][y]|=2; // Fill the cell with 0โ†’2 or 1โ†’3 depending on the value f(v,x+1,y) // Do a recursive call downwards f(v,x,y+...) // Do a recursive call towards the right f(v,x-...,y) // Do a recursive call upwards f(v,x,y-...);} // Do a recursive call towards the left // (method `f` always result in 1, so we use it to our advantage to // save bytes here by nesting, instead of having four loose calls) }finally{return 1;}} // Ignore any ArrayIndexOutOfBoundsExceptions with a finally-return, // which is shorter than manual checks // And return 1 to increase the counter ``` [Answer] # Perl 5 (`-0777p`), 110 bytes May be improved, uses a regex to replace `1` with `3`, then `0` with `2`. ``` / /;$m="(.{@-})?";sub f{($a,$b,$c)=@_;1while s/$b$m\K$a|$a(?=$m$b)/$b/s||s/$a/$b/&&++$c;$c}$_=f(1,3).$".f(0,2) ``` [TIO](https://tio.run/##HYlBC4IwAEbv/gqRD9lwui0JD2Povb8QyCZKwkxpRQf1r7esw4PHe0v/cOcQeMQVJp2QYm3yndaJ8i8bDyuBYbAMHdVNq@T7Nro@9hwW0/UCs8GQWmOCpUfjftuOZ36aplmGTqHb0eqBSFbSAkkxEMFONAQpRCT@yM@8PMf57kMuqqpa3Bc) [Answer] # T-SQL 2008, 178 bytes Input is a table variable. > > x and y are the coordinates > > > v is the values 0 and 1(could also handle other numeric values) > > > The test data used in this example: ``` 100 000 001 ``` ``` DECLARE @ table(x int, y int, v int) INSERT @ values (1,1,1),(1,2,0),(1,3,0), (2,1,0),(2,2,0),(2,3,0), (3,1,0),(3,2,0),(3,3,1) SELECT*,y-x*99r INTO # FROM @ WHILE @@rowcount>0UPDATE # SET r=b.r FROM #,# b WHERE abs(#.x-b.x)+abs(#.y-b.y)=1and #.v=b.v and #.r>b.r SELECT v,count(distinct r)FROM # GROUP BY v ``` **[Try it online](https://rextester.com/BJX75675)** [Answer] # [R](https://www.r-project.org/), ~~194~~ 172 bytes ``` function(m,u=!1:2){for(i in 1:2){w=which(m==i-1,T) N=1:nrow(w) A=!!N for(s in N){u[i]=u[i]+A[s] while(any(s)){A[s]=F s=c(N[as.matrix(dist(w))[s[1],]==1&A],s[-1])}}} rev(u)} ``` [Try it online!](https://tio.run/##jY4/a8MwEMX3@xT2Uu6oUnIZAzd4yeipm9DgOjER1DJIdt1i/Nldy21IyB@IdCfQu/fTk58qmarOla1tHNaqk5S3GxqqxqNNrEuWWy/90ZZHrEXsitU7QS68db7psSfIJE1ziESIRE5Dp62ReLxmOhiY4c8DFu4HA9EQJdlBkBJzXYS3umi9/ca9De38Gumg2Sgjwi@ZUUGv2NA4juAPX9jROFXoP6zbY4msknORguR/LZP1qe5N@OHkAXORQ0AAl59Yq7mvgD8tWp9xXsfxjW8hb7S4@a42J0@/ "R โ€“ Try It Online") Perform a depth-first search starting in each cell of the matrix that is equal to 1 (or zero). * -2 bytes thanks to @Giuseppe ]
[Question] [ **This question already has answers here**: [Swap Two Values in a List](/questions/236301/swap-two-values-in-a-list) (49 answers) Closed 1 year ago. Given an array of positive integers and two distinct valid indices, return the array with the two elements corresponding to the two indices swapped. You may choose to use 0-indexing or 1-indexing, but the testcases below will be 0-indexed. ``` array m n output [1,2,3,4] 0 1 [2,1,3,4] [5,8,9] 0 2 [9,8,5] [11,13,15,3] 1 2 [11,15,13,3] [11,13,15,3] 2 1 [11,15,13,3] [11,15,15,3] 2 1 [11,15,15,3] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # C~~/C++~~, ~~53~~ ~~50~~ 39 bytes ``` f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];} ``` [Try it online](https://tio.run/##dZDLboMwEEXX@CtGSJVwMlWBNFIrmi9xqWTRpPICUwXKU3w7HcbFyaYbj@eeOw@7ePwqimW5RBpLtNLYZqezSasy/zhpZfnc7tm8tJX5hOZcNxE5YacR1li7ULpgpZhEsHZcFSszQVl1BS4xcII4o/AGNTxBbcZzRVYV55LU/V6KIPi@kvMShQ/pD4QIWpmcm2z6uw0pn4XgodrYiCdSRsWtymnElCCkCAeE5xlJ7Zx6RHhBeGWp/zOSMyFfQuzAYPgPjHfguIF1Mf6QFrfXtBIhJk5LOtR51DmUetR71BNK7tHg0SD5NbeGo0fjDc3LLw) Saved 11 bytes thanks to @Dennis [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~98~~ 95 bytes ``` f={t=_this;a=t select 0;b=+a;m=t select 1;n=t select 2;a set[m,b select n];a set[n,b select m]} ``` Modifies the array directly. **Explanation:** ``` t=_this; // Give a shorter name for the array of arguments. a=t select 0; // Let 'a' be a pointer to the array that we modify. // (The language doesn't have a concept of pointers really, // yet its array variables are pointers to the actual array.) b=+a; // Make a copy of the original array and save a pointer to it // in the variable 'b'. This saves a few bytes later. m=t select 1; // Read the index arguments from the input array and save them n=t select 2; // to their respective variables. a set[m,b select n]; // Do the swapping by reading the values from the copy and a set[n,b select m] // writing them to the original array. The last semicolon can // be omitted because there are no more statements following // the last statement. ``` **Call with:** ``` array = [1,2,3,4]; str = format["%1", array]; [array, 0, 1] call f; hint format["%1\n%2", str, array]; ``` **Output:** [![enter image description here](https://i.stack.imgur.com/sHwSA.jpg)](https://i.stack.imgur.com/sHwSA.jpg) [Answer] # JavaScript ES6, ~~36~~ 32 bytes Look, Ma, no temporary variable! ``` (a,m,n)=>[a[m],a[n]]=[a[n],a[m]] ``` * 4 bytes saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) bringing [this consensus](https://codegolf.meta.stackexchange.com/a/4942/48934) to my attention. --- ## Try it Enter a comma separated list of elements for `a` and 2 integers for `m` & `n`. ``` f= (a,m,n)=>[a[m],a[n]]=[a[n],a[m]] oninput=_=>o.innerText=(f(b=i.value.split`,`,+j.value,+k.value),b);o.innerText=(f(b=(i.value="5,8,9").split`,`,j.value=0,k.value=2),b) ``` ``` *{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;} ``` ``` <label for=i>a: </label><input id=i><label for=j>m: </label><input id=j type=number><label for=k>n: </label><input id=k type=number><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` แนš,แธทyJ}แป‹ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlk6D3dsr/Sqfbi7@3@x0eHl@o@a1rj//x8dbaijYBSroxCtAGQoGAGxMRCbxOpwKYCkjMFSpkAhCyC2VAACsJQRVMoQqMYQqMMQpMQYLGUMNRBNKhYA "Jelly โ€“ Try It Online") ### How it works ``` แนš,แธทyJ}แป‹ Main link. Left argument: [i, j]. Right argument: A (array) แนš Reverse; yield [j, i]. แธท Left; yield [i, j]. , Pair; yield [[j, i], [i, j]]. J} Indices right; yield all indices of A. y Transliterate; replace j with i and i with j. แป‹ Index into A. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~7~~ 6 bytes ``` yyP)w( ``` Indices are 1-based. [**Try it online!**](https://tio.run/##y00syfn/v7IyQLNc4///aENDBUNjBUNTBeNYrmgjIAkA) ### Explanation Consider inputs `[11 13 15 3]`, `[2 3]`. ``` yy % Take two inputs implicitly. Duplicate them % STACK: [11 13 15 3], [2 3], [11 13 15 3], [2 3] P % Flip % STACK: [11 13 15 3], [2 3], [11 13 15 3], [3 2] ) % Reference indexing (pick indexed entries) % STACK: [11 13 15 3], [2 3], [15 13] w % Swap % STACK: [11 13 15 3], [15 13], [2 3] ( % Assignment indexing (write values into indexed entries). Implicitly display % STACK: [11 15 13 3] ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~41~~ 32 bytes -9 bytes thanks to @notjagan ``` def f(a,m,n):a[m],a[n]=a[n],a[m] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1EnVydP0yoxOjdWJzE6L9YWROiAuP8TbaMNDXUMjXUMTXWMY7lAag11jDS5Cooy80o0EjX/AwA "Python 3 โ€“ Try It Online") Modifies its argument, which is a [valid output format](https://codegolf.meta.stackexchange.com/a/4942/64121). [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` {e\} ``` [Try it online!](https://tio.run/##S85KzP2fU133vzo1pvZ/XUGOn25txv9oQwUjBWMFk1gFEDBQMOSKNlWwULCE8EEiRlzRhoYKhsYKhqYKxkBhQwwRIwVDAA "CJam โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 16 bytes ``` hV(A=UgV UgWยนhWA ``` [Try it online!](https://tio.run/##y0osKPn/PyNMw9E2ND1MITQ9/NDOjHDH//@jDXWMdIx1TGIVDBQMAQ "Japt โ€“ Try It Online") Saved a byte thanks to ETHproductions [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 48 43 31 bytes ``` (a,m,n)=>a[m]+=a[n]-(a[n]=a[m]) ``` [Try it online!](https://tio.run/##bU/LCsIwELz3KxZPCcZCEU81gngTBcGDh9JDiFEW7EaSqIj022tSwQc4sMOys7MP7UfaOtNBhD4p72Hj7NGpJkuVR88JPqiAGq4W97BWSIy/pU9Twvbug2nyuQ5oaYoUqlpETjGDg8w6pkQjiMuZqpp6KFVF9YgllqnAuzL7mXdVDpDOlwASyNyqGh5QFAKKcYyJgDG05Y/hwPr2qEaRl/@OW1jy9mTyncNgVkiG@eCQjvnSxs8GYiBeK/mXve2ztnsC "C# (.NET Core) โ€“ Try It Online") Swaps the numbers in the original array, no temporary variables used. Nonetheless I can't take credit for this answer as it has been [Neil's idea](https://codegolf.stackexchange.com/questions/127839/swap-the-two-given-indices#comment315239_127842). [Answer] # [Common Lisp](http://www.clisp.org/), 42 bytes *-2 bytes thanks to [@coredump](https://codegolf.stackexchange.com/users/903/coredump).* ``` (lambda(a i j)(rotatef(elt a i)(elt a j))) ``` [Try it online!](https://tio.run/##dU1LCsIwEN3nFI@KMLMQqtbfccY2gZaJlXRU3PTqsUILbty9/6u1He6ZGh@ekhDfm@ElE1eJ10ZI0KJjSr2J@UBeDZPEM@iYObNzP21JCSsqscUOe1Q44IgTzrgwOwp9imIwFKOM62LOf43HrRbV5X4ZKlH9b@UP "Common Lisp โ€“ Try It Online") Quite straight forward, since there is a Common Lisp macro to swap: `rotatef`. [Answer] # Javascript ES6, ~~36~~ 34 bytes ``` (a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x) ``` * *-2 Bytes because the function is altering the array. No need to return the array. Thanks to @Neil* ## Demo ``` f= (a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x) let a1=[1,2,3,4], a2=[5,8,9], a3=[11,13,15,3] f(a1,0,1); f(a2,0,2); f(a3,1,2); console.log(JSON.stringify(a1)); //[2,1,3,4] console.log(JSON.stringify(a2)); //[9,8,5] console.log(JSON.stringify(a3)); //[11,15,13,3] ``` [Answer] # Shenzhen I/O, 735 Bytes 23ยฅ, 810 Power, 48 Lines of Code ``` [traces] ...................... ...................... ...................... ...................... ...................... ...................... .14.14.14............. .94.14.14............. .A........1C.......... .3554..95556.......... .9554.16.............. .A.................... .2.................... ...................... [chip] [type] UC6 [x] 4 [y] 2 [code] slx x0 mov x1 acc mov x1 dat mov acc x3 mov dat x3 mov acc x3 mov dat x3 [chip] [type] UC6 [x] 8 [y] 5 [code] slx x2 mov x2 x1 mov x0 dat mov x2 x1 mov x0 acc mov x2 x1 mov dat [chip] [type] UC4X [x] 2 [y] 6 [code] slx x0 mov 0 x3 j: mov x0 acc mov acc x2 teq acc 0 - jmp j mov -999 x1 [chip] [type] RAM [x] 5 [y] 6 ``` [![SIO](https://i.stack.imgur.com/HorMB.jpg)](https://i.stack.imgur.com/HorMB.jpg) DISCLAIMER: Arrays are 0-terminated in this. Arrays are a pain in the ass to work with in Shenzhen I/O otherwise. I actually made a steam level for this game. You can play it [here.](http://steamcommunity.com/sharedfiles/filedetails/?id=954747779) EDIT: Aaand I just realized I said that the array in was ordered. Heck. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes ``` iสฐ{pแต—z=แต—!|}htI&hโˆ‹โ†™I ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/5mnNlQXPNw6vcoWSCjW1GaUeKplPOroftQ20/P//2iF6GhDHSMdYx2TWB2FaAMdw1gQHW2qY6FjCRExgogYGuoYGusYmuoYg7iG2IWNYPpBwqaowgqxAA "Brachylog โ€“ Try It Online") The process of writing this [generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) was fairly clumsy, so there's probably some further golfing to do. I may not have thought to use `i` if I hadn't initially thought I had some use for the value half of the pair it outputs! Takes input as `[array, [m, n]]`. [Answer] # [Java 8](http://openjdk.java.net/), 48 bytes ``` (a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;return a;} ``` Input: ``` int[] a int b int c ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` Dยฒรจยณวยนยณรจยฒว ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f5dCmwysObT4@99DOQ5uBrE3H5/7/H22oY6RjrGMSy2XAZQgA "05AB1E โ€“ Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 28 bytes ``` @(a,n){a(n)=a(flip(n)),a}{2} ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnT7M6USNP0zZRIy0nswDI0tRJrK02qv2fphFtqGOkY6xjEqsDYsVqcgGFTHUsdCzBAsYQAUNDHUNjHUNTIF8n2girqDFI838A "Octave โ€“ Try It Online") Quite satisfied with this one actually :) Takes input on the form: `f([1,2,3,4],[1,2])`, 1-indexed. **Explanation:** ``` @(a,n) % Anonymous function that takes two 1-dimensional % arrays as input { , } % Create a cell with two elements a(n)=a(flip(n)) % One element are the two number at indices given by % the second input array. This will be a 1x2 array {a(n)=a(flip(n)),a} % Place those two in a cell together with the entire array a % a is now updated, thanks to Octave's inline assignment {a(n)=a(flip(n)),a}{2} % Return the second element ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 7 bytes ``` p ZRi i ``` Takes a list and a pair of indices. [Try it online!](https://tio.run/##y0rNyalMyyzO@P@/gCsqKJMr8///aDMFUwVzBctYrmhDBeNYAA "Jellyfish โ€“ Try It Online!") ## Explanation Jellyfish happens to have a "modify items at indices" function, `Z`, which does exactly what we need. The two `i`s grab the inputs from STDIN. `Z` takes as arguments the second input, the reversal function `R`, and the list. Then `Z` performs the modification, and `p` prints the result. [Answer] # R, 38 bytes ``` function(x,a,b){x[c(a,b)]=x[c(b,a)];x} ``` Feels rather long, but I can't get it much shorter. Sadly it requires the explicit returning through `x`, requiring `{}` around the function body. `pryr::f()` doesn't recognise the need for `x` as function argument so doesn't work :/. [Answer] # Java 8 + [InverseY](https://github.com/PlutoPowered/InverseY/blob/master/src/main/java/com/gmail/socraticphoenix/inversey/many/Consumer3.java), 27 bytes ``` java.util.Collections::swap ``` Just calls the swap function... this is a method reference of the type `Consumer3<List, Integer, Integer>`. [Try it online!](https://tio.run/##TVDBTsMwDL3vK3zs0Ig2ygE2NmnaCQmkSvsCk2VVSppEsTs0oX17cQIMoiS23rPfi9PhCW9DNL47vI@2jyExdIKpga1TN6tJHN6c1aAdEsErWg@fk1@QGFnCKdgD9EJVe07Wt0opwNTSVEpB1i54GnqT6qcXSzyDZ8@mNemabIA@MMIaxj/nXXDOaLbSulxmelwVrawALl9r2KaEZ1JIGazmM7iTs5D9KKmEh@l3T25XGp2rXPG/F/qH2p@JTa/CwCrK09n5UiPs5TqlwCYdUZt/gzRi04hHU2/yf2Sp8gvFpVlALDzEUgKxFsGseBm/AA) (header and footer for boilerplate & copy of `Consumer3` interface) [Answer] # Swift, ~~111~~ 65 bytes (0-indexed) Swift is already notorious for being one of the worst code-golf languages, but here is a function ~~that makes use of ternary expressions~~: ``` func t(l:[Int],m:Int,n:Int){var r=l;r[m]=l[n];r[n]=l[m];print(r)} ``` [Check it out!](http://swift.sandbox.bluemix.net/#/repl/594bac0de7b3821b65a0c480) - **Usage:** `t(l:[1,2,3],m:0,n:1)`. [Answer] # [k](http://en.wikipedia.org/wiki/K_(programming_language)) ([kona](https://github.com/kevinlawler/kona)), 13 bytes ``` {x[y]:x@|y;x} ``` Pretty basic, but it works. Ex: ``` k){x[y]:x@|y;x}[1 2 3 4; 0 1] 2 1 3 4 ``` [Answer] # [Perl 5](https://www.perl.org/), 32 bytes *-3 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)!* 30 bytes of code + `-pa` flags. ``` @F[pop@p,@p]=@F[@p=<>];$_="@F" ``` [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAsS/zu4RRfkFzgU6DgUxNoCOQ4FtjZ2sdYq8bZKDm5K//8bKhgpGCuYKJgqmCmYK1goWCoYGnAZcVkAAA "Perl 5 โ€“ Try It Online") Quite straight forward, using array slices. [Answer] # Mathematica, 32 bytes ``` (a=#;a[[{##2}]]=a[[{#3,#2}]];a)& ``` [Answer] # C, 42 bytes Modify the array in place with a temp value. ``` f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;} ``` # C, ~~60~~ 58 bytes A little more interesting, not using any temp value... ``` f(a,m,n)int*a;{a[m]+=a[n];a[n]-=a[m];a[n]*=-1;a[m]-=a[n];} ``` # C, 49 bytes Using XOR ``` f(a,m,n)int*a;{a[m]^=a[n];a[n]^=a[m];a[m]^=a[n];} ``` [Answer] # [Julia 0.5](http://julialang.org/), 20 bytes ``` x*t=x[t]=x[t[[2,1]]] ``` [Try it online!](https://tio.run/##dc5BCgIxDAXQdXuKLlP5m7QWdOFJShaCCpWhylCht68ZBmEYMIsPyYNPnp@pXNMY/dAuPTdZIucAFpHxeM2OOpp3pVpDlBkBEUeB09HNBfGwxlFOOOG83leJP2EGR3BCVNbmfxI3bYuknXhrjdE3Nd9zqW2q1L2919v4Ag "Julia 0.5 โ€“ Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~17~~ 8 bytes Saved 9 bytes thanks to Leaky Num. ``` @LQ.rUQE ``` [Test it online!](https://pyth.herokuapp.com/?code=%40LQ.rUQE&input=%5B11%2C13%2C15%2C3%5D%0A%281%2C2%29&debug=0) This is 0-indexed, and the indices are provided as a tuple: `(n, m)`. **Explanations** ``` @LQ.rUQE UQ # Generate [0, 1, 2, ..., len(input)] E # Get the indices as the tuple (1, 2) .r # Translate each element of UQ to its cyclic successor in E # Now the indices are permuted (e.g. [0, 2, 1, ..., len(input)] @LQ # For each index, get it's value. Implicit print ``` [Answer] # Mathematica, 20 bytes ``` #~Permute~Cycles@#2& ``` Pure function taking two arguments in the following 1-indexed (and possibly abusive) format: the second test case `[5,8,9]; 0 2; [9,8,5]` would be called as ``` #~Permute~Cycles@#2& [ {5,8,9} , {{1,3}} ] ``` (spaces are extraneous and just for visible parsing). `Permute` is the builtin function that applies a permutation to a list, and `Cycles[{{a,b}}]` represents the permutation that exchanges the `a`th and `b`th elements of a list and ignores the rest. [Answer] # x86 Machine Code, 10 bytes ``` 8B 04 8B 87 04 93 89 04 8B C3 ``` This is a function written in 32-bit x86 machine code that swaps the values at the specified indices in a given array. The array is [modified in-place](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/4942#4942), and the function does not return a value. A custom calling convention is used, requiring the function's parameters to be [passed in registers](https://codegolf.meta.stackexchange.com/a/8508/58518): * The address of the array (pointer to its first element) is passed in the `EBX` register. * The zero-based index of element A is passed in the `ECX` register. (Assumed to be a valid index.) * The zero-based index of element B is passed in the `EDX` register. (Assumed to be a valid index.) This keeps the size down and complies with all formal requirements, but does mean that the function cannot be easily called from other languages like C. You'd need to call it from another assembly-language program. (You could rewrite it to use *any* input registers, though, without affecting the byte count; there's nothing magical about the ones I chose.) Ungolfed: ``` 8B 04 8B mov eax, DWORD PTR [ebx+ecx*4] ; get value of element A 87 04 93 xchg eax, DWORD PTR [ebx+edx*4] ; swap element A and element B 89 04 8B mov DWORD PTR [ebx+ecx*4], eax ; store new value for element A C3 ret ; return, with array modified in-place ``` [Answer] ## R, 34 bytes ``` pryr::f(`[<-`(a,c(m,n),a[c(n,m)])) ``` [Answer] # JavaScript (ES2015), 66 57 49 bytes A different (alas, longer) approach than previous JavaScript answers ``` (s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h])) ``` Source ``` const swap = (arr, a, b, splice) => { splice(a, 1, ...splice(arr[b], 1, arr[a])) } ``` ]
[Question] [ I haven't. :P So I decided to define one: A **tralindrome** is a string which contains three equal-length sections X, Y, Z such that * all characters in the string are included in at least one of the three sections, * X starts at the first character, Y starts at or right after the last character of X, and Z starts at or right after the last character of Y: ``` abcdefgh or abcdefgh XXX XXX YYY YYY ZZZ ZZZ ``` * and X is equal to the reverse of Y, and Y is equal to the reverse of Z. Some examples of tralindromes: ``` a (a / a / a) bb (b / b / b) - note that there are two possible choices for Y ccc (c / c / c) coco (co / oc / co) mamma (ma / am / ma) uhhuh (uh / hu / uh) xyyxxy (xy / yx / xy) banaban (ban / nab / ban) dottodot (dot / tod / dot) dadadadada (dada / adad / dada) ``` non-tralindromes: ``` xy coc faff xyzzy mummy random hotshot tralindrome dadadadadada aabaabaaaabaa abccbacbaabcabc ``` Given a nonempty string that entirely consists of lowercase letters, determine if it is a tralindrome. For output, you can choose to * output truthy/falsy using your language's convention (swapping is allowed), or * use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. Shortest code in bytes wins. [Answer] # Regex (Perl / PCRE2 / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~59~~ ~~47~~ ~~46~~ ~~38~~ ~~37~~ ~~33~~ 32 bytes ``` ^((.+)((.)(?3)\4|(?=\2$).?))?.?$ ``` [Try it online!](https://tio.run/##VU1Nb4MwDL37V1htVIjWj7GPS1OKKnU79tRjNRQCCCRCugBSacf@OjObOrWK/ez4PT8fE1u89rpFZgVeCqNkgWwh6Ouvtpv9Zt1BaqzLcv9RrNaCqscvmKc04ZejzcsaR4dyJDpkBfpYNVFVkzyczrypx5PPgcTgZv5IDMclslAAkhG6tDiZ/CsKUni8TJyxcz3gDhL/GxfMLnIeOHvbJEtEZ@m8y6Ki1uGiI7M/NSsEdmH4ttuGYf/huvMHTsDd4JkfXr7cwD88MT4POA/mAev7Me6tLPIytkYnFYCEKAKlFCijDGiptYQmy5oMTm17OrUQyVJSQmzq2hBALK8PYIw7U87qO0faIS9IZZpSfz63oButW7CyjI2GzNQVJdws3ViSqaRzQ/zCHTWQkVKRVINCUfwA "Perl 5 โ€“ Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VU_NTsJAEL7PU0xgQ7uRv6oHQykNCXrkxJHYbJc2NOl2cdsmFKwv4oWDvo5neRunIgay87fzffNN5v1jE5n0cPxWFTLj4j7VUqTIBi59vfFsuphOaoi1sVniDd3xxKXs8D0mMXX4fmOSrMDWMmu5NbIUPczLMC-IHnR7Ttfh0UsDon_RHxLCcYQscAFJCG0a7HT-GSkxHJ5FVts6L7AbiveGA2YGCfethSmjEaI1sp5EmlNpcbcmsRObpS7WQfA4nwXBZ1nEvYcjPtt2_4ZT4LZ_x5f3r7bvLW8Z7_uc-32fnXiHv3T8auPCiDTJVkarKAcQEIYgpQSppQYllBJQrtflGrZVtd1WEIpMkMNKF4WmACtxfgBtnOusV1wp0gxpQSzimOrdrgJVKlWBEdlKK1jrIieHi6ELSRIVtK6x33AFNWAoZShkw5Bkp7N-AA "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##XZJtb9sgEMff8ykosRrYHOdh2aaEWX6zdKo0pVOWd3OHMMG1NTAWxlLSrZ89O2ea1k5wp@Puzw840Vbt@UPWVi2OPE4xmRKc4NbrB@F1a6TSdDxNXmVCVNIEoZxta6N9TnPG8920G8d4DFZCUjzoQdAE3YSOCnFz@3kjBIvxnAGSTPuacFQ3teh0oKRVXieFVD@CBydMbetAYkyWi9Vy9e79YvWWMI5K52lUpzMembQEfke/7j/ebhlnP3Fd0sh864I3uoGITeb3aUryhjAQd30BFUjHs3gyZ/yirplWlRskHAN1zhGGPKb/GNfXgJzdX6Xj0RiOiGx6aYWVQVU08jFIOB4gf1pkZBeE9h5uya7SL7vNJ7G9E5vd7m6Xkc2QX2OyppHNyN73eo1hRW6k6SCE5@EnuMCFRiJD@NN/TaaMn79Tmrxm4BjN3rB8@Ytmab6IWJIxliVZdD6P8N5LUzcH76zuEJKoKJBSCimnHLLSWon6quordDydjscTKmQjwdDBheDAoYP8OxAa4a1rJuEFEfYAC5WyLCF@fDwh21t7Ql42B2dR5UIHhp5teoYEqITjhnlxL0pDsVAKvsGgUDB/Aw "PHP โ€“ Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=XZLdbtMwFMfFrZ_Cc6PVhjT9oHy0JsoNHZqEOhR6R4bluM4SESeR40jtYC8CN5MQr8P9eBpOWhAbss_J8Tl__2wf5dv3Jm9ufz36-iqCAHsWh5iMCQ5wY_WVsLoppdJ0OA4eR0LksnRC1aYpSm0TmjCexON26OMhWAZJcaV7QeV05VoqxNn525UQzMdTBkgy7grCUVEVotWOkkZZHaRSfXIWnCgLUzjiYzKfLeaL5y9mi2eEcZTVlnpFOOFeGWbAb-n7zevzNePsMy4y6pUfWmdLXUHERtPLMCRJRRiI2y6FCqT9iT-aMn5QF0yrvO4lHAN1yhGGPKb_GKengJxcnoTDwRCO8Ex4aIWRTuXUsz5IOO4hxxaVsnVCWwu3ZCfhu3j1RqwvxCqOL-KIrPr8EpMl9UxENrbTSwwrcibLFkJ4Hr6BCxxoxCsJv_mvyZTxH53LRi_v8EdKgycMHKPRU5bMv9AoTGYeCyLGoiDyjrrbP5-7nwO8sbIsqq2tjW4RkihNkVIKqVrVyEhjJOryvMvRbr_f7fYolZUEQ9vauRoc2sq_A6EBXtfVyD0gwh5goUxmGcTX13tkOmP2yMpqWxuU164FQ_c23UMCVMJx_Ty4B6W-mCoF_0avUDCPz_oN "PHP - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##XVFNj9owEL37V0xhtdi7QJel6iFZFqmHHnuoOLQCGjmO86EmduQ4grDlr5eOHWihTjwae2bem3kWdT3JhDgNCyXKNpHwEmvd2PdGZnI/zev6lYicG4jq9RYW8HXwabf7Gc/b7133bZV/3OX09IPS6SNDw@hyzjYfftHlYvN8x6ZLxpbT5d2J/V8zGMNDvYjqx1lI/hEXyGskr15JoSzUBm0kjdGGCq0aC76Ph0o2Dc8ke2tsEgQCE@DlBc63zvX3UiVlCEba1iiYhUcPWfFCUQZvBHDVa2QrpaI1m8y2i6cQWsyZP0cWtDu5ggwdn@wxMb9QGQbq1obQ9@TFCgKvFtLRenxzFQSF4I1k4eW2qbgVOexybnvkVBugjuvgSD1PJm1ZKEn7AQs17ikR5LCYXdp3q0iBHhhgzElDRxs1YuFN1Beun7Zwfw8X/91iNByxv2leC6d1Sq87jxrJjch7hLFveIwDMljCYGVaGQAMIIDBZ142eBhcEac7U1jZV05FhLJRdp5h2hQH6U6zsZtVu6l83dHb83uh6MfTEFaGow6J0fi4hHASx0QIQYQWmlS8qjhp87zNyb7r9vuOxFxx3CTR1mo0JOGXj5AhfNFqYm8QsQaxSMrTFP3DoSNVW1UdMVwluiK5tg1uclV0BYmgHOnc781NyAVjIWIuXIbA/7dIS541p0npRY68xn8A "C++ (gcc) โ€“ Try It Online") - Boost [Attempt This Online!](https://ato.pxeger.com/run?1=bU9LTsMwEN3PKYa0UmPRRi2wQEFWdixZddcWyXEcEsmfynGkJOImbLqBO7DlAOx7G-yWilZCno-tee-N39vHtneV0bvPWm2Nddj0zdSKF9GBRYo2iqL31pWz-z0-x3FyTXwhcXZL1nevcUbXN2OSZIRkSTb-xX15ymqRzhabBxzoHEpjUWKtg3LSuKLWKSDWJQ4pbm2tXUyObyl0LAkyXaBceTqlk7WepCipXM2D3j-w-eaKTkaTk5LQBY2WthUpYhTABydJI5jlVWyn6IlCNgKjR-ZbilHY_ceVJPx5cXSy23-PcGmZrHVhjRINAIM8B845cMMNKKYUg7aq2gq6vu-6HnKmmU8ojHPGFyjY6QCM8MnombtQ9ByvBSUrS38fhh5Uq1QP1vszCirjGp9wRjqT9KLMrwtxKBejMMw5zxkPCO7jaOsH "Python - Attempt This Online") - Python `import regex` This has been a special-case rollercoaster. The original versions needed `|^.$` to match one-character strings โ€“ and then two 38 byte versions suddenly didn't need that anymore, and just naturally matched one-character strings. And then at 37 the `|^.$` was back... it stuck around during the drop to 33 bytes. Now at 32 bytes, it's still there, but hiding. It's subsumed into the rest of the expression, at the cost of also matching an empty string (which is allowed by the challenge's rules). The following explanation is for the 33 byte version, because it's easier to format the comments. The transformation is `^pattern.?$|^.$` โ†’ `^(pattern)?.?$`, with all of `pattern`'s capture group indices incremented by 1. ``` ^ # Anchor start (.+) # Match the longest prefix that we conjecture (but later prove) # recurs as a suffix, and capture it in \1. # Match the palindromic subsection at the end, using recursion ( # Define recursive subroutine (?2) (.) # \3 = one character from the left side (?2) # Call self recursively \3 # Match the same character on the right side | # or... (?=\1$) # End the recursion. Assert that the remaining suffix exactly # matches the prefix we captured. .? # Optionally skip one character, which will happen if the # palindromic portion is odd in length. ) .? # Optionally skip one character at the end. This will have been # verified already by the "(?=\1$)" above, so we don't need to # do so again. $ # Assert we've reached the end of the string. |^.$ # Match a one-character string as a special case, since the # above algorithm only works on multi-character tralindromes. ``` A previous 38 byte version was PCRE2-only due to use of non-atomic lookahead, but that has turned out to be unnecessary. # Regex (Ruby), ~~53~~ ~~52~~ ~~44~~ ~~43~~ ~~39~~ 38 bytes ``` ^((.+)((.)\g<3>\k<4+0>|(?=\2$).?))?.?$ ``` [Try it online!](https://tio.run/##VU3fb4IwEH6/v@JEoxIjQbcnsRITt0cfFt/EkVKKkLWFFIhglv3rrOiWaHr35a7fj9N11HYaCX7wM28KR/EL7raHraM5jT3MiOvhJc0ER0HOvCoBMUswG/T/RV2VHnJ10y28nhDH@eJEiBUoyzMOcXQdZ7483VR360A4XBZV6@N4bOTuaUAmw4nhEAudqQoFkh/U6KN10DVfIVq4QuuditIs1n/Sn/a@huHbfheG3ed06sxsA3ZwXr9sgq/168zdfE99EixHtuPbtu/4o64b4kFTkalY55KXABSiCBhjwHKWg6RSUqjTtE6hadumaSGiipqGOK@q3ADE9P8BDHGfq3n1lGg8JgsSmiRmvl5bkLWULWiq4lxCmlelaXgwPUSaUGrO9XWDJ6onI8YiynoFM/UL "Ruby โ€“ Try It Online") This is the ~~47~~ ~~46~~ ~~38~~ ~~37~~ ~~33~~ 32 byte regex ported to Ruby's subroutine call syntax. `\k<4+0>` retrieves `\4` from the current level of recursion, whereas what `\4` would retrieve may have been overwritten at a deeper level of recursion. # Regex (.NET), 35 bytes ``` ^(.?(.)*.?)(?<-2>\2)*(?(2)^)\1$|^.$ ``` [Try it online!](https://tio.run/##bU/BasMwDL3rK0xqiF2WsPaYrEthsNt26m1dwXGcOSy2i@PQJF2@vVMHgw6GJVmS33uSj@6kfKdV216o37x59aGG9yyz6sS28eXA0oKlfJkWnBUPyfpxv@ZLVrA1P/D9in4dUnqJt3fRkzPHplVVxHM6be7z2nklpGa0JY0ltLHHPvBzUzM68fPJN0El2nVhRvAqb2qCwETYKrEuXNO2@VTxYhnzWzDBV1yrbawiEWU/LJ@@iCC16pDFOTnHO9@rjMQzUW2nsH4WeGfxzEk05/9r0Xa@LMjOC6wq74zqAASUJUgpQTrpwAhjBPRa9xqGcRyGEUphBTpULgSHASrxewAW5NXZJPxRRA5qQS3qGvNpGsH0xozg8dvOgHahQ4cb0o0kigocd7WfAKKUshTy2pJo3w "PowerShell โ€“ Try It Online") From [Neil's Retina answer](https://codegolf.stackexchange.com/a/250413/17216); please see his post for the explanation. Beats my .NET regex by ~~20~~ ~~12~~ ~~11~~ ~~7~~ 6 bytes. I have ported it to my style here, optimizing for the best speed at its length. Moving the special-case test to the end should make it theoretically faster to match any valid multi-character tralindrome, at the cost of being slower to match a one-character string. Ported to PCRE2, this is 55 bytes, demonstrating that what's optimal in one regex engine isn't necessarily so in others: ``` ^(?*((.?).*(?=(.*))(.?)))\2((.)(?5)\6|(?=\3$)\4)\1$|^.$ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZLdbtMwFMfFrZ_Cc6PVrtL0g26jC1Fu6NAk1KHSO7JZjussEXEcOY7Uju1F4GYS4jl4jvE0nLQgBorPyfHf5_xsH_nrtzqvH3---PI6hgB7FkeYjAgOcG3VLbeqLoVUtD8KBjHnuSgdl0bXRalsQhMWJqtR0_dxHywDkd-qLqFyqnIN5fzi8t2Cc-bjCQMkGbUFCVFRFbxRjpJaWhWkQn5yFhwvC1044mMym85n89Oz6fyEsBBlxlKviMahV0YZ8Bv6Yf3mcslC9hkXGfXKj42zpaogYsPJdRSRpCIMkps2hRWQ_bE_nLBwn10wJXPTpYQYqJMQYdAx_cs4Pgbk-Poo6vf6sIWno30rtHAyp571ISXEHeTQolI0jitr4ZTsKHq_Wrzlyyu-WK2uVjFZdPo5JufU0zFZ21adY5iRC1E2EML18AMcYE8jXknCh_-aTFn4vXXZ8NXT2Q2NB5QGMQsGNI5oMGCsmzGWTEFmND5hyek9LCUvPZbMWDLx7m8C71D--Pv39KOH11aURbWxRqsGIYHSFEkpkTTSIC20FqjN8zZH291uu92hVFQCDG2McwYc2og_H0I9vDTV0P1DhBpgoUxkGcR3dzukW613yIpqYzTKjWvA0LOiZ0iACtiuG3uHRColvJFOkjAO9_gF "PHP - Attempt This Online") - PCRE2 v10.40+ # Regex (.NET), ~~64~~ ~~63~~ ~~55~~ ~~47~~ ~~46~~ ~~42~~ 41 bytes ``` ^((.+)(.)*(?=\2$).?(?<-3>\3)*(?(3)^))?.?$ ``` [Try it online!](https://tio.run/##bU9fa4MwEH@/TxHagEk3ZVvfdJ2Fwd62p76tK8QYF5kxJUaqFj@7OwuDFkbuLnf5/UlytCflGq2qaqJu8@nUt@q@4rhWJ7YNpgNj0R1nEV@xdLN/ojxKWfocrl/26/mIrfmB8zRK6RRs7xev1hzLSuULntBh85AU1ikhNaMVKWtCy/rYen4uC0YHfj650qtQ28aPSH5MyoIgMRR1HtbWz21V/qhguQr4NZkgio@rylqRBWUXlYvehZdaNajinJyDnWtVTIKRqKpROL8J3ONg5GQxJv970WqclmTnBE65s0Y1AAKyDKSUIK20YIQxAlqtWw1d33ddD5moBSbk1nuLBXLxtwCW5MPWob9xRA16QSGKAvth6MG0xvTg8NvWgLa@wYQr0ZUlmgq8bo5LuYFmMJMyE3JmSIxf "PowerShell โ€“ Try It Online") At ~~55~~ ~~47~~ ~~46~~ ~~42~~ 41 bytes, this is now a port of the ~~38~~ ~~37~~ ~~33~~ 32 byte Perl/PCRE2/Boost regex. `((.)(?3)\4|pattern3.?)` becomes `(.)*pattern3.?(?<-3>\3)*(?(3)^)`, using .NET's balancing groups instead of recursion to match the palindromic subsection: `(.)*` - capture the left half of the palindrome, pushing it onto the `\3` stack one character at a time. `.?` - optionally skip one character, in the case that the palindrome is odd in length. `(?<-3>\3)*` - pop every character off the `\3` stack, matching them in reverse order. `(?(3)^)` - assert that if the `\3` stack isn't empty, then something impossible (that we're at the start of the string) is true โ€“ i.e. assert that the `\3` stack is empty. # Regex (Perl / PCRE / .NET), ~~61~~ ~~57~~ 51 bytes ``` ^(.+)((.?)(?=.*?(\3(?(4)\4|.?)$)))+(?=\1$).?\4$|^.$ ``` [Try it online!](https://tio.run/##VU1Nb4JAEL3Pr5joRnaroqT2IiIxsT325JFIlhUiCcvaBRLxo3/dDm1sNDtf@96bN4fUFm833SKzPp4Lo2SBbOLTN1isV5vV8gqZsZzlwdRfLH3qnjhjnhEizgeblzX2orLnX5EVGGDVJFVN8ng09kaeSL86EsMHfEqMwDmy2AckI@S0OBj8KwpSeKJMnb5zP8A7SfCNE2YnuQidjW3SOaIzdz5kUdHoCP9KZn9qVvh4jeP3z3Uc37bcHQrO3VDwMHBfQh698pDPRDS7EMaEEEMiIo8JN4xm7LJ12e3Wx42VRV7urNFpBSAhSUApBcooA1pqLaHZ75s9HNv2eGwhkaWkhJ2pa0MFdvL@APr4acpx/eRIO@QFmcwymk@nFnSjdQtWljujYW/qihIelh4syVTSuS5@yxPVkYlSiVSdQlH8AA "Perl 5 โ€“ Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VU_NTsJAEL7PU0xgY3cVCo0cDLU2JurRE8eGZru0oUm3i9s2oSK-iBcO-jqe5W2cihjMzt_O97PZt_dVaovd_ku3yKyPm8IoWSAb-XQNru9uZ7c3W8iM5SwPxv71jU_dExvMM9qIzcrmZY29qOz5W2QFBlg1SVUTPR4MvYEn0qcOxPBkPyZE4BRZ7AOSEXISnp39MQpieKJMnb5zfIB3lOAVR8yOchE6M9ukU0Rn6jzIoqLREf6WzA5sVvi4jeP7x7s4_mjqbHi1v5xz90Jw7oaCh4F7HvLokod8IqLJC-2YEOKCgMhjwg2jCXuZu-wg3f22_WcfZ1YWebmwRqcVgIQkAaUUKKMMaKm1hGa5bJawbtv1uoVElpISFqauDRVYyOMB6OOjKYf1P0fSkBdkMstofn5uQTdat2BluTAalqauKOFEdGJJppKe6-Kn_IM6MFEqkapjKIrDt74B "Perl - Attempt This Online") - Perl v5.36+ **[Try it online!](https://tio.run/##lVJRb5swEH73r3BdVOyVQKLlKYTxsnSqNKVTlrfRWsaYgoZxZBsp6drfnh2ZqjV9K7ZPx3efvzudrxSuOVolKjyxFQ5DbJfLkH/wC9Ey3zU7HFicYZIQHOOdVY/cql0npKJhEn/KOW9E57k0etd2yha0YGmxSVwYQdoI1wDyRzUSeq967yjnN7ffV5yzCM8YSIJwitq@5U55SnbSqrgU8re3YHjX6taTCJPJjLAUn9OskoN1renf0VBtLA3abJoGXVZDckd/br/erlnK/uC2pkH3y3nbqR48NpndZxkpesKA7IYSIgBH02gyGxMCu2VKNmakpBhUZynCgGP6X@PqCiSn9xdZeBlCikBnpz5p4WVDAxsBJcWjyL/@dcJ5rqyFKtlF9mOz@sbXd3y12dxtcrIa8QUmCxronGztoBYY/siN6By4YxdeoICTGgk6kr68ewHK0uMDja8ZpXHOaJ7BI9HiM83pnBXzZ8ACxtg1BIpZwOK8mAfPD3Fw/Oh0oFMJkx6qsOSLNJWKYVhStVcSJ4OzSdn2yTg@r6HjJd5a0bV9ZY1WDiGByhJJKZE00iAttBZoaJqhQfvDYb8/oFL0Ag6qjPcGDKrE60LoEq9NP/FninAHtFAt6hr8p6cD0oPWB2RFXxmNGuMdHPTm0htJEBWQbtwncxYag6WUMJkjQ8L@Cw "Bash โ€“ Try It Online") - PCRE1** [Try it online!](https://tio.run/##XZJRb9sgEMff@RSUoAZW10m6bFPiWX5ZWlWa0inL29wiTHBtDYyFsZR07WfPzpmmtZO503H35wc@aKv2@DlrqxZTj1NMJgTHuPX6UXjdGqk0G0/id5kQlTRBKGfb2mifs5wn@WbSjSM8BishKR71IGiCbkLHhLi@/boSgkd4xgFJJn1NElQ3teh0YKRVXseFVD@DBydMbetAIkzmV4v54uOnq8UHwhNUOs9onU4TatIS@B37vv1yu@YJ/4XrklHzowve6AYifjm7T1OSN4SDuOsLqEA6mkaXM56c1DXXqnKDJMFAnSUIQx6zf4zzc0BO78/S8WgMW1CbnlphZVAVoz4CSYIHyJ8WGdkFob2HU/Kz9NtmdSPWd2K12dxtMrIa8ktMlozajGx9r5cYZuRamg5C@D38Agc40Qg1JHn5r8mMJ8cHFl9wxuKMsyyFe2D5e5axOc/nz5CjnPMLKOQzyuMsn9Pnh5gejyO89dLUzc47qzuEJCoKpJRCyimHrLRWor6q@grtD4f9/oAK2UgwtHMhOHBoJ/9@CI3w2jWX4Q0R1gALlbIsIX56OiDbW3tAXjY7Z1HlQgeGXi16hQSohO2GcXJvSkOxUApexqBQMH4D "PHP โ€“ Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=XZLdbtMwFMfFrZ_Cc63VZmnabuWjDVFu6NAk1KHSO7JZjussEXESOY7Uju1F4GbStNfhfjwNJy2IDcU-OTnnf362j_Pjvs7qu18vvr-LwMHU4hCTIcE-rq2-ElbXhVSa9Yf-y0iITBZOqMrUeaFtzGIexMth0_dwH2YKQXGlO0HpdOkaJsTp2ce5ENzDYw5IMmxzEqC8zEWjHSO1stpPpPrqLBhR5CZ3xMNkcjydTF-_OZ6-IjxAaWUZzcNRQIswBX7DPq_eny14wL_hPGW0-NI4W-gSPD4YX4QhiUvCQdy0CWQg7I28wZgHO3XOtcqqThJgoI4DhCGO2T_G4SEgRxcHYb_XhyWoCXetMNKpjFHrgSTAHWTfokI2TmhrYZf8IPy0nH8Qi3MxXy7PlxGZd_EZJjNGTURWttUzDF_kVBYNuHA8fAsb2NEILUhw-1-TGQ8eWpcO3j6eXDL_iDPmR5xFIVwHi09YxCY8ntxAjHLOjyARjyn3o3hCby59ui-9-_N6_NnDKyuLvFzbyugGIYmSBCmlkKpUhYw0RqI2y9oMbbbbzWaLEllKmGhdOVeBQWv590GohxdVOXDPiFADLJTKNAX_-nqLTGvMFllZriuDsso1MNGToidIgEpYrhs78yzVJROl4HfpFArG_li_AQ "PHP - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##bU9fa4MwEH@/TxHagEk7ZWV9UoqFwd62p77NFWKMU2ZMiZGqrZ/dnYVBCyN3l7v8/iQ5mbOyTaGqaqJ292nVt@q@wrBWZ7b3piML1pyxIOYs3gWrmCUvLGZbnmyveEY552sEkg3lQZxs6fUY0MnbPy1ejT6VlcoWPKLD7jnKjVVCFoxWpKwJLetT6/ilzBkd@OVsS6f8wjRuRPImKnOCRF/UmV8bN7dV@aO85crj92SCKD6zKmtFFpTdVDZ4F04WqkEV5@TiHWyrQuKNRFWNwvlN4B56IyeLMfrfi1bjtCQHK3DKrNGqARCQpiClBGmkAS20FtAWRVtA1/dd10MqaoEJmXHOYIFM/C2AJfkwte8eHFGDXpCLPMd@GHrQrdY9WPy20VAY12DCnejOEk0FXjfHrTxAM5hKmQo5MyTGLw "PowerShell โ€“ Try It Online") - .NET This is a port of the ~~46~~ ~~38~~ 33 byte Perl/PCRE2/Boost version, to regex engines that don't have recursion (or do have it, but not in a non-atomic form, in the case of PCRE1). To match the palindromic subsection, group-building (with a nested backreference) is used instead of recursion. # Regex (Java / Perl / PCRE / .NET), ~~66~~ 56 bytes ``` ^(.+?)((.?)(?=.*?(\3(\4|(?!\6).?)$))())+(?=\1$).?\4$|^.$ ``` **[Try it online!](https://tio.run/##bZFbT9swFIDf/SsOoVrtMkzR0B6IsmqTxtNA0@BtHZLjOI3Bl852oKX0t3cnbZjoRhI79rl853YnHsTxXXW/0XbuQ4I7vHPt@SiH15I2afOmLKiZWnSaeVsaLUEaESNcCu1g1YtiEgl/D15XYFFBr1PQbgYizOLPXwxSE/xjhK8LqeZJe3QkABfaKKgLpx63R5px6SvFUZ@x/Etb1yqo6ocSlQpQbs32hfTFs7/WjOV93Pg@5Y9Nx6c0FiWWIKpv2inK2EHhWmOYrmnk6ncrTKTZyWg0yhhb7ZvuCJSmNwErJKS/BAScIKFEu/s8HhXDqRt2/5Svd7L1d5GSCg5C0Z@wWjvvAkSWYzeupXAOK9Vu3iYooCuul9HrZUzKcu0Yjscl0MU4h76@rT1vRLxSi4TpwQowM31QjFnv5lE/x7Yk42gHKE67eBhx1yuDwXYQh4S@dGQANdwoN0sNZZ/G8O4dGC4bET4nOsYmDA@HbDvG7rkUSTaYvEVW4HZ3owY5/@ZQU8tr7SrKYALZTWjVOUAG55BdYCPxgrNf/@fVodbrNekGtbml/GjCKOW4TQo@mtDpBzo9e6aTg@lHhtIBY9iII1ROTwcomJ4Nnm/5YNMNaXMIN0EYzCB4qyIhgpQlkVIS6aUnVlgrSNs0bUMWy@VisSSlcAIXqXxKHjdSiZeXkEO48u447RHRB1mkFnWN56enJbGttUsShKu8JY1PERd55fQKiVCB4bpvu@2pOmUpZSlkZyHx@wM "Java (JDK) โ€“ Try It Online") - Java 12.0.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=bZLbTtswGIAvduen-CkVtcswRUMTIsqqnZAmAUKUXa1Dchyn8ZbYneNAS-mT7IYL9jq7Z0-z301AsJGD4__0_Qfn5-03cSFu_rzo6nJqnYcgcm15P4LHmtrr4lmdUxM1-9eC8Qe6UBFM66TQEmQhqgqOhDawaFWVFx4_F1anUKKBjrzTZgLCTaovXxn43NnLCj7OpJp6bTGQAAQoZLFRl6stDUS-gvOJ8ifOeiWD8we7QrKgfW9TNbK1k6qRD60UwQclbz-ffmq0J8LnlLHoXZ1lyqn0VIlUOUhWuZ4q6X36VswwDGtr669e-ugyD3VSWsUJzkekh9pgcrYWm7oomM5oxdWPWhQV7Wz3-_0OY4unrg2BUv8sYIEE_0BAwDYSEvT7HlWbcW9seuHro2WjW2Jx2J5XzoCL2x2XtpyGHBWLYCSFMditNtPaQwyhwVZHR_PKq5Jrg37aeNDxIIK2wZU_z0V1rGYe64MFYGl6LR6wNsyifYpz8QXOGwHxThjVw7AKTNZADBLa3pEBtOCFMpNwJm8GsLEBBZe5cG89HeAUeus9tvofwnUkvMyx-BJZjpeNRIvQ1j81ZLTkmTYpZTCEzpmr1T5AB_ahc4CTRKHDouV_UQG1XC5JOKlftc-29u72zinfHDJKOS7DmPeHdPyKjnev6XBt_JqhtssYzmMTjeOdLirGu93rc95t4m_DkTXbm7vf63DmRIFlOVuqihBBkoRIKYm00pJSlKUgdZ7XOZnN57PZnCTCCHxJar23uJBU3N-ErMOxNVv-CRFjkEUykWW4v7qak7IuyzlxwqS2JLn1Fb7kUdAjJEIFpgvPanliCsZEykTI4CHxadr6Cw "Java - Attempt This Online") - Java 18.0.1+** [Try it online!](https://tio.run/##VU3LbsIwELzvV2zBauzyjEp7IIQIifbIiWNE5JhERIpj6iQS4dFfp5tWVCDvyzOzs/vE5m9X3SCzHp5yo2SObOTR158tF@vF/AKpsZxl/tibzT3qrjhhlhIiTnubFRV2wqLjXZDl6GNZx2VF8qg/cPuuSL5aEoM7fEyMwCmyyAMkI@S0@Pz8r8hJ4YoicbrO7QBvJf43jpgdZSJw1rZOpojO1PmUeUmjI7wLmf2pWe7hJYo@Vssoum74sBcIzodUAn/4EvDwlYeTMw@ewndBKBOCC9EjMnQZAeGEnTdDdr12cW1lnhVba3RSAkiIY1BKgTLKgJZaS6h3u3oHh6Y5HBqIZSEpYWuqylCBrbw9gC6uTDGoHhxph7wglWlK8/HYgK61bsDKYms07ExVUsLd0p0lmUo618ZveaBaMlYqlqpVKIof "Perl 5 โ€“ Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VU_LTsMwELzvVyytRWxKWyIqhJqGqBJw5NRjROQ4iRopjsFJpKal_AgXDvA7nOnfsKGAirwvz8yO5Ze3h9QWr7tP3SKzHm4Ko2SBbOzR1Z9dzxfzqy1kxnKW-2fe7Mqj7ooN5hkhYvNg87LGXlj2vC2yAn2smriqSR6dDt1TV6SPHYnBAX5GjMApssgDJCPktHh8_KcoSOGKMnX6zu8DvJP4zzhmdpyLwFnYJp0iOlPnVhYVjY7wtmS2V7PCw20U3dxdR9F7U2fDy93lPR8NAsH5iErgj04CHp7zcPLEg6PwQhDKhOBCDIgMXUZAOGFP9yO233_9abuPPi6sLPIysUanFYCEOAalFCijDGiptYRmuWyWsGrb1aqFWJaSEhJT14YKJPL3APTxzpTD-p8j7ZAXZDLLaF6vW9CN1i1YWSZGw9LUFSUcLB1Ykqmk57r4Lv-ojoyViqXqFIpi_60v "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##lVJNb9swDL3rVyiKUUur4yRYsUMcz5elQ4EhHbLc5laQZbk2ZlmBJANJP357Rmco1vRWSyLox6dHgmIhXH20SpR4YkschtgulyH/4BeiZbardziwOMVkSnCMd1Y9cKt2rZCKhtP4U8Z5LVrPpdG7plU2pzlL8s3UhRGkjXAFIH9QA6HzqvOOcn5982PFOYvwnIEkCCeo6RrulKdkJ62KCyH/eAuGt41uPIkwmcwJS/A5zSrZW9eY7h0NVcbSoElnSdCmFSR39Nf2282aJewJNxUN2t/O21Z14LHJ/C5NSd4RBmTXFxABOJpFk/mQENgNU7I2AyXBoDpPEAYc0/8aFxcgObsbpeE4hBSBTk990sLLmgY2AkqCB5F//WuF81xZC1WyUfpzs/rO17d8tdncbjKyGvAFJgsa6Ixsba8WGP7ItWgduEMXXqCAkxoJWpK8vHsBypLjPY0vM0ZpDCZL4ZVo/pnmV880G@VfGKABY5SxSwjm8wCA/Cp4vo@D40dHBJ3qmHRQiiVfpSlVDBOTqL2SeNo7Oy2abjrM0GvoOMZbK9qmK63RyiEkUFEgKSWSRhqkhdYC9XXd12h/OOz3B1SITsBBpfHegEGleF0IjfHadBN/pgh3QAtVoqrAf3w8IN1rfUBWdKXRqDbewUFvLr2RBFEB6YZ9MmehIVhICeM5MCTsvw "Bash โ€“ Try It Online") - PCRE1 [Try it online!](https://tio.run/##XZLRbpswFIbv/RSOYxV7JSTpsk6Jh7hZOlWa0inL3Wgt45iChgEZIyVd@@zZIdO0dsI@Ovzn92dzTFu0p09JW7SYOhxjMiU4wq0zj9KZtlLasGAavUukLFTlpW5sW1bGpSzlIt1OuyDEAcwcRPloBkPtTe07JuXN7de1lDzEcw5IMu1LIlBZl7IznpFWOxNlSv/0DoKsSlt6EmKyuFoultcfr5YfCBcobxyjZTwTtIpz4Hfs@@7z7YYL/guXOaPVj867ytSQ8cn8Po5JWhMO5q7PoAJyOAsncy7O7pIbXTSDRWCgzgXCoGP2j3FxAcjZ/SgOxgFsQW18boVVXheMuhAsAg@QPy2qVOelcQ5OyUfxt@36i9zcyfV2e7dNyHrQV5isGLUJ2bnerDC8kRtVdZDC5@EXOMCZRmhFxMt/TWZcnB5YdJlwxiIISQwXwdL3LF08s2SUXnNQKeeM80sopnMKQrqgzw8RPZ3GeOdUVdZ711jTIaRQliGtNdKNbpBV1irUF0VfoMPxeDgcUaZqBRPtG@8bCGiv/j4IjfGmqSf@DRHWAAvlKs8hf3o6Ittbe0RO1fvGoqLxHUz0atErJEAVbDeMc3hTGoqZ1vB7DA4N4zc "PHP โ€“ Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=XVLRbtMwFBWv_grXtVabpWk7ylgXorysQ5NQh0rfyGY5rrNExEnkOFI7th-Bl0mI3-F9fA03LYgN2ffm-txzj-3rfPteZ_XDrxdf30YQYGpxiMmIYB_XVt8Iq-tCKs0GI_9lJEQmCydUZeq80DZmMQ_i5agZeHgAlgIobnRHKJ0uXcOEOL94PxeCe3jCQZKM2pwEKC9z0WjHSK2s9hOpPjsLThS5yR3xMJkezaaz4zdHs9eEByitLKN5OA5oEaag37CPq7OLBQ_4F5ynjBafGmcLXULEh5OrMCRxSTiQmzaBDMDe2BtOeLBj51yrrOooAQbVSYAw4Jj90zg4AMnxVS8c9AewBTXhrhVGOpUxaj2gBLgT2beokI0T2lo4Je-FH5bzd2JxKebL5eUyIvMOP8XklFETkZVt9SmGFTmXRQMhXA_fwwF2aoQWJLj_r8mMBz9alw5PHk-umX8YccZ8cFEI78HiVyye3rGoFx9zQCnnjPNDSMYTCkA8pXfXPt3XP_z5PP7s45WVRV6ubWV0g5BESYKUUkhVqkJGGiNRm2Vthjbb7WazRYksJRhaV85V4NBa_h0I9fGiKofumSLUgBZKZZpCfHu7RaY1ZousLNeVQVnlGjD0pOiJJIhK2K6bO_cs1SUTpeCf6RgK5v5avwE "PHP - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##bU9fa8IwEH@/T5FpoInOMpnswSIVBnvbnnxbJ6RpupQ1jaQp2mo/e3cVBgojl8vd/f4kOdijcrVWZTlQt/l06ludvtbrSh3ZNhj2LJzHnLEQU7wJZzFLnlmyurD4IXnhOKWcM87nCCZLioNkRS/7kA7B9nHyas2hKFU24RHtNk9Rbp0SUjNakqIitKgOjefnIme04@ejK7xaaFv7HsnLqMgJEheiyhaV9WNZFj8qmM4CfksmiOJby6JSZELZVeXCd@GlVjWqOCfnYOcatSZBT1RZK@zfBJ7roOdk0kf/e9GyH6Zk5wR2mbNG1QAC0hSklCCttGCEMQIarRsNp7Y9nVpIRSVwQ2a9t5ggE38LYEo@bLXwd46oQS/IRZ5j3XUtmMaYFhx@2xrQ1te44UZ0Y4mmAq8b45ruoBFMpUyFHBkS4xc "PowerShell โ€“ Try It Online") - .NET This is a port of the ~~61~~ 51 byte Perl/PCRE/.NET version, to regex engines that don't have conditionals but do have nested backreferences. Java seems to have some bugs in its regex engine, especially in the vein of giving up on backtracking when there are too many possibilities (and there don't even have to be all that many). To work around this, `(.+?)` is used instead of `(.+)`. If Java's regex engine were really behaving well, this wouldn't be necessary. Some other variants don't play nice in Java. For example, a port of the previous 57 byte Perl/PCRE/.NET version is **62 bytes**: ``` ^(.*)(?=(.)).?((.)(?=.*(\4(\5()|(?!\7))$)))*(?=\1\2$).?\5$|^.$ ``` But fails in Java: [Try it online!](https://tio.run/##bZFbT9swFIDf/SsOoaJ2NkyZhiYRZdUmjSdA0@BtGZLjOI0htjvbgZbS396dtGGCjTaJfW7fud2Ke3F4W91ttJk7H@EWZa4dTzN4qemibt/UeTVTi94y78pWS5CtCAEuhLawGlQhiojHvdMVGDTQq@i1nYHws/DzF4PYePcQ4NtCqnnUDgMJwJluFdS5VQ/bK024dJXiaE9Y9rWra@VV9UOJSnkot26vlfQ5chBrxrIhb3gfs4em51Ma8hJbENW5tooytpfbrm2Zrmng6ncn2kCTozRNE8ZWr113BErjm4AVEuJfAgKOkFCi310W3uXjwo77M2brnW79XcSovAWfDzfs1sz7BIFlOI0rKazFTrWddxFy6JsbdPRqGaIyXFuG67ERdD7JYOhv688bES7VImJ5sAKsTO/lEzaEObTPcSyxtbQH5Md9Psy4m1WLyXYQi4ShdWQAbXmr7Cw2lH2ewMEBtFw2wn@JdIJDGO@P2XaN/e9CRNlg8QZZnpudRFvk/FtDTQ2vta0ogykk175TpwAJnEJyhoNEAXe//i@qR63Xa9IvanNDecroNKecMT6leKDAU1p8pMUJZU90uld8YmzEGEvRUhwXH0boWJyMnm74aNOvarMP1160WId3RgVCBClLIqUk0klHjDBGkK5puoYslsvFYklKYQW@pHIxOvyQSjz/CdmHS2cP4ysixiCL1KKu8f74uCSmM2ZJvLCVM6RxMeBLXgS9QCJUYLr@2X6IKKUshexVEp8/ "Java (JDK) โ€“ Try It Online") (12.0.2) / [Attempt This Online!](https://ato.pxeger.com/run?1=bZLdTtswFIAvduenOJSK2t1myjS0iShU-0OaBAhRdrUOyXGcxltid44DLaVPshsu2HPsOdjT7LgJCBhJ_HOOz_nOj_Pr-rs4E1d_n3V1ObXOQxC5trwfwX1N7XXxpM6piZo9PkH_PV2oCKZ1UmgJshBVBQdCG1i0qsoLj8uZ1SmUeEBH3mkzAeEm1ddvDHzu7HkFn2ZSTb226EgAAhSy2Kjz1ZYGIl_B-UT5I2e9ksH4o10hWdB-sKka2dpJ1cj7Vopgg5K3X44_N9oj4XPKWPS-zjLlVHqsRKocJKtYD5X0NnwrZuiGubX5Vy98dJ6HPCmt4gT7I9J9bTA4W4tNXRRMZ7Ti6mctiop2Nvv9foexxUPThkCpfxKwQIK_IyBgEwkJ2v2Iqudxb2x6YfXRstEtMTkszytnwMXtjktbTkOMikUwksIYrFabae0hhlBgq6OjeeVVybVBO2086HgQQVvgyp7nojpUM4_5wQIwNb0WD1jrZvF8in3xBfYbAfFWaNVdswoM1kAMEtrakQG04IUyk3AnuwPY2ICCy1y4d54OsAu99R5b_Q_hORBe5ph8iSzHy0aiRSjrUQ4ZLXmmTUoZDKFz4mq1A9CBHejsYSdR6LBo-Z9XQC2XSxJu6nfts5dvb3ZPKe8zOowpZ4wPKS4o8D4dv6bjbcou6XBt_IaxLmOsjyfjrfGrLhqOt7uXp7zbUK7DxTXbq5s_63DiRIHJOVuqihBBkoRIKYm00pJSlKUgdZ7XOZnN57PZnCTCCBwktd5bnEgqbl9C1uHQmpf-ARF9kEUykWW4v7iYk7IuyzlxwqS2JLn1FQ5yz-keEqECw4VvNRGRSJkIGVQSv6aOfw "Java - Attempt This Online") (18.0.1+) This warrants further research. # Regex (Perl / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), ~~61~~ 59 bytes ``` ^(.+)((.?)(?=.*?(?=(\3(?(5)\5|.?)$))(\4)))+(?=\1$).?\4$|^.$ ``` [Try it online!](https://tio.run/##VU1Nb4JAEL3Pr5jopuy2FiXVi4ikie3Rk0dSsiwQSFi2XSCRKv3rdmhjY7Pzte@9efOe2Wp10T0y6@OpMkpWyOY@fYPN7vnwvB0gN5azMlj4m61P3RMnLHNCxOndlnWLk6ie@AOyCgNsuqRpSR7PHr2ZJ7KPkcTwBl8QI3CNLPYByQg5Ld7d/SkqUniizpypcz3AR0nwhXNm56UInYPtsjWis3ZeZdXQ6Ah/ILNfNat8HOL4Zb@L48sbdx8E524oeBi49yFVHj3xkK9EtDoTzITg0VII8UBU5DHhhtGSnd9cdrlM8WBlVdapNTprACQkCSilQBllQEutJXRF0RVw7PvjsYdE1pISUtO2hgqk8voAprg39WP7z5F2yAtymec0f372oDute7CyTo2GwrQNJdws3ViSqaRzY/yUf9RIJkolUo0KRfEN "Perl 5 โ€“ Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VU9LTsMwEN3PKUbUIjbQlAgqoZoQIQHLrrqMiBw3USPFMTiJ1FDKRdiwgOuwprdhQgG18vw8780bzev7Q-bKt82X6ZA5iavSalUiG0n6hpc317PrqzXk1nFWhKfy8kpSDsQKi5w6YvXgiqrBg7g6kGtkJYZYt2ndED05GQYngcgeexCjnf4pIQInyBIJSELIafDw8J9REiMQVeYNvL8FvKeELzhiblSIyJu5NpsgehPvTpU1lZ6QaxLbslkpcZ0kt9ObJPlom3x4sZH33D8WnPuR4FHoH0UUeXzGIz4W8fiZ2kwIHp8LIY4JigMm_Cg-Z8_3PttKvP2mzecAZ06VRTV31mQ1gII0Ba01aKstGGWMgnaxaBew7LrlsoNUVYoc5rZpLAWYq78HMMCprYbNniLNkBbkKs-pfnrqwLTGdOBUNbcGFrapyWFnaEeSRBWt6-0n7EE9mGqdKt0zNNn2rG8 "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##lVJRb5swEH73r3AdVOyVQKK1L6GMl6VTpSmdsryN1jLGFDSMI9tISdf@9uzIVK3pW7F9Or77/N3pfKVwzcEqUeGprXAYYnt9HfIPfiG6zrfNFgcWZ5gkBMd4a9Ujt2rbCalomMSfcs4b0Xkujd62nbIFLVharBMXRpA2wjWA/FGNhN6r3jvK@c3t9yXnLMJzBpIgnKK2b7lTnpKttCouhfztLRjetbr1JMJkOicsxac0q@RgXWv6dzRUG0uDNpulQZfVkNzRn5uvtyuWsj@4rWnQ/XLedqoHj03n91lGip4wILuhhAjA0SyazseEwG6Zko0ZKSkG1XmKMOCY/tc4PwfJ2f1ZFk5CSBHo7NgnLbxsaGAjoKR4FPnXv044z5W1UCU7y36sl9/46o4v1@u7dU6WI77AZEEDnZONHdQCwx@5EZ0Dd@zCCxRwVCNBR9KXdy9AWXp4oPEFozTOGc0zeCSwtPhMc3rFiqtngAPGaHHJGLuAUDEPWJwXl8HzQxwcPjol6FjKtIdqLPkiTaViGJpU7ZTEyeBsUrZ9Mo7Ra@gwwRsruravrNHKISRQWSIpJZJGGqSF1gINTTM0aLff73Z7VIpewEGV8d6AQZV4XQhN8Mr0U3@iCHdAC9WirsF/etojPWi9R1b0ldGoMd7BQW8uvZEEUQHpxn00J6ExWEoJEzoyJOy/ "Bash โ€“ Try It Online") - PCRE1 [Try it online!](https://tio.run/##XZJRb9sgEMff@RSUoBpWx0m6ZFPiWX5ZOlWa0inL29wiTHBtzRgLYynp2s@enTNNaydzp@Puzw980Jbt6VPali2mDieYTAiOcOv0o3C6raXSLJhE71IhSll7oaxpq1q7jGU8zraTLghxAFZAUjzqQdB43fiOCXFz@3UtBA/xjAOSTPqKxKhqKtFpz0irnI5yqX56B07Ulak8CTGZXy/nyw8fr5cLwmNUWMdolUxjWicF8Dv2fff5dsNj/gtXBaP1j867WjcQ8fHsPklI1hAO4q7PoQLpcBqOZzw@qyuuVWkHSYyBOosRhjxm/xiXl4Cc3l8kwSiALahJzq0w0quSUReCJMYD5E@Latl5oZ2DU/KL5Nt2/UVs7sR6u73bpmQ95FeYrBg1Kdm5Xq8wzMiNrDsI4ffwCxzgTCO0JvHLf01mPD49sOiKMxalnKUJ3AN4lr1nKVvwbPEMaco5y@ac8ysoZTPKozSb0@eHiJ5OI7xzsq6avbNGdwhJlOdIKYWUVRYZaYxEfVn2JTocj4fDEeWykWBob7234NBe/v0QGuGNbcb@DRHWAAsVsiggfno6ItMbc0RONntrUGl9B4ZeLXqFBKiE7YZxdm9KQzFXCl7IoFAwfgM "PHP โ€“ Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=XZJRb9MwEMfFqz-F50arzdK0HS3QmigvdGgS6lDpG9ksx3WWiDiJHEdqx_ZF4GUS4uvwPj4NlxbEhuK7XO7-_tk-59v3Oqvvfz37-iaCAHsWh5gMCQ5wbfW1sLoupNK0PwyeR0JksnBCVabOC21jGjMer4ZN38d9sBSS4lp3gtLp0jVUiLPz9wshmI_HDJBk2OaEo7zMRaMdJbWyOkik-uwsOFHkJnfEx2RyOpvMXr46nU0J4yitLPXycMS9IkyB39CP67fnS8bZF5yn1Cs-Nc4WuoSIDcaXYUjikjAQN20CFUj7I38wZnyvzplWWdVJOAbqmCMMeUz_MY6PATm6PAr7vT4s4Zlw3wojncqoZ32QcNxBDi0qZOOEthZ2yY7CD6vFO7G8EIvV6mIVkUWXn2Myp56JyNq2eo7hi5zJooEQjofvYAN7GvEKwu_-azJl_Efr0sHrB35FgxNGaRAxGoVwHeBp_IJGdMri6S2kPcZoPGGMnUApHnssiOKJd3sVeAfE_Z_Xw88eXltZ5OXGVkY3CEmUJEgphVSlKmSkMRK1WdZmaLvbbbc7lMhSgqFN5VwFDm3k3wehHl5W5cA9IcIcYKFUpinENzc7ZFpjdsjKclMZlFWuAUOPJj1CAlTCct3YuyelrpgoBb9Np1AwDsf6DQ "PHP - Attempt This Online") - PCRE2 v10.40+ **[Attempt This Online!](https://ato.pxeger.com/run?1=bY_NTsMwDMfvfgrTTVoCrNoEk1CnqjeOnLitm5SmKa2UjylNpXXiTbjsAu_AlQfgvrfBZSBAQrGdD_v_c_z0su1D7ezhtTFb5wO2fXvp1YPagccUfRRFz12opjfH5YbFF5yxOOMsS-PzjCLLr1jGFjxfPNLzmHOWX3POLyiVz8c8zvLr8eMmHn8h3oi2mifT-XqJ-3QGlfOosbFD07gNZWMTQGwq3Ce49Y0NjJ_uWlmmOQpbol6RPE0nuZ0kqFO9mg28f8pm67N0Mpp8k5Qt0-jedypBjIbizyHjVgkva-YvkYRKtwqjW0FbgtHQ-0er-fDn-WmSw_F9hPde6MaW3hnVAggoCpBSgnTSgRHGCOjquqth1_e7XQ-FsIIcSheCowCl-F4AI7xzdhr-EElDLKhEVdF5v-_BdMb04Gk-Z6B2oSWHX6JfSIIKajfYZ_iTGpKFlIWQQ4UkO431AQ "Python โ€“ Attempt This Online") - Python `import regex`** [Try it online!](https://tio.run/##bU9fa4MwEH@/TxHagEk7ZWXti1IsDPa2PfVtrhBjnDJjSoxUbf3s7loYtDByd7nL70@Sozkp2xSqqiZqt59WfavuKwxrdWI7bzqwYMkZC2LO4m2wiLGy5IXFbMOTzQWPKecsWXPOlwglK8qDOFnTyyGgk7d7mr0afSwrlc14RIftc5Qbq4QsGK1IWRNa1sfW8XOZMzrw88mWTvmFadyI5FVU5gSJvqgzvzbu2lblj/LmC4/fkwmi@NyqrBWZUXZT2eBdOFmoBlWck7O3t60KiTcSVTUK5zeBe@iNnMzG6H8vWo3TnOytwCmzRqsGQECagpQSpJEGtNBaQFsUbQFd33ddD6moBSZkxjmDBTLxtwDm5MPUvntwRA16QS7yHPth6EG3Wvdg8dtGQ2Fcgwl3ojtLNBV43TVu5QG6gqmUqZBXhsT4BQ "PowerShell โ€“ Try It Online") - .NET This is a port of the 51 byte Perl/PCRE/.NET regex to engines that lack nested backreferences. To emulate them, `\4` and `\5` are copied back and forth to each other. Ruby does not work with this regex at all. It just hangs. # Regex (Java / Perl / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 64 bytes ``` ^(.+?)((.?)(?=.*?(?=(\3(\6|(?!\7).?)$))(\4))())+(?=\1$).?\4$|^.$ ``` [Try it online!](https://tio.run/##bZFbT9swFIDf/SsOoaJ2GaZoaJOIsmqTxtNA0@BtGZLjOI0htjvboS2lv707acNEN9rkxD6X79zuxaM4uS8fNtrMnI9wj3euHR@l8FrTRt28qfNqqhadZdYWjZYgGxECXAltYdWrQhQRP49Ol2DQQG@i13YKwk/Dz18MYu3dPMDXhVSzqB0GEoBL3SioMqvm2yNNuHSl4mhPWPqlrSrlVflDiVJ5KLZu@0r6EtlfK8bSPm94F9N53fEpDVmBLYjym7aKMnaQ2bZpmK5o4Op3K5pAk9PRaJQwttp33REojW8CVkiIfwkIOEVCgX4PaTjOhrkddt@Yrne69XcRo/IWfNafsFsz6xIEluI0bqSwFjvVdtZGyKBrrtfRm2WIynBtGa7HRtDZOIW@v60/r0W4VouI5cEKsDJ9kI1ZH@bQPsOxxMbSDpCddfkw425WDSbbQSwS@taRAbThjbLTWFP2aQxHR9BwWQv/OdIxDmF4OGTbNXa/KxFljcUbZHludjfaIOffGipqeKVtSRlMILn1rboASOACkkscJF5w9@v/ojrUer0m3aI2d5QfTxilHMUk46MJSpq/p/mHZzo5yD8yNAwYo/k5CsaO0ZyfDVCbnw@e7/hg0y1rcwi3XjRYiXdGBUIEKQoipSTSSUeMMEaQtq7bmiyWy8ViSQphBb6kdDE6FKQUL39CDuHa2ZO4R8QYZJFKVBWen56WxLTGLIkXtnSG1C4GfMmroFdIhApM1z1bsWfqjIWUhZCdh8TnDw "Java (JDK) โ€“ Try It Online") - Java 12.0.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=bZLbTtswGIAvduen-CkVtcswRUPbRJR1R6RJgBBlV-uQHMdpvCV25zjQUvoku-GCvc7u2dPsd1MQZeTg-D99_8H5dfNdnIvrv8_auhxb5yGIXFvejeChpva6eFLn1EhNHlswfl8XKoJxnRRagixEVcGh0AZmS1XlhcfPudUplGigA--0GYFwo-rrNwY-d_aigk8TqcZeWwwkAAEKWWzUxWJLA5Ev4Hyk_LGzXsng_NEukCxoP9hUDWztpGrkAytF8EHJ2y8nnxvtsfA5ZSx6X2eZcio9USJVDpJFrlUlvUu_FDMMw9qW9VfPfXSRhzopreIE5yPSA20wOVuLTV0UTGe04upnLYqKtra73W6Lsdmqa0Og1D8JmCHB3xMQsI2EBP1-RNVm3BmaTvj6aN7o5lgctueVM-Di5Y5LW45DjopFMJDCGOxWm3HtIYbQ4FJHB9PKq5Jrg37aeNBxL4Jlgwt_novqSE081gczwNL0WtxjyzCL9jHOxRc4bwTEO2FU98MqMFkDMUhY9o4MoAUvlBmFM3nTg40NKLjMhXvnaQ-n0FnvsMX_EK5D4WWOxZfIcrxsJFqEth7VkNGSZ9qklEEfWqeuVnsALdiD1j5OEoUWi-b_RQXUfD4n4aR-1z7ben379ozyzT6jlOPSj3m3jysdvqDDl1e0vzZ8xdDQZowOd3FhbBPNw502aoe77asz3m44N-Homu317Z91OHWiwPKcLVVFiCBJQqSURFppSSnKUpA6z-ucTKbTyWRKEmEEviS13ltcSCrubkLW4ciaLb9CxBhkkUxkGe4vL6ekrMtySpwwqS1Jbn2FL3kQ9ACJUIHpwrNYVkzBmEiZCBk8JD5NW_8A "Java - Attempt This Online") - Java 18.0.1+ [Try it online!](https://tio.run/##VU1NT8MwDL37V5gtogmDjoovaV2pkIAjpx2rVWnWqpWSBtJWWhnlrxcXBBqK/ez4PT@/5k7fjKZH5kI8aKukRrYM6RutHx82D/cDFNZxVkWX4fo@pBqIA1YFTcTh1VV1i7OknoUDMo0RNl3WtCRPzy@C80DkbxOJ8dH8khiBK2RpCEhGyGnx9PRPoUkRiDr35t7vAT5Jok9cMresROxtXJevEL2V9yx1Q60nwoHMftRMhzik6dPLY5qOW@4vYsG5TxBH/llMyJMrntx@8PgkuRNEMCF4ck0gxILoJGA0Ta7Zx9Zn4zjHjZO6qnfOmrwBkJBloJQCZZUFI42R0JVlV8K@7/f7HjJZS0rY2ba1BLCTvw9gji@2vmj/OdIOeUEhi4L69/ceTGdMD07WO2ugtG1DCUdLR5ZkKuncFN/wj5rITKlMqkmhKL4A "Perl 5 โ€“ Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VU_LTsMwELzvVyzUIjb0QQQC1DQNSIUjpx4jIsdN1EhxXJxEaijlR7j0AL_Dmf4NGwqoyLuz653Zsfz6tkhsvtl-6gaZ9XCVGyVzZAOPrv5ocjO9Ga8hNZazzD_1RmOPqitWmKU0EauFzYoKD8Pi0Fsjy9HHso7LiuRRt-d2XZE8tiQGe_NTYgQOkUUeIBkhp8Wjoz9FTgpXFInTcX4f4K3Ef8EBs4NMBM7U1skQ0Rk6dzIvqXWEtyaznZrlHq6j6PZ-EkXvdZX2rrbXD7x_EgjO-wSB3z8OCHl4xsOLZx4chJeCCCYED88JhDghOnQZTcNz9vzQZzufzU_ZfnRwamWeFTNrdFICSIhjUEqBMsqAllpLqOfzeg7LplkuG4hlISlhZqrKEMBM_h6ADt6bolf9c6Qd8oJUpin1T08N6FrrBqwsZkbD3FQlJewt7VmSqaTn2viGf1RLxkrFUrUKRbH71hc "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##lVJRb9sgEH7nVxBi1bA6TqJVmxTH88vSqdKUTlne5hZhjGtrxkSApaRrf3t2zlSt6VsNnM73fXx3Oq4Qrj5aJUo8sSUOQ2yXy5C/8wvRMtvVOxxYnGIyJTjGO6seuFW7VkhFw2n8IeO8Fq3n0uhd0yqb05wl@WbqwgjSRriCIH9QA6HzqvOOcn59833FOYvwnIEkCCeo6RrulKdkJ62KCyF/ewuGt41uPIkwmcwJS/A5zSrZW9eY7g0NVcbSoElnSdCmFSR39Of2682aJewPbioatL@ct63qwGOT@V2akrwjDMiuLwCBcDSLJvMhIbAbpmRtBkqCQXWeIAxxTP9rXFyA5OxulIbjEFIEOj31SQsvaxrYCCgJHkT@9a8VznNlLVTJRumPzeobX9/y1WZzu8nIaogvMFnQQGdka3u1wPBHrkXrwB268AwFnNRI0JLk@c0LUJYc72l8mTFKYzBZCq8EluYfaf7piWaj/DMDIGCM5ldgGLsEOJ8HEM2vgqf7ODi@d1TQqZ5JByVZ8kWaUsUwOYnaK4mnvbPToummwyy9QMcx3lrRNl1pjVYOIYGKAkkpkTTSIC20Fqiv675G@8Nhvz@gQnQCDiqN9wYMKsXLQmiM16ab@DNFuANaqBJVBf7j4wHpXusDsqIrjUa18Q4OenXplSSICkg37JM5gwawkBLGdGBI2H8B "Bash โ€“ Try It Online") - PCRE1 [Try it online!](https://tio.run/##XZLRbtsgFIbveQpCUAOr4yRd1iphlm@WVpWmdMpyN7cIE1xbM7aFsZR07bOnx6mmtZPh1/E5Px/44CZvjl/jJm8wdTjCZEJwiBtnHqUzTam0YaNJ@CmWMlell7q2TVEal7CEi2QzaUcBHsHMICkfTW@ovKl8y6S8vv2@kpIHeMYBSSZdQQQqqkK2xjPSaGfCVOnf3oHIsrCFJwEm84vFfHF5dbH4QrhAWe0YLaKpoGWUAb9lP7ffbtdc8D@4yBgtf7XelaaCiI9n91FEkopwMLddChVIB9NgPOPi5C640XndWwQG6kwgDHnM/jHOzgA5vR9Eo@EItqA2OrXCKq9zRl0AFoF7yFuLStV6aZyDU/JB9GOzupHrO7nabO42MVn1@SUmS0ZtTLauM0sMb@RalS2E8Hn4BQ5wohFaEvHyX5MZF8cHFp7HnLEQJI7gIkBZ8pkll88sHiRXHAqUc5bMQTg/h3Iyo5BN5vT5IaTH4xBvnSqLaudqa1qEFEpTpLVGutY1sspahbo873K0Pxz2@wNKVaVgol3tfQ2Cdurvg9AQr@tq7D8QYQ2wUKayDOKnpwOynbUH5FS1qy3Ka9/CRO8WvUMCVMF2/TjJh1JfTLWG36R3aBiv "PHP โ€“ Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=XZJRb9MwEMfFqz-F61qrzdK0HWWjC1F4oEOTUIdK38hmOa6zRMRJ5DhSO7YvAi-TEF-H9_FpuLQgNhTf5XL398_2Od--11l9_-vZ19cRBJhaHGIyItjHtdXXwuq6kEqzwch_HgmRycIJVZk6L7SNWcyDeDlqBh4egKWQFNe6E5ROl65hQpydv58LwT084YAkozYnAcrLXDTaMVIrq_1Eqs_OghNFbnJHPEymR7Pp7PjkaPaS8ACllWU0D8cBLcIU-A37uHp7vuAB_4LzlNHiU-NsoUuI-HByGYYkLgkHcdMmUIG0N_aGEx7s1DnXKqs6SYCBOgkQhjxm_xgHB4AcX_bCQX8AS1AT7lphpFMZo9YDSYA7yL5FhWyc0NbCLnkv_LCcvxOLCzFfLi-WEZl3-VNMThk1EVnZVp9i-CJnsmgghOPhO9jAjkZoQYK7_5rMePCjdenw1cObK-YfRpwxH1wUwn2AZ_ELFh_fsqgXn3AoUM5ZPAXH-SGU4wmFbDylt1c-3XPu_7wefvbxysoiL9e2MrpBSKIkQUoppCpVISONkajNsjZDm-12s9miRJYSDK0r5ypwaC3_Pgj18aIqh-4JEeYAC6UyTSG-udki0xqzRVaW68qgrHINGHo06RESoBKW68bOPSl1xUQp-Hc6hYKxP9Zv "PHP - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##bU9Na8JAEL3PrxhjwN2qwaC0kBK89diTN2Nhs9k0gf2QzQqJ@N/txCJVKDvz9uPNe7NzHELj7PramqPzAbuhW3j1rXrwmKOPouj6xZL5ljOWEGzz5GVLyIo1K14vbDsp3jgRMees2BBwPie6SGN6LTbx5SuJr2SyT7NlenjHc76C2nnU2NqxV9KFqrUZILY1njM8@tYGxn/vWlmmOQpbod6TPM9nhZ1lqHO9X41@/5StDpN8Np3dnZSt8mjnTypDjMbi22xJp4SXDfMLJKHSncLoQ9CWYTT2/tNqPv45vU5x54VubeWdUR2AgLIEKSVIJx0YYYyAU9OcGuiHoe8HKIUVlFC5EBwBVOK@AKb46ewyPDmShrygFnVN5/N5AHMyZgBPczkDjQsdJTyIHizJVFC7MW7wRI1kKWUp5FghKX4A "Python 3 โ€“ Try It Online") - Python `import regex` / [Attempt This Online!](https://ato.pxeger.com/run?1=bU9LTsMwEN3PKaZppdpAo1ZUgIKismLJqrumlRzHIZH8qRxHaipuwoYN3IEtB2DPbZhQEFRCnnn-vHlvPI8v2y5Uzj691mbrfMCma868ulc78Jiij6LouQ3l5OrjZsPi0wVnLCZYpPHJgpBl5yy7eGCLQXbJiRhxzrI5AeenRGezEb1m89HDJh59-7yR5WqWTGbra9ynUyidR4217TvHTShqmwBiXeI-wa2vbWD8cNfKMs1R2AL1iuRpOs7sOEGd6tW09_unbLoepOPh-MdJ2SKNlr5VCWLUF39NGjdKeFkxf4YkVLpRGN0K2hKM-t6_Ws37P88Okzx9vA9x6YWubeGdUQ2AgDwHKSVIJx0YYYyAtqraCnZdt9t1kAsrKKFwITgCKMTPAhjinbOTcORIGvKCUpQlnff7DkxrTAee5nMGKhcaSvgj-mNJpoLa9fEFR1RP5lLmQvYVkuIw1ic "Python - Attempt This Online") [Try it online!](https://tio.run/##bU9da4MwFH2/vyKzAZN2ysrKBkqxMNjb9tS3uUKMccqMKTHSautvd7eFQQcj9577eU6SvTko25aqridq1x9WfanjZxQ16sA2/rRj4SLhjIUIyTqcJ4gsfWTp05kld@kzxwHlnKUrBM4XOE6XFLvpip53IZ38zb33YvS@qlXu8ZgO64e4MFYJWTJak6ohtGr2neOnqmB04KeDrZwKStO6EZeXcVUQXAxEkweNcZe0rr6VP5v7/HaZ4BTfXFeNIh5lV5YN34STpWqRxTk5@VvbqYj4I1F1q7B@FRgjf@TEG@P/tWg9TjOytQKr3BqtWgABWQZSSpBGGtBCawFdWXYlHPv@eOwhE41Ah9w4ZxAgF78HYEbeTRO4P4rIQS0oRFFgPgw96E7rHix@22gojWvR4YZ0I4miAq@72BVAZFJmQl5aEu0H "PowerShell โ€“ Try It Online") - .NET This combines both the 56 Java and 59 byte Python ports, to support five different regex engines. ## \$\large\textit{Anonymous functions}\$ # [Perl](https://www.perl.org/), ~~49~~ ~~45~~ 44 bytes ``` sub{pop=~/^((.+)((.)(?3)\4|(?=\2$).?))?.?$/} ``` [Try it online!](https://tio.run/##VY5Nb8IwDIbv/hUWRDTR@NzHhaz0tuNOHNFQGlpaqUm6tNUoHfvrzAVtAsV2rLyvH6dMfPFybqoEq9rnupbY91/K29zuK4mmRZaG56qJu9KV4c/sg/Ppg6AiePQkNs/fPAo3j0xMIyGiacRmp7NMneemZXk4l68rSfdCdJinnOWiK31uaxxs7ECeLvQCQyQ8redsO54sxguRfPY6Rjfvc1IELpFtJSCxkBeJ3dcZjY9G/76CfAthk2AYiI5tw8FAXvdxlk5WpIsoWPsmWSIGy@BNFRW1gaCfXG2skKfzENdeFbndeWeSCkBBHIPWGrTTDowyRkGTZU0Gh7Y9HFqIlVWUsHN17ajATv0dgCG@Ozup74g0QyxIVZpSfzy2YBpjWvDK7pyBzNUVJdwM3SAJqmhdH5dyJ/VirHWsdO/QFL8 "Perl 5 โ€“ Try It Online") # [Ruby](https://www.ruby-lang.org/), ~~53~~ ~~49~~ 48 bytes ``` ->s{s=~/^((.+)((.)\g<3>\k<4+0>|(?=\2$).?))?.?$/} ``` [Try it online!](https://tio.run/##VY1Nc4IwEIbv@ytWdFTGAdH2JEZuPfbkTbATAgjTfDgQpoZ@/HUabJ3Rye5ONu/7Pqnb1PQF6b1d89mQn@VxPvcXrh1ufNo@7eL37fMi2H3NIxKvJ64fuW7kR5Pld9@RIMSPsuI5cnLKdQOIVYHdaHg/t7oJMZdZiB1ZhYPAD94qIcSJpRPaBD8Evu@tk3/X5I3Iiv8hRtzPxVmbCKdTGwuSEZmNZ1ZDPNeV1FgceIIROvu6zTeIDm7QeaG8sYtz5cHNya9rP8Z9TXkls1qJvAGgkKbAGAOmmAJBhaDQlmVbwsWYy8VASiW1DZnSWtkBGb0dgDG@KunpB6LNWBYUtCjsvesMiFYIAzWVmRJQKt3YhrvQHdJCqf1uqOt4kAYxZSylbHAwW78 "Ruby โ€“ Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes ``` $args-match'^(.?(.)*.?)(?<-2>\2)*(?(2)^)\1$|^.$' ``` [Try it online!](https://tio.run/##dY1Nb4MwDIbv/hUWjUZSCdT22K7jtuNOva2rFEJYkEjShaAWOn47C0jVusPkj9iO38dne5GuUbKuR1LubyPh7rNJNPdCxSeaZjRlyzRjNHtONi/HDVvSjG7YiR3X5PuUkngcdqTfr3aldZILRUmNlUFSmXPr2Q0Qq5KSnt0urvIyUbbxQ9hfzx8YthP5hVGEiXVI6vfVx9wvIoaTdkBZN3IuEX8JmBhr5KWujMSI0An0RMqgD6r44Fq5RYzv2viVh3cbBiyakPAfidQwjAs8OB7awlktGwAOeQ5CCBBWWNBcaw6tUq2Ca9ddrx3k3PAQUFjvbUhQ8LsBLPDNmsT/IQZNYEHJyzLUfd@BbrXuwHFTWA3K@iYEPIgekAHKw7nJ5wQ8FyLnYhqJ4D8 "PowerShell โ€“ Try It Online") # [Julia](https://julialang.org) v1.2+, ~~54~~ ~~50~~ 49 bytes ``` s->endswith(s,r"^((.+)((.)(?3)\4|(?=\2$).?))?.?") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VU_LTsMwELzvVywpam1BKwocUKM0N46ceqMgOU7cBPmBHEc0EX-ChCqk_g73_g2blkqtvB7bmp2Z9df2rdGV2PyoZNsENX7YTevxvLB5_VGFktXXPnplbHLFCThL7_jy_pOlyfL2kk9SztNJGvF_4XeXKKHrIkblPGqsLPpC5LqyRc04IK60y4TGLq4UwbuvbNCW8ZjSYuyS4JuCuojUhV1RuObzGxwOUT9PXy6S0WBELOJexxSxmGK0INEMMcIZRo99Op19FnnCsVdzoOdhys3ud4ALL2iq3DtT1AACsgyklCCddGCEMQKasmxKWLftet1CJqygDbkLwRFALo4LYIBPzo7DmSNpyAuUUIruXdeCaYxpwQubOwOlCzVtOBGdWJKpoLi-9nBG9WQmZSZk3yGpDt_6Aw "Julia - Attempt This Online") # [R](https://www.r-project.org/), ~~58~~ ~~53~~ 52 bytes ``` \(L)grepl('^((.+)((.)(?3)\\4|(?=\\2$).?))?.?$',L,,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY_BSsQwEIbv8xTRlU0G6-KqB7GU3jwVT4KXIqRpsi20yZK0sK36JF5WwVfwMbz7Nk5dhV0yMyQz__8leX3z23eTfPSdObv-vspFhiuv143gj0IsTpEKivQS8_zqWaRJnl-c4CJFTBfpCY-yKFrin_czJOcxGxNTN1och66s7THGYJwXGastC_167XUID9Lb2q6C8FqWWW11ECMiPgFjtREBlewEzy3HOCTLeNe1qpKEQTafE6cIHR2iJd19lPAZRzZ5aqOboIUhWcTvfa9vGOMRv5XUvWEccWJNwgzjF1CNI_GI8e712--vGbv3sqlt6V2rA4CEogClFCinHLSybSX0VdVXsBmGzWaAQlpJCaXrOkcFSvm_AGbsztmz7oBIHmKBkcbQfhwHaPu2HcBLW7oWKtcFStgz7SEJKum6KX7LwWgaFkoVUk0KRbH71g8 "R - Attempt This Online") # [PHP](https://php.net/), ~~64~~ ~~60~~ 59 bytes ``` fn($s)=>preg_match('/^((.+)((.)(?3)\4|(?=\2$).?))?.?$/',$s) ``` [Try it online!](https://tio.run/##VVHBbtswDL3zK1TFaCQsSZMs25B4mi/Lil7SIc2t6QxZsWtjkmVIMhB37bendIZhLUQ@EOTjIwk1ZXP6mjRlQ6JCnIqaRZ6Lb43LH1MjgyrZ8OoXY5MPHIGz5CPfL55ZIvbziE8SzpNJEl0NR9h0iqu6Sn0eGG2UyyeZVL@DQ0h1ZapAR4Qu5svF8vOX@fIT5TEU1rGoEtM40qJ4zINnd7vvNxse8z@kKlik731wOseNNB/PHoSg@5pyJPs2wwqmR9PReMbjM7viuSptT4kJqs5iIJgn7L/G5SVKTh8uxHAwxBE9nZzv1NKHNHcO9@EX4ud2fZ1ubtP1dnu7Tei6z68IXbGo34kndOfafEUwQ39I7THEY17@ytFI0/jlNCA7J3VVH5w1uQeQkGWglAJllQUjjZHQlmVbwrHrjscOMllLdDjYECwCHOS/BzAgG1uPwztF7EEtKGRRYPz01IFpjenAyfpgDZQ2eHR40/RGEkUljuvtDO9KfTFTCn@vZyi0Vw "PHP โ€“ Try It Online") # [Python](https://docs.python.org/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 71 bytes ``` lambda s:regex.match(r'((.+)((.)(?3)\4|(?=\2$).?))?.?$',s);import regex ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZC9TsMwEMf3e4ojrZRY0KgFBpTKygYbU7emg-MkJJI_KtuRkog3YelSnoDnYO_b4LRFtBLy3fnj_vc72x-f297VWu2-GrnVxqHt7RIHOl9iRbN966rZ0-FFMJkXDG1iyreyiyVzvI5MGEXxLfGBROkDyR7fo5Rm91MSp4SkcToN7yxZnrHHwjNuX2mDAhs1NoutKxqVAGJT4ZDg1jTKReS0F6WKBEGmChTr2WJDaZipMEFBxXqe-IN_ZPPNDQ0n4S-pVAUNVqYtE8RgFFejtBS2xOCZ-SnBYOz2pxZk_IDF6bK7w_cEV4aJRhVGy9ICMMhz4JwD11yDZFIyaOu6raHr-67rIWeKeYdCO6d9gIL9DoAJvmo1c1dEX-NZULGq8uth6EG2UvZg_Iu0hFo76x0uii6QHsp8u9GO4So1JnPOc8ZHBfd2etYP "Python โ€“ Attempt This Online") # [Python](https://docs.python.org/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 72 bytes ``` lambda s:__import__('regex').match(r'((.+)((.)(?3)\4|(?=\2$).?))?.?$',s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBLTsMwEN3PKYa0km2gUQssUFCUHWLFqru2ihwnIZH8qRxHSirOwAXYdAPHYd_b4BAqWgl55o09n-eZef_c9q4yen94q9XWWIdN3zzgLp5DaSxKrPXgCRuX1zoCxLrEXYRbW2tH2fiWhaaSIdc5ytVssYljstYkQhnL1Tzyjn_S5puLmEzIkanQeRwsbVtEiMGQTD9aV87uD0-Sqyzn2ERpOjaYppTY4qXoCAsVd6KillAaXjEPjCa3bH33SpN4fTNlYcJYEiZTct2wX75LRDZ0UcimwOCRexNhMAzy14hkwwIWY8X-8DXBpeWy1rk1qmgAOGQZCCFAGGFAcaU4tFXVVtD1fdf1kHHNvUJunDMeIOfHAzDBZ6Nn7ozR13guKHlZ-vtu14NqlerB-mUZBZVxjVc4KTqh9KTcfzfID5yFhmAmRMbFkCG8jGN9Aw "Python โ€“ Attempt This Online") (If it must be a pure lambda.) # Java, ~~85~~ 75 bytes ``` s->s.matches("((.+?)((.?)(?=.*?(\\4(\\5|(?!\\7).?)$))())+(?=\\2$).?\\5)|.") ``` [Try it online!](https://tio.run/##ZY9Nb9swDIbv@hWMU7RSugjZsGFAPSfYDj1tvaS3eQdatmNl@jAsuY3b5rdnjNMC7QqJ1MdLPi@4xTucb8u/B21b30XY0lv2URtZ905F7Z2cpfBOnKVMGQwBfqF28MgA2r4wWkGIGOm487oESxpfx067ze8/gN0miLEU4PqZ/e2kfvjhvanQLaGG7BDmyyAtRtVUgSecy8uVoExplcnZiuf5Z4ovT3w1yfOvgoQzIbgQl6Tn@acz@iFZPMlEHFKyWyt0rupAu7aPkIGr7l/@@HoIsbJSO0FDugg6W6Rw32hTAR/rZYPhptpF4sMj6JrrSbYQz22e9JYGiMbxIyD7mI7jnaYCQ2YniCPCT@2qsaoGbqSp3CY2XCwXcH4ORqoGu@@RL8Qku5heiBFDoP98eC2xbc3AjYAVJLddX10BJHAFyTWaQI@EHN51GZGy/X5/mMJth0a7svO2CowhKwqmlGLKK88sWousb5q@Ybth2O0GVqBDClb6GD0lVuLLYmwKN97N4xsi9RCL1VjXdH94GJjtrR1Yh670ljU@Bgr2qukVkqBIdsc9pjfSUSyUKlAdKxTtfw "Java (JDK) โ€“ Try It Online") ## \$\large\textit{Full programs}\$ # [Perl](https://www.perl.org/) `-p`, ~~42~~ ~~38~~ 37 bytes ``` $_=/^((.+)((.)(?3)\4|(?=\2$).?))?.?$/ ``` [Try it online!](https://tio.run/##VY3BboMwDIbvfoqIRpRoLW239dKIcdtxpx6rIRPCQCIJgiAVur76mFtp0qrYvx399udWd81@HnrN9vF2t5XMjLxM@iG/8CxpXStnqpvPKIqfBImI0hdxev2O0uT0zEWcCpHGKd/MkmdXyXqPXjM@ST6FYdvV1gcnG9Av2UmmKmdaSXxMeCbrMmq0/fIVRxaGjC72vos4rrarnbB6uViKy50Q8XL9RoZIg2M36ANjwSF4x6anNhDX@wzjKNlgC10yns0LduywqW3ROaN7AIQ8B6UUKKccGDQGYaiqoYLzOJ7PI@RokRIK570jgQL/HsCCfTi79g9E2iEWlFiW1E/TCGYwZoQObeEMVM73lPBv6R@SoEjnbnGXB@tm5krlqG4TiuLHtb52tp/X7S8 "Perl 5 โ€“ Try It Online") # [Ruby](https://www.ruby-lang.org/) `-n`, ~~47~~ ~~43~~ 42 bytes ``` p~/^((.+)((.)\g<3>\k<4+0>|(?=\2$).?))?.?$/ ``` [Try it online!](https://tio.run/##KypNqvz/v6BOP05DQ09bE0hoxqTbGNvFZNuYaBvY1WjY28YYqWjq2Wtq2uvZq@j//5@SCIP/8gtKMvPziv/r5gEA "Ruby โ€“ Try It Online") Prints `nil` for false and `0` for true, which are respectively falsey and truthy in Ruby. If printing `0` or `1` is desired, replace `p~` with `p !!` (+2 bytes). # [PHP](https://php.net/) `-F`, ~~63~~ ~~59~~ 58 bytes ``` <?=preg_match('/^((.+)((.)(?3)\4|(?=\2$).?))?.?$/',$argn); ``` [Try it online!](https://tio.run/##VUzbisIwEH2f7yiYsFph3TeVvO1XyMpkao3gZEpMoRG/3ThdWHCZcw4D5zKEodad2w/pdD4yZgpmsf4xpv2wKta4jT18PYzbHz4b2zprXeua9WLZYDpHu60VwXsgIiAhAUZmhDGEMcBUyjQV8BhRCZ3kLCrQ4d9pZK5Bj32v//1egEfmAgljJwxB8k0JOeH1ErskfHprax91ecav/LNm0xN5pDlBiqcM@SLxVlffLw "PHP โ€“ Try It Online") - bare-bones test harness [Try it online!](https://tio.run/##VVFNj9owED13fsXbEBGiNmRpeyKE3FB7aVfq3oAixzE4UmJHxqh8hN9OHdhdgT0e229m3szYOdvKy8/ZnxRGsAKRKRAEMJNJsHobwWWSpY0Rm1XNLJeDIP47GAw/h06Fg@xbuPjeDrJ08dUPh1kYZsPMj4MvPjMbFSaXdxISXGpECt4kO2VT33jBuYO8hfKSAFNwXYjE6cZojpcfLzgh1o2NG9nEeam6HRFHLCxHVGArtbEr3Qi1smyT/laIZm8cZ/ony0rgvilUbTu/pvcrD8uk0PTJ3Y/wj1i2bVdJckxHCco15njqLDdP9PsO8E/V@Hk8OuMpRdALHAGsFArXpjrHad8/uaLno@U5eUwc7XAzPS/PYGhbiH1pk46UIU0xwrLf/3icV7MTY8C7lXSFZqzaOsxLsC4TfMAuKRVaiUsPr4ZVpSqMrsWWiFGeE@ecuOaaalbXjHZS7iTtD4f9/kA5U8wtF22tdooK9j6JevilVWQfGF2M46I1W6/d@Xg8UL2r6wMZpgpdk9TW/Yalu6A7SkfKXLpOrurB1BlzznPGOw/u5D8 "Bash โ€“ Try It Online") - fancier test harness [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 38 bytes -14 bytes thanks to [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). ``` g a=a?tail a f(a++g(reverse a)++g a)=1 ``` [Try it online!](https://tio.run/##zU5RDsIgFPv3FC98bVETPcDiETyA8aPCkEUfLIyZsctPYDHGGxigLSWPVo7ex32PhxyW5U5ocAronoSNrrDd3ivfvlo/tIQ63RI2x4XRWWpIuQ1R7zsbqGL0pOmSDCIBsSMhpSzkpMvMYC7@aMxosphinKaY1Q0W6YjdOq5cCC5BflL4LHGtv3Gw8ax/Q9evUlwmDa3XjHkuPo/MRXhY5Tgr48Jgcso6HzyenVXecfsbrEptpIZ5FyhGKvRHja41nehQL28 "Curry (PAKCS) โ€“ Try It Online") --- # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 52 bytes ``` f([_]?(a++reverse(g a)++a))=1 g(a?(a++[_]))=a?tail a ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NIzo@1l4jUVu7KLUstag4VSNdIVFTWztRU9PWkCtdIxEsB1QD5CfalyRm5igk/s9NzMxTsFVIU1BKSYRBpf8A "Curry (PAKCS) โ€“ Try It Online") Returns `1` for truth, and nothing otherwise. ## How? Returns `1` when the input is either: * a single character, or * in the form `a ++ reverse b ++ a`, where `b` is one of the following: + `a`, + removing the first character from `a`, + removing the last character from `a`, + removing the first and the last characters from `a`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` s=>[...s,l=r=''].some(t=>s.match(`^${l+=t}?${r=t+r}?${l}$`)) ``` [Try it online!](https://tio.run/##TVHBTsMwDL3nK3yY1ERsKXeUceIj0Bial6akqKmnJIWWad8@nA4Qrd6z/Zy6T/E7fmCysTvlzUCNu7bmmsx2p7VO695EU1V7nSg4mc026YDZenl4XZ37O5Mvj6tzNPkulqS/rA5KXbNL2WJyCQwcBMLtkQg1LFDiePzRjlwvULCBgbKD7DEzuegAGfmT4EQpdcfegfXUWR7bUoRnYa29DbE8YIESlizdNGKBFpWUCBhC8SHDYiAwBbYxej/6IjPX4Eem0SsxzfM0zSwz1TBPTNPMpnFAxs03xxq4Lt5xUKKhnImpNEuogUtmzrmJvy83C7MHjqXNsfywGBctti3nX1@zCGMIs4g4NBSEp5wYIkfsu6GJvIp/IxsUB51jF6TS6dR3WVYvQ6V4Tyc5gdnCbvrVoVK7@/3P4TXUL7LWZVlyUnv1IP72pvmCn5C3LHfdGtxelTFnAXyXQ6Le6Z7eZCs7nuH4u4t6uH4D "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Python](https://www.python.org), 72 bytes ``` lambda s:1>s.find(s[(l:=len(s))//-3:])<=s.find(s[-~-l//3-1::-1])<=l%3//2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVHBToQwEI3XfsVcTGgi2133Yoh49hfMuodSaNqk7RBaIuzBH_GyidF_0q9xCqsReG8674Xpo7x99nMyGM7vun7-GJMu774enfRNKyFWu4e40Ta0RTwUrqpdF4rIuRDlvjry-_rPLF9LJ8S-3FVVucuOu94LcXuZt9U4gAUbAHuasOUVA1vbTeydTQU_bI8M-sGGVNgbXVjO1_fO31e9hPUqJAhYwFnTXLSG-gUcSgiYOkhGJqJu6EAS0gtCjzHaxnWgDFrVRchhnphSah2iaMACzhQqXDUkARcVOfPS-5yj8EsAT-QpxmjMaLJMLMCMRKPhbJrnaZpJJhIwT0TTTKFlkIQ1N1UB1OfsMnDWYkpIlM1cBFBLTGsy5e9NZmbKQDXbVDmTNDc_C9H2-TOYllrT-nSamR-9n9kgQ4ueGUyRwNIgHf26AX33b4NWrif_Aw) ### Previous [Python](https://www.python.org), 74 bytes ``` lambda s:s.find(u:=s[(l:=len(s))//-3:])<1>=s[l//3:l-l//3].find(u[::-1])>=0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVFRToQwEI2_PcV80kS2bPwxjewBvIFZ-SiFpk1oh9ASYa_izyZG76SncQprIvDe67yB6QPev8Y1WQzXD1O_fs7JlI_fz4PybacgyngwLnTFLOt4LgZZD30oIudClA-y4U_HE_mDEA9yKLM0t9vPUpbHhp_q6jaxMjiBAxcARxpRccnA1e4Qx8Glgp-rhsE4uZAKd28Kx_n-3PXnblSwH4UCARs4a9ub11K9gUMJAVMPyapE1E89KEJ6QxgxRtcOPWiLTvcRcpgXprXeh2gasIEzjRp3D8nAzUXOvPI-5yj8FsATeYoxWzvbbBMLsDPRbDlb1nVZVrKJBKwL0bJSaBUUYc9NKoDqnF0FzjpMCYlyM4sAKolpTU31d1IzM2UgzW1SzhTNzddGtH1-DWaUMbS-XFbmZ-9XNqnQoWcWUySwNKmBftaEvv-3Qaf2L_8L) ### Previous [Python](https://www.python.org), 88 bytes ``` lambda s:{s[~(n:=len(s)//-3)::-1]}&{s[:n-1:-1]}&{s[n-~n:~n-n],s[-n:n],s[~n:n],s[-n:-~n]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVBLTsMwFBRbn-KtUCw1pBUbFKn3AJUsnJ9sKfaLYkckRe1F2FRCcCc4DeOkIOLMjN885Xmct89-Dprd5b3dP3-MoU0fvh47Zctakc9f_eGcuHzfNS7xMsvSe5nn6a443aKTu3T3V7j07PKzS12x8YfU5Yuer4oa7eJ0nb9teSBDxhH3GLyVuSCzN3e-70xI5GFbCOoH40JiNm1ipFy_u3zf9IrWJ1GU0QIpyvLqlagXSErJcWgoaBVAzdCQAsILU8_em7JrqNJsqsZTDPMkqqpah1QYsECKiitePYbBi8tSWGVtzJHYJYAFWcQYtR51tMEZ6RE0aimmeZ6mGTYoo3kCTTNCK6eANTc0I9Qxu3JS1BwCg2IzSkYowdijqX4XmpGRARrbUCkU5sZ3IRwfryFa1bbYH4-zsKO1sxiUq9kKzcEDIgyqM64e2Db_DqjV-ud_AA) Returns the middle copy of the "template" as a singleton set (which is truthy in Python) or the empty set (falsy in Python). ### Previous [Python](https://www.python.org), 90 bytes (-1 @Steffan) ``` lambda s:s[~(n:=len(s)//-3)::-1]in(s[n:]==s[:-n])*[s[n-~n:~n-n],s[-n:n],s[~n:n],s[-n:-~n]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDNToYwEIzXPsUeqRH5jBfThAdR5FD-0ia0S2iJ4OF7ES8mRt9Jn8YpfCYCM9uZDbsDb1_TFg3794-hfP5c4pA_fD-N2jWdpqBCdc68KsfeZ0EWRX4vlcrvagtZeVWXZahU7mt5XUHnZ6_OHvImVLlXez1fKjTadX3ZcBp4JkvWE0-YfZJKkC3tbZhGGzNZnWpB02x9zOzNkFkpj_fef64mTceVaSpohxRNc_Ea6B2ScvIce4pGR1A_96SB-MI0cQi2GXtqDdu2D5TCPIq2bY8hLQbskKLllg-PYfDushROO5dyZG4P4EAOMRZjFpNscEFmAS1GinXb1nWDDSpoW0HrhtDaa-DIjVoQdMquvRQdx8ig1EylIEgwzmjqvxvNxMiAmtqoUmjMTc9OWJ8-Qwx6GHB-fd2EW5zbxKx9x04YjgEQcdaj9d3Mrv-3oNPHn_8F) Sort of similar to [@alephalpha's logic](https://codegolf.stackexchange.com/a/250404/107561) now. ### Previous wrong [Python](https://www.python.org), 85 bytes ``` lambda s:s[~(n:=len(s)//-3)::-1]in(s[n:]==s[:-n])*(s[2*n:n],s[-n:-2*n],s[n-~n:-n+~n]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVBLjtUwEBRbn6KX8TAhD9ggSzkGCxSycH6ypbg7ih2RzOJdhM1ICO4Ep6GcPCRiVXVXddIu5fuv5UhO-PXHVH_9uaWp_PT782xDN1iKJjb3gk09j1xEXVXlR21M-b71kA2btq5jY0pu9RP0hyc23D7HpmRTQuSWyzsEv73jncfy2yQrefJMsmDtTRtFvvbv4jL7VOjm1ipaVs-p8M9T4fXju9c_bzpL11NYquiEVl338DroE5pKYkkjJWcTaFxHskD6JrRIjL6bR-qd-H6MlMN8UX3fX0t6LDihVS-9XJ7AkNMVrYINIecowhkggAJibM5tLtvgitwG2pxW-3Hs-wEbVNGxg_YDoS1b4MqNWhF0zm5Zq0FSElAe5lIRJBg9hvbfwTAzMqDmMWq-MAdXk50m9C8vhwpbCIdaLQ8SlJMUAZVWO3seVgnjfysHe_3rvw) Fails on aabaabaaaabaa (false positive). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 61 bytes ``` lambda s:s[1:~(m:=-len(s)//3)]in s[m-1:~m:-1]in s[:-m]==s[m:] ``` [Try it online!](https://tio.run/##TUyxasQwDJ1PX@ExgYbjuKUYPF7XW7pdM8iOjQORbWyHxjf011OlpVCkJ/Se9F5q1cdwfU15d@pjX5D0hKLI8rjIr46kGhYbutKfz9d@nIMoDxr4QnK4/FI50KgUy3Lca24STp9@Xqx4z6tlcipCiTmktXY9s5TnUDvHgS@i9GA3Y1MVt/vbLeeYpUhYyo6gNRhjwEQTgZAIYfV@9bC1tm0NNAZkwBRrjTxgwr/il8MGDp3j/flsQCtRg4xhigQ@1sKAmnGZw5Qj2X9u9iMnH/0zALUxGs0hGe5v "Python 3.8 (pre-release) โ€“ Try It Online") * If the full string S has length \$L\$, then the length \$l\$ of each of the three sections is \$\lceil\frac{L}{3}\rceil \$; \$m = \lfloor\frac{-L}{3}\rfloor = -\lceil\frac{L}{3}\rceil = -l\$. * The sections X and Z are extracted as `s[:-m]` and `s[m:]`; they must be equal. * The remainder of the string, reversed, which is `s[m-1:~m:-1]`, must be X with the first and last characters each possibly removed. This is equivalent to it being a substring of X and a superstring of (X with the first and last characters removed). (There is a subtlety to why this equivalence is true. The generalisation to removing up to \$k\$ characters from each end is false: for X=`dedent` and \$k=2\$, `ded` is a substring of X and a superstring of the central part `de`, but cannot be obtained from X by removing up to 2 characters from each end. However, the original equivalence (which is the \$k=1\$ case) is true. If the length is reduced by 2, that is the same as the central part's length, so it can only be a superstring of the central part if it is equal. If the length is reduced by 1 or 0, then for it to be a substring of X, it can only be X with one end possibly removed.) * Chaining of comparisons is used to check all those conditions together concisely. * The \$L=1\$ case is a bit different, but it works out because negative-length slices produce empty strings in Python. [Answer] # [J](http://jsoftware.com/), 31 bytes ``` <e.[:;&.>@,(<{@;g@|.,g=.<@;}.)\ ``` [Try it online!](https://tio.run/##bY/LCsIwEEX3fkVwYRRqcJ22UhBcuXKrm2naNErTQJtCU/Xba31mBJkHOZfJcOc8TBmVJOaEkoCsCB9rychmv9sOUc4OPJyxdRLMo0sSFsmVBUXMoiS8scVxWExyoQyhtm6tcvRFkgScwhdomvq3EAKBEcaTBq3Rr1apVnnsnOs6h5ZCBWN5ITPWmrEhBT7x1qiEsnF4548XDxKkxGN9jyZ1qzXCGqrMaM/K2EZhG7aG8lRltdH5P28ZuhnGkx75bHS4Aw "J โ€“ Try It Online") Inspired by [alephalpha's Curry answer](https://codegolf.stackexchange.com/a/250404/15469), and Bubbler's edit. It's a bit ugly mechanically, but I like the simplicity of the idea. For each prefix, we create the Cartesian product of: 1. [prefix] 2. [prefix reversed, tail of prefix reversed] 3. [prefix, tail of prefix] And then check if the input is equal to any of the elements of any of the Cartesian products. [Answer] # [lin](https://github.com/molarmanful/lin), 69 bytes ``` .+.#a $`.a len `t1+ `t \; `| .+ `rev \`_`.' ,.a"^%s?%s?%1$s$".@ sf ?t ``` [Try it here!](https://replit.com/@molarmanful/try-lin) Switched to an approach inspired by @tsh because previous approach - although interesting - sucked at handling the edge cases. For testing purposes: ``` "mamma" ; outln .+.#a $`.a len `t1+ `t \; `| .+ `rev \`_`.' ,.a"^%s?%s?%1$s$".@ sf ?t ``` ## Explanation Prettified code: ``` .+.#a $` .a len `t 1+ `t \; `| .+ `rev \`_`.' , .a "^%s?%s?%1$s$".@ sf ?t ``` * `.+.#a` store input as *a* * `$` .a len `t 1+ `t` generate prefixes * `\; `|` check if any are true... + `.+ `rev` duplicate prefix, reverse + `\`_`.'` convert to string + `,` pair + `"^%s?%s?%1$s$".@ sf` turn into regex (templated as *x*, *y*, *x*) + `.a ... ?t` check if regex matches [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes ``` ^.$|^(.?(.)*.?)(?<-2>\2)*(?(2)^)\1$ ``` [Try it online!](https://tio.run/##TYzRCsIwDEXf8x0T2oEF9yz20Z8YwzTd6MC0MDtYh/9eM0GQ3HsJIecuY54j1pO6P@pgmvegjFVGt8ZqZa/n7tZ3ulVWdXrQ/aWpFcE5ICKgRAkYmRHWENYAWynbVsBhRDH4lHOSAI@/kZcDgwmnSfZ9L8Arc4EFo08MIeWXGPKCzzn6JfH4RwuP0nzoG4COyCEdJxJ9AA "Retina 0.8.2 โ€“ Try It Online") Link includes test cases. Explanation: Port of @alephalpha's Curry explanation. ``` ^.$| ``` Match a single character, or... ``` ^(.?(.)*.?) ``` ... a leading substring, capturing a substring of that which optionally skips the first and/or last characters, ... ``` (?<-2>\2)*(?(2)^) ``` ... the inner substring in reverse, ... ``` \1$ ``` ... and the leading substring again. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~20~~ 19 bytes ``` ~cแนช{|~k}สฐ{|~b}แต—โ†บโ†”สฐ= ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy754c5V1TV12bWnNgCppNqHW6c/atv1qG3KqQ22//8rJSXmJQKx0n8A "Brachylog โ€“ Try It Online") ### Explanation ``` ~cแนช Deconcatenate the input into 3 strings {|~k}สฐ Do nothing, or add an unknown trailing char to the first string {|~b}แต— Do nothing, or add an unknown leading char to the last string โ†บโ†”สฐ Reverse the middle string = The 3 strings must be equal ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ฮทฮตยบyรปโ€šyyยฆโ€šฮดยซ}Qร  ``` [Try it online](https://tio.run/##yy9OTMpM/f//3PZzWw/tqjy8@1HDrMrKQ8uA1Lkth1bXBh5e8P9/bmJubiIA) or [verify all test cases](https://tio.run/##VU0xDsIwDPwKytw/dOEDzIjBcVulEqmlNkVNJSQmHsDIxMTCCkKCrd37iH4k2EEMKM7d@WydqQFd5mHnU7WYj6eFSv0yTM/pMbz8@J4PZ@@HK9N0H2771XgJSVgrUInSmgERBQmJyYK1MmmNaQ1z533XeVmFCvizysg5YhAJvxdXvzGMBRRFdPpeTNtaK1xDlZFlYcg1Jia4GrZlldVk87@8mAh8USqC9BpRA4qJXGrzAQ). **Explanation:** ``` ฮท # Get the prefixes of the (implicit) input-string ฮต # Map over each prefix: โ€š # Push a pair of: ยบ # The mirrored version of the prefix yรป # And the palindromized version of the prefix # e.g. "abc" โ†’ ["abccba","abcba"] โ€š # Push another pair of: y # The prefix yยฆ # And the prefix minus its first character # e.g. "abc" โ†’ ["abc","bc"] ฮด # Apply double-vectorized over the two pairs: ยซ # Append # โ†’ [["abccbaabc","abccbabc"],["abcbaabc","abcbabc"]] } # Close the map Q # Check if any inner-most string is equal to the (implicit) input ร  # Check if any is truthy by taking the flattened maximum # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` โŠ™ฮธโŠ™๏ผฅโŠ•ฮบโฎŒโœ‚ฮธฮผโŠ•ฮบยนฮฆยฒโˆงโผโ€ฆฮธโบฮผฮพฮปฮฆยฒโผฮปโœ‚ฮธโบฮบฯ ``` [Try it online!](https://tio.run/##XY1BCsIwEEWvkuUE4kK3rqQouBBKPUFIBho6TdpJWuzpYyIq6Cz@37z3x/SaTdCUc8vOJzj5DWYlat30BFdvGEf0CS0MUokOV@SIcCdnsIKjEv/MXsqSF0cJGQ51y8J5XjRFaDZD2PRhqmpLS4TiPypOP8obJyW@j170oATLzx1ztiGlUCLvVnoC "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a tralindrome, nothing if not. Explanation: Brute-force search for a substring whose reverse equals its possibly overlapping prefix and suffix. ``` ฮธ Input string โŠ™ Any index satisfies ฮบ Current index โŠ• Incremented ๏ผฅ Map over implicit range ฮธ Input string โœ‚ ยน Sliced from ฮผ Inner index to ฮบ Outer index โŠ• Incremented โฎŒ Reversed โŠ™ Any reversed substring satisfies ยฒ Literal integer `2` ฮฆ Filter over implicit range ฮธ Input string โ€ฆ Truncated to length ฮผ Inner index โบ Plus ฮพ Optional overlap โผ Equals ฮป Reversed substring โˆง Logical And ยฒ Literal integer `2` ฮฆ Filter over implicit range ฮป Reversed substring โผ Equals ฮธ Input string โœ‚ Sliced from ฮบ Outer index โบ Plus ฯ Optional overlap Implicitly print ``` The final optional overlap is added rather than subtracted because the outer index is actually that of the last character in the substring (which is why it is incremented when the substring is actually extracted). `Filter` is used instead of `Any` in the inner loops because it accepts an implicit range and `Any` does not. [Answer] # [R](https://www.r-project.org), ~~96~~ 86 bytes ``` \(x,l=sum(x|1),t=l%%3>0,`!`=\(y)any(y-x[1:h]))!tail(x,h<-l%/%3+t)|!x[q<-h:1+h]&!x[q-t] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZNRS8MwEMcfBB_2KbJJJWErc-xljFXwQVHwSacwtsHSrCWDptE2xWTsm_gyBT-UfhqvLd1Y2rZ3Se9-veZ_aT-_kv136P1kKnRHv68LrHuRl2YC692A9JQXOc7w-qq3aq-8BTaExgYbV88HY74kpK3oJoIn-MSNnL4z7Cqya-v5-8Tl40GXLy_zG1cty-p_Z-eMKtyZPr1M72eLuENaIYbMaCofYojTDiEXqDwwRX1UmAX5_pHCPgCFEeSiWKoAKU4VuCAJEAVTHxK9yTTd-FGAGJcbFqQolAmanVZljB3KYgYVC7NezSSTFYWZBEIWmLQ4QYWotGBRiBDghC0l4zzjFZdxQHgGLuMWp43R2pQg1gYQo8FpY7eGxhTssESYAwaxvEM0tui1VEqCqxYAU-AgBB7mNk2rs-BxPsuFwZjzMJJWq9jdu5vH59uG3S0V1DpaD4Y0DOtRbbbbhgoiE6IhnNB4LUU9zqVKean5NKESGm3idSJFUE8exZfyrc8Wmp5fhWtI-4z5lOUMgysHyt9hvy_Hfw) Pretty naive implementation, with some optimizations to make the code shorter (and unreadable). Takes input as a vector of character codes. Outputs `FALSE` for tralindromes and `TRUE` otherwise. ### Explanation outline: 1. Let `l` be the length of input vector `x`. 2. Compute `h` - the length of the tralindrome parts. It's \$\lfloor\frac{l}{3}\rfloor+t\$, where `t` is 0 for `l` divisible by 3 and 1 otherwise. 3. Prepare a helper function `!`, which compares its input with first `h` elements of `x` (denote them with `X` as in the question). 4. Then last `h` characters must be equal to `X`. 5. And one of the following must be equal to `X`: 1. characters from `h+1` to `2*h`, reversed 2. characters from `h+1-t` to `2*h-t`, reversed. [Answer] # Python3, 305 bytes: ``` lambda s:any(all({*s}-{*k}for k in j)^1and K(s,j)and j[0]==j[1][::-1]==j[2]for i in R(1,L(s)+1)for j in C(s,i)) R=range L=len K=lambda s,l:not(l or s)or l and s[:(T:=L(l[0]))]==l[0]and any(K(s[T-i:],l[1:])for i in[0,1]) C=lambda s,n,l=[]:L(l)==3and[l]or[j for x in R(L(s)-n+1)for j in C(s,n,l+[s[x:x+n]])] ``` [Try it online!](https://tio.run/##dZJNb9swDIbP068QcrGY2E2dXgYDPvXYYIeil0FxAcWWZ7n6MCwFtVv0t2eU02zDgMbhK4kEyUcChzl0zt59H8ZzWx7OWphjI6gvhJ2Z0Jq9r/1H9r5@@WjdSF@osrSH51zYhj4wn/YQdz2/rcqy53nFiyLLl/2uigkqJjyyPN0zD5scoq@PvntMVgDksRyF/SXJvtTSkofy2j/VhXWBaYoJHlA0jZ08L9hTUe6ZxpYA2CluYiTyIhF/ylRRpZrnRQVXAn6b5hWQ@7/VbapLXhVYB8ryDvO5rtzIexpTpgt0RM7s/9CYueGeT8W0sVUF1VmZwY2BjpL4vFytVoJefkzQLV0MyPH46TvieTGgGcULSho6EVDkKKlAC6@ODs57ddSS1p1TtfQL1E9S1/WlSI0FFgNSu9pdfA4dbvE6IEYYEzmYWQAMikGMU9eduuhG3dLuhHLqgEzzPE0zulG2dJ5QphmhhRVoF25ctxTPkV1YII0LwaHEYFy2FI@ouMeguH4YjIoMuMYwroCPRP4MR6t0kCP74axMqc9v/KBVYMnBJgAF@TaMygbWslHetMo2cSKT58PrJkmpgmUGiN/FZ5/m@BikFW2LF3p7m4k5GTMTHK/GGdK54NFIGIXGOqMz8h/MRhCBd43/RSLhpXOSJevdLXzFu/uKF2f7/Bs) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 11 bytes ``` p::โ†”แตƒแถœt$,,= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VU8xDsIwDNx5BYoY2x1V4iWIwXEbBYEb1KZS2xWJF7DB0AEkBhYGeAGfYCwvwU5hQHHuLmfrrBwuebZyBB6ucxWTisYqztSiO1fexNPbJkneu31_3_aPo59E0exUaiy_3e71VKBGSmsGRBR06JgIiKRTWVtZ5rpp6rqRUciBL6vUee8YRMLvhNEhhtGAMcFpWzGpIhIuIE8dsbDOlzYk-ALWyzwtHGV_eSEReKNUAHlrRA0oJnKp4TMf) A port of [my Curry answer (based on @Bubbler's comment)](https://codegolf.stackexchange.com/a/250404/9288). ``` p::โ†”แตƒแถœt$,,= p Find a prefix of the input :: Triplicate it โ†” Reverse the third copy แตƒแถœt Optionally drop the first character of the second and third copies $ Swap the second and third copies ,, Join three copies together = Check if the result is equal to the input ``` ]
[Question] [ You probably all know the fibonacci sequence: ``` fibonacci(n)=fibonacci(n-1)+fibonacci(n-2) fibonacci(0)=0 fibonacci(1)=1 ``` Your task is as simple as it could be: * Given integer `N` compute `fibonacci(n)` but here is the twist: * Also do negative `N` Wait. What? ``` fibonacci(1)=fibonacci(0)+fibonacci(-1) ``` so ``` fibonacci(-1)=1 ``` and ``` fibonacci(-2)=fibonacci(0)-fibonacci(1)=-1 ``` and so on... * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest programm in bytes win. * You may submit a function or a full programm * N is in [-100,100] Testcase(s) in CSV: ``` -9;-8;-7;-6;-5;-4;-3;-2;-1;0;1;2;3;4;5;6;7;8 34;-21;13;-8;5;-3;2;-1;1;0;1;1;2;3;5;8;13;21 ``` Hint: > > n<0 and n&1==0: > > > ``` > fibonacci(n)=fibonacci(abs(n))*-1 > ``` > > > > [Answer] # Mathematica, 9 bytes ``` Fibonacci ``` Yes, this built-in function supports negative numbers. [Answer] # Octave, 20 bytes ``` @(n)([1,1;1,0]^n)(2) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaepEW2oY2htqGMQGwfkGGn@T8wr1jDQ/A8A "Octave โ€“ TIO Nexus") ### Explanation This makes use of the fact that the fibonacci sequence `f(n)` can be written as (this should be a matrix vector notation): Recursively: ``` [f(n+1)] = [1 1] * [f(n) ] [f(n) ] [1 0] [f(n-1)] ``` Explicitly: ``` [f(n+1)] = [1 1] ^n * [1] [f(n) ] [1 0] [0] ``` This means that the top right entry of this matrix to the power of `n` is the value `f(n)` we're looking for. Obviously we can also invert this matrix as it has full rank, and the relationship still describes the same recurrence relation. That means it also works for negative inputs. [Answer] # Maxima, 3 bytes ``` fib ``` supports positive and negative numbers. Try it (paste) on [CESGA - Maxima on line](http://maxima.cesga.es/) [Answer] ## Python, 43 bytes ``` g=5**.5/2+.5 lambda n:(g**n-(1-g)**n)/5**.5 ``` A direct formula with the golden ratio `g`. With `f` the above function: ``` for n in range(-10,11):print f(n) -55.0 34.0 -21.0 13.0 -8.0 5.0 -3.0 2.0 -1.0 1.0 0.0 1.0 1.0 2.0 3.0 5.0 8.0 13.0 21.0 34.0 55.0 ``` Same length alt, only aliasing the square root of 5: ``` a=5**.5 lambda n:((a+1)**n-(1-a)**n)/a/2**n ``` I didn't see a way to make a recursive function that could compete with these. A mildly-golfed attempt for 57 bytes: ``` f=lambda n:n<0and(-1)**n*f(-n)or n>1and f(n-1)+f(n-2)or n ``` For comparison, an iterative method (60 bytes in Python 2): ``` n=input() a,b=0,1;exec"a,b=b,a+b;"*n+"a,b=b-a,a;"*-n print a ``` Or, for 58 bytes: ``` n=input() a,b=0,1;exec"a,b=b,a+cmp(n,0)*b;"*abs(n) print a ``` [Answer] ## JavaScript (ES6), 42 bytes ``` f=n=>n<2?n<0?f(n+2)-f(n+1):n:f(n-2)+f(n-1) ``` ### Test ``` f=n=>n<2?n<0?f(n+2)-f(n+1):n:f(n-2)+f(n-1) for(i = -9; i < 9; i++) { console.log(i, f(i)) } ``` [Answer] # JavaScript (ES7) 37 bytes Uses [Binet's Formula](http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html "Binet's Formula"). ``` n=>((1+(a=5**.5))**n-(1-a)**n)/a/2**n ``` This outputs the `n`th Fibonacci number +- `0.0000000000000005`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 9 bytes ~~I'm happy about the `[3,2]`, which surely could be golfed, if anyone knows a way please let me know=) (It would also work with `[1,3]`.)~~ Thanks @LuisMendo for -2 bytes=) ``` IHhBiY^2) ``` This is using the same approach as the [Octave annswer](https://codegolf.stackexchange.com/questions/105183/fibonacci-1fibonacci0-fibonacci1/105184#105184). But to generate the matrix ``` [1,1] [1,0] ``` we just conver the number `3` and `2` from decimal to binary (i.e. `11` and `10`). [Try it online!](https://tio.run/nexus/matl#@@/pkeGUGRlnpPn/v64JAA "MATL โ€“ TIO Nexus") [Answer] # Jolf, 2 bytes ``` mL ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=bUw) The fibonacci builtin, implemented using the `phi` formula. [Answer] # Haskell, 51 bytes ``` s=0:scanl(+)1s;f z|even z,z<0= -f(-z);f z=s!!abs z ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 112 Bytes ``` function f($n){$o=('-','+')[$n-lt0];&(({$a,$b=(2,1|%{f("$n$o$_"|iex)});"$a- $o$b"|iex},{$n*$n})[$n-in(-1..1)])} ``` **Demo Call:** ``` -9..9 | %{"{0,2}`t=> {1,3}" -f $_,(f($_))} ``` **Output of Demo:** ``` -9 => 34 -8 => -21 -7 => 13 -6 => -8 -5 => 5 -4 => -3 -3 => 2 -2 => -1 -1 => 1 0 => 0 1 => 1 2 => 1 3 => 2 4 => 3 5 => 5 6 => 8 7 => 13 8 => 21 9 => 34 ``` [Answer] ## [Lithp](https://github.com/andrakis/node-lithp), 88 bytes ``` #N::((if(< N 2)((if(< N 0)((-(f(+ N 2))(f(+ N 1))))((+ N))))((+(f(- N 2))(f(- N 1)))))) ``` My look at all those [parentheses](https://xkcd.com/297/). [Try it online!](https://andrakis.github.io/lithp-webide/?code=KAogICAgKGRlZiBmICNOOjooCiAgICAgICAgKGlmICg8IE4gMikgKAogICAgICAgICAgICAoaWYgKDwgTiAwKSAoCiAgICAgICAgICAgICAgICAoLSAoZiAoKyBOIDIpKSAoZiAoKyBOIDEpKSkKICAgICAgICAgICAgKSAoCiAgICAgICAgICAgICAgICAoKyBOKQogICAgICAgICAgICApKQogICAgICAgICkgKAogICAgICAgICAgICAoKyAoZiAoLSBOIDIpKSAoZiAoLSBOIDEpKSkKICAgICAgICApKQogICAgKSkKICAgIChpbXBvcnQgbGlzdHMpCiAgICAoZWFjaCAoc2VxICgtIDkpIDgpICNJIDo6ICgocHJpbnQgIkZvciAiIEkgIjogIiAoZiBJKSkpKQop) Not very small really. There's currently a parsing bug that requires one to use `(get N)` or `(+ N)` instead of simply `N`. I chose the smaller one. However I don't think there's anything that can be done further to golf this. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ร†แธž ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Md8/7rWhZZKlgfbld51LRGwf0/AA "Jelly โ€“ Try It Online") Boring builtin answer, Jellyโ€™s Fibonacci builtin handles negative inputs just fine ]
[Question] [ *Disclaimer:* This challenge inspired by me trying to find pairs in a large pile of socks. *Disclaimer:* This is looking for a very different process and output to [Help me sort my socks!](https://codegolf.stackexchange.com/questions/77031/help-me-sort-my-socks). Please don't claim it as a duplicate until you've read both ;) --- So, I have a huge pile of socks. Of course I keep them categorized by compatibility number. Compatible socks, which I can wear together, have the same number. (Of course, every programmer does this). My super-convenient plot device quickly scans the pile and outputs an array of compatibility numbers for the pile. It looks a bit like this: ``` [2, 3, 3, 6, 0, 4, 9, 1, 6, 7, 11, 3, 13, 3, 5, 12, 2, 1, 10, 2, 1, 11, 2, 13, 12, 10, 1, 7, 0, 0, 12, 12, 6, 2, 13, 6, 10, 0, 0, 12, 5, 0, 2, 3, 4, 0, 5, 8, 1, 6, 9, 7, 10, 14, 10, 8, 3, 8, 9, 8, 5, 11, 7, 9, 9, 9, 7, 14, 4, 2, 8, 14, 3, 11, 12, 14, 7, 13, 11, 13, 4, 7, 5, 12, 3, 1, 12, 4, 5, 13, 2, 13, 2, 14, 1, 13, 11, 1, 4, 8] ``` That's good data, but it's about as much use to me as scanning the pile myself by eye. What I want to know is how many compatible pairs I need to look for, and which are going to be 'odds', which I can discard for now. In the above example, I am looking for these pairs of socks: ``` {3=>4, 6=>2, 2=>4, 1=>4, 11=>3, 13=>4, 12=>4, 10=>2, 7=>3, 0=>3, 5=>3, 4=>3, 9=>3, 8=>3, 14=>2} ``` (4 pairs of number 3, 2 pairs of number 6 etc.) And these numbers will have 'odd ones out'. When I've found all the pairs for these, I can discard the last one. ``` [0, 6, 10, 7, 2, 14] ``` --- # The challenge * Convert a list of compatible numbers to a count of pairs for each number and an array of 'odds'. + The pairs will be composed of a data structure (hash, or other) showing how many pairs can be made of each compatibility number (can be skipped if no pairs can be made). + The odds will be composed of a list of numbers which occur and odd number of times in the array. * The order of the outputs is not significant. * The size of my sock pile can, of course, be arbitrarily large. # The Rules * It's golf, make it short. * No standard loopholes. * Use any language you like. * Please include a link to an online interpreter. # Test Cases Input: `[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]` Output: Pairs: `{2=>1, 3=>1, 4=>2, 5=>2}` Odds: `[1, 3, 5]` --- Input: `[2, 3, 3, 6, 0, 4, 9, 1, 6, 7, 11, 3, 13, 3, 5, 12, 2, 1, 10, 2, 1, 11, 2, 13, 12, 10, 1, 7, 0, 0, 12, 12, 6, 2, 13, 6, 10, 0, 0, 12, 5, 0, 2, 3, 4, 0, 5, 8, 1, 6, 9, 7, 10, 14, 10, 8, 3, 8, 9, 8, 5, 11, 7, 9, 9, 9, 7, 14, 4, 2, 8, 14, 3, 11, 12, 14, 7, 13, 11, 13, 4, 7, 5, 12, 3, 1, 12, 4, 5, 13, 2, 13, 2, 14, 1, 13, 11, 1, 4, 8]` Output: Pairs: `{3=>4, 6=>2, 2=>4, 1=>4, 11=>3, 13=>4, 12=>4, 10=>2, 7=>3, 0=>3, 5=>3, 4=>3, 9=>3, 8=>3, 14=>2}` Odds: `[0, 6, 10, 7, 2, 14]` --- Input: `[1, 2, 1, 2]` Output: Pairs: `{1=>1, 2=>1}` Odds: `[]` --- Input: `[1,2,3]` Output: Pairs `{}` Odds: `[1,2,3]` --- Input: `[]` Output: Pairs: `{}` Odds: `[]` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 46 bytes ``` {.kv.map(*=>*+>1),.keys.grep:{.{$^k}%2}}o*.Bag ``` [Try it online!](https://tio.run/##RY/BCoMwEETv/Yo9tKW1IZgYNbboob9RWvCgHqxUFAoifrvVnaqwkNmdl@ykzpp3MFYdHXOKx16WX1ml9cmJE@eSqLOQZda1smiy@trLfv8qh4Meho8j72kx3nZt2lFODy3I4woEuYKMoEiQ4jachGJPAfEnNfGaAeWuSkF5sGdD8W2Xi2eaX/xTAaDN9lkhimE9TeySI0KUmTU4LZOWLYtc2BgtFQI2/KpF4wHjPAbIMsLecP2ih49pHvsA9HYY2Mttpuxz/AE "Perl 6 โ€“ Try It Online") ### Explanation ``` { }o*.Bag # Convert to Bag and feed into block , # 2-element list .kv # Key-value list (key is sock type, value is count) .map( ) # Map to *=>*+>1 # Pair of sock type and count right-shifted by 1 .keys # Keys (sock types) .grep: # Filter {.{$^k}%2} # Count is odd ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~85~~ ~~78~~ ~~73~~ 72 bytes ``` lambda s:{*((c,(d:=s.count)(c)//2)for c in s),*(c for c in s if d(c)%2)} ``` [Try it online!](https://tio.run/##RY/NDoIwEIRfZS8mrWmE/iDFxCdRD1pCJFEggAdjfHasOyLJJp3d@badds/x2jbWd/1U7Y/T7Xy/lGcadq@1EEGJcrcfNqF9NKMUQSaJkVXbU6C6oUGqtQi09FRXVEZqZeR76vq6GUUlDkaR5doqShU5RYUizW0ehWZPA8miirxhQKd/paEs7K@heTvl4pnhG3/UFtBiZ6wQxbGOEz/nKBDlyzqcnknPlkcuvFjMlQN2fKtHY4FxHgdkHuHd/P9Fi48ZHmcAzHI42PM2U/4k5fQB "Python 3.8 (pre-release) โ€“ Try It Online") --- Output is a list where pairs are tuples, `(a, b)` rather than `a => b`, and odds are not part of a tuple. There's a sub-70 in here somewhere just staring at me, I can feel it... **Previous Version (73 bytes):** ``` lambda s:{*((c,s.count(c)//2)for c in s),*(c for c in s if s.count(c)%2)} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ยข2รทรธรช,ยขร‰รรช, ``` [Try it online!](https://tio.run/##RY@7DQMhEERboYAN@B5Qi@XAJzlw5MBVOHIPF7oBOz4KwzBjOGklZnce7HB/XNbbtdZ9s@VTvuUt@1ae5dVErScryqEWUVqUF5VFGbSxCQPPEAlNNd4CMHoqQ@Vod8PgtkZhZvHin1oIHXaAYhQP3SZp5MiM0lnPM4FMsBJzcWMeFQl7vJrYOGLI44mMEffG@UXHj1mMAwF7HD2GzMuA0vkH "05AB1E โ€“ Try It Online") ``` ยข # count occurences of each element in the input 2รท # integer divide by 2 รธ # zip with the input รช # sort and uniquify , # output (this is the list of pairs counts) ยข # count occurences of each element in the input ร‰ # mod 2 ร # filter the input, keep only where the above is 1 รช # sort and uniquify , # output (this is the list of singles) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {ฮณฮตร™ygยช}Dฮต`2รทโ€š}sรธ`ร‰รโ€š ``` Outputs as a pair of lists, where both are ordered ascending by key. Also includes the optional value=0 pairs in the output, like all answers. (Initially) inspired by [*@Malivil*'s C# answer](https://codegolf.stackexchange.com/a/196208/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##RY87DsIwEESv4gO4iH@J03MLhBSQEKKiSIVQJFoqajgCLYqgxn0OwUWMM4MTaSXP7jx7x4d2vdlvYzwNz6EPt@Pu8@gWQ9/o8Pqe710b3k24hGvSMS61FAZVSlFIYaWopVBoqyQUPEXEJZV4DUAVk1JUhvZoKNwuUJhpvPinSkKz7aAYxUKnic85akYZWcvTg/SwPHNxY52rImzxqmdjiCGPJZJH3FtNXzT8mMbYEdDzYWnn26D86gc) or [verify all test cases](https://tio.run/##NVAxTsNAEOx5ReR6hbx35/hMkyYNFQ2dZSmJFCEaQHKCZCFLtFTU8ARaFKDO9X5EPmJm7mKtzjc7s7O758d2vbnfjs/Z9cPTfnc1yxbd7eVSLrKb/Q5ES2Z8Gb6HQ/jo7o5f/XI4rEz4Pb1@9m34W4W38A48yvFnMda1EYuYSy5OKlGgUlRBKflC1IgBrXm6lJclC0ZRmyOYGTijNKdyZguhzaJ1Duxj@4oDoDp@PUQPynMS21UxSsoOVk9gKXGGo5Ay9izTelai6pjZtEOs1akWkm9kVnP39Fy6UxRTTAU4E7QEPO5s428x0cYGtmn@AQ). **Explanation:** ``` { # Sort the (implicit) input-list # i.e. [4,2,3,3,1,3,2,4,4,3,4,3] โ†’ [1,2,2,3,3,3,3,3,4,4,4,4] ฮณ # Split it into groups of the same keys # i.e. [1,2,2,3,3,3,3,3,4,4,4,4] โ†’ [[1],[2,2],[3,3,3,3,3],[4,4,4,4]] # (this is shorter than the regular (unsorted) group-by `.ยก}`) ฮต # Map each inner list `y` to: ร™ # Uniquify the list, so a single key wrapped in a list remains # i.e. [3,3,3,3,3] โ†’ [3] yg # Push the list `y` again, and pop and push its length (the count) # i.e. [3,3,3,3,3] โ†’ 5 ยช # Append it to the 'key-list' to create the key-count pair # i.e. [3] and 5 โ†’ [3,5] # i.e. [[1],[2,2],[3,3,3,3,3],[4,4,4,4]] โ†’ [[1,1],[2,2],[3,5],[4,4]] }D # After the map: duplicate the list of key-count pairs ฮต # Map it to: ` # Push key and count separated to the stack # i.e. [3,5] โ†’ 3 and 5 2รท # Integer-divide the count by 2 # i.e. 5 โ†’ 2 โ€š # And pair them back together # i.e. 3 and 2 โ†’ [3,2] # i.e. [[1,1],[2,2],[3,5],[4,4]] โ†’ [[1,0],[2,1],[3,2],[4,2]] }s # After this map: swap to get the initial duplicated key-count pairs again รธ # Zip/transpose; swapping rows/columns # i.e. [[1,1],[2,2],[3,5],[4,4]] โ†’ [[1,2,3,4],[1,2,5,4]] ` # Push both lists separated to the stack ร‰ # Check for each count whether it is odd # i.e. [1,2,5,4] โ†’ [1,0,1,0] ร # Only leave the keys at the truthy indices # i.e. [1,2,3,4] and [1,0,1,0] โ†’ [1,3] โ€š # And pair it together with the earlier created list of key-count//2 pairs # (after which the result is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda A:({v:A.count(v)/2for v in A},{v for v in A if A.count(v)%2}) ``` [Try it online!](https://tio.run/##TZDbDoIwDIav9Sl6YwLJoqxMGSRe7DmQCw8hkigYgyTG@OxIWwYmzdb2/3rYHu/22tTYl/tDfzveT5cjuCz4dJlbn5tX3QZduMGyeUIHVQ3uqz4dzCFUJczgCr9hT6IjMc@1AmSLvZk/2/5boZaLfCJ3CiJmUgWaw2RwNGtakKFIS/MhraPJk5kEkUyC5uqIjXPIHUdqJ9Asb9lDv27EGev3SGUVYo3clknLkpW9ZGLqLRHYcFcrQSwY72ME8SmZm0xPjOVh6D@NAJwvI7KvZsoWCsbfp1MiVDE5BRTZcvF4VnULZeDC0e9/ "Python 2 โ€“ Try It Online") Outputs a `dict` containing the number of pairs, and a `set` of left-over sock ids. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 [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 tacit prefix function. Prints (unique sock number, count of pairs) pairs, then prints list of odds. ``` โˆŠ{โŠ‚(2|โ‰ขโต)/โŠƒโŽ•โ†โบ,โŒŠ2รทโจโ‰ขโต}โŒธ ``` [Try it online!](https://tio.run/##TZC9bsIwEMd3niJjKzlqfDbEmVnKVAn6AkhVWJDatSosICEaJREMvAATQ6VOVREjvMm9SLDv4iTSyb67/@8@7OnHPHz7nM7fZ1WF2@wLs9UDLPD7iMXf4xNmaywPuNlhcRGYZ3D7x@LE6hLzc5WSVlpo9GLh66/Czd5Gk/HQnq/Po0mVBlIEQKa86Y71u9YLw7CXtuxABBFRiXBtbBhbR5ImGbFlktvbtIwaj6c6yMlOkFQdkVEOqGNNDRhq5T554BeOKGP8Hgmv4ljNtyHSkGR4L56YeIsZ1tTVcKAYo300Iz7Fc@PmiYofBv7bHADtpVn21USZ@kOl/xZoEiBU7WPx47w7 "APL (Dyalog Unicode) โ€“ Try It Online") `{`โ€ฆ`}โŒธ`โ€ƒon each (unique sock number, its indices in sock list): โ€ƒ`โต`โ€ƒindices in sock list; `[4,5,6]` โ€ƒ`โ‰ข`โ€ƒcount them; `3` โ€ƒ`2รทโจ`โ€ƒlet two divide them; `1.5` โ€ƒ`โŒŠ`โ€ƒround down; `1` โ€ƒ`โบ,`โ€ƒprepend sock number; `[3,1]` โ€ƒ`โŽ•โ†`โ€ƒsend to console; `"3 1\r"` โ€ƒ`โŠƒ`โ€ƒpick the first (the sock number); `3` โ€ƒ`(`โ€ฆ`)/`โ€ƒmake this many copies of that: โ€ƒโ€ƒ`โ‰ขโต`โ€ƒthe count of indices; `3` โ€ƒโ€ƒ`2|`โ€ƒthe 2-mod of that (i.e. "is it odd?"); `1` โ€ƒ`โŠ‚`โ€ƒenclose so all the results will be self-contained; `[1]` `โˆŠ`โ€ƒ**ฯต**nlist (flatten); `[1,3,5]` [Answer] # [R](https://www.r-project.org/), 47 bytes ``` S=table(scan());S[S%/%2>0]%/%2;names(S[!!S%%2]) ``` [Try it online!](https://tio.run/##NY6xDoMwDER/xQyRYGqcBAhC7U9kRAy0YmsZSv8/vUtaWYrte/Y575zT9bPdn3t7Praj7bo5LclcjLvZlWk@ttd@tmlpmmSMW7vsxCMGsRJkEkU1iiokpd6LOnGQ1dakTJ4qFMWsRbBz2CxoIPmpvXDNw9qijsV@4gHQwDcCRkiRl2g3lRiJA1YjC0/EG4GgdvQc6/e8FBrY@fqHMqv/WaCYvw "R โ€“ Try It Online") Returns a `table` with `names` equal to the compatibility number and the pair counts as the values, as well as the compatibility numbers (as strings) of unpaired socks. [Answer] # [J](http://jsoftware.com/), ~~39~~ ~~27~~ ~~26~~ 24 bytes ``` ~.((,.<.@-:);[#~2|])#/.~ ``` [Try it online!](https://tio.run/##RY/BDoIwEETv/YqNHICkVFoKFJTExMSTJ6/Gk0iMF3/A8Ou17FhJtul05207ffmNSicaekpJUkl9WIWi4@V88rPKMqn26lD0@e6azOZzy5Otmn0uxDgoI6niasKgJCupk6T52Aah2dNA6qACbxjQ5V9pqAr2YmieLrm4Z/jGH9UAWu2aFaJY1qHjYo4OURbWYndMOrYccuHFLlYL2PKtDocKGOexQGIL77b/L1b4mOF2DcCsm4Udp5lyQjzuzzdNNPov "J โ€“ Try It Online") *-2 bytes thanks to ngn* [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~162~~ ~~154~~ ~~136~~ ~~128~~ 108 bytes ``` a=>(a.GroupBy(x=>x).Select(x=>(x.Key,x.Count()/2)),a.GroupBy(x=>x).Where(x=>x.Count()%2>0).Select(x=>x.Key)) ``` [Try it online!](https://tio.run/##dVNRb9owEH7PrzihTrIlNyOBljCaPKzapm6VVqkPfWA8hMSsFixBiWFUUX47O59jiNouOoXzfd99/hwfWX2Z1eq4rdQ@1RJqnWqVwdddkd2oQs8XAtjdl2L3R1bpciNvGBYF4IsnAvoAlhKewAriYxonLPW/VeVu@/mFHeLkwP1HuZGZNgt28H/IF3Hwb8tdoRn/GHIuXtOfnmUlKXe0D2Ey7MuQCufHmeftS5XDQ4UO3liFlMzCEq3lbw3DmnuNB/jclkVdbqT/VCkt71Uh2cXgIVVV/Qmapqk1qv/2v5eqYAMBGLmzst5vIU7gYtBg5qdtnFCybAecty2@Z//V/5nnKD9/R33N28WvwvS2nvfK9HyRQLnVCgUhhkL@hXtV6w7pToPV@QKaQEBIMXIx7sVVP1pxbqTMCpnn1H8tYEidUwEBLSeYBIQFloJSgd0Sy8HwlFknhmRgAwTUPTRx2omwkJQ79rUl2zDQFWWhO8yQKpHzM7WWDHdsfyNiRgRFhnzezDqYupjYpjGpR3YxstbJ19hSXMnuPzkdeWQPGrpPi4T@FzT8TiXoqRA7ImL/BtzVmfd79dG5CHTx0EDrtTNvVVYyzZ6B7dOqmxIkuHlxw25AlpsxwwlaMYt2g2r/RwTi9B3/AQ "C# (Visual C# Interactive Compiler) โ€“ Try It Online") -8 bytes thanks to @Kevin Cruijssen for pointing out an unnecessary variable -18 more bytes thanks to @Kevin Cruijssen for letting me know the 0 rule was made optional and changing the return type from dynamic to array -8 bytes thanks to @my pronoun is monicareinstate for in-lining the grouping assignment which changes this to a true one-liner -20 bytes thanks to @Innat3 for changing the grouping to remove an un-needed comparison [Answer] # JavaScript (ES10), ~~91~~ 82 bytes Returns `[odds_array, pair_object]`. ``` a=>[[...new Set(a)].flatMap(v=>(a.map(x=>n+=v==x,n=0),o[v]=n>>1,n&1?v:[]),o={}),o] ``` [Try it online!](https://tio.run/##dVDBTsQgEL37FT0ZGpEUym6pCfgFnjySHsjabjQVNm6Dmxi/vdIZ6W7MmkxgeO/NzGPeXHTH3cfrYbr34aWfBz07baxljPn@s3juJ@LKjg2jm57cgURtiGPvKTtp4@901PpEva5KGmzstDeGU3/LH@OD7RKmv77T2c274I9h7NkY9mQgltNCQNQ55EVsLqMry5s/1WvdlhYVVLS04PBsUsKB4yhJLTiOSjCv1gwdLKKFXggO1RUEYAI6/qq2KDrTG8hENl8BorKPFq0sWom3AqUCSqEvnNjmaFAsoavCR40y8CNRkiGc26xfrPFjIq9wEYjzJZHO1aBSV5bL84rEv2R9hUnQ/AM "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` a => [ // a[] = input array [...new Set(a)] // build the set of distinct values in a[] // and turn it back into an array .flatMap(v => // for each value v in there: ( a.map(x => // count the number n of values in the original array n += v == x, // that are equal to v n = 0 // start with n = 0 ), // o[v] = // set o[v] to n >> 1, // floor(n / 2) n & 1 ? v : [] // yield v if n is odd, or [] otherwise ), // o = {} // o = object holding the number of pairs ), // end of flatMap() o // append o ] // ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 63 bytes ``` lambda s:sum([[(c,(d:=s.count(c))//2)]+d%2*[c]for c in{*s}],[]) ``` [Try it online!](https://tio.run/##RY/NCsIwEIRfJRch0aDNT9tU8EliDppSFLQtrR5EfPYad6zCQmZ3vmQn/eN26lrj@mFqdvvpcrge6wMbt@P9yr3nUfJ6uxvXsbu3Nx6F2Gy0CKt6oZc@hqYbWGTn9rkcX0H6IKZ@OCeu4V5LZqgKyTLJrGSVZIraMglFngKSJ5V4TYDKfkpBGdgfQ9HtjIpmml78UgWgv52TQhRLOk3cnKNClA9rcToiHVkOubCxmqsEbOlVh8YAozwWyDzC3vL3RYOPaRrnAPT/sLDn20S5IMT0Bg "Python 3.8 (pre-release) โ€“ Try It Online") Outputs a list, with tuples `(a, b)` indicating pair counts and solitary elements indicating left over socks. Interestingly, the `hash` function on integers seems to be the identity function, and so the output is conveniently ordered `[(0, count of 0 pairs), 0 if 0 has odd count, (1, count of 1 pairs), 1 if 1 has odd count, ...` as long as a contiguous sequence of numbers starting at 0 is used for sock indicators. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 69 bytes ``` a=>[a.filter(n=>p[n]?0:(a.map(m=>c+=m==n,c=0),p[n]=c>>1,c%2),p={}),p] ``` [Try it online!](https://tio.run/##dVDBasMwDL3vK3IZOMwLtpM2TkHeh4QcjJeMjsQJbell7NszW5rTMjp42JLek/TsT3u1Z3c6LpdXP7/36wCrBdPaYjiOl/7EPJil9d2bODBbTHZhExj3AhOA5w5EziMLzhjJ3bMKKXx9h7Nb3ezP89gX4/zBBtZKnilEmVDdYXePLs@f/nRvfXueCexoeCYxrUMgkZMkCSMkrQplKbaIHERRpCMhsVsgsKZw4q9qT6IbvcNIJfMCKzr5aMhK1FZ0a1RqpDT5oo1NQk3iCqdqSkqSoZ@KJKlEe@vtiSU9TKUvjAJ1uyqiUzeq9IPPlemL1L9k@YAJpfUH "JavaScript (Node.js) โ€“ Try It Online") ``` a=>[ a.filter(n=> // Filter out paired ones, return unpaired (odd) ones p[n]?0: // If we already paired it, skip ( a.map(m=>c+=m==n,c=0), // Count p[n]=c>>1, // Count / 2 pairs found c%2 // If count % 2 != 0, there is an odd one ), p={} // Initial pairs dictionary ),p] ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 16 bytes ``` ,R//Qd2{Qf%/QT2{ ``` [Try it online!](https://tio.run/##K6gsyfj/XydIXz8wxag6ME1VPzDEqPr//2hDHQUjMDKGIRMkZIqMYgE "Pyth โ€“ Try It Online") -1 byte thanks to @isaacg Two separate operations, returns two separate lists. Includes zero-pairs, which I believe is optional? Can fix at the cost of 2 bytes, if not allowed, by prepending e# -> `e#,R//Qd2{Qf%/QT2{` ## How it works ``` ,R//Qd2{Qf%/QT2{ ,R//Qd2{Q -- Returns pairs R {Q - Right map to the input cast to a set , - A two element list starting with the element of the set (implicit) //Qd2 - ...and ending with the count of that element in the input/2 f%/QT2{ -- Returns odds f { - Filter the implicit input cast to a set /QT - By the count of each element of the set in the input % 2 - Modulo 2 Both lists print implicitly ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` แนขล’rH2ยฆโ‚ฌ,แนชแธ‚$ฦ‡ฦŠแธž ``` [Try it online!](https://tio.run/##TZA9DsIwDIWvkqFjhuavTW/AFVDVkQV1YmPtUomRiYmBgQFxgHYFtfcIFwmJH02RrOTZ74vjZL9r26P3brxN58NGvu6f7snd@HBDl839fHLD1b/76ezGSxasrfc1qyVniqLgLOdMc1ZxJigtgxDkCSAmqMBLAkSelIBSsKMh6HROQTVJHX9UAWi1DSmMokmHil3mqDBKZDV2S6Qly2Iu3FgtUQLW1NUiUcBoHg1kKeHeMj1R4WGSygaAXDcNezlNlG04q/ET6U/RNoX5jxWP65qpKBvWfAE "Jelly โ€“ Try It Online") Somehow, before I stepped back for a bit and questioned my decisions leading up to it, my original solution was going to be `แนขล’rZd2ยฆ2Zยต1,[2,1]ล“แป‹โฑฎ,แนชแนช$ฦ‡`. I may have gotten a bit too attached to using divmod... [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` แป{รทโ‚‚แต—}แต|แป{t%โ‚‚1&h}หข ``` [Try it online!](https://tio.run/##TZC/CsIwEMZf5RB0itD8qU0XfZDSQR10EAQRRKqLg@AguLmKT@Cigo6OPkV9kZrcZ1vhSL777pfLJYNZfzheTqYjVWSLBrW71Fj0PtvLZ7PJb6f8sVvn10ORP/fZ6@6969EbK2/Mm86QrfH6fS6KhBIlSHN0BAWCjKBYkOQ0ckJyTQIJnXK8YkAGlZJQGmVfkHw64GBPcccf1QFUl0NWGMWwdo4t54gximcNdsuk5ZLFXLgxLiMCbLirRaKB8TwGSGnh3qh6osbDFNshAFVvBuXyNFM2FZTgJ6o/Rdsqwv@ocb/WmfYypfQL "Brachylog โ€“ Try It Online") [Generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output, since it saves a byte over using a fork: [`แปโŸจ{รทโ‚‚แต—}แตโ‰ก{t%โ‚‚1&h}หขโŸฉ`](https://tio.run/##TZC/asMwEMZf5TC0kwrWH8fy0j6I8ZBkaIZCoQRCMVkyFDwUsmU0zZRsWUwgGTv2KawXcaX7YjtwSN9999PppNnHdL74fHt/VV25iujpmaLVi/s6uc2mvVTrttl27fXb1Yfy9xy8Zhc8V/2Uywefy8fF@m/v6mPX5ZQrQZpjIigWZARlgiSnqReSaxJI4pXnFQMyHpSE0iiHguTTMQd7ijveqAmgsZywwiiGtXdsP0eGUQJrsFsmLZcs5sKNWR8pYMNdLRINjOcxQHoL96bDEzUepthOAKhxMyj3p5myhaAcPzH8KdoOkdzHiId1zHSQBRX/) ``` | The output is แป the list of pairs [unique element of input, # of occurrences] { }แต with each pair แต— 's last element รทโ‚‚ divided by 2 (rounding down), | or |แป that same list of pairs { }หข filtered by t the last element %โ‚‚ mod 2 1 being 1, { & }หข and mapped to h each pair's first element. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` {ร…ฮณUยฉX2โ€ฐรธ`.รรธ,ยฎsร, ``` [Try it online!](https://tio.run/##RY89CgIxEIWvkgMMsvnZTfYggiCCChZWFlvaaGHtOWxEsNl603sILxKT99xdGMibeV8yL6dutz8eUjrH2@e9HB4r8728Yr9dxGvsZXh28S4prY0oi2pEVaKcqFaURuuz0PA0kTqrzBsAupqUprK0i6Fxu0JhZvDin2oIzXYNxSgOOk/CmKNllMI6ngFkgBWYixvbsTxhh1cDG0sMeRyRccS9fvqi5ccMxjUBMx8lhkyXAYXNDw "05AB1E โ€“ Try It Online") ``` { sort input ร…ฮณ push run-length encoded input (count each element of input) UยฉX save compatibility number in ยฎ and count in X 2โ€ฐ divmod count by 2 (for each compatibility number, get the count of pairs and info if a single sock is remaining) รธ split that into a list of pair counts and a list of single socks ` push those lists onto the stack .ร rotate the stack, so list of compatibility numbers and the list of pair counts are at the top of the stack รธ zip them (for each compatibility number, get the pair count) , print that ยฎ push another list of compatibility numbers s swap with the list of single socks ร keep only compatibility numbers of single socks , print that ``` [Answer] # [Red](http://www.red-lang.org), 169 bytes ``` func[a][b: copy[]m: copy#()foreach n a[alter b n unless m/:n[put m n 0]m/:n: m/:n + 1]foreach k keys-of m[t: m/:k either t = 1[remove/key m k][m/:k: t / 2]]insert b m b] ``` Doesn't work in TIO (Apparently `remove/key` is added only recently). It works fine in the [Red](http://www.red-lang.org) GUI console: [![enter image description here](https://i.stack.imgur.com/KOksA.png)](https://i.stack.imgur.com/KOksA.png) `#()` is a map structure, the list of single socks is after it. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` รผ lu mรŽpยก[XรŽXรŠz] ``` Output is an array of the format: `[O1,O2,...On,[[V1,P1],[V2,P2],...[Vn,Pn]]]` where `O`s are odds, `V`s are values and `P`s are pairs. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/ApsdSBtznChW1jOWMp6XQ&footer=Vsy3K1IrVq9K&input=WzIsMywzLDYsMCw0LDksMSw2LDcsMTEsMywxMywzLDUsMTIsMiwxLDEwLDIsMSwxMSwyLDEzLDEyLDEwLDEsNywwLDAsMTIsMTIsNiwyLDEzLDYsMTAsMCwwLDEyLDUsMCwyLDMsNCwwLDUsOCwxLDYsOSw3LDEwLDE0LDEwLDgsMyw4LDksOCw1LDExLDcsOSw5LDksNywxNCw0LDIsOCwxNCwzLDExLDEyLDE0LDcsMTMsMTEsMTMsNCw3LDUsMTIsMywxLDEyLDQsNSwxMywyLDEzLDIsMTQsMSwxMywxMSwxLDQsOCwxNV0) (Footer formats the output for easier reading) [Answer] # APL(NARS), chars 66, bytes 132 ``` {โˆจ/cโ†ร—bโ†โŒŠ2รทโจโ‰ขยจaโ†aโŠ‚โจ1+aโ†โต[โ‹โต]:(โŠ‚c/b,ยจโˆชยจa),โŠ‚โˆชโŠƒโˆช/a/โจ0โ‰ 2โˆฃโ‰ขยจaโ‹„(โŠ‚โฌ),โˆช/a} ``` test: ``` fโ†{โˆจ/cโ†ร—bโ†โŒŠ2รทโจโ‰ขยจaโ†aโŠ‚โจ1+aโ†โต[โ‹โต]:(โŠ‚c/b,ยจโˆชยจa),โŠ‚โˆชโŠƒโˆช/a/โจ0โ‰ 2โˆฃโ‰ขยจaโ‹„(โŠ‚โฌ),โˆช/a} โŽ•fmt f 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 โ”Œ2โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚โ”Œ4โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œ3โ”€โ”€โ”€โ”€โ”€โ”โ”‚ โ”‚โ”‚โ”Œ2โ”€โ”€โ”€โ” โ”Œ2โ”€โ”€โ”€โ” โ”Œ2โ”€โ”€โ”€โ” โ”Œ2โ”€โ”€โ”€โ”โ”‚ โ”‚ 1 3 5โ”‚โ”‚ โ”‚โ”‚โ”‚ 1 2โ”‚ โ”‚ 1 3โ”‚ โ”‚ 2 4โ”‚ โ”‚ 2 5โ”‚โ”‚ โ””~โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚ โ”‚โ”‚โ””~โ”€โ”€โ”€โ”˜ โ””~โ”€โ”€โ”€โ”˜ โ””~โ”€โ”€โ”€โ”˜ โ””~โ”€โ”€โ”€โ”˜2 โ”‚ โ”‚โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ 3 โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โŽ•fmt f 1 2 1 2 โ”Œ2โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚โ”Œ2โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œ0โ”€โ”โ”‚ โ”‚โ”‚โ”Œ2โ”€โ”€โ”€โ” โ”Œ2โ”€โ”€โ”€โ”โ”‚ โ”‚ 0โ”‚โ”‚ โ”‚โ”‚โ”‚ 1 1โ”‚ โ”‚ 1 2โ”‚โ”‚ โ””~โ”€โ”˜โ”‚ โ”‚โ”‚โ””~โ”€โ”€โ”€โ”˜ โ””~โ”€โ”€โ”€โ”˜2 โ”‚ โ”‚โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ 3 โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โŽ•fmt f 1 2 3 โ”Œ2โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚โ”Œ0โ”€โ” โ”Œ3โ”€โ”€โ”€โ”€โ”€โ”โ”‚ โ”‚โ”‚ 0โ”‚ โ”‚ 1 2 3โ”‚โ”‚ โ”‚โ””~โ”€โ”˜ โ””~โ”€โ”€โ”€โ”€โ”€โ”˜2 โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โŽ•fmt f โฌ โ”Œ2โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚โ”Œ0โ”€โ” โ”Œ0โ”€โ”โ”‚ โ”‚โ”‚ 0โ”‚ โ”‚ 0โ”‚โ”‚ โ”‚โ””~โ”€โ”˜ โ””~โ”€โ”˜2 โ””โˆŠโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` but if it not be "codegolf" i would write for question of readability this 93 bytes code: ``` cโ†{+/โต=โบ}โ‹„fโ†{0=โ‰ขaโ†โต:โฌโฌโ‹„(โŠ‚{ร—โ‰ขbโ†({0โ‰ โŒŠ2รทโจโตc a}ยจb)/bโ†โˆชโต:b,ยจ{โŒŠ2รทโจโตc a}ยจbโ‹„โฌ}โต),โŠ‚โˆช({0โ‰ 2โˆฃโตc a}ยจa)/a} ``` because `({0โ‰ โŒŠ2รทโจโตc a}ยจb)/b` or exprestion as that has to be idiomatic... `g(fยจb)/b` traslate the math set `{g(x):xโˆŠbโˆงf(x)}`. [Answer] # [K4](https://kx.com/download), ~~27~~ 25 bytes **Solution:** ``` (,#:'=&_p),,&p>_p:.5*#:'= ``` **Example:** ``` q)k)(,#:'=&_p),,&p>_p:.5*#:'=1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 2 3 4 5!1 1 2 2 1 3 5 // this is how a dictionary looks in the repl q)k)*(,#:'=&_p),,&p>_p:.5*#:'=1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 2| 1 3| 1 4| 2 5| 2 ``` **Explanation:** ``` (,#:'=&_p),,&p>_p:.5*#:'= / the solution = / group input #:' / count (#:) each .5* / half (ie pair up) p: / save as p _ / floor p> / p > floor p? ie find whole pairs & / where true , / enlist , / join ( ) / do all this together _p / floor p & / where = / group #:' / count (#:) each , / enlist ``` **Extra:** * **-2 bytes** thanks to ngn [Answer] # [C (gcc)](https://gcc.gnu.org/), 155 154 151 bytes Thanks to ceilingcat for the suggestion. I use `-1` as the sentinel value for the list. First, I count the length of the input list, then I increment a count array at the index pointed into from the input. Lastly, I print the pairs in `type:number of pairs` format, then any singles remaining. I initialize `c` to zero even though it's a global because it won't necessarily be zero at the end of the function and I need to have it set correctly at the start of the function. I also use a dynamically-allocated count array so that it will be zero-initialized. ``` d,c,*a;f(int*i){for(c=0;~i[c++];);for(a=calloc(d=c,4);d--;a[i[d]]++);for(d=c;d--;)a[d]&&printf("%d:%d\t",d,a[d]/2);for(;c--;)a[c]%2&&printf("%d\t",c);} ``` [Try it online!](https://tio.run/##dVJfb4IwEH/nUzQuGgplo4iC69gnMHvbE/JA2uFqGBjF7cGwjz7W9kQlUXJJr78/d9dS7q057zpBOHFyVtiyahyJj0W9s3nis1@ZctfNGGYayROel2XNbZFwEmImPI/lqUxFlrkuSBRjYJwrdDLZ7lTBwh6NxfNYrJoREUQTTwGoGQcpz8bBtVgrOWZt9yArXh7EB3rZN0LWj5@vlqVE6CuXlf1dS4HR0UJIQ45Ms0RvENKnSDN8pAQFJqZ9hFcxG4ZHWzJwn31zgnzjWBBEzTZSCTUcBYnyU2ilYOqfM5hAizStCQpN@i8ytf0TH5jqJ8ccDBd6ZrKgP4hvkLifaQFjaW1o1kGf2LhiI4thXmoMiz4iMIamQwybKcjMbCFIeghmiHSpQSMK851ccM1aHFyWEOi@klHFN34A7a8xuEtObzBn4O19uVRJS5DjbJilUv3mNolkSO3R9tDs7dGq8u58I4xRYTsb/bSttvvjRZmv95338w8 "C (gcc) โ€“ Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~81~~ 74 bytes *-3 bytes by testing set difference in arithmetic mode instead, -4 bytes by using `local` instead of `typeset`* ``` local -A p for x;a=(${a:#$x} ${x:|a})&&((${#x:|a}&&++p[$x])) local p <<<$a ``` ~~[Try it online!](https://tio.run/##qyrO@J@moanxv6SyILU4tURB11GhgCstv0ihwjrRVkOlOtFKWaWiVkGlusKqJrFWU00tGsZWiFVT09DQ1i6IVqmI1dTkgplQwGVjY6OS@F@TiytNwRAIjYDQGAxNoNAUBv8DAA "Zsh โ€“ Try It Online")~~ [Try it online!](https://tio.run/##qyrO@J@moanxPyc/OTFHQddRoYArLb9IocI60VZDpTrRSlmlolZBpbrCqiaxVlNNTQMoqAzmqKlpaxdEq1TEampyQTQXcNnY2Kgk/tfk4kpTMARCIyA0BkMTKDSFwf8A "Zsh โ€“ Try It Online") The expansion `a=(${a:#$x} ${x:|a})` puts `$x` in `$a` if it isn't there, and takes it out if it is. Then we check if `$x` just got removed, and increment our pair count if it was. --- With a looser definition of "list", we can shave this quite a bit. # [Zsh](https://www.zsh.org/), ~~56~~ 52 bytes ``` local -A p l for x;((p[$x]+=1^(l[$x]^=1))) local p l ``` ~~[Try it online!](https://tio.run/##qyrO@J@moanxv6SyILU4tURB11GhQCGHKy2/SKHCWkOjIFqlIlbb1jBOIwfEirM11NTU5IIpBqr8r8nFlaZgCIRGQGgMhiZQaAqD/wE "Zsh โ€“ Try It Online")~~ [Try it online!](https://tio.run/##qyrO@J@moanxPyc/OTFHQddRoUAhhystv0ihwlpDoyBapSJW29YwTiMHxIqzNdTU1OSCKAWq@6/JxZWmYAiERkBoDIYmUGgKg/8B "Zsh โ€“ Try It Online") Prints the leftover socks as all elements in an associative array with value `1`, not `0`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` โ‰”โฆƒโฆ„ฮท๏ผฆฮธยซ๏ผฆยฌโ„–ฯ…ฮนยซโŠžฯ…ฮนยงโ‰”ฮทฮนโฐยปยงโ‰”ฮทฮนโŠ•ยงฮทฮนยป๏ผฉ๏ผฅฯ…โŸฆฮนรทยงฮทฮนยฒโŸง๏ผฉฮฆฯ…๏นชยงฮทฮนยฒ ``` [Try it online!](https://tio.run/##RY8xbsIwFIav4gN4iB2HOGdBDIilA1IlboBKhjJDxzLVUQtDxRIiMrm7cwdfIEdInfdjIj3p/e//P9vPq5flZvW6XA@Dfz948@bNztV9a9zNnkOzF7/76ErX2LPff5KoAuhq1/jtr71P0/5oq1HYe99@9@1XV/qTcc1f/bCv/lSFxJmu7JufaA7DfC45S6lmnCWcKc4KzgSNeRCCMgEkCyrwkgCRPJWAShGPgaDTCRV5km58UDNAU5yRwiqKdHB03KPAKiOr0DWRmiKNvfBiESsHrOhWjSEFRvsoINHCu/nziyk@JsnOAMipKcTxNFF6sfgH "Charcoal โ€“ Try It Online") Unfortunately I don't know how to get the deverbosifier to output `โฆƒโฆ„` (I just get `ยซยป` when I try). Explanation: ``` โ‰”โฆƒโฆ„ฮท ``` Initialise a dictionary. ``` ๏ผฆฮธยซ ``` Loop over the socks. ``` ๏ผฆยฌโ„–ฯ…ฮน ``` Test whether the compatibility number has been seen before. (Sadly Charcoal has no functions for determining dictionary keys, so I have to use a parallel list.) ``` ยซโŠžฯ…ฮนยงโ‰”ฮทฮนโฐยป ``` If it hasn't been seen then push the number to the list and zero out its dictionary entry. ``` ยงโ‰”ฮทฮนโŠ•ยงฮทฮนยป ``` Increment the dictionary entry. ``` ๏ผฉ๏ผฅฯ…โŸฆฮนรทยงฮทฮนยฒโŸง ``` Output the number of pairs for each compatibility number. The compatibility number and number of pairs are output on separate lines, with each pair of numbers double-spaced. ``` ๏ผฉฮฆฯ…๏นชยงฮทฮนยฒ ``` Output those compatibility numbers with odd socks, each on their own line. 52 bytes for a deverbosifier-friendly version: ``` ๏ผฆฮธยซโ‰”ฮฆฯ…โผฮนยงฮบโฐฮทยฟฮทโ‰”โŠŸฮทฮทยซโ‰”โŸฆฮนโฐโŸงฮทโŠžฯ…ฮทยป๏ผต๏ผญฮทโบฮบฮปยป๏ผฉ๏ผฅฯ…๏ผฅฮนรทฮปโŠ•ฮผ๏ผฉฮฆฯ…๏นชโŠŸฮนยฒ ``` [Try it online!](https://tio.run/##TY9Na8MwDIbPya/Q0QYP8tmm9FS6DXoo5B56CI27mDlJGydlMPrbM1tK2hmDJb2PpNfnuuzPXamn6dL1wG4cfn1vZ4z6atmn0oPs2Sjg4zaW2jAlYDcc2kr@sG8BAedcQM23vqcuwGoOc1/eXW02S1Ib6WYuQws7JDjNopePpnYLMHv43rG87rumKduK1QJyPRq3SXMrP/y8V@3A9qUZmOVcm3vsvEM7vKu7qiTTLjn3spHtICvWcDzb/62vXx27atQd2lXWboToNBVFJCDGu7JeBSQCNgJCTNc2CFELCUltZPkIgTB4RiFFMclOCLE7wIu1CCfO1Iqgl5xiRFYSjG0lW3xsyIpjE3ozJDOUMvJFGzfLXROc4NSMkpgw9JMQspRo7/r5xZg@FmE5JSB6PQnJSzdS2ek0vd31Hw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs the odd sock compatibility numbers double-spaced. 56 bytes for the original (IMHO better) condition that disallows printing zero pairs of socks: ``` ๏ผฆฮธยซโ‰”ฮฆฯ…โผฮนยงฮบโฐฮทยฟฮทโ‰”โŠŸฮทฮทยซโ‰”โŸฆฮนโฐโŸงฮทโŠžฯ…ฮทยป๏ผต๏ผญฮทโบฮบฮปยป๏ผฉฮฆ๏ผฅฯ…๏ผฅฮนรทฮปโŠ•ฮผยงฮนยน๏ผฉฮฆฯ…๏นชโŠŸฮนยฒ ``` [Try it online!](https://tio.run/##bY9Na8MwDIbPya/w0QYP8tU2pafSbdDDIPfSQ2jcxsxJ2jgpg9HfnslS3F4GBkt6H72STnXZn7rSTNO56xm/CfYbBltr9aXln9oMquejZB@3sTSWa8m2w76t1A//liwSQkhWi00Y6DPjtWBzX9FdIZslZaxynt70ACbRcRaDYrS1G4DZIwy@yuuua5qyrXgtWWFG6yYZAfIjLHrdDnxX2sGvBrjrdh/Y7tvhXd91pbhxyalXjWoHVfFG4Kp@d0BjV9n84@jcumo0HV6hoStBdJoOh0SyFN8STpAsk2wNTpiuIIhRiwlZQAR8gkAcPaOYopRkJ8TYHeHDWoKOM7Uk6CUvMKJVMoyhkvs91rSKYzP6cyRzlHLaiyau/VsRnKFrTklKGO6TEeJLNHf1PDGlwxIsLwhIXl9Gsu9GKj8ep7e7@QM "Charcoal โ€“ Try It Online") Link is to verbose version of code. Would be 43 bytes if Charcoal supported dictionary iteration: ``` โ‰”โฆƒโฆ„ฮท๏ผฆฮธยงโ‰”ฮทฮนโˆจโฌคฮทโปฮนฮปโŠ•ยงฮทฮน๏ผฉฮฆ๏ผฅฮทโŸฆฮบรทฮนยฒโŸงยงฮนยน๏ผฉฮฆ๏ผฅฮทฮบ๏นชยงฮทฮนยฒ ``` [Answer] # [Haskell](https://www.haskell.org/), 112 bytes ``` import Data.List f i=(\j->([(x,l`div`2)|(x,l)<-j,l>1],[x|(x,l)<-j,l`mod`2>0]))[(x,length s+1)|x:s<-group.sort$i] ``` [Try it online!](https://tio.run/##hZDJboMwEIbveYo59ACqQdiQYKqEU4/tE1BUkLI5ZRPQikPeneKZmuQSao3k8fzfbD7n3dehKMZRlU3d9vCa97n7prp@dQS1sz4uTmwl1sCKbK9@MmFftW9vnQsrYp6yZLgLZGW9z0TspbaNKYfq1J@he@b2dXjpts6prb8bt5vaPKl0LHNVwQ7KvHn/BKtpVdWDC0cbkoQzEGi@seDO1veWruDRYclcYcPAw9yIAcdnODkcNU7IVIxT0ynMvdmjWTSkZS1wzPbQMCaw4h@1Iegmr9ETZg0PI9LMEdEomg3olkhKlCTNRR0jYyHBAVaV9PAJw3kCQkyI@obzij4tJsxnakDcroBkk42UXPxmbj5L/IMJ5i8SC2I6/gI "Haskell โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` รผ lu mรŽuUmรŽรญUร‹รŠz ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=/ApsdSBtznVVbc7tVcvKeg&input=IFsyLDIsMiwyLDEsM10) Better solution that pairs list of first elements with list of lengths/2 using **รญ** instead of **รข**. # [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` รผ lu mรŽuUร‹รขDรŠz h ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=/ApsdSBtznVVy%2bJEynogaA&input=IFsyLDIsMiwyLDEsM10) output [sock , pairs num] list followed by odd socks. ``` รผ // sort and group input and save it lu mรŽ // first element of groups of odd length u // perpended by.. Uร‹ // imput mapped รข // unique elements DรŠz h // concatenated to half of the length to string ``` Thanks to @Shaggy for finding a bug. Unfortunately using **รข(x?)** => **x** is concatenated *before* returning unique elements , so it failed with *[2,2,2,2]* case. Fixed by using **h** method which returns a string. [Answer] # [Lua](https://www.lua.org/), ~~144~~ 142 bytes ``` load'r,p,o,i={},{},{},...for a=1,#i do r[i[a]]=(r[i[a]]or 0)+1 end;for a,b in pairs(r)do p[a],o[#o+1]=b//2,(b%2>0)and a or nil end;return p,o' ``` [Try it online!](https://tio.run/##RZHRqsIwDIbvfYqAHGwxzHWbOjnsvIh40Z1NKI51dNu5EZ/dkyZOIdA0/5f2b9PN9tn5X9vBFSqw49iGSVHFNpuAA3p01f2BEkmSXH0AWxlcO2g8hLM728ulUq@ExFRvDbR9880k1uB6GKwLowqaOgbC0J/XfmsuVb3bZajqr@wn1bZvwAL19K7j/tBOc6Be9JunXq3EoyOP9wwh5zggpAgFwgnB8PZIiWHNCLKnjPiMAZO@MyNZLnIUDHenHFzL@MQXdRDoI@85EysF51QpFx8nsRLZQtaSyZKlUnzJjacljgIXfGopm1ww9lMIspTk3uP7ibk8LOPyXoDssxQiL91MlY/lXwcbRgQ/TyN98FU5@vA4vxv@feYXGR2nPgTXT4o0HQe1ku1k665N5n6wvzcVD9L6@Q8 "Lua โ€“ Try It Online") Function that takes list as argument and returns hashtable representing pairs and list of ones without match using Lua "multireturn". Note: if there is only one sock of some color (poor guy), it still will go in pairs list with zero pairs. If this is not up to spec, please tell me (it will cost a bunch of bytes but is easily doable). I personally consider `return` to be required, but results are also stored in globals `p` and `o`, so it in fact can be omitted. [Answer] # [Perl 5](https://www.perl.org/), 82 bytes ``` sub{my%H;$H{$_}++for@_;delete@H{@A=grep$H{$_}%2,keys%H};map$_/=2,values%H;\%H,\@A} ``` [Try it online!](https://tio.run/##dY9da4MwFIbv9yt2odDSU2ZirLHisNALb/YPCmJZHGVagx@DIv71uXMSe@d4ITl5n/ORo1VbBbNTJnM3XMf64Waxk41OPu12ZdOmefypKtWrNBvTU/LVKm2py@FbPTo3m@K60E7@lnD4KapBoRVf3Awu6Wma4xfd3u7963motWo3Trl/3zDgKN9ILAqe2m7XSmz6ATxMjYBhFAJjaDHyA2DUkQHz7EUTkKCLDsNcD0UvjpUGHYgsbgCe@Y/AOwBp2kc0AKmgUyKUaEmaRO0io5CwwFJJgU@IZggC9kU9Q/s9HwylTdHmyyGAPXMRyfXlzTbA/4f@OkJ3/m10f2vu3bz/OBd9cTzahD8 "Perl 5 โ€“ Try It Online") # (`-ap`), 73 bytes Returning hash as key value pairs list ``` s/(\b\d+)( .*)(\b\1\b)/$H{$1}++;$2/e&&redo;delete@H{@F};$_="@{[%H]} | @F" ``` [Try it online!](https://tio.run/##NY/dioMwEIXvfYqhpMVUVh2NNSIuXhXfYV2WLWahIDW0vXN99c3ORMuBzOR885NYcx8Ld/0JRfwurJz3XRPKWthGxIt7JGF/6YdIhhAfJefYX2QiulngEkW1yBJzONzNMNWDGc3TtN3cnpdafDW7dv7Yd58L/EJ73jmHkJFyL7WpeClYyQlScitAykpAJAvZLwC5GQHTNfAwIuSSg1SbkviWUadHJyabW0DqVyuKBWg/vuIFRBWfmqAmS/MmHld5lYwVtWpOcka8QzFYbzyzXJ@Xg6f8KbKz7VCAr1pCOvAPh8zHPAj@Jvu8TreHe/se7T8 "Perl 5 โ€“ Try It Online") [Answer] # [Lua](https://www.lua.org/), ~~133~~ ~~123~~ 119 bytes (using global output var) ``` r,o,s={},{},{}for _=1,#t do d=t[_]r[d]=(r[d]or 0)+.5 end for a,b in pairs(r)do s[a],d=math.modf(b)o[#o+1]=d>0 and a end ``` [Try it online!](https://tio.run/##jZLNasMwDMfvfQrhXmJqQpyPNh24r7DdsxDSOaaBNh6Jyw6lz5450tIw6GCgxLL0k/U38vlaj@bafbjWdmACx8deWDGo212gGdtDpaRYO9AWtHJFVfaFLlUw/X0y4pswg6bTMKG1OELbwWfd9kPQc18yFHUptLrU7hRerDbBkdtibTeyVPoQQe0L66l89N/KBLdYQIK2FRAJSAXsBUjc7rwjMScJybzn@RgBGT08SV5C6SkhsTpCw1iMJ/5QW4KWdIYeSUnR95F81rEnKROb0pojmWMqJ13UcT/bjuAUT81pkxCGelJC5hD13T2umNDFYgxnBMTLklJ6rkYqv/OV8WNwyvXXZtXa8KtvXROwt2k4L3BjHIcrqmoZ2cCnMT/YAA/AITEGnmYCGA/DKgyZOjDvVByoianPQ4PvYOl0f@/YHyJetfYaimcaLGkw4IPu1HT/kPNExW8lJePjNw "Lua โ€“ Try It Online") # [Lua](https://www.lua.org/), 135 bytes (using output return) ``` r,o,s={},{},{}for _=1,#t do d=t[_]r[d]=(r[d]or 0)+.5 end for a,b in pairs(r)do s[a],d=math.modf(b)o[#o+1]=d>0 and a or x end return o,s ``` [Try it online!](https://tio.run/##jVJNa8MwDL33Vwj3EjM35LNNB@5hfyCDHrMQ3DlhgTYprsM2Sn9750hLeyljIJJnvSfpGXk/qGszdO@27TtoPMuvRvTiJM8XgdH0BioZirkF3YOWtqhKU@hSeuPXkQF/8lOoOw2jVIkdtB0cVWtOnuGu5FSoUmh5UPbDP/S68Xa8L@b9U1hKvQlAuUIFrvILe5jaDqYD5@DqjrNcbGXjnSMBMcZSQCAgEbAWEOJx5UCIXEiS1CGnj1AQBjcUEoqJHokQqwMMzEXY8Ve1JNGdThGRlQSxy2STjzVZGbUJ/TNUZkhl5IsmrqdYkTjBrhkdYpKhn4QkU4rmrm5XjOliEaZTEkT3X0L0VI2q7MJni8VLrQbbNt@QD/Y42FnjlmWlNUM9a3v/07S29tjruMJnODOOT0BU1X2xWz4@hpvWwwa4SsbGXTIBjPt@5ftMbpgDFQca0qj9qcZN3ydd3jrGH5vItXYeikce8n96@HN0yfj1Bw "Lua โ€“ Try It Online") [Answer] # [Clojure](https://clojure.org/), 102 bytes ``` (fn[d](def f(frequencies d))[(map(fn[[x y]][x(quot y 2)])f)(map first(filter #(=(mod(nth % 1)2)1)f))]) ``` [Try it online!](https://tio.run/##hZDRisIwEEXf/YrBZSGBLjRp1XZhv2H3PeSh2gQrNdXagn59N5nZVIUFYSDJvSd3Jtm13WHszcRqY2E/MetUrfFgme3NeTRu15gL1JwrdqxOAVBXuGmtruw8dgPcQHLNLQ8u2Ka/DMw27WB6eGNf7NjVzA17eAfBJRee8/DEF6GFg1PfuOGjN5exHUCpCrZaLwAY6q2D5U/lAz9hCRV/0r/rGuUt91FPKWwPSiQgsbJY@UOtHkvPAa37L2oOWSeQ4vUyAYHHjd8I9AQhPk9QXy@LdN7ROAEKdjAE3k6xUJOY@EetCbrbK9zJ@JIUlSLOUdIogc1pLZAs0CpoLupYxtoQnGNqQYeMMJwnJyRK1HczPzGjh8n4nwGQ9yUnO95Gqnj10yL@l3xNyiR7BXl/@gU "Clojure โ€“ Try It Online") I really thought clojure would have a better chance. If only I had access to fmap. :-( [Answer] As suggested by JoKing this can be substantially shortend to: # [Ruby](https://www.ruby-lang.org/), 90 bytes ``` c=Hash.new(0) ARGV.each{|s|c[s.to_i]+=1} c.each{|k,v|p k if(p"#{k}=>#{v/2}"if v>1)&&v%2>0} ``` [Try it online!](https://tio.run/##KypNqvz/P9nWI7E4Qy8vtVzDQJPLMcg9TC81MTmjuqa4Jjm6WK8kPz4zVtvWsJYrGSqerVNWU6CQrZCZplGgpFydXWtrp1xdpm9Uq5SZplBmZ6ipplamamRnUPv//3/D/0ZAaAyGJlBoCoMA "Ruby โ€“ Try It Online") Old version: # [Ruby](https://www.ruby-lang.org/), 139 bytes ``` c=Hash.new(0) ARGV[0].split(",").map(&:to_i).each{|s|c[s]+=1} o = [] c.each{|k,v|o<<k if v.odd?} c.each{|k,v|o<<"#{k}=>#{v/2}" if v!=1} p o ``` [Try it online!](https://tio.run/##KypNqvz/P9nWI7E4Qy8vtVzDQJPLMcg9LNogVq@4ICezRENJR0lTLzexQEPNqiQ/PlNTLzUxOaO6prgmObo4VtvWsJYrX8FWITqWKxkqk61TVpNvY5OtkJmmUKaXn5JiX4sup6RcnV1ra6dcXaZvVKsEVqgIMqlAIf////9KhjoKRmBkDEMmSMgUGSkBAA "Ruby โ€“ Try It Online") Pardon me for writing non-idiomatic Ruby maybe. ]
[Question] [ I know there have been a lot of challenges about "the two best code-golfers in the world", but this one is a bit more unique, being *Round 1* in a series of (future) challenges involving the two of them. --- Your task is to write a program or function that returns two different non-whitespace ASCII strings, corresponding to the one who has more reputation at the moment the program is ran, between [Dennis โ™ฆ](https://codegolf.stackexchange.com/users/12012/dennis) and [Martin Ender โ™ฆ](https://codegolf.stackexchange.com/users/8478/martin-ender). The tricky part is that you must output the exact string ***"tie"*** in case the reputation is identical (not likely), and the two *different non-whitespace ASCII strings* mentioned above should be different than *"tie"* **\***. No input can be taken, such as usernames or user ids. As usual, URL shorteners are forbidden, and so are the common loopholes. ## Examples: ``` Let the chosen string for Dennis be "D" and the chosen one for Martin Ender be "M" (should be specified) If Dennis' rep > Martin Ender's rep => D If it's the other way around => M If it's a tie => tie ``` --- > > **IMPORTANT!** Voting on posts by Dennis & Martin for the sole purpose of affecting a tie in order to test the solutions below constitutes targeted voting which is forbidden across the Stack Exchange network. If you want to test that a solution properly outputs `tie` then change the IDs in it to those of 2 users you know to be tied. See [this Meta post](https://codegolf.meta.stackexchange.com/q/12334/58974) for more details. > > > \**I think no one would have used that, anyway* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~65~~ 64 bytes ### Code: ``` โ€ขะฒ=6{โ€ข5รดvyโ€™ฦ’ร‹ล ห†.ร‚โ€šโ€นยบ.ล’ล’/โ€ ลก/รฟโ€™.wโ€™โ€žร–="ร‚ห†"โ€™ยก1รจั‚ยฃรพ}})ZQฤ*O<โ€œD Mยทโ€กโ€œ#รจ ``` Uses the **05AB1E** encoding. ### Explanation: `โ€ขะฒ=6{โ€ข` converts the number `ะฒ=6{` from base 255 to base 10, resulting in [1201208478](https://tio.run/nexus/05ab1e#@/@oYdGFTbZm1UD6/38A). The first half being the ID of Dennis (12012) and the second half being the ID of Martin (8478). Split into pieces of 5 using `5รด` to get the following array: ``` ['12012', '08478'] ``` Luckily, we can leave the leading zero from Martin's ID, since [this will still work](https://codegolf.stackexchange.com/users/08478) (check the link before clicking to see the leading zero). We now loop through this array using `vy` and construct the following string from this 05AB1E code: ``` โ€™ฦ’ร‹ล ห†.ร‚โ€šโ€นยบ.ล’ล’/โ€ ลก/รฟโ€™ --> codegolf.stackexchange.com/users/รฟ ``` Whereas `รฟ` is the current element of the iterator (using string interpolation) [Try it online!](https://tio.run/nexus/05ab1e#ATAAz///MTIwMTIg4oCZxpLDi8Wgy4Yuw4LigJrigLnCui7FksWSL@KAoMWhL8O/4oCZ//8 "05AB1E โ€“ TIO Nexus") After constructing the link, `.w` reads all data from the link, resulting into a huge amount of text. To scrape the reputation from this, we need to split on the string `title="reputation"`. Or in a more compressed version: [`โ€™โ€žร–="ร‚ห†"โ€™`](https://tio.run/nexus/05ab1e#@/@oYeajhnmHp9kqHW463aYE5P7/DwA). Split on this piece of string (with `ยก`) and get the second element (with `1รจ`) and keep the first **100 characters** (with `ั‚ยฃ`). Now, our scraped text looks a bit like this: ``` > 139,883 <span class="label-uppercase">reputation</span> </div> <div class="ba ``` This part is easy, we just remove anything **but digits** to remain the reputation number, for which we have a builtin (`รพ`). We end the loop and wrap everything into an array `}})`. Finally, we can go on to processing the reputation numbers: ``` ZQฤ*O<โ€œD Mยทโ€กโ€œ#รจ - On stack: an array in the format [Dennis rep, Martin rep] Z # Get the maximum of the array Q # Check for equality with the array ฤ* # Multiply by it's index (1-indexed) O< # Sum and decrement by 1 โ€œD Mยทโ€กโ€œ# # Push the array ['D', 'M', 'tie'] รจ # Get the element on the index of the sum ``` Which results in either `D`, `M` or `tie`. [Answer] # PowerShell v3+, ~~147~~ ~~123~~ ~~119~~ ~~103~~ ~~101~~ 96 Bytes ``` $a,$b=irm api.stackexchange.com/users/12012`;8478?site=codegolf|% I*|% r*n;$a-$b|% T*g "D;M;Tie" ``` Saved 24 bytes using true/false output instead of the names. Saved another 4 by restructuring the final checks. saved 16 by getting only the reputations of the two users from the request, saves having to use the `|% r*n` more than once, also means we can get rid of like a million brackets, and two useless variables. -2 thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) - using an escape char instead of two doublequotes for the url, also removed the `@` from the array which was un-needed (oopsie) used a weird `.ToString` trick I never knew existed until now reccomended by [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) -5, and finally below 100. --- Version which returns names: ``` $a,$b=irm "api.stackexchange.com/users/12012;8478?site=codegolf"|% I* if(($c=$a|% r*n)-eq($d=$b|% r*n)){"tie"}else{@(($a|% d*),($b|% d*))[$c-lt$d]} ``` this looks pretty messy due to the shortening of parameter names. anywhere `|% r*n` appears we're getting the `ReputatioN`, and `|% d*` is the `Display_name` uses `Invoke-RestMethod` (alias `irm`) to query the API, stores the result named `Items` (gotten using `|% I*`), into the two variables `$a` & `$b`, one for each pro golfer's, the `ToString` (`|% T*g`) trick results in one of the values `D`,`M` or `Tie` if the number is odd/even/zero. [Answer] # [Python 2](https://docs.python.org/2/), 160 bytes ``` from requests import* print cmp(*[get('http://api.stackexchange.com/users/12012;8478?%ssite=codegolf&filter=!9aK21rboZ'%s).text for s in'order=asc&',''])or'tie' ``` Not the shortest Python answer, but the shortest one so far that doesn't make any assumptions. Prints `1` if Martin has more rep, `-1` if I do. [Answer] # JavaScript (ES6), ~~167~~ ~~156~~ ~~146~~ ~~144~~ ~~141~~ ~~132~~ 103 bytes Stupid [`fetch`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) and its stupid, expensive [`Promise`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) chaining! Assumes, as currently allowed, that Dennis & Martin will always be the 2 top ranked users. Needs to be run from the root level of `api.stackexchange.com`. Returns a `Promise` object (as is now [permitted by consensus](https://codegolf.meta.stackexchange.com/a/12327/58974)) containing `tie` or the JSON object for whoever has the most rep at the time. If the JSON object isn't considered valid output then add 5 bytes for `.link`. ``` _=>fetch`users/?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j) ``` * Saved 11 bytes thanks to [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) suggesting I return the profile `link` rather than the first letter of the `display_name`, which also provide better future-proofing against them changing their usernames to start with the same letter! * 5 bytes saved adapting a tip from [kamoroso94](https://codegolf.stackexchange.com/users/57013/kamoroso94) on a another solution of mine. --- ## Try It ``` f= _=>fetch`//api.stackexchange.com/users/?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j) f().then(console.log) ``` --- ## Alternative If a time comes that Dennis & Martin aren't at the top and we still want to know who has the most rep between them then we'd need the following, at a cost of an additional 10 bytes. ``` _=>fetch`users/12012;8478?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j) ``` [Answer] # Python 3, ~~160~~ ~~157~~ 151 bytes ``` from requests import* a,b,*c=get('http://api.stackexchange.com/users?site=codegolf').json()['items'] r='reputation' print(['tie',a['link']][a[r]>b[r]]) ``` --- *-3 bytes thanks to @KevinCruijssen* Prints a link to the user having more reputation Assumes they are on #1 and #2 --- **Without making any assumptions, Python 2, 157 bytes**: ``` from requests import* a,b=get('http://api.stackexchange.com/users/8478;12012?site=codegolf').json()['items'] r='reputation' print['tie',a['link']][a[r]>b[r]] ``` [Answer] # PHP, 167 Bytes prints -1 for Dennis , 1 for Martin Ender. tie in case of a tie ``` <?=($b=($t=json_decode(gzdecode(join(file('http://api.stackexchange.com/users/12012;8478?site=codegolf&order=asc'))))->items)[0]->reputation<=>$t[1]->reputation)?:tie; ``` [Answer] # Python, ~~226~~ ~~225~~ 221 bytes I feel like this is too long. ``` import requests as r,re def f(i):d=re.sub('[, ]','',r.get('http://codegolf.stackexchange.com/users/'+i).text);D=d.index('"reputation">')+14;return int(d[D:d.index('<',D)]) a=f('8478') b=f('12012') print([a>b,'tie'][a==b]) ``` Prints `"True"` if Martin has more rep than Dennis, `"False"` if Dennis has more rep than Martin, and `"tie"` if they have the same (theoretically. I can't test this :P). `https` -> `http` for 1 byte thanks to @KevinCruijssen! `re as r, r.sub` -> `re, re.sub` for 4 bytes thanks to @ovs! [Answer] # Bash + [jq](https://stedolan.github.io/jq/), 140 133 bytes ``` w3m 'api.stackexchange.com/users/12012;8478?site=codegolf&sort=name'|jq '.items|map(.reputation)|1/(index(min)-index(max))'||echo tie ``` ## Formatted and explained First, we *curl* w3m the API (and use `--compressed`, or short `--com` to un-gzip): ``` w3m 'api.stackexchange.com/users/12012;8478?site=codegolf&sort=name' ``` That's some JSON. Notice the order ist stable, not based on reputation. JQ then processes the JSON, which is what it's made for. ``` .items # take the items array | map(.reputation) # extract only the reputations | 1 / (index(min)-index(max)) # This checks if the bigger value is first (1) or last (-1) in array ``` We use `1/x` above to generate an division-by-zero error when min==max, so in a tie situation. The `||echo tie` in bash catches that. *Note that a warning is printed on stderr by JQ in that case, but we consider only stdout the actual result of the program ;)* [Answer] # [Python 2](https://docs.python.org/2/), ~~228~~ ~~223~~ ~~204~~ 199 bytes I did this on a mobile hotspot so... it's not great... ~~Assumes both of them will always be in the same hundred thousand.~~ Doesn't assume anything now. :D ``` import urllib as l,re f=lambda i:int(re.search('n">\s*([\d,]+)',l.urlopen('http://codegolf.stackexchange.com/users/%d'%i).read()).group(1).replace(',','')) d,m=f(12012),f(8478) print[d>m,'Tie'][d==m] ``` Prints `True` if Dennis has more reputation than Martin, `False` otherwise and `Tie` if they are... tied. [Answer] ## [Stackexchange API Data Explorer](https://data.stackexchange.com), ~~184~~ 180 bytes Thanks to @Kevin Cruijssen for -4 bytes ``` DECLARE @M int,@D int;SELECT @M=reputation from users where id=8478;SELECT @D=reputation from users where id=12012;IF @D=@M PRINT('tie')ELSE BEGIN;IF @D>@M PRINT(1)ELSE PRINT(2)END ``` Prints 1 for Dennis and 2 for Martin Since i only [yesterday](https://codegolf.stackexchange.com/a/143116/56341) learned about the [SEADE](https://data.stackexchange.com) this should be very beatable. [Try it here](https://data.stackexchange.com/codegolf/query/725157/martin-ender-versus-dennis) ]
[Question] [ If you sort a string you'll typically get something like: ``` ':Iaaceeefggghiiiiklllllmnnooooprrssstttttuuyyyy ``` Yes, that was the first sentence sorted. As you can see, there are a lot of repeated characters, `aa`, `eee`, `ttttt`, 9 spaces and so on. If we add `128` to the ASCII-value of the first duplicate, `256` to the second, `384` to the third and so on, sort it again and output the new string (modulus 128 to get the same characters back) we get the string: ``` ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt ``` (Note the single leading space and the 4 trailing spaces). The string is "sequentially sorted" `<space>':I....uy`, `<space>aeg....uy`, `<space>egi....ty`, `<space>iloty`, `<space>lt`, `<space>`, `<space>`,`<space>`, `<space>`. It might be easier to visualize this if we use a string with digits in it. The string `111222334` will when "sorted" be: `123412312`. ## Challenge: To no surprise, the challenge is to write a code that sorts a string according to the description above. You can assume that the input string will contain only printable ASCII-characters in the range 32-126 (space to tilde). --- **Test cases:** ``` **Test cases:** *:Tacest*es*s* If you sort a string you'll typically get something like: ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt Hello, World! !,HWdelorlol #MATLAB, 114 bytes #,14ABLMTbesty 1A f=@(s)[mod(sort(cell2mat(cellfun(@(c)c+128*(0:nnz(c)-1),mat2cell(sort(s),1,histc(s,unique(s))),'un',0))),128),'']; '()*+,-0128:;=@[]acdefhilmnoqrstuz'(),0128@acefilmnorstu'(),12celmnostu'(),12celnstu(),clnst(),cls(),cs(),()()()() ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in *each language* counted in bytes will win[ref](http://meta.codegolf.stackexchange.com/a/10132/31516). [Answer] # Pyth, 5 bytes ``` s.T.g ``` [Test suite](https://pyth.herokuapp.com/?code=s.T.g&test_suite=1&test_suite_input=%22%2a%2aTest+cases%3A%2a%2a%22%0A%22If+you+sort+a+string+you%27ll+typically+get+something+like%3A%22%0A%22Hello%2C+World%21%22%0A%22%23MATLAB%2C+114+bytes%22%0A%22f%3D%40%28s%29%5Bmod%28sort%28cell2mat%28cellfun%28%40%28c%29c%2B128%2a%280%3Annz%28c%29-1%29%2Cmat2cell%28sort%28s%29%2C1%2Chistc%28s%2Cunique%28s%29%29%29%2C%27un%27%2C0%29%29%29%2C128%29%2C%27%27%5D%3B%22&debug=0) Very straightforward: Group and sort, transpose, concatenate. ``` s.T.g s.T.gkQ Implicit variables .gkQ Group the input input lists of elements whose values match when the identity function is applied, sorted by the output value. .T Transpose, skipping empty values. This puts all first characters into a list, then all second, etc. s Concatenate. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ฤ Zแป‹ ``` [Try it online!](https://tio.run/nexus/jelly#JYw/TsMwGMX3nOJDDLFdI9URAwqq1DKBBFsl1KIOwXVaC8eGfPYQRpYOvUQP0LFbx3KRcpFgq9v783uv/93Nz8dtfz4eTpu/n/2s7xmbKvQgK1RYMpY91dC5AOhaDxWgb7VdpSQ3Bnz3qWVlTAcr5SPSKL9OtdEfqswelTGOw6trzfIqu36ZTJ8nDxyEuIX3zivM6tGYIH1r3JKkeyLjoGiqi6iDJWMiqRyI4o6RYWntd7Q3gvKIFAm5rJBywdcavSTIg9VfQcWMUp4Hm/NhUvEh2nxx/w8 "Jelly โ€“ TIO Nexus") ### How it works Oh boy, this challenge was all but made for Jelly. The *group* atom (`ฤ `) takes an array1 as input and groups indices that correspond to identical elements of the array. The array of index groups is sorted with the corresponding elements as keys, which is precisely the order we require for this challenge. Next, the *zip* atom (`Z`) transposes rows and columns of the generated (ragged) matrix of indices. This simply consists of reading the columns of the matrix, skipping elements that are not present in that column. As a result, we get the first index of the character with the lowest code point, followed by the first index of the character with the second lowest code point, โ€ฆ followed by the second index of the character with the lowest code point, etc. Finally, the *unindex* atom (`แป‹`) retrieves the elements of the input array at all of its indices in the generated order. The result is a 2D character array, which Jelly flattens before printing it. --- 1 Jelly doesn't have a *string* type, just arrays of characters. [Answer] # Python 3, ~~109~~ ~~105~~ ~~104~~ ~~103~~ ~~99~~ ~~93~~ ~~90~~ ~~88~~ ~~81~~ ~~79~~ 69 bytes *2 bytes saved thanks to FlipTack* *7 bytes saved because flornquake caught my dumb error* *2 bytes saved thanks to xnor* *10 bytes saved thanks to Dennis* ``` a=[*input()] while a: for c in sorted({*a}):print(end=c);a.remove(c) ``` ## Explanation We start by converting our string to a list using a splat and storing that list in a variable `a`. Then while our `a` is not the empty list we go through each unique member of `a` in sorted order, print it and remove a copy of that character from the list. Each iteration prints thus prints one copy of each character present in `a`. [Answer] ## Haskell, 44 bytes ``` import Data.List concat.transpose.group.sort ``` Usage example: ``` Prelude Data.List> concat.transpose.group.sort $ "If you sort a string you'll typically get something like:" " ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt " ``` Sort, group equal chars to a list of strings (e.g. `"aabbc"` -> `["aa","bb","c"]`), transpose and flatten into a single string, again. [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` lambda s:`zip(*sorted((s[:i].count(c),c)for i,c in enumerate(s)))[1]`[2::5] ``` [Try it online!](https://tio.run/nexus/python2#JY9PT8MwDMXP9FMYcahTAlorJqGgSRsnkOA2iUOptixNt4g0Kfkj1H35kWg3P/v3nu0BVvB90Xw89Bw825/VhJW3Lsge0bdMdY/CRhNQECrIYB0oKkAZkCaO0vEg0RNC2rrbtw1jy@6SmV0mHDdHiUvCipvJKRNgQMf/dspMMSAhl6raSh9AcC89q6rifYDZRsjLId0SkueYO6XWEOZJCa71DEcZEjLKcMpjrX4kK96k1pbCl3W6vy3uPjfbj80rhbp@gsMcpC@G1Tqd2Y62xxyPIhmakV@LIRpcp//Efd08V7hgxpyTfKgJTUiTkavLE1rTk/JBoKfRqN94fZ6W0ZR0kauUkGTZvfwD "Python 2 โ€“ TIO Nexus") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 20 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` t[0~โจโˆŠโ‰(โŠ‚โ‹โˆชt)โŒทโŠขโŒธtโ†โž] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94H9JtEHdo94Vjzq6HvV2ajzqanrU2/2oY1WJ5qOe7Y@6Fj3q2VHyqG3Co955sSD1/xXAoIDLM02hMr9UoTi/qEQhUaG4pCgzLx0kop6To1BSWZCZnJiTU6mQnloCVJKbWpIBks7JzE61AgA "APL (Dyalog Unicode) โ€“ Try It Online") `t[`...`]`โ€ƒindex *t* (to be defined shortly) with... โ€ƒ`0~โจ`โ€ƒzeros removed from โ€ƒ`โˆŠ`โ€ƒthe enlisted (flattened) โ€ƒ`โ‰`โ€ƒtransposed โ€ƒ`(โŠ‚`โ€ฆ`)โŒท` reordered usingโ€ฆ โ€ƒโ€ƒ`โ‹`โ€ƒthe indices which would sort โ€ƒโ€ƒ`โˆช`โ€ƒthe unique letters of โ€ƒโ€ƒ`t`โ€ƒ*t* (to be defined shortly) โ€ƒ`โŠขโŒธt`โ€ƒkeyed\* *t*, which has the value of โ€ƒโ€ƒ`โž`โ€ƒprompted text input [TryAPL online!](http://tryapl.org/?a=%u2359%u2190%27If%20you%20sort%20a%20string%20you%27%27ll%20typically%20get%20something%20like%3A%27%20%u22C4%20t%5B0%7E%u2368%u220A%u2349%28%u22A2%u2338t%29%5B%u234B%u222At%u2190%u2359%3B%5D%5D&run) --- \*ย `โŠขโŒธt` creates a table where the rows (padded with zeros for a rectangular table) list each unique letters' indices in *t*. [Answer] # C, ~~109~~ ~~106~~ ~~105~~ ~~104~~ ~~102~~ ~~100~~ ~~97~~ ~~98~~ ~~96~~ 91 Bytes ~~Back up to 98 Bytes, needed to initialize j to make f(n) re-useable~~ ~~Down to 96 Bytes using puts in place of strlen B-)~~ It's strange I had to back to strlen but I got rid of the for(;i++;) loop so now it's down to 91 Bytes. Apparently the man page for puts reads; ``` "RETURNS If successful, the result is a nonnegative integer; otherwise, the result is `EOF'." ``` ... I was lucky it was working in the first place ``` char*c,i,j;f(m){for(j=strlen(m);j;++i)for(c=m;*c;c++)if(*c==i){*c=7,putchar(i),j--;break;}} ``` test code... ``` main(c,v)char**v; { char test[] = "If you sort a string you'll typically get something like: "; char test2[] = "Hello, World!"; f(test);puts(""); f(test2);puts(""); } ``` Here are a few test cases, now it's time to golf this down ``` C:\eng\golf>a.exe ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt !,HWdelorlo ``` [Answer] # Mathematica, ~~68~~ ~~60~~ 59 bytes ``` Split[Characters@#~SortBy~ToCharacterCode]~Flatten~{2}<>""& ``` Accepts a String. Outputs a String. **If list of characters were allowed (46 bytes):** ``` Split[#~SortBy~ToCharacterCode]~Flatten~{2,1}& ``` **Version using `Sort` (40 bytes):** ``` Split@Sort@Characters@#~Flatten~{2}<>""& ``` This version cannot be my answer because `Sort` cannot be used here; `Sort` sorts by canonical order, not by character code. [Answer] # Python 2, ~~77~~ 76 bytes ``` d={} def f(c):d[c]=r=d.get(c,c),;return r print`sorted(input(),key=f)`[2::5] ``` Takes a quoted string as input from stdin. [Try it online!](https://tio.run/nexus/python2#FYxBCsMgEEX3OcWQTRUki0I3Fg/QM4RAgo6pxBox40JKz251@/77rxr1/Q0GLVimuTSzXlRSZtqRmBaai2dCyilAGmJygdbrTISGuRAzMS4OLMrydb5L@VhqHV8WypmhW7DBRe2zd3LzHqhEpzfvC7R6Uz5I7z57d6Ac6x8) [Answer] ## JavaScript (ES6), 79 bytes ``` f=s=>s&&(a=[...new Set(s)]).sort().join``+f(a.reduce((s,e)=>s.replace(e,``),s)) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Works by extracting the set of unique characters, sorting it, removing them from the original string, and recursively calculating the sort of the rest of the string. 81 byte solution that I found interesting: ``` f=s=>s&&(s=[...s].sort().join``).replace(r=/(.)(\1*)/g,"$1")+f(s.replace(r,"$2")) ``` [Answer] ## [J](http://jsoftware.com/), ~~16~~ 15 bytes ``` /:+/@(={:)\;"0] ``` This is a verb that takes and returns one string. [Try it online!](https://tio.run/nexus/j#@5@mYGuloG@lre@gYVttpRljrWQQ@z81OSNfIU1BPTExKSk5JRUI1f8DAA "J โ€“ TIO Nexus") Miles saved a byte, thanks! ## Explanation Nothing too fancy here: sort primarily by order of occurrence, secondarily by char value. ``` /:+/@(={:)\;"0] Input is y. \ Map over prefixes: +/ Sum @( ) of = bit-array of equality {: with last element. This gives an array of integers whose i'th element is k if index i is the k'th occurrence of y[i]. ; Pair this array "0 element-wise ] with y /: and sort y using it as key. ``` [Answer] # [Brainf\*ck](https://github.com/TryItOnline/tio-transpilers), ~~458~~ 226 bytes ``` ,[>>>>>>,]<<<<<<[[-<<<+<<<]>>>[>>>[>>>>>>]<<<[>>--[<->--]<-<[>->+<[>]>[<+>-]<<[<]>-]>>.[[-]<]<<<[[>>>>>>+<<<<<<-]<<<]>>>>>>]>>>[>>>[>>>>>>]<<<[>>--[<->--]<-<[>->+<[>]>[<+>-]<<[<]>-]>>[-<+<+>>]<[->>+<<]<[<<<<<<]>>>]>>>]]<<<<<<] ``` [Try it online! - BF](https://tio.run/nexus/brainfuck#pU/RDoIwDPwcNrca4MnoXPiPpg8GIZLAiA5e/Hm8Df7AJm2ut9612yz7HFZcDmZCNUgBy0ci0jsgETtCFUdoyRtU8eyMB@UYKoLwDBtxWXLIzW6fhrJzcvxjAa40oCBiyuYA@wY5nOX4kGxbf29U1DzNTxXnz6Labhzr6bGDfg2qUa1uTVVfTqq8hvBFS5W2GKnTyK6K2lb2NcSlVdGuYXivHTitbbGGwpYJwQFtIbcf "Brainf*ck โ€“ TIO Nexus") # [Numberwang](https://esolangs.org/wiki/Numberwang_(brainfuck_derivative)), ~~262~~ 226 bytes ``` 8400000087111111442111911170004000400000071114002241202271214020914070419027114170270034427171114400000091111112711170000007000400040000007111400224120227121402091407041902711417027004219190071420091171411111170007000771111117 ``` [Try it online! - NW](https://tio.run/nexus/numberwang#pU/tCsIwDHyctVqhiYWuirD3EH9I3XAwO7TbH19@Xj/ewEDC5Zq7pFtrdI7WUg5jGNUhLVhTE5HeAZkNMaolRsvaoVptyGlQZKBiCI@wsZQlVe6KfRrKzsnxjwW40oGCyHA2BygbbHW29UN224ZLJ6K8vuaHiPNnEb6fJn7dCxjWIDrhpd8TtzuhTyF80R5IKoxwGimqKBWp5xgXL6Jaw/hee3BSqmYNjdIJwQFtczv/AA "Numberwang โ€“ TIO Nexus") I put both of these here because they are identical code. [Answer] # PHP, 83 bytes ``` for($s=count_chars($argv[1]);$s=array_filter($s);$c%=128)echo$s[++$c]--?chr($c):''; ``` Unfortunately you can't have `unset` in a ternary so I need to use the annoyingly long `array_filter`. Use like: ``` php -r "for($s=count_chars($argv[1]);$s=array_filter($s);$c%=128)echo$s[++$c]--?chr($c):'';" "If you sort a string you'll typically get something like:" ``` [Answer] ## Python 2, 70 bytes ``` f=lambda s,i=0,c='':s[i>>7:]and(s.count(c)>i>>7)*c+f(s,i+1,chr(i%128)) ``` [Try it online](https://tio.run/nexus/python2#RU27CoMwFN39iiCUJrWIFkqLoHtnx9IhjUm9NA/JvQ75ehunHjjLeW6mt9K9J8nwDH3T4ROG4dq9pJ841iqsnriaI4dDe7kLMWT3Jk5/pTI8F6tWbOCWEIlhwiKzRk1RqzUiBG/BAfG2yRDF2JcPw1JYGe75fEwR/GdXjtYySgsoaW1iH53XgtM077aFr@7KYslZYoaPYvsB) This is very inefficient. The test link changes the `i>>7` to `i>>5` and sets the recursion limit to 10000. Assumes the inputs only has ASCII values up to 126. Uses the div-mod trick to iterate through two loops: minimum counts `i/128` in the outer loop and ASCII values `i%128` in the inner loop. Includes a character `c` with the given ASCII value if the number of times it appears in the string is at least its minimum count. The code uses a trick to simulate the assignment `c=chr(i%128)` so that it can be referenced in the expression `(s.count(c)>i>>7)*c`. Python `lambda`s do not allow assignment because they only take expressions. Converting to a `def` or full program is still a net loss here. Instead, the function pushes forward the value `chr(i%128)` to the next recursive call as an optional input. This is off by one because `i` has been incremented, but doesn't matter as long as the string doesn't contain special character `'\x7f'` (we could also raise 128 to 256). The initial `c=''` is harmless. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~37~~ 36 bytes Thanks @DJMcMayhem for the byte! ``` ร./&รฒ dd:sor รรฎ รฒรยจ.ยฉยจยฑยซยฉยฑร€!ยจ.ยซยฉ/ยฑยณยฒ ``` [Try it online!](https://tio.run/nexus/v#@3@4V09f7fAmrpQUq@L8Iq7DvYfXcR3edLj30Aq9QysPrTi08dBqIL3xcIMiSATI1gcKbT606f9/zzSFyvxSBaCuEoVEheKSosy8dJCIek6OQkllQWZyYk5OpUJ6aglQSW5qSQZIOiczO9UKAA "V โ€“ TIO Nexus") Not sure I like the regex at the end, but I needed to make the `รฒ` break somehow. ### Explain ``` ร./&รฒ #All chars on their own line dd:sor #Delete empty line, sort chars รรฎ #Join all lines together s/\n// รฒรยจ.ยฉยจยฑยซยฉยฑร€!ยจ.ยซยฉ/ยฑยณยฒ #until breaking s/\v(.)(\1+)\1@!(.+)/\3\2\1 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 3 bytes ``` sฤ โˆฉ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwic8Sg4oipIiwiIiwiSGVsbG8sIFdvcmxkISJd) ``` s # Sort ฤ  # Group run lengths โˆฉ # Transpose # (d flag) take deep sum ``` [Answer] # [Perl 6](http://perl6.org/), 68 bytes ``` {my \a=.comb.sort;[~] flat roundrobin |a.squish.map({grep *eq$_,a})} ``` I was a little surprised to find that there's no built-in way to group like elements in a list. That's what the squish-map bit does. [Answer] # JavaScript (ES6), ~~77~~ 75 bytes ``` s=>(a=[],x={},[...s].sort().map(c=>a[x[c]=n=-~x[c]]=(a[n]||'')+c),a).join`` ``` Stable sorts the lexicographically sorted string by nth occurence ``` F=s=>(a=[],x={},[...s].sort().map(c=>a[x[c]=n=-~x[c]]=(a[n]||'')+c),a).join`` const update = () => { console.clear(); console.log(F(input.value)); }; input.oninput = update; update(); ``` ``` #input { width: 100%; box-sizing: border-box; } ``` ``` <input id="input" type="text" value=" ':Iaaceeefggghiiiiklllllmnnooooprrssstttttuuyyyy" length=99/> <div id="output"></div> ``` [Answer] # [Perl 6](http://perl6.org/), 54 bytes ``` {[~] flat roundrobin |.comb.classify(~*){*}.sortยป[*]} ``` Explanation: * `{ }`: A lambda that takes one argument -- e.g. `21211`. * `.comb`: Split the input argument into a list of characters -- e.g. `(2,1,2,1,1)`. * `.classify(~*)`: Group the characters using string comparison as the grouping condition, returning an unordered Hash -- e.g. `{ 2=>[2,2], 1=>[1,1,1] }`. * `{*}`: Return a list of all values of the Hash -- e.g. `[2,2], [1,1,1]`. * `.sort`: Sort it -- e.g. `[1,1,1], [2,2]`. * `ยป[*]`: Strip the item containers the arrays were wrapped in due to being in the hash, so that they won't be considered as a single item in the following step -- e.g. `(1,1,1), (2,2)`. * `roundrobin |`: Zip the sub-lists until all are exhausted -- e.g. `(1,2), (1,2), (1)`. * `flat`: Flatten the result -- e.g. `1, 2, 1, 2, 1`. * `[~]`: Concatenate it to get a string again -- e.g. `12121`. (Credit for the `roundrobin` approach goes to [Sean's answer](https://codegolf.stackexchange.com/a/106412/14880).) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` {.ยก"รค"ยฉยนgร—ยซรธJยฎK ``` [Try it online!](https://tio.run/nexus/05ab1e#ASkA1v//ey7CoSLDpCLCqcK5Z8OXwqvDuErCrkv//yoqVGVzdCBjYXNlczoqKg) or as a [Test suite](https://tio.run/nexus/05ab1e#JYy7TsMwGIX3PMVPGWIbg@qIAQUhtUxct0odEENwndTCsSG/jWTgPZiRWBASM3PyYMFRt3P5zhnfX@LbUf85G75m/Xdsho/@Z/i76n@v@TgytlLoQVaosGQsu6whugDoOg8VoO@0baYkNwZ8fNKyMiZCo3xCWuW3U230oyqzC2WM47B2ndnsZfu3y9XN8pyDEMfwEL3CrD5bEKR3rduQ6Z7INCjaaifqYMmCSCoPRHHCyLy09jXZQ0F5QooJ2a2QcsG3Gr0kyIPVz0GljFKeB5vz@aTSQ7L5/ek/) **Explanation** ``` { # sort input .ยก # group by equal elements "รค"ยฉ # push "รค" and store a copy in the register ยนgร— # repeat the "รค" input-nr times ยซ # concatenate the result to each string in the grouped input รธ # zip J # join to string ยฎK # remove all instances of "รค" in the string ``` 10 of the 15 bytes are for getting around 05AB1E's way of handling zipping strings of different length. [Answer] # FSharp, ~~194~~ ~~190~~ ~~170~~ ~~140~~ 133 bytes ``` let f=Seq.map let(@)=(>>) f [[emailย protected]](/cdn-cgi/l/email-protection) id@f([[emailย protected]](/cdn-cgi/l/email-protection)((*)128@(+)))@[[emailย protected]](/cdn-cgi/l/email-protection)@f((%)@(|>)128@byte)@Array.ofSeq@f char ``` Using Seq instead of Array saves a couple of bytes Defining a shorter name, and using another maps to avoid a `(fun ->)` block It turns out F# can map a char to an in, so removing the shortened name of System.Text.Encoding.ASCII, and adding in another map saves me 20 bytes! Returning a char array instead of a string, saves me 30 bytes! I no longer need to make sure it's a string, saves me 7 bytes [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ฮฃTgO ``` [Try it online!](https://tio.run/##yygtzv7//9zikHT/////e6YpVOaXKhTnF5UoJCoUlxRl5qWDRNRzchRKKgsykxNzcioV0lNLgEpyU0syQNI5mdmpVgA "Husk โ€“ Try It Online") ## Explanation ``` ฮฃTgO O Order g group T Transpose ฮฃ join ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 71 bytes ``` f=x=>x&&[...x].filter(k=c=>k[c]?![h+=c]:k[c]=1,h='').sort().join``+f(h) ``` [Try it online!](https://tio.run/##FYrdDoIgFIBfhbxQmMXWrRt23TMwNxmBoCdwcGr69BSX38@qvirr5He8hfgypVhxiPFoW8k5PyZuPaBJdBNajJvU0@MiXS/0NFQQ96sTXcd4jgkp42v0YZ57Sx0rOoYcwXCIC7W0eVpyxg@pI1EkY/JhqaYDIHjuXiuAkywG/8vboKsZ/GaGhrHyAw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as a character array, output as a string. ``` รผ ร•c ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&header=cQ&code=/CDVYw&input=IklmIHlvdSBzb3J0IGEgc3RyaW5nIHlvdSdsbCB0eXBpY2FsbHkgZ2V0IHNvbWV0aGluZyBsaWtlOiI) ``` รผ ร•c :Implicit input of character array รผ :Group & sort ร• :Transpose c :Flatten :Implicitly join & output ``` [Answer] # JavaScript (ES6), 114 bytes Separated with newline for clarity, not part of byte count: ``` s=>[...s].map(a=>(m[a]=-~m[a])*128+a.charCodeAt(),m={}) .sort((a,b)=>a-b).map(a=>String.fromCharCode(a%128)).join`` ``` ## Demo ``` `**Test cases:** *:Tacest*es*s* If you sort a string you'll typically get something like: ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt Hello, World! !,HWdelorlol #MATLAB, 114 bytes #,14ABLMTbesty 1A f=@(s)[mod(sort(cell2mat(cellfun(@(c)c+128*(0:nnz(c)-1),mat2cell(sort(s),1,histc(s,unique(s))),'un',0))),128),'']; '()*+,-0128:;=@[]acdefhilmnoqrstuz'(),0128@acefilmnorstu'(),12celmnostu'(),12celnstu(),clnst(),cls(),cs(),()()()()`.split`\n\n`.map(s=>(p=s.split`\n`,console.log(`${p[0]}\n\n${r=f(p[0])}\n\nmatch: ${r==p[1]}`)), f=s=>[...s].map(a=>(m[a]=-~m[a])*128+a.charCodeAt(),m={}).sort((a,b)=>a-b).map(a=>String.fromCharCode(a%128)).join``) ``` [Answer] ## Clojure, 79 bytes ``` #(for[V[(group-by(fn[s]s)%)]i(range 1e9)k(sort(keys V))c[(get(V k)i)]:when c]c) ``` An anonymous function, returns a sequence of characters. Supports up-to 10^9 repetitions of any characters, which should be plenty. [Answer] ## [Retina](https://github.com/m-ender/retina), 24 bytes ``` O`. O$#`(.)(?=(\1)*) $#2 ``` [Try it online!](https://tio.run/nexus/retina#@@@foMflr6KcoKGnqWFvqxFjqKmlyaWibPT/v2eaQmV@qUJxflGJQqJCcUlRZl46SEQ9J0ehpLIgMzkxJ6dSIT21BKgkN7UkAySdk5mdaqUAAA "Retina โ€“ TIO Nexus") [Answer] # Ruby, 59+1 = 60 bytes Adds one byte for the `-n` flag. Port of @PatrickRoberts' dictionary solution. ``` d={};print *$_.chars.sort_by{|c|d[c]||=0;c.ord+128*d[c]+=1} ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 6 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` โˆพยทโŠ’โŠธโŠ”โˆง ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+wrfiipLiirjiipTiiKcKCj7ii4jiiJhGwqgg4p+oCiAgIioqVGVzdCBjYXNlczoqKiIKICAiSWYgeW91IHNvcnQgYSBzdHJpbmcgeW91J2xsIHR5cGljYWxseSBnZXQgc29tZXRoaW5nIGxpa2U6IgogICJIZWxsbywgV29ybGQhIgogICIjTUFUTEFCLCAxMTQgYnl0ZXMiCiAgImY9QChzKVttb2Qoc29ydChjZWxsMm1hdChjZWxsZnVuKEAoYyljKzEyOCooMDpubnooYyktMSksbWF0MmNlbGwoc29ydChzKSwxLGhpc3RjKHMsdW5pcXVlKHMpKSksJ3VuJywwKSkpLDEyOCksJyddOyIK4p+p) sort, group by occurrence count, join. [Answer] # [Factor](https://factorcode.org) + `grouping.extras`, 48 bytes ``` [ natural-sort [ ] group-by values round-robin ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDLTsMwEBTXfsVSDnngoKbiUKVCarkAEiAhijhUObiu01o4dvADERBfwqUX-AD-Br6GTV0kfPHM7Myudt8_K8qcNpufvZu724vrswKsNk6oFayM9g2CI_7sDLVArdXMguWPnivG_6E_h9DQGO5c2xihHIx7rz3A10_TGbcOGLXcFmnaD-pFBa3223FAwTrTDUUlkhKwhWBUyhZW3KGl5m7dlaV44MUuf86l1ATutZHL_Z12cDWdXU5PCeT5MSxax-2uUJ1MYpvMa72Mu4Exw_CwpgFUXsWTmCXsMB-O0nhQKPWCNMsTgpZhZwkpm5CcrIV1LLbEK4H7o5YkJPIqIoMOYQekUTnu994-vKuy0fdgDoo6b6jMtsvOoQzHzRYtPFHp8ZZI1TIzeiEUlCH3VdMGveGWJXDK1qGw2YT_Fw) * `natural-sort` Sort the input * `[ ] group-by values` Group like contiguous elements, e.g. `"aabbc"` -> `{ "aa" "bb" "c" }` * `round-robin` One from each group in order, until there are no elements left. e.g. `{ "aa" "bb" "c" }` -> `"abcab"` ]