text
stringlengths 180
608k
|
---|
[Question]
[
Output this exact text:
```
1 i
12 hi
123 ghi
1234 fghi
12345 efghi
123456 defghi
1234567 cdefghi
12345678 bcdefghi
123456789abcdefghi
12345678 bcdefghi
1234567 cdefghi
123456 defghi
12345 efghi
1234 fghi
123 ghi
12 hi
1 i
```
A single trailing newline is acceptable, but no other formatting changes are allowed.
### Rules and I/O
* No input
* Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# C, ~~87~~ ~~85~~ ~~81~~ 80 bytes
```
j;main(i){for(;++i<19;)for(j=19;j--;)putchar(j?j<i^j<20-i?32:106-j-j/10*39:10);}
```
[Try it online!](https://tio.run/##FchbCoAgEEDR7Wgy5AMCG8OdBCJUM9CDqK9o7WZ/99wMc86lMK6JNkHymfZToFIUjEf5g4daDIDyuK@8pHoiBxo5WA0Une2N7oCBW6Mb56skvqV8 "C (gcc) – Try It Online")
### Explanation
```
j; // same as int j;
main(i){ // same as int main(int i){, where i = argc (1 with no arguments)
for(;++i<19;) // loop over rows, i = 2..18
for(j=19;j--;) // loop over chars, j = 19..0
putchar(j?j<i^j<20-i?32:106-j-j/10*39:10); // output characters:
// j? :10 // on last char (j=0), output \n
// j<i // check for top/left half
// j<20-i // check for bottom/left half
// ^ // 1 if only one half matched
// ?32: // if so, output space
// 106 // char code for j
// -j // get desired letter
// -j/10*39 // subtract 39 for j>9 (numbers)
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
```
i=9
exec"i-=1;a=abs(i);print'123456789'[:9-a]+' '*a+'abcdefghi'[a:];"*17
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWkiu1IjVZKVPX1tA60TYxqVgjU9O6oCgzr0Td0MjYxNTM3MJSPdrKUjcxVltdQUFdK1FbPTEpOSU1LT0jUz060SrWWknL0Pz/fwA "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 64 bytes
```
for(i in abs(8:-8))cat(intToUtf8(c(57-8:i,32*!!-i:i,97+i:8,13)))
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPITGpWMPCStdCUzM5sUQjM68kJD@0JM1CI1nD1FzXwipTx9hIS1FRNxPIsjTXzrSy0DE01tTU/P8fAA "R – Try It Online")
* -3 bytes thanks to @Giuseppe
* -5 bytes thanks to @J.Doe
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 15 bytes
```
A9£Sāì9LÂì×ζRû»
```
[Try it online!](https://tio.run/##ASIA3f8wNWFiMWX//0E5wqNTxIHDrDlMw4LDrMOXzrZSw7vCu/// "05AB1E (legacy) – Try It Online")
-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
# [Python 2](https://docs.python.org/2/), 80 bytes
```
j=i=1
exec"print'123456789'[:i]+' '*(9-i)+'abcdefghi'[-i:];i+=j;j-=2*(i>8);"*17
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8s209aQK7UiNVmpoCgzr0Td0MjYxNTM3MJSPdoqM1ZbXUFBXUvDUjdTU1s9MSk5JTUtPSNTPVo30yrWOlPbNss6S9fWSEsj085C01pJy9D8/38A "Python 2 – Try It Online")
[Answer]
# QBasic, 72 bytes
Based on [Taylor Scott's submission](https://codegolf.stackexchange.com/a/167477/16766).
```
FOR y=-8TO 8
z=ABS(y)
?"123456789abcdefghi";
LOCATE,10-z
?SPC(2*z)"
NEXT
```
### Basic explanation
On each line, we print the full string `123456789abcdefghi`. Then we *go back* and overwrite part of it with spaces.
### Full explanation
With code slightly ungolfed:
```
FOR y = -8 TO 8 ' Loop for 17 rows
z = ABS(y) ' z runs from 8 to 0 and back to 8
? "123456789abcdefghi"; ' Print the full string and stay on the same line (important!)
LOCATE , 10-z ' Go back to column 10-z on that line
? SPC(2*z); "" ' Print 2*z spaces
' (SPC keeps the cursor on the same line unlesss you print
' something after it, so we'll use the empty string)
NEXT ' Go to the next y value
```
[Answer]
# T-SQL, 108 bytes
```
DECLARE @ INT=8a:
PRINT STUFF('123456789abcdefghi',10-abs(@),2*abs(@),SPACE(2*abs(@)))
SET @-=1IF @>-9GOTO a
```
Returns are for readability only.
Tried lots of other variations, including number tables, this was the shortest.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
9LJη.BA9£.sí.Bí)øJû»
```
[Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//zlMSs63LkJBOcKjLnPDrS5Cw60pw7hKw7vCu/// "05AB1E – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
9R[]z9m±[]±+─
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE5JXVGRjMyJXVGRjNCJXVGRjNEJXVGRjVBJXVGRjE5JXVGRjREJUIxJXVGRjNCJXVGRjNEJUIxJXVGRjBCJXUyNTAw,v=3)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
```
9Æ9Ç>YÃê1 Ë?S:°EsH
ê
```
[Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.5&code=OcY5xz5Zw+oxIMs/UzqwRXNICuo=&input=LVI=)
Output as an array of arrays of characters. The `-R` flag isn't necessary to work, it just makes the output look nicer.
Explanation:
```
9Æ9Ç create a 9x9 2D array
>YÃ fill bottom left triangle with "false", upper right with "true"
ê1 mirror horizontally
Ë?S replaces "true" with a space
:°EsH replaces "false" with the horizontal index + 1 converted to base 32
\n Store the result in U (saves bytes by not closing braces)
ê palindromize vertically
```
[Answer]
# PowerShell 5.1, ~~70~~ ~~69~~ ~~64~~ 57 Bytes
Thanks Mazzy for -7 bytes
```
1..9+8..1|%{-join(1..$_+' '*(9-$_)+' ihgfedcba'[$_..1])}
```
Turns out gluing it together manually saves a byte. Making it all one mega-join also saves 5 more. ~~Also works by turning a range of ints into a char[] to get the a-i.~~ Using a range over the actual letters is 5 bytes better.
[Answer]
# [Julia 1.0](http://julialang.org/), 73 bytes
```
[1:9;8:-1:1].|>i->println(join(1:9)[1:i]*" "^(18-2i)*"abcdefghi"[10-i:9])
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P9rQytLawkrX0MowVq/GLlPXrqAoM68kJ08jKz8zTwMoqwlUkhmrpaSgFKdhaKFrlKmppZSYlJySmpaekakUbWigm2llGav5/z8A "Julia 1.0 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 47 bytes
```
9l$lRtH2$PhO18Y"yPvv1=49:57 97:105h19T3$X"32b(c
```
[Try it online!](https://tio.run/##y00syfn/3zJHJSeoxMNIJSDD39AiUqkyoKzM0NbE0srUXMHS3MrQwDTD0DLEWCVCydgoSSP5/38A "MATL – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes
```
9ʀṘǔmkrf*ꜝøṗ↵§
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI5yoDhuZjHlG1rcmYq6pydw7jhuZfihrXCpyIsIiIsIiJd)
**Explanation**
A transposition approach.
```
9ʀ # range from 0 to 9 inclusive
Ṙ # reversed
ǔ # rotated right (last item goes to first)
m # and concatenated with its reverse
kr # string of digits, lowercase alphabet, and uppercase alphabet
f # into a list of characters
* # repeat (vectorises)
ꜝ # remove empty strings in the list
øṗ # palindromise each item, center, and join by newlines
↵ # split on newlines
§ # vertically join
```
[Answer]
# Japt, ~~24~~ 19 bytes
Returns an array of lines
```
9õ Ôê1 Ëç°TsH)êÃû y
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=OfUg1OoxIMvnsFRzSCnqw/sgeQ&input=LVI)
```
9õ Ôê1 Ëç°TsH)êÃû y
9õ :Range [1,9]
Ô :Reverse
ê1 :Mirror
Ë :Map
ç : Repeat
°T : Prefix increment T (initially 0)
s : Convert to base
H : 32
) : End repeat
ê : Palindromise
à :End map
û :Centre pad each with spaces to the length of the longest
y :Transpose
```
([It did indeed, 4 year ago Shaggy, it did indeed](https://codegolf.stackexchange.com/questions/167405/alpha-numerical-bowtie/254376#comment404603_167407)!)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
â4+╤jo♂▐▀3bkWíæß╝╖
```
[Run and debug it](https://staxlang.xyz/#p=83342bd16a6f0bdedf33626b57a191e1bcb7&i=&a=1)
Explanation:
```
9R$|[|<Va17T|]r|>\|pm Full program
9R$ Produce "123456789"
|[|< Left-aligned prefixes (["1 ", "12 ", ...])
Va17T Produce "abcdefghi"
|] Suffixes (["abcdefghi", "bcdefghi", ...])
r|> Reverse and left-align ([" i", " hi", ...])
\ Zip both arrays (["1 i", "12 hi", ...])
|p Palindromize array
m Map over array, printing each with a newline
```
[Answer]
# JavaScript (ES6), 76 bytes
```
f=(x=y=0)=>y<17?(x>y^x++<17-y?x.toString(36)+[`
`[x%=18]]:' ')+f(x||!++y):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajwrbS1kDT1q7SxtDcXqPCrjKuQlsbyNattK/QK8kPLinKzEvXMDbT1I5O4EqIrlC1NbSIjbVSV1DX1E7TqKipUdTWrtS0Ulf/n5yfV5yfk6qXk5@ukaahqfkfAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 bytes
```
(⊢⍪1↓⊖)(↑,\1↓⎕d),⌽↑,\⌽819⌶9↑⎕a
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9/b/Go65Fj3pXGT5qm/yoa5qmxqO2iToxYF7f1BRNnUc9e8EiQNrC0PJRzzZLIBcolQjS/T8dAA "APL (Dyalog Unicode) – Try It Online")
`↑` convert to a matrix (auto pads with spaces)
* `,\` the prefixes of
* `1↓` the first element dropped from
* `⎕d` this string `'0123456789'`
* This gives the character matrix
```
1
12
123
1234
12345
123456
1234567
12345678
123456789
```
`,` concatenated with
* `⌽` the reversed
* `↑` matrixified
* `,\` prefixes of
* `⌽` the reversed
* `819⌶` and lowercased
* `9↑` first 9 elements of
* `⎕a` this string `'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
* This gives the character matrix
```
i
hi
ghi
fghi
efghi
defghi
cdefghi
bcdefghi
abcdefghi
```
and on this result
```
1 i
12 hi
123 ghi
1234 fghi
12345 efghi
123456 defghi
1234567 cdefghi
12345678 bcdefghi
123456789abcdefghi
```
perform the following train `(⊢⍪1↓⊖)`
`⊢` the right argument
`⍪` concatenated vertically with
`1↓` the first row dropped from (this avoids the repeating of the middle row)
`⊖` the right argument reversed vertically
---
Other solutions
### 33 bytes
```
(⊢⍪1↓⊖)(↑,\⍕¨q),⌽↑,\⎕ucs 106-q←⍳9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9/b/Go65Fj3pXGT5qm/yoa5qmxqO2iToxj3qnHlpRqKnzqGcvhN83tTS5WMHQwEy38FHbhEe9my1Buv@nAwA "APL (Dyalog Unicode) – Try It Online")
### 33 bytes
```
(⊢⍪1↓⊖)(↑,\⍕¨q),⌽↑,\⌽⎕ucs 96+q←⍳9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9/b/Go65Fj3pXGT5qm/yoa5qmxqO2iToxj3qnHlpRqKnzqGcvhA@k@6aWJhcrWJppFz5qm/Cod7MlSP//dAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 17 bytes
```
G↗↓←⁹β←G↖↓⁹⭆χι‖O↓
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pwyq0ICgzPaNER8HKJb88D0j5pKYBeZY6Ckma1ly@@WWpGmAhIAdJD0QRVAtQbXBJUWZeum9igYahgY5CpiZQdVBqWk5qcol/WWpRDlAcrFbT@v///7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
G↗↓←⁹β
```
Draw a lower right triangle and fill it using the lowercase alphabet. (The fill is based on tiling the plane with the alphabet and then copying the drawn area.)
```
←
```
Move left to draw the numeric triangle.
```
G↖↓⁹⭆χι
```
Draw a lower left triangle and fill it using the digits. (Since the triangle is drawn to the left of the origin, the digits are taken right-justified, so only the digits 1 to 9 get used.)
```
‖O↓
```
Reflect to complete the bottom half.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~25~~, 21 bytes
```
¬19¬ai8ñHÄ/á
r ge.YGp
```
[Try it online!](https://tio.run/##K/v//9AaQ8tDaxIzLQ5v9Djcon94IVeRQnqqXqR7wf//AA "V – Try It Online")
2-4 bytes saved thanks to nmjcman101!
Hexdump:
```
00000000: ac31 39ac 6169 38f1 48c4 2fe1 0a72 2067 .19.ai8.H./..r g
00000010: 652e 5947 70 e.YGp
```
[Answer]
# [J](http://jsoftware.com/), 44 bytes
```
(m]\u:49+i.9),.(m=.,}.@|.)]\&.(|."1)u:97+i.9
```
[Try it online!](https://tio.run/##y/r/PzU5I18jNzam1MrEUjtTz1JTR08j11ZPp1bPoUZPMzZGTU@jRk/JULPUytIcJP//PwA "J – Try It Online")
I tried to generate numerically a mask of 1 and zero to use for indexing, but the cost of getting rid of the extra row was high and I gave up:
```
(9-.~i.18){0<:-/~(,|.)i.9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
1 1 1 1 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 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1
1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1
1 1 1 1 1 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 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
1 1 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 1
```
[Answer]
## [Perl 5](https://www.perl.org/) + `-M5.010`, 49 bytes
```
say 1..9-abs," "x abs,(a..i)[-9+abs..-1]for-8..8
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLBUE/PUjcxqVhHSUFBqUIBxNJI1NPL1IzWtdQG8vT0dA1j0/KLdC309Cz@//@XX1CSmZ9X/F/X11TPwNAAAA "Perl 5 – Try It Online")
[Answer]
# [QBasic](https://archive.org/details/msdos_qbasic_megapack "QBasic Emulator"), 87 bytes
An anonymous function that takes no input and outputs to the console.
```
For y=-8To 8:z=Abs(y):a$="123456789abcdefghi":?Mid$(a$,1,9-z)Spc(2*z)Mid$(a$,10+z):Next
```
This answer is technically a polyglot, and will function in VBA
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 314 308 bytes
```
<p0+3*67p0+4*77p0+3*77p0-7*88p0-6*88"#v#v>"
"i "11g1-21p56+1g1+56+1p28*1g1+28*1p ^ >25*
" 1"92g1+82p56+2g1-56+2p28*2g1-28*2p91g00g`#v_^ >
"ihgfedcba "93p26*3g1-26*3p">^"88*7-0p88*7-4pv >25*
"987654321 "14p26*4g1+26*4p26*4g12g`#v_ ^
>:#,_@#:<
```
[Try it online!](https://tio.run/##fY7BDoIwEETvfEWzvRWb0FLaQkjjl4CiWL2Yvcjv4y7BhJNzedNkprPT/Pi887yuPVZlrXwgOBXC9mLooGIkeALIRS4JCniJXWBMNtoabHxJrmSgjYo9A4UY9miyjSrgVzTQWspEy01ymsFN9gxsTa6qfJHLyD8kGn3mx3y/TVcBbY3Wq5qjBIQ0QIwq6Ao3OFwOk20MvnG1NXSt457j4wi7t9uIOGgoxD@lTp7Gs@z6df0C "Befunge-93 – Try It Online")
Golfed 6 bytes by placing a `>` with the `p` instruction
[Answer]
## Matlab, 122 bytes
```
function[r]=f,s=[49:57,'a':'i'];r=[];for i=1:9,r=[r;s(1:i),repmat(' ',[1,18-2*i]),s(19-i:18)];end,r=[r;flip(r(1:8,:))];end
```
[Try it Online!](https://tio.run/##JctBCsMgEEDRq2SnlsnC0lId8STiQlKFgVbDxPT6Vsjy8/ht6@mXxyhn3Tq1Gjj6AocPD4vPF4gkUJCIjn2IrjReyGu0MJPdITWSAs77N3UpFgFBgzbr/UZRwVS7Emqjosv1fS3lQ7vk@RlAdcEoUo0/)
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 956 bytes
```
{iiiii}dc{dd}iii{c}cccccc{{i}ddd}iiic{{d}i}dddddc{iiii}dcic{dd}ii{c}cccc{{i}ddd}iicic{{d}i}dddddc{iiii}dcicic{dd}i{c}cc{{i}ddd}icicic{{d}i}dddddc{iiii}dcicicic{dd}{c}{{i}ddd}cicicic{{d}i}dddddc{iiii}dcicicicic{dd}dcccccccc{{i}ddd}dcicicicic{{d}i}dddddc{iiii}dcicicicicic{dd}ddcccccc{{i}ddd}ddcicicicicic{{d}i}dddddc{iiii}dcicicicicicic{dd}dddcccc{{i}ddd}dddcicicicicicic{{d}i}dddddc{iiii}dcicicicicicicic{dd}ddddcc{iiiiii}iiiiiicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicicicic{iiii}cicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicicic{dd}ddddcc{iiiiii}iiiiiicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicic{dd}dddcccc{{i}ddd}dddcicicicicicic{{d}i}dddddc{iiii}dcicicicicic{dd}ddcccccc{{i}ddd}ddcicicicicic{{d}i}dddddc{iiii}dcicicicic{dd}dcccccccc{{i}ddd}dcicicicic{{d}i}dddddc{iiii}dcicicic{dd}{c}{{i}ddd}cicicic{{d}i}dddddc{iiii}dcicic{dd}i{c}cc{{i}ddd}icicic{{d}i}dddddc{iiii}dcic{dd}ii{c}cccc{{i}ddd}iicic{{d}i}dddddc{iiii}dc{dd}iii{c}cccccc{{i}ddd}iiic
```
[Try it online!](https://tio.run/##rZNBDoQgDEVPNIcy/zuZrmfZcHam2uoIiRBUNkB970elcJ74lu/nlbPKMhKhZLKVImEdqlb1mq1tXnY0LngJI4Q/jjM@jFXYcbR4N0zYcPR4NwiUH3F43FBDZuUWQFPfAlj6FdKJ2EMsxU9Hkk811g2SqGNcfegdbv@PWydyuRfG2m6srceuTeta5vwD "Deadfish~ – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 119 bytes
```
import Data.Char
main=putStr$do i<-[-8..8];[chr$if abs j>abs i then j+96-fromEnum(j<0)*38else 32|j<-[-9..9],j/=0]++"\n"
```
[Try it online!](https://tio.run/##Fcw9DsIgGADQ3VN8aTqoCDY2MRBbF/UEjpUBKw0gPw3QzbtjurzxKZG@0tpStJtDzHAXWZCbEnHjhPb9vORnjvUngO7wgCkhlF@GUcVaTyDeCcx1VUNW0oNB7IynGNzDL25ruma3b6m0SUJ7@pk1YIQwfjDHvuEIVS9flfIH "Haskell – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 54 bytes
```
[8:-1:1;0:8].|>i->print.([1:9-i;" "^2i;'a'+i:'i';"
"])
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P9rCStfQytDawMoiVq/GLlPXrqAoM69ETyPa0MpSN9NaSUEpzijTWj1RXTvTSj1T3VqJSylW8/9/AA "Julia 1.0 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~81~~ 79 bytes
```
a=Table[" ",17,18];Do[a[[i;;-i,i]]=a[[1-i;;i-1,i]]=i~IntegerString~35,{i,18}];a
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1iamVoSzcVVUJSfbqvxP9E2JDEpJzVaSUFJx9Bcx9Ai1tolPzoxOjrT2lo3UyczNtYWyDHUBXIzdQ3B/Mw6z7yS1PTUouCSosy89DpjU53qTKDO2ljrxP@a1lxcAUDhEgcHB5AVXFyx/wE "Wolfram Language (Mathematica) – Try It Online")
Throws a lot of ignorable errors.
[Answer]
# VBA, 75 bytes
An anonymous VBE immediate window function that takes no input and outputs to the console.
```
For y=-8To 8:z=Abs(y):a="123456789abcdefghi":Mid(a,10-z)=Space(2*z):?a:Next
```
] |
[Question]
[
Inspired by Silicon Valley's "three-comma club" scenes, like [this one](https://www.youtube.com/watch?v=rIB5HEcZBs8), in this challenge you'll be telling ten people the "comma club" to which they each belong.
If you're unfamiliar with the term "comma club," let me explain: you're in the one-comma club if the money you have is in the inclusive range $1,000.00 to $999,999.99; you're in the two-comma club if it's in the range $1,000,000.00 to $999,999,999.99; these "clubs" repeat through the three-comma club, since no individual on Earth (AFAIK) owns more than one trillion U.S. dollars (Japanese Yen would be a different story very quickly). So, the number of commas your bank account has, according to the notation standards most common in the United States and Great Britain, denotes the comma club to which you belong. The same "comma" rules apply for negative numbers (although you wouldn't want to be in the negative comma club): negative amounts in the inclusive range [-0.01, -999.99] belong to the zero-comma club, amounts in the range [-1000.00, -999999.99] belong to the one-comma club, etc.
# The test cases
```
Friend Amount
John 100000
Jamie 0.05
Kylie 1549001.10
Laura 999999999.99
Russ 986000000
Karla 1
Reid 99.99
Mark 999.99
Manson 1000.01
Lonnie 999999999999.00
Nelly -123.45
```
The right answers:
```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
```
Whatever array setup you need to get a `friends` array and `amounts` array does not count towards your score. So for Python, the following code doesn't count:
```
f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = ['100000', '0.05', '1549001.10', '999999999.99', '986000000', '1', '99.99', '999.99', '1000.01', '999999999999.00']
```
### Edit: Please see the revised test cases
I removed the actual string commas from the test cases to make things a bit more difficult, as opposed to just counting commas.
[Answer]
## JavaScript (ES6), 80 bytes
```
a=>a.map(([s,n])=>s+` is in the ${n.toFixed(n<0?3:4).length/3-2|0}-comma club.`)
```
Takes an array of [friend, amount] arrays and returns an array of "friend is in the n-comma club." strings. Works by adding extra trailing zeros so that the length is 6-8 for the 0-comma club, 9-11 for the 1-comma club, 12-15 for the 2-comma club etc.
<https://jsfiddle.net/cau40vmk/1/>
[Answer]
# PostgreSQL, 61 bytes
```
SELECT f||' is in the '||div(log(@a),3)||'-comma club.'FROM p
```
`@x` is the absolute value of `x`, `log(x)` is base-10 logarithm and `div(y, x)` computes the integer quotient of y/x.
---
Setup:
```
CREATE TEMP TABLE p AS
SELECT * FROM (VALUES
('John', 100000),
('Jamie', 0.05),
('Kylie', 1549001.10),
('Laura', 999999999.99),
('Russ', 986000000),
('Karla', 1),
('Reid', 99.99),
('Mark', 999.99),
('Manson', 1000.01),
('Lonnie', 999999999999.00),
('Nelly', -123.45)
) AS p (f, a)
```
---
Output:
```
?column?
--------------------------------
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
(11 rows)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34 32~~ 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»j)⁹żY
```
A dyadic link (function) which takes a list of bank balances as numbers (decimals / integers) and a list of names as strings and returns a list of strings.
**[Try it online!](https://tio.run/##y0rNyan8/9/x4Y55SSe2@zxqmPmocZv1o4Y5hxY/3Dnz2JriR437Eg6tebh76cOdTSDhRTYPd285sczi0OKcQ7uzNB817jy65//h5ZH//0cbGoCAjoKBnoGpjoKhqYmlgYGhniFQxBIG9CwtgTIGMABkgyTBosiyegaGSJpAMiC1uoZGxnomQKN14YbF/o9W98rPyFPXUVD3SszNTAUxvCtzIAyfxNKiRBAjqLS4GCyTWJQDEUjNTAHRvolF2RA6rzgfbIpPfl4eRLcfKGggjPT0SvVYAA "Jelly – Try It Online")** - the footer `çY`simply calls the function and joins the resulting list with line feeds so it has nice output when run as a full program.
### How?
```
AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»j)⁹ż - Main link: bankBalances, names
) - for each bankBalance:
A - absolute value (treat negatives and positives the same)
Ḟ - floor (get rid of any pennies)
bȷ - convert to base 1000
L - length (number of digits in base 1000)
’ - decrement by one
⁶; - concatenate a space with that ...because -------.
“ “ » - compressed list of strings: ↓
£ṙƬs⁾`¬ụṂ - " is in the" ← cannot compress a trailing space :(
¢<ỴȦ8£l - "-comma club."
j - join that list of strings with the "number plus space"
⁹ - right argument (names)
ż - zip with L
```
[Answer]
# PHP, ~~76~~ 74 bytes
```
// data as associative array
$d=[Poorman=>-1234,John=>100000,Jamie=>0.05,Kylie=>1549001.10,Laura=>999999999.99,Russ=>1000000000,Karla=>1,Reid=>99.99,Mark=>999.99,Manson=>1000.01,Lonnie=>999999999999.00];
// code
foreach($d as$n=>$a)printf("$n is in the %d-comma club.
",log($a*$a,1e6));
```
Fortunately I don´t have to cast to int (as I would have to in C); PHP does that implicitly for `%d`.
[Answer]
# Mathematica (86 bytes)
The set-up (with names as strings, money as numbers):
```
n = {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
m = {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45}
```
The attempt:
```
MapThread[#~~" is in the "~~ToString@Max[Floor@Log[10^3,#2],0]~~"-comma club."&,{n,m}]
```
All of Mathematica's string functions include "String" in the name, so I think logs are shorter. The `Max[...,0]` is to deal with the pesky negative numbers or negative infinity for people who own between -1 and 1 dollars. The log of a negative number includes imaginary stuff, but Mathematica helpfully ignores that when taking a `Floor`!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 36 bytes
This takes in the amount as the first input, name as the second.
```
V+` e {w0 x4 l /3-2|0}-¬mµ club
```
### Explanation
```
V+` e {w0 x4 l /3-2|0}-¬mµ club
V+ // Second input +
` // compressed string:
e // " is in the "
{ } // Insert here:
w0 // The larger of 0 and the first input
x4 // Rounded to the 4th decimal
l // Length
-¬mµ club // "-comma club"
// A closing backtick is auto-inserted at the end of the program
```
Japt uses the [shoco library](http://ed-von-schleck.github.io/shoco/) for string compression.
*Inspired by @Neil's [solution](https://codegolf.stackexchange.com/a/111745/61613).*
*Saved 7 bytes thanks to @ETHproductions*
[Try it online!](https://tio.run/nexus/japt#@x@mnaBwqFPhUIfCoQmpCtXlBgoVJgo5CvrGukY1BrW6h9bkHtqqkJxTmvT/v6EBCOgoeeVn5CkBAA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 32 bytes
```
Äï€g3/î<“-comma†Ú“«“€ˆ€†€€ “ì‚ø»
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@45fD6R01r0o31D6@zedQwRzc5Pzc38VHDgsOzgLxDq4EEUPp0G5AACoLIpjUKQMHDQO6swzsO7f7/P1rd0AAE1HUU1A30DExBtKGpiaWBgaGeIVjUEgb0LC3BsgYwAOZBlEDlUFXpGRiiGACShejSNTQy1jMxVY/lilb3ys/IA4l5JeZmpoIY3pU5EIZPYmlRIogRVFpcDJZJLMqBCKRmpoBo38SibAidV5wPNsUnPy8PotsvNSenUj0WAA "05AB1E – TIO Nexus")
**Explanation**
```
Ä # absolute value of input
ï # convert to int
€g # length of each
3/ # divided by 3
î # round up
< # decrement
“-comma†Ú“« # append string "-comma club" to each number
“€ˆ€†€€ “ì # prepend string "is in the " to each number
‚ # pair with second input
ø # zip
» # join by spaces and newlines
```
[Answer]
# R, 68 bytes
The setup:
```
f <- c('John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly')
a <- c(100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45)
```
The solution:
```
cat(paste0(f, " is in the ",floor(log10(abs(a))/3)),"-comma club.\n"))
```
Take the base 10 log of the absolute value of the account, round down then print with the names.
I'm not sure if it could be smaller if `a` would be a character vector...
[Answer]
## JavaScript, 59 bytes
*Saved 3 bytes thanks to @ETHproductions*
*Saved 2 bytes thanks to @Cyoce*
```
n=>m=>n+` is in the ${m>1?Math.log10(m)/3|0:0}-comma club.`
```
### Demo
```
f=n=>m=>n+` is in the ${m>1?Math.log10(m)/3|0:0}-comma club.`
console.log((f("John")(100000)))
console.log((f("Jamie")(0.05)))
console.log((f("Kylie")(1549001.10)))
console.log((f("Laura")(999999999.99)))
console.log((f("Russ")(986000000)))
console.log((f("Karla")(1)))
console.log((f("Reid")(99.99)))
console.log((f("Mark")(999.99)))
console.log((f("Manson")(1000.01)))
console.log((f("Lonnie")(999999999999.00)))
console.log((f("Nelly")(-123.45)))
```
[Answer]
# MATL, ~~50~~ ~~48~~ 43 bytes
```
`j' is in the 'i|kVn3/XkqV'-comma club'&hDT
```
Try it at [**MATL Online**](https://matl.io/?code=%60j%27+is+in+the+%27i%7CkVn3%2FXkqV%27-comma+club%27%26hDT&inputs=John%0A1000.05%0AJamie%0A0.05%0AKylie%0A1549001.10%0ALaura%0A999999999.99%0ARuss%0A1000000000%0AKarla%0A1%0AReid%0A99.99%0AMark%0A999.99%0AManson%0A1000.01%0ALonnie%0A999999999999.00%0ANelly%0A-123.45&version=19.8.0)
**Explanation**
```
` % Do...While loop
j % Explicitly grab the next input as a string
' is in the the ' % Push this string literal to the stack
i % Grab the next input as a number
| % Compute the absolute value
k % Round towards zero
V % Convert to a string
n3/Xk % Divide the length of the string by 3 and round up
q % Subtract one
V % Convert to a string
'-comma club' % Push this string literal to the stack
&h % Horizontally concatenate the entire stack
D % Display the resulting string
T % Push TRUE to the stack, causing an infinite loop which automatically
% terminates when we run out of inputs
% Implicit end of do...while loop
```
[Answer]
# Vim, 72 bytes
```
:%s;\v +\-=(\d+).*;\=' is in the '.(len(submatch(1))-1)/3.' comma club'
```
Somehow I should show that there's a trailing return, but unsure how. This is just a basic regex answer, that I'm sure could be beaten by any regex language. I would have used V, but I think that the substitute commands in V use `/` as a separator by default, and I couldn't figure out how to make it not complain about the divide.
Takes input as OP's table, and returns values as the table, but with the financial information replaced by " is in the X comma club"
[Try it online!](https://tio.run/nexus/v#TY5BDoIwEEX3PcVsDKBh7KgsKvECii5YsynQBGIpCQUTT49SIOHt/s/8lxmvOxtnHzhk4c3PykOA@zi7eVBbqA30lQIPfa2Mb4e8kX1R@RQEIQXHM3pQtE0jodBD7rFxvLeVAQfxCXaXTa1cwZFH7PHVS6ToIjgnJM4SOXTSlWIFhWDpYO3W5XwP2en5lliq6hKW3TR4yu695qUwtjWrATmxpDVmfkBswL/4pbT@unFIpzNeoh8 "V – TIO Nexus")
[Answer]
# Python 3 (~~207 159 110 95~~ 86 bytes, thanks to @iwaseatenbyagrue)
A little bit of setup:
```
f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly']
a = [100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45]
```
My attempt:
```
['%s is in the %d-comma club.'%(p,-(-len(str(int(abs(v))))//3)-1) for p,v in zip(f,a)]
```
Results:
```
['John is in the 1-comma club.', 'Jamie is in the 0-comma club.', 'Kylie is in the 2-comma club.', 'Laura is in the 2-comma club.', 'Russ is in the 2-comma club.', 'Karla is in the 0-comma club.', 'Reid is in the 0-comma club.', 'Mark is in the 0-comma club.', 'Manson is in the 1-comma club.', 'Lonnie is in the 3-comma club.', 'Nelly is in the 0-comma club.']
```
Edit: converting everything to absolute values saved me 15 bytes.
[Answer]
# Python 2, 69 bytes
Setup our arrays:
```
n = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = [100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00]
```
And our function can then be:
```
f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(a)))/3)))
```
Giving us:
```
>>> [f(x,y) for x,y in zip(n,a)]
['John is in 2 comma club', 'Jamie is in 0 comma club', 'Kylie is in 2 comma club', 'Laura is in 3 comma club', 'Russ is in 3 comma club', 'Karla is in 0 comma club', 'Reid is in 0 comma club', 'Mark is in 1 comma club', 'Manson is in 1 comma club', 'Lonnie is in 3 comma club']
```
If the array needs to be identical to that provided in the question, then the solution costs 76 bytes:
```
f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(float(a))))/3)))
```
[Answer]
## Powershell, 82 bytes
```
$args[0]|%{$_[0]+" is in the "+(('{0:N}'-f$_[1]-split',').Count-1)+"-comma club."}
```
Assuming a 2D-array input of
`cc.ps1 @(@("John",100000),@("Jamie",0.05),@("Kylie",1549001.10),@("Laura",999999999.99),@("Russ",986000000),@("Karla",1),@("Reid",99.99),@("Mark",999.99),@("Manson",1000.01),@("Lonnie",999999999999.00),@("Nelly",-123.45))`
The output is
`John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.`
[Answer]
## Haskell, 71 bytes
```
n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."
```
Defines an operator '#' that provides the correct answer. E.g.:
```
*Main> "John"#100000
"John is in the 1-comma club."
```
Unfortunately, Haskell doesn't have a compact `log10` function like many other languages, but it does have a useful `logBase` function, which means we don't need to divide our answer by 3. Unfortunately, `logBase 1000 0.05` is a negative number, so we need to use the longer `truncate` rather than `floor` to round it.
Full program including test cases:
```
(#) :: (RealFrac n, Floating n) => [Char] -> n -> [Char]
n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."
testCases = [
("John", 100000),
("Jamie", 0.05),
("Kylie", 1549001.10),
("Laura", 999999999.99),
("Russ", 986000000),
("Karla", 1),
("Reid", 99.99),
("Mark", 999.99),
("Manson", 1000.01),
("Lonnie", 999999999999.00),
("Nelly", -123.45)]
main = putStrLn $ unlines $ map (uncurry (#)) testCases
```
Gives the following results:
```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
```
[Answer]
# [Python 2.7](https://docs.python.org/2/), ~~89 86 84~~ 76 bytes
```
for g,b in input():print g,'is in the',`~-len('%d'%abs(b))/3`+'-comma club.'
```
**[Try it online!](https://tio.run/##TY7NEoIgHMRfhYuDTkpgeaBH6OvQ1WlGLFMmBAf04KVXN8TUdjj9/rvLNn1bKRkPw0tpUIY54NK@pmv94NBoLlsLITcjbqsChtknEoX0ofeEHsuNnwfBdpdtYPRQdc3AQ3Q5gsOQpvCoKglDQPCoewgsYTW3FQAjnDhw6oUDJNlTjAkik@/MOs0sprMQpe5w64xZKpfaE9NitJPJU/Cny86hC9PvqWwl0qh5G8JT7qykdGPon9Dvi2shRG9vEYl3aJ/8WFk6tm68fwE)**
Full program that takes a list of pairs of names and bank balances - and prints the resulting strings. (Note the question states "friends array and amounts array, but this is the format used by the accepted answer, so I guess it's allowed!)
[Answer]
## K, 66 bytes
```
/n is names and a is amounts
n
("John";"Jamie";"Kylie";"Laura";"Russ";"Karla";"Reid";"Mark";"Manson";"Lonnie")
a
("100000";"0.05";"1549001.10";"999999999.99";"1000000000";,"1";"99.99";"999.99";"1000.01";"999999999999.00")
/the function
{x," is in the ",($(#.q.cut[3;*"."\:y])-1)," comma club"}./:+(n;a)
/output
("John is in the 1 comma club";"Jamie is in the 0 comma club";"Kylie is in the 2 comma club";"Laura is in the 2 comma club";"Russ is in the 3 comma club";"Karla is in the 0 comma club";"Reid is in the 0 comma club";"Mark is in the 0 comma club";"Manson is in the 1 comma club";"Lonnie is in the 3 comma club")
```
[Answer]
# C#, 125 bytes
```
(p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};
```
Anonymous function which prints the result in the the OP's format.
Full program with test cases:
```
using System;
class CommaClub
{
static void Main()
{
Action<string[], double[]> f =
(p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};
// test cases:
string[] personArr = new[] {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
double[] amountArr = new[] {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45};
f(personArr, amountArr);
}
}
```
[Answer]
# Perl 6, ~~107~~ 95 bytes
```
for @f {printf "%s is in the %d-comma club.\n",@f[$++],(abs(@a[$++].split(".")[0]).chars-1)/3;}
```
Not my proudest work, give me a heads up if ive forgotten any golfing techniques.
EDIT: -12 bytes thanks to @Ven
[Answer]
## Python 2, 87 bytes
```
for n,a in input():print n+' is in the %dd-comma club.'%'{:20,.2f}'.format(a).count(',')
```
Slightly older (90 bytes):
```
for n,a in input():print n+' is in the '+`'{:20,.2f}'.format(a).count(',')`+'-comma club.'
```
Takes input as a list of tuples (name, amount).
I'm doing this on my phone at school so I'll test it later.
[Answer]
## dc, ~~56~~ 54 bytes
```
[P[ is in the ]Pd*vdZrX-1-3/n[-comma club.]pstz0<g]sglgx
```
This takes input from the stack, which should be pre-loaded with the first name at top of stack, the first number, the second name, second number, etc.
Here is an example of loading the stack and running the macro, g:
```
#!/usr/bin/dc
_123.45 [Nelly]
999999999999.00 [Lonnie]
1000.01 [Manson]
999.99 [Mark]
99.99 [Reid]
1 [Karla]
986000000 [Russ]
999999999.99 [Laura]
1549001.10 [Kylie]
0.05 [Jamie]
100000 [John]
[P[ is in the ]Pd*v1/Z1-3/n[-comma club.]pstz0<g]sglgx
```
which produces the usual output,
```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
```
Here's an exegesis of the code:
```
[P[ is in the ]Pd*v1/Z-1-3/n[-comma club.]pstz0<g]sglgx
[ # begin macro string
P # print and pop person name
[ is in the ]P # print and pop ' is in the '
# Get absolute value of number by squaring and square root
d*v # d=dup, *=multiply, v=root
1/ # 1/ truncates to integer since scale is 0
Z # Z=number length
1-3/n # n=print and pop (#digits - 1)//3
[-comma club.]p # print '-comma club.' and newline
st # pop '-comma club.' off stack into register t
z0<g # Do macro g if 0 is less than z=stack height
] # end macro string
sg # Save macro g
lgx # Load g and do its initial execution
```
Note, in edit 1 I replaced `dZrX-` (d=dup, Z=number length, r=swap, X=fraction, -=subtract) with `1/Z` (divide number by 1, which with default scale of zero truncates to integer; then Z=number length), saving two bytes.
[Answer]
# [Swift](https://www.swift.org), ~~166~~ ~~158~~ 145 bytes
```
var c="comma club",i=0
f.map{k,v in var a=abs(v);print(k,(1000..<1000000~=a ?1:1000000..<1000000000~=a ?2:1000000000..<1000000000000~=a ?3:0),c)}
```
And here is the dictionary:
```
var f = [
"John": 100000, "Jamie": 0.05, "Kylie" : 1549001.10,
"Laura": 999999999.99,"Russ":1000000000,"Karla": 1,
"Reid": 99.99,"Mark": 999.99, "Manson": 1000.01,
"Lonnie": 999999999999.00, "Nelly": -123.45
]
```
**[Try it here!](http://swift.sandbox.bluemix.net/#/repl/59ad3583dd73eb75289a5494)**
[Answer]
# [JavaScript (V8)](https://v8.dev/), 55 bytes
```
n=>m=>n+` is in the ${Math.log10(m*m)/6|0}-comma club.`
```
[Try it online!](https://tio.run/##VZJLT@MwFEb3/hV3MRL2QF07tIhQpaxgwVNCs@Ih1QRDPONHZadQBPz2ThwnNNzdPbnfsR37r3gVofRqWY9eDzels6GG0hkjoNjYYm6Kud1dgAqgLNSVhF8fl6KuqHYvnGHz25DxwSf7GqVIqVePdLGZIZREz15J@xSggAU6c5WFtjiLhc6EUbIFjLIpOn/XXcunk5wxTjlDF2LlRQvzvmieo5tVCMmVHx6wpDsXXqdRjm6keuq@t/OXwv/r@w7Y4Gy/Gco4unDWpvXzQdFGfCW1fm/DI57t08kU3UrveCKdL5JsuMC1lWmiCcXdNX22PX1s9@HbsM1MYHDYyP68uaEnZhuUDX9kS37atuEfwh5XXqbd9c5WEmk20Ea4oLVXBhMENCy1qvHOvd2J3bPzJ6KssFZWQjGHDwSQ7vzOCiP3oBShemguPg502THsjgk1Yonxeg8UiTkFx7AUPshT7USN1wSOYE1mnc1pGV8abl8XjmKCo5g0E19ktvkP "JavaScript (V8) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 29 bytes
```
¹ð«E⟨b?6Ḃ«⁰²∆τ6ḭS‹`ḊṄa ⟇¦.`Wṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCucOwwqtF4p+oYj824biCwqvigbDCsuKIhs+ENuG4rVPigLlg4biK4bmEYSDin4fCpi5gV+G5hSIsIiIsIlJ1c3Ncbjk4NjAwMDAwMCJd)
## Explained
```
¹ð«E⟨b?6Ḃ«⁰²∆τ6ḭS‹`ḊṄa ⟇¦.`Wṅ
¹ð # Get first input and push space
«E⟨b?6Ḃ« # Push compressed string "is in the "
⁰² # Get second input and square it
∆τ # Log10 it
6ḭ # Floor divide by 6
S # Stringify
‹ # Push a hyphen
`ḊṄa ⟇¦.` # Push string "comma club"
Wṅ # Join stack
```
[Answer]
## Clojure, 108 bytes
```
(def f ["John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"])
(def a ["100000", "0.05", "1549001.10", "999999999.99", "986000000", "1", "99.99", "999.99", "1000.01", "999999999999.00", "-123.45"])
(map #(str %" is in the "(quot(-(count(nth(partition-by #{\.}(drop-while #{\-}%2))0))1)3)"-comma club.")f a)
```
Not sure if operating on floats would be shorted than on sequences of characters. Not sure if non-function answer is fine which returns a sequence of answers.
[Answer]
# Rebol, 118 bytes
```
d: charset"0123456789"forskip s 2[c: 0 parse s/2[opt"-"any[3 d and d(++ c)]]print[s/1"is in the"join c"-comma club."]]
```
Ungolfed with array declaration:
```
s: [
{John} {100000}
{Jamie} {0.05}
{Kylie} {1549001.10}
{Laura} {999999999.99}
{Russ} {986000000}
{Karla} {1}
{Reid} {99.99}
{Mark} {999.99}
{Manson} {1000.01}
{Lonnie} {999999999999.00}
{Nelly} {-123.45}
{Baz} {1.12345678} ;; added extra Baz test case
]
d: charset "0123456789"
forskip s 2 [
c: 0
parse s/2 [
opt "-"
any [3 d and d (++ c)]
]
print [s/1 "is in the" join c "-comma club."]
]
```
Output:
```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
Baz is in the 0-comma club.
```
[Answer]
# Java 8 ~~154~~ 141 bytes
```
m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);
```
---
## Ungolfed
```
public static void main(String[] args) {
Map<String, Number> m = new LinkedHashMap<String, Number>(){{
put("John", 100000);
put("Jamie", 0.05);
put("Kylie", 1549001.10);
put("Laura", 999999999.99);
put("Russ", 1000000000);
put("Karla", 1);
put("Reid", 99.99);
put("Mark", 999.99);
put("Manson", 1000.01);
put("Lonnie", 999999999999.00);
put("Nelly", -123.45);
}};
m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);
}
```
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
[ sq log10 6 /i [I ${} is in the ${}-comma club.I] ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZFBTsMwEEXFNqcYVWxjbEirBg6AQksXIFZRFsa4xKpjF9sRqqKchE02cAeOAqchqZM29C9sWc9_xn_88bWmzGnT_J69Pz0mq9troNZqZmHDjeISCury_YLWpWJOaGVBKMfNVkvqOAgNN0FQBdCqgsmdztUE9iK4E9QHRAvBPcMIT49gsZMDINMoxpggMvItaWmox_EgFMfHCw-ltX3PeD7DJ20X1MjeTkYeLl4Gz_9q99RsDuQUKat9vC4cwqOCS61UnyIeCY2fsuJS7nztkFxeoagbQv1ZunU4_4lSsG8g9WubfQYXAtIEzqsaRDdvcDnvTiHTRUGByfIZJRlk3vudgpKQQQu32nL_gyGnLPe8afz-Bw)
Port of @MatthewJensen's [JavaScript answer](https://codegolf.stackexchange.com/a/246158/97916).
] |
[Question]
[
You are given a string. Output the string with one space per words.
# Challenge
Input will be a string (not `null` or empty), surrounded with quotes(`"`) sent via the `stdin`. Remove leading and trailing spaces from it. Also, if there are more than one space between two words (or symbols or whatever), trim it to just one space. Output the modified string with the quotes.
# Rules
* The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive) except `"`,i.e, the string will not contain quotes(`"`) and other characters outside the range specified above. See [ASCII table](http://c10.ilbe.com/files/attach/new/20150514/377678/1372975772/5819899987/f146bf39e73cde248d508e5e1b534865.gif) for reference.
* You must take input from the `stdin`( or closest alternative ).
* The output must contain quotes(`"`).
* You can write a full program, or a function which takes input (from `stdin`), and outputs the final string
# Test Cases
```
"this is a string " --> "this is a string"
" blah blah blah " --> "blah blah blah"
"abcdefg" --> "abcdefg"
" " --> ""
"12 34 ~5 6 (7, 8) - 9 - " --> "12 34 ~5 6 (7, 8) - 9 -"
```
# Scoring
This is code golf, so the shortest submission (in bytes) wins.
[Answer]
# CJam, 7 bytes
```
q~S%S*p
```
**Code Explanation**
CJam has reserved all capital letters as inbuilt variables. So `S` has a value of a space here.
```
q~ e# Read the input (using q) and evaluate (~) to get the string
S% e# Split on running lengths (%) of space
S* e# Join (*) the splitted parts by single space
p e# Print the stringified form (p) of the string.
```
This removes the trailing and leading spaces as well
[Try it online here](http://cjam.aditsu.net/#code=q%7ES%25S*p&input=%22this%20%20is%20%20a%20%20%20%20string%20%20%20%22)
[Answer]
# [///](https://esolangs.org/wiki////): 18 characters
```
/ / //" /"// "/"/
```
Sample run:
(Using [faubiguy](https://codegolf.stackexchange.com/users/29990/faubiguy)'s interpreter from his [Perl answer](https://codegolf.stackexchange.com/a/37105) for [Interpret /// (pronounced 'slashes')](https://codegolf.stackexchange.com/questions/37014/interpret-pronounced-slashes).)
```
bash-4.3$ ( echo -n '/ / //" /"// "/"/'; echo '" foo * bar "'; ) | slashes.pl
"foo * bar"
```
[Answer]
# Perl, 22
(20 bytes of code, plus 2 command line switches)
```
s/ +/ /g;s/" | "/"/g
```
Needs to be run with the `-np` switch so that `$_` is automatically filled via stdin and printed to stdout. I'm going to assume this adds 2 to the byte count.
[Answer]
# Bash, ~~36~~ 32 bytes
As a function, a program, or just in a pipe:
```
xargs|xargs|xargs -i echo '"{}"'
```
## Explanation
The first `xargs` strips the quotation marks.
The second `xargs` trims the left side and replaces multiple adjacent spaces in the middle of the string with one space by taking each "word" and separating each with a space.
The `xargs -i echo '"{}"'` trims the right side and rewraps the resulting string in double quotes.
[Answer]
# Ruby, ~~31~~ ~~29~~ ~~25~~ 23 Bytes
```
p$*[0].strip.squeeze' '
```
**Code Explanation:**
* **`p`** outputs string within double quotes to `STDOUT` ([There's more to it](https://stackoverflow.com/a/1255362/1533054) though...)
* **`$*`** is an array of `STDIN` inputs, `$*[0]` takes the first one
* **`strip`** removes starting and ending spaces
* **`squeeze ' '`** replaces >1 space characters with a single space
**Test Cases:**

[Answer]
# Pyth, ~~17~~ ~~15~~ ~~11~~ 10 bytes
(thanks to [Ypnypn](https://codegolf.stackexchange.com/users/16294/ypnypn) and [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman))
```
pjd-cQdkNN
```
Could probably be golfed more.
If the output can use `'` instead of `"` then I only need 8 bytes:
```
`jd-cQdk
```
[Answer]
# Haskell, ~~31~~ 25 bytes
```
fmap(unwords.words)readLn
```
`words` splits the string into a list of strings with spaces as delimiters and `unwords` joins the list of strings with a single spaces in-between. The quotes `"` are stripped of and put back by Haskell's `read` and `show` (implicitly via the REPL) functions on strings.
Outputting by the function itself is three bytes longer, i.e. 28 bytes:
```
print.unwords.words=<<readLn
```
Edit: @Mauris pointed to the `readLn` function, which saved some bytes.
[Answer]
# JavaScript (ES6), 49 ~~52 58~~
**Edit** 6 bytes shorter, thanks to @Optimizer
**Edit 2** -3, thanks to @nderscore
Input/output via popup. Using template string to cut 1 byte in string concatenation.
Run snippet to test in Firefox.
```
alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`)
```
[Answer]
# R, 45 bytes
```
cat('"',gsub(" +"," ",readline()),'"',sep="")
```
The `readline()` function reads from STDIN, automatically stripping any leading and trailing whitespace. Excess space between words is removed using `gsub()`. Finally, double quotes are prepended and appended and the result is printed to STDOUT.
Examples:
```
> cat('"',gsub(" +"," ",readline()),'"',sep="")
This is a string
"This is a string"
> cat('"',gsub(" +"," ",readline()),'"',sep="")
12 34 ~5 6 (7, 8) - 9 -
"12 34 ~5 6 (7, 8) - 9 -"
```
[Answer]
## Python2, 37
Reduced by 1 byte thanks to @ygramul.
```
print'"%s"'%' '.join(input().split())
```
Original version:
```
print'"'+' '.join(input().split())+'"'
```
Test cases:

[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
#õKðý'".ø
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f@fBW78MbDu9VV9I7vOP/fwUgMDRSMDZRUKgzVTAD8jTMdRQsNBV0FSyBWAEA "05AB1E – Try It Online")
---
```
# | Split on spaces.
õK | Remove empty Strings.
ðý | Join with spaces.
'".ø | Surround with quotes.
```
[Answer]
# Java 8, 40 bytes
```
s->'"'+s.replaceAll(" +"," ").trim()+'"'
```
**Explanation:**
[Try it here.](https://tio.run/##jY7NTsMwEITvfYqRL7WVxhL/oAokHoBeOCIOG8dtXRwnit1KCIVXD1tiuKFieS2vPd/s7OhAZdvZsKvfRuMpRjyRCx8zwIVk@zUZi9WxBZ5T78IGRuZLVEt@H7h4x0TJGawQcI8xlg9zMS@i7m3n2eLReylQiIWAUJrxRqqCFeNyort95ZnOJofW1Wg4Rp708gpSOcN7TLbR7T7pjr@SDzJoI0XausiRuegoi1NC8LTvkH@DQOVpOx3IzUmIKlPb9eYf5r/rpPbsHBeXwOcVrlklbxa4VShxx/UDD7Nh/AI)
```
s-> // Method with String as parameter and return-type
'"' // Return a leading quote
+s.replaceAll(" +", // + Replace all occurrences of multiple spaces in the input
" ") // with a single space
.trim() // and remove all leading and trailing spaces
+'"' // + a trailing quote
```
[Answer]
# Mathematica, 75 bytes
```
a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]
```
[Answer]
# KDB(Q), 28 bytes
```
" "sv except[;enlist""]" "vs
```
# Explanation
```
" "vs / cut string by space
except[;enlist""] / clear empty strings
" "sv / join back with space
```
# Test
```
q)" "sv except[;enlist""]" "vs"12 34 ~5 6 (7, 8) - 9 - "
"12 34 ~5 6 (7, 8) - 9 -"
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 44 bytes
```
@(x)[34 strjoin(regexp(x,'\S+','match')) 34]
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Iz2thEobikKCs/M0@jKDU9taJAo0JHPSZYW11HPTexJDlDXVNTwdgk9n9KZnGBRpqGUklGZrGCAggnKgABUG9mXjqQoaSpyQVTo6CQlJOYASEUoBxk@cSk5JTUtHRULXCALGxoBLRcQaHOVMEMKKNhrqNgoamgq2AJxCB1/wE "Octave – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 17 bytes
16 bytes of code + 1 for `-p`
```
s/ *("| ) */$1/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0FLQ6lGQVNBS1/FUD/9/38lBQWFpJzEDAgB4yj9yy8oyczPK/6vWwAA "Perl 5 – Try It Online")
[Answer]
# Powershell, 40 bytes
```
"`"$(($args-Replace' +'," ").trim())`""
```
Pretty straight forward and not very impressive.
**Explanation**
Take input parameter via (predfined) args-variable, replace all multiple spaces with one, trim leading and trailing spaces using trim()-method, add quotes. Powershell will print strings to console as default behavior.
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 42 bytes
```
split(" ")|map(select(length>0))|join(" ")
```
Sample Run
```
$ jq -M 'split(" ")|map(select(length>0))|join(" ")' < data
"this is a string"
"blah blah blah"
"abcdefg"
""
"12 34 ~5 6 (7, 8) - 9 -"
$ echo -n 'split(" ")|map(select(length>0))|join(" ")' | wc -c
42
```
[Try it online](https://jqplay.org/s/0wZCH3DObP)
[Answer]
# [Tcl](http://tcl.tk/), 69 bytes
```
puts [string map {{ "} \" {" } \"} [regsub -all \ + [gets stdin] \ ]]
```
[Try it online!](https://tio.run/##PYxLDoJAEET3nuKlVxpl4V/PAiyGjwPJSAgzrAhefWyVWEl1p166OpQuxn4MntSHoe0sT9MzTchMJkzCZ8@kQ239WJAY58jYktpaSz5UbZcryPMYhdC0Hj42qJaPyEqgcKb5DZag2BRlVT/s9@AvTfsDxxO8zlwUrK87bhsS7mrkDQ "Tcl – Try It Online")
# [Tcl](http://tcl.tk/), 79 bytes
```
puts \"[string trim [regsub -all \ + [string range [gets stdin] 1 end-1] \ ]]\"
```
[Try it online!](https://tio.run/##PYtLDoIwGIT3nuJLVxplgW/PAl0UqIWkNoSWrVevv4pOMpPMK7U@53FOkVpVMU1DcIg@qCbr4txQGO@p2fJrJxOcpXJWPjF1Q9CU2NAVpZad1rXKWaV@iPCmQbBcUSsFjTf9V1iMxKZpO3t3n8Ef4so9hyM8T5wlWF92XDcU3ISoFw "Tcl – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¸f ¸
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=uGYguA&input=InRoaXMgIGlzICBhICAgIHN0cmluZyAgICI)
[Answer]
# [Zsh](https://www.zsh.org/), 15 bytes
```
<<<\"${(Qz)1}\"
```
[Try it online!](https://tio.run/##PYzLCoMwEEX3fsVtcKHQLOy71J/oPpvEpCYYFBJBsLS/no59XbjD3DOPOdo0WecNgpEaPMC73lyghyyaEZwjX0Cq61qw/F5c57J6CJb0QJCN1kVgsQQpjsH1LTUsY4Dy0n4KvoGwVI02t/a9ACWbTkThhYzW0BNMQ@hWv/u/KFUbbHfAc48DgeK4xqkEx5lM4xc "Zsh – Try It Online")
Input string contains embedded quotes. Remove the `Q` for **14 bytes** if the input string does not contain embedded quotes, as is done in some of the other answers here.
Parameter expansion flags: `Q` dequotes, then `z` splits into words as the shell does. The words are then implicitly joined by spaces.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 8 bytes
```
' '%' '*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X11BXRWItf7/VyjJyCxWUADhRAUgKC4pysxLVwAA "GolfScript – Try It Online")
# Explanation
The logic is quite simple:
```
' '% # Split on spaces, remove empty results
' '* # Join on spaces
```
[Answer]
# [Nim](http://nim-lang.org/), 72 bytes
```
import strutils
echo'"',stdin.readAll[1..^2].splitWhitespace.join" ",'"'
```
[Try it online!](https://tio.run/##LcsxCoAwDEDR3VOELC4S0Bt4CgdRqFpoJLalieevgi4f3vAjX7XylVMxUCu3sWjj95BabDu1gyMV745RZO6J1mEhzcI2BTav2e2ezsQRAbt3qBUBNnHhC/zABw "Nim – Try It Online")
Ignoring the IO restrictions as many answers do, **58 bytes**:
```
import strutils
echo stdin.readAll.splitWhitespace.join" "
```
[Try it online!](https://tio.run/##LcfNCYAwDAbQu1OEDtAdnMJzbQP9JP2hifNHQS8PXkdzR5tjGamt2yC6ca7jXUGPi1PZRaJOgR0VxjpT5ngN9EDBneiUVD/ozwM "Nim – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 82 bytes
```
char*s=&s+9;main(t){for(gets(s);*s;s++)*s>32|(s[1]>32&&s[2]&&t)&&putchar(*s,--t);}
```
[Try it online!](https://tio.run/##Fcw5DsIwEEbhq/xKMZqx4yIOW2TBRaIUkQWBgkWZoWK5ugnFk77q5TDlXEo@j7PTPanv0nW83NjkdbrPPB1NWSU5Teq9OD208c3aN8MCIu3jQGRC9Hja/8FO6xBM0qeUqoloV8B3jQ0A3tbYCQK6JVQ/ "C (gcc) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ ~~18~~ ~~16~~ 15 bytes
```
" "/(~#:')_" "\
```
[Try it online!](https://ngn.codeberg.page/k#eJw9ikkKgDAUQ/c9RfgubEER5+EsgtShVRAX6tqz+0vFQMJLiOkIlMgn6EI1MPZCmFDSvW4X4KzBuu5zOywDCRAw7nr1ga+4XY/TvBjrL79cTTPkBfCUqHiRdYRGIUbLBinxAvV/HD0=)
* `" "\` split (implicit) input on spaces
* `(~#:')_` drop empty strings
* `" "/` join remaining items with spaces
[Answer]
# [Fortran](https://en.wikipedia.org/wiki/GNU_Fortran), 113 bytes
[Try it Online!](https://tio.run/##JYhLDoIwFEXnruLGSd9TSIP/SjBxDV1BQynWVDC1TN16xTA4N@ceN8YUzVD2bpGc24eJpk1dJKVY17EzljaFoDuL@epGrIWUKfoXGfucPimQZpZyzis7wjdVoVTtHWnyV7@t@CYAwa0JAe49paUz191g7fjfnKsd9gfge8QJAJ0LXBgl1Ax@)
```
character(99)S;read(*,'(A)')S;S='"'//trim(adjustl(S))//'"'
do i=1,99;if(S(i:i+1)>' ')call fput(S(i:i));enddo;end
```
Per [wikibooks](https://en.wikibooks.org/wiki/Fortran/strings), "*It should be remembered that Fortran is designed for scientific computing and is probably not a good choice for writing a new word processor.*"
Fortran doesn't have a regex concept either. This just makes [string](https://codegolf.stackexchange.com/a/185992/15940) [challenges](https://codegolf.stackexchange.com/a/189152/15940) more [interesting](https://codegolf.stackexchange.com/a/182522/15940)!
In this solution, we trim the string `S`, then iterate over it. Print each character unless it's a space followed by another space.
Previously: ~~[127 bytes](https://tio.run/##JYlNDsIgFIT3nuLFDe9pW1L/kXThGTgBKWAxSA3SrVfHNl3Ml/lm3Jhy0rF@urWU0g866T7bhEKQkslqg7uK4YPYrKpjW8Z5Tv6N2rymbw6oiDif540ZwXdtJYT0DhX6u9@31ETbMABGebBR9joEcJ8prz@RtNF4t9CMC0tpD3A8AfzOcAEAvFZwI6hBzIE/)~~, ~~[147 bytes](https://tio.run/##NYxNDsIgFIT3nOKlG3hKS@p/bbrwDJyAFLCYCgmi7rw6osbFfJl8yYwNMUXl67P9lZzHSUU1JhNZ16Hso1GaLThlJ6QoiRxoRYVI0V2Z0pf7Lc1MIgpRNNEB3NDy2fjiemeZZO7oli023jQUgGKajCfP6JL5f3KlH8qPZqh8qPA7QGK8drYv1OHDnNsVrDcAry3sAIDtORwQauhK4A0)~~
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 26 bytes
```
join(explode(s,"%S+")," ")
```
`explode` groups by non-spaces, and then `join` re-concatenates them.
[Try it online!](https://tio.run/##SyxKykn9/z8rPzNPI7WiICc/JVWjWEdJNVhbSVNHSUFJ8////0oKCkk5iRkQQgHKUQIA "ARBLE – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
OðjṘ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPU8lQzMlQjBqJUUxJUI5JTk4JmZvb3Rlcj0maW5wdXQ9JTIydGhpcyUyMCUyMGlzJTIwJTIwYSUyMCUyMCUyMCUyMHN0cmluZyUyMCUyMCUyMCUyMiUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAnJTIydGhpcyUyMGlzJTIwYSUyMHN0cmluZyUyMiclMEElMjIlMjAlMjBibGFoJTIwYmxhaCUyMCUyMCUyMCUyMGJsYWglMjAlMjIlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJyUyMmJsYWglMjBibGFoJTIwYmxhaCUyMiclMEElMjJhYmNkZWZnJTIyJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCclMjJhYmNkZWZnJTIyJyUwQSUyMiUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMiUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAnJTIyJTIyJyUwQSUyMjEyJTIwMzQlMjAlMjB+NSUyMDYlMjAlMjAlMjAoNyUyQyUyMDgpJTIwLSUyMDklMjAtJTIwJTIwJTIyJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCclMjIxMiUyMDM0JTIwfjUlMjA2JTIwKDclMkMlMjA4KSUyMC0lMjA5JTIwLSUyMicmZmxhZ3M9Qw==)
#### Explanation
```
OðjṘ # Implicit input
# Implicit eval to
# remove the quotes
O # Split on spaces
ðj # Join on spaces
Ṙ # Repr (surround
# by quotes)
# Implicit output
```
[Answer]
# golfua, 42 bytes
```
L=I.r():g('%s*\"%s*','"'):g('%s+',' ')w(L)
```
Simple pattern matching replacement: find any double quotes (`\"`) surrounded by 0 or more spaces (`%s*`) & return the single quote, then replace all 1 or more spaces (`%s+`) with a single space.
A Lua equivalent would be
```
Line = io.read()
NoSpaceQuotes = Line:gsub('%s*\"%s*', '"')
NoExtraSpaces = NoSpaceQuotes:gsub('%s+', ' ')
print(NoExtraSpaces)
```
[Answer]
# Cobra - 68
As an anonymous function:
```
do
print'"[(for s in Console.readLine.split where''<s).join(' ')]"'
```
] |
[Question]
[
A [\$k\$-hyperperfect number](https://en.wikipedia.org/wiki/Hyperperfect_number) is a natural number \$n \ge 1\$ such that
$$n = 1 + k(\sigma(n) − n − 1)$$
where [\$\sigma(n)\$](https://en.wikipedia.org/wiki/Divisor_function) is the sum of the divisors of \$n\$. Note that \$\sigma(n) - n\$ is the [proper divisor sum](https://en.wikipedia.org/wiki/Aliquot_sum) of \$n\$. The sequence of \$k\$-hyperperfect numbers begins
$$6, 21, 28, 301, 325, 496, 697, \dots$$
This is [A034897](https://oeis.org/A034897) on the OEIS.
For example:
$$\begin{align}
\sigma(21) & = 1 + 3 + 7 + 21 = 32 \\
21 & = 1 + 2(32 - 21 - 1) \\
& = 1 + 2 \times 10 \\
& = 21
\end{align}$$
Therefore, \$21\$ is a \$2\$-hyperperfect number.
---
You are to take a \$k\$-hyperperfect number \$n\$ as input and output the value of \$k\$. You can assume you will never have to handle numbers greater than your language's limit at any point (i.e. \$k\sigma(n)\$ will always be within the bounds of your language), and you may input and output in any [convenient format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
The input is guaranteed to be a \$k\$-hyperperfect number, you don't have to handle inputs such as \$2, 87, 104\$ etc. that aren't \$k\$-hyperperfect.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
These are the outputs for all the listed values in the OEIS for this sequence, and are the exhaustive list of inputs for \$n < 1055834\$
```
n k
6 1
21 2
28 1
301 6
325 3
496 1
697 12
1333 18
1909 18
2041 12
2133 2
3901 30
8128 1
10693 11
16513 6
19521 2
24601 60
26977 48
51301 19
96361 132
130153 132
159841 10
163201 192
176661 2
214273 31
250321 168
275833 108
296341 66
306181 35
389593 252
486877 78
495529 132
542413 342
808861 366
1005421 390
1005649 168
1055833 348
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
:Æṣ’$
```
```
: integer divide
Æṣ’$ the decremented divisor sum
```
This uses \$\lfloor\frac{n}{\sigma(n)-n-1}\rfloor\$ instead of \$\frac{n-1}{\sigma(n)-n-1}\$, but it still works because \$\frac{1}{\sigma(n)-n-1}\$ can never be greater than or equal to 1.
[Try it online!](https://tio.run/##LY67cQMxDERbuUCJZi7A/wCpAFXiRHMNKHNk1aDYVTi@SuxGKCzHAckl8LCL@8e@P8a4HF@/P99/n6/TuB7P822MWBfhPrkuSi1UfF2suhy1rQurat9F1QwZSEZFC3Ay5piiAIXzZH0aWoCQdmmb7uBXocEwJXagXglLDhW0eYuIGWGydV@cdHptngiVngevFJx4sxzJlpFIsXKXXtRNDKskZc48oi79i7CCcFi@AQ "Jelly – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 23 20 bytes
```
<.@%1<:@#.[:I.0=i.|]
```
[Try it online!](https://tio.run/##XVHLSsUwEN37FUGRi6BhHplpptzCBUEQXLkVVxcv6sYf8N9r28mU1kUW52RyHpPv8TofLmno0yHdJ0j9dB5yenx9eRqP@XSLx/50k9/65wzDV/59H@@uPs6fPwnTkC5JHdACCLdXVB3pghjaJTsk2c4Wa0LoSmpdw3XByMx7wsB2LwgK7rPECwZ3NNjFqxgB0QkENd5GRhXkrSaaREV1USoaqsWD0RQ9stvCTCKrM7uQKes/ah6S6OjiKFajFFobUybYFcVONcS4bR4LdaGlLZcAr/8DjeukxpbUO9MULTxZ2s8p1rAUN@VqEsvqXKxUrWvzVqqYCLV/4uKcFCqxVm6uFWpdO1hrDzCN4r7FTGpZFYOUucf4Bw "J – Try It Online")
-3 thanks to [rak's rounding down trick](https://codegolf.stackexchange.com/a/223678/15469)
Let `n` be the input.
* `<.@%` round down n divided by
* `1<:@#.` 1 minus the sum of
* `[:I.` the indexes where
* `0=` 0 is equal to the remainder when
* `i.` the list 0..n-1
* `|` is divided elementwise into
* `]` n.
[Answer]
# JavaScript (ES6), 36 bytes
```
n=>~-n/(g=k=>~k--&&!(n%k)*k+g(k))(n)
```
[Try it online!](https://tio.run/##VY7BUsIwEEDvfMXKjCQRG5oGK9UpnvTohSNwqCWtpSWpaXF0HP0CZ7x41P/we/gBP6HG0irkkN03u/t2l8F9UIQ6yUtLqoWoIr@S/vjFkgMc@6nJUsvq9Q6wPEzJUdqPcUoIlqTS4m6daIFRVCBCtQgWV0kmJo8yxDahpZqUOpExJrTIs6TE3ZnsEhopfRmEt7gAfwxPHYApyGMQD7kIS7GAOfhQUDO4@psbQH9A6CrI8fV6dSM0OTdToZKFygTNVIynRqCFEUJkzmpy/995Aej7623z8W5@BGeANp@vaE6XKpEYzUpEjPGZVFA/dxuAdergsIadhkd7dW63dXfLzknDvOaht@9zvdMGax/jnDc8qtmzvV127CHb7XdY27@9h3vtfm7/8ojt3cds12v97Ac "JavaScript (Node.js) – Try It Online")
### How?
\$\sigma(n) − n − 1\$ is the sum of the divisors of \$n\$ in \$[2..n-1]\$. This is also the sum of the divisors of \$n\$ in \$[-1..n-1]\$ because \$1\$ and \$-1\$ cancel each other out. The helper function \$g\$ computes the latter, so that we can use the slightly more golf-friendly halt condition `~k--`.
**Note**: From a mathematical perspective, we really should remove \$0\$ from the list of possible divisors. But it is quietly ignored in this code as we get `!NaN*0`, which is \$0\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
--+#/(Tr@Divisors@#-#-1)&
```
[Try it online!](https://tio.run/##JY3BSsRgDIRfRSjIqin9k/xJk4PQgw@g4AsUWdYedoVu3Yv47HV@PE2SmXxznrfP43nelo95Pz3vff/UDYf3dXpZbsv1a71OXd/1/HC/v67LZbsbprfv5bhNj6dh@nESJgnSwqRiVNPJcyRWVeIsSVIqEthJE6FgpLl4wnbjFrKGqA5T8DoSrpjT1ZnaaAhZBjDsKrB4dPcGrTIqiRVthNECJYI/JLU4ByTS0FTDA@CaZpJkVSqKo0S0hlJw@FevCbUG@t33Pw "Wolfram Language (Mathematica) – Try It Online")
-1 byte from @att
[Answer]
# [Haskell](https://www.haskell.org/), 38 bytes
```
k n=div n$sum[d|d<-[2..n-1],mod n d<1]
```
[Try it online!](https://tio.run/##VZDBboMwDIbvfYocetikFsV2YmKJ7gn2BlUPSKANtUDVdttl784MJB1wiT7s/P6cz/J@ri@XYTib7lA136bb3r/aY/VbFfsjZlm3h9Ou7SvTmaqA09CWjfb1G2OOza4/Ffu2vJpbXVbZT3@r7sX27aN@vDddrR3XW9M9ti9n0xwO/U7bX/XnGDCY6eP5MLCZDoTIGDms6mRTnWdGH5kmdrLOY8kjTnlARJHDxGJlyWgdLPsRUv/sQ5Lmkx05wMoPLEvKn5g90MIXxK/2Q8cpj8c8VN3o60YfvZ3qIMrCxDMD6f2x6mnBXsLTX/OACeN9kLGeM/NiPoLDPPqR@qK3FP2AdT7mPsT9wY6s81M@6z5kGUJ6D68cxMf90Wu@CxzSPrned@I9yr@vd@ji@5BTDjaE6EeaD9ZqR2SxE7OTpx9Y//QjF/4A "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
zUâ ¤x
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=elXiIKR4&input=WzYsMjEsMjgsMzAxLDMyNSw0OTYsNjk3LDEzMzMsMTkwOSwyMDQxLDIxMzMsMzkwMSw4MTI4LDEwNjkzLDE2NTEzLDE5NTIxLDI0NjAxLDI2OTc3LDUxMzAxLDk2MzYxLDEzMDE1MywxNTk4NDEsMTYzMjAxLDE3NjY2MSwyMTQyNzMsMjUwMzIxLDI3NTgzMywyOTYzNDEsMzA2MTgxLDM4OTU5Myw0ODY4NzcsNDk1NTI5LDU0MjQxMyw4MDg4NjEsMTAwNTQyMSwxMDA1NjQ5LDEwNTU4MzNdLW0K)
* Uses [Jelly answer](https://codegolf.stackexchange.com/a/223678/84844) formula
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), ~~81 79~~ 70 bytes
```
"aD@ai0
<esc>V{g<c-a>{dd}dkqqC<c-r>=!(<c-r>a%<c-r>")*<c-r>"
<esc>k@qq@q:%s/\n/+
$x0C<c-r>=<c-r>a/(<c-r>")
```
[Try it online!](https://tio.run/##K/v/XynRxSEx04DLJrU42S6sOt0mWTfRrjolpTYlu7DQGcgrsrNV1ADTiapgSklTC0JD9GQ7FBY6FFqpFuvH5Olrc6lUGEB1QfToa0A1cf3/b2T4X7cMAA "V (vim) – Try It Online")
Uses the observation in [rak1507's Jelly answer.](https://codegolf.stackexchange.com/a/223678/80214)
-2 bytes from kops.
-9 more bytes from kops, removing the entire third line!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
*Ties [rak1507's Jelly answer](https://codegolf.stackexchange.com/a/223678/94066) for #1.*
```
ѨO<÷
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MRDK/xtDm///9/QwMDUxMgQAA "05AB1E – Try It Online")
```
ѨO<÷ # full program
# implicit input...
÷ # divided by...
O # sum of...
Ñ # divisors of...
# implicit input...
¨ # excluding the last...
÷ # rounded down
# implicit output
```
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
function(x,y=x-1)y/sum(2:y*!x%%2:y)
```
[Try it online!](https://tio.run/##K/qfHZ9RWZBaBERpqckltv/TSvOSSzLz8zQqdCptK3QNNSv1i0tzNYysKrUUK1RVgbQmmh4NM00uNBEjQ0whCwwhQwMzS2MsoqamFsbGmv8B "R – Try It Online")
Inspired by [@Dominic's answer to linked challenge](https://codegolf.stackexchange.com/a/211058/55372).
Uses the fact that \$\sigma(n)-n-1\$ for `n>2` is just sum of divisors that lie between `2` and `n-1`. Then, we simply divide `n-1` by the obtained value to get `k` (as `n` is guaranteed to be hyperperfect).
### [R](https://www.r-project.org/), 34 bytes
```
function(x)x%/%sum(2:x*!x%%2:x,-x)
```
[Try it online!](https://tio.run/##K/qfHZ9RWZBaBERpqckltv/TSvOSSzLz8zQqNCtU9VWLS3M1jKwqtBQrVFWBtI5uhSaaFg0zTS40ESNDTCELDCFDAzNLYyyipqYWxsaa/wE "R – Try It Online")
Using [@rak's formula](https://codegolf.stackexchange.com/a/223678/55372).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ 44 bytes
```
i,t;k(x){for(t=i=1;++t<x;)i-=x%t?0:t;x/=-i;}
```
[Try it online!](https://tio.run/##ZVPBbqMwEL3zFbNZVSKqs7UxdnBT2tOeV8p5L2wwwQrBlTFpqqrfnh1skq60IIt59sx7b0Zmt9rvdpeLIX5zSM/Lj8a61JemZJv7e/903izNqjzf@Rf66Dfnh3JlNp@X76bfdWOt4WnwtbE/2uckadKeuOVHAqb3YEs4BLxJ4NXhTpMuDinc1QQXLKF8nr4PD3A3/O4XBDOJJbYs3cvCHhaPi5/b7a8tfJveBXJ8JhPpsTJ9uoQPlJKE4XaTZoxkMSjmHU4ZkTHKBOEhytU1X6o1YbGCcc4JK2KsqLrGGc3ZNSfDpFmAKyTmNMQFu8kxKhXSzEAKxmd1psSXuVxOrmJxhh7WJI9imI8nTAWgJJcI@NUfZYJ/QaGKyRidlXgWCufDtZTypsbybM0JnyckKEcjTM7drUUx9U1niJrIKueJUckK7FJEVCiBvWUi0uaFLND4uphHKkSmbu5EnuXYOs8jLGhRoB8@8zJKMQGxojcsc3UzxagIrniYyucFVmCg6mvwMA4aPxb22kNtTmawboBhPCZPr04/J/9dVix90zD4yuElHB101r7Cm/Et@JIFTo3rj8ZCDeeJWZ/jVfatPkLj7DHo1Bp1kn@uPsQn0BuvXeU1VF0Hp6ob9RCYqzpYNdDrfeXNSXfvYBo42nrsLPZiBqBJ/IXg61lBY3pkep@Ynfaj68E7O@5b0BU6dGZ3QKfRFFp/hxX2D2@t2bWxUdwNvhkMdiJpq1NoB@4ZoNPjZCxO8ZBi6fIv "C (gcc) – Try It Online")
* uses [Jelly's](https://codegolf.stackexchange.com/a/223678/84844) formula
* saved 1 by sum negatively and starting from 1
Explanation
```
i and t used to get divisors sum
for(t=i=1;++t<x) - we start our loop with t=1 and end before x to exclude them from dividers
i-=x%t?0:t; - we iterate all values and add to i negatively if modulo t is 0
x/=-i; - finally we return trough eax trick x divided by -sum which started from 1 so we have the +1 term added to k(sum)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes
```
.+
$*
1(?=(1(?<=(?=(?(\3+$)(\2?\3)))(1+)))+1)(\2)+
$#4
```
[Try it online!](https://tio.run/##Vc69DgIhDADgnae4xDMpkhjaIkLihdGXYNDBwcXB3Psjv/GOoeWjTen3tb4/z3SE@yOdlZhPAiEskMNtKZcAkdUsIVKILKUEVDkqLC8y9x9MSlM9tqUJRU2E3dTtdnXWo26b6dLN1cbv51l/7azzkJm7XbXXfmvSBrf9hKO/7cN@/M@62OF/vx8 "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation:
```
.+
$*
```
Convert the input to unary.
```
1(?=(1(?<=(?=(?(\3+$)(\2?\3)))(1+)))+1)(\2)+
$#4
```
Based on @Deadcode's answer to [Am I not good enough for you?](https://codegolf.stackexchange.com/questions/181350) this calculates the sum of divisors from `2` to `n-1`, but golfed down (removed a `^` and two `$`s) by assuming that the input is a hyperperfect number. After the sum of divisors is calculated the result is then divided into `n-1`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~46~~ 45 bytes
1 byte off thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! Also, this uses the floor trick from [@rak1507's answer](https://codegolf.stackexchange.com/a/223678/36398).
```
lambda n:n//sum(k*(n%k<1)for k in range(2,n))
```
[Try it online!](https://tio.run/##JY/BTsQwDETvfEUvSC2ytLEdu/EKvgQ4FEFh1d3sqpQDX18m4mRnZvxGuf1uX9eq@/z0sp@ny9v71NVjPRy@fy798tDX@@WRh/m6dkt3qt061c@PXqgOw97ErYnPTsIkhTQxqRjlcPIYiVWVOFKQpIwE3qSBUGGkOXnAduMWsobIDlNwOhJU7OHqTG01hCwKMOwqsHh09wbNMiqJJW2E0QpKBHdIanIuGCUMTbl4ATiHmQRZlozikkppDSlB@J@eA9Ma6PV4193WU936ud/w5T8)
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 18 bytes
```
{_x%+/1_&~(!x)!'x}
```
[Try it online!](https://tio.run/##JY07DgJBDEOvEgpYEELkPwmXoaOhoF0JwdUXj6icxM7z8/J6btvj9r6v@/NV7ofvcbeedsv62R4LJamQFhkLmQZ5J2UPEjMjaW5SdiSwkzVCJUgLZ8POkBmKifCEqXgdhCvmTkuhOQZC0QWMpCksGZk5oa7DSINtEkYUShR/SBqnFKQ60OSVBbB3hDaFq6O4uGo2MOPw1/SGxgRtPw "K (oK) – Try It Online")
A port of @Jonah's [J answer](https://codegolf.stackexchange.com/a/223680/75681) - don't forget to upvote him!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes
```
∆K‹ḭ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%86K%E2%80%B9%E1%B8%AD&inputs=697&header=&footer=)
Porting the jelly answer ftw
## Explained
```
∆K‹ḭ
∆K # sum of proper divisors of input
‹ # ↑ - 1
ḭ # input // ↑ (integer division)
```
[Answer]
# Excel, 52 bytes
```
=LET(n,A2-1,q,SEQUENCE(n),n/SUM((MOD(A2,q)=0)*q,-1))
```
Works except for the last test case. `SEQUENCE` is limited to 2^20. The following works up to 2^40 and is 79 bytes.
```
=LET(q,SEQUENCE(A2^0.5),a,(MOD(A2,q)=0)*q,(A2-1)/(SUM(a,IFERROR(A2/a,0))-A2-1))
```
[Answer]
# [Pari/GP](https://pari.math.u-bordeaux.fr/gp.html), 23 bytes
```
n\sum(i=2,n-1,!(n%i)*i)
```
] |
[Question]
[
## Rövarspråket
[Rövarspråket](http://en.wikipedia.org/wiki/R%C3%B6varspr%C3%A5ket) is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.
The basic rules are as follows (from Wikipedia):
* Every consonant (spelling matters, not pronunciation) is doubled, and
an o is inserted in-between.
* Vowels are left intact.
A few examples:
* "hello" -> "hohelollolo"
* "Min svävare är full med ål" -> "MoMinon sosvovävovarore äror fofulollol momedod ålol"
Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.
The letter "y" is taken as a consonant in this case - as most of the time it is.
---
## Your Task:
Write a program to convert a string of Swedish letters, inputted through a function or through stdin, into its Rövarspråket equivalent. Shortest answer in bytes wins!
[Answer]
# [Retina](https://github.com/mbuettner/retina), 14 + 5 = 19 bytes
Retina is a language that is essentially just .NET regex with as little overhead as possible. The code for this program consists of two files:
```
i`[b-z-[eiou]]
```
```
$0o$0
```
This reads the input on STDIN and prints the output to STDOUT.
If you call the files `pattern.rgx` and `replacement.rpl`, you can run the program simply like
```
echo "hello" | ./Retina pattern.rgx replacement.rpl
```
## Explanation
This is pretty straightforward, but let me add some explanation anyway (mostly about how Retina works). If Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.
Retina can be configured (which includes `RegexOptions` and other options) by prepending the regex with ``` and a configuration string. In this case I'm only giving it `i` which is the normal regex modifier for case insensitivity.
As for the regex itself, it uses .NET's character class subtraction to match any consonant in the ASCII range. The replacement then just writes the match back twice with an `o` in between.
[Answer]
**Using Unix KSH ~~27~~ ~~28~~ ~~32~~ 27 bytes** (or 21 if we only count inside sed command)
Thanks to the suggestions of others :) Appreciated.
.. I got down to this:
```
sed 's/[^AEIOUÅÄÖ ]/&o&/ig'
```
(allowed for spaces and Swedish characters)
```
echo "hello" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
hohelollolo
echo "HELLO" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
HoHELoLLoLO
echo "QuIcKlY Now" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
QoQuIcocKoKlolYoY NoNowow
```
[Answer]
# CJam, ~~32~~ 30 bytes
```
q{_eu'[,66>"EIOU"-#)g{'o1$}*}/
```
This is a full program reading from STDIN and printing to STDOUT. It works for arbitrary Unicode input and treats the following 42 characters as consonants:
```
BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz
```
[Test it here.](http://cjam.aditsu.net/#code=q%7B_eu'%5B%2C66%3E%22EIOU%22-%23)g%7B'o1%24%7D*%7D%2F&input=Min%20sv%C3%A4vare%20%C3%A4r%20full%20med%20%C3%A5l.)
## Explanation
```
q "Slurp STDIN.";
{ }/ "For each character...";
_eu "Duplicate and convert to upper case.";
'[,66> "Get a string from B to Z using range and slice.";
"EIOU"- "Remove the remaining four vowels.";
# "Find the position of the character in this string or
-1 if the character can't be found.";
)g "Increment, take signum, which gives 1 for consonants,
and 0 otherwise.";
{ }* "Repeat this block that many times, i.e. do nothing for
non-consonants.";
'o "Push an 'o'.";
1$ "Copy the current character.";
```
[Answer]
# JavaScript, ~~59~~ ~~57~~ ~~55~~ ~~44~~ bytes
```
s=>s.replace(/(?![eiou])[b-z]/gi,"$&o$&")
```
Thanks to Masterzagh for reminding me that a function would be acceptable as well, and for his regex tip regarding backreferences without capturing!
Longer version with input/output:
```
alert(prompt().replace(/(?![eiou])[b-z]/gi,"$&o$&"));
```
Displays a prompt box to enter the string, then shows a dialog containing the Rövarspråket output. The code uses a regex to double the consonants and insert `o`s.
[Answer]
# Mathematica, ~~84~~ ~~73~~ 72 bytes
```
StringReplace[#,a:RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]":>a<>"o"<>a]&
```
Explanation:
* `RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]"` is a regex matching all consonants case-insensitively.
* `a:*..*:>a<>"o"<>a` creates a delayed rule to bind those consonants to `a`, and replace it with and o surrounded by itself.
* Finally, `StringReplace[#,*..*]&` creates a pure function applying that rule to every matching letter in its argument.
[Answer]
# Julia, ~~46~~ 44 bytes
```
t->replace(t,r"(?![eiou])[b-z]"i,s->s*"o"*s)
```
This creates an anonymous function that takes a single string input and prints the Rövarspråket equivalent. To call it, give it a name, e.g. `f=t->...`.
Not much has really been golfed here, other than spaces after the commas in `replace()`.
Here we're using 3 arguments in the `replace()` function: the input string, the regular expression for identifying substrings, and a replacement. Julia denotes regular expression patterns by `r"..."`. Adding `i` to the end makes it case insensitive. This particular regex matches consonants. If a function is used for the replacement, the output is that function applied to each matched substring. The function we're using here takes a string `s` and returns `sos`, since `*` performs string concatenation in Julia. Thus the end result is the input string with each consonant doubled with an "o" between.
Examples:
```
julia> f("Min svävare är full med ål")
"MoMinon sosvovävovarore äror fofulollol momedod ålol"
julia> f("hello")
"hohelollolo"
julia> f("Rövarspråket")
"RoRövovarorsospoproråkoketot"
```
Note that this will be 9 bytes longer if we have to print the result rather than return it. Awaiting confirmation from the OP.
---
**Edit:** Saved 2 bytes thanks to Martin Büttner!
[Answer]
# Haskell, 81 bytes
```
x n|elem n"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"=[n,'o',n]|1<2=[n]
f=(>>=x)
```
Usage: `f "Hello there!"` -> `"HoHelollolo tothoherore!"`.
I cannot cleverly construct the list of consonants without expensive `import`s. Even turning the letter to check to lowercase needs more bytes than simply listing both upper and lowercase consonants.
[Answer]
# Java 8, 45
Use as a lambda function. Uses regular expression.
```
a->a.replaceAll("(?i)[b-z&&[^eiou]]","$0o$0")
```
[Try here](http://ideone.com/nhwZax)
[Answer]
# Perl, 33 Bytes
This answer is mostly regex-only, with a small amount of extra code to perform I/O.
```
$_=<>;s/[^aeiou\W]/$&o$&/gi;print
```
It's been a while since I've used Perl regexes, so this can probably be improved.
```
$_=<>; This takes input from STDIN `<>` and stores
it into the default variable $_
s/ / /gi; This is a case-(i)nsentive, (g)lobal,
(s)ubstitution regex. Since no other
variable is specified, it is applied to
the default variable $_.
[^aeiou\W] This matches any single character that
is a consonant, by using a double-
negative ^\W to match only alphanumeric
characters excluding vowels. Accented
vowels are not considered alphanumeric
by Perl.
$&o$& This forms the replacement. $& contains the
match (the consonant), so this replaces each
consonant with two copies of itself with
an 'o' in between.
print This prints the result. With no arguments,
it prints $_ by default.
```
[Answer]
# Python, 61
I couldn't get a character class union or subtraction to work, and so I don't think Python has that feature. I had to use a negative lookahead instead.
```
import re;f=lambda s:re.sub('(?i)(?![eiou])([b-z])',r'\1o\1',s)
```
Run it here: <http://repl.it/fQ5>
Link to the inverse: <https://codegolf.stackexchange.com/a/48182/34718>
[Answer]
## **Windows Batch, 235 bytes**
```
@echo off
setlocal enabledelayedexpansion
set d=qwrtypsdfghjklzxcvbnm
set #=%1
:x
if defined # (
for /l %%i in (0,1,20)do (
set m=!d:~%%i,1!
if /i !m!==%#:~0,1% set g=!g!!m!o)
set g=!g!%#:~0,1%
set #=%#:~1%
goto x)
echo %g%
```
Usage:
```
script.bat hello
```
Output:
```
hohelollolo
```
You might be wondering why I didnt set d to "aoui", checking for not-equals requires breaking out of a loop. Not everything that should work, does work, in batch. The script handles 1 word of characters [as they appear on your keyboard]. All spaces and newlines that are still present are required for the script to run.
*Windows XP or higher, required. Not tested in Windows 8 and above.*
[Answer]
## **PowerShell - 35 bytes**
Just to show that PowerShell can compete in these sometimes too, and with the regex shamelessly stolen from Martin Büttner's Retina answer:
```
%{$_-replace'[b-z-[eiou]]','$0o$0'}
```
accepts string input from stdin
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 15 13 bytes
-2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
žNDu«SD'o«€Ć‡
```
[Try it online!](https://tio.run/##ATwAw/9vc2FiaWX//8W@TkR1wqtTRCdvwqvigqzEhuKAof//TWluIHN2w6R2YXJlIMOkciBmdWxsIG1lZCDDpWw "05AB1E – Try It Online")
[Answer]
# C 106
**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**
```
x;main(c){for(;read(0,&c,1);printf("%s%s%s"+x*2,&c,x+"o",&c))x=c<66|c>122|c>90&c<98||index("EIOUeiou",c);}
```
[Try it online!](https://tio.run/##FYlBC8IgGED/iggNbQabh9FwdevQITr1A@RTQ3A6XBtC9ttt48HjwYPTG6CUJEZpPQH6NSESEbVUpGEVsJaKKVr/MQQf5h1cpyPfT6pxwFtQmi4wdF2Ga8v55r6pYOjPOVuvdCL4dn@@tA0LZkDFr5SH9Whe5SqjRjIisziHRq2QdH8 "C (gcc) – Try It Online")
[Answer]
# Pyth - 28 bytes
This is works in the obvious way by generating the consonants list on the fly using set-wise difference.
```
FNzpk+N?+\oN}rNZ-{G{"aeiou"k
```
Explanation coming soon.
[Try it here](http://pyth.herokuapp.com/?code=FNzpk%2BN%3F%2B%5CoN%7DrNZ-%7BG%7B%22aeiou%22k&input=hello).
[Answer]
# [Clip 10](http://esolangs.org/wiki/Clip), 30
```
gx"((?i)[b-z&&[^eiou]])""$1o$1
```
Basic regex substitution.
[Answer]
# Pyth, 25 24 23
```
sm+d*+\od}rd0-G"aeoui"z
```
[Run it here.](https://pyth.herokuapp.com/?code=sm%2Bd*%2B%5Cod%7Drd0-G%22aeoui%22z&input=Min+sv%C3%A4vare+%C3%A4r+full+med+%C3%A5l&debug=0)
[Answer]
# K, 38 chars
```
f:{,/(1+2*~(_x)in"aeiouåäö ")#'x,'"o"}
-1 f"Min svävare är full med ål";
MoMinon sosvovävovarore äror fofulollol momedod ålol
```
[Answer]
# K, 31 bytes
```
,/{(x,"o",x;x)9>" aeiouåäö"?x}'
```
A straightforward solution seems fairly competitive given that K lacks regexes. Select between the "XoX" form and "X" form based on whether each character was found in a lookup table of ignored vowels and join the resulting lists.
You can try it in your browser using [oK](http://johnearnest.github.io/ok/index.html):
```
http://johnearnest.github.io/ok/index.html?run=%20%2C%2F%7B(x%2C%22o%22%2Cx%3Bx)9%3E%22%20aeiouåäö%22%3Fx%7D'%22Min%20svävare%20är%20full%20med%20ål%22
```
(Unfortunately I can't provide a clickable link because stack overflow doesn't appear to allow accented characters in URLs)
[Answer]
# Golfscript, 35 bytes
```
{."aeiouåäö\n "?-1={."o"\}{}if}%
```
Expects the input to be on the stack. With input (50 bytes):
```
"#{STDIN.gets}"{."aeiouåäö\n "?-1={."o"\}{}if}%
```
Works with the swedish vovels å, ä and ö.
[Answer]
# Sed (on command line), 28 bytes
```
sed 's/\([^aeiou]\)/\1o\1/g'
```
Either pipe the text in or type it direct. Just the sed code on its own is 22 bytes.
[Answer]
# R, 45 chars
```
gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
```
Simple regex. Reads from stdin. `i=T` stands for `ignore.case=TRUE` (thanks to partial matching of argument names), which makes `gsub` case insensitive.
Usage:
```
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
Min svävare är full med ål
[1] "MoMinon sosvovävovarore äror fofulollol momedod ålol"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hello
[1] "hohelollolo"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hElLo
[1] "hohElolLoLo"
```
[Answer]
# <>< (Fish), 64 bytes
```
>" oieauåäöOIEAUÅÄÖ"0i:1+?!;01.
:&=?\ l?!v&
^[0o&<&o"o"o:&<
```
It's not the shortest answer but I enjoy the challenge of programming in <><
[Try it out here](http://fishlanguage.com/playground/xx5w7wxAa3t3u6oJm)
[Answer]
# golflua, 36 bytes
```
B=I.r():g("[^aeiou%W ]","%1o%1")w(B)
```
Simple pattern-matching: take stdin, then find the non-vowels (`%W` takes care of non-alphanumeric chars) & insert an `o` between the two replacements. Sadly, doing all this within the write (i.e., `w(I.r():g(....))`) also output the count of insertions, though it saved 3 chars. A Lua equivalent would be
```
line = io.read()
rovar = line:gsub("[^aeiou%W ]","%1o%1")
print(rovar)
```
[Answer]
# REXX, 107 bytes
```
parse arg s
v='aeiouåäö '
o=
do until s=''
parse var s l 2 s
if verify(l,v)>0 then l=l'o'l
o=o||l
end
say o
```
"MoMinon sosvovävovarore äror fofulollol momedod ålol"
[Answer]
# JavaScript 43
Thanks to @Masterzagh for saving on function syntax.
```
x=>x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")
```
## JavaScript 62
```
function E(x){return x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r\c_+io
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clxjXytpbw&input=IkhlbGxvLCBXb3JsZCEi)
[Answer]
# Haskell, 75 bytes
```
x n|elem n[x|x<-['B'..'z'],notElem x"EIOUaeiou"]=[n,'o',n]|1<2=[n]
f=(>>=x)
```
This is a slight improvement on [nimi's answer](https://codegolf.stackexchange.com/a/48126/92098) (unfortunately I can't comment yet) which uses a "clever" way to generate a list of consonants (`[x|x<-['B'..'z'],notElem x"EIOUaeiou"]`) that saves 6 bytes over just listing them out.
In this case `['B'..'z']` expands to `"BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"`.
While some non-letter characters are included in the list of consonants, these don't include any punctuation or spaces so it should work for any regular sentence.
Usage: `f "Hello there!"` -> `"HoHelollolo tothoherore!"`.
] |
[Question]
[
Your task is to implement a floor function in as few bytes as possible.
A floor function is a function that takes a real number and returns the largest integer less than or equal to the input.
Your program should support both positive and negative inputs. Since it is provably impossible to support all real numbers you need only support a reasonable subset of them. This subset should include positive numbers, negative numbers and of course numbers that are not integers. Such number systems include fixed-point numbers, floating point numbers and strings.
Your code may be a complete program or function.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being a better score.
[Answer]
### PARI/GP (10)
In gp (and some other languages) x%1 gives the decimal part of x:
```
f(x)=x-x%1
```
NOTE: For negative x, x%1 returns (1 - abs(decimal part of x)), so the above works both for positive and negative numbers.
[Answer]
## Javascript - 6 bytes
Usage of the arrow function declaration (as an anonymous function here) and a bitwise "AND" operator
```
x=>x&x
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1q5CrYIrOT@vOD8nVS8nP10jwVTPVCEpNTk/N7VYQaU6TQPI16zVUdBFF9cFSyRo/v8PAA "JavaScript (Node.js) – Try It Online")
or alternatively using the bitwise "OR" operator:
```
x=>x|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1q6ixoArOT@vOD8nVS8nP10jwVTPVCEpNTk/N7VYQaU6TQPI16zVUdBFF9cFSyRo/v8PAA "JavaScript (Node.js) – Try It Online")
[Answer]
# Python (20)
```
f=lambda x:int(x//1)
```
or, if the result doesn't need to be of type `int`, 15 characters:
```
f=lambda x:x//1
```
[Answer]
## JavaScript, ~~50~~ ~~34~~ ~~33~~ 32 characters
```
function f(n){return~~n-(~~n>n)}
```
Works the same way as the PHP one I submitted.
[Answer]
## DC (15 bytes)
Makes use of a nifty little trick that occurs during division in DC. Add a 'p' to then end to get output (it performs the floor correctly anyway), I assume that stuff is not already on the stack, and that input is in stdin.
```
[1-]sazk?z/d0>a
```
EG: `echo 0 2.6 - | dc -e '[1-]sazk?z/d0>ap'`
[Answer]
# Python (81)
```
def f(x):return str(x - float("." + str(float(x)).split('.')[-1])).split('.')[0]
```
[Answer]
### C (51)
```
int F(float x){int i=x-2;while(++i<=x-1);return i;}
```
[Answer]
### LISP (26)
(Same trick as in PARI/GP answer)
```
(defun f(x)(- x(mod x 1)))
```
[Answer]
## C 126 (including NL)
Doesn't use any built-in conversion such as `(int)x`.
```
r(float x) {
int
p=*(int*)&x,
f=p&8388607|1<<23,
e=((p>>23)&255)-150;
if(e>0)f*=1<<e;
if(e<0)f/=1<<-e;
return p>>31?-f-1:f;
}
```
[Answer]
## J 7 chars
```
f=:-1&| NB. x - (x mod 1)
```
eg.
```
f 3.14
3
f _3.14
_4
```
[Answer]
## C (80)
Well it's not the shortest, but it's a great opportunity to show off my bit twiddling skills :D.
```
main(){int I,X=0x7FFFFF;scanf("%f",&I);printf("%d",((I&X)|X+1)>>-(I>>23)+150);}
```
[Answer]
# C, ~~42~~ 41 bytes
```
int F(float x){int i=x;return i<=x?i:i-1;}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z8zr0TBTSMtJz@xRKFCsxrEzbStsC5KLSktylPItLGtsM@0ytQ1tK4FK81NzMzT0FSo5uIsKALy0zSUVFNi8pR0gGaY6plqalojS4CFdaHitf8B "C (gcc) – Try It Online")
```
int F(float x){int i=x;return x>i?i:i-1;}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z8zr0TBTSMtJz@xRKFCsxrEzbStsC5KLSktylPItLGtsM@0ytQ1tK4FK81NzMzT0FSo5uIsKALy0zSUVFNi8pR0gGaY6plqalojS4CFdaHitf8B "C (gcc) – Try It Online")
[Answer]
**Ruby 1.9 (12 14)**
```
f=->x{x-x%1}
```
It's more a "for the record" type solution along the lines of the PARI/GP one.
```
>> f[3.4] #=> 3.0
>> f[-3.4] #=> -4.0
```
[Answer]
# Julia, 17 bytes
```
f(x)=x-x%1-(x<0)
```
port of the PARI/GP answer
```
f(-pi) = -4
f(pi) = 3
```
[Answer]
# [APL](https://aplwiki.com), 1 [byte](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"))
According to the updated rules, built-ins are allowed:
```
‚åä
```
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~5~~ 4 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")
Anonymous tacit prefix function abiding by the old prohibition on built-ins:
```
⊢-1|
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R12LdA1r/mv@T1Mw1jM04UpTMADiQ@tBnH/5BSWZ@XnF/3WLAQ "APL (dzaima/APL) – Try It Online")
`⊢` the argument
`-`‚ÄÉminus
`1|`‚ÄÉthe division remainder when divided by 1
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.html), 39 bytes
```
0 * * r 0
0 _ _ l 1
1 * _ l 1
1 . _ l 2
```
[Try it online!](http://morphett.info/turing/turing.html?52b4094ddbcf7fe982b16d9a1de81ead)
[Answer]
## Perl (23)
```
$_=int($_)-(int($_)>$_)
```
**Example:**
```
perl -ple '$_=int($_)-(int($_)>$_)'
```
Every value entered on input will now be printed "floored".
Its bass5098's technique, but smaller =).
### As a function(36):
```
sub f{int($_[0])-(int($_[0])>$_[0])}
```
[Answer]
**C# (56 chars):**
My quick and naive answer earlier had a stupid logical flaw in it. Two approaches here, which I believe are both the same length. Double approach relies on the fact that casting to int removes the decimal part of a double.
```
int F(double d){return(int)(d%1==0?d:(int)d-(d<0?1:0));}
```
Decimal approach relies on the fact that d%1 returns the decimal part of the number for decimal data type.
```
int F(decimal d){return(int)(d%1==0?d:d-d%1-(d<0?1:0));}
```
Could save a few characters in both cases by returning their own type instead of int, but I feel a floor function should return an int.
[Answer]
## PHP, ~~51~~ ~~45~~ ~~43~~ 37 characters
```
function f($n){return~~$n-(~~$n>$n);}
```
This should be able to be applied to most languages that do not support the `n%1` trick.
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 4 bytes
```
]1%-
```
## Explained
```
]1%-
] # Duplicate the implicit input
1% # Modulo 1
-# Subtract Modulo 1 of the input from the input, inplicitly outputting the floor'd result.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/z/WUFX3////xnqGRqYA "RProgN 2 – Try It Online")
[Answer]
# Java 8, 19 bytes
Lambda from `double` to `int`. There are plenty of choices for types to assign to: `Function<Double, Integer>`, `DoubleFunction<Integer>`, or `DoubleToIntFunction`.
```
n->(int)(n<0?n-1:n)
```
[Try It Online](https://tio.run/##NY9NS8NAEIbPya8YCoVdSIZW/IC2KoIIHjzVm3hYs0nZdDMbspNIKfntcTQV5jIf7/O@U5vB5KEtqbbHqe2/vCug8CZGeDOO4JwmbecGwyVENizLypHxUIsMe3Yeq54KdoHwOYi6fA@vxC@XGVQ@hA7uJ8oflCPWinarR8rXG9JTsk0FPjte2ENwFhrxVXvuHB0@PsF0h6h/YySVkJT9MwELG6DyG@ZWzs63eJdBfo1XGdzgapwlyf4UuWww9IzyBrH/J6PQGsNqscR1JbClXWRgszkwmrb1p6conyirtd4KakylxukH)
[Answer]
# x86\_64 machine language (Linux), 11 bytes
```
0: c4 e3 79 0b c0 01 vroundsd $0x1,%xmm0,%xmm0,%xmm0
6: f2 0f 2c c0 cvttsd2si %xmm0,%eax
a: c3 retq
```
This requires a processor with AVX instructions.
To [Try it online!](https://tio.run/##PU7RasMwDHz3V4iMgr0moU07ykizH5n3kMpxEnDs4ThgKPn1ecpaBgKdTjrdYdEjpvQyWjSL6q5zUKMrhw/2z0xtGDZitAE0V265mQ6iuPsuLN6CNs55HkW9MnR2DoBD66H//GoyGfEsY3eS8fIu4@FG84H6UUZdUdcyVvjg8JTV7M9hakfLxZ0BaHoLTzsFDRTH8q0mdIUH2DdlBQK2U4BvT2LNIdtp2CkqabMcVL4lFjlwTmv@Kp7xhegJChA1iVe2spR@UJu2n1Nhpl8 "C (gcc) – Try It Online"), compile and run the following C program.
```
#include<stdio.h>
#include<math.h>
int f(double x){return floor(x);}
const char g[]="\xc4\xe3\x79\x0b\xc0\x01\xf2\x0f\x2c\xc0\xc3";
int main(){
for( double d = -1.5; d < 1.5; d+=.2 ) {
printf( "%f %d %d\n", d, f(d), ((int(*)(double))g)(d) );
}
}
```
[Answer]
# Excel, 7
Tested in Excel Online. Closing parens not counted toward score.
The only reason I posted this is because, oddly enough, it seems to work the exact same as `FLOOR.MATH()` with 1 argument.
```
=INT(A1)
```
Semantically, at least to me, it would make sense if this didn't work for negative numbers. However, `INT(-.5)` is `-1` for some reason. `TRUNC()` does what I think `INT()` should do.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~16~~ 15 bytes
```
g;f(d){g=d>>9;}
```
[Try it online!](https://tio.run/##VU7LbsIwELz7K1ZUkdYVsWI4lChpjnxFL6lfWHLsKnEqJMSvYwwiLexpdnYeK0ojREqm0SjpyXzKrqubc3qzXrhZKminKG1gh478U0MfDzfG@ggx7O1RSZRh/nYKNCUnAnlGFefRA2YNRQ3v8FBQ5G1bU9qQMyG/wUqIaoqL3Sz2nzEbNa4KDYVZQyG//GoNGWkXwoiGZoRLt6GPvNtDQ289LjH3bM6qfP5byy3jm2eiZh8vd77ZbdnumXr1V6zi9750Edr1ZkqlG64 "C (gcc) – Try It Online")
>
> Such number systems include **fixed-point numbers**, floating point numbers and strings.
>
>
>
I don't know why people insist on using floats... Fixed point is much easier üôÇ
Uses 32-bit fixed9 precision. Abuses arithmetic shift right. Return hack, not much else to say.
[Answer]
# x86-64 machine code, 7 bytes
Machine code:
```
00000000: 66 0f 3a 0b c0 01 c3 f.:....
```
Assembly:
```
.intel_syntax noprefix
.globl floor_sse4
floor_sse4:
roundsd xmm0, xmm0, 1
ret
```
[Try it online!](https://tio.run/##VZFda4MwFIbv8yuCo5CCBm3L1n3ejF0PuttBsCaxgXxIEotj7K/PRRurkyDJOW@e97xaNU1WV1V/I3QlW8rgk1BKaG@FxqcXAFjnmdUweU0gIarY7Cnk0hhLnGM7NJW69SMAhJROEYIOydv7BwIwPjjQmCTuS/uyg9o0lnHRze1amqNcQMG8fegnlTWtpi4YKZWn8V1cGZb5qxKX3k9m0Wod5kmGCeeQzlNhhoBzSZX@NEY@G0GhZ84jatqjZJCvwffodY0LnyFRijgWrCjigb1sW@Za6YNm8aW6qIlIepg0A6c6e0cJv92hy9WobcJP8BwlKw5XdVifOkkhTy/Y4JpOmKD/ASCIoSqFRtO4Y4YC5xE3HrMtLjbLwj2@@9cPCbZ4vyz9v5/jvBj9@t@Ky7J2fSZVn6khJS7@AA "C++ (gcc) – Try It Online")
Accepts a `double` in an `xmm0`.
Returns the floored `double` in `xmm0`.
Outgolfs the previous answer without cheesing with fixed point.
* Nowhere did it say the return type had to be an `int`, just an *integer*. Therefore, I can just skip the conversion code, storing the integer as a `double`. JavaScript has been doing it for decades.
* This one only requires SSE4.1. üòè
Yes, I know the SSE conversion functions are a little redundant in the test code.
# x86-64 machine code, fixed point joke, 1 byte
Machine code:
```
00000000: c3 .
```
Assembly:
```
.intel_syntax noprefix
.globl floor_fixed
floor_fixed:
ret
```
[Try it online!](https://tio.run/##dVHLTsMwELz7K1ZBlRyUWm0Rr4K4ILgiwRUpcv1ILDl2ZLslCPHrBKdp2gDFl/XueGd2x6yupwVjrWiCcAaS@wS8KozgwErqQGprXS5VI3j@5mhdC4d9aV2AJr1BKM@pr/IcPycPTy8Ywe4QZYLQuX83gTZgbO1EpDjAhbYrPeZGo/uyHd45Edr/e4Z50JHacq/VsLLooqBNBoKrPcCo1l0cTzFgld34ZmiiJRoNdFiChjBsuNsvjSYknS0nyjC95gJufeDKkvJuVKpoKLsK6n0M9rHTxtyuV1qATNEH2mmt44f0bqdYwikszi9IpP9EaGMVhyB8@NNWu@i9xMlEwqSACX81SQYy69fEMs2OfukwhEzTXiCSQEWVwQPvVmxOZhHep9MzMl@MC9fk8hd@Nc5/Ns/IbL4Va7@Y1LTw7VRX3w)
This function takes a 16-bit fixed8 in `ax` and returns a signed 8-bit integer in `ah`. It is not sign extended.
Nobody gave any specifics about precision üòÇ
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Oï
```
[Try it online](https://tio.run/##yy9OTMpM/f/f//D6//91TfSMAA) or [verify all values in the range \$[5,-5]\$ in \$0.1\$ increments](https://tio.run/##yy9OTMpM/W9q4KJxdEeIflmlvZLCo7ZJCkr2lYeW//c/vP6/zn8A).
**Explanation:**
```
O # Sum the stack, which will use the (implicit) input-string if the stack is empty
# (the input is read as string by default, so this `O` basically casts it to a float)
ï # Floor this input-float
# (and output the resulting integer implicitly)
```
Although it may look pretty straight-forward, there are actually some things to note:
In the legacy version of 05AB1E, which was built in Python. The `ï` builtin would translate to the following code snippets:
```
# Pop number
a = str(number) # Cast number to a string
a = ast.literal_eval(a) # Evaluate this string as Python structure (so it goes back to a float)
a = int(a) # Cast this float to an integer (which will truncate)
```
So whether you had string input or decimal input, it would cast it to a string during the code execution anyway, before casting it to an integer to truncate all decimal values.
[Try it online with `-0.5` as decimal argument.](https://tio.run/##MzBNTDJM/W9orfH/8Pr//wE)
[Try it online with `"-0.5"` as string argument.](https://tio.run/##MzBNTDJM/a@ka6BnqvT/8Pr//wE)
The new version of 05AB1E is built in Elixir however. Now, the `ï` builtin translates to the following code snippets (huge parts removed to only keep the relevant stuff):
```
call_unary(fn x -> to_integer(x) end, a) # Call the function `to_integer`, which will:
# (I've only kept relevant parts of this function)
is_float(value) -> round(Float.floor(value)) # If it's a float: floor it down
true -> # Else (it's a string):
case Integer.parse(to_string(value)) do # Parse it from string to integer
:error -> value # If this resulted in an error: return as is
{int, string} ->
cond do # Else it was parsed without errors:
Regex.match?(~r/^\.\d+$/, string) -> int
# If it contains no decimal values:
# Return parsed int
true -> value # Else: return as is
```
Or as a TL;DR: float inputs are floored; string inputs are truncated.
[Try it online with `-0.5` as decimal argument.](https://tio.run/##yy9OTMpM/W9orfH/8Pr//wE)
[Try it online with `"-0.5"` as string argument.](https://tio.run/##yy9OTMpM/a@ka6BnqvT/8Pr//wE)
As you can see, a string input gives the incorrect floored result for negative decimals. Unfortunately, the default (implicit) input from STDIN is always a string, so we'll have to convert it to a float first (for which I've used `O` - which only works on an empty stack in the new 05AB1E version built in Elixir; for the legacy 05AB1E version built in Python, the sum would result in `0` for an empty stack).
[Answer]
# Vyxal, 3 bytes
```
1%-
```
Push input, modulo with 1 and negate!
[Try it!](http://lyxal.pythonanywhere.com?flags=&code=1%25-&inputs=100.435&header=&footer=)
# Vyxal, 1 byte
```
‚åä
```
Though a builtin.....
[Try it!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8C%8A&inputs=100.435&header=&footer=)
[Answer]
# [floor](https://esolangs.org/wiki/Floor), 5 bytes
`floor`
The floor function is a (the only) built-in.
## Full program (17 bytes):
Floor only accepts integers as program Input, so the program uses two inputs to generate a rational number to be passed to the floor function
`f:x y->floor(x/y)`
[implementation](https://github.com/bsoelch/floorLang)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 5 bytes
*The programming language used in this answer was created after the challenge was posted.*
```
it1\-
```
### Examples
```
>> matl it1\-
> 5.6
5
>> matl it1\-
> -5.2
-6
```
### Explanation
Pretty straightforward. It uses a [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation) with divisor `1`.
```
i % input
t % duplicate
1 % number literal
\ % modulus after division
- % subtraction
```
[Answer]
# [Mouse-2002](https://github.com/catb0t/mouse15), 13 bytes
Second place, ahh! (And this is a full program, not a function definition)
```
?&DUP &FRAC -
```
Take the fractional bit of the input and subtract it from the input.
] |
[Question]
[
Write a program that groups a string into parentheses cluster. Each cluster should be balanced.
### Examples :
```
split("((())d)") ➞ ["((()))"]
split("(h(e(l)l)o)(w(o)r)l(d)(w)h(a(t)(s)u)p") ➞ ["((()))", "(())", "()", "()", "(()())"]
split("((())())(()(()()))") ➞ ["((())())", "(()(()()))"]
```
Input may contain letters other than parentheses but you are not sorting them. (The possible characters in the input are uppercase and lowercase letters, numbers, and `()`)
Given parentheses will always be complete (i.e : `(` will be matched with `)` )
Cluster is when outermost `(` ends with `)`. In short when your parentheses are all balanced at that moment so :
```
((( ---> this will be balanced when 3 ) are added
))) ---> now its balanced this is cluster 1
() ---> this is cluster 2
(((((((((((((((((((((((((((((( ---> this is start of cluster 3. will need equal amount of ) to balance
```
This is code-golf, shortest code wins
(Link to challenge on Code Wars : [link](https://www.codewars.com/kata/614b02aab2d61200476973e9) for those that wish to check it)
[Answer]
# [Vim](https://www.vim.org), 20 bytes
```
:s/\w//g
qq%a
<Esc>@qq@q
```
[Try it online!](https://tio.run/##K/v/36pYP6ZcXz@dq7BQNZFL2qGw0KHw/3@NDI1UjRzNHM18TY1yjXzNIs0cjRQgUzNDI1GjRFOjWLNUswAA)
Programmer's text editor builtins ftw! \o/
Explanation:
```
:s/\w//g # Remove all letters and numbers
qq # Start macro 'q'
%a # Jump to matching parenthesis and insert newline
<Esc>
@q # Call macro 'q'
q # End macro 'q'
@q # Call macro 'q'
```
[Answer]
# [J](http://jsoftware.com/), 35 bytes
```
(](]<;.2~0=[:+/\_1+2*i.)[-.-.)&'()'
```
[Try it online!](https://tio.run/##PYy7DoJAFAV7v@KGwnuOuFekRKlMrKxskRijEDCbrPEROn99RQuTmXLmGhPTVspCVOaSSTHqTDb73TaiRr1eWf7OyqpIF4fjMs1nvbFy5oxTBTVy0py7IK0oOjTw9AwUDAi80@NCw8AOJzypigdfvOk/SQCQX/CDHI8f "J – Try It Online")
* Remove all parens from the input.
* Turn `(` into -1 and `)` into 1, and take the scan sum, then convert that into a mask which is 1 wherever the sum is 0.
* Finally, use that mask to cut the cleaned input into chunks.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
fØ(µO-*ĬṖk
```
[Try it online!](https://tio.run/##y0rNyan8/z/t8AyNQ1v9dbUOtxxa83DntOz/h9sjNbMeNe7j4vr/X0lDQ0NTM0VTSUcBwgQhDTDS1ISIZmikauRo5mjma2qUa@RrFmnmaKQAmZoZGokaJZoaxZqlmgVKAA "Jelly – Try It Online")
The Footer just runs all the test cases, joins each cluster by a single newline and each test case by 2.
## How it works
```
fØ(µO-*ĬṖk - Main link. Takes a string S on the left
fØ( - Remove all non-"()" characters
µ - Use this string of parentheses P as the argument from here:
O - Convert to ords ("(" -> 40, ")" -> 41)
-* - Raise -1 to that power, yielding "(" -> 1, ")" -> -1
Ä - Cumulative sum
¬ - Logical NOT, converting 0 -> 1, everything else -> 0
Ṗ - Remove the trailing 1
k - Split P at the indices of the 1s
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 26 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵⊂⍨¯1⌽0=+\¯1*')'=⍵}∩∘'()'
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VRV9Oj3hWH1hs@6tlrYKsdA2RpqWuq2wKlah91rHzUMUNdQ1MdAA&f=JYs7CsAgFMD2nsLtJUvvVLDiIFj6wev3BxkyJCUFoNmYyuOVlWazmxh0dxvZmWFl4TSCw8vtr9/zhQ81bg&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) or [Try it with step by step output](https://razetime.github.io/APLgolf/?h=Cy7IySxReNQ2QUFdQf1RxwyNR50LHnW1PepapMnllZ@ZB5Z61LVYByitAxTlcoMIqT/q3fqoq@lR7wqFQ@sNH/XsVTCwVdCOAXG0FNTVNdXVbRWAStS5wosSC8A6qtWrgSb0btVRr33UsRJolbq6BlCZei0A&c=qy5ILCopVtB51LvEQEHDKz8zT/9RR5emg@GjrkUKGo@6mh71btWs1njU26cQXpRYoADiPurdVXtohQJI8aPeFTEKECMetU1QeNSzN7ggJ7NEAaQEAA&f=c8tTSFNQ19DQ0NQEIQ0w0tTUVAcA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
`∩∘'()'` intersect right argument with `()`. This removes all other characters.
`{ ... }` call the dfn with the cleaned string as its right argument `⍵`.
`')'=⍵` for each character in the string, is it equal to `)`?
`¯1*` this maps `(` to 1 and `)` to ¯1.
`+\` cumulative sums. This is the nesting level for each character.
`0=` equal to 0?
`¯1⌽` rotate the trailing 1 to the front.
`⍵⊂⍨` partition the string at characters with nesting level 0.
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
def f(s,x=1):
for i in s:y=(i==")")-(i=="(");x+=y;y and print(i,end=" "*x)
```
[Try it online!](https://tio.run/##NY7BCsIwEETv/YplTztaD@KtJf6IeCgkpYGSlCZi8/UxiQpzmF1md96W4uLdLWdtZpol9Ie6Yuho9jtZso7CkJRYpRiMSzPCGI@zSmOiyWnaduui2N44rZj4dCBHE2IgRY@ORQTQ4L7YRYysWOEhb/HYsYouFotMEiEBL2wtWG@qpAkAP7uuEtXHFaoVFMpvd51@9epOjELfdvgHkD8 "Python 3 – Try It Online")
prints the clusters separated by spaces
# [Python 3](https://docs.python.org/3/), 88 bytes
```
def f(s,x=1,w=""):
for i in s:y=(i==")")-(i=="(");x+=y;w+=y*y*i+" "*x
return w.split()
```
[Try it online!](https://tio.run/##NY7NCoMwEITveYplTzM2LZTeLOmLlB4KKgZEJYmoT29NoDAs37B/M@@pn8bHcTRtJx2i3dzdrk6VtZFuCuLFjxLr3cE7p1ReC0D53C5uf65nqfbKX1S02oyENi1hlPUW58En8EhtTFGcvI0CIBuqPbFHi4EDJ2LFxMABzYns8UUiIhfOZTDvZKGIpH6Mycny4RyuPDjTzsGPCdlZUXEvUdsVS/6bPH4 "Python 3 – Try It Online")
returns a list of clusters
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žuÃDÇÈ·<.¥_Å¡¦
```
-1 byte because of the rule change from all printable ASCII to just parenthesis and alphanumeric characters in the input
-3 bytes and improved performance thanks to *@cairdCoinheringaahing*
Output as a list of list of characters.
[Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8W@dcODRMOHw4jCtzwuwqVfw4XCocKm//8oVyloKGEodCkocyl1KXAx) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/6P7Sg83uxxuP9xxaLuN3qGl8YdbDy08tOy/l85/DQ0NTc0UTS6NDI1UjRzNHM18TY1yjXzNIs0cjRQgUzNDI1GjRFOjWLNUs4ALrBqENMBIU1MTAA).
**Explanation:**
```
žu # Push constant string "()<>[]{}"
à # Only keep those characters from the (implicit) input-string
D # Duplicate this string
Ç # Convert each character in the copy to its unicode integer:
# "("→0; ")"→1
É # Check for each whether it's odd: "("→0; ")"→1
· # Double each: "("→0; ")"→2
< # Decrease each by 1: "("→-1; ")"→1
.¥ # Undelta this list
_ # Check for each whether it's equal to 0 (1 if 0; 0 otherwise)
Å¡ # Split the string we've duplicated at the truthy indices,
# which implicitly converts the parts to character-lists
¦ # And remove the leading empty list
# (after which the result is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->s{s.tr('^()','').scan /\(\g<0>*\)/}
```
[Try it online!](https://tio.run/##NctLDoIwGEXhOav4J6b3Gi0uQNkIxaTysCRESAshBlh7FROTM/gmx0@Pd2xu8ZyFJejRQ91BdVKKOpT2JamBeV4v2dEw3eJhzhMRAGTFXQ41OnbsiRk9PTtUX9LBYiQCJw7/Yw@/SCaFrm3pZJG1XWWQJm8L2eIH "Ruby – Try It Online")
Returns an array of clusters. The numbered subpattern `\g<0>` nests the balanced-parentheses-matching regex within itself.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~15~~ ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r\w ó@T±JpXc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clx3IPNAVLFKcFhj&input=IihoKGUobClsKW8pKHcobylyKWwoZCkodyloKGEodCkocyl1KXAiCi1R)
```
r\w ó@T±JpXc :Implicit input of string U
r :Replace
\w : RegEx /[a-z0-9]/gi
ó :Partition after each character X
@ :That returns falsey (0) when passed through the following function
T± : Increment T (initially 0) by
J : -1
p : Raised to the power of
Xc : Charcode of X
```
[Answer]
# JavaScript (ES6), ~~61 60~~ 59 bytes
*Saved 1 byte thanks to @tsh*
Outputs a string with one cluster per line.
```
s=>s.replace(/./g,c=>c=='('?(s=-~s,c):c==')'?--s?c:`)
`:'')
```
[Try it online!](https://tio.run/##bYxBCoMwFET3nqK4yQyYuBeiVzHEqC3BiN/WXa@eki5L4a1meO/hXk78cd9PvaUp5Nlmsb2YI@zR@YDWtEvjbe@tVVADxOq3NJ5dGagGrWXw3chq7JRi9mmTFIOJacGMGgA5sSar32dFQGRk4g0XEg9GTDS4uMLhpILwyf2fWqIFfCFLP38A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~28~~ ~~25~~ ~~24~~ 23 bytes
```
Fca@X^pI$==_NyPBcMpY/Py
```
[Try it here!](https://replit.com/@dloscutoff/pip) Or, with a variable definition in the header, you can also [Try it online!](https://tio.run/##K8gs@F9gpaShqfTfLTnRISKuwFPF1jberzLAKdm3IFI/oPL///8aGRqpGjmaOZr5mhrlGvmaRZo5GilApmaGRqJGiaZGsWapZgEA "Pip – Try It Online")
### Explanation
Pushes one parenthesis at a time onto `y`, checks whether `y` is balanced, and if so, outputs and resets it.
```
Fca@X^pI$==_NyPBcMpY/Py
a is cmdline arg; p is "()"; y is "" (implicit)
Fc For each character c in
a@ each regex match in a of
X a regex matching
^ either of the characters in
p "()":
I If
yPBc we push c onto the end of y
_N and then the number of occurrences in y of
Mp each character in "()"
$== is equal:
Py Print y
/ and invert (resulting in nil because y isn't a number)
Y and yank that as the new value of y
```
This works because pushing a string onto a variable that is nil sets the variable to the pushed string, the same as if the variable's value had been `""`.
[Answer]
# Java 8, ~~89~~ ~~82~~ 81 bytes
```
s->{int t=0;for(var c:s)System.out.print(c==40?++t>0?c:c:c==41?--t<1?") ":c:"");}
```
-7 bytes thanks to *@ZaelinGoodman*
Input as character-array; output as a space-delimited string.
[Try it online.](https://tio.run/##bZBBb4MwDIXv/AqLkz1ExKSdYGk19bxTj1UPWYCVLiUoMUxVxW9ngTFt2ib5ENl@733xWQ0qPZdvkzbKe3hWTXuLADwrbjScw1T03BhR963mxrZiZ1vfXyr3qE/KHY4bqEFOPt3cmpaBZVbU1uGgHOjc0/7quboI27PoXFhALeVDtsVZS6iT7I6ThPK5e79NU5Yy28YEca7zOKZinIoowHT9iwkwK9NgmxIugRP3HDxfD0dQNDMDcOUZY0QkKinofzZPWKEhQ5bwHS05MliGJ51QIRN66qn7JZl95sKliFbLMfo@0AKzrH/CgF9R/vzcJ3EOXwG1UFpXXegKtrtwjCfn1DVEFP@KTYtr8jh9AA)
**Explanation:**
```
s->{ // Method with character-array as parameter and no return
int t=0; // Create a temp integer, starting at 0
for(var c:s) // Loop over the characters of the input-array:
System.out.print( // Print:
c==40? // If the current character is '(':
++t // Increase `t` by 1
>0?c:c // And print the '('
:c==41? // Else-if the current character is ')':
--t // Decrease `t` by 1
<1? // If it is now 0:
") " // Print the ')', plus a space
: // Else (it's not 0):
c // Print just the ')'
: // Else (it's a different character):
"");} // Print nothing
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
A=>[...A.replace(/[^()]/g,(o=0,t=''))].map(l=>(t+=l,!(o+=l<")"||-1)&&t+(t="")||""))
```
[Try it online!](https://tio.run/##dY1Ra8JAEITf/RXXfTAzJJ72vSv4O0IKR3Jqy9ULybW@5L@nSaWipcIyMyyz3767L9fX3VubVqfY@HGv4063pbV2ZzvfBld7rMtXsFofCkTdFEmzjKzsh2sRdIuUayieECd7EcowrJ65XKYcSUU4DJNwrOOpj8HbEA/YQwCQDYUmN2JUJ8lNeVlTKi4Wfw@O8AgMjDQ4I7JjQEOLM49wSMzQ85PtHfEKLIzM4cdvFcSDd3N9HvBS4n9gXNG/pYrjNw "JavaScript (Node.js) – Try It Online")
If it accepts array having `,` in between parentheses otherwise :
# [JavaScript (Node.js)](https://nodejs.org), ~~101~~ ~~100~~ 95 bytes
```
A=>[...A.replace(/[^()]/g,(o=0,a=[],t=''))].map(l=>(o+=l<")"||-1,t+=l,!o&&a.push(t+(t=''))))&&a
```
[Try it online!](https://tio.run/##dY3BbsIwEETvfIXxgcwoxpR7jcR3RK5kJYaADLYSUy78e5o0KmqrVlrN7o5m357du@vr7pTy@hobPxzMsDe7Smu9151PwdUem@oNtJujQjQvypnKqmyKgrT64hKC2SGWJrxKysdjvVV5XNQyrlZOp1vfIpeY8@ToDXW89jF4HeIRB0gAZENJUQopjBmlFNVsU1ouFr8PWngEBkYK3BHZMaChxp0tHDIL9Lwx/SA@gUrIafjs3xXEP@@m@FTgHOJfYDzRXyHL4QM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~86~~ ~~80~~ 79 bytes
```
n->{int o=0;for(var c:n)if(o!=(o+=c>41?0:81-2*c))System.out.print(o<1?") ":c);}
```
[Try it online!](https://tio.run/##RVBNb4MwDL3zK7xeSLZBy7RDBaPVjj3s1OO0QwiBpqMJSgzThPjtLHyUWXLiPD/Hz76ylgXX/HvgFbMWPphU0HkeONtugV@YKgXLKgFSoTAF42LKrS84OTos1mqZAwqLQFyl@fxyvLpBmkyMfv62brJKcrDI0F1TyW3sSs5opCpdETOlpXcVixIrsKlX4ARWVw1KrSBdwX92qatC5MB1LgYVHDqnFnS6SwptSMsM8FhRWRD9kBL9lPLDa3TcxfsoeHnklJ5/LYpbqBsMaycIiX6LjhsKm5jTpB@Std8a3LWE4@hEiR@Yp@984j9PnjmnS0xnB/99PGakdyvyliWB1w9/ "Java (JDK) – Try It Online")
-7 thanks to Kevin Kruijssn and Zaelin Goodman!
[Answer]
# JavaScript, ~~55~~ 53 bytes
Outputs a space delimited string with a trailing space.
```
s=>s.replace(/./g,x=>x>{}?``:(n+=x>s||-1)?x:`) `,n=0)
```
[Try it online!](https://tio.run/##HYtNDoIwFAb3nMLl@yIU3ZK0HERNXgPlL7UlFLWJeHYEklnMYmbQbx2qqR/nzPnarI1cg1RBTGa0ujKUi7xNo1RRfX8lc0HuLKMKy5JdUcaCceLUyQvWyrvgrRHWt3RLmIiAGpxu2pEhCwsP@pDHBEv1puhI0wwKeGE8wv3ZoQMAnDzEU4/UQAy@d3x3jPUP)
[Answer]
# [Perl 5](https://www.perl.org/), 26 bytes
```
y/()//cd;s/\((?R)*\)/$&
/g
```
[Try it online!](https://tio.run/##HcoxCsJAEEbhfs8R5H@CTGVlkTtYpxE3GGFwl2xC8PKOGviKV7w6zn6OeJswu@dLs0HqrxwHrDske0RIgkzSpFGOU9Cmwowr/5JJNy2osVLTfv9pB3xKXZ7l1eJU/Qs "Perl 5 – Try It Online")
```
y/()//cd; #delete all chars from input line except ( and )
s/\((?R)*\)/$& #print clusters separated by newline
/g #found by recursive regexp with (?R)
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 89 80 bytes
-9 bytes thanks to @mazzy!!!
```
$args-replace"\w"|sls "(\((?=\(*(?<S>\)))|\k<S>(?<-S>))+?(?(S)(?!))"-a|% M*|% V*
```
[Try it online!](https://tio.run/##VU7BCsIwFLvvK@ZjSjKZUL269Qs8DTz1MrbqwMJGq@zg/PZZPQhCCEkgIeMwWR9661zRDt4u2aV8Llnjr6HwdnRNa8VMMgcXUoEBdGmQQx/rypCczS2qaIu6IrcaGjWhV6QUzbxOT3mkc768ElE7STbZJa70sHBK0XEgJgz0dOiiZI8GdyLwwVEpSWT/KwFkxxgd/qIP8EV8I8sb "PowerShell Core – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 62 bytes
```
switch($args){'('{$r+=$_;++$l}')'{$r+=$_;if(!--$l){$r;$r=''}}}
```
[Try it online!](https://tio.run/##XVDRaoQwEHzPV6QhbXZRv@AQhEJfr9THUo6rxtOSq14SsWDz7TbqmTu6hGR3ZnYnbNcOUptaKjXxiqZ0nMzQ2KIGftQng6MAMXIdpfywiyKunMBQNxU8JAlX6IEd16kQzrnJEZIBITEwAEAskcV0TZHhAtcgQaHCFmGAFjUqKH2KNRzBIhjssbtrWrLre38DQhg5C@YDuMI3UwgTNgYJQfpLH@lIqA9e6facW918n2LK5U8nCytLvwl@WHktTa@sB578grKbemHfX/Pn3tj2vP/88o0f2Tp0jrwvCmmMb2TXGYwm8uKrzYQF7dvmEaSBevGG82/@GTvipj8 "PowerShell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
I think at this point I have to admit I'm on a ternary operator abuse spree.
Big thanks to ErikF for -14 bytes.
And thanks the ceilingcat for -4 more!
```
c;f(d){for(d=0;read(0,&c,1);c>47||(d+=2*putchar(c)-81)||putchar(32));}
```
[Try it online!](https://tio.run/##Nc1BCoMwFEXR3ZT3rILaQgtB9xJ@tCmkjUTFgXHtUQcOz@ReKT4iKYnqYbj2PsA0pQqdNijzm@QVlbTPV4ww96bOhnkSqwOExbtijJcfNam29NPfP44MTsCig6OjJxZ4BrrjgYUWGhMxcuawAw "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~99~~ 92 bytes
Or **[R](https://www.r-project.org/)>=4.1, 85 bytes** by replacing the word `function` with `\`.
*-7 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(s,x=utf8ToInt(s))Map(intToUtf8,split(a<-x[x<42],head(diffinv(!cumsum(a*2-81)),-1)))
```
[Try it online!](https://tio.run/##LU0xDsIwENv5BZ1slA5UDB3KAxjYyoQYoqZRI6VJ1STQ34cUIVmWbfnOa9bXrJMbovEOQWzXFHXb@5uLCORdLjAu9v5RUhEWayJkV2/Prbs0LzGNUkEZrY174zikOaQZ8tTU7ZkUdSFmjQoAqVjxsJsJIywtPfGB50oLVSQnSESW1cTlX93vduCH8q1i/gI "R – Try It Online")
As always, [R](https://www.r-project.org/) is terrible in string challenges...
[Answer]
# [Lua](https://www.lua.org/), 46 bytes
```
print(arg[1]:gsub("%w",""):gsub("%b()","%1;"))
```
[Try it online!](https://tio.run/##NcdLCoAgFAXQvTwQ7oUmTmsp0UApMpAUP7j8l5Nm58TuVHN53gZX7t0e6127h5ghiwj/eXDe2E1IVUXAhcjIRAwkFkackwxwaERlZ/4A "Lua – Try It Online")
Looks like it happened working. Though I don't know much about [Lua](https://www.lua.org/).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
\w
!`\(((\()|(?<-2>.))*.
```
[Try it online!](https://tio.run/##HYo7CoAwAMX23sJBeBF0cBYdvUQHBYUKxYofXLx7rUKGELLP57KOMVc/RHsbkw1WkhWPuqas2wqKKsbUYMIYOc3yeAK6FdjxmpLiNOpEBxdb2r7/Qz/ACw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first two lines simply delete letters and digits. The final line matches groups of (assumed) parentheses. .NET balancing groups keep track of the number of unmatched `(`s and don't allow more `)`s than `(`s. This means that the inner loop stops when it reaches the matching `)` for the outer `(`. The `!` causes the groups themselves to be output on separate lines.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
FS≡ι(«ι⊞υυ»)«ι¿¬⊟υ⸿
```
[Try it online!](https://tio.run/##ZYw7DsIwEERrOMXK1YwEF4AT0KBItDSWCdiSFUf@kALl7GYFdHRvdt6s8za7ZGPv95QFp2lu9VJzmB4gpSyhOi8IlNfW2TKKgTkobwZVqt6Piq14tJ00DevP4p8V7oJzqhjSjEb9/e3MNZvPbu0dHiMiIxOxIDEz4qZID4tKFDbOff@Mbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS≡ι
```
Switch over each character of the input string.
```
(«ι⊞υυ»
```
If it's a `(` then print it and push the predefined empty list to itself. The list therefore contains itself as many times as there are unbalanced `(`s.
```
)«ι
```
If it's a `)` then print it, and...
```
¿¬⊟υ⸿
```
... if popping the list leaves it empty again then move to the next line.
] |
[Question]
[
In the alternating Fibonacci sequence, you first start with `1` and `1` as usual.
However, instead of always adding the last two values to get the next number, you alternate starting with adding, and every other time you subtract instead.
The sequence starts like this:
```
1
1
2 # 1 + 1
-1 # 1 - 2
1 # 2 + -1
-2 # -1 - 1
-1 # 1 + -2
-1 # -2 - -1
-2 # -1 + -1
1 # -1 - -2
-1 # -2 + 1
2 # 1 - -1
1 # -1 + 2
1 # 2 - 1
```
etc.
Notice that after it starts over once it gets to `1` and `1` again.
Given a number *N*, print the *N*th term of the alternating fibonacci sequence.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
# JavaScript (ES6), 25 bytes
```
n=>"334130110314"[n%12]-2
```
0-indexed. You can shorten the string with a slightly recursive version, though it adds 6 bytes:
```
f=n=>"3341301"[n]-2||f(13-n%12)
```
This is still shorter than the definitive recursive formula:
```
f=n=>n<2||f(n-2)+f(n-1)*(-n%2|1)
```
[Answer]
## Python, 31 bytes
```
lambda n:2-33107256/5**(n%12)%5
```
Doesn't bother trying to compute the value. Just looks in up in the peroidic length-12 list `[1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]`, which is compressed in base 5.
Compare to a recursive solution (37 bytes) with `True`'s for 1:
```
f=lambda n:n<2or(-1)**n*f(n-1)+f(n-2)
```
or to string storage
```
lambda n:int('334130110314'[n%12])-2
```
or an attempt at an arithmetical expression.
```
lambda n:4**n%7%3*(-1)**((n+n%2*4)/6)
```
[Answer]
# [Oasis](http://github.com/Adriandmen/Oasis), 10 bytes
Reminds me to implement some more built-ins :p. The input is **0-indexed**.
Code:
```
n>2%x<*c+V
```
Translated version:
```
a(n) = (2*((n+1)%2)-1) * a(n-1) + a(n-2)
a(1) = 1
a(0) = 1
```
And calculates the *n*th term.
[Try it online!](http://oasis.tryitonline.net/#code=bj4yJXg8KmMrVg&input=&args=NQ)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 10 bytes
```
•É&†º•sèÍ
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiw4kmw4LigKDCuuKAonPDqMON&input=NQ)
[Answer]
# Pyth - 13 bytes
Base encoded once cycle series, modular indexed.
```
@-R2jC"
ûx"5
```
[Try it online here](http://pyth.herokuapp.com/?code=%40-R2jC%22%0A%C3%BB%03x%225&input=5&debug=0).
[Answer]
# Jelly, 12 bytes
```
“½Ġ⁻S’b5_2⁸ị
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcwr3EoOKBu1PigJliNV8y4oG44buL&input=&args=NA)**
1-based, given the first and second values are `1`.
Not sure if this is shorter yet, but for this I noted that the series has a period of 12:
`[1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]`
So, I took that and added `2` to give
`[3, 3, 4, 1, 3, 0, 1, 1, 0, 3, 1, 4]`
then converted that as a base `5` number to base `250`, to give:
`[11, 197, 140, 84]`
(which is `184222584`).
```
“½Ġ⁻S’b5_2⁸ị - Main link: n
“½Ġ⁻S’ - base 250 number 184222584
b5 - convert to base 5 [3, 3, 4, 1, 3, 0, 1, 1, 0, 3, 1, 4]
_2 - subtract 2 [1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]
⁸ - left argument, n
ị - index into (1-based and modular)
```
[Answer]
# Haskell, ~~33~~ 26 bytes
```
a!b=a:b:(a+b)!(-a)
(1!1!!)
```
Recursive approach. 0-indexed. [Try it on Ideone.](http://ideone.com/90QKI3)
Saved 7 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
Usage:
```
Prelude> (1!1!!)11
2
```
[Answer]
# Mathematica, 40 bytes
Just creates a lookup table and accesses it cyclically, as in ETHproductions's answer. Unnamed function, 1-indexed.
```
Join[s={2,1,1,2,-1,1},-s][[#~Mod~12+1]]&
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~17~~ ~~16~~ 15 bytes
```
'"Bl)e'F5Za2-i)
```
Input is 1-based.
[Try it online!](http://matl.tryitonline.net/#code=JyJCbCllJ0Y1WmEyLWkp&input=MTA)
### Explanation
The sequence has period `[1 1 2 -1 1 -2 -1 -1 -2 1 -1 2]`.
```
'"Bl)e % Compressed array [1 1 2 -1 1 -2 -1 -1 -2 1 -1 2] with source
% alphabet [-2 -1 0 1 2]
F5Za % Decompress with target alphabet [0 1 2 3 4]
2- % Subtract 2 to transform alphabet into [-2 -1 0 1 2]
i) % Input N and use as (modular, 1-based) index into the sequence
```
[Answer]
# WinDbg, 26 bytes
```
?(85824331b>>@$t0%c*3&7)-2
```
Input is passed in through the pseudo-register `$t0`. 0-indexed. +2 of each term in the sequence is stored in 3 bits making `85824331b`.
How it works:
```
? (85824331b >> @$t0 % c * 3 & 7) - 2 ;*? Evalutes the expression. Shifts 85824331b to get
*the 3 bits for the @$t0'th term (mod c (12) when
*the sequence repeats). Bitwise AND by 7 to get the
*desired 3 bits, finally subtract 2 since the terms
*where stored as +2.
```
Sample output, a loop printing the first 14 values of the sequence:
```
0:000> .for(r$t0=0;@$t0<e;r$t0=@$t0+1){?(85824331b>>@$t0%c*3&7)-2}
Evaluate expression: 1 = 00000001
Evaluate expression: 1 = 00000001
Evaluate expression: 2 = 00000002
Evaluate expression: -1 = ffffffff
Evaluate expression: 1 = 00000001
Evaluate expression: -2 = fffffffe
Evaluate expression: -1 = ffffffff
Evaluate expression: -1 = ffffffff
Evaluate expression: -2 = fffffffe
Evaluate expression: 1 = 00000001
Evaluate expression: -1 = ffffffff
Evaluate expression: 2 = 00000002
Evaluate expression: 1 = 00000001
Evaluate expression: 1 = 00000001
```
[Answer]
# Java, 32 bytes
```
n->"334130110314".charAt(n%12)-50
```
Since this is Java, the answer is 0-indexed.
## Testing and ungolfed:
```
class Ideone {
public static void main (String[] args) throws Exception {
java.util.function.IntFunction f = n->"334130110314".charAt(n%12)-50;
for (int i = 0; i < 12; i++) {
System.out.printf("%d -> %d%n", i, f.apply(i));
}
}
}
```
[Test on Ideone](http://ideone.com/DrjtfE)
[Answer]
# Mathematica, ~~45~~ ~~41~~ 38 bytes
Thanks to @MartinEnder for 3 bytes.
```
±0=±1=1;±n_:=±(n-2)+±(n-1)(1-2n~Mod~2)
```
0-indexed.
**Usage**
```
±5
```
>
> `-2`
>
>
>
[Answer]
# [Perl 6](https://perl6.org), ~~39 35~~ 32 bytes
```
{(1,1,{|(($/=$^a+$^b),$b-$/)}...*)[$_]}
```
```
{(|(334130110314.comb X-2)xx*)[$_]}
```
```
{(|334130110314.comb xx*)[$_]-2}
```
```
{334130110314.substr($_%12,1)-2}
```
[Answer]
# C#, 117 Bytes
Golfed:
```
int A(int n){var f=new List<int>{0,1,1};for(int i=3;i<=n;i++){f.Add(i%2>0?f[i-1]+f[i-2]:f[i-2]-f[i-1]);}return f[n];}
```
Ungolfed:
```
public int A(int n)
{
var f = new List<int> { 0, 1, 1 };
for (int i = 3; i <= n; i++)
{
f.Add(i % 2 > 0 ? f[i - 1] + f[i - 2] : f[i - 2] - f[i - 1]);
}
return f[n];
}
```
Testing:
```
var alternatingFibonacci = new AlternatingFibonacci();
Console.WriteLine(alternatingFibonacci.B(10));
1
```
[Answer]
# R, 38 bytes
Uses the lookup table solution inspired by @ETHproductions JS answer.
```
c(s<-c(2,1,1,2,-1,1),-s)[scan()%%12+1]
```
Edit: Forgot to mention that this is 1-indexed.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 22 bytes
```
34*@%"334130110314"E≈¬
```
[Try it online!](http://actually.tryitonline.net/#code=MzQqQCUiMzM0MTMwMTEwMzE0IkXiiYjCrA&input=NTA)
Explanation:
```
34*@%"334130110314"E≈¬
34*@% input % 12
"334130110314"E get that character in the string
≈¬ convert to int, subtract 2
```
[Answer]
# Java 7, ~~88~~ ~~82~~ 79 bytes
golfed:
```
int f(int n){int c,i=0,a=1,b=1;for(;i<n;){c=i++%2>0?a-b:a+b;a=b;b=c;}return b;}
```
ungolfed:
```
int f(int n)
{
int c, i = 0, a = 1, b = 1;
for (; i < n;)
{
c = i++ % 2 > 0 ? a - b : a + b;
a = b;
b = c;
}
return b;
}
```
[Try it online](https://ideone.com/8MSHDc)
[Answer]
## DC, 55 bytes
```
?sd[ln1+snly[[+2Q]sEln2%1=E-]xlyrsylnld>r]sr1sy0sn1lrxp
```
0-indexed.
```
?sd takes input and stores
it in register d
1sy0sn1 stores 1 in register y
and 0 in register n and
appends 1 to the stack
[ln1+snly adds 1 to register n and
appends the value of
register y to the stack
[[+2Q]sEln2%1=E-] adds or subtracts the
the two values on the
stack depending on
parity of n
xlyrsylnld>r] does the rest of the
stuff required to store
the new values properly
and quits if it has
done enough iterations
sr stores the main macro
in register r
lrxp executes the macro and
prints the stack
```
Register d stores the index of the value. Register n counts the number of iterations completed. Register r stores the main macro. Register y stores the later value in the sequence, while the stack contains the earlier value in the sequence.
Visual explanation of whats going on in the big loop (assuming addition):
```
register: y=1 y=1 y=1 y=1 y=1 y=2
stack: 1 1 1 2 2 1 1 2 1
ly + ly r sy
```
The check to determine whether to add or subtract takes the counter modulo two and uses [this trick](https://codegolf.stackexchange.com/questions/77698/tips-for-golfing-in-dc) to make an if then else construction.
At the end the stack contains a single number, the desired value, which is printed with `p`.
(I'm new to `dc`, so I'd expect there are some obvious improvements to be made here.)
[Answer]
# [ForceLang](https://github.com/SuperJedi224/ForceLang), 153 bytes
```
def s set
s a 1
s b 1
s p 1
s k io.readnum()
if k=0
goto b
label a
s c b.mult p
s c a+c
s a b
s b c
s p p.mult -1
s k k+-1
if k
goto a
label b
io.write a
```
[Answer]
# [Turtlèd](http://github.com/Destructible-Watermelon/Turtl-d), 35 bytes
```
#112-1_--_1-2#?:[*l+].(-r'1)(_"-2")
```
0 indexed
## Explanation:
```
#112-1_--_1-2# the 12 values of sequence. - is -1, _ is -2
?: input a number and move right that many
[*l+] move back to the asterisk on start cell,
increment sting pointer by amount moved
. write pointed char
(-r'1) if it was -, move right, write 1
(_"-2") if it was _, write "-2"
[print grid]
```
### [Try it online!](http://turtled.tryitonline.net/#code=IzExMi0xXy0tXzEtMiM_OlsqbCtdLigtcicxKShfIi0yIik&input=MA)
[Answer]
# ABCR, 43 bytes
```
)AAB)ABB..A))A..A)AA(ABB.)A+A)))AiB5aAb(Bxo
```
Explanation: the first part (`)AAB)ABB..A))A..A)AA(ABB.)A+A)))A`) sets up queue A to contain [1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2], keeping all other queues empty. `iB` stores our desired term, and the loop `5aAb(Bx` cycles through the the queue that many times. `o` prints the front of the queue as a number, which will then be our desired answer.
[Answer]
## Batch, 49 bytes
```
@cmd/cset/a"n=%1%%12,~!(n%%3)*(1|-!(n%%5*(n/4)))"
```
Takes input as a command-line parameter. Explanation: Closed form uses the following observations:
* Sequence is cyclic with period 12
* Every third term is ±2 while other terms are ±1
* Terms after the third are negative except multiples of 5 (after reducing modulo 12)
We therefore start by reducing modulo 12 (to save 2 bytes). We then reduce modulo three and invert the result, which is 1 for multiples of 3 or 0 otherwise. We then bitwise not that value, giving us -2 for multiples of 3 or -1 otherwise. We then reduce modulo 5 and separately divide by 4, giving zero for terms 1, 2, 3, 5, 10 and 12 (0). Inverting and negating gives us -1 for those values and zero for other values. We then bitwise or that with 1 and multiply with the earlier calculation.
[Answer]
# TI-Basic, 26 bytes
Unfortunately, very uninteresting approach. I could not find anything shorter. The list is 1-indexed.
```
Input :{1,1,2,-1,1,-2:augment(Ans,-Ans:Ans(X
```
[Answer]
## C#, ~~73~~ 71 bytes
This uses 0-indexed values of n.
```
n=>{int a=1,b=1,i=0,r;for(;++i<n;){r=i%2>0?a+b:a-b;a=b;b=r;}return b;};
```
Formatted version:
```
Func<int, int> f = n =>
{
int a = 1, b = 1, i = 0, r;
for(; ++i < n;)
{
r = i % 2 > 0 ? a + b : a - b;
a = b;
b = r;
}
return b;
};
```
] |
[Question]
[
**This question already has answers here**:
[Incrementing Numbers, Over Multiple Sessions](/questions/11056/incrementing-numbers-over-multiple-sessions)
(23 answers)
Closed 7 years ago.
In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.
For example, this (ungolfed) Python 3 program satisfies this behavior:
```
N = 1
print(N)
with open(__file__, 'r+') as f:
N = int(f.readline()[4:]) + 1
code = 'N = ' + str(N) + '\n' + f.read()
f.seek(0)
f.write(code)
```
Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.
If the file were named `incr.py`, running it on the command line would look something like this:
```
C:\somepath> python incr.py
1
C:\somepath> python incr.py
2
C:\somepath> python incr.py
3
C:\somepath> python incr.py
4
```
At this point, `incr.py` would read:
```
N = 5
print(N)
with open(__file__, 'r+') as f:
N = int(f.readline()[4:]) + 1
code = 'N = ' + str(N) + '\n' + f.read()
f.seek(0)
f.write(code)
```
Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)
Give the program that prints `1` in your answer. Programs for all higher N can then be inferred. **The shortest `1`-printing program in bytes wins.**
## Notes
* The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.
* Your program must actually rewrite its own source code file, not simply output its modified source like a quine.
* The file name and/or path of the source file may be hardcoded into your program (e.g. `'incr.py'` could have replaced `__file__` in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.
* The source file's name and path should *not* change during execution.
* Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:
1. Printing N to stdout.
2. Changing the source file so it will print N+1 when next run.
[Answer]
# [bash](http://linux.die.net/man/1/bash) (+ [wc](http://linux.die.net/man/1/wc) + [id](http://linux.die.net/man/1/id)), 16 bytes
```
wc -l<$0;id>>$0
```
Counts its lines, then appends a line of garbage to itself.
Needs a trailing newline.
Crashes on line 2 with a syntax error, which thankfully prints to STDERR and exits.
After three invocations, the script looks like this for me:
```
wc -l<$0;id>>$0
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
```
[Answer]
# Python 2, 31 bytes
```
open(*'aa').write('+1');print 1
```
Simply appends `+1` to the source file upon execution. This program assumes that the source file is named as `a`. It can be easily modified to work with an arbitrary filename at 38 bytes as follows:
```
open(__file__,'a').write('+1');print 1
```
Additionally, a 37 bytes alternative exists though it isn't valid due to the 'no temporary files' rule:
```
f=open(*'aa')
print>>f
print f.tell()
```
This program appends a newline to the file `a` which is assumed not to exist before the first execution of the program. Then, the program prints the file size of `a` which is simply `f.tell()` since the file object is now pointing to the end of the file after appending.
[Answer]
# Perl (+shell), 30 bytes
`self.pl`:
```
#!/usr/bin/perl
print 1;`$^X -pi -es/1/1+1/ $0`
```
Works as shown, but replace `^X` by the literal control byte for the claimed score. This does lead to a warning on recent perl versions though.
Because the filename is passed through the shell it should not contain any special characters.
A pure perl version weights in at 32 bytes (or 33 if you add a `-X` option to suppress the `-i` warning)
```
#!/usr/bin/perl -pi
INIT{print 1;@ARGV=$0}s/1/1+1/
```
If you don't mind calling with `perl -M5.010` in both version 2 more bytes can be removed by using `say` instead of `print`
[Answer]
# Pyth - 7 bytes
Very simple, save as `o.txt`.
```
.wk)l"1
```
(btw to change filename, replace the paren for the `.w` with a string, like: `.wk"file.pyth"l"1`
[Answer]
## QBasic (QB64), 47 bytes
```
OPEN"C:\p.bas"FOR APPEND AS 1:?LOF(1)\2-22:?#1,
```
Adjust the path and filename as desired. Note: you must create the file `C:\p.bas` with an external text-editor (I used Notepad++) and make sure it does **not** contain a trailing newline. The QB64 editor adds one when you save the file, which throws off the math and the bytecount. (I assume actual QBasic would do the same, not to mention the auto-formatting.)
Here's an ungolfed version (which *does* expect a trailing newline):
```
OPEN "C:\p.bas" FOR APPEND AS 1
PRINT LOF(1) \ 2 - 32
PRINT #1,
```
**How it works**
The program opens its own code file in `APPEND` mode. It then uses `LOF` to get the length of the current version in bytes. To begin with, this is 47, so we calculate `LOF(1)\2-22` (where `\` is integer division) and print the resulting `1`.
Finally, we want to write some no-op to the end of the file. The shortest way to do this turns out to be writing *nothing*, with a trailing newline automatically added. Since this is Windows (or DOS), the newline is `\r\n`, adding two bytes and necessitating the division by 2 earlier in the code.
(Always `CLOSE` your files when you're done with them, kids. Unless you're golfing.)
[Answer]
# [V](http://github.com/DJMcMayhem/V), 15 bytes
```
:e z
jñ:wñck0
```
*Or*, this readable version:
```
:e <C-r>z
j<C-a>ñ:wñck0
```
This will not work on the online interpreter, since it disallows file access.
Here is a hexdump:
```
00000000: 3a65 2012 7a0a 6a01 f13a 77f1 636b 30 :e .z.j..:w.ck
```
Explanation:
```
:e "Edit the following file:
<C-r>z "Insert the full path to the source file
j "Move down a line
<C-a> "And increment the first number on this line
ñ:wñ "Save this file. Surrounding it with 'ñ' is a fun little hack that allows this to appear on the same line
ck "Change this line and the line above us
0 "To '0' (or whatever number we're on)
```
[Answer]
# PowerShell, 69/60 57
Further golfed and regex corrected based on feedback from TimmyD and Matt
```
($a=1);$a++;(gc($b=$PSCommandPath))-replace"\d+",$a|sc $b
```
69 for completely path and filename agnostic
```
($a=1)|oh;$a++;$b=$PSCommandPath;((gc $b)-replace"\d",$a)|Out-File $b
```
60 bytes if I can specify a fixed filename
```
($a=1)|oh;$a++;(gc .\a.ps1)-replace"\d",$a)|Out-File .\a.ps1
```
Explanation:
Sets $a to 1, returns it. Then it increments the variable, finds its own invocation path, brings that into memory and uses regex to replace digits with the value in $a, then writes to disk.
[Answer]
# Javascript (Node.js), 92 bytes
```
s=require('fs')
f=s.readFileSync(l=__filename)
console.log(f.length-91)
s.writeFile(l,f+';')
```
Prints out the length of the file minus 91, and adds a semicolon (which is ignored by the interpreter) to the final line of the file each time it is run
[Answer]
# C#, 124 bytes
```
namespace System.IO{class C{static void Main(){Console.Write(File.ReadAllLines("p").Length);File.AppendAllText("p","\n");}}}
```
Usage: Source file needs to be called `p`. If using Visual Studio, make sure the Build Action is set to Compile (not default for non-cs files). Also, under project properties ensure the the Output Path is the current directory (ie- empty text box) (again not a default setting).
How it works: It opens the source file and outputs the line count. Then it appends an empty line to the source file.
Pretty print version:
```
namespace System.IO // Put in System.IO namespace so no usings needed.
{
class C
{
static void Main()
{
Console.Write(File.ReadAllLines("p").Length); // Write line count/run count
File.AppendAllText("p","\n"); // Increment line count/run count
}
}
}
```
[Answer]
# PHP, 38 bytes
There are so many ways in PHP to do that ... this one´s the shortest I could find:
```
<?=stat(n)[7]-37;fputs(fopen(n,a),1);#
```
print file size (initially 38) -37, append a character (`1` in this case) to the comment at the end.
* save with file name `n`, call with `php n`
* make sure that the file contains no trailing newline
* `fclose` is called implicitly when the script finishes.
* if you pick another filename, replace `37` with the new file size -1.
* if filename gets longer than 5 characters (including eventual quotation marks), use `$n=filename` for the first occurence, `$n` for the second.
* if filename gets longer than 7 characters, use `__FILE__` instead of the literal file name.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 21 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Define `f` as the following:
```
(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'
```
`⎕NR'f'` the **N**ested **R**epresentation of `f`; on the first run, this is {`f`, `(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'`}
`'⍝',⍨` append a comment symbol, giving {`f`, `(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'`, `⍝`}
`(`...`)` apply the following function:
`⎕FX` **F**i**x** definition of `f`
`⊢` then
`2-⍨` subtract two from
`⍴` the length of the argument (3 on the first run)
Example run:
```
f
1
f
2
f
3
```
[Answer]
## Batch, ~~70~~ 55 bytes
```
@cmd/cset/a-1>>%0
@call:l
@echo %n:~1%
:l
@set/an=0
```
Ensure that the file does not end in a newline. Use the full file name to invoke the file (e.g. `incr.bat`). Works by appending `-1` (`cmd/cset/a` does not output a trailing newline) to the end of the file on each run (including the first!) so that `n` is the negation of the desired result, then just strips off the leading minus sign when printing `n`.
Edit: Saved 8 bytes by removing an `exit/b` which had no visible effect. Saved 7 bytes by switching from `@echo off` to `@` prefixes on each line.
[Answer]
# R, 45 bytes
```
f=function(){body(f)[[3]]<<-body(f)[[3]]+1;1}
```
Not sure if a function counts as a "full program" but calling `f()` will return 1,2,... within the same R session. It also satisfies the self-modifying criterion.
It is necessary to use the double-harpoon operator `<<-` or else `f` will just make a local copy of itself and modify that instead. `<<-` forces that to happen at the top level.
[Answer]
## JavaScript (browser) (ES6), 84 bytes
```
s=document.querySelector('script');f=_=>eval(s.innerHTML);n=0;s.innerHTML+='n++;n;';
```
Run by calling `f()`. Note that this is reset on page load.
I assume that modifying the `<script>` tag counts as rewriting the source code.
[Answer]
# PowerShell ~~55~~ ~~53~~ 31 Bytes
```
"$(gc($p='.\1.ps1'))+1"|sc $p;1
```
Read in the file then just add +1 to the end of the file. Powershell will evaluate that as addition so for the fifth pass the file would have `....;1+1+1+1+1` which evaluates to five!
Old version using saved integer in a variable.
```
($a=1);$a++;(gc .\1.ps1)-replace'=\d+',"=$a"|sc .\1.ps1
```
Since we can hardcode a name it saves spaces over the script determining its own name. Printer the current value of `$a`. Increase $a by one. Using regex, replace the digits that follow an equal sign with the now updated value. Then write back to the original file.
If I change the way I locate the first number I can get down to 53. Using a newline I change my regex to look for numbers at the end of a line. This is why I have to a semicolon to the last line to get that omitted.
```
$a=1
($a++);(gc .\1.ps1)-replace'\d+$',$a|sc .\1.ps1;
```
] |
[Question]
[
## Background
The number 1729 is the Hardy-Ramanujan number. An amazing property of it was discovered by S. Ramanujan (who is widely regarded as the greatest Indian mathematician1), when G.H. Hardy paid a visit to him in a hospital. In Hardy's own words:
>
> I remember once going to see him when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a dull one, and that I hoped it was not an unfavorable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two different ways."
>
>
>
Besides that, it has many other amazing properties. One such property is that it's a Harshad Number, i.e the sum of its digits (1+7+2+9=19) is a factor of it. That too, a special one. As Masahiko Fujiwara showed, 1729 is a positive integer which, when its digits are added together, produces a sum which, when multiplied by its reversal, yields the original number:
1+7+2+9 = 19
19 √ó 91 = 1729
A positive integer having such property is what I define as Hardy-Ramanujan-*ish* Harshad Number, for the purpose of this post. (There might be a technical term for it, but I couldn't find it, unless it's [member of A110921](https://oeis.org/A110921))
---
## The Task
Given a positive integer `n` as input, output a truthy or falsey value based on whether the input `n` is a Hardy-Ramanujan-*ish* Harshad Number. Output truthy, if it is. Otherwise, output falsey.
Note that only four Hardy-Ramanujan-*ish* Harshad Numbers exist (`1`,`81`,`1458` and `1729`), and you can write code which checks for equivalence with them. But I don't think that will be fun.
---
## Input
Your program should take a positive integer (a natural number, in other words). It may take it in any way except assuming it to be present in a variable. Reading from modal window, input box, command line, file etc. is allowed. Taking input as function argument is allowed as well.
---
## Output
Your program should output a truthy or falsey value. They need not be consistent. Your program may output in any way except writing the output to a variable. Writing to screen, command line, file etc. is allowed. Outputting with function `return` is allowed as well.
---
## Additional Rules
* You **must** not use a built-in to accomplish the task (I wonder any language will have such built-in, but then *Mathematica...*)
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
---
## Test Cases
```
Input Output
1 Truthy (because 1 √ó 1 (reverse of 1) = 1)
2 Falsey
3 Falsey
4 Falsey
5 Falsey
81 Truthy (because 9 (8 + 1) √ó 9 (reverse of 9) = 81)
1458 Truthy (because 18 (1 + 4 + 5 + 8) √ó 81 (reverse of 18) = 1458)
1729 Truthy (because 19 (1 + 7 + 2 + 9) √ó 91 (reverse of 19) = 1729)
1730 Falsey
2017 Falsey
```
---
## Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
---
1Every year, on 22nd December, the birthday of Srinivasa Ramanujan, [National Mathematics Day](https://en.wikipedia.org/wiki/National_Mathematics_Day) is observed in India. His colleagues, those in Cambridge, compared him to Jacobi, Euler, and even Newton. Besides being so great, he had almost no formal training in *Pure Mathematics*, but still, he made important contributions to *mathematical analysis*, *number theory*, *infinite series*, and *continued fractions*. Unfortunately, he died at an early age of 32 with thousands of mathematical discoveries in his mind. [A film was also made](https://en.wikipedia.org/wiki/The_Man_Who_Knew_Infinity_(film)) on him, which was based on [his biography](https://en.wikipedia.org/wiki/The_Man_Who_Knew_Infinity), *The Man Who Knew Infinity*.
[Answer]
# ArnoldC, 888 Bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE a
YOU SET US UP 0
GET TO THE CHOPPER a
HERE IS MY INVITATION 1
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE b
YOU SET US UP 0
GET TO THE CHOPPER b
HERE IS MY INVITATION 81
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE c
YOU SET US UP 0
GET TO THE CHOPPER c
HERE IS MY INVITATION 1458
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE d
YOU SET US UP 0
GET TO THE CHOPPER d
HERE IS MY INVITATION 1729
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE res
YOU SET US UP 0
GET TO THE CHOPPER res
HERE IS MY INVITATION a
CONSIDER THAT A DIVORCE b
CONSIDER THAT A DIVORCE c
CONSIDER THAT A DIVORCE d
ENOUGH TALK
TALK TO THE HAND res
YOU HAVE BEEN TERMINATED
```
I know, I just check for equality, but that shouldn't be the fun part of the program.
Enjoy reading it. :)
Added some newlines there for easier readability:
[Try it online](https://tio.run/##pZLBasMwEETv/oq59dqUlqbHjb2NRCIpldYxPiZ2D4XSQvr/uCtDKAUbDLkYWTPeN4vndPn6/uy7YbByl5BMaMQ6Lgy3KE20SRwlSGTGR9GGGokFdUJ9wH2x1bPeRVBST4CjmNRWBViBD01h0ZCXLFHaZSsIm9qXBuEVbzUnscEnkK/wZzV0ZIhhp/ep4cgqOseVJeF9W0xFO01G01k6Rr3hcOCoJqPDYBNcC@uPVijjsRo/JpV8GPfB9d3lpdmHemsgtN9Nss9L2OcZ9vpGeLcE3s0t/vi0vg3fL8H3c/jnh5fb8Jf3nyUBsm06wqkotX@2UpMYEm1nZY8hlvmvzindrNL/C5wf1yQmNzzHGOOOBd8wewhHZ732uhqG9eoX)
[Answer]
# [Neim](https://github.com/okx-code/Neim), 5 [bytes](https://github.com/okx-code/Neim/wiki/Code-Page)
```
ùê¨Dùê´ùïãùîº
```
Explanation:
```
Example input: 1729
ùê¨ Implicitly convert to digit list and ùê¨um the digits [19]
D Duplicate [19, 19]
ùê´ ùê´everse [19, 91]
ùïã mulùïãiply [1729]
ùîº check for ùîºquality with input [1]
Implicit output: 1
```
[Try it!](http://178.62.56.56:80/neim?code=%F0%9D%90%ACD%F0%9D%90%AB%F0%9D%95%8B%F0%9D%94%BC&input=2017)
[Answer]
# x86 Assembly, ~~55~~ ~~35~~ ~~33~~ 31 bytes:
Assumes an ABI where the return value is in EAX and parameters are pushed on the stack... so almost all of them.
```
00000000: 8B 44 24 04 mov eax,dword ptr [esp+4]
00000004: 48 dec eax
00000005: 74 16 je 0000001D
00000007: 83 E8 50 sub eax,50h
0000000A: 74 11 je 0000001D
0000000C: 2D 61 05 00 00 sub eax,561h
00000011: 74 0A je 0000001D
00000013: 2D 0F 01 00 00 sub eax,10Fh
00000018: 74 03 je 0000001D
0000001A: 33 C0 xor eax,eax
0000001C: C3 ret
0000001D: 40 inc eax
0000001E: C3 ret
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
·∫π+S‚Üî;S√ó?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6OmptrTi/4/3LVTO/hR2xTr4MPT7f//jzbUMdIx1jHRMdWxMNQxNDG10DE0N7IEEsYGOkYGhuax/6MA "Brachylog – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~56~~ 55 bytes
```
f n|m<-sum$read.pure<$>show n=n==m*(read.reverse.show)m
```
[Try it online!](https://tio.run/##ZcmxDoIwEADQ3a@4oYOak9ACARPqjxiGJhyByB1NK7r47wVdfesbXXzQPKc0gHy4vcSVVSDXZ34N1KpbHJc3iBVr@Xz8RaAXhUjZd06c2E0CFvrlAD5M8gQF7DwMcNfYaNRl1aCuzbX7e4MFlljtW@Rocl13aQM "Haskell – Try It Online")
---
**Pointfree:** (56 bytes)
```
(==)<*>((*)=<<read.reverse.show).sum.map(read.pure).show
```
[Try it online!](https://tio.run/##ZcqxCoMwEADQvV9xQ4dEjmCiokLSHykOAU@UGg2X2n5@Kq6d35t9etG65jw54Zy0xUOIQjprmfyomD7EiVSa969U6Qgq@CguigeTvCAHv2zgYNxvEHnZ3nCHs8EET42dRl03HerW9MOfG6ywxubUqkRT6nbIPw "Haskell – Try It Online")
---
**Boring:** (24 bytes)
```
(`elem`[1,81,1458,1729])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WIyE1JzU3IdpQx8JQx9DE1ELH0NzIMlbzf25iZp6CrUJKPpdCQVFmXomCikJuYoFCmgK6Ugx5Ix1jHRMdU6CssYGOkYGheex/AA "Haskell – Try It Online")
[Answer]
## JavaScript ES6, ~~59~~ 57 bytes
```
x=>(q=eval([...x].join`+`)+'')*[...q].reverse().join``==x
```
[Try it online!](https://vihan.org/p/tio/?l=javascript-node&p=fcnRCoIwFADQd79ib7vLuDgrNOL2IyFM4i6K4XAz2d8r0ktE7PUcx5OwJBJdYSSeewc3REwdvvxzMKVRpZRqt9nYYeCZQ2RQnzVEqSjufojeMTr/AAtSS7UXU3izuvxWmzl9PLWZbepzbg/VtrZ38U/XlW6@elkB)
Basically splits into digit array, and joins with `+` and evals that expression to basically sum the digits. `string*string` will automatically convert strings into ints. Takes input as a string
[Answer]
# Mathematica, 42 bytes
```
(s=Tr@IntegerDigits@#)IntegerReverse@s==#&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
SOÂ*Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2P9wk1bg//@G5kaWAA "05AB1E – Try It Online")
[Answer]
# Ruby, 69 Bytes
First try, with integer as input:
```
->i{(x=i.to_s.split'').inject(0){|s,a|s+a.to_i}*(x[-1]+x[0]).to_i==i}
```
Second try, with string as input:
```
->i{(x=i.split('').map &:to_i).inject(0,&:+)*(x[-1]*10+x[0])==i.to_i}
```
[Answer]
## Batch, 164 bytes
```
@set/an=%1,s=0
:s
@set/as+=n%%10,n/=10
@if %n% gtr 0 goto s
@set/an=s,r=0
:r
@set/ar=r*10+n%%10,n/=10
@if %n% gtr 0 goto r
@set/an=%1-r*s
@if %n%==0 echo 1
```
Prints 1 on success, no output on failure.
[Answer]
## JavaScript (ES6), 72 bytes
This is valid ES6 submission. Add `f=` at the start and invoke like `f(arg)`.
```
n=>(y=[...`${n}`].reduce((c,p)=>+c+ +p))*[...`${y}`].reverse().join``==n
```
---
### Test Snippet:
```
let f =
n=>(y=[...`${n}`].reduce((c,p)=>+c+ +p))*[...`${y}`].reverse().join``==n
console.log(1 + " -> " + f(1))
console.log(81 + " -> " + f(81))
console.log(1458 + " -> " + f(1458))
console.log(1729 + " -> " + f(1729))
console.log((randomNum = Math.floor(Math.random() * 10000) + 1) + " -> " + f(randomNum))
```
[Answer]
## Kotlin, ~~111~~ 108 bytes
```
fun main(a:Array<String>)=print(a[0].sumBy{c->"$c".toInt()}.run{"${this*"$this".reversed().toInt()}"}==a[0])
```
[Try it online!](https://tio.run/##y84vycnM@/8/rTRPITcxM08j0cqxqCix0ia4pCgzL91O07YASJdoJEYbxOoVl@Y6VVYn69opqSQr6ZXkewIlNGv1ikrzqpVUqksyMou1lFRAlJJeUWpZalFxaoqGJlydUq2tLcgYzf///xuaG1kCAA "Kotlin – Try It Online")
As is typical for statically compiled JVM solutions, a lot of bytes are lost on just the main function declaration and calling print(). The meat of the function is 60ish bytes, which is not bad at all for a general purpose statically typed language like Kotlin.
# Kotlin, boring solution, 69 bytes
```
fun main(a:Array<String>)=print(a[0].toInt()in setOf(1,81,1458,1729))
```
[Try it online!](https://tio.run/##y84vycnM@/8/rTRPITcxM08j0cqxqCix0ia4pCgzL91O07YASJdoJEYbxOqV5HsCmZqZeQrFqSX@aRqGOhaGOoYmphY6huZGlpqa////NwIA "Kotlin – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
def f(n):x=sum(map(int,`n`));return x*int(`x`[::-1])==n
```
[Try it online!](https://tio.run/##lZDdCoMwDIXvfYrc2YoO/4auo3sRJ1Omsl5YRSs4ZM/uSlU2FQbLzQnpl9Mk9VM8Ku6OY5YXUCCOSU/brkRlWiPGhZnwBONzk4uu4dAbsoSSPokIsZwYU8pHkbfidk/bvAUKkQYyHFOJO4k3iT/J0QSl4Qw5/jGcs8A9LZlnzxa2E2ixphVVAwwYh89vRAF1IycCfSB@9tIPEitTgRg2r@p1Ct266OvCQNwvfLUuk@tu2o2f3eoiO4vlQhsrSnde/wxeSGJ8Aw "Python 2 – Try It Online")
## Explanation
```
def f(n): # define a function f that takes an argument n
x = sum( # assign to x the sum of...
map(int, `n`)) # ...the integer conversion of all elements in stringified n
return x * int( # return True if x times the integer conversion of...
`x`[::-1]) # ...the stringified x reversed...
== n # ...equals n
```
An `eval()` solution is a ~~bit~~ 2 bytes longer...
```
def f(n):x=eval('+'.join(`n`));return x*int(`x`[::-1])==n
```
## Alternate ~~(invalid?)~~ solution, ~~42~~ 29 bytes
This solution checks for equality against all of the numbers.
```
lambda n:n in[1,81,1458,1729]
```
[Try it online!](https://tio.run/##lY7dCoJAEIXvfYq5U2MN1x@0BXsRlXbLpIVcRbeLkJ7dll2jUgiamzPMnPPNdHd5aUUw1VkxXVlzrBgIIoCLHKMUIxzFKcJJsCsneR7k4cSG8wAZ5BaowkhLYCQ0EhmJEWhNZ5MmmU7hXl3ozwgfJ1ZpWXXbA1fX4X2NaEPXcyHBHklUPeytsjVMOtxFhd6asr29/T0YSfBhH26N07DOUSREOXXdRXzzM61SDl0haE6Ih8slKstWrH8er5VjegI "Python 2 – Try It Online")
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 60 bytes
```
(n,g=x->x?g(x/10|0)+x%10:0)->n==g(n)*number::("%d"%g(n)).rev
```
[Try it online!](https://tio.run/##FYvtCoIwFEBfJQThrq626wfaYutBoh@Wmwo5ZFgMzGdf@udwOHBevW7bxoW3ng9GQgCLnfSJ8rcO/Jn4j7OTj4kLzhJlpezAsqP9jE/thIAobqN4Tyx1@hvY9U6YYY4FllgTUlHWSFV22ZBzzDhVj3RsJrCJWgYDZj@XyQ123mxdWfgD "Cheddar – Try It Online")
[Answer]
# [NewStack](https://github.com/LyamBoylan/NewStack), 16 bytes
```
ḟᵢ¹f YΣ©Eᴙx| ∏=f
```
## The breakdown:
*Using 1729 as example*
```
ḟᵢ Define new function equal to input. []
¬π Add 1 to stack. [1]
f Multiply stack by the function. [1729]
Y Split the stack into digits. [1,7,2,9]
Σ Sum the stack. [19]
© Duplicate stack. [19,19]
E | Define new value for the first element [19,19]
·¥ôx Reverse first element. [91,19]
‚àè Take the product. [1729]
=f Remove from stack if not equal to the function. [1729]
```
Prints nothing if false, and the original input if true.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
tV!UstVPU*=
```
[Try it online!](https://tio.run/##y00syfmf8L8kTDG0uCQsIFTL9r9LyH9DLiMuC0MuS0suQxNTCyBhbsBlaG5kCRSxtAQA "MATL – Try It Online")
`t` - take input and duplicate it
`V!U` - split it into individual digits
`s` - sum those digits
`t` - duplicate that sum
`VP` - turn that into a string, flip it left to right
`U` - turn that back into a number
`*` - multiply the last two values (the digit-sum and its left-to-right flipped version)
`=` - check if this is equal to the original input (which is the only other value in stack)
[Answer]
# Japt, 8 bytes
```
¬x
*sÔ¥N
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=rHgKKnPUpU4=&input=IjgxIg==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
DS×ṚḌ$$=
```
[Try it online!](https://tio.run/##y0rNyan8/98l@PD0hztnPdzRo6Ji@/9w@@EJaf//G@oY6RjrmOiY6lgY6hiamFroGJobWQIJYwMdIwNDcwA "Jelly – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 30 bytes
```
{my \n=sum .comb;$_==n*n.flip}
```
[Answer]
# [PHP](https://php.net/), 52 bytes
```
<?=strrev($x=array_sum(str_split($argn)))*$x==$argn;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaG5kqWTNZW8HFLYtLikqSi3TUKmwTSwqSqyMLy7N1QCKxRcX5GSWaIB1aGpqagHlbcEc6///AQ "PHP – Try It Online")
# [PHP](https://php.net/), 36 bytes
```
<?=in_array($argn,[1,81,1458,1729]);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaG5kqWTNZW8HFLbNzItPLCpKrNQAS@pEG@pYGOoYmpha6ICUxWpa//8PAA "PHP – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 18 bytes
```
{(⍵=⍎∘⌽×⍎)⍕+/⍎¨⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24RqjUe9W20f9fY96pjxqGfv4elApuaj3qna@kDGoRVAFlC@9v//R71zfTKLSxTy0xTySnOTUouKFUrzUlKLFIwMDAwUMvOSc0qLM8tSFUoyEksUEouAjKLSkoxKLiegHY96N4NUcTkBzVzheGiFEwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~56~~ 52 bytes
```
n->n==(s=sumdigits(n))*fromdigits(Vecrev(digits(s)))
```
[Try it online!](https://tio.run/##NcvNCsIwEATgV1l6ysoGmv7QekgfoxfxULQpAV2XpAp9@piAXob5YEaW4PUmyYFNrCe2VkUb38@73/weFSOeXHj9Oa@3sH7UTxER0yLyOBSDnkCC5z3XqqACV94EF0PQELQEHUFPMGabrh9zDs25ZFvnRW2GK6Yv "Pari/GP – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
Σ_x*=
```
[Try it online!](https://tio.run/##y00syUjPz0n7///c4vgKLdv//w25jLiMuUy4TLksDLkMTUwtuAzNjSyBhLEBl5GBoTkA "MathGolf – Try It Online")
Pretty much the same as the Neim solution byte for byte.
] |
[Question]
[
Inspired by the recent craze over another two character language, [`;#`](https://codegolf.stackexchange.com/questions/121921/make-a-interpreter)
**Intro**
According to [community consensus](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073), acceptable answers on this site must use programming languages that, at minimum:
1. Can determine if a natural number is prime
2. Can add two natural numbers together
3. Can represent a list/tuple of numbers, as well as a single number
For purposes of this challenge, we will ignore #3. Therefore, the simplest language that could be used on this site (ignoring #3) would have exactly two commands, `isPrime` and `add`. For ease of interpretation and byte count, let's assign `isPrime` to `p` and `add` to `+`. Thus, we have our language, `+p`. Your challenge is to interpret some `+p` code.
**Behavior**
* `+` the `add` instruction takes two numbers, adds them, and outputs the result
* `p` the `isPrime` instruction takes a single number, and outputs `1` if it is prime, and `0` if it is not
**Rules**
* You must write a program/function which, given a string of characters, interprets that string as `+p` code. You may assume well-formed input (only `+` and `p` characters).
* Input is flexible. You may take in the program as a string, character array, integer array of codepoints, etc. Input for the program being interpreted is also flexible. You may take in an integer array, and use up entries as the program executes, or each instruction (`+` and `p`) may individually request input. You may assume there will be enough input for every instruction. Input is guaranteed to consist of numbers between 0 and 200 (but your algorithms should theoretically work for any positive integer input).
* Output is also flexible. You may print the results, return them as a list, return a string that contains all the results, etc. If printed or returned as a string, output must be separated by some non-digit, consistent separator, such as a new line, tab, space, or `,` character. You may have a trailing separator or some trailing whitespace. Also, `p`'s output may be any truthy or falsey value, as defined by the language you are working in, rather than `1` or `0`.
* The interpreter may or may not terminate (if it is a full program), but it must stop printing after all instructions are interpreted. (It cannot continue printing the separator forever, or a null character, etc.).
* [These standard loopholes](https://codegolf.meta.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'"), the answer with the least bytes wins
**Test Cases**
```
Program: +
Input: [56, 50]
Output: 106
----------------------------------
Program: p
Input: [12]
Output: 0
----------------------------------
Program: p
Input: [13]
Output: 1
----------------------------------
Program: ++
Input: [172, 120, 33, 58]
Output: 292 91
----------------------------------
Program: p
Input: [29]
Output: 1
----------------------------------
Program: pp
Input: [176, 12]
Output: 0 0
----------------------------------
Program: ++++p
Input: [32, 16, 69, 197, 73, 171, 21, 178, 72]
Output: 48 266 244 199 0
----------------------------------
Program: pp+++p+pp+
Input: [151, 27, 119, 189, 198, 107, 174, 15, 166, 106, 134, 108, 169, 55, 42]
Output: 1 0 308 305 189 0 240 0 0 97
----------------------------------
Program: p+p+++++++pp+p
Input: [143, 67, 30, 149, 178, 52, 112, 122, 55, 122, 142, 199, 20, 175, 138, 80, 116, 180, 50, 116, 15, 92, 74]
Output: 0 97 1 230 234 177 341 195 218 296 0 0 107 0
----------------------------------
Program: ++p++p+pp+++++p+p+pp++
Input: [120, 177, 23, 116, 163, 52, 65, 98, 177, 16, 96, 131, 160, 48, 153, 0, 139, 33, 62, 49, 129, 86, 99, 135, 187, 80, 137, 130, 113, 136, 0, 1, 186, 100, 38, 153]
Output: 297 139 1 117 275 0 227 0 0 153 172 111 215 234 0 217 0 249 0 0 286 191
----------------------------------
Program: ++p+++++p+p+++++++
Input: [181, 169, 6, 84, 68, 171, 129, 107, 106, 114, 197, 58, 11, 88, 156, 169, 43, 77, 49, 43, 102, 78, 93, 51, 91, 37, 64, 93, 82, 126, 181, 81, 44]
Output: 350 90 0 300 213 311 69 244 0 120 0 145 171 142 101 175 307 125
----------------------------------
Program: ++p+
Input: [131, 127, 115, 40, 113, 196, 83]
Output: 258 155 1 279
----------------------------------
Program: +ppp++p+ppp+p++++++++p+p+++pp+ppp++
Input: [6, 9, 187, 168, 96, 167, 178, 139, 86, 148, 99, 103, 166, 18, 119, 15, 132, 77, 16, 88, 139, 34, 58, 90, 43, 69, 68, 152, 59, 106, 134, 49, 155, 100, 52, 55, 27, 188, 41, 77, 23, 49, 171, 23, 193, 84, 111, 165, 80, 18, 63, 23, 116, 112, 119]
Output: 15 0 0 0 345 225 0 202 0 0 0 147 0 104 173 148 112 220 165 183 255 0 82 0 118 72 194 1 0 276 0 0 0 139 231
----------------------------------
Program: ++++++++p++++++++++++
Input: [156, 5, 34, 25, 117, 98, 139, 131, 88, 82, 191, 13, 1, 170, 51, 116, 144, 85, 92, 170, 25, 94, 149, 131, 19, 161, 115, 160, 8, 6, 195, 101, 11, 185, 87, 50, 33, 140, 188, 135, 164]
Output: 161 59 215 270 170 204 171 167 0 177 195 243 150 276 168 201 112 272 83 328 299
----------------------------------
```
[Many, many, very long test cases](https://gist.github.com/SocraticPhoenix/189d9db9b47e9e6f35007f4eefa086b5)
[The java code used to generate test cases](https://gist.github.com/SocraticPhoenix/2fda089ab53a9eaa71464aa16bc7cb0d)
**Example**
Below is an ungolfed java function which will interpret `+p`:
```
public static void interpret(String program, int[] input) {
int index = 0;
for (char inst : program.toCharArray()) {
switch (inst) {
case '+':
System.out.print((input[index++] + input[index++]) + " ");
break;
case 'p':
int n = input[index++];
System.out.print((isPrime(n) ? 1 : 0) + " ");
break;
}
}
}
public static boolean isPrime(long n) { //Taken from https://stackoverflow.com/a/2385999/4484294
if (n < 2) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i + 1) == 0) return false;
}
return true;
}
```
Note: Using the search query `prime AND add AND interpret is:question`, there do not appear to be any duplicates to this question. If there is one, sorry.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
vy.V,
```
[Try it online!](https://tio.run/nexus/05ab1e#LU7bDQMxCPv3KqlOEEKARTrHfVXq9DlTFYEA2zzO53u9X@fc46aPMbro/LeuobOwA2pYUHFoJKYhJhnGMmgq0dUQhZOSjRKKBbWZyK7AcrjAEqVguxMWqERygWRPuqOXdRQmT0pB6f77QWMjCXr0eMYD "05AB1E – TIO Nexus")
**Explanation**
This challenge fit 05AB1E like a glove :)
```
vy # for each instruction in the program
.V # execute as 05AB1E code
, # print
```
[Answer]
# Python 2, ~~135~~ 133 bytes
```
l,p=input()
i=j=0
while len(l)-i:print(int(all(l[i]%k for k in range(2,l[i])))if p[j]=='p'else l[i]+l[i+1]);i+=1+'p+'.find(p[j]);j+=1
```
-2 bytes thanks to kundor
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
p,i=input()
for c in p:n=i.pop(0);print all(n%k for k in range(2,n))if c>'+'else n+i.pop(0)
```
[Try it online!](https://tio.run/nexus/python2#TY7bCoMwDIbv9xS5GbW0jLZWbTfci4xdiLhRlFqce36XFIWFHnL4vyRbkqENMX3Xgp9e8wI9hAjpGttwSXMqFL@lJcQVumkq4nkE0oykWbr4HgojI@fhBf2dCTZMnwGiOMhtY2K3JP6MyYeuagmVhNJKMPhr3UjwDp3S06MlOIycwcBryuDF0yjEyNHIa4u0Q9qbvUStvKXK0UWTU2eCxtQowr4Ee4pVruClNg53qFBQ0jCrKJs3yqB9/gA "Python 2 – TIO Nexus")
[Answer]
# Haskell, ~~88~~ 79 bytes
```
('+':r)!(a:b:c)=a+b:r!c
('p':r)!(a:c)=min(foldr((*).mod a)1[2..a-1])1:r!c
_!e=e
```
`"commands" ! [args]` for use.
* Saved 9 bytes thanks to @Laikoni (#56433)
I'm still learning Haskell; golfing tips appreciated!
[Answer]
# Ruby 2.4, 77+7 = 84 bytes
Uses the `-rprime` flag.
```
->g,i{g.chars.map{|c|c==?p?i.shift.prime?? 1:0: c==?+?i.shift(2).sum: p}-[p]}
```
[Answer]
# [Perl 6](http://perl6.org/), 70 bytes
```
{@^b.rotor($^a.comb.map(1+(*ne'p'))).map({$_-2??.[0].is-prime!!.sum})}
```
First the `rotor` method is used to split the input list into chunks of size 1 or 2 depending on whether the next character of the program is `p` or not. Then that chunked list is mapped over; chunks of size 2 are summed, and chunks of size 1 have their sole element tested for primality.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ÆP,+/ị@L
OḂ‘Bṁ@Ç€K
```
[Try it online!](https://tio.run/nexus/jelly#zVA7TsNQEOx9iu39JLz7/H6ponQIpKRHFFRUgBUlPaQIBRfgEBwARJmTOBd5zNiUHADpaTSrmZ3dt5vt0/327mEhTdsOfAOwnchEm8vHYb@DfKPWOdGUnJgH0QiIYMGcxOCk5F@ZSqHqlQW6ekoBXib44sSDR/T14GqAzB4WHkmakZInL@M8mXKmj3MELRzQofBz9m2z3u/mTa0kThFFVxJLQToxS8COTixpUFRMA77SU1Wq1pfJYzmKFpV6Om5cezF@vy2vm/X4eTg/v6/Gr5fl6fV8@Liqtf59svrfT/UD "Jelly – TIO Nexus")
**Alternate solution, 18 bytes**
```
⁴Ḣ
¢+¢µ¢ÆPµḂ?
OÇ€K
```
[Try this one online!](https://tio.run/nexus/jelly#zVC7bsMwDNz1FdytwaSsV5bOQYd4Lzp06pTGCJIPaIb2PzxnbADPypckP6Ie7Y75gALC4Yg7Hin2@937/m27ItM0g74B2Mxkpmb9MRwPkF9YWkscoyVxIBwAAcyLpeAt5fQnq5JVdawFujqVPLya4LIlBx7Q14GzAJL2aOGQxAkpafZqnFPGOtOFJUItOqBF4ZbsV7M5HpZNJUedQoyuSBI9tSQSga06saRAYRL2@EqnKqsqXZ49kgJxZqr3z5/bNJoyNmUslzJev/pyuU2nJ7O5ft9P5@da6@Or1f9@rV8 "Jelly – TIO Nexus")
[Answer]
# C#, ~~130~~ 129 bytes
```
p=>d=>{var i=0;p.Any(c=>{Console.Write((c==43?d[i++]+d[i]:Enumerable.Range(2,d[i]-2).Any(x=>d[i]%x==0)?0:1)+" ");return++i<0;});}
```
[Try it online!](https://tio.run/nexus/cs-mono#VVDda9swEH/3X3EURiXkGclfses4JYwNBhuUprCH4AfPMUHgyJokl4aQv9092yukfpDu7vd11mClOsLubF17Krzhpgt@SfWv8JquthaeTH809QkunnW1kw289vIAL6115MegmrV1BpX@tnGyV2up3L7abECedOfDgoFeLHyYUTz14Kh38WCmkf8wJQtQeNdPUb9rqcjihOLaHC2dl7m1hnIG9rwqvJuQj7Gogp3upCP3cE@DXdu1jSMWyg38VC4Kg6fa2JZYSoOXfmtMfSa4xfyLoy43h3Jzea0NyJIXOtiqM2lw8q1Xtu/a4I@RriU4KuPo8bCXjFUMr@rhuxpOran/Iue5VseWhP40/xrS2eMNjbH98laWnD7yB0HZHdzRwrRuMIoxuebFlRbX0b99v48Huo4j01ozpucLi@VbSr1M2ZhCDiJbgUgzyFO8sFxlIKIcMmxjnCKBR4hgi4DANkE8hNWkgmwhRzEkyOUQR5DmgG4iCSGZtKhDNJ50KOQcJiCBEOUojsVkFEYzYSWmSuQRZDFGCQxIIONTcBrNECYKEU5rvAM "C# (Mono) – TIO Nexus")
* Saved 1 byte by currying the function (thanks to Cyoce)
[Answer]
## PowerShell 3+, ~~151~~ 121 Bytes
```
$r,$v=$args;$p={0-notin((2..(($n=0+"$args")-1)|%{$n%$_}))};$i=0;$r|%{if($_-eq"p"){&p $v[$i]}else{$v[$i]+$v[($i+=1)]}$i++}
```
PowerShell has no prime built-ins so I had to roll my own. My first version was terrible and I took from most of the other ones that test for 0 among modulus results which saves a lot. Also sabed a few bytes by using `-notin` instead of `-notcontains` but it mean PowerShell v2 is out.
### Comment based explanation
```
# $r is the program code. Assumed char array
# $v is the remaining variables in an assumed integer array.
$r,$v=$args
# Anonymous function to determine if a number is a prime or not.
# Test all potential factors. Check if any 0 modulus remainders are present
$p={0-notin((2..(($n=0+"$args")-1)|%{$n%$_}))}
# $i is an index for tracking location in $v
$i=0
# Cycle each of the instructions
$r|%{if($_-eq"p"){
# Call the prime checking anonymous function on this number
&p $v[$i]
}else{
# Add the next two numbers. Adjust the index accordingly.
$v[$i]+$v[($i+=1)]
}
# Next number in list.
$i++
}
# Next number in list.
$i++
}
```
[Answer]
# F#, 130 bytes
```
let rec r=function|[],_->()|'+'::t,f::s::u->printf"%i "(f+s);r(t,u)|_::t,n::u->printf"%b "(List.exists((%)n>>(=)0)[2..n-1]);r(t,u)
```
[Try it online!](https://tio.run/##VYvNioMwFEZf5SKUJviDUaM1wTzB7LoUEVoMCG10kgiz8N2dm5nOQLM4fDeco136XMxyHI/Jg53uYDu9mbufF7P3QzKmitD9HJ@F8IkWwgmxpWq1s/E6Os0QER07Ki3xyUb3MVjmTbmh8jE7n01fSEfIiRqlSEdz2hdZZlI2/OWHBRKt8Rr/vhVntKufeNHX6TOBnlWlhLqRUOYSWNUimosEXuBgAQWC89dgVUCLVpFL1oTvEu1LaFmNCIv/Xxxki0FTDfT4Bg "F# (Mono) – Try It Online")
[Answer]
# QBasic, 122 bytes
```
INPUT p$
FOR i=1TO LEN(p$)
INPUT x
IF"+"=MID$(p$,i,1)THEN INPUT y:?x+y:ELSE f=0:FOR j=2TO x:f=f-(x MOD j=0):NEXT:?f=1
NEXT
```
Takes the code as a line of input, then takes each input number on its own line. The outputs are interspersed with the inputs because they're printed as soon as they're calculated. The truthy value is `-1`; falsey is `0`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes the programme as a character array, outputs `true` or `false` for the prime test.
```
Ëø²?Vv j:Vv +Vv
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cQ&code=y/iyP1Z2IGo6VnYgK1Z2&input=IitwcHArK3ArcHBwK3ArKysrKysrK3ArcCsrK3BwK3BwcCsrIgpbNiwgOSwgMTg3LCAxNjgsIDk2LCAxNjcsIDE3OCwgMTM5LCA4NiwgMTQ4LCA5OSwgMTAzLCAxNjYsIDE4LCAxMTksIDE1LCAxMzIsIDc3LCAxNiwgODgsIDEzOSwgMzQsIDU4LCA5MCwgNDMsIDY5LCA2OCwgMTUyLCA1OSwgMTA2LCAxMzQsIDQ5LCAxNTUsIDEwMCwgNTIsIDU1LCAyNywgMTg4LCA0MSwgNzcsIDIzLCA0OSwgMTcxLCAyMywgMTkzLCA4NCwgMTExLCAxNjUsIDgwLCAxOCwgNjMsIDIzLCAxMTYsIDExMiwgMTE5XQ) (Header splits the programme into an array)
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~206~~ ~~197~~ 177 bytes
Outputs `0` for composites and `-0.5` for primes
```
listen to S
cut S
while S
listen to N
if roll S's "+"
listen to I
say N-I/-1
else
let D be N
let P be N-1
while P and D-2
let D be-1
let M be N/D
turn M up
let P be N/D-M
say P
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in, with the programme as the first line of input and each integer on its own line)
] |
[Question]
[
## Explanation
A perfect shuffle is where a deck of cards is split exactly in half and the cards from each pile are alternately interleaved. The original bottom cards and the original top card must be preserved after a perfect shuffle.
After 8 perfect shuffles, a standard 52 card deck returns to its original order.
## Challenge
Write a program that displays the state of a deck of cards as it goes through 8 consecutive perfect shuffles. You may use any human-readable representation of a deck, provided that it displays the number and suit of each card in the deck in sequential order. It must display a representation of all of the cards, for all nine states.
This is **code golf**, so the shortest solution wins.
## Example Output
Here is an example output produced by [this example implementation in Javascript](http://jsfiddle.net/bBmMJ/4/)
```
AS,AC,AD,AH,2S,2C,2D,2H,3S,3C,3D,3H,4S,4C,4D,4H,5S,5C,5D,5H,6S,6C,6D,6H,7S,7C,7D,7H,8S,8C,8D,8H,9S,9C,9D,9H,10S,10C,10D,10H,JS,JC,JD,JH,QS,QC,QD,QH,KS,KC,KD,KH
AS,7D,AC,7H,AD,8S,AH,8C,2S,8D,2C,8H,2D,9S,2H,9C,3S,9D,3C,9H,3D,10S,3H,10C,4S,10D,4C,10H,4D,JS,4H,JC,5S,JD,5C,JH,5D,QS,5H,QC,6S,QD,6C,QH,6D,KS,6H,KC,7S,KD,7C,KH
AS,4C,7D,10H,AC,4D,7H,JS,AD,4H,8S,JC,AH,5S,8C,JD,2S,5C,8D,JH,2C,5D,8H,QS,2D,5H,9S,QC,2H,6S,9C,QD,3S,6C,9D,QH,3C,6D,9H,KS,3D,6H,10S,KC,3H,7S,10C,KD,4S,7C,10D,KH
AS,9S,4C,QC,7D,2H,10H,6S,AC,9C,4D,QD,7H,3S,JS,6C,AD,9D,4H,QH,8S,3C,JC,6D,AH,9H,5S,KS,8C,3D,JD,6H,2S,10S,5C,KC,8D,3H,JH,7S,2C,10C,5D,KD,8H,4S,QS,7C,2D,10D,5H,KH
AS,5S,9S,KS,4C,8C,QC,3D,7D,JD,2H,6H,10H,2S,6S,10S,AC,5C,9C,KC,4D,8D,QD,3H,7H,JH,3S,7S,JS,2C,6C,10C,AD,5D,9D,KD,4H,8H,QH,4S,8S,QS,3C,7C,JC,2D,6D,10D,AH,5H,9H,KH
AS,3S,5S,7S,9S,JS,KS,2C,4C,6C,8C,10C,QC,AD,3D,5D,7D,9D,JD,KD,2H,4H,6H,8H,10H,QH,2S,4S,6S,8S,10S,QS,AC,3C,5C,7C,9C,JC,KC,2D,4D,6D,8D,10D,QD,AH,3H,5H,7H,9H,JH,KH
AS,2S,3S,4S,5S,6S,7S,8S,9S,10S,JS,QS,KS,AC,2C,3C,4C,5C,6C,7C,8C,9C,10C,JC,QC,KC,AD,2D,3D,4D,5D,6D,7D,8D,9D,10D,JD,QD,KD,AH,2H,3H,4H,5H,6H,7H,8H,9H,10H,JH,QH,KH
AS,AD,2S,2D,3S,3D,4S,4D,5S,5D,6S,6D,7S,7D,8S,8D,9S,9D,10S,10D,JS,JD,QS,QD,KS,KD,AC,AH,2C,2H,3C,3H,4C,4H,5C,5H,6C,6H,7C,7H,8C,8H,9C,9H,10C,10H,JC,JH,QC,QH,KC,KH
AS,AC,AD,AH,2S,2C,2D,2H,3S,3C,3D,3H,4S,4C,4D,4H,5S,5C,5D,5H,6S,6C,6D,6H,7S,7C,7D,7H,8S,8C,8D,8H,9S,9C,9D,9H,10S,10C,10D,10H,JS,JC,JD,JH,QS,QC,QD,QH,KS,KC,KD,KH
```
[Answer]
## J, 66 65 54 52 50 47 43 characters
```
26({.,@,.}.)^:(i.9),{'A23456789TJQK';'SCDH'
```
Output:
```
┌──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┐
│AS│AC│AD│AH│2S│2C│2D│2H│3S│3C│3D│3H│4S│4C│4D│4H│5S│5C│5D│5H│6S│6C│6D│6H│7S│7C│7D│7H│8S│8C│8D│8H│9S│9C│9D│9H│TS│TC│TD│TH│JS│JC│JD│JH│QS│QC│QD│QH│KS│KC│KD│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│7D│AC│7H│AD│8S│AH│8C│2S│8D│2C│8H│2D│9S│2H│9C│3S│9D│3C│9H│3D│TS│3H│TC│4S│TD│4C│TH│4D│JS│4H│JC│5S│JD│5C│JH│5D│QS│5H│QC│6S│QD│6C│QH│6D│KS│6H│KC│7S│KD│7C│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│4C│7D│TH│AC│4D│7H│JS│AD│4H│8S│JC│AH│5S│8C│JD│2S│5C│8D│JH│2C│5D│8H│QS│2D│5H│9S│QC│2H│6S│9C│QD│3S│6C│9D│QH│3C│6D│9H│KS│3D│6H│TS│KC│3H│7S│TC│KD│4S│7C│TD│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│9S│4C│QC│7D│2H│TH│6S│AC│9C│4D│QD│7H│3S│JS│6C│AD│9D│4H│QH│8S│3C│JC│6D│AH│9H│5S│KS│8C│3D│JD│6H│2S│TS│5C│KC│8D│3H│JH│7S│2C│TC│5D│KD│8H│4S│QS│7C│2D│TD│5H│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│5S│9S│KS│4C│8C│QC│3D│7D│JD│2H│6H│TH│2S│6S│TS│AC│5C│9C│KC│4D│8D│QD│3H│7H│JH│3S│7S│JS│2C│6C│TC│AD│5D│9D│KD│4H│8H│QH│4S│8S│QS│3C│7C│JC│2D│6D│TD│AH│5H│9H│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│3S│5S│7S│9S│JS│KS│2C│4C│6C│8C│TC│QC│AD│3D│5D│7D│9D│JD│KD│2H│4H│6H│8H│TH│QH│2S│4S│6S│8S│TS│QS│AC│3C│5C│7C│9C│JC│KC│2D│4D│6D│8D│TD│QD│AH│3H│5H│7H│9H│JH│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│2S│3S│4S│5S│6S│7S│8S│9S│TS│JS│QS│KS│AC│2C│3C│4C│5C│6C│7C│8C│9C│TC│JC│QC│KC│AD│2D│3D│4D│5D│6D│7D│8D│9D│TD│JD│QD│KD│AH│2H│3H│4H│5H│6H│7H│8H│9H│TH│JH│QH│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│AD│2S│2D│3S│3D│4S│4D│5S│5D│6S│6D│7S│7D│8S│8D│9S│9D│TS│TD│JS│JD│QS│QD│KS│KD│AC│AH│2C│2H│3C│3H│4C│4H│5C│5H│6C│6H│7C│7H│8C│8H│9C│9H│TC│TH│JC│JH│QC│QH│KC│KH│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┤
│AS│AC│AD│AH│2S│2C│2D│2H│3S│3C│3D│3H│4S│4C│4D│4H│5S│5C│5D│5H│6S│6C│6D│6H│7S│7C│7D│7H│8S│8C│8D│8H│9S│9C│9D│9H│TS│TC│TD│TH│JS│JC│JD│JH│QS│QC│QD│QH│KS│KC│KD│KH│
└──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘
```
I'm being forced further and further into J's tutorials and reference manuals to stay ahead here. :-S
[Answer]
## Haskell, 103
```
m(a:s,b:t)=a:b:m(s,t);m _=[]
main=mapM_ putStrLn.take 9.iterate(m.splitAt 26)$take 13.enumFrom=<<"🂡🃑🃁🂱"
```
Output:
```
🂡🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂬🂭🃑🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃜🃝🃁🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃌🃍🂱🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂼🂽
🂡🃁🂢🃂🂣🃃🂤🃄🂥🃅🂦🃆🂧🃇🂨🃈🂩🃉🂪🃊🂫🃋🂬🃌🂭🃍🃑🂱🃒🂲🃓🂳🃔🂴🃕🂵🃖🂶🃗🂷🃘🂸🃙🂹🃚🂺🃛🂻🃜🂼🃝🂽
🂡🃑🃁🂱🂢🃒🃂🂲🂣🃓🃃🂳🂤🃔🃄🂴🂥🃕🃅🂵🂦🃖🃆🂶🂧🃗🃇🂷🂨🃘🃈🂸🂩🃙🃉🂹🂪🃚🃊🂺🂫🃛🃋🂻🂬🃜🃌🂼🂭🃝🃍🂽
🂡🃇🃑🂷🃁🂨🂱🃘🂢🃈🃒🂸🃂🂩🂲🃙🂣🃉🃓🂹🃃🂪🂳🃚🂤🃊🃔🂺🃄🂫🂴🃛🂥🃋🃕🂻🃅🂬🂵🃜🂦🃌🃖🂼🃆🂭🂶🃝🂧🃍🃗🂽
🂡🃔🃇🂺🃑🃄🂷🂫🃁🂴🂨🃛🂱🂥🃘🃋🂢🃕🃈🂻🃒🃅🂸🂬🃂🂵🂩🃜🂲🂦🃙🃌🂣🃖🃉🂼🃓🃆🂹🂭🃃🂶🂪🃝🂳🂧🃚🃍🂤🃗🃊🂽
🂡🂩🃔🃜🃇🂲🂺🂦🃑🃙🃄🃌🂷🂣🂫🃖🃁🃉🂴🂼🂨🃓🃛🃆🂱🂹🂥🂭🃘🃃🃋🂶🂢🂪🃕🃝🃈🂳🂻🂧🃒🃚🃅🃍🂸🂤🂬🃗🃂🃊🂵🂽
🂡🂥🂩🂭🃔🃘🃜🃃🃇🃋🂲🂶🂺🂢🂦🂪🃑🃕🃙🃝🃄🃈🃌🂳🂷🂻🂣🂧🂫🃒🃖🃚🃁🃅🃉🃍🂴🂸🂼🂤🂨🂬🃓🃗🃛🃂🃆🃊🂱🂵🂹🂽
🂡🂣🂥🂧🂩🂫🂭🃒🃔🃖🃘🃚🃜🃁🃃🃅🃇🃉🃋🃍🂲🂴🂶🂸🂺🂼🂢🂤🂦🂨🂪🂬🃑🃓🃕🃗🃙🃛🃝🃂🃄🃆🃈🃊🃌🂱🂳🂵🂷🂹🂻🂽
🂡🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂬🂭🃑🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃜🃝🃁🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃌🃍🂱🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂼🂽
```
---
Don't know if there are any UTF-8 problems around here, shouldn't... this is a hex dump of the program
```
0000000 286d 3a61 2c73 3a62 2974 613d 623a 6d3a
0000010 7328 742c 3b29 206d 3d5f 5d5b 6d0a 6961
0000020 3d6e 616d 4d70 205f 7570 5374 7274 6e4c
0000030 742e 6b61 2065 2e39 7469 7265 7461 2865
0000040 2e6d 7073 696c 4174 2074 3632 2429 6174
0000050 656b 3120 2e33 6e65 6d75 7246 6d6f 3c3d
0000060 223c 9ff0 a182 9ff0 9183 9ff0 8183 9ff0
0000070 b182 0a22
0000074
```
and of the first output line
```
0000000 9ff0 a182 9ff0 a282 9ff0 a382 9ff0 a482
0000010 9ff0 a582 9ff0 a682 9ff0 a782 9ff0 a882
0000020 9ff0 a982 9ff0 aa82 9ff0 ab82 9ff0 ac82
0000030 9ff0 ad82 9ff0 9183 9ff0 9283 9ff0 9383
0000040 9ff0 9483 9ff0 9583 9ff0 9683 9ff0 9783
0000050 9ff0 9883 9ff0 9983 9ff0 9a83 9ff0 9b83
0000060 9ff0 9c83 9ff0 9d83 9ff0 8183 9ff0 8283
0000070 9ff0 8383 9ff0 8483 9ff0 8583 9ff0 8683
0000080 9ff0 8783 9ff0 8883 9ff0 8983 9ff0 8a83
0000090 9ff0 8b83 9ff0 8c83 9ff0 8d83 9ff0 b182
00000a0 9ff0 b282 9ff0 b382 9ff0 b482 9ff0 b582
00000b0 9ff0 b682 9ff0 b782 9ff0 b882 9ff0 b982
00000c0 9ff0 ba82 9ff0 bb82 9ff0 bc82 9ff0 bd82
00000d0 000a
00000d1
```
(the [unicode playing cards](http://en.wikipedia.org/wiki/Playing_Cards_%28Unicode_block%29))
[Answer]
## Python 2, 79 chars
```
d=zip("23456789TJQKA"*4,"CDHS"*13)
exec'print d;d[::2],d[1::2]=d[:26],d[26:];'*9
```
The output is a bit ugly but I believe it should count.
```
[('2', 'C'), ('3', 'D'), ('4', 'H'), ('5', 'S'), ('6', 'C'), ('7', 'D'), ('8', 'H'), ('9', 'S'), ('T', 'C'), ('J', 'D'), ('Q', 'H'), ('K', 'S'), ('A', 'C'), ('2', 'D'), ('3', 'H'), ('4', 'S'), ('5', 'C'), ('6', 'D'), ('7', 'H'), ('8', 'S'), ('9', 'C'), ('T', 'D'), ('J', 'H'), ('Q', 'S'), ('K', 'C'), ('A', 'D'), ('2', 'H'), ('3', 'S'), ('4', 'C'), ('5', 'D'), ('6', 'H'), ('7', 'S'), ('8', 'C'), ('9', 'D'), ('T', 'H'), ('J', 'S'), ('Q', 'C'), ('K', 'D'), ('A', 'H'), ('2', 'S'), ('3', 'C'), ('4', 'D'), ('5', 'H'), ('6', 'S'), ('7', 'C'), ('8', 'D'), ('9', 'H'), ('T', 'S'), ('J', 'C'), ('Q', 'D'), ('K', 'H'), ('A', 'S')]
[('2', 'C'), ('2', 'H'), ('3', 'D'), ('3', 'S'), ('4', 'H'), ('4', 'C'), ('5', 'S'), ('5', 'D'), ('6', 'C'), ('6', 'H'), ('7', 'D'), ('7', 'S'), ('8', 'H'), ('8', 'C'), ('9', 'S'), ('9', 'D'), ('T', 'C'), ('T', 'H'), ('J', 'D'), ('J', 'S'), ('Q', 'H'), ('Q', 'C'), ('K', 'S'), ('K', 'D'), ('A', 'C'), ('A', 'H'), ('2', 'D'), ('2', 'S'), ('3', 'H'), ('3', 'C'), ('4', 'S'), ('4', 'D'), ('5', 'C'), ('5', 'H'), ('6', 'D'), ('6', 'S'), ('7', 'H'), ('7', 'C'), ('8', 'S'), ('8', 'D'), ('9', 'C'), ('9', 'H'), ('T', 'D'), ('T', 'S'), ('J', 'H'), ('J', 'C'), ('Q', 'S'), ('Q', 'D'), ('K', 'C'), ('K', 'H'), ('A', 'D'), ('A', 'S')]
[('2', 'C'), ('2', 'D'), ('2', 'H'), ('2', 'S'), ('3', 'D'), ('3', 'H'), ('3', 'S'), ('3', 'C'), ('4', 'H'), ('4', 'S'), ('4', 'C'), ('4', 'D'), ('5', 'S'), ('5', 'C'), ('5', 'D'), ('5', 'H'), ('6', 'C'), ('6', 'D'), ('6', 'H'), ('6', 'S'), ('7', 'D'), ('7', 'H'), ('7', 'S'), ('7', 'C'), ('8', 'H'), ('8', 'S'), ('8', 'C'), ('8', 'D'), ('9', 'S'), ('9', 'C'), ('9', 'D'), ('9', 'H'), ('T', 'C'), ('T', 'D'), ('T', 'H'), ('T', 'S'), ('J', 'D'), ('J', 'H'), ('J', 'S'), ('J', 'C'), ('Q', 'H'), ('Q', 'S'), ('Q', 'C'), ('Q', 'D'), ('K', 'S'), ('K', 'C'), ('K', 'D'), ('K', 'H'), ('A', 'C'), ('A', 'D'), ('A', 'H'), ('A', 'S')]
[('2', 'C'), ('8', 'C'), ('2', 'D'), ('8', 'D'), ('2', 'H'), ('9', 'S'), ('2', 'S'), ('9', 'C'), ('3', 'D'), ('9', 'D'), ('3', 'H'), ('9', 'H'), ('3', 'S'), ('T', 'C'), ('3', 'C'), ('T', 'D'), ('4', 'H'), ('T', 'H'), ('4', 'S'), ('T', 'S'), ('4', 'C'), ('J', 'D'), ('4', 'D'), ('J', 'H'), ('5', 'S'), ('J', 'S'), ('5', 'C'), ('J', 'C'), ('5', 'D'), ('Q', 'H'), ('5', 'H'), ('Q', 'S'), ('6', 'C'), ('Q', 'C'), ('6', 'D'), ('Q', 'D'), ('6', 'H'), ('K', 'S'), ('6', 'S'), ('K', 'C'), ('7', 'D'), ('K', 'D'), ('7', 'H'), ('K', 'H'), ('7', 'S'), ('A', 'C'), ('7', 'C'), ('A', 'D'), ('8', 'H'), ('A', 'H'), ('8', 'S'), ('A', 'S')]
[('2', 'C'), ('5', 'C'), ('8', 'C'), ('J', 'C'), ('2', 'D'), ('5', 'D'), ('8', 'D'), ('Q', 'H'), ('2', 'H'), ('5', 'H'), ('9', 'S'), ('Q', 'S'), ('2', 'S'), ('6', 'C'), ('9', 'C'), ('Q', 'C'), ('3', 'D'), ('6', 'D'), ('9', 'D'), ('Q', 'D'), ('3', 'H'), ('6', 'H'), ('9', 'H'), ('K', 'S'), ('3', 'S'), ('6', 'S'), ('T', 'C'), ('K', 'C'), ('3', 'C'), ('7', 'D'), ('T', 'D'), ('K', 'D'), ('4', 'H'), ('7', 'H'), ('T', 'H'), ('K', 'H'), ('4', 'S'), ('7', 'S'), ('T', 'S'), ('A', 'C'), ('4', 'C'), ('7', 'C'), ('J', 'D'), ('A', 'D'), ('4', 'D'), ('8', 'H'), ('J', 'H'), ('A', 'H'), ('5', 'S'), ('8', 'S'), ('J', 'S'), ('A', 'S')]
[('2', 'C'), ('T', 'C'), ('5', 'C'), ('K', 'C'), ('8', 'C'), ('3', 'C'), ('J', 'C'), ('7', 'D'), ('2', 'D'), ('T', 'D'), ('5', 'D'), ('K', 'D'), ('8', 'D'), ('4', 'H'), ('Q', 'H'), ('7', 'H'), ('2', 'H'), ('T', 'H'), ('5', 'H'), ('K', 'H'), ('9', 'S'), ('4', 'S'), ('Q', 'S'), ('7', 'S'), ('2', 'S'), ('T', 'S'), ('6', 'C'), ('A', 'C'), ('9', 'C'), ('4', 'C'), ('Q', 'C'), ('7', 'C'), ('3', 'D'), ('J', 'D'), ('6', 'D'), ('A', 'D'), ('9', 'D'), ('4', 'D'), ('Q', 'D'), ('8', 'H'), ('3', 'H'), ('J', 'H'), ('6', 'H'), ('A', 'H'), ('9', 'H'), ('5', 'S'), ('K', 'S'), ('8', 'S'), ('3', 'S'), ('J', 'S'), ('6', 'S'), ('A', 'S')]
[('2', 'C'), ('6', 'C'), ('T', 'C'), ('A', 'C'), ('5', 'C'), ('9', 'C'), ('K', 'C'), ('4', 'C'), ('8', 'C'), ('Q', 'C'), ('3', 'C'), ('7', 'C'), ('J', 'C'), ('3', 'D'), ('7', 'D'), ('J', 'D'), ('2', 'D'), ('6', 'D'), ('T', 'D'), ('A', 'D'), ('5', 'D'), ('9', 'D'), ('K', 'D'), ('4', 'D'), ('8', 'D'), ('Q', 'D'), ('4', 'H'), ('8', 'H'), ('Q', 'H'), ('3', 'H'), ('7', 'H'), ('J', 'H'), ('2', 'H'), ('6', 'H'), ('T', 'H'), ('A', 'H'), ('5', 'H'), ('9', 'H'), ('K', 'H'), ('5', 'S'), ('9', 'S'), ('K', 'S'), ('4', 'S'), ('8', 'S'), ('Q', 'S'), ('3', 'S'), ('7', 'S'), ('J', 'S'), ('2', 'S'), ('6', 'S'), ('T', 'S'), ('A', 'S')]
[('2', 'C'), ('4', 'H'), ('6', 'C'), ('8', 'H'), ('T', 'C'), ('Q', 'H'), ('A', 'C'), ('3', 'H'), ('5', 'C'), ('7', 'H'), ('9', 'C'), ('J', 'H'), ('K', 'C'), ('2', 'H'), ('4', 'C'), ('6', 'H'), ('8', 'C'), ('T', 'H'), ('Q', 'C'), ('A', 'H'), ('3', 'C'), ('5', 'H'), ('7', 'C'), ('9', 'H'), ('J', 'C'), ('K', 'H'), ('3', 'D'), ('5', 'S'), ('7', 'D'), ('9', 'S'), ('J', 'D'), ('K', 'S'), ('2', 'D'), ('4', 'S'), ('6', 'D'), ('8', 'S'), ('T', 'D'), ('Q', 'S'), ('A', 'D'), ('3', 'S'), ('5', 'D'), ('7', 'S'), ('9', 'D'), ('J', 'S'), ('K', 'D'), ('2', 'S'), ('4', 'D'), ('6', 'S'), ('8', 'D'), ('T', 'S'), ('Q', 'D'), ('A', 'S')]
[('2', 'C'), ('3', 'D'), ('4', 'H'), ('5', 'S'), ('6', 'C'), ('7', 'D'), ('8', 'H'), ('9', 'S'), ('T', 'C'), ('J', 'D'), ('Q', 'H'), ('K', 'S'), ('A', 'C'), ('2', 'D'), ('3', 'H'), ('4', 'S'), ('5', 'C'), ('6', 'D'), ('7', 'H'), ('8', 'S'), ('9', 'C'), ('T', 'D'), ('J', 'H'), ('Q', 'S'), ('K', 'C'), ('A', 'D'), ('2', 'H'), ('3', 'S'), ('4', 'C'), ('5', 'D'), ('6', 'H'), ('7', 'S'), ('8', 'C'), ('9', 'D'), ('T', 'H'), ('J', 'S'), ('Q', 'C'), ('K', 'D'), ('A', 'H'), ('2', 'S'), ('3', 'C'), ('4', 'D'), ('5', 'H'), ('6', 'S'), ('7', 'C'), ('8', 'D'), ('9', 'H'), ('T', 'S'), ('J', 'C'), ('Q', 'D'), ('K', 'H'), ('A', 'S')]
```
[Answer]
## Python2, 104
This is similar to Ev\_Genus's solution. I put suit before rank because it enables me to save a character.
```
d=[s+[r,`10`][r>"Q"]for r in'A23456789ZJQK'for s in"SCDH"]
exec'print d;d=sum(zip(d[:26],d[26:]),());'*9
```
**Output**
```
['SA', 'CA', 'DA', 'HA', 'S2', 'C2', 'D2', 'H2', 'S3', 'C3', 'D3', 'H3', 'S4', 'C4', 'D4', 'H4', 'S5', 'C5', 'D5', 'H5', 'S6', 'C6', 'D6', 'H6', 'S7', 'C7', 'D7', 'H7', 'S8', 'C8', 'D8', 'H8', 'S9', 'C9', 'D9', 'H9', 'S10', 'C10', 'D10', 'H10', 'SJ', 'CJ', 'DJ', 'HJ', 'SQ', 'CQ', 'DQ', 'HQ', 'SK', 'CK', 'DK', 'HK']
('SA', 'D7', 'CA', 'H7', 'DA', 'S8', 'HA', 'C8', 'S2', 'D8', 'C2', 'H8', 'D2', 'S9', 'H2', 'C9', 'S3', 'D9', 'C3', 'H9', 'D3', 'S10', 'H3', 'C10', 'S4', 'D10', 'C4', 'H10', 'D4', 'SJ', 'H4', 'CJ', 'S5', 'DJ', 'C5', 'HJ', 'D5', 'SQ', 'H5', 'CQ', 'S6', 'DQ', 'C6', 'HQ', 'D6', 'SK', 'H6', 'CK', 'S7', 'DK', 'C7', 'HK')
('SA', 'C4', 'D7', 'H10', 'CA', 'D4', 'H7', 'SJ', 'DA', 'H4', 'S8', 'CJ', 'HA', 'S5', 'C8', 'DJ', 'S2', 'C5', 'D8', 'HJ', 'C2', 'D5', 'H8', 'SQ', 'D2', 'H5', 'S9', 'CQ', 'H2', 'S6', 'C9', 'DQ', 'S3', 'C6', 'D9', 'HQ', 'C3', 'D6', 'H9', 'SK', 'D3', 'H6', 'S10', 'CK', 'H3', 'S7', 'C10', 'DK', 'S4', 'C7', 'D10', 'HK')
('SA', 'S9', 'C4', 'CQ', 'D7', 'H2', 'H10', 'S6', 'CA', 'C9', 'D4', 'DQ', 'H7', 'S3', 'SJ', 'C6', 'DA', 'D9', 'H4', 'HQ', 'S8', 'C3', 'CJ', 'D6', 'HA', 'H9', 'S5', 'SK', 'C8', 'D3', 'DJ', 'H6', 'S2', 'S10', 'C5', 'CK', 'D8', 'H3', 'HJ', 'S7', 'C2', 'C10', 'D5', 'DK', 'H8', 'S4', 'SQ', 'C7', 'D2', 'D10', 'H5', 'HK')
('SA', 'S5', 'S9', 'SK', 'C4', 'C8', 'CQ', 'D3', 'D7', 'DJ', 'H2', 'H6', 'H10', 'S2', 'S6', 'S10', 'CA', 'C5', 'C9', 'CK', 'D4', 'D8', 'DQ', 'H3', 'H7', 'HJ', 'S3', 'S7', 'SJ', 'C2', 'C6', 'C10', 'DA', 'D5', 'D9', 'DK', 'H4', 'H8', 'HQ', 'S4', 'S8', 'SQ', 'C3', 'C7', 'CJ', 'D2', 'D6', 'D10', 'HA', 'H5', 'H9', 'HK')
('SA', 'S3', 'S5', 'S7', 'S9', 'SJ', 'SK', 'C2', 'C4', 'C6', 'C8', 'C10', 'CQ', 'DA', 'D3', 'D5', 'D7', 'D9', 'DJ', 'DK', 'H2', 'H4', 'H6', 'H8', 'H10', 'HQ', 'S2', 'S4', 'S6', 'S8', 'S10', 'SQ', 'CA', 'C3', 'C5', 'C7', 'C9', 'CJ', 'CK', 'D2', 'D4', 'D6', 'D8', 'D10', 'DQ', 'HA', 'H3', 'H5', 'H7', 'H9', 'HJ', 'HK')
('SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'S10', 'SJ', 'SQ', 'SK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'CJ', 'CQ', 'CK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'DJ', 'DQ', 'DK', 'HA', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'H10', 'HJ', 'HQ', 'HK')
('SA', 'DA', 'S2', 'D2', 'S3', 'D3', 'S4', 'D4', 'S5', 'D5', 'S6', 'D6', 'S7', 'D7', 'S8', 'D8', 'S9', 'D9', 'S10', 'D10', 'SJ', 'DJ', 'SQ', 'DQ', 'SK', 'DK', 'CA', 'HA', 'C2', 'H2', 'C3', 'H3', 'C4', 'H4', 'C5', 'H5', 'C6', 'H6', 'C7', 'H7', 'C8', 'H8', 'C9', 'H9', 'C10', 'H10', 'CJ', 'HJ', 'CQ', 'HQ', 'CK', 'HK')
('SA', 'CA', 'DA', 'HA', 'S2', 'C2', 'D2', 'H2', 'S3', 'C3', 'D3', 'H3', 'S4', 'C4', 'D4', 'H4', 'S5', 'C5', 'D5', 'H5', 'S6', 'C6', 'D6', 'H6', 'S7', 'C7', 'D7', 'H7', 'S8', 'C8', 'D8', 'H8', 'S9', 'C9', 'D9', 'H9', 'S10', 'C10', 'D10', 'H10', 'SJ', 'CJ', 'DJ', 'HJ', 'SQ', 'CQ', 'DQ', 'HQ', 'SK', 'CK', 'DK', 'HK')
```
[Answer]
## APL (42)
```
{↑{⍉2 26⍴⍵}⍣⍵,'A23456789TJQK'∘.,'SCDH'}¨⍳9
```
Output is top-down instead of left-right (but it's still human readable so I guess it's not against the rules).
Output:
```
AS AS AS AS AS AS AS AS AS
7D 4C 9S 5S 3S 2S AD AC 7D
AC 7D 4C 9S 5S 3S 2S AD AC
7H TH QC KS 7S 4S 2D AH 7H
AD AC 7D 4C 9S 5S 3S 2S AD
8S 4D 2H 8C JS 6S 3D 2C 8S
AH 7H TH QC KS 7S 4S 2D AH
8C JS 6S 3D 2C 8S 4D 2H 8C
2S AD AC 7D 4C 9S 5S 3S 2S
8D 4H 9C JD 6C TS 5D 3C 8D
2C 8S 4D 2H 8C JS 6S 3D 2C
8H JC QD 6H TC QS 6D 3H 8H
2D AH 7H TH QC KS 7S 4S 2D
9S 5S 3S 2S AD AC 7D 4C 9S
2H 8C JS 6S 3D 2C 8S 4D 2H
9C JD 6C TS 5D 3C 8D 4H 9C
3S 2S AD AC 7D 4C 9S 5S 3S
9D 5C 9D 5C 9D 5C 9D 5C 9D
3C 8D 4H 9C JD 6C TS 5D 3C
9H JH QH KC KD 7C TD 5H 9H
3D 2C 8S 4D 2H 8C JS 6S 3D
TS 5D 3C 8D 4H 9C JD 6C TS
3H 8H JC QD 6H TC QS 6D 3H
TC QS 6D 3H 8H JC QD 6H TC
4S 2D AH 7H TH QC KS 7S 4S
TD 5H 9H JH QH KC KD 7C TD
4C 9S 5S 3S 2S AD AC 7D 4C
TH QC KS 7S 4S 2D AH 7H TH
4D 2H 8C JS 6S 3D 2C 8S 4D
JS 6S 3D 2C 8S 4D 2H 8C JS
4H 9C JD 6C TS 5D 3C 8D 4H
JC QD 6H TC QS 6D 3H 8H JC
5S 3S 2S AD AC 7D 4C 9S 5S
JD 6C TS 5D 3C 8D 4H 9C JD
5C 9D 5C 9D 5C 9D 5C 9D 5C
JH QH KC KD 7C TD 5H 9H JH
5D 3C 8D 4H 9C JD 6C TS 5D
QS 6D 3H 8H JC QD 6H TC QS
5H 9H JH QH KC KD 7C TD 5H
QC KS 7S 4S 2D AH 7H TH QC
6S 3D 2C 8S 4D 2H 8C JS 6S
QD 6H TC QS 6D 3H 8H JC QD
6C TS 5D 3C 8D 4H 9C JD 6C
QH KC KD 7C TD 5H 9H JH QH
6D 3H 8H JC QD 6H TC QS 6D
KS 7S 4S 2D AH 7H TH QC KS
6H TC QS 6D 3H 8H JC QD 6H
KC KD 7C TD 5H 9H JH QH KC
7S 4S 2D AH 7H TH QC KS 7S
KD 7C TD 5H 9H JH QH KC KD
7C TD 5H 9H JH QH KC KD 7C
KH KH KH KH KH KH KH KH KH
```
[Answer]
# K, 55 53 51
```
{$,/(,').`$2 26#x}\[8;,/"A23456789TJQK",/:\:"SCDH"]
```
Shaved 2 chars by changing from symbol representation to string
output
```
k){$,/(,').`$(2 26)#x}\[8;,/"A23456789TJQK",/:\:"SCDH"]
"AS" "AC" "AD" "AH" "2S" "2C" "2D" "2H" "3S" "3C" "3D" "3H" "4S" "4C" "4D" "4H" "5S" "5C" "5D" "5H" "6S" "6C" "6D" "6H" "7S" "7C" "7D" "7H" "8S" "8C" "8D" "8H" "9S" "9C" "9D" "9H" "TS" "TC" "TD" "TH" "JS" "JC" "JD" "JH" "QS" "QC" "QD" "QH" "KS" "KC" "KD" "KH"
"AS" "7D" "AC" "7H" "AD" "8S" "AH" "8C" "2S" "8D" "2C" "8H" "2D" "9S" "2H" "9C" "3S" "9D" "3C" "9H" "3D" "TS" "3H" "TC" "4S" "TD" "4C" "TH" "4D" "JS" "4H" "JC" "5S" "JD" "5C" "JH" "5D" "QS" "5H" "QC" "6S" "QD" "6C" "QH" "6D" "KS" "6H" "KC" "7S" "KD" "7C" "KH"
"AS" "4C" "7D" "TH" "AC" "4D" "7H" "JS" "AD" "4H" "8S" "JC" "AH" "5S" "8C" "JD" "2S" "5C" "8D" "JH" "2C" "5D" "8H" "QS" "2D" "5H" "9S" "QC" "2H" "6S" "9C" "QD" "3S" "6C" "9D" "QH" "3C" "6D" "9H" "KS" "3D" "6H" "TS" "KC" "3H" "7S" "TC" "KD" "4S" "7C" "TD" "KH"
"AS" "9S" "4C" "QC" "7D" "2H" "TH" "6S" "AC" "9C" "4D" "QD" "7H" "3S" "JS" "6C" "AD" "9D" "4H" "QH" "8S" "3C" "JC" "6D" "AH" "9H" "5S" "KS" "8C" "3D" "JD" "6H" "2S" "TS" "5C" "KC" "8D" "3H" "JH" "7S" "2C" "TC" "5D" "KD" "8H" "4S" "QS" "7C" "2D" "TD" "5H" "KH"
"AS" "5S" "9S" "KS" "4C" "8C" "QC" "3D" "7D" "JD" "2H" "6H" "TH" "2S" "6S" "TS" "AC" "5C" "9C" "KC" "4D" "8D" "QD" "3H" "7H" "JH" "3S" "7S" "JS" "2C" "6C" "TC" "AD" "5D" "9D" "KD" "4H" "8H" "QH" "4S" "8S" "QS" "3C" "7C" "JC" "2D" "6D" "TD" "AH" "5H" "9H" "KH"
"AS" "3S" "5S" "7S" "9S" "JS" "KS" "2C" "4C" "6C" "8C" "TC" "QC" "AD" "3D" "5D" "7D" "9D" "JD" "KD" "2H" "4H" "6H" "8H" "TH" "QH" "2S" "4S" "6S" "8S" "TS" "QS" "AC" "3C" "5C" "7C" "9C" "JC" "KC" "2D" "4D" "6D" "8D" "TD" "QD" "AH" "3H" "5H" "7H" "9H" "JH" "KH"
"AS" "2S" "3S" "4S" "5S" "6S" "7S" "8S" "9S" "TS" "JS" "QS" "KS" "AC" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C" "TC" "JC" "QC" "KC" "AD" "2D" "3D" "4D" "5D" "6D" "7D" "8D" "9D" "TD" "JD" "QD" "KD" "AH" "2H" "3H" "4H" "5H" "6H" "7H" "8H" "9H" "TH" "JH" "QH" "KH"
"AS" "AD" "2S" "2D" "3S" "3D" "4S" "4D" "5S" "5D" "6S" "6D" "7S" "7D" "8S" "8D" "9S" "9D" "TS" "TD" "JS" "JD" "QS" "QD" "KS" "KD" "AC" "AH" "2C" "2H" "3C" "3H" "4C" "4H" "5C" "5H" "6C" "6H" "7C" "7H" "8C" "8H" "9C" "9H" "TC" "TH" "JC" "JH" "QC" "QH" "KC" "KH"
"AS" "AC" "AD" "AH" "2S" "2C" "2D" "2H" "3S" "3C" "3D" "3H" "4S" "4C" "4D" "4H" "5S" "5C" "5D" "5H" "6S" "6C" "6D" "6H" "7S" "7C" "7D" "7H" "8S" "8C" "8D" "8H" "9S" "9C" "9D" "9H" "TS" "TC" "TD" "TH" "JS" "JC" "JD" "JH" "QS" "QC" "QD" "QH" "KS" "KC" "KD" "KH"
k)@[a;0]~@[;8]a:{$,/(,').`$(2 26)#x}\[8;,/"A23456789TJQK",/:\:"SCDH"] /8th iteration identical to the first?
1b
```
[Answer]
## Ruby 1.9 (~~95~~ ~~93~~ 87)
```
a=(0..51).map{|i|:A23456789TJQK[i/4]+:SCDH[i%4]}
9.times{p a;a=a.zip(a.pop 26).flatten}
```
Output:
```
["AS", "AC", "AD", "AH", "2S", "2C", "2D", "2H", "3S", "3C", "3D", "3H", "4S", "4C", "4D", "4H", "5S", "5C", "5D", "5H", "6S", "6C", "6D", "6H", "7S", "7C", "7D", "7H", "8S", "8C", "8D", "8H", "9S", "9C", "9D", "9H", "TS", "TC", "TD", "TH", "JS", "JC", "JD", "JH", "QS", "QC", "QD", "QH", "KS", "KC", "KD", "KH"]
["AS", "7D", "AC", "7H", "AD", "8S", "AH", "8C", "2S", "8D", "2C", "8H", "2D", "9S", "2H", "9C", "3S", "9D", "3C", "9H", "3D", "TS", "3H", "TC", "4S", "TD", "4C", "TH", "4D", "JS", "4H", "JC", "5S", "JD", "5C", "JH", "5D", "QS", "5H", "QC", "6S", "QD", "6C", "QH", "6D", "KS", "6H", "KC", "7S", "KD", "7C", "KH"]
["AS", "4C", "7D", "TH", "AC", "4D", "7H", "JS", "AD", "4H", "8S", "JC", "AH", "5S", "8C", "JD", "2S", "5C", "8D", "JH", "2C", "5D", "8H", "QS", "2D", "5H", "9S", "QC", "2H", "6S", "9C", "QD", "3S", "6C", "9D", "QH", "3C", "6D", "9H", "KS", "3D", "6H", "TS", "KC", "3H", "7S", "TC", "KD", "4S", "7C", "TD", "KH"]
["AS", "9S", "4C", "QC", "7D", "2H", "TH", "6S", "AC", "9C", "4D", "QD", "7H", "3S", "JS", "6C", "AD", "9D", "4H", "QH", "8S", "3C", "JC", "6D", "AH", "9H", "5S", "KS", "8C", "3D", "JD", "6H", "2S", "TS", "5C", "KC", "8D", "3H", "JH", "7S", "2C", "TC", "5D", "KD", "8H", "4S", "QS", "7C", "2D", "TD", "5H", "KH"]
["AS", "5S", "9S", "KS", "4C", "8C", "QC", "3D", "7D", "JD", "2H", "6H", "TH", "2S", "6S", "TS", "AC", "5C", "9C", "KC", "4D", "8D", "QD", "3H", "7H", "JH", "3S", "7S", "JS", "2C", "6C", "TC", "AD", "5D", "9D", "KD", "4H", "8H", "QH", "4S", "8S", "QS", "3C", "7C", "JC", "2D", "6D", "TD", "AH", "5H", "9H", "KH"]
["AS", "3S", "5S", "7S", "9S", "JS", "KS", "2C", "4C", "6C", "8C", "TC", "QC", "AD", "3D", "5D", "7D", "9D", "JD", "KD", "2H", "4H", "6H", "8H", "TH", "QH", "2S", "4S", "6S", "8S", "TS", "QS", "AC", "3C", "5C", "7C", "9C", "JC", "KC", "2D", "4D", "6D", "8D", "TD", "QD", "AH", "3H", "5H", "7H", "9H", "JH", "KH"]
["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH"]
["AS", "AD", "2S", "2D", "3S", "3D", "4S", "4D", "5S", "5D", "6S", "6D", "7S", "7D", "8S", "8D", "9S", "9D", "TS", "TD", "JS", "JD", "QS", "QD", "KS", "KD", "AC", "AH", "2C", "2H", "3C", "3H", "4C", "4H", "5C", "5H", "6C", "6H", "7C", "7H", "8C", "8H", "9C", "9H", "TC", "TH", "JC", "JH", "QC", "QH", "KC", "KH"]
["AS", "AC", "AD", "AH", "2S", "2C", "2D", "2H", "3S", "3C", "3D", "3H", "4S", "4C", "4D", "4H", "5S", "5C", "5D", "5H", "6S", "6C", "6D", "6H", "7S", "7C", "7D", "7H", "8S", "8C", "8D", "8H", "9S", "9C", "9D", "9H", "TS", "TC", "TD", "TH", "JS", "JC", "JD", "JH", "QS", "QC", "QD", "QH", "KS", "KC", "KD", "KH"]
```
[Answer]
### Python3, 180 179
```
from itertools import*;i=list(map("".join,product("A23456789XJQK","SCDH")));exec('print(",".join(i).replace("X","10"));i=list(chain(*zip(islice(i,0,26,1),islice(i,26,52,1))));'*8)
```
Outputs lines like in task.
### Native Format 151
```
from itertools import*;i=list(map("".join,product("A23456789TJQK","SCDH")));exec('print(i);i=list(chain(*zip(islice(i,0,26,1),islice(i,26,52,1))));'*8)
```
Output is like in Ruby version.
[Answer]
### GolfScript, 51 50 46 characters
```
"A23456789TJQK"4*"SCDH"13*]{zip""*2/.p 26/}9*;
```
This GolfScript code yields the following output (see [here](http://golfscript.apphb.com/?c=IkEyMzQ1Njc4OVRKUUsiNCoiU0NESCIxMypde3ppcCIiKjIvLnAgMjYvfTkqOw%3D%3D)):
```
["AS" "2C" "3D" "4H" "5S" "6C" "7D" "8H" "9S" "TC" "JD" "QH" "KS" "AC" "2D" "3H" "4S" "5C" "6D" "7H" "8S" "9C" "TD" "JH" "QS" "KC" "AD" "2H" "3S" "4C" "5D" "6H" "7S" "8C" "9D" "TH" "JS" "QC" "KD" "AH" "2S" "3C" "4D" "5H" "6S" "7C" "8D" "9H" "TS" "JC" "QD" "KH"]
["AS" "AD" "2C" "2H" "3D" "3S" "4H" "4C" "5S" "5D" "6C" "6H" "7D" "7S" "8H" "8C" "9S" "9D" "TC" "TH" "JD" "JS" "QH" "QC" "KS" "KD" "AC" "AH" "2D" "2S" "3H" "3C" "4S" "4D" "5C" "5H" "6D" "6S" "7H" "7C" "8S" "8D" "9C" "9H" "TD" "TS" "JH" "JC" "QS" "QD" "KC" "KH"]
["AS" "AC" "AD" "AH" "2C" "2D" "2H" "2S" "3D" "3H" "3S" "3C" "4H" "4S" "4C" "4D" "5S" "5C" "5D" "5H" "6C" "6D" "6H" "6S" "7D" "7H" "7S" "7C" "8H" "8S" "8C" "8D" "9S" "9C" "9D" "9H" "TC" "TD" "TH" "TS" "JD" "JH" "JS" "JC" "QH" "QS" "QC" "QD" "KS" "KC" "KD" "KH"]
["AS" "7S" "AC" "7C" "AD" "8H" "AH" "8S" "2C" "8C" "2D" "8D" "2H" "9S" "2S" "9C" "3D" "9D" "3H" "9H" "3S" "TC" "3C" "TD" "4H" "TH" "4S" "TS" "4C" "JD" "4D" "JH" "5S" "JS" "5C" "JC" "5D" "QH" "5H" "QS" "6C" "QC" "6D" "QD" "6H" "KS" "6S" "KC" "7D" "KD" "7H" "KH"]
["AS" "4S" "7S" "TS" "AC" "4C" "7C" "JD" "AD" "4D" "8H" "JH" "AH" "5S" "8S" "JS" "2C" "5C" "8C" "JC" "2D" "5D" "8D" "QH" "2H" "5H" "9S" "QS" "2S" "6C" "9C" "QC" "3D" "6D" "9D" "QD" "3H" "6H" "9H" "KS" "3S" "6S" "TC" "KC" "3C" "7D" "TD" "KD" "4H" "7H" "TH" "KH"]
["AS" "9S" "4S" "QS" "7S" "2S" "TS" "6C" "AC" "9C" "4C" "QC" "7C" "3D" "JD" "6D" "AD" "9D" "4D" "QD" "8H" "3H" "JH" "6H" "AH" "9H" "5S" "KS" "8S" "3S" "JS" "6S" "2C" "TC" "5C" "KC" "8C" "3C" "JC" "7D" "2D" "TD" "5D" "KD" "8D" "4H" "QH" "7H" "2H" "TH" "5H" "KH"]
["AS" "5S" "9S" "KS" "4S" "8S" "QS" "3S" "7S" "JS" "2S" "6S" "TS" "2C" "6C" "TC" "AC" "5C" "9C" "KC" "4C" "8C" "QC" "3C" "7C" "JC" "3D" "7D" "JD" "2D" "6D" "TD" "AD" "5D" "9D" "KD" "4D" "8D" "QD" "4H" "8H" "QH" "3H" "7H" "JH" "2H" "6H" "TH" "AH" "5H" "9H" "KH"]
["AS" "3D" "5S" "7D" "9S" "JD" "KS" "2D" "4S" "6D" "8S" "TD" "QS" "AD" "3S" "5D" "7S" "9D" "JS" "KD" "2S" "4D" "6S" "8D" "TS" "QD" "2C" "4H" "6C" "8H" "TC" "QH" "AC" "3H" "5C" "7H" "9C" "JH" "KC" "2H" "4C" "6H" "8C" "TH" "QC" "AH" "3C" "5H" "7C" "9H" "JC" "KH"]
["AS" "2C" "3D" "4H" "5S" "6C" "7D" "8H" "9S" "TC" "JD" "QH" "KS" "AC" "2D" "3H" "4S" "5C" "6D" "7H" "8S" "9C" "TD" "JH" "QS" "KC" "AD" "2H" "3S" "4C" "5D" "6H" "7S" "8C" "9D" "TH" "JS" "QC" "KD" "AH" "2S" "3C" "4D" "5H" "6S" "7C" "8D" "9H" "TS" "JC" "QD" "KH"]
```
[Answer]
### Perl, 91 chars
Any suggestions on a more concise way of building the initial deck? My approach uses 2 substitutions to build `$_` and then a global match in list context to initialize `@_`.
The shuffling is then done by repeatedly `splice`ing `@_` onto `@a` and interleaving the two lists with `map` back into `@_`.
```
s//A23456789TJQK/,s/(.)/$1S$1C$1D$1H/g,@_=/../g;say@_=map{shift@_,$_}@a=splice@_,26for 0..8
```
[Answer]
# Mathematica 131 129 120 114 100 86 chars
With help from Mr.Wizard:
```
NestList[Riffle @@ #~Partition~26 &, # <> "" & /@ Tuples@Characters@
{"A23456789TJQK", "HDCS"}, 8]
```
Output:

[Answer]
# CJam, 34 bytes
CJam is newer than the question, so this answer doesn't compete for the green checkmark, but I thought this would be a nice problem to try in CJam.
```
A,2>s"TJQKA"+"SCDH"m*{_p26/z:~}8*p
```
[Test it here.](http://cjam.aditsu.net/)
It prints the output like
```
["2S" "2C" "2D" "2H" "3S" "3C" "3D" "3H" "4S" "4C" "4D" "4H" "5S" "5C" "5D" "5H" "6S" "6C" "6D" "6H" "7S" "7C" "7D" "7H" "8S" "8C" "8D" "8H" "9S" "9C" "9D" "9H" "TS" "TC" "TD" "TH" "JS" "JC" "JD" "JH" "QS" "QC" "QD" "QH" "KS" "KC" "KD" "KH" "AS" "AC" "AD" "AH"]
["2S" "8D" "2C" "8H" "2D" "9S" "2H" "9C" "3S" "9D" "3C" "9H" "3D" "TS" "3H" "TC" "4S" "TD" "4C" "TH" "4D" "JS" "4H" "JC" "5S" "JD" "5C" "JH" "5D" "QS" "5H" "QC" "6S" "QD" "6C" "QH" "6D" "KS" "6H" "KC" "7S" "KD" "7C" "KH" "7D" "AS" "7H" "AC" "8S" "AD" "8C" "AH"]
["2S" "5C" "8D" "JH" "2C" "5D" "8H" "QS" "2D" "5H" "9S" "QC" "2H" "6S" "9C" "QD" "3S" "6C" "9D" "QH" "3C" "6D" "9H" "KS" "3D" "6H" "TS" "KC" "3H" "7S" "TC" "KD" "4S" "7C" "TD" "KH" "4C" "7D" "TH" "AS" "4D" "7H" "JS" "AC" "4H" "8S" "JC" "AD" "5S" "8C" "JD" "AH"]
["2S" "TS" "5C" "KC" "8D" "3H" "JH" "7S" "2C" "TC" "5D" "KD" "8H" "4S" "QS" "7C" "2D" "TD" "5H" "KH" "9S" "4C" "QC" "7D" "2H" "TH" "6S" "AS" "9C" "4D" "QD" "7H" "3S" "JS" "6C" "AC" "9D" "4H" "QH" "8S" "3C" "JC" "6D" "AD" "9H" "5S" "KS" "8C" "3D" "JD" "6H" "AH"]
["2S" "6S" "TS" "AS" "5C" "9C" "KC" "4D" "8D" "QD" "3H" "7H" "JH" "3S" "7S" "JS" "2C" "6C" "TC" "AC" "5D" "9D" "KD" "4H" "8H" "QH" "4S" "8S" "QS" "3C" "7C" "JC" "2D" "6D" "TD" "AD" "5H" "9H" "KH" "5S" "9S" "KS" "4C" "8C" "QC" "3D" "7D" "JD" "2H" "6H" "TH" "AH"]
["2S" "4S" "6S" "8S" "TS" "QS" "AS" "3C" "5C" "7C" "9C" "JC" "KC" "2D" "4D" "6D" "8D" "TD" "QD" "AD" "3H" "5H" "7H" "9H" "JH" "KH" "3S" "5S" "7S" "9S" "JS" "KS" "2C" "4C" "6C" "8C" "TC" "QC" "AC" "3D" "5D" "7D" "9D" "JD" "KD" "2H" "4H" "6H" "8H" "TH" "QH" "AH"]
["2S" "3S" "4S" "5S" "6S" "7S" "8S" "9S" "TS" "JS" "QS" "KS" "AS" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C" "TC" "JC" "QC" "KC" "AC" "2D" "3D" "4D" "5D" "6D" "7D" "8D" "9D" "TD" "JD" "QD" "KD" "AD" "2H" "3H" "4H" "5H" "6H" "7H" "8H" "9H" "TH" "JH" "QH" "KH" "AH"]
["2S" "2D" "3S" "3D" "4S" "4D" "5S" "5D" "6S" "6D" "7S" "7D" "8S" "8D" "9S" "9D" "TS" "TD" "JS" "JD" "QS" "QD" "KS" "KD" "AS" "AD" "2C" "2H" "3C" "3H" "4C" "4H" "5C" "5H" "6C" "6H" "7C" "7H" "8C" "8H" "9C" "9H" "TC" "TH" "JC" "JH" "QC" "QH" "KC" "KH" "AC" "AH"]
["2S" "2C" "2D" "2H" "3S" "3C" "3D" "3H" "4S" "4C" "4D" "4H" "5S" "5C" "5D" "5H" "6S" "6C" "6D" "6H" "7S" "7C" "7D" "7H" "8S" "8C" "8D" "8H" "9S" "9C" "9D" "9H" "TS" "TC" "TD" "TH" "JS" "JC" "JD" "JH" "QS" "QC" "QD" "QH" "KS" "KC" "KD" "KH" "AS" "AC" "AD" "AH"]
```
## Explanation
```
A,2>s"TJQKA"+"SCDH"m*{_p26/z:~}8*p
A, "Get the range from 0 to 9.";
2> "Slice off first two elements.";
s "Convert to string '23456789'.";
"TJQKA"+ "Append this string.";
"SCDH" "Push the suits.";
m* "Take the Cartesian product. This yields the first line.";
{ }8* "Execute this block 8 times.";
_p "Duplicate the last line and print it.";
26/ "Split the array into halves.";
z "Zip, i.e. transpose the array.";
:~ "Flatten the array.";
p "Print the final deck.";
```
[Answer]
# [R](https://www.r-project.org/), 97 bytes
Saved a few bytes with a convenient out-of-order deck
```
d=paste(rep(c(2:10,"A","J","Q","K"),4),quote(S(C,D,H)))
for(i in 1:9)print(d<-c(t(matrix(d,26))))
```
[Try it online!](https://tio.run/##K/r/P8W2ILG4JFWjKLVAI1nDyMrQQEfJUUlHyQuIA4HYW0lTx0RTp7A0H6goWMNZx0XHQ1NTkystv0gjUyEzT8HQylKzoCgzr0QjxUY3WaNEIzexpCizQiNFx8gMqFDz/38A "R – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 753 bytes
```
/*/\/\///}/S,*'/C,*"/D,*;/H,*b/A'*c/A"*d/A;*e/2}*f/2'*g/2"*h/2;*i/3}*j/3'*k/3"*l/3;*m/4}*n/4'*o/4"*p/4;*q/5}*r/5'*s/5"*t/5;*u/6}*v/6'*w/6"*x/6;*y/7}*z/7'*-/7"*B/7;*+/8}*!/8'*E/8"*F/8;*G/9}*@/9'*I/9"*_/9;*(/10}*L/10'*M/10"*N/10;*O/J}*P/J'*)/J"*R/J;*$/Q}*T/Q'*U/Q"*V/Q;*W/K}*X/K'*Y/K"*{/KH
A}/A}bcdefghijklmnopqrstuvwxyz-B+!EFG@I_(LMNOP)R$TUVWXY{-bBc+d!eEfFgGh@iIj_k(lLmMnNoOpPq)rRs$tTuUvVwWxXyYz{n-NboBOcp+Pdq!)erERfsF$gtGThu@UivIVjw_Wkx(XlyLYmzM{GnT-hNub@oUBiOvcIpV+jPwd_qW!k)xe(rXElRyfLsYFm$zgMt{qGWn!Tk-)hxNeu(br@XoEUlBRiyOfvLcsIYpFVm+$jzPgwMdt_{iqyGOWfnv!LTcks-I)YhpxFNVemu+($bjrz@PXgowEMUdltB_R{eimquy+G(O$Wbfjnrvz!@LPTXcgkosw-EIM)UYdhlptxBF_NRV{cegikmoqsuwy-+EGI(MO)$UWYbdfhjlnprtvxzB!F@_LNPRTVX{bcdefghijklmnopqrstuvwxyz-B+!EFG@I_(LMNOP)R$TUVWXYKH
```
[Try it online!](https://tio.run/##ldFZbqMIFEDR/9oFCAl4xHpVmSN@MF1AiJlCYQapJNTYmNFgM5lBrD2dLbSudDZw2/LfNo3bry8E/Psd4op/7oDGf@6AxN93wOP7HUS4peGAWxKOuOUhxvsVTnhPQ4L3JKR4z0OGDyvk@EBDgQ8klPjAwxkfV6jwkYYaH0m44CMPV3xaocEnGlp8IqHDJx56fF5hwGcabvhMwojPPEz4ssKMLzRs8IUEEV944PB1BQJfaZDwlQQZX3lQ8G0FAd9oUPGNhBDfeGDw188VtG9p0L8lwfiWBxM/VrDwgwYWP0iw8YMHCj9XcPCThj1@kuDiJw8e7lbwcUdDgDsSFty9/9iuuF2jwzE@JWmWF@W5qi/Xpu364TZO80bkCElWBDVkNN0wLdamnL3r@cGyicQDdyRi6SQnSipkah4WTKmd9cqozYt1ZRu7pTqn3w/uzRv9KZiXamNEtWgeLpx1vBJs3Ej2qZWppFOctBf22aC6@S30ipHxy0kLzrO@KJWzSY0@Euq9mJnDQb24XG7djuHVIwp2jJnGl0p7OmltIJ@pOdG75ap4FeEUGzYdjbhnokbwa2lfinY2madBO7RqcJHdM0fls5Xc9GMXLtl1UkzvVA2E5hyKdqOyQXoZZcONzz3HUFHezILlJ/VN0vfHshNDe4mz87WfOIUxKS865VUzzISgWY5/SIq6vW0kVWf3wTEtL90oyqFhu8shTrLiXF/b/jZtOElRGd1kqb0XRMdTmpfVpemGcRYJWQg1w7Id11/@/5fd@9fXfw "/// – Try It Online")
Uses the example output (it's pretty fit for this purpose) without the trailing spaces.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2TŸ.•-Ÿ•S«.•ôì•âJ9F=2äζ˜
```
Uses lowercase cards to save 2 bytes with compression, since any human-readable output is allowed.
Starting/ending deck is:
```
['2c','2d','2h','2s','3c','3d','3h','3s','4c','4d','4h','4s','5c','5d','5h','5s','6c','6d','6h','6s','7c','7d','7h','7s','8c','8d','8h','8s','9c','9d','9h','9s','10c','10d','10h','10s','ac','ad','ah','as','jc','jd','jh','js','qc','qd','qh','qs','kc','kd','kh','ks']
```
[Try it online](https://tio.run/##MzBNTDJM/f/fKOToDr1HDYt0j@4AksGHVoM4h7ccXgOiFnlZutkaHV5ybtvpOf//AwA) (PS: Uses the legacy TIO because it is much faster.. All builtins that were used in this answer are the same in both the Python legacy and Elixir rewrite versions of 05AB1E however.)
**Explanation:**
```
2TŸ # List in the range [2,10]: [2,3,4,5,6,7,8,9,10]
.•-Ÿ• # Compressed string "ajqk"
S # As a list of characters: ["a","j","q","k"]
« # Merge the lists together: [2,3,4,5,6,7,8,9,10,"a","j","q","k"]
.•ôì• # Compressed string "cdhs"
â # Create each possible pair (cartesian product)
J # Join each pair together (now we have our deck of cards)
9F # Loop 9 times:
= # Print the deck with trailing newline, without popping the deck
2ä # Split it in two equal parts
ζ # Zip it (swap rows/columns)
˜ # Flatten the list of lists
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•-Ÿ•` is `"ajqk"` and `.•ôì•` is `"cdhs"`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes
```
9o åÈó c}"SCDH"ï"TJQKA"i2ò9 ¬¹w
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=OW8g5cjzIGN9IlNDREgi7yJUSlFLQSJpMvI5IKy5dw==&input=LVE=)
Although Japt has a reasonable "interleave two lists" function, it does not have a great "separate into halves" option. Instead I opted to *unshuffle* a deck and just display those steps in reverse.
Explanation:
```
9o ¹ Generate 9 rows, starting with...
"SCDH" The suits
ï Cartesian product with...
"TJQKA" The "special" card values
i Concatenated with...
2ò9 ¬ Digits 2-9 as a string; i.e. "23456789"
å } And getting each subsequent row by "unshuffling":
Èó Separate every-other card; e.g. [1,2,3,4,5,6] -> [[1,3,5],[2,4,6]]
c and flatten the two lists; e.g. [[1,3,5],[2,4,6]] -> [1,3,5,2,4,6]
w Display in reverse order
```
I could [save 2 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=OW8g5cjzIGN9IlNDREgi7yJUSlFLImk59SCsuXc=&input=LVE=) if I could use 1 for aces instead of A, but none of the other answers did that
[Answer]
# [Perl 6](http://perl6.org/), 69 bytes
```
([o] {.say;.[flat ^26 Z 26..*]}xx 9)(«A {2..10} J Q K»X~ <S C D H>)
```
[Try it online!](https://tio.run/##K0gtyjH7/18jOj9WoVqvOLHSWi86LSexRCHOyEwhSsHITE9PK7a2okLBUlPj0GpHhWojPT1Dg1oFL4VABe9DuyPqFGyCFZwVXBQ87DT//wcA "Perl 6 – Try It Online")
* `{ .say; .[flat ^26 Z 26..*] }` is an anonymous function that prints its argument list, then returns a perfect shuffle of that list
* `xx 9` produces a list containing nine copies of that anonymous function
* `[o]` reduces that list with the function composition operator `o`, producing a function that calls the original anonymous function nine times, passing the shuffled list down each level
* Finally, the original unshuffled deck is passed to that composed function. `«A {2..10} J Q K»` is a list of the ranks, `<S C D H>` is a list of the suits, and `X~` produces the cross product of those lists with the string concatenation operator `~`.
] |
[Question]
[
---
The scenario: You are a software designer working for a gov't-run company that designs license plates for cars and other vehicles. You've been asked to develop software that generates license plates. Before you got to work, your bosses laid down these ground rules.
---
# A license plate cannot contain:
* `ASS`
* `666`
* `69<any number here>`
* `<any number here>69`
* `KKK`
* `SHT`
# Rules and requirements:
* License plate **must** be randomly generated.
* Once a random license plate is generated, the same license plate cannot be generated again.
* You must output at least 200 **unique** license plates. You can generate more **if you want to**.
* You may store generated plates in a file to "remember" them.
* The license plate contains 2 sections, one containing only three letters, and one containing only three numbers, separated by a dash, like this: `233-ADF` or `ADF-233`.
* You can only use numbers and capital letters.
* License plates can be written to stdout, or a file.
* Each "side" of a license plate will contain either three numbers or letters.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest, most popular, answer wins. Winner will be chosen after seven days.
# General rules
* Answer **should** include, but not limited to, the following.
* Language name.
* Character count.
* File size.
* How the code is run.
* The code itself.
* Example: **Python 234 chars** or **Python 23mb**.
---
If I need to clarify any additional details, please mention it in the comments and I will add it to my post. Anyways, good luck, and generate me some appropriate license plates!
---
# Update 1: Winner will be chosen slightly earlier.
Turns out I have to go on a trip soon, so I will be choosing a winner around 00:00 UTC, July 25. After the winner is chosen, you can still submit entires, just know that a winner has been chosen. Bai.
---
# Update 2: Winners!
We have winners! Yay! Cheese and wine to everyone who participated! Here's who won.
* 1st place: **Àngel - Bash (95 characters)**
* 2nd place: **Martin Büttner - Mathematica (182 bytes)**
* 2nd place: **Emilio M Bumachar - Pyg (92 ?)**
* 2nd place: **Peter Taylor - Golfscript (98 characters)**
* 3rd place: **Mark Thomas - Ruby (127 characters)**
Wow, three second place ties. Wow. The competition is over, but feel free to submit entries if you want to. Bai!
---
[Answer]
# bash (95 chars)
Save the script as `m` in a folder in your PATH with execute bit set.
Run as `bash m`. The plates are stored in file p
```
l(){ tr -dc $1</dev/urandom|head -c3;};egrep -ve"ASS|666|69|KKK|SHT" -fp>>p<<<`l 0-9`-`l A-Z`;m
```
This is equivalent to running the following:
```
# Print three random numbers and three random letters
echo $(tr -dc 0-9 < /dev/urandom | head -c3)-$(tr -dc A-Z < /dev/urandom | head -c3) |
# Print only plates not matching the blacklist or any line of p
# Append the plates ton p
egrep -v -e "ASS|666|69|KKK|SHT" -f p >> p
# Execute itself again
m
```
Caveat: The final `m` should actually be `exec m` (+5 chars) in order to avoid leaving processes waiting for completion (but you can have thousands without much problem)
Credit goes to <http://www.cyberciti.biz/faq/linux-random-password-generator/> for the idea of using `tr -dc`
[Answer]
## [PYG](https://gist.github.com/Synthetica9/9796173) - 92
```
Pe(Se(Re.sub(".*(666|69|ASS|KKK|SHT).*","",J(RSm(STuc*3,3)+[j]+RSm(STd*3,3)))for j in'-'*K))
```
Now able to select uniformly from all unused plates, keeping to OP's specs, while being shorter by 1 more character.
It's theoretically possible that the list of 999 plates will contain enough repetitions so that the trimmed set will be less than 200. But the odds of that are infinitesimally small. In ten trials, the lowest length I got was 994.
EDIT: changed 999 to K (which is pyg for 1000), to save two chars at the advice of bitpwner.
[Answer]
## Mathematica, 182 bytes
Ugh, this is long
```
l={};While[Length[l=Union@Pick[l,StringFreeQ[l,"ASS"|"666"|"69"|"KKK"|"SHT"]]]<200,AppendTo[l,RandomSample[FromCharacterCode/@{48+9~(r=RandomInteger)~3,65+25~r~3}]~Riffle~"-"<>""]];l
```
Ungolfed
```
l = {};
While[
Length[
l = Union@
Pick[l, StringFreeQ[l, "ASS" | "666" | "69" | "KKK" | "SHT"]]
] < 200,
AppendTo[l,
RandomSample[
FromCharacterCode /@ {48 + 9~(r = RandomInteger)~3,
65 + 25~r~3}]~Riffle~"-" <> ""]
];
l
```
Pretty straight-forward. Generates random plates, and filters out duplicates and forbidden ones until 200 are found.
[Answer]
## GolfScript (98 chars)
```
260{3?}:^~,{.10^+`-3>'-'+\10^/26^+26base(;{65+}%+.-1%}%{'ASSKKKSHT66669'3/{1$\?)!},*},{,^^rand}$n*
```
This generates all possible licence plates in a random order using some ugly base conversion followed by filtering. There are a lot of them, so don't expect it to execute quickly, but the question didn't place any constraints on execution time.
[Answer]
## JavaScript (ES6) - 213
It can probably be improved. Tested on Firefox Console.
**Change that alert to a `console.log()` if you want to test**
```
r=x=>~~(Math.random()*x)+'';l=x=>[...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'][r(26)];a=[];while(a.length<200)p=r(10)+r(10)+r(10)+'-'+l()+l()+l(),!/ASS|666|69|KKK|SHT/.test(p)&&a.indexOf(p)<0&&a.push(p);a.forEach(x=>alert(x))
```
[Answer]
### Ruby — ~~136~~ ~~133~~ 129 characters
Hideous. Think there's room for improvement, though. Just drop the code in `irb` or `pry` and hit enter to run:
```
f=->*t{[0,1,2].map{t.sample}*''}
g=->l{(a=f[*?A..?Z]+?-+f[*?0..?9];l|=[a]if/69|666|ASS|SHT|KKK/!~a)until l.size>199;l}
puts g[[]]
```
[Answer]
# Ruby, 127 chars
My attempt at a "readable" Ruby version:
```
a=[]
until a.size==200 do
p="#{rand(899)+100}-#{('A'..'Z').to_a.sample(3).join}"
a<<p unless p=~/69|666|ASS|SHT|KKK/
end
puts a
```
[Answer]
## Python 2.7 - 258 chars
I'm not a professional programmer or anything, so I'd say I'm satisfied with the result.
```
import random as o
r=o.randint
t,j,k=[],0,""
b=["SHT","KKK","ASS","69","666"]
for i in range(200):
l,j=b[0],b[4]
while any(w in l for w in b):
l,j="",""
for i in range(3):
l+=chr(r(65,90))
j+=str(r(0,9))
t.append(l+'-'+j)
print "\n".join(set(t))
```
Filesize is 4.0 K, run with `python file.py` !
[Answer]
# Python - 208
Hi heres my stab at license plate generation. This solution is similar to @bitpwner's solution but without the string module and instead of a list for the license plate I chose to use a set and its also allows numbers first.
```
import random as r,re
f=r.randint
l=lambda x:chr(f(65, 90))if x else`f(0,9)`
d=set()
while len(d)<200:
k=f(0,1);j=1-k;c=l(k)+l(k)+l(k)+'-'+l(j)+l(j)+l(j)
if not(re.search("666|69|ASS|KKK|SHT",c)):d.add(c)
```
Sample output:
```
set(['DQJ-641', '086-QRY', '981-GAZ', 'UHN-718', '114-VMI', 'GLO-887', ...
```
[Answer]
# Python, 252 bytes
Here's my contribution. I'm impressed with it, but I know others have done better with python.
```
from random import randint as r
f=()
while len(f)<200:
t=str(r(0,999))
if not("666" in t or "69" in t):
u=''.join(chr(r(65,90)) for _ in [1,2,3])
if not("KKK" in u or "SHT" in u or "ASS" in u):f+=("%s-%s"%(t.zfill(3),u),)
f=tuple(set(f))
print f
```
[Answer]
# Python - 165
Those imports...
```
import random as r,re
j="666|69|ASS|KKK|SHT"
t=r.randint
while len(j)<2e3:
exec"x="+"chr(t(0,25)+65)+"*3+"'-'"+"+`t(0,9)`"*3
if not re.search(j,x):print x;j+='|'+x
```
If there is a need to begin randomly with either numbers or alphabets, which I don't think is really needed, then 190.
```
import random as r,re
j="666|69|ASS|KKK|SHT"
t=r.randint
while len(j)<2e3:
exec"x="+"chr(t(0,25)+65)+"*3+"'-'"+"+`t(0,9)`"*3
x=x[::r.choice((-1,1))]
if not re.search(j,x):print x;j+='|'+x
```
[Answer]
## PHP 341 324 320
Was the best I could do.
```
<?$a="p";$b=fopen($a,'a+');while($c<200){$d=rand(100,999);$e='';for($f=0;$f<3;++$f)$e.=chr(rand(65,90));$g=(rand(1,2)==1)?"$d-$e":"$e-$d";$h=array('ASS','666','69','kkk','SHT');$i=1;foreach($h as $j)!preg_match("/$j/",$g)?:++$i;if($i==1){$k=fread($b,filesize($a));if(!strpos($k,$g)){fwrite($b,$g);echo"$g<br />";++$c;}}}
```
To run the code just save as a .php file and browse to it on any web server. It will attempt to create the blacklist file p.txt if it does not exist already. However you may need to define it with a full server path if you do not have root access.
The code itself is here pre golfification:
```
<?
// create random plate
// check it does not break rules
// check is not on all time blacklist file
// Add to blacklist file
// Output to screen
// open file handle
$file = "p"; // filename and path if not root access
$fh = fopen($file, 'a+');
// do 200
while($x<200) {
// get random number
$rand_number = rand(100,999);
// get random letters
$letters = '';
for($y=0; $y<3; ++$y) $letters .= chr(rand(65,90));
// mix up combination
$string = (rand(1,2)==1) ? "$rand_number-$letters" : "$letters-$rand_number";
// assume is ok
$ok = 1;
// Set checks to be excluded on new plates.
$checks = array('ASS','666','69','kkk','SHT');
// do the exclusions
foreach ($checks as $check) !preg_match("/$check/", $string) ? : ++$ok;
// if all ok, check is not on the blacklist
if($ok == 1) {
// read blacklist
$blacklist = fread($fh, filesize($file));
// if not on blacklist, add it to file, echo it to output, increment counter
if (!strpos($blacklist, $string)) {
fwrite($fh, $string);
echo "$string<br />";
++$x;
}
}
}
```
Was as short as I could get it :-(
Sample Output
```
XWU-888
PUD-534
355-QXG
WDE-402
113-QID
362-YBW
TBK-594
939-XDT
148-ARZ
838-ICY
723-ZDA
.... does exactly 200 new plates.
```
EDIT: tidied up a couple of if statements to use short form.
[Answer]
## Delphi, 161 bytes
Here is my take on this. It outputs license plates to stdout without line feed between them. If LF is needed (not specified in the rules), than that adds extra 4 bytes.
Golfed version:
```
var S,L:string;begin repeat Str(100+Random(69),S);S:=S+'-';while Length(S)<7do S:=S+Chr(65+Random(10));if Pos(S,L)=0then L:=L+S;until Length(L)>1393;Write(L)end.
```
Ungolfed:
```
var
S, L: string;
begin
repeat
Str(100 + Random(69), S); // generate and add first three numbers
S := S + '-'; // add dash
while Length(S) < 7 do // generate and add last three letters
S := S + Chr(65 + Random(10));
if Pos(S, L) = 0 then // check if its not in the L string and add it
L := L + S;
until Length(L) > 1393; // exit loop once L string has more than 1393 chars (199 * 7 = 1393)
Write(L); // output L to stdout
end.
```
How to run:
```
app.exe > plates.txt
```
[Answer]
## PHP, 267
This is about as short as I can get it.
```
<?php $g=file("p",2)?:[];$b=["ASS","666","KKK","SHT"];for($i=0;$i<200;){$m="A";$n=rand(702,18277);for($j=0;$j<$n;$j++){$m++;}$m.=-rand(100,999);if(!(strpos($m,"69")|in_array($m,$b)|in_array($m,$g))){$g[]=$m;echo"$m\n";$i++;}}file_put_contents("p",implode("\n",$g));?>
```
Plates are stored in file "p".
```
<?php
$g=file("p",2)?:[]; // Read existing plates
$b=["ASS","666","KKK","SHT"]; // Don't generate these
for($i=0;$i<200;){ // 200 plates
$m="A"; // Base letter
$n=rand(702,18277); // 3 random letters
for($j=0;$j<$n;$j++){$m++;} // Increment until letters are reached (SLOW, but short)
$m.=-rand(100,999); // Add a dash and three numbers
if(!(strpos($m,"69")|in_array($m,$b)|in_array($m,$g))){ // Check that it's valid and unused
$g[]=$m;echo"$m\n";$i++; // Echo it, add it to used array and increment counter
}
}
file_put_contents("p",implode("\n",$g)); // Save the plates
?>
```
[Answer]
## R, 229 characters
I'm sure this could be improved:
```
l=function(x)paste0(sample(x,3,r=T),collapse="")
a=function()c(l(LETTERS),l(0:9))
A=list()
for(i in 1:200)while(any(sapply(c("ASS","666","69","KKK","SHT"),grepl,A[[i]]<-a()))|A[i]%in%A[-i])A[[i]]=a()
lapply(A,paste,collapse="-")
```
Run in the console, prints a list of license plates.
[Answer]
# Cobra - 198
```
class P
def main
l,r=[],Random()
while l.count<200
a,b=r.next(1000),''
for i in 3,b+='[r.next(65,91)to char]'
if not ('69'in'[a]'or 666==a or b in'ASS KKK SHT'),l+=['[a]-'+b]
print l
```
[Answer]
# ECMAScript 6 - ~~155~~ ~~168~~ 158
**Warning**: 200 alert dialogs (change `alert` to `console.log` to test)
```
for(i=0,s={},r=Math.random,l=x=>String.fromCharCode(65+r()*26);i<200;)/ASS|666|69|KKK|SHT/.test(p=(r()+'-'+l()+l()+l()).slice(-7))?0:s[p]=s[p]||(alert(p),i++)
```
**Edit**: Oops. Original version printed duplicates...
**Edit 2**: Closer to the original score now - switched from a set to an associative array with some fugly duplicate checks allowing it to print as it goes
Tested in Firefox console.
[Answer]
# JavaScript (ES6) 184
As usual, test in FireFox console and change `alert` to `console.log` or be prepared to press `escape` 200 times.
```
R=x=>Math.random()*++x|0
for(l='ABCDEFGHIKJLMNOPQRSTUVWXYZ',i=0,u={};i<200;)
!(/69|666|ASS|SHT|KKK/.test(k=l[R(25)]+l[R(25)]+l[R(25)]+'-'+R(9)+R(9)+R(9))&u[k])&&alert(k,u[k]=++i);
```
[Answer]
## Python3, 257 chars
```
import string as X,re,random as R
I=[0,1,2]
s={}
while len(s)<200:
L=R.sample([[R.choice(X.digits) for i in I],[R.choice(X.ascii_uppercase) for i in I]],2);L=''.join(L[0]+['-']+L[1])
if re.search('ASS|KKK|SHT|69|666',L) or L in s:continue
print(L);s[L]=0
```
Sample output:
```
# python3 shortened.py
EUN-215
546-SIL
464-ZTR
XIX-794
```
[Answer]
# PHP,167
```
while(count($a)<200){$c="";for(;++$y&3;)$c.=chr(rand(65,90));$d=rand(100,999);$c=rand()&1?"$d-$c":"$c-$d";preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;}print_r($a);
```
that's 100 chars less than current PHP's best :)
```
while(count($a)<200)
{
$c="";
for(;++$y&3;) $c.=chr(rand(65,90));
$d=rand(100,999);
$c=rand()&1?"$d-$c":"$c-$d";
preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;
}
print_r($a);
```
hope you like it. In case it is allowed:
```
while(count($a)<200){$c="";for(;++$y&3;)$c.=chr(rand(65,90));$c.=-rand(100,999);preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;}print_r($a);
```
is only 141 chars but doesn't shuffle chars and numbers.
Any suggestions wellcome :)
[Answer]
# F#, 264 chars
Not really a language designed for golfing, but I'm sure this could be improved. Using Seq.exists with a lambda is pretty annoying, as are the many parens and lack of implicit conversion.
Uses recursion, keeps going forever.
```
let g=System.Random()
let c()=char(g.Next(65,90))
let k(i:string)l=Seq.exists(fun e->i.Contains(e))l
let rec p d:unit=
let l=sprintf"%i-%c%c%c"(g.Next(100,999))(c())(c())(c())
if k l d||k l ["ASS";"666";"69";"KKK";"SHT"]then p d else
printfn"%s"l
p(l::d)
p[]
```
Can be run in FSI.
[Answer]
## Python 203
I'm not sure if this technically counts, but I liked it so I'm posting it anyway. While I do generate the answers pseudo-randomly, as pretty much everyone else did, I strategically picked the random seed such that invalid answers wouldn't end up in the output. So, my answer isn't actually capable of generating the entire set of valid answers, without also generating the invalid ones.
```
from random import*;seed(1);L='ABCDEFGHIJKLMNOPQRSTUVWXYZ';D='0123456789';C=choice
for i in 'x'*200:s=randint(0,1);a=''.join(C(L)for _ in'000');b=''.join(C(D)for _ in'000');i=[a,b];print i[s-1]+'-'+i[s]
```
[Answer]
## Perl - 123 Characters
```
while(@p<200){$l=(AAA..ZZZ)[int rand 999]."-".(100+int rand 899);@p=grep!/ASS|666|69|KKK|SHT|$l/,@p;push@p,$l}$,=$/;print@p
```
Ungolfed:
```
while(@p < 200){ # Repeat until we get 200 plates
$l = (AAA..ZZZ)[int rand 999]."-".(100+int rand 899); # generate the license plate
@p = grep !/ASS|666|69|KKK|SHT|$l/, @p; # remove disallowed license ones and duplicates
push @p, $l # add a license plate
}
$,=$/; # so they print with newlines
print @p # print the plates
```
If anyone has ideas to golf it further, let me know, I am interested. If you want further explanation of part of the code, leave a comment and I'd be happy to explain more too.
[Answer]
# Javascript - 283 327 Characters
# Edit:
After implementing the suggestions from **Alconja**, here's my new version:
```
m=Math.random;function y(v){return "ASS|KKK|SHT|666".indexOf(v)<0&&v.indexOf("69")<0?0:!0}function c(){return String.fromCharCode(m()*26+65)}for(i=0;i<200;i++){do {do {n=(m()+"").slice(2,5)}while(y(n));do {l=c()+c()+c()}while(y(l));r=l+"-"+n}while(o.indexOf(r)>=0);o+=r+"\n"}alert(o)
/* 1 line - 283 Characters */
```
1) Remove Variable:s and use literal:"\n" [-4][323]
2) Remove "var o="",i,r,n,l," [-17][306]
3) Remove Variable:t and use literal:"ASS|KKK|SHT|666" [-4][302]
4) Set m=Math.random and use "m" instead [-7][296]
5) Use (m()+"") rather than m().toString() [-6][290]
6) Remove unneeded ";" [-7][283]
---
# Old-version: Javascript - 327 Characters
I'm sure there's some room for improving... I'm pretty inexperienced at Code-golfing:
```
var o="",s="\n",i,r,n,l,t="ASS|KKK|SHT|666";function y(v){return t.indexOf(v)<0&&v.indexOf("69")<0?0:!0;}function c(){return String.fromCharCode(Math.random()*26+65);}for(i=0;i<200;i++){do {do {n=Math.random().toString().slice(2,5);}while(y(n));do {l=c()+c()+c();}while(y(l));r=l+"-"+n;}while(o.indexOf(r)>=0);o+=r+s;}alert(o);
/* 1 line - 327 Characters */
```
Here is a formatted, "Ungolfed" version with "un-minified" variable/function names:
```
var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";
function fnvfy(vinp){
return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;
}
function fnchr(){
return String.fromCharCode(Math.random()*26+65);
}
for(ndx=0;ndx<200;ndx++){
do {
do {
nbr=Math.random().toString().slice(2,5);
}
while(fnvfy(nbr));
do {
ltr=fnchr()+fnchr()+fnchr();
}
while(fnvfy(ltr));
res=ltr+"-"+nbr;
}
while(outp.indexOf(res)>=0);
outp+=res+lsep;
}
alert(outp);
```
---
Here is a "debug" version that can be pasted into URL of browser favorite/bookmark. Output is placed in a "TEXTAREA" on a new "window" instead of "alert()":
```
javascript:(function(){var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";function fnvfy(vinp){return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;}function fnchr(){return String.fromCharCode(Math.random()*26+65);}for(ndx=0;ndx<200;ndx++){do {do {nbr=Math.random().toString().slice(2,5);}while(fnvfy(nbr));do {ltr=fnchr()+fnchr()+fnchr();}while(fnvfy(ltr));res=ltr+"-"+nbr;}while(outp.indexOf(res)>=0);outp+=res+lsep;}var x=window.open();x.document.write('<head>\n</head>\n<body>\n<form name=sa><textarea name=t rows=25 cols=80 wrap>'+outp+'</textarea><br />\n</body>\n');x.document.close();})()
/* */
```
Here is the "debug" version, formatted:
```
javascript:
(function(){
var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";
function fnvfy(vinp){
return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;
}
function fnchr(){
return String.fromCharCode(Math.random()*26+65);
}
for(ndx=0;ndx<200;ndx++){
do {
do {
nbr=Math.random().toString().slice(2,5);
}
while(fnvfy(nbr));
do {
ltr=fnchr()+fnchr()+fnchr();
}
while(fnvfy(ltr));
res=ltr+"-"+nbr;
}
while(outp.indexOf(res)>=0);
outp+=res+lsep;
}
var x=window.open();
x.document.write('<head>\n</head>\n<body>\n<form name=sa><textarea name=t rows=25 cols=80 wrap>'+outp+'</textarea><br />\n</body>\n');
x.document.close();
}
)()
```
] |
[Question]
[
Given an array of letters in the range 'a' to 'o', compute how to construct the array by successively inserting the letters in alphabetical order. You will always start the insertion with a base array of all the 'o's that are in the array to be reconstructed.
# Examples
Let the input array be:
```
['o', 'b', 'o', 'b', 'a']
```
The base would have been ['o', 'o'] in this case. To construct it you would do the following insertings.
* Insert 'a' at index 2 (indexing from 0). This gives ['o', 'o', 'a']
* Insert 'b at index 1. This gives ['o', 'b', 'o', 'a']
* Insert 'b' at index 3. This gives ['o', 'b', 'o', 'b', 'a']
Let the input array be:
```
['a', 'o', 'b', 'o', 'a', 'c', 'b']
```
The base case to start inserting will therefore be: ['o', 'o']
* Insert 'a' at index 0 giving ['a', 'o', 'o']
* Insert 'a' at index 3 giving ['a', 'o', 'o', 'a']
* Insert 'b' at index 2 giving ['a', 'o', 'b', 'o', 'a']
* Insert 'b' at index 5 giving ['a', 'o', 'b', 'o', 'a', 'b']
* Insert 'c' at index 5 giving ['a', 'o', 'b', 'o', 'a', 'c', 'b']
Let the input array be:
```
['c', 'b', 'a', 'o', 'o', 'o']
```
The base case to start inserting will therefore be: ['o', 'o', 'o']
* Insert 'a' at index 0
* Insert 'b' at index 0
* Insert 'c' at index 0
Let the input array be:
```
['c', 'b', 'a', 'o', 'b', 'o', 'b', 'a']
```
# Output
The exact output format is of your choosing but it should be equivalent to:
For case 1:
```
'a', 2
'b', 1, 3
```
For case 2:
```
'a', 0, 3
'b', 2, 5
'c', 5
```
For case 3:
```
'a', 0
'b', 0
'c', 0
```
For case 4:
```
'a', 0, 3
'b', 0, 3, 5
'c', 0
```
BONUS (just for bragging rights) Make your code time efficient. That is can you minimise the number of operations it performs?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
η@O<ø{.γн}¦
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3HYHf5vDO6r1zm2@sLf20LL/h3b/jzbUUTDQUTACk0C2MZAdCwA "05AB1E – Try It Online")
Takes a list of numbers, 0 to 14, with `o` being 0, and `a, b, ...` being 1,2,....
We can notice that the index of an element in the correct list is the number of elements before it which are less than or equal to it.
```
η # prefixes [[1], [1, 0], [1, 0, 2], [1, 0, 2, 0], [1, 0, 2, 0, 1], [1, 0, 2, 0, 1, 3], [1, 0, 2, 0, 1, 3, 2]]
@ # element in list greater than or equal to each element in the prefixes: [[1], [0, 1], [1, 1, 1], [0, 1, 0, 1], [1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1]]
O # sum: [1, 1, 3, 2, 4, 6, 6]
< # subtract one, to account for the element itself: [0, 0, 2, 1, 3, 5, 5]
ø # zip with the original array: [[1, 0], [0, 0], [2, 2], [0, 1], [1, 3], [3, 5], [2, 5]]
{ # sort: [[0, 0], [0, 1], [1, 0], [1, 3], [2, 2], [2, 5], [3, 5]]
.γ # group by:
н # the first element
} # [[[0, 0], [0, 1]], [[1, 0], [1, 3]], [[2, 2], [2, 5]], [[3, 5]]]
¦ # remove the first element, the zeros: [[[1, 0], [1, 3]], [[2, 2], [2, 5]], [[3, 5]]]
```
If we can use a looser output format, not grouping the pairs by value, we can get [8 bytes: `η@O<øʒнĀ`](https://tio.run/##yy9OTMpM/f//3HYHf5vDO05NurD3SMP//9GGOgoGOgpGYBLINgayYwE)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
14ʁṘ(n~=T,o
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIxNMqB4bmYKG5+PVQsbyIsIiIsIlswLCAxNCwgMSwgMTQsIDAsIDIsIDFdIl0=)
Takes a list of numbers, outputs 14 arrays containing the indices from `n` to `a`, descending.
[9 bytes](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIxNChufj1ULG8iLCIiLCJbMTQsIDAsIDEzLCAwLCAxNCwgMTIsIDEzXSJd) if I can take input as [14...0] instead of [0...14].
```
14ʁṘ(n~=T,o
# Implicitly inputting the array
14ʁṘ( # Loop n from 13 to 0:
n~=T, # Print all the indices of n in the current array
o # Remove n from the array
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
K≥Ṡ‹Zs⁽hġḢ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJL4oml4bmg4oC5WnPigb1oxKHhuKIiLCIiLCJbMSwgMCwgMiwgMCwgMSwgMywgMl0iXQ==)
Port of Command Master's clever answer.
[Answer]
# [R](https://www.r-project.org), 41 bytes
```
\(x)Map(\(i)which(x[x<=i]==i)-1,1:max(x))
```
**How?**
```
f=
\(x) # define function with argument x;
Map( ... ,1:max(x)) # map over integers from 1 to max(x)
# for each of these, assigned to variable i:
which( ) # find the indices of
x[ ] # elements of the subset of x
x<=i # that contains only elements <=i
==i # that are equal to i
-1 # and subtract 1 to convert to 0-based indices
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFN75L8vNLcpNSiYtu00rzkksz8PI0KzeLEgoKcSo0KHbhYTmpJSWqRZmlJmkVIvmdeCUxAVdXSTFXV0FSTK812KVBW1-KmZgzQBN_EAo0YjUzN8ozM5AyNiugKG9vMWFvbTE1dQx1Dq9zECqAaTYiGW4y2aRpwZ2gka6jnq-soqCeBCAQrUV1TU1NBWcHWDsTWUTCyhkgY6igYc6HpT0TVmg_RDySSIWKoJhkATYAaZqSjYGoNUWaKbmgyklOghkKNzkc3EGqaAdQoAyKMIuRdJEeCmAh3GnBBQnHBAggNAA)
Outputs a list of vectors of the 0-based indices to insert each element that is present in the input.
Can be [2 bytes shorter](https://ato.pxeger.com/run?1=jZBNCsIwEIVx21MEpCQDEVqlomjci7hzpy5qaDGgTW1TrGdxUxceSk9jSuJfN7qZDG_efLzJ-ZJVt5mSSbHfRFnO4iLhSsiElJCHabo7kZK-tF2kVJRBoeLBQk4T9RRcd9h3XT8AJ2ZXPe0MbnilCfMwJSsi4LgVfEvKZTlmYs2YgI5P8-igHWDs9xaLySsE4QRLTBHe1OXdhRgAUBuxSd1T1B2ZgU9Rz2nsh9-r0uzrwo32TfI0wcK6FAUjYwuaUP4RxUItWjaBluZZlPcH6te5HyHr9p3Tc8wvVpV5Hw) by also including some empty vectors for elements that aren't present in the input. And, of course, trivially 2 bytes shorter again using R's native 1-based indexing (omit the `-1`).
---
# [R](https://www.r-project.org), 93 bytes
```
\(x){a=l=!1:15
a[]=list({})
Map(\(v){a[[v]]<<-c(a[[v]],l[v])
l[v:15]<<-l[v:15]+1},x+1)
a[-1]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5BboMwEEX3PoWrCjEjjFS3IqJJ3H0VddeuiBcGgYTkAAITUUWcJBu66KG4TU2dsPnz9f7Mt68_7TQfTF31pzRvO1H0VWbKuoIBO9U0-hsGtjKdG5O32Jsi_qzfK3MHnve68TweISnEr03DeJZH23BRQosHvuURUYkUuuwMXEYkH6qBI5xtniRnKff7MANnmbaKxKo9WoKbC_jIhoCj7Qm5HG-PfBWw_hwy8JXPqF8vkq7un2WOISJ9pOLN0SdGX3Zu9ZnRaOfWIuLKp8nNPw)
Runs in O(n) time complexity, making a single pass through the input list with only O(1) operations at each step.
[Answer]
# JavaScript (ES6), 67 bytes
Expects an array of integers in \$[1\dots15]\$. Returns an array of 14 arrays containing the insertion indices.
```
f=(a,n=14,b=[])=>n?[...f(a.filter((c,i)=>c-n||!b.push(i)),n-1),b]:b
```
[Try it online!](https://tio.run/##VY/NCsIwEITvfYp46gbSYEEELamI@BQlh83a2khNSls99d1rfxR1Dx/LzCzM3vCJLTW27iLnL/kwFApQOBVvhFGZ5ip1h0xKWQDKwlZd3gCQsKNOkev7lZH1oy3Bci5cFHNh9N4MSRYwloU@FCw0E74bhlrMJv7rfjFH0KK9Y/Rz@Ym9oQMdyMI3Z6QSkKmUkXetr3JZ@StMhe9YA82GpBKb0/jgsYM1ZxHbbfk4yfAC "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input array
n = 14, // n = item counter
b = [] // b[] = output array for the current item
) => //
n ? // if n is not equal to 0:
[ // update the output:
...f( // do a recursive call:
a.filter( // filter a[]
(c, i) => // for each value c at index i in a[]:
c - n || // keep this value if it's not equal to n
!b.push(i) // otherwise, remove it and append i to b[]
), // end of filter()
n - 1 // decrement n
), // end of recursive call
b // append b[]
] //
: // else:
b // stop
```
[Answer]
# Python3, 202 bytes:
```
def f(a):
t=[[],[]]
for i in a:t[i!='o']+=[i]
q=[(t[0],sorted(t[1]),[])]
while q:
j,k,I=q.pop(0)
if a==j:return I
if k:
for u in range(len(j)+1):q+=[(j[:u]+[k[0]]+j[u:],k[1:],I+[(k[0],u)])]
```
[Try it online!](https://tio.run/##VY5BbsMgEEX3PsV0ZZBRFaubCokD@AwjFjSBBhwBpqCqp3eHOlKazdfo/zfzJ//Ua4pv77ns@8U6cMxwOUBViFqg1gO4VMCDj2BkRf@ixjTqSaGnaFPIKp60@Eql2gvNs@a0xSn7vvqbhY1uQRCrWNT2mlNmJ06Gd2CUCrLY2kqE5bDWzv7VtV5XTPy07GYjC3yaudyolAWUTU@4UqmeAjapxYoz6TIh665onOr3XHyszDGkbwWMH10ekxk158ODMc9xOhiS8@E90@d/d@70fSd1cv8F)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 60 58 56 bytes
```
{-1_'"o"_(+/'</1*:\-1_(1_)\|<<x*~"o"=x)@|'=|x,:@/1>:\?x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWNYxXV8pXitfQ1le30TfUsooBimgYxmvG1NjYVGjVAeVsKzQdatRtayp0rBz0De2sYuwrarm49PUVyjNLMvJLSxSK84tKMvPSFbJTK4u59BXSrKpxm6hraKqFbCbQpDSl/KT8pEQlICMRyEpMTgIxk5MS8/PzlbgAxLIuvQ==)
Probably missing something clever but sorting the keys in the result cost ~~16~~ 14 bytes.
-2 : Cheaper way to force o’s to bottom
[Answer]
# Python 3, 74 bytes
```
f=lambda x:sorted((i,sum(j<=i for j in x[:n]))for n,i in enumerate(x)if i)
```
Takes input as integers:
```
['a', 'o', 'b', 'o', 'a', 'c', 'b'] -> [1, 0, 2, 0, 1, 3, 2]
```
Outputs an array in the form [(input, index)]:
Input:
```
['a', 'o', 'b', 'o', 'a', 'c', 'b']
```
Output:
```
[(1, 0), (1, 3), (2, 2), (2, 5), (3, 5)]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
⊞υoW⌊⁻θυ⟦ιI⌕A⁻θ⁻θ⊞Oυιι
```
[Try it online!](https://tio.run/##RYzNCsIwEITvPsXSS7IQn6AnEbyJvYccYixkIU00P/XxV1OhXmaGj5lx3maXbGCeWvGyKRjSgOPh7SnMIK8UaWlL91bkS0FDRJgyxSo1KTjbUuWF4uMUwr@0h/55e87Z1pT7N33XmxocmbUWVigQqct9TxtzP2YMH9fwAQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υo
```
Start as if `o` had already been processed.
```
W⌊⁻θυ
```
While there are any unprocessed letters, take the minimum.
```
⟦ιI⌕A⁻θ⁻θ⊞Oυιι
```
Output the letter and the indices that it would have been at i.e. the indices after removing the remaining unprocessed letters.
```
⊞Oυι All processed letters so far (including the current one)
⁻θ⊞Oυι All unprocessed letters so far (may include duplicates)
⁻θ⁻θ⊞Oυι Input with unprocessed letters removed
⌕A ι Get the indices of the current letter
⟦ιI Output the letter with its indices
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 22 bytes
```
FiR,14{PiAEg@*ig:gRMi}
```
`a` to `o` is mapped from 0 to 14.
*Semi-port of [Steffan's Vyxal answer](https://codegolf.stackexchange.com/questions/265455/reconstruct-an-array-by-successive-insertions/265462#265462)*
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhbb3DKDdAxNqgMyHV3THbQy063Sg3wzayGSUDXbow10FAxNgBhCAXlGQBbMCAA) | [19 bytes if indices don't have to be grouped](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhab3TKDdAxNqgPSHbQy063Sg3wzayEyUAXbow10FAxNgBhCAXlGQBZMPwA)
```
FiR,14{PiAEg@*ig:gRMi}
FiR,14{ } # For i in range 14, 0
P g@*i # Print all indices of i in list
iAE # Prepended with i
g:gRMi # Remove all instances of i in list
```
[Answer]
# [J](https://www.jsoftware.com), 21 bytes
```
*@/:~#/:{1#.(}:<:{:)\
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsVXLQd-qTlnfqtpQWU-j1srGqtpKMwYid3OtJpefk54CViVgGaCArp6aAVDaTs1AGSFXklpcYqunkJqcke-ga6UQbaWQpqCen5iUnJKalp6RmZWdk5tXUFhUXFJaVl5RWaWulqnHxWWkYKhgrADSClSblJ-UqM5lABQwUjAFQrCwgnoiUCIxOQkkA4IQxclJifn5-eoQRy9YAKEB)
Inspired by [CommandMaster's nice insight](https://codegolf.stackexchange.com/a/265463/15469), though the mechanics are different.
* `1#.(}:<:{:)\` For each prefix, count `1#.` the number of those to the left of the last element `}:` that are less than or equal to `<:` the last element `{:`. This part is the same as CommandMaster's approach.
* `/:{` Now order those elements according to the "grade up" `/:` of the original input. For example, if, when ordering the original input, the 3rd element moves to the first slot, then move the 3rd element of the result of step 1 to the first slot, and so on.
+ At this point we are done, except that we are still including the "base element" zeroes. They will all be at the beginning of our answer now, so we only need to remove from the start of our solution array the number of zeroes contained in the input.
* `*@/:~` To remove them, we sort the input and take the signum, which will give as an array like `0 0 1 1 1 1`, where the number of zeroes at the start matches the number of zeroes in the input.
* `#` Use that to filter our previous result.
[Answer]
# [Python](https://www.python.org), 95 bytes
```
f=lambda a,c='l':[0]*(c<'a')or-~(x:=a.rfind(c))and[c,x]+f(a[:x]+a[x+1:],c)or f(a,chr(ord(c)-1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY349NscxJzk1ISFRJ1km3Vc9Stog1itTSSbdQT1TXzi3TrNCqsbBP1itIy81I0kjU1E_NSopN1KmK10zQSo62AdGJ0hbahVaxOMlC1AlBQJzmjSCO_CKRY11BTE2LNxoKizLwSjTQNpfyk_KREJZg4zBkA)
# [Python](https://www.python.org), 97 bytes
```
f=lambda a,c='n':c>'`'and(-~(x:=a.rfind(c))and f(a[:x]+a[x+1:],c)+[c,x]or f(a,chr(ord(c)-1)))or[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEEWvUrpJhiRCdxKIFwkBJ1NCC5qUoULceBE33egJvIy3saW4_P89-P_5nu7zUPKyvG5zMscvJnfBa-yxQU1OZGHpJM4Ccy_NQ1br8MBpXBMBrGWTJHpbg0JfVWeDJlCedA2FN6RpYFl4s00HAIV92Ic-E495lkm2FLHEErEF2NH_yw8)
Using a more standard output format.
Explanation forthcoming.
[Answer]
# [jq](https://stedolan.github.io/jq/), 62 bytes
```
unique[:-1][]as$e|map(select(.<=$e or.=="o"))|[$e]+indices($e)
```
[Try it online!](https://tio.run/##bczBCsIwDAbgu08hoYcW24JXsU9Seqgxh4q227rd9uyLnUNB8fAn/Hwht56tljzl1E/kT@YYfIhV0PyInax0JxylPTtB@zJY56CAUrMXFA4pXxNSlYIUKw3AvqGGS8t7Rwg736b@krXjq6@Kn9tNt/yTn89L6cZUcmWDbIYn "jq – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 420 bytes
Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/265456/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##bVBRa8IwEH73V2RPXjCEbY@BCGPsYTAdbI8iI7apTRuT2p6iiL@9u7bCnEjhuMv3ffd9vSYx3rRxVdgE2cy4wOwBbUgb9lJV7NSmNmMZGPXhGly85qZecn3aG89QG5lFn365dY4AfzhwcT1wfkpMY8EJOIgj53rqMnAPehzHHJxS3aP1RDgImo78POosPWwHy6vF4raFrhfvAfmSPvVZoYthcQst9ZZtDCZ5n4PNndfTeQx21McqRCkcV6rucxmtC/4dNxRX1nZv68b24RhhpQwxvG0qPHIP9WQCjwwjK6S3YY05lxg7Z5l5gzNTwU5PuxmgkGhKCztOklLm1qRKFTKtI3E4FyXBzosLJHaUxdHRBlsyooN4GDah/HkWVJ5kE2u0qaB/Iea5HTFW1S6gD5ANXLquYONVV/46Myb2Ha75T4sDl0oyvN1XJVd7L6qLNvaKc/sL)
```
def f(a:List[Char])={val t=a.foldRight((List[Char](),List[Char]())){case(i,(x,y))=>if(i!='o')(i::x,y)else(x,i::y)}
def l(q:List[(List[Char],List[Char],List[(Char,Int)])]):Option[List[(Char,Int)]]=q match{case Nil=>None
case(j,k,i)::r=>if(a==j)Some(i.reverse)else if(k.nonEmpty)l(r++(0 to j.length).toList.flatMap(u=>List((j.take(u)++(k.head::j.drop(u)),k.tail,(k.head,u)::i))))else l(r)}
l(List((t._2,t._1.sorted,Nil)))}
```
Ungolfed version. [Try it online!](https://tio.run/##hVLBatwwFLzvV0xPKxEhmh4XXAglh0CTkvYYlqLYz7G8Wsm15TRh2W/fSrI3qw2B@vAsjWaeZ/Q8lMqow8E9tlR63CptQS@ebDXgquuwWwAV1aiZWuG7HvzDt0b1a77Cj85rZx8SxiIocGM9X69RJBXwrAx82ClZO1P91E@NZ@zUg3GBfMc5dijVQGBagL0IvAao@Jp6AboOOD4VWLolj8vVCokDMlET1gl75UmwTzWV6N8417E/I400x8iM5DbmdR6I/yft7C81x1b5spnzxyfludMm5MCds3R@wFqBTfDNo/GeBn@Ke4ysUBRoOX65LTEte3qmfiCesVL8SN1I6@z1tvPhTnYZYZqEpb/3yWIB9hneoZWG7JNvuPQu5pK1Uf5WdWyMZiPCWCu92hAbOS4u4gcaUlX02sqqDxc68jDDTeBoI47HAmOKo8NAz0ykEaSQodfRTU7ZT1F2H6vOmIv8vXjjTaa9/P1FINRLObjeU7AUJjDZ2S9C6XptvbGsngThhxJYPsZyWqnlJHjPVec0N3FDKSfsY1WZ9Z1Vs9Ylxf5w@Ac)
```
object Main extends App {
def f(a: List[Char]): Option[List[(Char, Int)]] = {
val t = a.foldRight((List[Char](), List[Char]())) { case (i, (x, y)) =>
if (i != 'o') (i :: x, y) else (x, i :: y)
}
def loop(queue: List[(List[Char], List[Char], List[(Char, Int)])]): Option[List[(Char, Int)]] =
queue match {
case Nil => None
case (j, k, i) :: rest =>
if (a == j) Some(i.reverse)
else if (k.nonEmpty) {
val newQueue = (0 to j.length).toList.flatMap(u => List((j.take(u) ++ (k.head :: j.drop(u)), k.tail, (k.head, u) :: i)))
loop(rest ++ newQueue)
} else {
loop(rest)
}
}
loop(List((t._2, t._1.sorted, Nil)))
}
println(f(List('o', 'b', 'o', 'b', 'a')))
println(f(List('a', 'o', 'b', 'o', 'a', 'c', 'b')))
println(f(List('c', 'b', 'a', 'o', 'o', 'o')))
}
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes (18 nibbles)
```
. ,@ :$ +-1 `? |@~-$@ @
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboW2_UUdBwUrFQUtHUNFRLsFWoc6nRVHBQcILJQRTujlaINdRQMdBSMwCSQbQxkxyrFQhUAAA)
Outputs a list containing 100 lists: the first entry of each is the element to add, the next entry/entries are the 0-based positions to insert it. Obviously only lists 1-14 can contain insertion positions if these are the only values possible in the input.
[8 bytes](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWW_QUdBwUtHUNFRLsFWoc6nRVHBQcIFJQFTujlaINdRQMdBSMwCSQbQxkxyrFQhUAAA) by outputting only lists of positions (without the element itself as the first entry); [6 bytes](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWG_QUdBwUEuwVahzqdFUcFBwgwlDZndFK0YY6CgY6CkZgEsg2BrJjlWKhCgA) using 1-based indexing.
```
. # map over
,@ # 1..100
:$ # prepending each value to:
`? # indices of
@ # the input
| # (filtered to retain only
~-$ # elements less than or equal to
@ # the current value)
@ # that equal the current value
+-1 # minus 1 (for 0-based indexing)
```
---
# [Nibbles](http://golfscript.com/nibbles/index.html), 10.5 bytes (21 nibbles)
```
. ,`/$] :$ +-1 `? |@~-$@ @
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWu_QUdBL0VWIVrFQUtHUNFRLsFWoc6nRVHBQcIAqg6nZGK0Ub6igY6CgYgUkg2xjIjlWKhSoAAA)
Outputs a list as above, but only containing lists of element(s) + position(s) for values that are present in the input.
[8.5 bytes](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboW22oU9BR0HBS0dQ0VEuwVahzqdFUcFBwgklA1O6OVog11FAx0FIzAJJBtDGTHKsVCFQAA) or [6.5 bytes](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWm2oU9BR0HBQS7BVqHOp0VRwUHCASUPmd0UrRhjoKBjoKRmASyDYGsmOVYqEKAA) by outputting only lists of positions, and with 1-based indexing, respectively.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 39 bytes
```
{a!1_{&(*z)=x^y}[x]':(1_)\a@:<a:?x^"o"}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1jt1SwyAQhe95CppxTOKQ5qfiBejoe8S03SBpM61BgTqJnfrshrbpz0VnYDlwzrdsxbYwSmfb++DhN3xpp90ubwufBeksfIc39gzstZ16ytshZNn2Lu/+NKswxi2fqxUP5hXUa97yjuuw2CGbe6pUJXjcg9IbBSTjKZ6EhTOgd0CUe0v0XoInPMOUE3rwRQlKqZNNEr5fZ/PUeKD77XgXQTFaWvtlWBwL9SEXal2NjQWxkq1YQrOQY6E+4++NNLZWjYmzJ/pIaayl6G9Wb4SNoIlAa+iisovMRghpTP0jo7oxUu8hhHJf+QT7pStnBX6BsDsIzpxwjynBE5eH66g65PsiDm8nMnHAEc4Ipk67DHVdxMVfQ5djOTcY6GRAk1vo7fkvp3D6YpAE/QNj1Is2)
Takes input as a string, returning a dictionary mapping the sorted non-"o" characters to lists of indices.
* `a:?x^"o"` identify the non-"o" characters in the input
* `a@:<` sort them, storing the result in the `a` variable
* `(1_)\` generate the suffixes of the sorted characters
* `{...}[x]':` set up an each-previous, fixing the `x` variable to the original input
+ `&(*z)=x^y` identify the indices each character should be inserted into
* `a!1_` build a dictionary mapping the non-"o" characters to the indices
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
>Ðḟ¹ẹɗⱮṀ’Ė
```
[Try it online!](https://tio.run/##y0rNyan8/9/u8ISHO@Yf2vlw186T0x9tXPdwZ8OjhplHpv1/uHOf9aOGOQq6dgqPGuZaH24HCqhwHW5/1LQm8v//6GgDHQUjHQUIaRiroxBtCOMBSSDbGMgGCRtDVICFQQhdDMmQWAA "Jelly – Try It Online")
A monadic link that takes a list of numbers from 0 to 14, with 0 corresponding to 'o' and 1 to 14 corresponding to 'a' to 'n'. Returns a list of lists; each list in the return value has the number in the original input it corresponds to as the first item and then a list of the 0-indexed insertion indices as the second item. If 1-indexing was allowed this would save a byte. If it were permissible to omit the labelling of the index lists with the number to which they correspond, this would save a further byte.
## Explanation
```
ɗⱮṀ | For each integer y from 1 to the max integer in the argument:
>Ðḟ | - Filter the original argument removing those values > y
¹ | - No-op (needed because of the way chaining works in Jelly within a dyadic chain)
ė | - Indices of y in this filtered list
’ | Decrease by 0 (because of Jelly’s 1-indexing)
Ė | Enumerate (prefix each list with a sequential number)
```
[Answer]
# Excel (ms365), 170 bytes
[](https://i.stack.imgur.com/szffA.png)
Formula in `B1`:
```
=DROP(IFNA(REDUCE(0,CHAR(ROW(97:110)),LAMBDA(o,n,IFERROR(VSTACK(o,HSTACK(n,LET(x,TOROW(A:A,3),y,FILTER(x,(x<=n)+(x="o")),FILTER(SEQUENCE(,COUNTA(y)),y=n)-1))),o))),""),1)
```
There is most likely some room for improvement. I deliberately use `TOCOL(A:A,3)` instead of an exact reference just so it's easy to moderate the input in column `A:A`.
Therefor, without too much hassle you can get the following:
[](https://i.stack.imgur.com/e8CcX.png)
] |
[Question]
[
Given a base as input, output all pan-digital numbers. A number is pan-digital if it includes every digit in that base at least once, possibly multiple times. Every number is considered to contain an infinite number of leading 0s.
[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. Given a base, you may either:
* Given an index, output the n-th pan-digital number in that base
* Output all pan-digital numbers up to a given index, or
* Output all pan-digital numbers in that base in ascending order.
You may also submit a function that outputs a generator or infinite list.
## Test cases
```
2 -> 1, 2, 3, 4, 5, 6... (all natural numbers)
3 -> 5, 7, 11, 14, 15, 16, 17, 19...
4 -> 27, 30, 39, 45...
...
10 -> 123456789, 123456798...
```
[Answer]
# x86-64 machine code, 28 bytes
```
31 C0 FF C0 50 31 C9 99 F7 FE 0F AB D1 01 C2 75 F6 58 FF C1 0F A3 F1 19 D7 73 E7 C3
```
[Try it online!](https://tio.run/##rZLBTsMwDIbPyVOYoUkJ7dBAaEgr4w24cEJiHNokXV116Wg66GB7dYrTFRhw4EIOsVP7//K7ihotlGrb2C1BwO1A8HTKmrICEzeh33hZTBla1eVstXYZVD7repTvUQ1H6lH6kTPU@ATGIWdJ7fq6pu5Ya5/siSy3L4AF0crVHtbxiUOqXuQRLklIhD0ip56y4GbKKlNzOZARR1tDKvxuQ/AhkRE8lUh3CRm1x4Qt1trAlas1lqfZdadYxmiF5K90f0XnVAxg62kspZE6Wg4zGEcUjmZwNqEkCCSHg/UpHF7gIITcqz@@ze0oGP3z@m4Pyd55RIHsXVL07hiNc2BhiFvyhV72x1jsS9ZPk4o8ROmlu8Op5vYmVhlaA6rUZtpZ8tTGU0PY0FGX8PoFG5/fEW0zE2JtHS6s0aCyuDqRqbxvHmS0g@cMCwO/6xBAEwTe5s@SOfzTIIYIyaY2Ts4tXdX4Ij2OdWVpTr5r31RaxAvXjpaTC9rojc9IaYp3 "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a 0-index in EDI and the base in ESI, and returns a number in EAX.
In assembly:
```
f: xor eax, eax # Set EAX to 0. EAX will hold the number being tested.
ol: inc eax # Increase EAX by 1.
push rax # Save the value of RAX (containing EAX) onto the stack.
xor ecx, ecx # Set ECX to 0.
il: cdq # Set EDX to 0 by sign-extending EAX.
idiv esi # Divide EDX:EAX by ESI (the specified base).
# The quotient goes in EAX and the remainder goes in EDX.
bts ecx, edx # Set the bit in ECX at position EDX (a digit) to 1.
add edx, eax # Add EAX to EDX.
jnz il # Jump back if the result of the addition is nonzero.
# This loop will exit when the quotient and remainder are both zero.
# This performs one more iteration after EAX first becomes zero,
# thereby processing one leading zero and ending with EAX=0, EDX=0.
pop rax # Restore the value of RAX (containing EAX) from the stack.
inc ecx # Add 1 to ECX.
bt ecx, esi # Set CF to the bit in ECX at position ESI (the base).
# If all digits are present, ECX was (2^base)-1 and became 2^base,
# and then CF=1. Otherwise, ECX is lower, and CF=0.
sbb edi, edx # Subtract EDX+CF from EDI (thus -1 when EAX is pandigital).
jnc ol # Jump back, to repeat, except when it goes from 0 to -1.
ret # Return.
```
[Answer]
# [Python](https://www.python.org), ~~74~~ 71 bytes
*-3 thanks to pan*
```
def f(b,i=1):b-len({i//b**k%b for k in range(i+1)})or print(i);f(b,i+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU31zNyC_KISheLKYi4g1itOLSlKTS4tKs7Mz8vJzM0s0TA00NKy1FxaWpKma3HTPSU1TSFNI0kn09ZQ0ypJNyc1T6M6U18_SUsrWzVJIS2_SCFbITNPoSgxLz1VI1PbULNWEyhWUJSZV6KRqWkN1goUhRi3GiKepmGsCRVZsABCAwA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒ*IвÙgQ
```
-2 bytes thanks to *@TheThonnu* (`¾šêIL<Q` to `0šÙgQ`).
-1 byte thanks to *@alephalpha* (`Iв0š` to `*Iв`).
Given \$n\$, outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5O0PC9sOjwzPfD/f2MA)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
ʒ # Filter it by:
* # Multiply the current integer to the (implicit) input-integer
Iв # Convert it to base-input as list
Ù # Uniquify this list
g # Pop and push its length
Q # Check if it's equal to the (implicit) input-integer
# (after which the filtered infinite list is output implicitly)
```
Multiplying the integer by the input results in an additional trailing `0` in the base-converted list (thanks *@alephalpha*).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
Longer than [EzioMercer's answer](https://codegolf.stackexchange.com/a/257760/58563) but works in theory1 for any base, rather than up to \$36\$.
Expects `(base)(n)` where both arguments are BigInts. Returns the \$n\$-th term of the sequence, 1-indexed.
```
b=>g=(k,q=x=1n,o=1n)=>q?g(k,q/b,o|1n<<q%b):k&&-~g(k-=-~o>>b,++x)
```
[Try it online!](https://tio.run/##TY1RC4IwFEb/yh5KNtwWmk/qXdAv0WsqpeymRgilf33NIOjl8J3z8t3KZzlV4/X@UJYutWvAIZgWeCcHmCGykjwEmOHUbu2Akt6RzfNhjyLtgkCtvitQKxmDMgxn4RoaOTJgsc0YshxYso0wFKwiO1Ff655aXpzLqWa7Fy6pZ8NRcH@0yJ/E/3L8l@QrWutCZO4D "JavaScript (Node.js) – Try It Online")
*1: In practice, it's ironically worse because of the recursion.*
### Without recursion, 70 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Backport of the C port.
```
b=>k=>{for(q=x=o=1n;k;q=q/b||(k-=-~o>>b,x+=o=1n))o|=1n<<q%b;return~-x}
```
[Try it online!](https://tio.run/##TYxNDoIwFISv0oUmbaA1ogtjeV14EigWo5A@W9CQ8HP1CiQmbGbmy2TmlX/zpvDPd8st3k0oIWhQFai@RE8ddIBwtLKSDtxBDwOtOPAJldJxF60dYzjMlqZur6U37cfbiXdjWPaaAEmsJJqkQC5LiCJGCrQN1kbU@KDZLW8M2fV6vM5aUs3ofDnGf0i2cNrCeQUhRMZk@AE "JavaScript (Node.js) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 66 bytes
*-1 thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
*-1 thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)*
A port of the JS version, but obviously without the benefit of BigInts.
```
o,q,x;f(b,k){for(q=x=0;k;q=q/b?:(k-=-~o>>b,x+=o=1))o|=1<<q%b;--x;}
```
[Try it online!](https://tio.run/##VY7RCoIwGIXvfYofQdhwszSvnL9Bz9GN0xSxXNMowezRW5PyoovD@eCDwyl4XRTGKKbZKCoiWUunSvVE44hb0QqNeiP3CWk58pfKMslGHxWGlKonhmmqPSk4H8Vs7qop4ZI3HaEwOQDLStPdQAJCJGylCLFt3/96gGtvfUXcQz6cwCsTG/aXIAiOnctAMliuQUh/EK2wWyGmVNjR2ZnNu6jOeT0Y/vgA "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ ~~10~~ 9 bytes
```
⁰τꜝ⁰ɽ⊍¬)ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigbDPhOqcneKBsMm94oqNwqwpyK8iLCIiLCI2XG4zIl0=)
Prints the first n pandigital numbers. Takes n then base.
*-1 thanks to @mathcat*
*-1 thanks to @AndrovT*
## Explained (old)
```
⁰τUs⁰ɽ~↔⁼)ȯ
)ȯ # First n numbers where:
⁰τ # that number in base input
Us # uniquified sorted
⁰ɽ ↔ # with digits from the range [1, input) kept
~ ⁼ # equals that range
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1bŻĠṫʋ#
```
A dyadic Link that accepts the base on the left and the number of pan-digital numbers to find on the right and yields a list.
**[Try it online!](https://tio.run/##y0rNyan8/98w6ejuIwse7lx9qlv5////Jv8NDQA "Jelly – Try It Online")**
### How?
```
1bŻĠṫʋ# - Link: integer, B; integer, N
1 - set the left argument to one (k=1)
# - increment (k), yielding the first (N) for which:
ʋ - last four links as a dyad - f(k, B): e.g. k=23, B=3
b - convert (k) to base (B) [2,1,2]
Ż - prefix with a zero [0,2,1,2]
Ġ - group indices by their values - [[1],[3],[2,4]]
ṫ - tail (that) from index (B) - [[2,4]]
- (the empty list is falsey, other lists are truthy)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 59 bytes
```
b=>{for(i=0;++i;)new Set(i.toString(b)+0).size<b||print(i)}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/ydauOi2/SCPT1sBaWzvTWjMvtVwhOLVEI1OvJD@4pCgzL10jSVPbQFOvOLMq1SappqYAKAaU1qz9n6ZhovkfAA "JavaScript (V8) – Try It Online")
## UPD 62 -> 60
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for the [tip](https://codegolf.stackexchange.com/questions/257752/print-all-pandigital-numbers/257760?noredirect=1#comment569606_257760) to reduce bytes count
## UPD 60 -> 59
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the [tip](https://codegolf.stackexchange.com/questions/257752/print-all-pandigital-numbers/257760?noredirect=1#comment569607_257760) to reduce bytes count
# [JavaScript (Node.js)](https://nodejs.org), 113 bytes
This code works for any base, rather than up to 36 and without a recursion
Expects one argument - `b (base)` as `BigInt`
```
b=>{for(n=0n;a=[],p=0n,k=++n;new Set(a).size<b||console.log(n)){while(k/b**p++);while(p--)k-=(a[p]=k/b**p)*b**p}}
```
[Try it online!](https://tio.run/##JYlBDsIgEAC/4pGFUj14w/UTHpseoIIiZCGlsYlt346aXiYzmZd@6zKMPk@S0t1Wh9XgdXFpZIQnUhq7vsk/awIKQYrsfLjZiWloi//Yi1nXIVFJ0bYxPRgBLPPTR8vC0XCehQC1d5YSgkSmu9zjPoH/uW3VsTNB/QI "JavaScript (Node.js) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes
```
n->for(i=1,oo,#Set(digits(i*n,n))<n||print(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN_XydO3S8os0Mm0NdfLzdZSDU0s0UjLTM0uKNTK18nTyNDVt8mpqCooy80o0MjU1IbqWpGmYQJkLFkBoAA)
Saved some bytes by multiplying `n` instead of prepending `0`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
If[DigitCount[n#,#]~FreeQ~0,Echo@n]~Do~{n,∞}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMt2iUzPbPEOb80ryQ6T1lHObbOrSg1NbDOQMc1OSPfIS@2ziW/rjpP51HHvFq1/wFFmXklCg7p0Sax/wE "Wolfram Language (Mathematica) – Try It Online") (press "play" to stop running)
prints sequence to infinity
-4 bytes from @alephalpha
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~9~~ 8 bytes
```
⟨×Bul=⟩#
```
[Try it online!](https://tio.run/##S0/MTPz//9H8FYenO5Xm2D6av1L5/39DAy4TAA "Gaia – Try It Online")
Takes `n`, then `b`; returns the first `n` pandigital numbers in base `b`. Uses the same trick as [this answer](https://codegolf.stackexchange.com/a/257754/67312) to add a zero.
Explanation of older answer below:
```
⟨ ⟩# # find the first n positive integers with a truthy result of:
B # convert to base b (implicitly pushed)
0+ # add 0 to the list
u # uniquify
l= # is the length equal to the base (implicitly pushed again)
```
[Answer]
# Java 8, ~~98~~ ~~97~~ ~~96~~ 94 bytes
Given a base \$b\$, it'll output the infinite sequence separated by newlines (pretty similar to [*@EzioMercer*'s JavaScript answer](https://codegolf.stackexchange.com/a/257760/52210)):
```
b->{for(int i=0;;)if(b.toString(++i*b,b).chars().distinct().count()==b)System.out.println(i);}
```
[Try it online.](https://tio.run/##LY67DsIwDEV3vsJjQmmExBiVnQEWRsSQpA9c2gQlLhJC/fZgoIsfV7o6pzdPU/b1PbvBpARHg/69AkBPTWyNa@D0fQGeAWtw4sB510SwUnM8r3gkMoQOTuChyrbcv9sQBfcBq63WElthFYUzRfSdKApc242Vyt1MTEKqGhOhd8SnC5PnXVVWnl@JmlGFidSDezR4gVLPWX@Bj8kODFy4P7GRtcUfcbka@Vf2yond4jnnDw)
Original answer **(~~98~~ ~~97~~ 95 bytes)**: Given two inputs \$b\$ and \$n\$, outputs the \$n^{th}\$ term in base-\$b\$.
```
b->n->{int r=0,i,t;for(;n>0;)n-=b.toString(++r*b,b).chars().distinct().count()<b?0:1;return r;}
```
[Try it online.](https://tio.run/##jY8xb4MwEIV3fsWJydRgQacqxnSr1KFTxqqDTSC5lBhkH5GiKL@dGsWVqqpDB/s96d199jvqsy6Ou8@lHbT38KbRXhMAT5qwhWNIxUw4iH62LeFoxUs09aulbt@5/D8zUZsGelCLKRpbNFe0BE6VOeYk@9ExaZtSZrZQRtC4JYd2zzh3DyY3mWgP2nmWiR16wkAPth1nG7Q2z@Wmkq6j2Vlw8rbIJDSYZjOEBrHIecQdnEI5dge/f@hs7Qmwvrz@xKhHCaZWT@HmPIYA24un7iTGmcQUFomlRvuuSLnh6QbSTMa5bwyqSgLWqiqDBE6M/wD1Qk/TcGGh3N1gxtMfxN8Lg2UxuyXruS1f)
**Explanation:**
```
b->n->{ // Method with two integer parameters and integer return-type
int r=0; // Result-integer, starting at 0
for(;n>0;) // Loop as long as input `n` is not 0 yet:
n-= // Decrease `n` by:
b.toString(++r // Increase the result-integer by 1 first with `++r`
*b // Multiply the new `r` by base `b`
// (this is to get an additional trailing 0)
,b) // Convert `r*b` to base-`b`,
.chars() // Convert it to an IntStream of codepoint integers
.distinct() // Uniquify this IntStream
.count() // Get how many items are left
<b? // If this is smaller than base `b`:
0 // Leave `n` the same by decreasing with 0
: // Else (the count is equal to `b` instead):
1; // Decrease `n` by 1
return r;} // After the loop, return the result-integer
```
Minor note: `.distinct().count()` is 4 bytes shorter than Java 16+'s `.boxed().toSet().size()`.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes
```
{&x=#'?'+0,x\!y}
```
[Try it online!](https://ngn.codeberg.page/k#eJxFT9tOwkAUfN+vGKMRiNvL3rq0G/UneEMSammhobTYFi0h+O2eBo0Pkz0zZ+Zspkguj8Pz/eR18hTy4e3ufGVskVwelufvNingY3DrZu+m6yItKze4s2tnqytbLCWsE5BQ0DCIViQpyNAZWAgBoSEMRARBNB63Gjpy0kKFUDG0WTEW4DNvz+iq5ovmxVKEEFJpE83D0N0mO49/NRvPxwjb9f2xS4Igazb5tqkKv+vTbJ8P2S6tt7mfNYfg45R3fdnUXSCNtUYGx7asey+tKu+Y1ptyW/Zp5dWnw3vedoxJeC8QHJJDcWgOwxH5vo8pJVCn/alN6b3ZZ0yNdrJYTkUJFBBERUQYtZiiTI8mSVSFhJjOmlEeQS3H//7q8f9+tP0B7edkeA==)
Takes the base as `x` and `y` as the zero-based index to generate all "pandigital" numbers up to.
* `x\!y` convert `0..y` to base `x`
* `+0,` prepend a `0`, then transpose to ensure all results contain a leading `0`
* `#'?'` count the number of distinct digits in each value
* `&x=` return indices where all digits are present
[Answer]
# [Julia 1.0](http://julialang.org/), 49 bytes
```
>(b,n=1)=1:b-1⊆digits(n;base=b)&&@show(n),b>n+1
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/304jSSfP1lDT1tAqSdfwUVdbSmZ6ZkmxRp51UmJxqm2SppqaQ3FGfrlGnqZOkl2etiFQh4nmfwA "Julia 1.0 – Try It Online")
prints the sequence indefinitely. Uses the beautiful `⊆` (same as the function `issubset`)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~29 24 23~~ 20 bytes
```
W1{I#UQy*aTDa=aPyUy}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZbwg2rPZVDAyu1EkNcEm0TAypDK2shUlAVi6ONY6FMAA)
*-1 thanks to @KevinCruijssen and @alephalpha*
*-3 thanks to @DLosc*
#### Explanation
```
W1{I#UQy*aTDa=aPyUy} # Implicit input on command line
# y is automatically initialised to 0
# (in a numerical context)
W1{ } # while True:
I # if
# # the length of
y*a # y * input
TDa # in base input
UQ # uniquified
= # equals
a # the input
Py # then print y
Uy # increment y
```
Old:
```
Y1W1{ISNUQyTDaPE0=,a{Py}Yy+1} # Implicit input on command line
Y1 # Set y to 1
W1{ } # while True:
I # if
yTDa # y in base input
PE0 # with a 0 prepended,
SNUQ # sorted and uniquified
= # equals
,a # range(0, input)
{ } # then
Py # print y
Yy+1 # y = y + 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
NθNηWη«→≧⁻¬⁻…¹θ↨ⅈθη»Iⅈ
```
[Try it online!](https://tio.run/##TYw9D8IgFEXn8isYHwkOJp3spE4ONKaT67MhQILQ8lEH429HMA4uN@fcm9xZY5g92lIubslpzI@7DLCygfy7rv7Uxkpakb5IJ/wm4TAZpVOdOoHLMUaj3LcBYVyOnI7@hzChUxL2nK6M0xNGCTdgzVjNdv4m12BcgjPG1DbGhlJ60pfdZj8 "Charcoal – Try It Online") Link is to verbose version of code. Takes `b` and `n` as input and outputs the `n`th pandigital number in base `b`. Explanation:
```
NθNη
```
Input `b` and `n` as integers.
```
Wη«
```
Repeat until `n` is zero.
```
→
```
Move right one position. This uses the current column index as the next trial pandigital integer.
```
≧⁻¬⁻…¹θ↨ⅈθη
```
If the set difference between the range from `1` to `b` and the base conversion of the trial integer is empty then decrement `n`.
```
»Iⅈ
```
Output the final pandigital integer.
26 bytes to output the first `n` pandigital integers:
```
NθNηW‹Lυη«→F¬⁻…¹θ↨ⅈθ⊞υⅈ»Iυ
```
[Try it online!](https://tio.run/##TY27DsIwDEXn5is8OlIYkDrRDSYkWlWdWEMV4kgloXmUAfHtwWx4sHSu7rFn0nEOeqn17J8lD@VxMxFX2Yl/JuYXucUAXkxKvLzNhEUqICnhLZo@bAYPk7OUudvcQwQcQsbe@ZJw0t4a3CtY2TjqZPCK8kc8MJbEpxRwxOpHjNH5jCedMj@QXa2taOtuW74 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Pushes the pandigital numbers to the predefined empty list as they are found and outputs the final list once `n` pandigital numbers have been found.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
.f!-tUQjZQE
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9NUbckNDArKtD1/39jLgsA "Pyth – Try It Online")
Prints the first n pandigital numbers, take input as base then n.
### Explanation
```
# implicitly assign Q = eval(input())
E # E = eval(input()) (second input)
.f E # print the first E numbers which satisfy lambda Z
jZQ # convert Z to base Q as a list of digits
tUQ # [1, 2,..., Q-1]
- # remove all digits in our number from the list of all digits
! # not (will be true for empty list)
```
[Answer]
# [Python](https://www.python.org), ~~93~~ ~~90~~ ~~87~~ 82 bytes
*-3 from @The Thonnu
-3 from @c--
-5 from @user85795*
```
def f(b,i=1,j=1,*s):i and f(b,i//b,j,i%b,0,*s);b>len({*s})or print(j);f(b,j+1,j+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU31zNyC_KISheLKYi4g1itOLSlKTS4tKs7Mz8vJzM0s0TA00NKy1FxaWpKma3EzKCU1TSFNI0kn09ZQJwuItYo1rTIVEvNSIKL6-kk6WTqZqkk6BiAp6yS7nNQ8jWqt4lrN_CKFgqLMvBKNLE1rkNosbUMQhpq8JE3DGMpcsABCAwA)
Infinitely prints out values.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
0-indexed
```
o1
@eUfXìNÎ}iV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bzEKQGVVZljsTs59aVY&input=Mwo3)
```
o1\n@eUfXìNÎ}iV :Implicit input of integers U=base & V=index
o1 :Range [1,U)
\n :Reassign to U
@ :Function taking an integer X as argument
e : Test U for equality with
Uf : U filtered by elements of
Xì : X converted to digit array in base
N : Array of all inputs
Î : First element (i.e., original U)
} :End function
iV :Get the Vth integer that returns true
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 65 bytes
```
j,k;f(*i,b,n){for(*i=j=0;n;j=!j?*i+=k=1:j%b==k?n-=++k/b,*i:j/b);}
```
[Try it online!](https://tio.run/##TY3BcoIwFEX3@YpbOnYSEqq4JD79FkOkJthHB9GNw7fTQG2nuzfn3XNvXdSXI39MUzStbWQejDOsHk3Xp5sibSzbSC/xkAdNLZVVXDmi9sAFad2unclDFddO2XF6DVxfbv6E3XXwoXs/74UIPIjPY2B574JX4iGAhNCfBgNnwDaBtAXpQNhaOOwI5cZCa6cwx4GvPimNzFZbXyFLnrILXzxOXmnBi1eigJtd/nVTSr79rT3Ff5V@Lkz/52f8GbwNV5llCxvFOH0D "C (clang) – Try It Online")
] |
[Question]
[
## Introduction:
*I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. Here is the third and easiest one (after the [Computer Cipher](https://codegolf.stackexchange.com/q/176931/52210) and [Trifid Cipher](https://codegolf.stackexchange.com/q/177353/52210) I posted earlier).*
---
With a Clock Cipher we use the following image to encipher text:
[](https://i.stack.imgur.com/yqHRk.jpg)
So a sentence like `this is a clock cipher` would become:
```
t h i s i s a c l o c k c i p h e r (without additional spaces of course, but added as clarification)
19:7:8:18:00:8:18:00:AM:00:2:11:14:2:10:00:2:8:15:7:4:17
```
## Challenge:
Given a string `sentence_to_encipher`, encipher it as described above.
## Challenge rules:
* You can assume the `sentence_to_encipher` will only contain letters and spaces.
* You can use either full lowercase or full uppercase (please state which one you've used in your answer).
* You are not allowed to add leading zeros for the single-digit enciphered letters `b` through `j`, but two zeros `00` are mandatory for spaces.
* You should use `:` as separator, and an additional leading or trailing `:` is not allowed.
* You are allowed to use lowercase `am` and `pm` instead of uppercase `AM` and `PM`, as long as it's consistent.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: "this is a clock cipher"
Output: "19:7:8:18:00:8:18:00:AM:00:2:11:14:2:10:00:2:8:15:7:4:17"
Input: "test"
Output: "19:4:18:19"
Input: "what time is it"
Output: "22:7:AM:19:00:19:8:12:4:00:8:18:00:8:19"
Input: "acegikmoqsuwy bdfhjlnprtvxz"
Output: "AM:2:4:6:8:10:12:14:16:18:20:22:24:00:1:3:5:7:9:11:13:15:17:19:21:23:PM"
Input: "easy peazy"
Output: "4:AM:18:24:00:15:4:AM:PM:24"
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~74~~ 72 bytes
```
lambda s:':'.join(['AM','PM','00',`ord(c)-97`]['az '.find(c)]for c in s)
```
[Try it online!](https://tio.run/##XY/bboMwDIbveQqLXaSVuooEWoqlXfQBKnHfVWrKYaQHYJCtoy/PbKptrFFkK479/f7rzhZVqfr85bU/68sh1dCiQDE/VqacbMV6I2Yi5uB5YravmnSSTJ@jcL/bCn0DMc9NyaVdXjWQgCmhnfZ1Y0oL@cS1hWmBrobkXCUnSExdZI07dZ7gflwZYYgrlCv0vN@83nBUKCXKgLN3f9P/gtoDlKHrOH8qWWsfmAGTZDTuuhbagjWXjBcy/waUIiqJ0iDpUKRZRYzRSo80nWRv5nSp3tuPaweHNC@O57Ju7OfXbUwmKIOWPO8xlPzIJTMVGVKoBhGJPrKxaHDss0sZ8h5KovIx3oyVM912UGf61o2FgmH/1Q9wgUMhJvnA7b8B "Python 2 – Try It Online")
Takes input as all lowercase
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 21 bytes
```
„AM24L„PM00)˜Að«s‡':ý
```
[Try it online!](https://tio.run/##FcU5DoJQFEDRrZDfGBMLYqjs6CWxJxZMIk4IH2WoWIgxsaZxAzRQugs28vA256Ta85NIZGrftrO2tv93jmkufy97/A6dntrPYjP2Iq7y1MpQAUQQQwJnuEIKGWh4QAk1GOBDCAc4wgkucIM75FDAEypo1F5m "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/W/q9v9RwzxHXyMTHyAd4GtgoHl6juPhDYdWFz9qWKhudXjvf53/0UolSjoKShkgIhNEFIMIBSzcRDgrGUTkgIh8ODcbVRastwBuciqIKFKK5YJalwo3ugQsWA5XmQgRhBlWAjcsF65PAZdbIWYlwh0BVp0Ol86GGwN2diHchFIQAXZCJdzAJBCRAiLS4G7Lgvs7D@69Irgry0BEBYioArsjFe6dYlSjC@BuS4SoBsvGAgA)
Some alternate **21** byte solutions:
```
':ýAð«24L„AMš„PMª00ª‡
00„AM24L„PM)˜AIk>è':ý
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 47 bytes
```
*.ords>>.&{<<00 AM{1..24}PM>>[$_%32]}.join(":")
```
[Try it online!](https://tio.run/##XY9bb4JAEIXf@RWTjTXAA7Ir3kZr4mMfTH2vTUN1ERQFWaxFi3/dzmIvtITsZHfO@c5MKrO4e90W0Azg/mo7SbZU47HTPI9GrguT6Zk7jvDK2XQ8fmq83LXFc@msk2hnMmTWdWgESQZmHO2kspxVJlPzYltwNgBa5sMuPeQfj4ecijXHubLnzHRsa85aQxJEATRckHtglZBVLvqUX0BgXhrc0qoSZKzkV0@3qKGfjfJa2RCA5WGkgH4fFnGy2MAiSkOZMeMWjcD4AHvYR95H1/2pk6k@BXKO3NPVvd2p3yG5h7zHDOM3RKr8L9LTID6oi46hn0MebaUeJ6rrhSAmRZKPUugkqyBEbaD/MH8hV9Fmm@zV4VjA6zII1/EuzfK391MNTEzN6Wq7q5m0DO9qpKBtBIoqg2Mb9VaDat22XpH39BiCo2jjbFoPlr4qIJX@qajleNX0/W9eB6uHGaV77BM "Perl 6 – Try It Online")
Anonymous Whatever lambda that takes a string of either case and returns the encrypted string.
### Explanation:
```
*.ords>>.&{ } # Map the ordinal values to
<< >>[$_%32] # The index in the list
00 AM{1..24}PM # 00, AM, the numbers 1 to 24 and PM
.join(":") # And join with colons
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 70 bytes
```
s=>string.Join(":",s.Select(a=>a<33?"00":a<66?"AM":a>89?"PM":a%65+""))
```
Takes input as a string of lowercase letters. First checks if the char is a space, and if it is, converts it to `00`. Next, it checks for if the char is an A, and converts it to `AM`. It checks again for Z and converts it to `PM` if it is. Lastly, if the char passes all the checks, it gets converted to its alphabetic order-1.
-2 bytes thanks to @dana
[Try it online!](https://tio.run/##bYxZC4JAFIXf@xXDhWCkkiCSFhdEDG0hyYnoUaeppmU0x9Y/b0pPUXA595zLdw@VLSp5MboKqss842LX/CwzNgppmJ@gjhMuMAygKdWQnRjNcWSYkd7pWNBuwyDSNc0Ce1Y6s9e3IKhcXes2ABSlGK4ynrMpFwzHGIjnh6gcGznTuTNBjh947qLkhrUvbuXZBBF/5lawT34B4oZ/rhFlO348Jxd5vT9RvNnuDyeRZvnt8QKVJMs0ZRlWft5cO1yjoNKqsngD "C# (Visual C# Interactive Compiler) – Try It Online")
```
// Input taking a string
s =>
// Join the following IEnumerable<char> with a ":" character
string.Join(":",
// Map all the characters in the string
s.Select(a =>
// Is the char less than 33, aka a space?
a < 33 ?
// If so, it's a "00"
"00"
// Else, is this an 'A'?
: a < 66 ?
// If so, convert it to "AM"
"AM" :
// If it's not 'A' or a space, could it be a 'Z'?
a > 89 ?
// If it is, turn the character into "PM"
"PM" :
// If it fails all of the checks above, get the characters position in the alphabet and subtract one from that.
a % 65 + ""))
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 86 bytes
```
s->"".join(":",s.map(c->c<33?"00":c<66?"AM":c>89?"PM":c-65+"").toArray(String[]::new))
```
[Try it online!](https://tio.run/##bU7RauMwEHzPVyyCgN0molAuXJ3UIZgcMddwpXbpQ@mDIsuJXFvSSXJS9@i36@Q0lEILWrSzMzs7FdmTcVU8O94oqS1UHuPW8hqfTQdfZmUrqOVSfEsaqxlpempAa2IMrAkX8G8AoNpNzSkYS6z/9pIX0HguyKzmYvv4BERvTXiUAvw63ZhlR79ZKizbMh2P3tUxlHDtzDhGCFfSm6AIjQxuiAroOKazy8s5urhAEZ1NJnO0WPsu/nk1R7d9N578OEcoxFYutCbdR4AoEuwQhm56TFBKHeyJ7lNFn5NBP7n25ffvlWI6IYYF4fREZp2xrMGytVh5W1sG6F5QrnZMsyKCoRmK5APBEQ8FGvWmIygxUarugt6d7og2QYg38oUVQRieLrwN@npzLl@lGfi3gOTmT/IbkvR2tbxz@TLL3cNqkUOerpe9IM0doWzLnxv517SHDjZFuatqobTdv7w6RkwHipHX7j8 "Java (JDK) – Try It Online")
## Credits
* -1 byte thanks to Kevin Cruijssen
[Answer]
# Pyth, 25 bytes
```
j\:m@+++"AM"S24"PM""00"xG
```
Try it online [here](https://pyth.herokuapp.com/?code=j%5C%3Am%40%2B%2B%2B%22AM%22S24%22PM%22%2200%22xG&input=%22acegikmoqsuwy%20bdfhjlnprtvxz%22&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=j%5C%3Am%40%2B%2B%2B%22AM%22S24%22PM%22%2200%22xG&test_suite=1&test_suite_input=%22this%20is%20a%20clock%20cipher%22%0A%22test%22%0A%22what%20time%20is%20it%22%0A%22acegikmoqsuwy%20bdfhjlnprtvxz%22%0A%22easy%20peazy%22&debug=0).
```
j\:m@+++"AM"S24"PM""00"xGdQ Implicit: Q=eval(input()), G=lowercase alphabet
Trailing dQ inferred
S24 [1-24]
+"AM" Prepend "AM"
+ "PM" Append "PM"
+ "00" Append "00" - this is the dictionary
m Q Map each element of Q, as d, using:
xGd Get the index of d in G, -1 if not present (i.e. space)
@ Get the element from the dictionary at the above index
j\: Join the result on ":", implicit print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~72~~ 65 bytes
Takes input in lowercase.
```
s=>[...Buffer(s)].map(c=>c<33?'00':c>121?'PM':c-97||'AM').join`:`
```
[Try it online!](https://tio.run/##bZBdb4IwFIbv9ysaboALkRYUOZkad0/i/bLErhZBERhFncb/7s5hm1mGTdOWjz7Pe85WHqVRTV63g7Ja61s6vZnp7NXzvJdDmurGMe6bt5e1o6Yz9RwEc9v3bVAzLvjcXiZ4HMTR9WovEtv1tlVermB1U1VpqkJ7RbVxUsdqs9wwnJKpolI7pvI6043luqwbwyGzeAwRTIBPwPfv@yKhVQDnwEPa/e9n/D7C30PgkfX036VNeyf3x48rJAOPe7dPmWxZm@81xc17ILotBKoxGVIwDK4IEgj8k/shWiq9yXf76sMcTmf2vk6zbVHWTXv8vJCG0Egl0pgAPlGxaj4mqMCyBYjOwiEAKj/u@hJQL3hEQQQHEcAy6am1NGdWa3k5P@wMqcOupMmvYgTdiyUGCq3bFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->a{a.map{|c|["00",:AM,*1..24,:PM][c.ord%32]}*?:}
```
[Try it online!](https://tio.run/##HYrRCoIwGEbve4ox6EZsmHUlVPQAQvfDi9/f2Zaaa5uZOp/dMvjgwDmf6fJhKU/L7gwTsAb05NFzGkU0TK5pGOwZi49hckszjqw1xfYQZ3NwSeaFUyeVJb8BwbrFiqDSUhgabqgT1q3sJTjiVCPWm/orQHFXVdO@bNcPJC9K@aif2rj3Z1yzADsQLWAc6CZjAlBO3nlNSu4YSjA2m5cv "Ruby – Try It Online")
Port of Jo King's [Perl answer](https://codegolf.stackexchange.com/a/178362/78274).
Takes input as an array of chars, returns a string with AM/PM in uppercase.
[Answer]
# [Red](http://www.red-lang.org), ~~124~~ ~~121~~ ~~110~~ 109 bytes
```
func[s][replace/all form collect[forall s[keep switch/default
c: -97 + s/1[0['AM]25['PM]-65["00"]][c]]]sp":"]
```
[Try it online!](https://tio.run/##TY5NboMwEIX3nGLkTRZVBKmUVmWXA0SKsh3NwhnGtYsBxzYl5PKUrIr0Nt/7kV6UZrlKg1SYejFjz5gIowSvWUrtPZghdsCD98IZV3h5CVuRAGlymW3ZiNGjzwXXsP/6hDdI5QEr3J3O9H7E3eVM@48jqqpSRMhElIKqFS0huj6DAZWtS7BKA/uBW2AXrERV/Bck5Q1OVmfIrpPXyG2T9fS3a7vhnsZphltj7I/vQ8y/j@emJTrNEEQ/Z7X8AQ "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
':ýð00:A24L„AMš„PMª‡
```
Greatly inspired by [*@Mr.Xcoder*'s 22-byter in the comment of the existing 05AB1E answer by *@Emigna*](https://codegolf.stackexchange.com/questions/178356/clock-transliterate-cipher/178363?noredirect=1#comment429848_178363).
Takes the input as a list of lowercase characters (would be 21 bytes with a leading `S` if I take the input as a string).
[Try it online](https://tio.run/##yy9OTMpM/f9f3erw3sMbDAysHI1MfB41zHP0PboQSAX4Hlr1qGHh///RSqlKOkqJQFwMxJVArADEBUAME68Ci8cCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF8Z7KKj5F9aAuX@V7c6vPfwBgMDK0cjE59HDfMcfY8uBFIBvodWPWpY@F/n0Db7/yUZmcUKQJSokJyTn5ytkJxZkJFaxFWSWlzCVZ6RWKJQkpmbClKQWcKVmJyanpmdm19YXFpeqZCUkpaRlZNXUFRSVlHFlZpYXKlQkJpYVQkA).
**Explanation:**
```
':ý '# Join the (implicit) input list of characters by ":"
# i.e. ["e","a","s","y"," ","p","e","a","z","y"] → "e:a:s:y: :p:e:a:z:y"
ð00: # Replace all spaces " " with "00"
# i.e. "e:a:s:y: :p:e:a:z:y" → "e:a:s:y:00:p:e:a:z:y"
A # Push the lowercase alphabet
24L # Push a list in the range [1,24]
„AMš # Prepend "AM" at the start of this list
„PMª # And append "PM" at the end of the list
‡ # Transliterate; mapping letters to the list-items at the same indices
# (and output the result implicitly)
# i.e. "e:a:s:y:00:p:e:a:z:y" → "4:AM:18:24:00:15:4:AM:PM:24"
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
UB:Fθ«→≡ι ×0²a¦AM¦z¦PMI⌕βι
```
[Try it online!](https://tio.run/##RY5BCsIwFETXzSk@WSVQQVzWlQruCkW9QEzT5tPYaJJWUHr2WFu0MKs3j2GkFk5aYWI8q7AXsqmd7dqS0YzyLamsA/bg8CZJbnvFshPWOoxF4p8YpAaGUymFV0CBZlA4bAO74E15Rtc0hQ3/6rMg/gLd5XThr4UXMy9VJToTfvggfGBHHH9dU0A@TQ5kiDFo9DBGgDRWNiDxrpUjcdWbDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case (can trivially be changed to upper case). Explanation:
```
UB:
```
Set the background character to `:`. This fills in the gaps between the output values created by the right movement.
```
Fθ«→
```
Loop over each character, leaving a gap each time. (The first move has no effect as the canvas is still empty at this point.)
```
≡ι ×0²a¦AM¦z¦PM
```
Switch on the character and if it's space, `a` or `z` then output the appropriate code. I use `×0²` instead of `00` here as the latter would cost two bytes in additional separators.
```
I⌕βι
```
Otherwise output the letter's 0-indexed position in the lower case alphabet as a string.
[Answer]
# [Perl 5](https://www.perl.org/) -pl, 46 bytes
```
s/./("00",AM,1..24,PM)[ord($&)%32].":"/ge;chop
```
Case doesn't matter. To run as `perl -ple '<code>'`. `-l` option passed to `perl` allows to drop the last colon with `chop`.
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fQ8nAQEnH0VfHUE/PyEQnwFczOr8oRUNFTVPV2ChWT8lKST891To5I7/g//@SjMxiBSBKVEjOyU/OVkjOLMhILfqXX1CSmZ9X/F@3IAcA "Perl 5 – Try It Online")
[Answer]
# Scala, 69 bytes
```
_.map(_.-(64)%32)map "00"+:"AM"+:1.to(24).map("".+):+"PM"mkString ":"
```
[Try it in Scastie!](https://scastie.scala-lang.org/ykA5WlPJQCCdRTBznSAuQw)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~72~~ ~~69~~ 63 bytes
```
$(switch($args){a{'AM'}z{'PM'}' '{'00'}default{$_-97}})-join':'
```
[Try it online!](https://tio.run/##XZHbbsIwDIbv@xS@6BaQQGpCOQVNAu0aDYnLaUIlGFootDTpOHR9duYUGGhRFavx/3924jQ5YKZDjOOLu4Q3KC5uTR8io8KaG2QrXS@Cgo3GrDwXbEKBASuY57Fygcsgj03hzpr9blnWm@sk2jHJLqXjDGsO0GpAjZkw0kBfACpO1AZUlIaYsQYw3pdd2ZO8Jz3vL47GdheSc8l9G73rP@XbJPcl77L6A47a3FC@BfD@U/IQBgZMtEVbPqp0QhCDSpCeqLSTRZD1qYF/kEDhKtpsk73ODyeYL5bhOt6lmfk@ni2QWNbfsTbPsqhp3rEoQV0LKSo2ly1pu@9X12rZq/CuLS@4FC1Jz/ooiIE@QYrB@WT5ftVt785py@pgQlV98tThB16gqLyuxp3BncIGuHhMURlc0Djd2TWboaZh0cErTXl411a5z8n0Pdcm2X7M12T7GhbTXCnU2tpvvqbC/YM7gOkNYCV32AA@cpPm5slWOqVz@QU "PowerShell – Try It Online")
Takes a lowercase string and does not add a leading `0`.
The string is passed to the function using splatting.
It iterates through all the characters of the string, replacing them with their encoded values.
The resulting items are then joined using ':' as separator.
-6 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy "#knowsAllTheTricks") !
[Answer]
# [Tcl](http://tcl.tk/), 100 bytes
```
proc C s {join [lmap c [split $s ""] {scan $c %c v
expr $v==65?"AM":$v==90?"PM":$v==32?00:$v-65}] :}
```
[Try it online!](https://tio.run/##Lc5NC4JAGATgu79ieLFjIIVBQYhulpamfX@IB1k6FKZLaxGIv922CObwnGam4nnbikfJwSBR38prgSS/ZwIciRT5tYIuQZSiljwroHN0OF7a5S0e0F/j8cC0yA5p9PXQsCj@u9@zDEOpOzCbFKOm/ZWqCY22nr@Big0WRGwB5seeuyaN3KMdxoGr5PlwIkfBdtjEnc48f74IwmUUr9bb3f5wPJ1BWoNaPCuJhKmPadN@AA "Tcl – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 98 bytes
```
s=>string.Join(':',s.Select(c=>"az ".Contains(c)?new[]{"AM","PM","00"}["az ".IndexOf(c)]:c-97+""))
```
Takes input as a (lowercase) char array. [Try it online!](https://tio.run/##JY7LCsIwEAB/JeylCbahN7G1lVIQFERBwUPpIazRLmgKSaQ@8NtjxcvAwBwGXYKOwvJucI6dsk0bO2/JXEpVBFeUf5HrngyPsih2cq@vGj3HogT1YiDr3nhFxnEUC6OHpn1DtYEYdj@kKXyaf7cyJ/3YnseszTCZTScAQoT8aMlrrjgMnfLM000zcow8yENfj0OVterJhRB5@AI "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
«"⁾PMµØAḊiȯ⁾00µe?€⁾AZj”:
```
[Try it online!](https://tio.run/##y0rNyan8///QaqVHjfsCfA9tPTzD8eGOrswT64F8A4NDW1PtHzWtAbIdo7IeNcy1@n90Uunh9v//E5NT0zOzc/MLi0vLKxWSUtIysnLyCopKyiqqAA "Jelly – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~31~~ 22 bytes
```
øA‹u025"J`00ṙ§m`2ẇĿ\:j
```
Thanks to @lyxal!
I'm not familiar with Vyncode so just classic version.
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBIiwiIiwiw7hB4oC5dTAyNVwiSmAwMOG5mcKnbWAy4bqHxL9cXDpqIiwiIiwiXCJ0aGlzIGlzIGEgY2xvY2sgY2lwaGVyXCJcblwidGVzdFwiXG5cIndoYXQgdGltZSBpcyBpdFwiXG5cImFjZWdpa21vcXN1d3kgYmRmaGpsbnBydHZ4elwiXG5cImVhc3kgcGVhenlcIiJd)
Explanation:
```
øA # Convert letter to number (space=0 and vectorized by default)
‹ # Increment (vectorized)
u025 # Push -1, 0 and 25
" # Pair top two items (0 and 25)
J # Join -1 (so "J shorter than 3¨ẇ)
`00ṙ§m` # This uncompressed to `00ampm` (how?)
2ẇ # Split into 2-chunks
Ŀ # Transliterate: replace each item of one value in another value with the corresponding element from a third value
\:j # Join by ":"
```
Old version for compare:
```
C97-⟨65N|0|25⟩⟨‛00|‛AM|‛PM⟩Ŀ\:j
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBIiwiIiwiQzk3LeKfqDY1TnwwfDI14p+p4p+o4oCbMDB84oCbQU184oCbUE3in6nEv1xcOmoiLCIiLCJcInRoaXMgaXMgYSBjbG9jayBjaXBoZXJcIlxuXCJ0ZXN0XCJcblwid2hhdCB0aW1lIGlzIGl0XCJcblwiYWNlZ2lrbW9xc3V3eSBiZGZoamxucHJ0dnh6XCJcblwiZWFzeSBwZWF6eVwiIl0=)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~98~~ 95 bytes
```
StringRiffle[Switch[#,1,"AM",26,"PM",0,"00",_,ToString@(#-1)]&/@LetterNumber@Characters@#,":"]&
```
[Try it online!](https://tio.run/##PcrBCsIwEEXRvV8RplAURmxduBCEiFuVYt1JkTFMTbC1JR2R@vMxIAgPLg9OS2K5JXGGgt2EUrx73k@urhu@lG8nxl4SzBG2B8DlCqGIzRCyDPCK5@7n9TSZ57MqXeg9i7A/vtobe72z5MnEP@gEYQ1VGorIRVsNYt2g4kiZpjMPZVxv2cPkD5iGUfVMnxHCFw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
We've all seen the signs on motels telling us if there's a vacancy or not:

Typically, these will permanently have the letters of **VACANCY** lit up, and have the letters of **NO** lit up if there isn't any room in the motel.
# The challenge
The average motel in the U.S. has 200 rooms.
You will write a program/function that takes an integer **T** (for taken rooms) as its only input.
Your program will then display the words `NO VACANCY`. The letters of `VACANCY` will be printed in red.
If **T** ≥ 200, the letters of `NO` will also be printed in red.
For example, assuming `a.out` is your program and "input" = command line argument:
[](https://i.stack.imgur.com/Y8WYQ.png)
(I typo'd and my system ignores case.)
# The rules
* Your program/function must **display** (or, if lambda, [return](https://codegolf.meta.stackexchange.com/a/2456/61563)) the exact string `NO VACANCY`, including case.
* Your program/function may only set the text foreground color to red and not the background.
* If you wish, you may use ANSI escape codes to print the red color - `\x1b[31m` will work.
* Your program/function may not change the text color of your shell after it finishes.
* Your program/function must terminate normally.
* Your program/function must print only to standard output.
* Your program/function must use your shell/terminal/IDE's default background color. (If you choose to have graphical output you may choose whatever color you like, except red.)
* If **T** ≤ 200, the letters of `NO` must be printed in your shell/terminal/IDE's default foreground color. (If you choose to have graphical output, once again you may choose whatever color you like)
* If for some reason your shell/terminal/IDE's default foreground/background color is red, you must print with a black background and a default white foreground.
* If you choose to use graphical output, red may only be used when specified in the program (e.g. your background color or default text color may not be red).
# The winner
As usual with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins! Brownie points for graphical output.
I'll accept the shortest answer in a week. Happy golfing!
# Leaderboard
```
var QUESTION_ID=123146,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Javascript (ES6), 60 bytes
(Open your browser's console while running the snippet to see the colored result.)
[](https://i.stack.imgur.com/xRihb.png)
```
f=
n=>console.log((n>199?'%cNO':'NO%c')+' VACANCY','color:red')
```
```
<input oninput=f(this.value)>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 26 bytes
```
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm
```
This uses `<CSI>` (**0x9b**), which is shorter than `<ESC>[` (**0x1b 0x5b**).
It resets the foreground color with `<CSI>m` instead of `<CSI>0m`, as the **0** is implicit.
### Verification
Note that your terminal emulator (e.g., Konsole) must be set to ISO 8859-1 or similar.
[")](https://i.stack.imgur.com/7jIhX.png "screenshot (click to expand)")
### How it works
```
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm Main link. Argument: n (integer)
<200 Compare with 200, yielding 1 if true, 0 if not.
o- Logical OR -1; map 0 to -1 (and 1 to 1).
“NO“ɓ31m” Yield ["NO", "\x9b31m"].
m Take the list "modulo" 1 or -1, keeping it as is for 1,
reversing it for -1.
“=ȤŻ» Implicitly print the previous result and yield the
string " vacancy". This is achieved by indexing into
Jelly's in-built dictionary.
Œu Convert to uppercase.
“ɓm Implicitly print the previous result and yield the
string "\x9bm", which is printed on exit.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) (\*nix style terminal), ~~54~~ ~~48~~ ~~45~~ ~~44~~ 43 bytes
*1 byte saved thanks to Value Ink*
*`␛` stands in for a literal esc byte (ASCII 27)*
```
->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"}
```
A port of my python answer, that is ~~a byte~~ several bytes shorter. I'm new to ruby golf but eager to learn so feedback is appreciated.
[Answer]
# [Python 3](https://docs.python.org/3/) (\*nix style terminal), ~~55~~ 54 bytes
```
lambda x:"\033[31m"*(x-199)+"NO\033[31m VACANCY\033[m"
```
---
This uses ANSI escape codes. `\033[31m` Makes the terminal red, if x is less than 200 we will start with one making `NO` red, otherwise we will have one after `NO` making it red anyway. When we are done `\033[m` clears the color from the terminal.
[Answer]
# HTML, ~~72~~ 71 bytes
```
<input min=200 type=number><x>NO <y>VACANCY<style>:valid+x,y{color:red}
```
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), ~~102~~ ~~89~~ ~~88~~ 51 bytes
Yes, Java. :P This only works on \*nix terminals.
```
x->(x>199?"\033[31m":"")+"NO\033[31m VACANCY\033[m"
```
[Answer]
# bash, 41 bytes
```
echo ␛[$[($1>199)*31]mNO ␛[31mVACANCY␛[0m
```
where ␛ represents a literal ESC character (ASCII \033).
[Answer]
# [Go](https://golang.org/), ~~82~~ 81 bytes
This only works on \*nix terminals. ~~I wonder how easy it would be to port this to Java...~~ [Done.](https://codegolf.stackexchange.com/a/123161/68615)
```
func f(x int)string{v:="NO\033[31m VACANCY\033[m";if(x>199){v=v[2:7]+v};return v}
```
[Answer]
## BASH / MKSH, ~~48 47~~ 46 bytes
```
(($1>199))&&a=^[[31m;echo $a^MNO ^[[31mVACANCY^[[m
```
Note: ^[ means 1 byte wide ESC character: 0x1b or decimal 27.
^M means 1 byte wide CR character: 0x0d, decimal 13.
[Answer]
# Excel VBA, ~~76~~ ~~73~~ 72 Bytes
Anonymous VBE immediate window function that takes input of expected type `Integer` from cell `[A1]` and outputs a (NO) VACANCY sign across cells `A2:B2`
```
[A2]="NO":[B2]="VACANCY":Range([If(A1>199,"A2:B2","B2")]).Font.Color=255
```
-3 Bytes for changing `rgbRed` to `255`
[Answer]
# HTML + CSS + JavaScript (ES6), ~~74~~ 59 bytes
Takes input as function argument of `f`, like `f(100)`.
### HTML
```
<x id=n>NO <j id=r>VACANCY
```
### CSS
```
#r{color:red
```
### JavaScript (ES6)
```
f=a=>a>199?n.id="r":0
```
## Test Snippet
```
f=a=>a>199?n.id="r":0
f(prompt("Enter a number"))
```
```
#r{color:red
```
```
<x id=n>NO <j id=r>VACANCY
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~54~~ 53 bytes
EDIT:
* -1 byte: From @Dennis's Jelly answer, the `0` argument in the final escape sequence can be dropped.
`f` takes an integer and returns a string. Use as `putStrLn$f 200`.
```
f t|t>199="\27[31m"++f 0|0<1="NO \27[31mVACANCY\27[m"
```
[Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlEpzcvJzEst1stNLNBI0ytKTUzR1CvPL0op/p@mUFJTYmdoaWmrFGNkHm1smKukrZ2mYFBjYGNoq@TnrwAVDXN0dvRzjgTxcpX@/zdQMDVQAOpSMDIwUDA2MAAA "Haskell – TIO Nexus") Alas, the colors don't show up in TIO, but you can see that the ANSI codes are correctly placed.
Golfing seemed to peter out pretty quickly with this one - not even naming the escape strings seems to save anything. The cleverest bit is recursing with `f 0` to use the other branch as a substring. Three different attempts at using list comprehensions all turned up one byte longer. Perhaps the nicest I found:
```
f t=foldr drop"\27[31mNO \27[31mVACANCY\27[m"[5|t<200]
```
[Answer]
# Bash script, 60 bytes
```
c="\e[1;31m";((199<$1))&&printf $c;printf "NO$c VACANCY\e[m"
```
[Answer]
## Mathematica, 67 bytes
```
Print[s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO",s@" VACANCY"]&
```
or (60 bytes, but may be considered cheating)
This is actually `Times["NO","VACANCY"]`, but appear to be correct.
```
(s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO")s@"VACANCY"&
```
[Answer]
# BASH, 100 bytes
```
if(($1<200));then
echo -n NO
else
echo -ne '\033[31mNO\033[0m'
fi
echo -e '\033[31m VACANCY\033[0m'
```
This can be probably be golfed, but I'm low on time. I'll come back to this later.
-5 bytes thanks to @R. Kap
[Answer]
# Mathematica, 47 bytes
```
(If[#>199,Style[NO,Red],NO]Style[VACANCY,Red])&
```
[Answer]
# C (\*nix style terminal), ~~50~~ ~~55~~ ~~52~~ 51 bytes
-1 thanks to Wheat Wizard
```
f(t){printf("␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0);}
```
␛ stands for the literal ESC byte, ASCII 27.
Call with `f(200)`, 200 being the number. Prints `NO VACANCY` colored to the spec.
[Answer]
# PHP, 41 bytes
```
␛[<?=$argn<200?31:''?>mNO␛[31m VACANCY␛[m
```
␛ represents the Escape character.
[Answer]
# [shortC](//github.com/aaronryank/shortC), 48 bytes
```
f(t){R"␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0
```
Where ␛ stands for ASCII 27, the ESCAPE byte.
[Answer]
# [GW-BASIC](https://en.wikipedia.org/wiki/GW-BASIC), ~~78~~ ~~74~~ 65 bytes
-12 thanks to Orjan Johansen
```
1INPUT X:IF X>199THEN COLOR 4
2?"NO ";:COLOR 4:?"VACANCY":COLOR 7
```
Prompts user for an integer. Output:
[](https://i.stack.imgur.com/SE9uE.png)
[Answer]
# Tcl/Tk, 96 bytes
```
grid [label .n -text NO -fg [expr \$argv>199?"red":"tan"]]
grid [label .v -text VACANCY -fg red]
```
[](https://i.stack.imgur.com/tfg0t.png)
] |
[Question]
[
Believe it or not, the [Sex Bob-ombs](http://scottpilgrim.wikia.com/wiki/Sex_Bob-omb) have become a world famous band and are currently on world tour! As their [bookkeeper](http://en.wikipedia.org/wiki/Bookkeeping) you must oversee their day to day finances and provide regular reports.
Every few weeks you compile a list of their expenses (in whole [USD](http://en.wikipedia.org/wiki/United_States_dollar)) in the order they were incurred.
For example, the list
```
378
-95
2234
```
means that $378 was deposited to their account, and after that $95 was withdrawn, and after that $2234 was deposited.
You want to make sure that the running sum of these values never goes below some threshold value *T*. You decide to write a program to do this for you.
# Challenge
Write a program or function that takes in a single integer *T* and a list of integers. If the running sum of the list of integers is ever less than *T*, then print or return a [falsy value](https://codegolf.meta.stackexchange.com/a/2194/26997), otherwise print or return a truthy value.
You may use any usual input methods (stdin, from file, command line, arguments to function).
* **At the start of the list the running sum is 0. So a positive *T* means the result is always falsy.**
* `+` will never be in front of positive integers.
* The list may contain 0.
* The list may be empty.
# Test Cases
*T* is -5 in all of these.
Falsy:
```
-6
```
```
1
2
3
-20
```
```
200
-300
1000
```
Truthy:
```
[empty list]
```
```
-5
```
```
4
-3
-6
```
# Scoring
The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to earliest posted submission.
[The regrettable comment that forced me to make this.](http://chat.stackexchange.com/transcript/message/20322986#20322986)
[Answer]
# Haskell, 22 bytes
```
f t=all(>=t).scanl(+)0
```
Usage: `f (-5) [4,-3,-6]` which outputs `True`.
Make a list of sub-totals and check if all elements are >= t.
Edit: Bugfix for empty list and positive `t`s
[Answer]
# Python 2, 41
```
f=lambda a,t:t<=0<(a and f(a[1:],t-a[0]))
```
The first argument is the array; the second is the minimum running total.
[Answer]
# J, 11 bytes
```
*/@:<:0,+/\
```
Tests
```
_5 (*/@:<:0,+/\) 1 2 3 _20
0
_5 (*/@:<:0,+/\) >a: NB. empty list
1
```
1-byte improvement thanks to [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl).
Explanation for the original version `(*/@(<:0,+/\))`
* `+/\` creates a running sum (sum `+/` of prefixes `\`)
* `0,+/\` appends a 0 to the running sum
* `(<:0,+/\)` left side input smaller or equal `<:` than (elements of of the) result of `0,+/\` on the right side input
* `@` with the previous result
* `*/` product of all elements (1 if all elements are 1, 0 if an element is 0)
[Answer]
# APL, ~~8~~ 10
```
∧.≤∘(0,+\)
```
This is a function that takes `T` as its left argument and the list as its right argument.
* `0,+\`: running sum of right argument, appended to a 0
* `∧.≤`: left argument smaller or equal (≤) than all (∧) items in the right argument
[Answer]
# Mathematica, 34 bytes
```
FreeQ[Accumulate@{0,##2},n_/;n<#]&
```
This defines an unnamed variadic function which take `T` as the first parameter and the transactions as the remaining parameters, and returns a boolean:
```
FreeQ[Accumulate@{0,##2},n_/;n<#]&[-5, 1, 2, 3, -20]
(* False *)
```
I like this because I could make use of the rather rare `##2` which "splats" all arguments from the second into the list. For more details see the last section [in this golfing tip](https://codegolf.stackexchange.com/a/45188/8478).
[Answer]
# k, 8 char
A dyadic verb taking the threshold as the first argument and the list as the second. Remarkably, this works in every version of k, including the open-source Kona.
```
&/~0<-\,
```
In k, composition of functions is just done by writing one and then the other, so we can break this up by functions. From right to left:
* `-\,` takes successive running sums and subtracts them from the threshold. (If `f` is dyadic, then `f\ (a; b; c; ...)` expands to `(a; a f b; (a f b) f c; ...)`. `,` just joins lists together.) Breaking even occurs when something is equal to 0, and overdrawing gives strictly positive values.
* `~0<` is Not 0 Less-Than. k doesn't really have a greater-than-or-equal-to `<=` operator, so we have to throw boolean NOT on a less-than, but this tests for whether the result is nonpositive. It automatically applies to each atom in the list.
* `&/` is the fold of logical AND over a list. (For `f` dyadic) So this tests whether every boolean in the list is True.
Examples:
```
(&/~0<-\,)[-5; 1 2 3 -20]
0
f:&/~0<-\, /assign to a name
f[-5; 4 -3 -6]
1
```
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), ~~144~~ 136 bytes
This was... hard...
```
?
?(1- )v1+(1-
^ # 1) v # -)1+(#
v# vv (##^v^+
^?+ v-(0## ^ # 01 #)(#)#
1 v# # )!
```
I think 6 voices is a new record for me, although I'm sure there's a way to reduce that and get rid of lots of that annoying whitespace. Checking the sign of a value (and therefore, checking whether one value is greater than another) is quite tricky in Prelude.
[Input and output is given as byte values.](http://meta.codegolf.stackexchange.com/a/4719/8478) When you use [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py), you can set `NUMERIC_OUTPUT = True`, so that you actually get an ASCII `0` or `1`. For numeric input, you'd have to add another `NUMERIC_INPUT` flag (I should probably publish my tweaked interpreter at some point).
Also note that Prelude cannot really distinguish the end of a list from a `0` within the list. So in order to allow zero transactions, I'm reading `T`, then the length `L` of the list, and then `L` transactions.
[Answer]
# CJam, 17 bytes
```
l~0\{1$+}%+\f<:+!
```
Takes input as an integer and a CJam-style array on STDIN:
```
-5 [1 2 3 -20]
```
[Test it here.](http://cjam.aditsu.net/#code=l~0%5C%7B1%24%2B%7D%25%2B%5Cf%3C%3A%2B!&input=-5%20%5B1%202%203%20-12%5D)
[Answer]
# Pyth, ~~16~~ 15
```
!sm>vzs+0<QdhlQ
```
Try it [online](https://pyth.herokuapp.com/) with the input
```
-5
[4, -3, 6]
```
## Explanation:
```
Implicit: z and Q read 2 line from input
z = "-5" (this is not evaluated, it's a string)
Q = [4, -3, 6] (this is a list though)
m hlQ map each number d in [0, 1, 2, ..., len(Q)] to:
>vz the boolean value of: evaluated z >
s+0<Qd the sum of the first d elements in Q
!s print the boolen value of: 1 > sum(...)
```
And again the stupid `s` function wastes two bytes. I think I'm gonna report this as a bug to the Pyth repo.
# edit: 13 (not valid)
Thanks to isaacg for one byte save (`>1` to `!`) and for changing the implementation of `s` in the Pyth repo. Now the following code is possible (but of course not valid for this challenge).
```
!sm>vzs<QdhlQ
```
[Answer]
# R, 35
```
function(t,l)all(cumsum(c(0,l))>=t)
```
Try it [here](http://www.r-fiddle.org/#/fiddle?id=facu0yds)
[Answer]
# Julia, 33 bytes
```
(T,l)->all(i->i>=T,cumsum([0,l]))
```
This creates an unnamed function that accepts two parameters, `T` and `l`, and returns a boolean.
The `all()` function does all of the heavy lifting here. It takes two arguments: a predicate and an iterable. For the predicate, we tell it that `i` represents the current value of the iterable using an unnamed function, specified by `i->`. Then at each iteration we compare `i` to `T` using `i>=T`.
To make sure that Julia doesn't freak out about using `cumsum()` on an empty list, we can tack a zero on there using `[0, l]`.
[Answer]
# [gs2](https://github.com/nooodl/gs2) - 6 bytes
Assume the list is on top of the stack, and the threshold is in register A. In mnemonics:
```
inits
sum get-a lt filter3
not
```
In bytecode:
```
78 64 D0 70 F2 22
```
[Answer]
# CJam, 18 bytes
Another approach in same bytes as the other one.
```
q~_,),\f<1fb:)f<:&
```
Takes input via STDIN in the form of `<threshold> <array of transactions>`
[Try it online here](http://cjam.aditsu.net/#code=q~_%2C)%2C%5Cf%3C1fb%3A)f%3C%3A%26&input=0%20%5B2%205%206%209%5D)
[Answer]
# JavaScript (ES6) 38 ~~33~~
**Edit** Fixed initial balance bug. Thx @martin & @rainbolt
```
F=(t,l)=>![r=0,...l].some(v=>(r+=v)<t)
```
**Test** In Firefox/FireBug console
```
console.log(F(-5,[-6]),F(-5,[1,2,3,-20]),F(-5,[200,-300,1000]))
console.log(F(-5,[]),F(-5,[-5]),F(-5,[4,-3,-6]))
console.log(F(5,[10]),F(5,[]))
```
>
> false false false
>
> true true true
>
> false false
>
>
>
[Answer]
# Python 2.7 - 55 bytes
```
f=lambda T,l:all(T<=sum(l[:i])for i in range(len(l)+1))
```
Call like `print f(-5,[1,2,3,-20])`. Test it [here](http://repl.it/cnB/3).
Thanks to Jakube for helping.
[Answer]
# ><>, 29 + 3 = 32 bytes
```
r0}&v >1n;n0<
&:&:<+^?=1l ^?(
```
Run like
```
py -3 fish.py bookkeep.fish -v -5 4 3 -6
```
where the threshold is the first number.
[Answer]
# Octave, 27
```
@(t,l)all(cumsum([0,l])>=t)
```
[Answer]
# Perl 6 (21 bytes)
```
{$^a>none [\+] 0,@^b}
```
It's a function taking initial argument, and list of elements. It works by checking if none ([by using junctions](https://en.wikipedia.org/wiki/Perl_6#Junctions)) of elements are below the threshold. `[\+]` is used for generating running sum, for example `[\+] 1, 2, 3` gives `1, 3, 6`. `0,` to append `0` at beginning of list is needed because of requirement that positive threshold always should fail.
Pretty much the same thing as Haskell solution, just in Perl 6 syntax (Perl 6 took so many neat programming features from Haskell).
[Answer]
## Perl - 20
Take the list of numbers on `STDIN` seperated by newlines and take `T` with the `-i` flag.
```
die if$^I>($i+=$_)
```
+2 for `-i` and `-n` flags. The exit value is `255` for failures and `0` on success.
Run with:
```
echo -e "4\n3\n-6" | perl -i0 -ne'die if$^I>($i+=$_)'
```
[Answer]
# Clojure, 45
```
(fn[T t](every? #(<= T %)(reductions + 0 t)))
```
E.g.
```
((fn[T t](every? #(<= T %)(reductions + 0 t))) -5 [1 2 3 -20])
;; =>false
```
Or a lil' nicer;
```
(defn f[T t](every? #(<= T %)(reductions + 0 t)))
(testing
(testing "tests from question"
(is (false? (f -5 [-6])))
(is (false? (f -5 [1 2 3 -20])))
(is (false? (f -5 [200 -300 1000])))
(is (true? (f -5 [-5])))
(is (true? (f -5 [4 -3 -6])))
(is (true? (f -5 []))))
(testing "the start of the list the running sum is 0. So a positive T means the result is always falsy"
(is (false? (f 5 [5])))
(is (false? (f 5 [10])))
(is (false? (f 5 [])))))
```
[Answer]
# Java 8 - 153 chars
Golfed function:
```
import java.util.stream.*;
boolean f(int t, IntStream s){int r=1;try{s.reduce(0,(a,b)->(a+b>=t)?(a+b):(a/(a-a)));}catch(Exception e){r=0;}return r==1;}
```
Ungolfed:
```
import java.util.stream.*;
boolean f(int t, IntStream s) {
int r=1;
try {
s.reduce(0,(a,b) -> (a+b>=t) ? (a+b) : (a/(a-a)));
} catch(Exception e) {
r=0;
}
return r==1;
}
```
Driver program:
```
import java.util.stream.*;
import java.util.*;
public class A {
// function f as above
public static void main(String... args) {
int t = -5;
IntStream s = null;
s = Arrays.asList(-6).stream().mapToInt(i->i);
System.out.println(new A().f(t,s));
s = Arrays.asList(1,2,3,-20).stream().mapToInt(i->i);
System.out.println(new A().f(t,s));
s = Arrays.asList(200,-300,1000).stream().mapToInt(i->i);
System.out.println(new A().f(t,s));
System.out.println("above false, below true");
s = IntStream.empty();
System.out.println(new A().f(t,s));
s = Arrays.asList(4,-3,-6).stream().mapToInt(i->i);
System.out.println(new A().f(t,s));
s = Arrays.asList(-5).stream().mapToInt(i->i);
System.out.println(new A().f(t,s));
}
```
}
Output:
```
bash-3.2$ javac A.java ; java A
false
false
false
above false, below true
true
true
true
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Ä<Ẹ¬
```
[Try it online!](https://tio.run/##y0rNyan8//9wi83DXTsOrfl/eLnS///RumaxOgrRhjpGOsY6ukYGII6RgYGOrjGQMDQwAAsYgggQ1jUFkSZAWR2gvv@6pjoKMGyGYOqaAgA "Jelly – Try It Online")
Outputs `0` for falsey and `1` for truthy. The final byte can be removed if the outputs can be flipped.
I decided to put this through a basic brute-forcer to try to get a 3 byte solution. Any such solution would have to be in the form `Ä<X`, where `X` is an unknown atom. [This](https://tio.run/##RU7bThNRFH22X8ELJsYzYVouDxSM96hBxICiNNWI4gURBBSEGDJTyq0FTTShooKlEptIVUKpnH0O8HBmSOpnrPMj4xkS48NeWXvvtdbe/X0DAxNB8CcfP61TJe0eeOmWeMicz5Eer1hnKGg2RJ5ujcZs7axGVEFVxlQZlD7RGQSqpH6qfS/n7dYeP8ma4y2tp86cPXf@wsVLl6@0XW2/1nG9s@vGze5bt3vu3L3Xe/9B38NHj5/0P302OPR8eGT0xcux8VeTr6fUliK1rcra3dFuRbtcu6Rdqd09iLy5Db4IwcE3IDPg2@C/QSnzGeQi6COoACpBboAOIOYhdyDeVb@Bp3yjzvjL4Gu@iSn4WyAHtAzKg75DzEJkIN4cSoh18BnwJQiCzIKXwXdBc5BLoE@gr6AfquilIRYgKxDvq0Xwad8Is34O/Itv7Ebjgmaqv0A50ApoHbQJMQeRhXh7uKc2ldTOB@2sBInIsUTCakqymkSUxVg9s2J22MRsm1n1BqK2fTSIhhCW1Rhig9ky40syE2A1spp/1fSfGmUk@Rc) Jelly program iterates through all atoms (ones that lead to errors were removed), inserts them into the template above and tests whether the atom gives the desired results for the inputs. If it does, it should output `1`. The final number is the number of successes, which is unfortunately `0`. However, if we change the template to mirror the above program (4 bytes), we get [7 results](https://tio.run/##RU7bThNRFH2mX8GLJoYzYVqEBwvGCxAlXiCgKE01XlAEVARFMcTMlHJrQRNNqHgthdhEChJK5exzkIczQ1I/Y50fGc@YEB7Wytp7r7X3HuwfHp4Igr/5@BmdKml330s3x0PlfFGlSJ9XrDcFaCZknm6JxmztfI2ogqqMqzIofaI7CFRJbao/Xs7bPXa8jp2KN7ecPnvufGtb@4WLHZcuX7na2dXdc@16742bfbdu37l7737/g4cDjwaHHj95OvJsdOz5i/GXr15PvlFbitS2Kmt3R7sV7XLtknaldvcg8uY2@AIEB1@DzIBvg/8GpcxnkAugT6ACqAS5BtqHmIPcgXhf/QGe8o074y@Bf/PNmoK/BXJAS6A86CfEDEQG4u2BhFgBnwZfhCDILHgZfBc0C7kI@gxaBW2oopeGmIesQHyoFsGnfGPM@jnw776JG48Lmq7@AuVAy6AV0DrELEQW4t3BnlpXUjsftbMcJCI1iYTVlGS1iSiLsQZmxeywiNk2sxoMRW37fyMaUgirMeSTZspMLsnMAquR1R6i6UgaZyT5Dw):
```
Ä<S¬
Ä<Ḅ¬
Ä<Ḍ¬
Ä<Ẹ¬
Ä<Ṁ¬
Ä<§¬
```
I've excluded [`Ä<V¬`](https://tio.run/##y0rNyan8//9wi03YoTX/Dy9X@v8/WtcsVkch2lDHSMdYR9fIAMQxMjDQ0TUGEoYGBmABQxABwrqmINIEKKsD1Pdf11RHAYbNEExdUwA) due to the extra output it produces
## How it works
```
Ä<Ẹ¬ - Main link. Takes L on the left and T on the right
Ä - Cumulative sum of L
< - Is each less than T?
This yields all 0s for a truthy input and at least 1 1 otherwise
Ẹ - Is there a 1?
¬ - Logical NOT
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
å+ e¨V
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5SsgZahW&input=WzQsLTMsLTZdCi01)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Λ>⁰∫²
```
[Try it online!](https://tio.run/##yygtzv7//9xsu0eNGx51rD606f///9GGOkY6xjq6Rgax/3VNAQ "Husk – Try It Online")
Not sure how to remove the superscripts, but it should be possible.
] |
[Question]
[
# Objective
You are to write a program that receives an integer `n` as input (from the command line), and embeds itself (the program) `n` directories down the directory tree. Example with `n=5`:

The folder names may be whatever you wish. The only requirements are that the depth is correct, and that the program can then be ran again from its new spot in the directory tree, and that the new source file retains the same filename.
## Bonuses:
* **Score \* 0.9** If the directories all have a different name (must be true at least to depth 1 000 000)
* **Score \* 0.5** If you do not **directly or indirectly** read or move the source file, or access the source code of the program
[Answer]
# Bash, 30\*0.9\*0.5 = 13.5
```
mkdir -p `seq -s/ $1`;ln $0 $_
```
Takes depth as the first argument. Creates a hard link to itself into the following directory structure:
```
1/2/3/4/5/.../n
```
The script may then be run from the new location, even if `rm` is run on the old script.
**Explanation:**
`seq -s/ $1` outputs the numbers from 1 to `$1` (the first argument), separated by a forward slash.
`mkdir -p `seq -s` $1` creates the directory specified by `seq`, with `-p` creating all intermediate directories.
`ln $0 $_` create a hard link to the current running script in the newly created directory.
**Old (30 \* 0.9 = 27):**
```
mkdir -p `seq -s/ $1`;cp $0 $_
```
**Example run (with ln):**
```
$ ls -lGR
.:
total 1
-rwx------+ 1 ducks 41 Jan 5 15:00 test.sh
$ ./test.sh 4
$ ls -lgR
.:
total 1
drwxr-xr-x+ 1 ducks 0 Jan 5 15:01 1
-rwx------+ 2 ducks 41 Jan 5 15:00 test.sh
./1:
total 0
drwxr-xr-x+ 1 ducks 0 Jan 5 15:01 2
./1/2:
total 0
drwxr-xr-x+ 1 ducks 0 Jan 5 15:01 3
./1/2/3:
total 0
drwxr-xr-x+ 1 ducks 0 Jan 5 15:01 4
./1/2/3/4:
total 1
-rwx------+ 2 ducks 41 Jan 5 15:00 test.sh
$ rm ./test.sh
$ ls -lg
total 0
drwxr-xr-x+ 1 ducks 0 Jan 5 15:01 1
$ ls -lg 1/2/3/4
total 1
-rwx------+ 1 ducks 41 Jan 5 15:00 test.sh
```
Thanks to @DigitalTrauma for suggestion to replace `$(..)` with ``..``
Thanks to @h.j.k. for suggestion to use `ln`.
[Answer]
# C, 225 \* 0.9 \* 0.5 = 101.25
My solution in C:
```
$ cat d.c
#define R(x)#x
#define T(x)R(x)
#define S(p)b[9];main(i,v)char**v;{for(i=atoi(v[1]);i--;sprintf(b,"%i",i),mkdir(b),chdir(b));fputs("#define R(x)#x\n#define T(x)R(x)\n#define S(p)"p"\nS(T(S(p)))",fopen("d.c","w"));}
S(T(S(p)))
```
Here in a somewhat more readable form:
```
#define R(x) #x
#define T(x) R(x)
#define S(p) char b[9];\
main(int i,char**v) { \
for(i=atoi(v[1]); i--; sprintf(b,"%i",i), \
mkdir(b), \
chdir(b)); \
fputs("#define R(x) #x\n" \
"#define T(x) R(x)\n" \
"#define S(p) " p "\n" \
"S(T(S(p)))", \
fopen("d.c", "w")); \
}
S(T(S(p)))
```
The check if it works:
```
$ gcc -o d d.c
# a lot of warning and notes from gcc ...
$ ./d 10
$ diff -s d.c 9/8/7/6/5/4/3/2/1/0/d.c
Files d.c and 9/8/7/6/5/4/3/2/1/0/d.c are identical
```
There most probably is a lot of golfing potential in the source code.
[Answer]
## Batch - 48 \* 0.9 = 43.2
```
for /l %%a in (1,1,%1)do md %%a&cd %%a&move..\%0
```
This script simply creates a new directory, and moves the source file to it - `n` times.
```
H:\MyDocuments\uprof\top>embed.bat 5
...
H:\MyDocuments\uprof\top>tree /f
Folder PATH listing for volume DATA009_HOMES
Volume serial number is B88B-384C
H:.
└───1
└───2
└───3
└───4
└───5
embed.bat
```
[Answer]
# Zsh, ~~63~~ ~~60~~ ~~58~~ 52 \* 0.9 = ~~56.7~~ ~~54~~ ~~52.2~~ 46.8
```
s=$(<$0);for i in {1..$1};{mkdir $i;cd $i};echo $s>f
```
Example:
```
llama@llama:...Code/misc/foo$ zsh f 5
llama@llama:...Code/misc/foo$ ls -R
.:
d1 f
./d1:
d2
./d1/d2:
d3
./d1/d2/d3:
d4
./d1/d2/d3/d4:
d5
./d1/d2/d3/d4/d5:
f
llama@llama:...Code/misc/foo$ cat d1/d2/d3/d4/d5/f
s=$(cat $0);for i in {1..$1};do;mkdir d$i;cd d$i;done;echo $s>f
llama@llama:...Code/misc/foo$ cat f
s=$(cat $0);for i in {1..$1};do;mkdir d$i;cd d$i;done;echo $s>f
llama@llama:...Code/misc/foo$ diff f d1/d2/d3/d4/d5/f
llama@llama:...Code/misc/foo$
```
[Answer]
# Rebol - 114 \* 0.9 \* 0.5 = 51.3
```
do b:[d: copy %./ repeat n do input[mkdir repend d[n"/"]]write join d s: system/options/script join"do b: "mold b]
```
Ungolfed:
```
do b: [
d: copy %./
repeat n do input [
mkdir repend d [n "/"]
]
write join d s: system/options/script join "do b: " mold b
]
```
### Original non-quine version - 90 \* 0.9 = 81
```
d: %./ repeat n do input[mkdir repend d[n"/"]write join d s: system/options/script read s]
```
Ungolfed:
```
d: %./
repeat n do input [
mkdir repend d [n "/"]
]
write join d s: system/options/script read s
```
[Answer]
# Bash 167\*0.5\*0.9 = 75.15
Borrowing heavily from [@es1024's great answer](https://codegolf.stackexchange.com/a/43205/11259), but this one is a true quine, so it qualifies for both bonuses.
```
b=\' c=\\ a='d=`seq -s/ $1`;mkdir -p $d;echo b=$c$b c=$c$c a=$b$a$b>>$d/$0;echo $a>>$d/$0'
d=`seq -s/ $1`;mkdir -p $d;echo b=$c$b c=$c$c a=$b$a$b>>$d/$0;echo $a>>$d/$0
```
Also, shell quine techniques from [here](http://c2.com/cgi/wiki?QuineProgram).
[Answer]
# AutoIt3, 106 \* 0,9 = 95,4 bytes
---
A bit long but I can't help with those long function/variable names:
```
$f = @WorkingDir
For $i = 1 To $CmdLine[1]
$f &= "\" & $i
Next
DirCreate($f)
FileCopy(@ScriptFullPath, $f)
```
Simply call it with `<script/.exe name> <depth>` eg. `script.exe 5`.
It will work for any amount of directories; maybe even more than your file system can handle. :D
## How it works:
It's just a simple loop that adds the index to a string. Then the directory (and all parent directories, too) get created and the file copies itself to that directory.
[Answer]
# Node.js, ~~136~~ 133 \* 0.9 \* 0.5 = ~~61.2~~ 59.85
```
r=require,f=r('fs'),p=__dirname;while(i=process.argv[2]--)f.mkdirSync(p+='/'+i);f.linkSync(a=__filename,p+'/'+r('path').basename(a))
```
`fs.linkSync` maps to the POSIX call [link](http://pubs.opengroup.org/onlinepubs/009695399/functions/link.html), which creates a hard link. An invalid argument will cause the program to crash.
[Answer]
# J, 82 \* 0.9 = 73.8
This is mostly a port of the top-voted answer.
```
exit (1!:1[1{A) 1!:2 <] (s,'/',>1{A)[fpathcreate s=:' /'charsub":1+i.".>{:A=:ARGV
```
Save as `skittish.ijs` or whatever you want, and call it from the command line using your version of `jconsole`. Mine is symlinked to `jc`:
```
$ jc skittish.ijs 20
$ ls 1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/skittish.ijs
1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/skittish.ijs
```
[Answer]
# [Zsh](https://www.zsh.org/), 55 \* 0.9 \* 0.5 = 24.75 bytes
I had my eyes on this challenge for a long time, but I wanted to complete it in Zsh without calling any external programs like `mkdir` and `ln` (otherwise, it would be identical to the bash solution). Turns out, Zsh can provide its own versions of those programs!
```
zmodload zsh/files
mkdir -p ${(j:/:):-{1..$1}}
ln $0 $_
```
[Try it online!](https://tio.run/##JcuxDoMgFAXQna@4wxugCaiDTcrPNKY8gxbFiEsxfvvr4HK2U0sUqUsOKQ8BtcRmnBIXtXzDtMNuoFPPvvHG27NzjrrrUmkFtaC3HDsz7KCO38a4R1oVf2IGad33eKB1ty9jRJ5/ "Zsh – Try It Online")
] |
[Question]
[
We define \$R\_n\$ as the list of remainders of the Euclidean division of \$n\$ by \$2\$, \$3\$, \$5\$ and \$7\$.
Given an integer \$n\ge0\$, you have to figure out if there exists an integer \$0<k<210\$ such that \$R\_{n+k}\$ is a permutation of \$R\_n\$.
## Examples
The criterion is met for \$n=8\$, because:
* we have \$R\_8=(0,2,3,1)\$
* for \$k=44\$, we have \$R\_{n+k}=R\_{52}=(0,1,2,3)\$, which is a permutation of \$R\_8\$
The criterion is not met for \$n=48\$, because:
* we have \$R\_{48}=(0,0,3,6)\$
* the smallest integer \$k>0\$ such that \$R\_{n+k}\$ is a permutation of \$R\_{48}\$ is \$k=210\$ (leading to \$R\_{258}=(0,0,3,6)\$ as well)
## Rules
* You may either output a truthy value if \$k\$ exists and a falsy value otherwise, or two distinct and consistent values of your choice.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Hint
>
> *Do you really need to compute \$k\$? Well, maybe. Or maybe not.*
>
>
>
## Test cases
Some values of \$n\$ for which \$k\$ exists:
```
3, 4, 5, 8, 30, 100, 200, 2019
```
Some values of \$n\$ for which \$k\$ does not exist:
```
0, 1, 2, 13, 19, 48, 210, 1999
```
[Answer]
# [R](https://www.r-project.org/), ~~63~~ ~~59~~ ~~46~~ 43 bytes
```
\(n,a=c(2,3,5,7))any(diff(s<-n%%a)&s[-1]<a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dc9LCsIwEAbgfU8xVCoJTqHpA1tpj6Eb62KoiQqlSBMXPYubCnooj-ENTGk3Ki7yB2YmfJnrre3vCgp4XIzy0-eiZA1SUbEQI0xwyTk1HduflGI69xvPIz7XW1_scuLTk9cM1poO0lEsTrnjzGAj25PqgOoaTHsxxw6M1AYq0lI7FRnmThM_3ZWLoOl8rjtWsQghRkgQUoQoQBCBjXAMkXEEZY9bNu43qqjW8i_60_1AB8cCNi0vMvsFq4diKGfZiE6L9_14vwE)
-4 bytes thanks to Giuseppe
-13 bytes by switching to `diff`
-3 bytes inspired by a suggestion from Dominic van Essen
(The explanation contains a spoiler as to how to solve the problem without computing \$k\$.)
Explanation:
Let \$s\$ be the list of remainders. Note the constraint that s[1]<2, s[2]<3, s[3]<5 and s[4]<7. By the [Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem), there exists a \$k\$ iff there is a permutation of \$s\$, distinct from \$s\$, which verifies the constraint. In practice, this will be verified if one of the following conditions is verified:
* s[2]<2 and s[2]!=s[1]
* s[3]<3 and s[3]!=s[2]
* s[4]<5 and s[4]!=s[3]
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
Based on the Chinese remainder theorem
```
m=[2,3,5,7]
f x|s<-mod x<$>m=or[m!!a>b|a<-[0..2],b<-drop a s,s!!a/=b]
```
[Try it online!](https://tio.run/##Hco7DoQgEADQfk8xJpaD35htwIsQiiFKJDJiwMLCu7Mb6/c2yvsaQims9IAjTvg1Hwf3k6XguMAt65lVTJqrimb7kBS6a5rBoJViSfEEgoz5j62ypjD5Q53JH1ftfLjWBO7tfWfKDw "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
g.mod
g r|let p?q=r p/=r q&&r q<p=2?3||3?5||5?7
```
[Try it online!](https://tio.run/##DcRBDoIwEAXQvaf4C8POSiDEmNj0IMqiwbY2DjiULufsDrzF@/jtG4g02pcmM//ep4QiFCrYrbaAr0dr0xw92HauF@ndIDK4m84@L7DgkpeKM2KmGgoinq0xXXsf9T9F8mnTy8S8Aw "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~64~~ ~~61~~ ~~59~~ 43 bytes
```
{map($!=(*X%2,3,5,7).Bag,^209+$_+1)∋.&$!}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/OjexQENF0VZDK0LVSMdYx1THXFPPKTFdJ87IwFJbJV7bUPNRR7eemopi7f@0/CIFYx0FEx0FUx0FCx0FYwMdBUMDIGEEIQwtFaq5FIoTKxWUVOJtlXQUivOBlmioxGtac9VyAcU1gAyQISB9QAQ0y9ASaB7QKCNDkAkgviU@Q/4DAA "Perl 6 – Try It Online")
-16 thanks to @Jo King
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~125~~ ~~42~~ ~~38~~ 36 bytes
```
n=>n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3
```
Direct port of @xnor's answer, which is based off of @RobinRyder's solution.
Saved 4 bytes thanks to @Ørjan Johansen!
Saved 2 more thanks to @Arnauld!
[Try it online!](https://tio.run/##JY0xC4MwEIV3f8UhKAonGGPaWqNjp@4dSgcbIg2UEzRtB7V/3SZ0@e7dx4OnpkxNZju9SElDFu/D8Gz7ZqOmpWgvRSwkRVwsFAnJY@4eJpbsS9Gu5Vsd9MOoO/VI3t0IVk8WDAHpz/U2c4QSQSAcEHiOwHKH4g9WIXjlsqNrelG6YsG8rqpqTYM5uIzG6rMhnYRzvh5hZmuIfgX7xJ80rYN1@wE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes
```
!FreeQ[Sort/@Table[R[#+k],{k,209}],Sort@R@#]&
R@n_:=n~Mod~{2,3,5,7}
```
[Try it online!](https://tio.run/##TYu9CsIwGEX3PkWk4OIH@bNohEImN0GjWykSNdRSm0LIFtJXjykuLmc4955R@7cZte@fOnV1Wh2dMZfmOjmP5U0/PqZRTbkZWggDMCJiC8smlSzbdaGkvR9qO5@m1xwYcKhgF9PZ9dYjLDssAwe0BVQB2gPiBBAlGewHKmLx/13m7DNzRUUuc8ToooUQMaUv "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
lambda n:n%5!=n%7<5or n%3!=n%5<3or-~n%6/4
```
[Try it online!](https://tio.run/##LdLLbhNBEIXhfZ7CLCzF0kH0qb6j@EkCC1tgYgkmkZUNG17d/I1YjDRTU9Uz5@t@@/3@8rrF/XL8cv95@nX@dtptn7d9/XDc9v2pvt522z6vh/qUX28f/2z79qncT8fnrKKqpq6hKSfZcshFrnKTuzwUSWFFKLKiKKqiKbqCV1M5KVs5lLNyUa7KTbkrT5WkYpVQ4UNFpao0lamaVK0aqlm1qjbVrjpUp1pSy2pFjf9qal1tqid1q4d6Vedvu/pQnxpJwxqhUTSqRtMgCVGsGZpZs2hWzabZNamvjIRMpEzETIRMpPwXnNqK7sxF/gWwBBYBBjazQDiWEH1YGAyjYTiMhwExIobEmBgUo2JYjIuBMTLGxcC4LGrqqLisOvPwGB8DZHhc117QA5JRMkzGyUC50dNYAzFD5rY2jb5GD2zGzcAZOUPnvnaUNdAzah7MQWfsDJ7H2m7mJnMYGkSjaAwNolE0jMYxcAwcA8dInIvEwcAz8IzE2Ujj68PD@fi87S7r/O2u2@522n58fwynw/WyuzxuBzrebtft/fF0PJ4P/@/Ph/tf "Python 2 – Try It Online")
Uses the same characterization as [Robin Ryder](https://codegolf.stackexchange.com/a/182676/20260). The check `n%2!=n%3<2` is shortened to `-~n%6/4`. Writing out the three conditions turned out shorter than writing a general one:
**46 bytes**
```
lambda n:any(n%p!=n%(p+1|1)<p for p in[2,3,5])
```
[Try it online!](https://tio.run/##LdLLahtBEIXhvZ9CWRgkchZ9qu8hehLFC4lEiSAZD8IbQ95d@cdkMTD0VPX0@brW97dfr0s8rsdvj9/nP5fv593y5by875fn9dNxed6vn/3Xh6/r7vp6362723IKZdWXw@N8PGUVVTV1DU05yZZDLnKVm9zloUgKK0KRFUVRFU3RFXyayknZyuyalYtyVW7KXXmqJBWrhAo/KipVpalM1aRq1VDlJFW1qXbVoTrVklpWK2qcq6l1tame1K0e6lWd03b1oT41koY1QqNoVI2mQRKiWDM0s2bRrJpNs2uyvmUkZCJlImYiZCLlR3DWtujOPOTfADaBjQADm14gHJsQdVgYDKNhOIyHATEihsSYGBSjYliMi4ExMsbFwLhs1Kyj4rKt0w@P8TFAhsd1uwtqQDJKhsk4GSg3ahp7IGbI3LZLo65RA5txM3BGztC5bzfKHugZNQ/6oDN2Bs9ju276Jn0YGkSjaAwNolE0jMYxcAwcA8dIzEViMPAMPCMxG2m8PD1djqflY/AWBm93Py8/f@zD6XC77q775UDFer8tb/vz8Xg5/H@/HB7/AA "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->n{[2,3,5,7].each_cons(2).any?{|l,h|n%l!=n%h&&n%h<l}}
```
[Try it online!](https://tio.run/##JY3fCoIwFMbvfYrThVpxEt2UEpo9yBhhongxTpF5IduefW0IHz/4/sD3XV@bn4S/dGQkQ44NXlUx9sP8HN60HNmp6Gl7GKtxtpTqg6B0zrKAu3bOS45QIzQINwReIlRlANtRtQgxCgqz6OqwYlUso2/b/QkMWLLJZ/0tIAknSUqdcxAd5Inzfw "Ruby – Try It Online")
Uses [Robin Ryder](https://codegolf.stackexchange.com/a/182676/6828)'s clever solution.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes
```
Or@@(Min[s-#]>0&/@Rest@Permutations@Mod[#,s={2,3,5,7}])&
```
[Try it online!](https://tio.run/##TYuxCoMwFEX3fsUDQVp4RZNU2gyW9wNS6SoOoQ3qEAWTTpJvT5906XKGe89xJozWmTC9TBrq9FiJjs00d/6c9fcyL@hpfaDWru4T2FpmT83y7jL09SZRYYXX2J/y1K7THKCgoaBNIVwQKoQbgioRRMmQPwgdD//ufvPO5EpoLjmSYp@11jGlLw "Wolfram Language (Mathematica) – Try It Online")
Finds all non-identity permutations of the remainders of the input modulo 2, 3, 5, 7, and checks if any of them are below `{2,3,5,7}` in each coordinate. Note that `Or@@{}` is `False`.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 36 bytes
```
n->n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3
```
[Try it online!](https://tio.run/##PU9La4NAEL77K4bABi2rxOi2NTG591Ao5Fhy2PoIa3UVdwyUxv51O6shC/MNM/M92EpepV/l35NqurZHqGgOBlR1UA46Q9Xq4GnvZLU0Bt6l0vDrAHTDV60yMCiR2rVVOTR0c0/YK335PIPsL8abqQBvGj/6IleZxAJKOEzaP2r2koq1SDWLxE0zkUbriIZQ3Pw/zZ6P0bSftUojuWFh0MDh7mdfxCHmIDi8cog2HMINwXaBMOEPnj3RjpAUdICYBNvQrpMkudPGJatse5fy5rTdkuk9Ik8/BosmaAcMOvojlu6KxfkOmGF6xWc2hzKw3bXgeYvp6Ngap38 "Java (JDK) – Try It Online")
## Credits
* Port of xnor's solution, improved by Ørjan Johansen.
[Answer]
# [R](https://www.r-project.org/), 72 bytes
```
n=scan();b=c(2,3,5,7);for(i in n+1:209)F=F|all(sort(n%%b)==sort(i%%b));F
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOsk2WcNIx1jHVMdc0zotv0gjUyEzTyFP29DKyMBS083WrSYxJ0ejOL@oRCNPVTVJ09YWzM4EsTWt3f4b/wcA "R – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~81~~ ~~78~~ 72 bytes
```
while($y<3)if($argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u)die(T);
```
A riff on [@Robin Ryder's](https://codegolf.stackexchange.com/a/182676/84624) answer. Input is via `STDIN`, output is `'T'` if truthy, and empty `''` if falsy.
```
$ echo 3|php -nF euc.php
T
$ echo 5|php -nF euc.php
T
$ echo 2019|php -nF euc.php
T
$ echo 0|php -nF euc.php
$ echo 2|php -nF euc.php
$ echo 1999|php -nF euc.php
```
[Try it online!](https://tio.run/##JctBC4IwGIDhv7Lgq31DwmhIgRtdIujSJW8hoTjnwOaYjvDXr6zr8/K6zkVxcp0jyvvBP71yg5@M1bhjOYHKa0skabWaRrwX5@vtq2lKRvMKfTUpspxbe4nvzvQKYRacmRZ/3xohSLrnGX3AXLKVRKjlv1CeHRZNkpJtoBYQWGMUFiyP8fgB "PHP – Try It Online")
### Or 73 bytes with `1` or `0` response
`while($y<3)$r|=$argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u;echo$r;`
```
$ echo 2019|php -nF euc.php
1
$ echo 1999|php -nF euc.php
0
```
[Try it online (all test cases)!](https://tio.run/##LY5Ba4NAEIXP3V8xDdO6koWoG2ntKj0VeigkdyvBhE0MhCjjSpG2v93O1lwezPtm3puu6ab8tWs6sEQt7ch2Lbnz9SSj0AiBzvauhwJKAVCCVrBWkCp4VqAjBXHEkswSZwruVitwNFhe9pRtVj7ybM03SeztLMug8qvH@tJbUXHPsSVbHxoJc2EZVVD3gDWdrhDCN@ch8Rc4skSGR3to2pkrWLx8uoWZvprzxUoccx0i/RT/8EHiUASJToMSxyq8LyTubyTQ6ZN3l8sqfMR9joPxoUhmusVv37e7t82HEb9i@gM "PHP – Try It Online")
### Original answer, ~~133~~ 127 bytes
```
function($n){while(++$k<210)if(($r=function($n){foreach([2,3,5,7]as$d)$o[]=$n%$d;sort($o);return$o;})($n+$k)==$r($n))return 1;}
```
[Try it online!](https://tio.run/##lY9Ba8JAEIXPza94lS3ZxQUTrbS6BvHQ0oJQwWMaJOimCZVs2Ky0IP72dBLtoYdSehmYmffme1PlVTObV3kFba2xG6srY11RvvFAKLAsarJDuXWFKTkrxfEjL/aa9/vsfTYMA1FknDMb/ZBkxup0m/N4KEdyLO@StGY7wUycRKy8YTtVE4AzI5TV7mBLZtRJkJNuiihitj0iziuE6tQoz2NO165GhNgDYowkbiXGEvcSo0AiDKgMzyWcIJG4Ggzg7EF38lZBK6pkDCdkJh@lb5sJyVtxlu5r7SXEujjRIb3vZ3COEAcJ0poaCBzpuN7mhjqJ3vTV9STYJ4VkGe8UNP0ezuGvFuu1jyn8x8Xz0pdYPa02Dy9L5Z06ZhfgF2j4L@iFev0XtvkC "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda x:int('4LR2991ODO5GS2974QWH22YTLL3E3I6TDADQG87I0',36)&1<<x%210
```
[Try it online!](https://tio.run/##JYxNC4JAGIT/ynup1djA3fVrQ4PAMEEIS4hQD0YtCaViHjbE324rXR5mhplpv/2zqdkk/Hx6le/bvQS5qepeQ2Z8opyTY3C0wjPljplcDpRe0zhmexbZabALktB1IgNhZutL4nlyQYkxtd08X2UCDXKE9RYGoUl9RCCaDiRUNWQMg4nBwuBiYAYGYijQPwjHMEdKK6rmHJiqqL5nw3lR4M@j9VFeI336AQ "Python 3 – Try It Online")
Hardcoded
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ƶ.L+ε‚ε4Åp%{}Ë}à
```
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8a1LkwrzrXigJrOtTTDhXAle33Di33DoP//MjAxOQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2SwqO2SQpK9v@PbdXz0T63NeJRw6xzW00OtxaoVtce7q49vOC/zv9oYx0THVMdCx1jAx1DAwMdIzA2tNRRAPJ1jHQMjXWAHBMLHSNDoIClpWUsAA).
**Explanation:**
```
Ƶ.L # Create a list in the range [1,209] (which is k)
+ # Add the (implicit) input to each (which is n+k)
ε # Map each value to:
‚ # Pair it with the (implicit) input
ε # Map both to:
4Åp # Get the first 4 primes: [2,3,5,7]
% # Modulo the current number by each of these four (now we have R_n and R_n+k)
{ # Sort the list
}Ë # After the inner map: check if both sorted lists are equal
}à # After the outer map: check if any are truthy by taking the maximum
# (which is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ.` is `209`.
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
1 e.(>:+i.@209)-:&(/:~)&(2 3 5 7&|"1 0)]
```
[Try it online!](https://tio.run/##TcqxCsIwFIXhvU/x0yFN0MbcpGJvwCIITk7uTtKiLr6A@OoxODn8y/nOs7S@W9hnOtYEcq33HC/nUxFmb6e8evhDDOr6bOwmf5yxkcSWnXm3QnDX4hqa@XZ/sWCmakPVkRSQEIi/RP8eFYhIQpRhJEodVJXyBQ "J – Try It Online")
Brute force...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
8ÆR©PḶ+%Ṣ¥€®ċḢ$
```
[Try it online!](https://tio.run/##y0rNyan8/9/icFvQoZUBD3ds01Z9uHPRoaWPmtYcWnek@@GORSr/rQ@3cx1uB4q4//9vrGOiY6pjoWNsoGNoYKBjBMaGljpAro6RjqGxDpBtYqFjZAgUsLS0BAA "Jelly – Try It Online")
I’m sure there’s a golfier answer. I’ve interpreted a truthy value as being anything that isn’t zero, so here it’s the number of possible values of k. If it needs to be two distinct values that costs me a further byte.
### Explanation
```
8ÆR | Primes less than 8 [2,3,5,7]
© | Copy to register
P | Product [210]
Ḷ | Lowered range [0, 1, ..., 208, 209]
+ | Add to input
¥€ | For each of these 210 numbers...
% ® | Modulo 2, 3, 5, 7
Ṣ | And sort
ċḢ$ | Count how many match the first (input) number’s remainders
```
] |
[Question]
[
>
> based off my previous challenge, [this](https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80) wikipedia article, and a Scratch project
>
>
>
Your task: given `i`, calculate \$\pi\$ till `i` terms of the Gregory-Leibniz series.
The series:
$$\pi=\frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\frac{4}{9}-...$$
Here, `4/1` is the first term, `-4/3` is the second, `4/5` is the second and so on.
Note that for the nth term,
* $$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$
* $$\pi\_n = \text S\_1 + \text S\_2 + ... + \text S\_n,$$
where \$\pi\_n\$ is \$\pi\$ approximated to \$n\$ terms.
Test cases:
```
In - Out
1 - 4
2 - 2.66666667
3 - 3.46666667
4 - 2.8952381
```
Floating point issues are OK.
You may not calculate infinite terms of pi using this as we are calculating a number rather than terms of a series here.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
**EDIT:** It's strange that this question got some new... activity.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~36~~ 35 bytes
```
f=lambda n,k=1:n and 4/k-f(n-1,k+2)
```
[Try it online!](https://tio.run/##BcExDoAgDADAWV/RscQSRZ1IeAwG0QYthLD4erwrX7uzbL1H9/j3CB6EkjNWwEuAfU46omhDaVpVj7kCAwtUL9eJhsAsyo5DqSwNmSAiK9V/ "Python 3 – Try It Online")
-1 thanks to Mukundan314.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L·<z··R®β
```
-5 bytes porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/252054/52210)
[Try it online](https://tio.run/##yy9OTMpM/f/f59B2myoTraBD685t@v/fGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R/i6mevpPCobZKCkr3ff59D222qTLSCDq07t@m/zn8A).
**Original 14 bytes answer:**
```
0λè®N>m4*N·</+
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4NzuwysOrfOzyzXR8ju03UZf@/9/YwA) or [verify the infinite sequence](https://tio.run/##yy9OTMpM/f/f4NzuQ@v87HJNtPwObbfR1649tOz/fwA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
· # Double each value: [2,4,6,...,2n]
< # Decrease each by 1: [1,3,5,...,2n-1]
z # Calculate 1/z for each: [1,1/3,1/5,...,1/(2n-1)]
4* # Multiply by 4: [4,4/3,4/5,...,4/(2n-1)]
R # Reverse the list: [4/(2n-1),...,4/5,4/3,4]
®β # Convert it from a base-(-1) list to a base-10 integer:
# (-1)^(n-1)*4/(2n-1) + ... + 1*4/5 + -1*4/3 + 1*4/1
# (after which the result is output implicitly)
```
The 14-byter is pretty similar as [my 05AB1E answer of the previous challenge](https://codegolf.stackexchange.com/a/251921/52210).
```
λ # Start a recursive environment,
è # to calculate a(input)
# (which is output implicitly afterwards)
0 # Start with a(0)=0
# Where every following a(n) is calculated by:
# (implicitly push the previous term a(n-1))
®N>m # Push (-1) to the power (n+1)
4* # Multiply it by 4
N·< # Push 2n-1
/ # Divide the earlier 4*(-1)**(n+1) by this (2n-1)
+ # Add it to the previous term a(n-1)
```
[Answer]
# [R](https://www.r-project.org), ~~31~~ 28 bytes
*Edit: -3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
\(n,m=2*1:n-1)sum(4i/1i^m/m)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZ7YjTydHJtjbQMrfJ0DTWLS3M1TDL1DTPjcvVzNSFKNqdpGGpypWkYgQhjEGEClVmwAEIDAA)
Uses
$$ (-1)^{n+1} = -1 \times (-1)^{n} = i^2\times i^{-2n} = i^{-2n+2} = i \times i^{-(2n-1)}$$
And then
$$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1} = \frac{\frac{4i}{i^{2n-1}} }{2n-1} $$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
RḤ’4÷Ṛḅ-
```
A monadic Link that accepts a positive integer, \$n\$, and yields a floating point number, \$\pi\_n\$.
**[Try it online!](https://tio.run/##ARwA4/9qZWxsef//UuG4pOKAmTTDt@G5muG4hS3///8z "Jelly – Try It Online")**
### How?
```
RḤ’4÷Ṛḅ- - Link: positive integer, n
R - range n -> [1,2,3,...,n]
Ḥ - double -> [2,4,6,...,2n]
’ - decrement -> [1,3,5,...,2n-1]
4 - 4
÷ - divide -> [4/1,4/3,4/5,...,4/(2n-1)]
Ṛ - reverse -> [4/(2n-1),...,4/5,4/3,4/1]
- - -1
ḅ - convert from base -> (-1)^(n-1)*4/(2n-1)+...+1*4/5+-1*4/3+1*4/1 = pi_n
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ 60 bytes
```
float f(n){float m=4,p=1,d=1;for(;n--;d+=2,m=-m)p+=m/d;--p;}
```
[Try it online!](https://tio.run/##XVDLboMwELznK1ZIkexgk/JIm8h1L1W/ouRAjZ2iBoMwUlERv15qMKWPlWytZ2fGuyvoRYhxVNcqa0EhjXuXljwhNQ9JzkOmqgYxTSnLfR6RktMS1z4v9zmjtGbDWGjLzwqNMPQbsOEsZFdL0cr8@Qwc@oRAFNy6uCMQB8maR8HxdIjiYziwWS4qbVoQr1mzs7cUb7JxHl7aPUVpd3q05@AR@P2OvUVtuwU0tVToXHZWdsOW9B5M8SErhb47w/sF2K0IA9@f2Xg2c/NMMTm21s1Z@RCyteTGNbaoUIv/49Li6ypm9Zn9ca0zM2uzF4MMUJDYdhpKevih1Y0lKuRtc6APsFWwNam2C2gJGLLuaDI6L/8Pm2H8FOqaXcxI378A "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)!!!*
[Answer]
# Excel, ~~51~~ 48 bytes
Saved 3 bytes thanks to some clever math from [JvdV](https://codegolf.stackexchange.com/questions/252030/calculating-pi-using-the-gregory-leibniz-series-until-n-terms/252132?noredirect=1#comment561841_252132)
```
=LET(s,SEQUENCE(A1),SUM((8*ISODD(s)-4)/(2*s-1)))
```
Input is in the cell A1. Output is wherever the formula is.
* `LET(s,SEQUENCE(A1)` defines `s` to be an array of numbers from 1 to the value in A1. This is what lets us calculate the first *n* terms.
* `(8*ISODD(s)-4)` creates an array of the same sized filled with `4, -4, 4, -4, ...`. The only trick is that `ISODD()` returns a boolean and Excel turns TRUE into 1 and FALSE into 0 when you force it to do math. That means it becomes an array of `8-4, 0-4, 8-4, 0-4, ...` which then simplifies as shown above.
* `(2*s-1)` creates an array of the same size filled with `1, 3, 5, 7, ...`
* `SUM((~)/(~))` divides the first array by the second (giving us each term in the sequence) and then adds them up.
[](https://i.stack.imgur.com/86dXU.png)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~41~~ 39 bytes
```
f=lambda x:x and(x%2*4-2)/(x-.5)+f(x-1)
```
[Try it online!](https://tio.run/##NYvLDsIgEEX3fMVsTEEFw6O2NvoxmEokaYEUTOjXI63xLu7kzJkJa3p7J0sxj0nPz1FDHjJoN@J8EEdFBbngTFlLTqZOToqdg18SxDUi4xewYN0GLKbRugFBjXXhDP6T4AGWxTDZhBug0JDdhsW6hA3eul4SUpWZvE64vhC4A3/RjhRe1wqJ2oJdf@mQrCiZ@qPabX9rhez5Fw "Python 3 – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 30 bytes
```
f(n)=∑_{k=1}^n4(-1)^k/(1-2k)
```
Pretty self-explanatory.
[Try It On Desmos!](https://www.desmos.com/calculator/xjdsckqop8)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ksfom64prc)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 10 bytes
```
4ÞNÞ∞d‹/¦i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCI0w55Ow57iiJ5k4oC5L8KmaSIsIiIsIjUiXQ==)
```
4 # 4
ÞN # [4, -4, 4, -4, 4, -4...
Þ∞ # [1, 2, 3, 4, 5, 6...
d # [2, 4, 6, 8, 10, 12...
‹ # [1, 3, 5, 7, 9, 11...
/ # [4/1, -4/3, 4/5, -4/7...
¦ # Take the cumulative sums of that
i # Index the input into that
```
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
f n=foldr((-).(2/))0[1/2..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYtPyelSENDV1NPw0hfU9Mg2lDfSE8vL/Z/bmJmnoKtQm5iga9CQVFmXomCCoijkKYQbaCnZxn7HwA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
4*JpU /(UÑÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=NCpKcFUgLyhV0cQ&input=NA)
## Without Flags, 11 bytes
```
DZZ4/°ZÃÔìJ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=x7FaNC%2bwWsPU7Eo&input=Mw)
```
4*JpU /(UÑÄ :Implicit map of each U in the range [0,input)
4* :Multiply 4 by
J :-1
pU :Raised to the power of U
/( :Divide by
UÑ :U times 2
Ä :Plus 1
:Implicit output of sum of resulting array
```
```
DZZ4/°ZÃÔìJ :Implicit input of integer U
Ç :Map each Z in the range [0,U)
±Z : Increment Z by itself
4/ : Divide 4 by
°Z : Z, prefix incremented
à :End map
Ô :Reverse
ì :Convert from digit array in base
J : -1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 13 bytes
Flag `ḋ` prints out rationals in their decimal form
```
ƛ4nd‹/un›e*;∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLGmzRuZOKAuS91buKAumUqO+KIkSIsIiIsIjQiXQ==)
**Explanation:**
```
ƛ4nd‹/un›e*;∑
ƛ ; Map trough range of input
4nd‹/ Divide four by 2n-1
un›e* Raise -1 to the n+1 and multiply
∑ Sum the fractions
```
[Another 13 byter: `ƛ4nd‹/k-ni*;∑`](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLGmzRuZOKAuS9rLW5pKjviiJEiLCIiLCI0Il0=)
[Answer]
# [Factor](https://factorcode.org/) + `koszul math.unicode`, 51 bytes
```
[ [1,b] [ dup 1 + -1^ 4 * swap 2 * 1 - / ] map Σ ]
```
[Try it online!](https://tio.run/##JYy9CsIwGEX3PsWd1VaiTgquxcVFnEKEmH7V0pjE/CD6Or6PrxSDbvecA7eXKlqfj4fdvl3jJuO1SWZQtqM/eGkuFDCSN6R/CqMNr6QR6J7IqBKdpxifzg8mYlNVy8zB2ewswNElB4YpanbCChOEh3RYlMFQYw5RHh0@b4ispNbY9trKiCZ/AQ "Factor – Try It Online")
* `[1,b] [ ... ] map Σ` Map each integer in 1..input using `[ ... ]` and add them together.
* `dup 1 + -1^ 4 * swap 2 * 1 - /` Just a straight translation of $$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$
Here's how the data stack looks arriving at the second term to add together:
```
! 2
dup ! 2 2
1 ! 2 2 1
+ ! 2 3
-1^ ! 2 -1
4 ! 2 -1 4
* ! 2 -4
swap ! -4 2
2 ! -4 2 2
* ! -4 4
1 ! -4 4 1
- ! -4 3
/ ! -1-1/3
```
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 60 bytes
```
function a(j)
do i=1,j
a=a+4.0*(-1)**(i+1)/(2*i-1)
enddo
end
```
[Try it online!](https://tio.run/##PZDNDsIgEITvPMUeAbGVWn@TPgxa2qwoNJTGx68bUOewGTbDN4QhxBSN345DMesUwxjNCyZkQEKf7GgjXK/g8iJa81SToYhNZR/tvDzTzFsBHfC6rXYKmupYdFKwr9q/b6rz5dDsz7oWDDKvD@A6rZZbWHzPvyzV46vTIgey3hGT5VJJAU6B4U6UWf/KXQlb3xORZX8PPhn0M6zD4u8Jg6crD8GoEanxwUxnNvRaybdaSMlxo0XNG4l0ZAQiDs01M7@/sn4A "Fortran (GFortran) – Try It Online")
Mostly just exploiting implicit typing so no need to declare variable types. Also saves 1 byte by removing the space between end and do.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
*-1 thanks to a clever rearrangement by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
```
Ḟ`-↑M/İ14
```
[Try it online!](https://tio.run/##yygtzv7//@GOeQm6j9om@uof2WBo8v//f2MA "Husk – Try It Online")
### Explanation
Husk's reversed operand order for subtraction really hurts here, but at least Dominic found a nice workaround for the reversed division.
```
Ḟ`-↑M/İ14
İ1 Infinite list of positive odd numbers
4 Integer 4
M For each element in the first argument,
/ divide the second argument by it
↑ Take the first N elements, where N is the program's argument
Ḟ Right-fold the resulting list
`- on subtraction
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 47 bytes
```
float f(n){return--n?(4.-n%2*8)/(n-~n)+f(n):4;}
```
[Try it online!](https://tio.run/##TU/bToNAEH3ufsUJhmSxu70BSZW2xhhf@wOFB1wWS2yHht0akgZ/HZdqrA9zP3PmjJLvSvV9eahzi5JTcGm0PTckJT3xaCLJX9wvgykn@UXBeAA8RknX31WkDudCY3XM7X6y37Bbx9iiqocWq8iyY14R/6yrImAXNvq5o9uTVlYXuwxrXLB93gpEAssJpggF4sWQzGOBcBZd01mMLmEjVZOxUPu8cU6rD93ssl10JfHS9nWRtg8vzmJP4H8desNyWTfgThHI4eeJC6s1ogTjMQVw0n61GTcd3nQbo1Pj8CX3/AJyA7@Eb1Jy5CRgxJ@EMn8z3EDe3qIswApzLeNs4OlY138D "C (gcc) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://dyalog.com), 18 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(4ׯ1*⍳)+.÷(1+2×⍳)
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dNf4VHbBAUDAA&c=0zA5PP3QekOtR72bNbX1Dm/XMNQ2OjwdxAMA&f=Szu0QsFQwUjBWMFEwRQA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
A tacit function.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
IΣEN×X±¹ι∕⁴⊕⊗ι
```
[Try it online!](https://tio.run/##LYi7CoNAEEV/xfIKpgjYpdTGIiIkPzCuQzKwD1lnzedPtvDC4XCu@1J2ibzZkiUqBjoUrxLwpB1T3IvOJayc0XbNWwIfWNKv5swfUsa93lIZ5ZSN0XfNFF3mwFF5w5jK6qulvfYw6@12@j8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input `n` as a number
E Map over implicit range
¹ Literal integer `1`
± Negated
X Raised to power
ι Current value
× Multiplied by
⁴ Literal integer `4`
∕ Divided by
ι Current value
⊗ Doubled
⊕ Incremented
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f i=g[1,3..i*2]
g(h:t)=4/h-g t
g[]=0
```
[Try it online!](https://tio.run/##NYnLCYQwFADvqeIdVfSZn7sqpAQrCEFy0CSsiqzpP4riHAaG8fb4TcuS0gxBOc1KgRgKbojLfB9zJWtfOYjEaaNoWm3YQMFq92GEbP@HLeKcg6aIjJrEoAJJ@GWOn4cvEVcKlG/K@7Zdw0XLTg "Haskell – Try It Online")
I think it's quite self descriptive due to Haskell feature of describing something.
I try to visualize what *g* does, pretty simple : taking a list of *i* denominators but all positive...
```
[1, 3, 5, 7]
4/7
4/5 - (4/7)
4 - ( 4/3 - ( 4/5 - (4/7)))
hence the signs result alternating
4 - 4/3 + 4/5 - 4/7
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Tr[4I^#/I/#&[2Range@#-1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2sQzTlnfU19ZLdooKDEvPdVBWdcwNlbtv0t@tEJAUWZeSXR1WnRWrI6CXzSIjq0FMquzdAx1TGoVYv8DAA "Wolfram Language (Mathematica) – Try It Online")
Unnamed function that takes a positive integer argument and returns an exact fraction (the TIO footer shows both the output fraction and its decimal equivalent). Managed to beat the super straightforward `Sum[-4(-1)^j/(2j-1),{j,#}]&` by one byte by using powers of the complex unit `I` instead of powers of `-1`.
[Answer]
# x86 32-bit machine code, 23 bytes
```
D9 EE D9 E8 D9 E8 D8 C0 DC E9 D8 F1 DE E2 E2 F4 DD D8 D8 C0 D9 E1 C3
```
[Try it online!](https://tio.run/##bVLbTgIxEH2mXzGuIWlhISwmxoDrF@iLTyZqSLeXpUlpybaLi4Rfd21Z8IL2odM5czpzelI2Khlr20tlmK65gFvnubLj5R36BWlVnGOVMmXE0GJBfciK2ovFAmNJnWdUa0JAW1MCt3WhBUisjAdD5rCxioMwHJM5om4FGB4TjMaltgXVIJGc9aTm7yjuGapmXexJyjk4jyck7UKAXF3Ec/YD4mrzg5UdWdU6ZtNvnrZ2DVUs@vXX3X8m0MKhXiU8CoJniCQQRKP4khVV5vAkWpUsBbakFQwGIdkQtEMQViw2kMMkhW0M8wP6tlTBDTwcNnCbQ3ZNDmhc6@ColzjpTxWM7qA/zm7u5YtJUmjSYF9DSNfhxHsxD5QtlRHALBez5FhuvmdxC7sTG/qT6VPotc0xro1TpRH8oHpAJHluhsNXMt@f1P1hBLUXOZzDwZMzTYD7CoqtF450yo/14GBdmahrj9r2g0lNS9eOVlfTsIVPkIfrQn8C "C (gcc) – Try It Online")
Following the `fastcall` calling convention, this takes a number `n` in ECX and returns the sum of the first `n` terms on the FPU register stack.
This code creates −2/1, −2/3, −2/5, ..., and combines them using the reverse-subtract instruction. This is equivalent to negating the running total before adding each term; this handles the alternating signs, but leaves the result with the wrong sign for odd `n`, which is corrected for by taking the absolute value at the end (because all the correct results are positive). The value is also doubled at the end.
In assembly:
```
# Example execution for i=2
# FPU register stack (left is bottom):
f: fldz # 0
fld1 # 0 1
r: fld1 # 0 1 1
fadd st(0), st(0) # 0 1 2
fsub st(1), st(0) # 0 -1 2
fdiv st(0), st(1) # 0 -1 -2/1
fsubrp st(2), st(0) # -2/1 -1
loop r #[The loop executes again:
# -2/1 -1 1
# -2/1 -1 2
# -2/1 -3 2
# -2/1 -3 -2/3
# -2/3+2/1 -3 ]
fstp st(0) # -2/3+2/1
fadd st(0), st(0) # -4/3+4/1
fabs # -4/3+4/1 (but for odd n, this fixes the sign)
ret
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 9 bytes
```
-´4÷1+2×↕
```
[Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=UCDihpAgLcK0NMO3MSsyw5fihpUKClDCqCAxK+KGlTY=)
### Explanation
```
-´4÷1+2×↕
↕ Range [0, n)
2× Double each number
1+ Add 1 to each number
4÷ Divide 4 by each number
-´ Right fold on subtraction
```
[Answer]
# MATLAB, 34 bytes
```
f=@(n)sum(4./[1:4:2*n,-(3:4:2*n)])
```
An anonymous function that makes an array of [ 1 5 9 ... -3 -7 -11 ...], member-wise divides 4 by the array and then sums the result.
Test:
```
arrayfun(f, 1:4)
ans = 4.0000 2.6667 3.4667 2.8952
```
[Answer]
# [Rust](https://www.rust-lang.org/), 62 bytes
```
fn f(n:f32,k:f32)->f32{if n==0.{return 4./k}4./k-f(n-1.,k+2.)}
```
[Try it online!](https://tio.run/##PY9NasMwFIT3OcXUi2ITSfEvFLsOlBAoFLLo1njhJDIYp0qQZCg1OkXprqfrRVwpONFiNIt535snB6WnqRVofZG3SUx6pwFdWx27FqIsQzZKrgcpkLJVb5xQm6YRI/0yZoFx4x9NJ/wA4wL2nbgG/7zwg@ZHlKiUPuYOm@e7lx2xGIInhhUSa7LYuSizNgnTqw8zVhdX0OEslMbmdbt5277nqB6VlgXi2kG9v98fj8B@394cb88SAp1AyFg6d7n1UXbGtkaj4M5ExILiHrjITuiTePC90YCuYXU0Fi4IFLntr3xfgd4Pq8QyqgPW7JW9@xkRp1ng6IPqvng9w83CTP8 "Rust – Try It Online")
[Answer]
## [Math++](https://esolangs.org/wiki/Math%2B%2B), 49 bytes
```
?>x
1>a
1>b
k+b*4/a>k
a+2>a
-b>b
x-1>x
4+5*!x>$
k
```
[Answer]
# [Raku](https://raku.org), 26 bytes
```
[\+] (4,-*...*)Z/(1,3...*)
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FCcWqhg@z86RjtWQcNER1dLT09PSzNKX8NQxxjM/G@tUJxYqaCkEq9gawdWHq0SH6ukkJZfpBBnaPAfAA "Perl 6 – Try It Online")
This is an expression for the infinite sequence of partial sums.
* `(4, -* ... *)` is the sequence 4, -4, 4, -4, ....
* `(1, 3 ... *)` is the sequence 1, 3, 5, ....
* `Z/` zips those two sequences together using division.
* `[\+]` produces the sequence of partial sums.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 33 bytes
```
0$\~n;
(?\:2%2*1-4*$:}2*1-,+$1-:1
```
[Try it online](https://tio.run/##S8sszvj/30Alpi7PmkvDPsbKSNVIy1DXREvFqhbE0NFWMdS1Mvz//79umQkA)
[Answer]
# TI-Basic, 22 bytes
```
sum(4/seq((1-2I)(-1)^I,I,1,Ans
```
Takes input in `Ans`. The first `-` is the subtraction sign, and the second is the negative sign. Only works for inputs less than or equal to 999, or 99 on a TI-83. For larger inputs, use this:
### 29 bytes
```
Input N
For(I,1,N
Ans+4(-1)^I/(1-2I
End
Ans
```
The first `-` is the negative sign, and the second is the subtraction sign. Assumes being run on fresh/RAM cleared calculator.
[Answer]
# APL (Dyalog Unicode), 10 bytes
```
4×-/÷1+2×⍳
```
[Try it on TryAPL.org!](https://tryapl.org/?clear&q=%E2%8E%95IO%E2%86%900%20%E2%8B%84%204%C3%97-%2F%C3%B71%2B2%C3%97%E2%8D%B34&run)
The environmental variable ⎕IO←0.
A tacit function.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
*4smc^_1dhy
```
[Test suite](https://pythtemp.herokuapp.com/?code=%2a4smc%5E_1dhy&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0)
##### Explanation:
```
*4smc^_1dhy | Full code
*4smc^_1dhydQ | with implicit variables
--------------+
m Q | For each d from 0 to input:
c^_1dhyd | (-1)^d/(2d+1)
s | Sum the results
*4 | Print sum * 4
```
] |
[Question]
[
In my [previous bioinformatics challenge](https://codegolf.stackexchange.com/questions/194297/mutate-my-dna-sequence), I asked you to mutate a DNA sequence. This time, I'd like you to evaluate how likely a mutation, or a series of mutations, is.
The two types of substitutions are [transitions and transversions](https://en.wikipedia.org/wiki/Transversion), and due to the chemical structure of DNA bases, transitions are more likely to occur than transversions. A transition is when a base is turned into one of the same size (purine -> purine or pyrimidine -> pyrimidine), and a transversion involves two bases of different sizes (purine <-> pyrimidine). Following Kimura's model, postulated in 1980, we can define `a` as the probability of a transition occurring for each unit of time, and `b` as the probability of a transversion occurring.
See diagram below. A and G are purines, C and T are pyrimidines.
[](https://i.stack.imgur.com/qiJS5.png)
Although the exact values of `a` and `b` change from organism to organism (and even between different areas in an organism's genome), we can set `a=0.25` and `b=0.1` for this challenge.
Given two DNA strings of same length as input, I would like you to calculate how likely it would be for string B to be a mutated version of string A. This is code golf, so fewest bytes wins!
Test cases:
```
Input String A | Input string B | Output probability
tgcctatc | tgcctata | 0.1
aggttcctt | gggttcctt | 0.25
aactgg | aaccgg | 0.25
atgccct | atcgcct | 0.01
tatcactaag | tgtcaatgag | 0.00625
ctcctgggca | cttttgcgca | 0.00625
ctgtgtgct | cagagagca | 0.0001
atcgctttca | ttggctttca | 0.01
attcac | taagcg | 0.000001
attttcattg | attttttacg | 0.000625
```
Specifications:
* The input DNA strings can be as strings of characters, binary or numerical.
* We will assume that all of the mutations are independent events.
* The output can be in plain notation (0.00015) or scientific (\$1.5\times10^{-4}\$).
If you have any questions or require more specifications, send them my way in the comments!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
^ị“½¥¢‘İP
```
[Try it online!](https://tio.run/##ZU@xSgNREKz1K8JZCUGfEZPfsLIJEZZFFkIq2SbdJa2dVQptBLWREAsLkTSX5EPyfuQ5uy93Hnj34N3czM7Mju8mk2lKt/ufh1g@VevqtXqJ5WK7uk7AxKK4epeDfiyfp/FzeRPnHzib9/PN232cfZ3uHvffi5SGx8PC1ETELEW34whHVItRF6wKs5KycYdvAnN00glnFzYtkOK3mkAacFD0rkxCrJLNLUWMbLHmyj6OGEto@GABFg4DIskVgDBCUkeE0HcftmAUYDIdOiiMDf3T2XaSE5nE3rbKQ70JHLIZnGpUy7LImrkA7fhvrxAaG5/CfF7PH@JWdy81@gU "Jelly – Try It Online")
Takes input as `2376` instead of `acgt` respectively. The Footer does this for you
-1 byte thanks to Jonathan Allan!
## How it works
```
^ị“½¥¢‘İP - Main link. Takes the first input on the left and the second on the right
^ - XOR the corresponding elements
“½¥¢‘ - Yield [10, 4, 1]
ị - Index into this array, 1-indexed and modularly
İ - Take the inverse of each
P - Take the product
```
### Why this works
| Characters | As integers | `XOR` | 1-index into `[10,4,1]` | Inverse |
| --- | --- | --- | --- | --- |
| `aa` | `2, 2` | \$0\$ | \$1\$ | \$1\$ |
| `cc` | `3, 3` | \$0\$ | \$1\$ | \$1\$ |
| `gg` | `7, 7` | \$0\$ | \$1\$ | \$1\$ |
| `tt` | `6, 6` | \$0\$ | \$1\$ | \$1\$ |
| `ac` | `2, 3` | \$1\$ | \$10\$ | \$0.1\$ |
| `ag` | `2, 7` | \$5\$ | \$4\$ | \$0.25\$ |
| `at` | `2, 6` | \$4\$ | \$10\$ | \$0.1\$ |
| `cg` | `3, 7` | \$4\$ | \$10\$ | \$0.1\$ |
| `ct` | `3, 6` | \$5\$ | \$4\$ | \$0.25\$ |
| `gt` | `7, 6` | \$1\$ | \$10\$ | \$0.1\$ |
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~18~~ ~~16~~ ~~13~~ ~~12~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
^Tη4ªsèzP
```
-4 bytes by porting [*@Arnauld*'s JavaScript answer (his first version)](https://codegolf.stackexchange.com/revisions/218833/1)
-2 bytes by taking the inputs as lists of codepoints (thanks *@cairdCoinheringaahing*)
-3 bytes by taking the inputs as `[0,1,2,3]` for `agct` respectively
-1 byte thanks to *@cairdCoinheringaahing* by porting [his Jelly answer](https://codegolf.stackexchange.com/a/218836/52210) (and now taking `[0,1,2,3]` for `acgt`)
-1 byte thanks to a tip of *@JonathanAllan* (and now taking `[2,3,7,6]` for `acgt`)
Inputs as two lists of integers `[2,3,7,6]` for `acgt` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f8/LuTcdpNDq4oPr6gK@P8/2kzHXMdMx1jHCAhBbCMd81guoKgRVNRYxwwsZx4LAA) or [try it online with strings input](https://tio.run/##yy9OTMpM/f@oYda5rUqJyeklSsaH5z5qWBhcm/A/7uhexcOLHjU1XdhUfHhFVcD//yWJJcmJySWJielcJelAZmJJemI6AA) or [verify all test cases](https://tio.run/##PY4xCsJAEEWvErZRIZWKljYeQNAuRBwHGawsHAQFQSw8gDewERFbsRLB9B4iF4l/Jsbd5v/5f97uYknT@axYrXvrzz0Qi4Zmq9vJd6fhtl@Ls2e@v@W7c5K9UnMhqptsRPnhGIXepBiPPo/2@7rMLptBERdJElSYlZRDXEkKaZwEElGFVwTy154QqwjGEAzhM9tl6wJlGJ8aF2UicToMelRusAEBZkIGtIJgpszErvOYxO4vcTq6voWVypSZvWZzPMjVvzxH07/mhyxLvw).
**Explanation:**
```
^ # Bitwise-XOR the (implicit) input-lists at the same positions together
T # Push 10
η # Pop and push its prefixes: [1,10]
4ª # Append a 4: [1,10,4]
sè # Index (0-based modular) the XOR-ed values into this list
z # Take 1/v for each
P # And take the product of the list
# (after which the result is output implicitly as result)
```
Here the transformations per pair:
| Character-pair | values | XOR-ed | 0-based index (modulo-3) | indexed into `[1,10,4]` | 1/v |
| --- | --- | --- | --- | --- | --- |
| `aa` | \$2,2\$ | \$0\$ | \$0\$ | \$1\$ | \$1\$ |
| `cc` | \$3,3\$ | \$0\$ | \$0\$ | \$1\$ | \$1\$ |
| `gg` | \$7,7\$ | \$0\$ | \$0\$ | \$1\$ | \$1\$ |
| `tt` | \$6,6\$ | \$0\$ | \$0\$ | \$1\$ | \$1\$ |
| `ac` | \$2,3\$ | \$1\$ | \$1\$ | \$10\$ | \$0.1\$ |
| `ag` | \$2,7\$ | \$5\$ | \$2\$ | \$4\$ | \$0.25\$ |
| `at` | \$2,6\$ | \$4\$ | \$1\$ | \$10\$ | \$0.1\$ |
| `cg` | \$3,7\$ | \$4\$ | \$1\$ | \$10\$ | \$0.1\$ |
| `ct` | \$3,6\$ | \$5\$ | \$2\$ | \$4\$ | \$0.25\$ |
| `gt` | \$7,6\$ | \$1\$ | \$1\$ | \$10\$ | \$0.1\$ |
[Answer]
# JavaScript (ES6), ~~52~~ 51 bytes
Expects two lists of codepoints as `(a)(b)`.
```
a=>b=>a.map((c,i)=>p/=!(c^=b[i])|22%c&4||10,p=1)&&p
```
[Try it online!](https://tio.run/##bZDBToQwEIbv@xS1iaRNsBSi3srB19isyTBCg1kXsoyeeHecsi3uqvT0lY9//uEdvmDCcz/Sw2l4a5fOLeDqxtVgPmBUCvNeu3os3J3CV9fs@4Oeq@oes8d5Lm0@ulJn2bhQO5FwQkEuGi1cLXA4TcOxNcfBq07tjTEvn13XnhXog77mhlnvdiFASfKIBIRSiFwkAiYtikJYU0YPvCfilySD538oetVTEgHJew5YA5kw0h8xDEOSUST0kaJo0@hQj0MBvFwrMvG3TEm0z1sohlbcDiG4XJB4SqB/XR8OXlZC8OGwuhWwW4W1HWddYjkz0e@uEG4xbR8648321t6kriEcJ9c/sD6AV4uFtss3 "JavaScript (Node.js) – Try It Online")
### How?
Given the code points **p** and **q** of the nucleobase characters, we use the formula:
```
(22 MOD (p XOR q)) AND 4
```
whose result is **4** for a transition pair (`a <-> g` or `c <-> t`) or **0** otherwise. Conveniently, **4** is the inverse of the probability of said transition.
```
c0 | c1 | p | q | x = p^q | 22%x | &4
-----+-----+-----+-----+---------+------+----
'a' | 'a' | 97 | 97 | 0 | NaN | 0
'a' | 'c' | 97 | 99 | 2 | 0 | 0
'a' | 'g' | 97 | 103 | 6 | 4 | 4
'a' | 't' | 97 | 116 | 21 | 1 | 0
'c' | 'c' | 99 | 99 | 0 | NaN | 0
'c' | 'g' | 99 | 103 | 4 | 2 | 0
'c' | 't' | 99 | 116 | 23 | 22 | 4
'g' | 'g' | 103 | 103 | 0 | NaN | 0
'g' | 't' | 103 | 116 | 19 | 3 | 0
't' | 't' | 116 | 116 | 0 | NaN | 0
```
[Answer]
# [R](https://www.r-project.org/), ~~77~~ 73 bytes
(input directly as DNA sequence)
```
function(t,f,`+`=utf8ToInt,d=abs(+t-+f)).1^sum(d>0)*2.5^sum(d%in%c(6,17))
```
[Try it online!](https://tio.run/##bZBBb4JAEIXv/gpDY7IrW7KYaHuh9957bhxHmXAQmzok/ff0zSqCUbjMwLffe/DbH/5@jp1Wfd21rM2pdRrqsM23Vaf1@9fps9Wwr2h3drm@5rX3Rfl97o5u/xH9clWsL8uiaRfsNqF88/5qdJkKs5JyFoaRMj9/mceinA0MiajinQKS23yhVusRI1YRMBgYwyNgCWwWBFrYFYljlFWBhkhSISw4RIMrbiY2thqowwQUhRR2W56iYneKZhK7RzBO4lMvmJITwmF56En2OP00VGUZXfe2dBqe9MnpoimMjv0/ "R – Try It Online")
---
# [R](https://www.r-project.org/), ~~53~~ ~~50~~ 48 bytes
(input as vector of `1` for A, `2` for C, `3` for G, `4` for T)
```
function(t,f,d=(t-f)^2).1^sum(d>0)*2.5^sum(d==4)
```
[Try it online!](https://tio.run/##pVQ9b4MwEN37KyK62BVFhiZVF7p37xzpdIFrhpCIPKT@e3oGBtLtDB6Qh@f3dXY/Nr@3y4B6bIeOcb52Dnmbn2qH19YfK1@Ux/twcafP4F@q4jBv6nrvF6Cje3Hu0EjTuwHtx/f1q4PjH@rRu4xYkOVZWb3t9QdhBoEz731ux1HE@d3zLhTlk52dRAA9CFZ6WQNn/uqQIoAYIlZ2RfGM2kIdI2Szc@1KFthMHlKCj5WrdSKxF69I1U4r/@E9KQGODWqTTFYRWjw0vgW5UYTEZS@CSeJ6kBCSypgqVUP2HDSEFXLDPFA8w/4I6PywPPhPTWAyoXbs12H66J8MnYXxDw "R – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
%@10 4*/@({~(>ag`ct)e.~/:~"1)~:#,.
```
[Try it online!](https://tio.run/##dZHBSsQwEIbv@xTDiqSR3WwiroeAuih4Eg8@gcOwjuzFy9yEvnqdSdJUYW1o6U@//PmSnqZ1cB9wl8HBBiJkvbcBnt5enqfLQ4pwc7U7DN/jcI/8TuKPYdzlcZ38mC82YfKrI31@gUPRi/TJWlaTCBK79t2t6svghIkEhRyAki2h8wCwzQAxpJlEZu0kEWck9@Rn8nrfUSRh1spSqok0WeUZ1JYkcQ0VMoPKVjR2AdPUYsSyKWFNOhutuaHxdikms1NLQqPJDoDJ0j8026C6OUK2UeBOLyLFshxwEdFVWurVyfwX3Lzn0zB/@nsa0a4Er48BHn5NOv8HF33zn34A "J – Try It Online")
## How it works
```
%@10 4*/@({~(>ag`ct)e.~/:~"1)~:#,.
,. join the characters to pairs
# take the ones
~: where both are different
/:~"1 sort the pairs
e.~ is it in …
(>ag`ct) 'ag' or 'ct'?
{~ map 0 and 1 to
%@10 4 0.1 and 0.25
*/@ fold with multiplication
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
1##&@@1[.1,.25,.1][[#-#2]]&
```
[Try it online!](https://tio.run/##PU4xbsMwDNzzikICjBaQ3cpFxgQC8oECHQ0PBJEwGZLB4WY4X3eOkm1xII93vNOd9Hq@k96Y5sthjt5XKcWuiaFp96GJfdf52rd9X81/w@2hQMdLSp@nKw3Eeh6eyX83oyNXH3@CY7QYnKC1wSna7/TVV69/psdr3I1OhVlJ2YWPdSY3BTAkooqFGiUbKByiRIzAxJjK1gw46@FoZmVv/jggkpICBCktV2y@8GcyFhEKG0MLK1bFlUmsVi6HQF4ucbaihbXUzCCZtz9mCcTlm/mRsbtpfgM "Wolfram Language (Mathematica) – Try It Online")
Uses `0123` for `acgt`.
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes
```
f=lambda x,y:x==[]or[1,.1,.25,.1][x.pop()^y.pop()]*f(x,y)
```
[Try it online!](https://tio.run/##ZZHRaoNAEEWf9SsW@xANIiYlfQj4JdstTCd1KiQqOgX9ejuzG61QFXbHOXPvXbaf@btrX5faVOZ9qas7PD5vYKZ8vk5VZV032FNeyHe@yOLsVPRdn2Yfc1jdsU6FzRb@GnkUDRvbBJAYABApyY2v5CPmxOXSZUJkYNTecw/SiV5MWZx0mgSV36wAbcWTOF8UAWQK4upC2tx1VRX9uNiow9Yv1UDNRQCAQgSpZARotSjLN6@DaiwBEJSTDCzCWv3j9HQUHBFI3z3lTX0SUQhiorRWKxYgTeYBSYd/5yrLTcZPyXw4nn8Ad9l9KBfHdTcYvRTTtH4dr3HU/jz8HdmDXsqhqJv2lmJmlEUFYSDnK9msgy6O@qFpOa3Towpk2fIL "Python 3 – Try It Online")
Port of my [Jelly answer](https://codegolf.stackexchange.com/a/218836/66833)
-2 bytes thanks to ovs!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~79~~ 71 bytes
-8 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
float r;f(a,b,l)int*a,*b;{for(r=1;l--;++a,++b)*a-*b?r/=*a**b-2?10:4:0;}
```
[Try it online!](https://tio.run/##dZPBboMwDIbvPAVCmgQhaFBtl6bRzrvv1nFwopKBWDql3qni2Tuboq4KWyIR5bP1O79lbOWsvVy68QiYBtXlII0ci96jACmMOnfHkAfdqLGqVFmCLEtTCKiEeQmPWoAQptq8NPX2aVur6YIqEQZOh7fjq8fcfkCYr5L00vHgi3OS0mJ1rz9hHI82fxIckL2u5aDmMJdU/Y6w6suy4OugazXsntVA977LWXPft1pn4FKL2X5oC89gqDZXjXDA7@BTr5Ip@YTe50tpflIKAPt232xafYW8zhlSJxDQZpO8o@AcIgUwwmDRuYixgo0SWZFyAaJky6LOOQsxd7xjGVIhRi@BmLP8ijFFpJIznqQx5n/HkaT717FdO7Zu7dhRcerF2jEtZ9eOwfGOMeX@6Zhbad0fjhHB3hzfTRLumlp9BRq6Ls8eqqY5pcu3e/eZ5GHAsmznHmErQ1H89miZW33CQEc@57aFFKB/p/wK5TzFwtwFFkEOqJvi8ofd2JRMlx8 "C (gcc) – Try It Online")
The function receives two arrays of integers. The bases are mapped as follows
```
A G
-2 -1
C T
1 2
```
This mapping allows the following decision making
```
*a-*b?r/=*a**b-2?10:4:0;
```
In a nutshell: the product of two bases is 2 only if they have the same size (A<->G or C<->T).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 bytes since we may take input mapped from `actg` to arbitrary numbers.
```
^«9‘İP
```
A dyadic Link accepting two lists of integers, `a:4 c:9 t:10 g:7` which yields the probability.
**[Try it online!](https://tio.run/##y0rNyan8/z/u0GrLRw0zjmwI@P//f7SJjqWOoYGOeSyICYaxAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ZZAxTsNAEEVrcoqVqSytwEEBlFvQW440GkWjRKnQNHSm5gIU0CYFTZpU6QgXwRdZ5s/aiSXWLnY8b/7/4/Vys3lJafH9Ne/a95/9U@raD2LRrv1c/R7f6lmcx2kVH5uyPO1uT9vn7vVQplRP6gIYETFLEYNX9opq0cQQwnWobiqch7t7g1WYlZSB9ncy8ArYFGJik/ZZAci56AmXMCuV7AVTQXPUhSr7uNnA4dyvYABzEyCSHMEqGyEZLIagDGMLwATOMqgJo/rHYVnJjkyCZ0y5qScxhSxmSkM1YBlCMgcsHV/28t/XE2BsPq/nh3iU3UM1fw "Jelly – Try It Online").
### How?
```
^«9‘İP - Link: a, b e.g. [4, 9,10, 7], [4, 4, 4, 4]
^ - bitwise XOR (vectorises) [0,13,14, 3]
9 - nine 9
« - minimum [0, 9, 9, 3]
‘ - increment [1,10,10, 4]
İ - inverse [1, 0.1, 0.25, 0.1]
P - product 0.0025
```
[Answer]
## [DESMOS](https://learn.desmos.com/), ~~125~~ 109 bytes
$$f(k,l)=\prod\_{n=1}^{\operatorname{length}\left(k\right)}\left\{k-l=0,\left|k-l\right|=2:.25,.1\right\}\left[n\right]$$
```
\prod_{n=1}^{\operatorname{length}\left(k\right)}\left\{k-l=0,\left|k-l\right|=2:.25,.1\right\}\left[n\right]
```
try it online:
<https://www.desmos.com/calculator/6nxdztewy3>
Explanation:
\$\prod\_{n=1}^{\operatorname{length}\left(k\right)}{}\left[n\right]\$ `takes the product of the list starting with n=1`
\$k-l=0\$ `if k-l = 0 returns 1`
\$\left|k-l\right|=2:.25,.1\$ `else if abs(k-l) = 2 returns 0.25 else return 0.1`
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~10~~ 7 bytes
```
꘍9v∵›ĖΠ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%EA%98%8D9v%E2%88%B5%E2%80%BA%C4%96%CE%A0&inputs=%5B4%2C%209%2C%2010%2C%207%5D%0A%5B4%2C%204%2C%204%2C%204%5D&header=&footer=)
*-3 by porting Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/218917/78850)*
## Explained
```
꘍9v∵›ĖΠ
꘍ # Bitwise XOR of the two input lists
9v∵ # vectorise(min, ^, 9)
› # ^ + 1 (vectorises)
Ė # 1 / ^ (vectorises)
Π # product(^)
```
[Answer]
# [Perl 5](https://www.perl.org/), 81 bytes
```
sub{$i="@_";$r=1;$_=ord($1^$3),$r/=10-/0/*9-/3|6/*6while$i=~s/(.)(.* )(.)/$2/;$r}
```
[Try it online!](https://tio.run/##XZDRboIwFIbvfYqO1AkMKGg0cUjm/ZJ5sztxpnbQkakQ6OIWdZd7gD3iXoSdFkSxTXrxnf/85z/Nonw9LHEclMXHao@TQJsuNR/ngefjZZDmrzr2XvDAsHBOAs@1iUvMsU0GhxExR7u3ZB1Bz3dBdMfQHRPBYxDcJ@BwLP1OnOb6hmZzMg93obO4I3xhFdk6ESTcEmsy6fWMfQfBEZwxQQVD1TmcAG0Ach1PSSnnQkBRnCr8GoC0P6y0lAnOEWpcALAWuNDKkUxcaAXjLQBat8ogo4I1pbyJCwAcGiC17qi2ZjIexGS0rkJYAePO4ErO5WXNQoxyeWv1SV5nUTHBrvEC5zY456aSsov15Qrs6j9c98Jb@YBj8yfqUNbaUyVXDZsvHVMLrywcfWZGMMVLv@YI81QEtziuBEbFszzZCkRXhe7ZUkBU38SL7HGnivSACiWKdS19R13bGxb1@/fzq0zDrWZVnnXL/bnFNM2n2TOaPd4gJOd3nXGMEMwI5CDVCRjCHMt/ "Perl 5 – Try It Online")
[Answer]
# Scala, ~~52~~ 51 bytes
```
_.lazyZip(_).map(_.^(_)*7%8/3*7/4*3+1)./:(1.0)(_/_)
```
[Try it online!](https://scastie.scala-lang.org/bzvAdRB2SsOz3TQLwJuq9w)
Uses `0123` for `actg`. Like many of the other answers, it xors the values and then hashes them to get the right probabilities.
Here is a table for the XOR, borrowed from Kevin Cruijssen's [answer](https://codegolf.stackexchange.com/a/218835/95792) (modified for `actg` instead of `acgt`).
| Character pair | values | XOR |
| --- | --- | --- |
| aa | 0,0 | 0 |
| cc | 1,1 | 0 |
| gg | 2,2 | 0 |
| tt | 3,3 | 0 |
| ac | 0,1 | 1 |
| at | 0,2 | 2 |
| ag | 0,3 | 3 |
| ct | 1,2 | 3 |
| cg | 1,3 | 2 |
| gt | 3,2 | 1 |
Basically, we get 0 when there isn't a mutation, 1 or 2 for purine -> pyrimidine or vice versa, or 3 for purine -> purine or pyrimidine -> pyrimidine. The goal is to get 0 to 1, 1 and 2 to 10, and 3 to 4, and then later reduce by dividing these inverses of the probabilities.
| Original value | `*7` | `%8` | `/3` | `*7` | `/4` | `*3` | `+1` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| 1 | 7 | 7 | 2 | 14 | 3 | 9 | 10 |
| 2 | 14 | 6 | 2 | 14 | 3 | 9 | 10 |
| 3 | 21 | 5 | 1 | 7 | 1 | 3 | 4 |
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
I∕¹ΠEEθ⁻℅ι℅§ηκ∨¬ι⎇﹪ι⁶χ⁴
```
[Try it online!](https://tio.run/##NYxBCgIxDEX3niLLDERwQNy4Et24qM7CC4S2zARLq5120NPXWvFBwuMnfD1x1IFdKUMUn/DIc8KTLGIs9gRDDCbrhIofbZ4ESnye8RqNeHYoHcHfD@nsjX3hRHDvKt8LXkJqTzcbPcc3qlroAgrBrqb9hmDb/diXwrmi6x5XTXNmPZb14j4 "Charcoal – Try It Online") Link is to verbose version of code. Takes the RNA translations as input, so expects characters from the set `acgu`. Works with both lower and upper case but not mixed case. Explanation:
```
θ First input
E Map over characters
ι Current character
℅ Ordinal
η Second input
§ Character at index
κ Current index
℅ Ordinal
⁻ Subtract
E Map over ordinal differences
ι Current difference
¬ Is zero
∨ Logical Or
ι Current difference
﹪ Modulo
⁶ Literal `6`
⎇ If nonzero then
χ Predefined variable `10`
⁴ Else literal `4`
Π Take the product
¹ Literal `1`
∕ Divide
I Cast to string
Implicitly print
```
[Answer]
# [PHP](https://php.net/), 78 bytes
Accepts input as arrays of integers `[0,1,2,3]`, where `a->0, c->1, g->2, t->3`
```
function($o,$p){$s=1;foreach($o as$k=>$v){$s/='104'[$p[$k]^$v]?:10;}return$s;}
```
[Try it online!](https://tio.run/##bZJfa4MwFMXf/RRBAlWQNXZ/HuZsnwZ7GKzv4solaJR2GkxaGKWf3d2b2K6sMy/3Jie/c2KiGz2@rHSjg4DXLGdjve@kbfsu4n3CdXzkJk@zuh8qkA3OMTB8my/5gVbm@SwVD7OC64Jvy09@KFfPqchOQ2X3Q8dNdhoz5NrKWIPsImCsCK2S0oKVYcLONYRlwuibz5m4S50MlLIWVy3p1KVxQidbPHodSKsUibCSWE0o9ldHXtLR0Jx8f5VOJ7wvRUMkgPIBscOt4LheJ54mpKRIGE0CSTGdRQ/q/pMqGt5fgqIh4eo0Qkz@LhySPBSJ5@4CPesop9NgVnl7biGumA6BMH989wHt@dVS0pJuSw@VHnpZGbqyGt9B2@m9jfMlDAN8b75AR2Hb2QPsEGbssDF619qIKty5A1lF6BgmIYYL0TB0P7oQSZosknssJ2AcZ8HlXfknAoa5KmZHzF3Jpme8jq4SeWEhyhgxN9NpGeP8@m29ef14z4LT@AM "PHP – Try It Online")
**Explanation**
```
function($o, $p) { // function accepting two arrays of integers
$s=1; // initial probability
foreach($o as $k=>$v) { // loop through first input as key, value pairs
$s /= // divide by... and assign result to $s
'104' // string of possible division integers
// 1 => no change in probability
// 0 => special case
// 4 => inverse of 0.25
[$p[$k] ^ $v] // take an integer from string offset based on XOR value
// of loop's 'value' and corresponding value in second input
?:10; // evaluate boolean value of integer and return it when "truthy"
// else return 10 (inverse of 0.1) when "falsy"
// 1) integer is 0 (special case)
// 2) integer is undefined (XOR was 3, string offset doesn't exist)
}
return $s; // return probability
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~124~~ 72 bytes
```
O$`.
$.%`
¶
L`..
A`(.)\1
%O`.
ag|ct
4
..
10
%`$
$*
¶
~`.+
.+¶1/$$.($&_
```
[Try it online!](https://tio.run/##NY3BCgIxDETv@Y6urG6JFvwB74IHr4INQYIXD5Kj@Fn7AftjdVJWcugwM2/6fvjzJaUN47XmdkmVKfFQaZmJzpWZTnXk7a3QcEEk9lGnI8EvBxpqorTr1W/liXha5rJPice0ubfmpurimlchwM0d2rP9FYmom2U8akYSXfUMLCAKHgURwwokcjHSQDGhkjHhYCDhWhxoFYuD13fQQBO1VcKN1RyzGn92F3nu0l3Ufg "Retina – Try It Online") Takes input on separate lines but link includes test suite that converts from comma-separated inputs for convenience. Outputs as a fraction `1/n`. Explanation:
```
O$`.
$.%`
¶
L`..
```
Transpose the inputs.
```
A`(.)\1
%O`.
ag|ct
4
..
10
```
Get the probability of each mutation.
```
%`$
$*
¶
~`.+
.+¶1/$$.($&_
```
Take the product and prefix `1/` to the result.
Previous 124-byte solution used decimal output:
```
O$`.
$.%`
¶
L`..
%O`.
(.)\1
1/1
ag|ct
25/100
[a-z].
1/10
+`\d+(.+)¶(\d+)/1
$.(*$2*)$1
{`/1$
^\B
0
(.)(\.(\d+))?/10
.$1$3/1
```
[Try it online!](https://tio.run/##NY2xTgNBDER7f8eetJtbfLdBqZGokVJQckFrGWTRUESugO/KB@THjvEpkQs/jWfG50//@pa2Dvm11/WYOlPiodP1QvTSmWk4QspclkZtaiT2p077w9Tmmd7k4efEoc809uVjzDyW6yWDCryJ8y7tdyU1@u1TS0TvyzPN0ZYX3lzlKbKcWnqc2rq6qbq41hsI/pk72KvdiUTUzSqWmpGEV70iFiGKPAwihhYg7mKkEUWFSkWFIwOEajFIq1gMtK0HDjhhuyHUaK1Rq/FzU3GvG7qL2j8 "Retina – Try It Online") Takes input on separate lines but link includes test suite that converts from comma-separated inputs for convenience. Explanation:
```
O$`.
$.%`
¶
L`..
```
Transpose the inputs.
```
%O`.
(.)\1
1/1
ag|ct
25/100
[a-z].
1/10
```
Get the probability of each mutation.
```
+`\d+(.+)¶(\d+)/1
$.(*$2*)$1
```
Multiply all of the probabilities together.
```
{`/1$
^\B
0
(.)(\.(\d+))?/10
.$1$3/1
```
Convert the fraction to a decimal.
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
a?b|a==b=1|a/b<0=10|1>0=4
a!b=foldl1(/)$zipWith(?)a b
```
[Try it online!](https://tio.run/##bY1BCoMwFET3OcVXBJOFaKTLfj1G1z@piaFRQ82iFO@eil0U2s5qHo9hRlpvg/cpUa82QlQoN6rVuUHZbLJr8MQoU2gWf/WS16J4unBxceS9IFDJwAMQNK3DXhYDJZVQdSAZfKW0h2h/hT5E9WcS36ZlzO4nEwVuBJvIzTuFu5sjFMBtHq3WkaLORfYhykV6AQ "Haskell – Try It Online")
* input : `a`-> 1, `g`-> 2, `c`-> -1, `t` -> -2
* `?` compares bases to get the inverse of probabilities
* `!` zips sequences using ? to compare each pair and folds by dividing
] |
[Question]
[
Given one line that consists of only letters, process as following:
* You maintain a string that's empty at the beginning.
* If the next input character is in the string, remove it from the string.
* If the next input character isn't in the string, append it to the string.
Output the final state of the string.
You can safely assume the input consists at least one character (i.e. non-empty), but there's no guarantee that the output isn't empty.
Pseudocode (Feel free to golf this):
```
str = EMPTY
for each character ch in input
if ch exists in str
remove all ch from str
else
append ch to str
print str
```
The input matches the regular expression `^[A-Za-z]+$`.
Sample test cases:
```
ABCDBCCBE -> ADCBE
ABCXYZCABXAYZ -> A
aAABBbAbbB -> aAbB
GG -> (empty)
```
The input can be given in any applicable way, but it must be treated as a string, and the same for output. The program should **not** exit with an error.
The shortest program in each language wins!
**Extra** (Optional): Please explain how your program works. Thank you.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
œ^/
```
[Try it online!](https://tio.run/##y0rNyan8///o5Dj9////Jzo6OjklOSYlOQEA "Jelly – Try It Online")
Full program.
[Answer]
# [Haskell](https://www.haskell.org/), ~~44~~ 42 bytes
```
foldl(#)""
s#x|z<-filter(/=x)s=z++[x|z==s]
```
[Try it online!](https://tio.run/##XY69DoIwFIX3PkVTFohWX8CatMWw6OTCjwwFqRILEooJQX11a@tE3L7v3JyTexX6VillJDkZeVdn5XsBQkB742vaYFmroer9NRkDTabFIrMpITo3jahbSGAjugP0u8dwHPp9u5IBzBBlPGScsx1aOo6TlFMW0yS1LihlrKBFwaxEEcrBE4NZA@ItpKEj8Nf9XWw6W3CRoBaAm3JmH8dv8ymlEhdtcNl1Xw "Haskell – Try It Online") *Edit: -2 bytes thanks to Zgarb!*
**Explanation:**
The second line defines a function `(#)` which takes a string `s` and a character `x` and performs either the remove or append. This is achieved by `filter`ing out every occurrence of `x` in `s`, resulting in the string `z`. If `x` does not occur in `s`, then `z` is equal to `s` and `z++[x|z==s]` yields the original string with `x` appended. Otherwise `[x|z==s]` yields the empty string and only the filtered string is returned.
`foldl(#)""` is an anonymous function which takes a string and adds one character after the other the initially empty string `""` with the function `(#)`.
[Answer]
# [J](http://jsoftware.com/), 21 19 bytes
```
#~~:&.|.(2|*)1#.=/~
```
How it works:
`=/~` - makes a table of equality of the characters in the string:
```
a =. 'ABCXYZCABXAYZ'
]b =: =/~ a
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1
0 0 1 0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1
```
`1#.` - sum of each row by base 1 conversion (how many times the letter occurs)
```
]c =: 1#. b
3 2 2 2 2 2 2 3 2 2 3 2 2
```
`~:&.|` - reverse, then apply nub sieve (is the char unique) and reverse again. Thus I find the last occurrences of the characters in the string:
```
]d =. ~:&.|. a
0 0 0 0 0 0 1 0 1 1 1 1 1
```
`*` - multiplies the count by 1 for the last position of the character in the sring, by 0 otherwise, computed by the above `~:&.|`
```
]e =. c * d
0 0 0 0 0 0 2 0 2 2 3 2 2
```
`2|` - modulo 2 (sets to 0 the positions of the chars that have even count):
```
]f =. 2| e
0 0 0 0 0 0 0 0 0 0 1 0 0
```
`#~` - copy the right argument left arg. times (~ reverses the places of the args)
`]f # a
A`
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F@5rs5KTa9GT8OoRkvTUFnPVr/uvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagrqjk7OLk7Ozk6s6slBEZJSzo1OEY2QUQjjR0dHJKckxKckJIeburv4fAA "J – Try It Online")
[Answer]
# Brainfuck, 95 bytes
```
,[<<<[[->+>>>+<<<<]>>>[-<+<->>]<<[[-]<]>[[-]>>[-]>[[-<+>]>]<<[<]<<]<<]<[->>>>[-]<<<]>>>>[->+<]>>[>]>>,]<<<[.<]
```
[Try It Online](https://tio.run/##NYxRCoBACEQPZNsJhoF26xTiRwVBBH0End90oR99zHPcnvW8j3e/3AcFoFooJCUYFqAFgkJadxZZrsw7QWjdIYb9lajnSSgOll9HmPtU21xbq8sH)
### How It Works
```
, Gets first input
[ Starts loop
<<< Go to start of string
[ Loop over the string
[->+>>>+<<<<] Duplicates the current char of the string
>>>[-<+<->>] Duplicates and subtracts the inputted char from the duplicate of the string char
<<[[-]<] If the char is different to the input, remove the difference
> If the char is the same
[
[-]>>[-]>[[-<+>]>]<<[<]<< Remove the char from the string and sets the inputted char to 0
]
<< Moves to the next char of the string
]
>>>[->+<] adds the inputted char to the string
>>[>]>>, gets the next input
]
<<<[.<] prints the string
```
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
*Another one bytes the dust thanks to Bruce Forte.*
```
import Data.List
foldl1(\x y->union(x\\y)$y\\x)
```
[Try it online!](https://tio.run/##FcixCoMwFEDRvV/xCB0UWqEfYCEvFhc7dVGbDglVDE1i0AjJ16c63OHcSay/QeuUlHHz4qESXhSNWv1pLMdZf/Ut4wHi9b5ZNdsscB7zc@Q85MkIZaEEI9wTMrf5l18aCwWMe/sEty1DDm9CkVXIGD7IBQ60Xc8otrTrjyEoRZRUSjxU1@ST/g "Haskell – Try It Online")
Takes a list of Strings.
Symmetric difference is annoying...
[Answer]
## [Retina](https://github.com/m-ender/retina), 16 bytes
```
+1`(.)(.*?)\1
$2
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX9swQUNPU0NPy14zxpBLxej/f0cnZxcnZ2cnVy4gKyIyytnRKcIxMoor0dHRySnJMSnJicvdHQA "Retina – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~21~~ 9 bytes
```
|&2!#'=|:
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqkbNSFFZ3bbG6n@auoaSo5Ozi5Ozs5OrkjWIHREZ5ezoFOEYGQXkJzo6OjklOSYlOQE57u5Kmv8B "K (ngn/k) – Try It Online")
If a character appears an even number of times in the string, it won't be present in the output. If it appears an odd number of times, only its last instance will remain.
* `#'=|:` count the number of times each distinct character occurs in the string (reversing the order)
* `|&2!` filter down to where the character appears an odd number of times, then reverse
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
vi"@X~
```
Doesn't work in the TIO environment, but works fine on the MATLAB implementation, and thanks to a fresh patch, you may try it on [MATL Online](http://matl.io/?code=%27%27i%22%40X%7E&inputs=%27ABCDBCCBE%27&version=20.5.1)
`X~` equals `setxor`, or symmetric difference, which does exactly what the challenge asks. The rest is just looping over the input `i"@` and starting with an empty string by concatenating the entire stack which is empty at the start (thanks Luis Mendo).
[Answer]
# [q](http://code.kx.com/q/ref/card/), 38 bytes
```
""{$[y in x;except;,][x;y]}/
```
[Answer]
# [R](https://www.r-project.org/), ~~92~~ ~~84~~ 77 bytes
```
for(i in el(strsplit(scan(,y<-''),y)))y=c(y[y!=i],if(!i%in%y)i);cat(y,sep='')
```
[Try it online!](https://tio.run/##DcoxDsMgDAXQqyRDFFuiJ2gZ4BpVB6BE/RIlkc3i09O@@clsyJLE6FvH53wrz@MUwoK@1EY6RK@GQVpSJ2eP276zM2Y2X8ietnq8HA5asaFvxuB7SYPMab38/84UQow55BznDw "R – Try It Online")
-15 bytes thanks to [djhurio](https://codegolf.stackexchange.com/users/13849/djhurio)
### Explanation
[djhurio](https://codegolf.stackexchange.com/users/13849/djhurio) provided an excellent R answer avoiding a `for` loop -- as R programmers instinctively do as a rule (myself included). Here's an R answer that utilizes a `for` loop (and saves a few bytes in the process).
* `x=scan(,'');` -- assign the input into the variable `x`
* `y='';` -- create an empty string in a variable called `y`
* `for(i in el(strsplit(x,'')))` -- for every character `i` in `x`
* `y=c(y[y!=i],if(!i%in%y)i)` -- assign to `y` every element of `y` that is not equal to `i`, appending `i` if `i` was not already in `y`
* `cat(y,sep='')` -- print the elements of `y` with no space between them
### Note
If you click the TIO link above, you'll find in the header `library(methods)`; this is to deal with the error [djhurio](https://codegolf.stackexchange.com/users/13849/djhurio) experienced regarding the `el()` function -- the function is provided by the `methods` package, which in any version of R I've used, is loaded by default, but for whatever reason isn't by TIO. If `library(methods)` is removed from the header and `unlist` is substituted for `el`, I gain four bytes, but so would [djhurio](https://codegolf.stackexchange.com/users/13849/djhurio), putting our byte counts at ~~96~~ 88 and 99 respectively.
[Answer]
# [R](https://www.r-project.org/), 84 bytes
```
y=el(strsplit(scan(,""),""));cat(unique(y[colSums(outer(y,y,"=="))%%2>0],,T),sep="")
```
[Try it online!](https://tio.run/##FcsxCgMhEEDRuwgLI0wR0gYDeoWkCynUDERw111npvD0ZlP87v0@Ox1aOsFK8m0ftnM4qsDSea9FgHPcAI2x/@wtRwHdyqEE45VbfejK0FSow8CBxrlTLcv1fnkjPi0y7e4cZ/Q@hORTCvMH "R – Try It Online")
Another solution, but there are better [R](https://www.r-project.org/) answers here.
# [R](https://www.r-project.org/), 88 bytes
```
z=table(y<-el(strsplit(scan(,""),"")));cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="")
```
[Try it online!](https://tio.run/##FcsxDsIwDEDRs1Cpki2ZhRU6JGdgQx2S1hWR0tDGzkAuH8Lwly@93DKfJWSGnfX9WQVbndT5yPB9XDmCaJYjBgVZXAIaBvyHeF9cf6xr2DYoKZylC6InUnI7C9TXpY7jbUYk4WPqpjljrPXGe9t@ "R – Try It Online")
Thanks to Giuseppe for -7 bytes!
[There is a shorter answer by duckmayr](https://codegolf.stackexchange.com/a/149103/13849).
1. `scan(,"")` read input from stdin.
2. `y<-el(strsplit(scan(,""),""))` split input by characters and save as `y`.
3. `z=table(y<-el(strsplit(scan(,""),"")))` compute frequencies of each character and save resulting table as `z`;
4. `unique(y,,T)` take unique characters from the right side.
5. `names(z[!z%%2])` select only even counts and extract names.
6. `setdiff(unique(y,,T),names(z[!z%%2]))` remove characters with even count.
7. `cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="")` print the output.
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
*-2 bytes thanks to xnor. -3 bytes thanks to ovs.*
```
lambda s:reduce(lambda a,c:a.replace(c,'')+c[c in a:],s)
```
[Try it online!](https://tio.run/##LcgxCoAgFADQq7ipJA2NQoN1ibIafl8loUzMhk5vDY3vxSdvZ2iKa@eyw7EaIJdM1txo2W8QKKFONu7wJQpKeYUTEh8IyEVcvMTkQyaO@RDvzDgvVHX9MOpedYMaNX0B "Python 2 – Try It Online")
Literally just golfed the pseudocode. :P
[Answer]
# JavaScript (ES6), 60 bytes
```
s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s
```
### Test cases
```
let f =
s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s
console.log(f("ABCDBCCBE")) // -> ADCBE
console.log(f("ABCXYZCABXAYZ")) // -> A
console.log(f("aAABBbAbbB")) // -> aAbB
console.log(f("GG")) // -> (empty)
```
[Answer]
# APL+WIN, 19 bytes
Logic similar to Galen's J solution.
```
(2|+⌿⌽<\⌽c∘.=c)/c←⎕
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
#//.{a___,x_,b___,x_,c___}:>{a,b,c}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V9ZX1@vOjE@Pl6nIl4nCUonA@laK7vqRJ0kneRatf/6DgrV1UqOSjoKSk4gwhlEuKByneFcV6VaHS4FIMDQEgEiIkFEFFwMoSQCzoUqgRuTCJdBqAYTSXCxJDjhhNDnDuK7K9XWxv4HAA "Wolfram Language (Mathematica) – Try It Online")
Takes input and output as a list of characters.
## How it works
Uses `//.` (alias `ReplaceRepeated`) to find two repeated characters and delete both, until no more repeated characters exist. If the character occurs more than twice, Mathematica will always delete the first two occurrences. So if a character occurs an odd number of times, its last instance will always be the one to survive.
[Answer]
# [Prolog](http://www.swi-prolog.org/) 81 byte
```
a([],O,O).
a([I|J],K,O):-delete(K,I,F),(K=F->append(K,[I],M),a(J,M,O);a(J,F,O)).
```
Non-obfuscated version:
```
append_and_eraze([], Output, Output).
append_and_eraze([I | Input], Interim, Output) :-
delete(Interim, I, Filtered),
( Interim = Filtered ->
append(Interim, [I], Interim1),
append_and_eraze(Input, Interim1, Output)
;
append_and_eraze(Input, Filtered, Output)
).
```
1. `delete/3` ensures that its third argument unifies with its first argument, with all instances of second argument removed from it.
2. If those turn out to be the same, we append the element (it wasn't removed).
3. `append/3` as per its name, appends an element to list.
4. We recur on the elements of the input until we hit the `[]` (empty list), at which point the intermediate result will unify with desired result.
Test:
```
?- append_and_eraze(`ABCDBCCBE`, [], X), string_codes(Y, X).
X = [65, 68, 67, 66, 69],
Y = "ADCBE".
?- append_and_eraze(`ABCXYZCABXAYZ`, [], X), string_codes(Y, X).
X = [65],
Y = "A".
?- append_and_eraze(`aAABBbAbbB`, [], X), string_codes(Y, X).
X = [97, 65, 98, 66],
Y = "aAbB".
?- append_and_eraze(`GG`, [], X), string_codes(Y, X).
X = [],
Y = "".
```
*Some Prologs treat strings in double quotes as lists, SWI can be configured to do the same, but for the sake of simplicity, I used `string_codes/2` to format output nicely.*
[Answer]
# Perl 5, 28 + 2 (-pF) = 30 bytes
```
$\=~s/$_//g||($\.=$_)for@F}{
```
[Try it online](https://tio.run/##K0gtyjH9/18lxrauWF8lXl8/vaZGQyVGz1YlXjMtv8jBrbb6/39HJ2cXJ2dnJ9d/@QUlmfl5xf91C9wA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-h`, 15 bytes
```
;£A=øX ?AkX:ApX
```
[Try it online!](https://tio.run/##y0osKPlf@N/60GJH28M7IhTsHbMjrBwLIv7/V3J0cnZxcnZ2clXi4tLNCAAA "Japt – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), ~~75..64~~ 49 bytes
*-22 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792)!*
```
_./:("")((?,y)=>if(?toSet y)?filter(y!=)else? +y)
```
[Try it online!](https://tio.run/##bYyxCsIwFEV3v@KZKQ9F90IbkiidnLq0XSSpqVZCW5ogBvHbYwVx6nY5597rGmVVHPTdNB5OYJ7e9BcHfBxfq4ey4G7DNCNIoPBT118hzf4pnnf7hBKClLJtwDTrWsr8UBgPAVnbWW8mGtYpGusMg03AOM5Lb3v6u6WEC3kQUoojQVwt2bKqJRclr@rFhuJcCM21Fos6z7/4HT8)
[Answer]
## [Alice](https://github.com/m-ender/alice), 9 bytes
```
/X&@
\io/
```
[Try it online!](https://tio.run/##S8zJTE79/18/Qs2BKyYzX////0RHRyenJMekJCcA "Alice – Try It Online")
### Explanation
Basically a port of [Erik's answer](https://codegolf.stackexchange.com/a/149046/8478). Apart from a bit of IP redirection the code is really just:
```
i&Xo@
```
which does:
```
i Read all input.
&X Fold symmetric multiset difference over the input.
o Output the result.
@ Terminate.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 16 bytes
```
{(,⍨~∩)/⍣(≢⍵)⊖⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZLWGzqPeFXWPOlZq6j/qXazxqHPRo96tmo@6pgGp2v//09QdnZxdnJydnVzVucCciMgoZ0enCMfIKJBAoqOjk1OSY1KSE4jn7q4OAA "APL (Dyalog Unicode) – Try It Online")
If errors were allowed, this would've been 9 bytes:
```
(,⍨~∩)/∘⊖
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
Vz?:kN)=-kN=+kN
```
[Try it online!](https://tio.run/##K6gsyfj/P6zK3irbT9NWN9vPVjvb7/9/RydnFydnZydXAA "Pyth – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->s{s.reverse.uniq.select{|c|s.count(c)%2>0}.reverse}
```
[Try it online!](https://tio.run/##NYpdC4IwGEbv@xUvgqxAR3SfsK3wL/iBF25MVEJr7xaE87cvFnR1OM95jJOfMFxDXuCG1Oi3NqipW6YXRf3Qym5eeaRqdYs9qlN6Kc77/7aHljAublwIficZRKnqRjBesbqJQ88Y55JJyaOVJekOVPdq3LzVaD08nUUgSYoJ5AVEEkihjTGD4Ueqxt5gR@d1Wro9fAE)
Input and output are both an array of chars. Test code calls `.chars` and `.join` for convenience.
## Explanation
Uses the fact that the letters in the resulting string appear an odd number of times and in the order from right to left.
```
->s{ # lambda function taking char-array argument
s.reverse # reverse the input
.uniq # get unique characters
.select{|c| # select only those which...
s.count(c)%2>0 # appear in the input array an odd number of times
}.reverse # reverse back and return
}
```
[Answer]
# Pyth, 13 bytes
```
{_xD_Qf%/QT2Q
```
Takes in input as list of characters. [Test it out!](http://pyth.herokuapp.com/?code=%7B_xD_Qf%25%2FQT2Q&input=%22A%22%2C%22B%22%2C%22C%22%2C%22D%22%2C%22B%22%2C%22C%22%2C%22C%22%2C%22B%22%2C%22E%22&debug=0)
```
f Q (f)ilter input (Q)
/QT On how many times (/) each character (T) appears in the
input (Q)
% 2 Only allow odd numbers of occurences (when x % 2 = 1)
_xD_Q Sort (D) descending (the first _) by the location (x) of
the last (the second _) inde(x) of the target character
in the input (Q)
{ Remove duplicates
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 34 bytes
```
{a=[]a-=_ if[_1 in a]else a+=_1;a}
```
[Try it online!](https://tio.run/##Tcm9DsIgFEDhmfsUN12NQ1cNAxdNX6E/NuRSIDbRYmi32mdHRreT76ToOL95XnAHEfAi8ZF3lsPIZ2lwDoOpsUwe/Wv1yCdp6isfWYSYcPPrZiYu7iIIMT05rX/4xVD0k@Zlw6oC4eLi4ciK9I20pjuUarteK2pV1wMrRWSVtQRN8wM "Röda – Try It Online")
This is a direct translation of the pseudocode. It treats input and output as streams of characters.
Explanation:
```
{ /* Anonymous function */
a=[] /* initialize a */
/* For each character _1 in the stream: */
a-=_ if[_1 in a] /* Remove it from a if a contains it */
else a+=_1; /* Otherwise append it to a */
a /* Push characters in a to the stream */
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 73 bytes
Not the shortest, but I like this approach.
```
lambda s:''.join(c*(s.count(c)%2)*(i==s.rfind(c))for i,c in enumerate(s))
```
**[Try it online!](https://tio.run/##Dcs7DgIhEADQq9CYndkYCu1MKBbWW9ggnzgbdyB8Ck@PtC95@dc@ie8jqtf42vPtraiPZZFHIga3QpUudW7g8HLDFUipKksk9lMwpiLo6gSxCNzPUGwLUBFHLjRPBOLcG@CUTZtdG6Offw "Python 3 – Try It Online")**
Loops through the string, keeping only those characters where:
* `(s.count(c)%2) == 0` - The character appears an even number of times.
* `(i==s.rfind(c))` - The current index is the last appearance of the character in question.
[Answer]
# [REXX](http://www.rexx.org/), 102 bytes
```
a=arg(1)
s=''
do while a>''
b=right(a,1)
if countstr(b,a)//2 then s=b||s
a=changestr(b,a,'')
end
say s
```
[Try it online!](https://tio.run/##LclBCsMgEADA@75ibyoIoTkGLOhPdhOjQjHgWppC/m5z6HGYFs9zjH0hRy3phwFxSsF24CeXV0R63mLXSspdk72/7Lge79qlN82WzDTN2HOsKI6vS4Dcmqmm@H@rlIFYNxD6oowxyPsQ2DOHHw "Rexx (Regina) – Try It Online")
How it works: Take the rightmost letter, see if the number of occurrences is even or odd (which also doubles as a truth value) and if odd, add it to the output string. Then remove all occurrences of the letter from the input string. Repeat until input is depleted.
[Answer]
# [Perl 5](https://www.perl.org/), 22 + 1 (`-p`) = 23 bytes
```
s/(.)(.*?)\1/$2/&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0NPU0NPy14zxlBfxUhfTa0oNSX//39HJ2cXJ2dnJ1cuICsiMsrZ0SnCMTKKK9HR0ckpyTEpyYnL3f1ffkFJZn5e8X/dAgA "Perl 5 – Try It Online")
[Answer]
# Java 8, 93 bytes
A lambda from `String` to `String`. Just an implementation of the pseudocode in the question.
```
s->{String o="";for(char c:s.toCharArray())o=o.indexOf(c)<0?o+c:o.replace(c+"","");return o;}
```
[Try It Online](https://tio.run/##XVA9b8IwEJ3DrzhZQopFsDoTQuWklKnqwAKtOjiOQ02DHdkOLUL57akhgQHJ8t29@3jvbs@ObKprofbFT1c3eSU58IpZC29MKjiPggG0jjlvSqlYBXvfRRonK1I2ijupFXkdnPnaGal2EfR2Aaz20wuqiqVhVkDS2eni3CdBJwjFpTYh/2YG@MwSpzPvUmPYKcRYJ5pIVYi/9zLkeP70rCd8pokRdcW4CPkEoQghHBvhGqNAx20XxKNHzUctCzj4dcKe9vMLmNlZfNkuuEPcq7OQgBK/cAcvFQGiafaSZlm6RNEt3mw/Mppu6PZjwBilaZrTPE8HYLW6Om3sP78iDOTAsssZZj1fryFYn6wTB6IbR2pf5KqbVOI7D8yFaGxhuoCxRVE/IHq4K/FhdQqvOYzxhbQd@dd2/w)
# Java 8, 182 bytes
Here's another lambda of the same type that uses streams! It's probably more efficient.
```
s->s.join("",s.chars().mapToObj(c->(char)c+"").filter(c->s.replaceAll("[^"+c+"]","").length()%2>0).distinct().sorted((c,d)->s.lastIndexOf(c)-s.lastIndexOf(d)).toArray(String[]::new))
```
[Try It Online](https://tio.run/##XVFdS8MwFH3ufkUIDBJsg/g4XSGtc/gge9AHtzEhTdKZmiUlydQh@@0ztXWgEHLvPTn33I807J1ltpWmEW@ndl9pxQHXzHvwwJQBX6NkAH1gIZpaGaZBE7PIPihN6r3hQVlD7gbn5jE4ZbYp6G0OWBvVBTVi5piXYHryWe5JY5VBEKae8FfmPMJkx9onu6gaxLMcdSDmFxBiUisdpOtQT5xsNeOSao3g@gVeRMYGph1LS7MNrwiPr/JLTITyQcV@oqy3LkiBEE8F7iTibOHeCPm5qBHH2V9AYEyCpc6xA@r7X28mEyM/MD4l16P/y3i3SoBd3NOZDJjbetytLTlDPI7twRREGXAGO0YCaVHeFmVZzGD6Gz8vVyUtnulyNWCM0qKoaFUVAzCf/zjH63jV1oGhOGBlt99JX6/vIXk8@CB3xO4DaSMp6N9WSczcsYDg2IMsB2MP014g/fdhJIb6gH7eMMZd0eMonuPpGw)
## Ungolfed
```
s ->
s.join(
"",
s.chars()
.mapToObj(c -> (char) c + "")
.filter(c -> s.replaceAll("[^" + c + "]", "").length() % 2 < 0)
.distinct()
.sorted((c, d) -> s.lastIndexOf(c) - s.lastIndexOf(d))
.toArray(String[]::new)
)
```
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
function(s){for(i in utf8ToInt(s))F=c(F[F!=i],i*!i%in%F);intToUtf8(F)}
```
[Try it online!](https://tio.run/##DcoxCoAwDADAr7SCkIjugjq0Q8C9TuJghUCWFLRO4tur63FnYTN2pvCtR5akcOHD6QQxoubO3Ic0a/4VaTqAVrKTbK00VmrRmnAQzSEtfwTCtzBUu3PeRxejr7B8 "R – Try It Online")
I was encouraged by djhurio to post this solution; djhurio's answer can be found [here](https://codegolf.stackexchange.com/a/149089/67312).
This uses the same idea as [duckmayr's answer](https://codegolf.stackexchange.com/a/149103/67312), but it leverages a numeric approach by converting the string to its codepoints rather than splitting it into characters, and is a function rather than a full program so it can return the new string rather than printing to stdout.
```
function(s) {
for(i in utf8ToInt(s)) # convert string to codepoints and iterate over it
F=c(F[F!=i], # remove duplicates and append
i*!i%in%F) # 0 if in F, i otherwise
intToUtf8(F) # collapse from codepoints to string
}
```
One important observation is that `F` is initialized to `FALSE` or `0` and `utf8ToInt(0)==""`, so this will succeed for the empty string as well as correctly collapsing the codepoints.
] |
[Question]
[
In probability theory, a Bernoulli variable is a random variable which has a single parameter \$p\$, and is equal to 1 with probability \$p\$, and 0 with probability \$1-p\$.
In this challenge, there are a bunch of independent Bernoulli variables with parameters \$p\_1, p\_2, ... , p\_n\$, and their XOR is calculated. The XOR is 1 if an odd number of variables are 1, and 0 if an even number of variables are 1. Your task is to calculate the probability the XOR is 1.
# Test cases
```
# Format: [p1, p2, ..., pn] -> probability XOR is 1
[0.123] -> 0.123
[0.123, 0.5] -> 0.5
[0, 0, 1, 1, 0, 1] -> 1
[0, 0, 1, 1, 0, 1, 0.5] -> 0.5
[0.75, 0.75] -> 0.375
[0.75, 0.75, 0.75] -> 0.5625
[0.336, 0.467, 0.016, 0.469] -> 0.499350386816
[0.469, 0.067, 0.675, 0.707] -> 0.4961100146
[0.386, 0.224, 0.507, 0.099, 0.742] -> 0.499658027097344
[0.796, 0.019, 0, 1, 0.217] -> 0.338830368
[0.756, 0.924, 0.001, 0.046, 0.962, 0.001, 0.144] -> 0.6291619858201004
```
# Rules
* The input list will never be empty, \$1\leq n\$.
* You can use any reasonable I/O format. Some particular examples:
+ You can choose whether to take \$p\_i\$ or \$1-p\_i\$.
+ You can choose whether to output \$p\$ or \$1-p\$.
+ You can take the list of probabilities in any reasonable format.
+ You can take the length of the list as an additional input.
+ You can take the probabilities as fractions instead of floating-point numbers.
+ You can assume the probabilities are sorted.
+ You can take the probabilities as a multiset, or a map from probability to number of appearances.
* Your algorithm must in theory output exactly the correct answer, assuming its floating point calculations were perfect. In particular, you can't just simulate a finite number of trials.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/92727) are disallowed.
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
foldr1$ \x p->x+p-2*p*x
```
[Try it online!](https://tio.run/##bU7LbsIwELz3K/bAASixbMfYNRKc@IMeIQc3OBDVOFYSRL6@BtsRD6nSSrMzs7O7J9X9amN8td77qjGHlkxgP4DLNsOny@jczQd/VrWFNdS2160q@wlcrKmt7hCclZt2p@aKKjRttTrAagXffVvbI2Qb2G2by4/RxWwGKAb8DiNC8@Ij4QIwWgZybxZAYoXmH@kxisQy9OKdvEh5zgNjXATAZGQymneMajL5GMQiJb/iLKUsXsNpgYwJwWg6KHlaK59/USLGZ6InUx7jaGKWRE5fRMJY8VdWRh07n5XO3QA "Haskell – Try It Online")
If you have two events with probabilities `x` and `p`, the probability of their xor is `p*(1-x)+x*(1-p)`, or `x+p-2*p*x`. `foldr1` folds this binary operator over the whole list.
A different approach that's longer in Haskell but may be golfier in other languages is to take the list product, but conjugated by the mapping `y=1-2*x`.
```
(\y->(1-y)/2).product.map(\x->1-2*x)
```
[Try it online!](https://tio.run/##bU7LbsMgELz3K/bQg6kCAUygjhSf@gc9xj5QBydWCbb8UJKfrxvAalOp0kqzM7Ozuyc9fBpr53pXzElxw3nC8A2tOSJd3x6maiRn3SXFFecM85crms@6cbCDxo2m19X4DJOzjTMDAT84nNoLqUnSG32A7Rbex75xR8A57N/a6cOaEiEgITDvKWE8LZ8iroCSjSf3ZgUslG/@kX5Gidr4Xv0lD1KaSs@EVB4oW1gWzDsGNZpyCVIVk69hlnMRrtG4IAsJJXg8mMm4Nvv9izO1PBO8LOYpDSYVUZT8QWRClF9VbfVxmHHVdd8 "Haskell – Try It Online")
Or, since the challenge allowing inputs and outputs of one minus probabilities, we could conjugate by `y=2*x-1` instead:
```
(\y->(y+1)/2).product.map(\x->2*x-1)
```
[Try it online!](https://tio.run/##bU7LboMwELz3K/bQA26D6wdgO1I49Q96DBxcYhJUxyAeavLzpWCnaipVWml2ZmfGPunhw1g717tijoprnEfXZ4peGMJd3x6masRn3UXFJc7Z0yWmaD7rxsEOGjeaXlfjI0zONs4MGFbjcGo/cY2j3ugDbLfwNvaNO0Kcw/61nd6tKREC7APznmApRPkQcAMEpwuhG1iG@FmXf6QfK8EsXXf2l9xJWZZ4M@crKHlj1B8X9Go48ltQ8ZCk3itEtkKiQgGhoVyGB0kSan8/iIUMeZb4Gwl5pZSHNIhc3okyzcqvqrb6OMxx1XXf "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
x=0
for p in input():x+=p-x*p*2
print x
```
[Try it online!](https://tio.run/##bU7RCoMwDHz3K4pPm3OSxtqugl8yfBoOhaFFlHVf72wim4NB4HJ3uSTuNbVDj8uz7R6NkGXjm1scx4uvILoPo3Ci69dy83Q4lv5UubNPXIKRG7t@En4Js1fIJOZ1xJgKyIpA1iYVkio0f6TPaGaK0JtfspPyXAemtAkAcmOWzBVJZVNvQTCcvNAsoqJrwAssJYxCPmg1r7Xfv1Ca7RnyLOcByATFosadKJWq3w "Python 2 – Try It Online")
**Also 39 bytes:**
```
lambda l:reduce(lambda x,p:x+p-x*p*2,l)
```
[Try it online!](https://tio.run/##bU7LDoIwELz7FT22WElbSmtJ/BLlgAKBpGJDIOLXV/qIYmKyyezM7OyueU3dY2C2PV2sru7XugK6GJt6vjUw8gWbYtmbw5KYhGGN7LPrdQNoYcZ@mGAL@8HME0QI2TNJKcvKXUAMSJo7sjYYUF@u@SN9RlOZu17@ko2UZcIxLqQDQiNT3lzRq8EUMUhkSB79LGPcXyNhgfIJyVk4qERYq75/MSrjM95TIU@INwkPomAbkXJevgE "Python 2 – Try It Online")
Folds (reduces) the binary function `(x,p)->x+p-2*p*x` like in [my Haskell answer](https://codegolf.stackexchange.com/a/262141/20260). The built-in `reduce` was removed in Python 3.
# [Python](https://docs.python.org/3.8/), 36 bytes
```
f=lambda p=2,*t:p>1or(1-2*p)*f(*t)+p
```
[Try it online!](https://tio.run/##bU7dCoIwFL7vKXY5l8nZT5sT7EXCCyNFwXTIKnr65TYpg8bgfD/nO@eYl@2mkedmdq4th/p2udbIlCwltjAnOs2YHhgxCWkxscneuGfXDw2ihZn70eJFbR71gPvR3C1OlufOkFHGq12sKYLs6MkCUkTD9@CP9GnN1NFj9Us2EufSMyGVL0BXpoO51KBGU65BUDGZh17GRNgGcYAOCSVYXKhlHKu/dzGq1mOCp2MeIJggoijZRqRCVG8 "Python 3.8 (pre-release) – Try It Online")
Takes input splatted, and outputs 1 minus the probability. Works for Python 2 or 3.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~8~~ 6 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Based on [xnor's Haskell answer](https://codegolf.stackexchange.com/a/262141/64121), 2 bytes saved by att and BQN's extensions of logical functions to real numbers.
```
(∨-∧)´
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKIqC3iiKcpwrQKCnRlc3RzIOKGkCDin6hbMC4xMjNdLCBbMC4xMjMsIDAuNV0sIFswLCAwLCAxLCAxLCAwLCAxXSwgWzAsIDAsIDEsIDEsIDAsIDEsIDAuNV0sIFswLjc1LCAwLjc1XSwgWzAuNzUsIDAuNzUsIDAuNzVdLCBbMC4zMzYsIDAuNDY3LCAwLjAxNiwgMC40NjldLCBbMC40NjksIDAuMDY3LCAwLjY3NSwgMC43MDddLCBbMC4zODYsIDAuMjI0LCAwLjUwNywgMC4wOTksIDAuNzQyXSwgWzAuNzk2LCAwLjAxOSwgMCwgMSwgMC4yMTddLCBbMC43NTYsIDAuOTI0LCAwLjAwMSwgMC4wNDYsIDAuOTYyLCAwLjAwMSwgMC4xNDRd4p+pCgo+4ouI4p+cRsKodGVzdHMK)
Spells the *XOR* out very literally now: `∨` without `∧`.
[Answer]
# [R](https://www.r-project.org/), 27 bytes
```
function(p).5-prod(1-2*p)/2
```
[Try it online!](https://tio.run/##bVDJisMwDL3PVwTmkgxNqs2ydWh/piXQSxvK9PtTL4kTSsEg@22S/JzH0zy@7pf/2@PeTt3g@un5uLbY09/UHWke20sLAxJ33W/Tn5t8/6noIQKuUq4QETw0mE@6LDR@Jb8GDN4l3G8E@0/qQ@CUVgWzJlLUpwK4vKxqxYwdcNCAungincXFo0s8@J1HEQFQVke0Jw2R5BWgNLMc44X2zdQFIA/mWWTdwrQMZ9s3EG7tmENgYA1166y30i3OkYsUUGkHokhNUTJUtOACQRxe5jc "R – Try It Online")
Based on [@xnor's Haskell answer](https://codegolf.stackexchange.com/a/262141/55372).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḤCPCH
```
A monadic Link that accepts the probabilities as a list of floats in \$[0,1]\$ and yields the XOR probability as a float.
**[Try it online!](https://tio.run/##y0rNyan8///hjiXOAc4e/3UOtx@d9HDnjEdNa7IeNcxRsLVTeNQwVzPy///oaAM9QyPjWB0uBQhLR8FAzxTCBTJ1FAzBCMTAKoikXM/cFMQzR@eiCBobm4H4JmbmIMrAEMqzhEoDWWBxiLQZVLOBOUy3BVi9kZEJ2F4DiCGWYD3mJkYwiy3NIIZbItxoZGgOdxZY1hJihoEBWNrABCJoZoQkaGhiAtQTCwA "Jelly – Try It Online")**
### How?
```
ḤCPCH - Link: probabilities, P
Ḥ - double {P} (vectorises)
C - complement (vectorises) e: 1-e
P - product
C - complement
H - halve
```
[Answer]
# [Python](https://www.python.org) NumPy, 28 bytes
```
lambda i:.5-(1-2*i).prod()/2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZFNTsMwEIXFNqewuopREvz_U6k9QW8ALAJNhKUktpK0Uk_Cgk0lBKfgInAaHDulFKRInvne87yx8vLuDuOT7Y6v9erubTfWufpoyvZhWwKzLHie4pxcG1i43m5TeEOi5XNvWmf7EXS71h1AOYDOJbXtwQaYDlhXdSmCywSYzIIVaEuXVvuyyTbF4Bozpot8vYDQy17sXFH2fXlIjQeuN92Y1r7ObOYVMzw2dqhm%C2%B8AmFMP35dPd-iAhN6D_I1CFUSQeY7PlPume8zgMM3FUHB__nfa4XkE5InRuUFvdC4IEGkVEycCTkdCM-dnm1Ma8oRVUJhMdm9EnzRLuahSP7YBcYIYRbM_tokE8LCpihG6DBBMnKOEFwhIpGWlLGwsRZxG31-KMGnEEqVoogKFR8XrDpm-OhwsAgF-QUxY_MAQTQWWCuuCPLbsiT-oG8)
Takes a numpy array. Essentially a port of @xnor's approach (not the one they use but the one they mention in their Haskell answer).
## How?
Writing \$q\_j := 1- p\_j\$ compare the products (1)
\$\prod q\_j-p\_j\$ and (2) \$\prod q\_j+p\_j\$. (1) can be rewritten (1') \$\prod 1-2p\_j\$, (2) is just a fancy way of writing \$1\$.
If we expand the two products (1,2) we get the same terms up to sign.
In (2) all the terms are positive, in (1) it depends on whether there is an odd or even number of \$p\_j\$'s in the term. If we subtract (1) from (2) the terms with an even number of \$p\_j\$'s cancel and those with an odd number of \$p\_j\$ occur twice each.
We can therefore compute the desired value by taking the product (1') subtracting it from 1 and dividing by 2
Writing this out in symbols is a bit heavy on notation:
\$2\sum\_{I\subseteq \{1,...,n\}:|I|\text{ odd}}\prod\_{j\in I}p\_j\prod\_{j\not\in I}q\_j \\ =1-\sum\_{I\subseteq \{1,...,n\}}\prod\_{j\in I}-p\_j\prod\_{j\not\in I}q\_j \\=1 - \prod q\_j-p\_j =1 - \prod 1-2p\_j\$
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~9~~ 7 bytes
```
I⊘⊕Π⊖⊗A
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyMxpyw1RcMzL7koNTc1rwTIDijKTylNLtFwSUWIueSXJuWA1RWUlmhoQoH1///R0QZ6RiYmOgoGegbmZiDK0tISTJlCBI0tkAQtTM1iY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @xnor's second Haskell answer, but thanks to @xnor, using `q` for I/O instead of `p`.
```
A Input list
⊗ Vectorised doubled
⊖ Vectorised decremented
Π Take the product
⊕ Incremented
⊘ Halved
I Cast to string
Implicitly print
```
Previous 9-byte answer that uses `p` for I/O:
```
I⊘⁻¹Π⁻¹⊗A
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyMxpyw1RcM3M6@0WMNQRyGgKD@lNLkEIeCSX5qUA1ThmVdQWqKhCQXW//9HRxvomZua6SgY6FkamYAoAwNDMGUCETQzQhI0NDGJjf2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @xnor's second Haskell answer.
```
¹ Literal integer `1`
⁻ Subtract
¹ Literal integer `1`
⁻ Vectorised Subtract
A Input list
⊗ Vectorised Doubled
Π Product
⊘ Halved
I Cast to string
Implicitly print
```
In succinct mode the input is actually implicit which would save me a byte on the above answers but it makes the verbose code look odd.
A port of @xnor's Python answer is 16 bytes:
```
≔⁰ηFθ≧⁺×ι⁻¹⊗ηηIη
```
[Try it online!](https://tio.run/##Tcy9CsIwGIXh3av4xi8QS1JiRTqJroUibqVDrLUJxETz4@1HahanF54DZ1LST06anI8h6MUio6BIu3k4D/gm0MlXGS56URF7kwKFq37OATWFTtsUkFM4u3Qz8x0VIaQc9F7biCcZ4optzsPAqv2uocCqQy3WMMZ/EQWb@g@5EOOYtx/zBQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰η
```
Start with a 0% chance that 0 variables have odd parity (in the computing sense).
```
Fθ≧⁺×ι⁻¹⊗ηη
```
For each variable, update the chances that the total parity is odd.
```
Iη
```
Output the final parity.
My original approach was 27 bytes:
```
⊞υ¹Fθ≔⁺×υ⁻¹ι×υιυIΣΦυ﹪Σ⍘겦²
```
[Try it online!](https://tio.run/##TYuxCsIwFEV3vyLjC8SShKiIkwpuQqFupUOotQ2mDeYl/n5sI4jT5R7OaQftW6dtSmXEASIjgh5WD@cJvCg5Ipp@gtJGhJsZO1yEq5nmKxgxlDLyw/nFOS69mQKcNQao4ggXY0Pnc@ju0boMTxq7KsxiD09G5JLKlOqaF7vNlhFe7KVahnORR33hVv5BoVTTpPXbfgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start with a 100% chance of 0 variables.
```
Fθ≔⁺×υ⁻¹ι×υιυ
```
For each variable, calculate the chances of that variable being `0` or `1`, given the chances of the previous variables.
```
IΣΦυ﹪Σ⍘겦²
```
Sum the chances where the parity (in the computing sense) is odd.
[Answer]
# [Arturo](https://arturo-lang.io), 24 bytes
```
$=>[0loop&'p->+p-p*2*<=]
```
[Try it!](http://arturo-lang.io/playground?EFXWir)
Port of xnor's [Python answer](https://codegolf.stackexchange.com/a/262142/97916).
```
$=>[ ; a function where input is assigned to &
0 ; push 0 to stack
loop&'p-> ; loop over input, assign current element to p
<= ; duplicate top of stack
2* ; double
p* ; multiply by p
p- ; subtract from p
+ ; add to sum (the 0 we pushed)
] ; end function
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
.U_-*Zty
```
[Try it online!](https://tio.run/##K6gsyfj/Xy80XlcrqqTy//9oAz1jYzMdBQM9EzNzEGVgCOVZxgIA "Pyth – Try It Online")
### Explanation
```
.U_-*ZtybbQ # implicitly add the bbQ sauce
# implicitly assign Q = eval(input())
.U Q # reduce Q on lambda b, Z with no starting value
yb # 2*b
t # 2*b-1
*Z # Z*(2*b-1)
- b # Z*(2*b-1)-b
_ # -(Z*(2*b-1)-b) = b-Z*(2*b-1)
# = b-Z*2*b+Z
# = b+Z-2*b*Z
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~53~~ 47 bytes
```
[](auto&v,auto&x){x=0;for(auto p:v)x+=p-x*p*2;}
```
[Try it online!](https://tio.run/##dVNdr6IwEH33V0zYZCMKppTPivqy2V@hPnCxeskqEFsNWcNfX7edwoXr3TVKZ858nTmWvK7dU54/s5us4Lh@bvdTbX6/O3g09qNZk/RYXRGGenm3m/m6dptZPaNp@0wn34oyP98OHFb5JZPvmxFQVEJeeXYZYwopytMYufNcVtfNpCglXLKinNqPCaiPkIfl0gRXY/t4rjK52YDkQgpYw@NBFh71WweM4QBZhOgpywEPv9r4FzYkL@JQO/GLN8Z8P9JuEMX6IF7nMRNVBsImGnWlJO5qE8ymNMCRxLRgWBIHtBvKItOZDeyoF/eMMMhMB0IwSgIDRnQEekHQtukXEY1wwJta@fygpRsE67XQD99wDyOKZ8CYHxK1QNJtzCLPU6OCzmNRmBAaExb7AXLz/STxiR8lKARlXuSxJEwoUVVBRyyvSiEhf8@uM/Xk@S9@3e41JWvX/KS7hv1Qv9ByYOz7VletLiRM9YUpygNvVBlJO3NlVhbFbz7tN7VTmM8xbIO5W/@RRqpOeK22mL1PPyebuwuC1yrP2lpDGPmYlfC9AX7mF674LUGOZ360yqubhNUKe6mjS08/J5o5SoIBb4eRmjKIEYepdISdviRw1aLX4ctWb1V1hjoT@jVCWsfsTUwFuMBtpaTH3fhFgp63tQd3AxZyR9/Y/T@pe@4R35Ud@3bSPv/kx3N2Ek/XVc3Wp/I2n9PsLw "C++ (gcc) – Try It Online")
*Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python](https://codegolf.stackexchange.com/a/262142/9481) answer*
*Saved 6 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·<P>;
```
Port of [*@xnor*'s third Haskell answer](https://codegolf.stackexchange.com/a/262141/52210), taking advantage of the \$1-p\$ input probabilities.
[Try it online](https://tio.run/##yy9OTMpM/f//0HabADvr//@jDfSMTHVARCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9mWKnrYq@k8KhtkoKS/f9D220C7Kz/u9iraxgf3mVfCZcxLNa1V9fU@R8dbaBnaGQcq6MAYegY6JmCOToGOoZACCTRuHAVeuamOiAChYMkYmxsBuSZmJkDSQNDCNsSIgVkgATBUmYQTQbmUF0WIJVGRiYgewzAei1Bis1NjKAWWZqBDbSEOsbI0BzmApCEJVingQFIysAELGJmBBcxNDGJjQUA).
**Explanation:**
```
· # Double each value in the (implicit) input-list
< # Decrease each value by 1
P # Pop and push the product of the list
> # Increase it by 1
; # Halve it
# (after which the result is output implicitly as result)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ḍ⁻p⁺½
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWax7u6HnUuLvgUeOuQ3uXFCclF0MlFqyONtAzMtUBEbEQIQA)
Port of xnor's third Haskell answer.
#### Explanation
```
Ḍ⁻p⁺½ # Implicit input
Ḍ # Double the input
⁻ # Decrement each
p # Take the product
⁺ # Increment it
½ # Halve
# Implicit output
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes (18 nibbles)
```
/$:-+!\$_**`(!$_*~
```
Nibbles natively supports neither floating-point arithmetic nor fractions, so input is a list of 2-element lists of integers representing the numerator & denominator of each probability expressed as a fraction.
We then reduce the list with (in pseudocode):
`function( [xnum, xden], [pnum, pden] ) = [xnum*pden + pnum*xden - 2*xnum*pnum, xden*pden]`
and output the final probability as ([non-reduced](https://codegolf.meta.stackexchange.com/questions/9263/which-number-formats-are-acceptable-in-output/9267#9267)) numerator & denominator.
```
/$:-+!\$_**`(!$_*~ # full program
/$:-+!\$_**`(!$_*~$ # with implicit arg added;
/$ # fold over input with this function:
+ # first, get the sum of
! # zipping together
\$ # reverse of left element
_ # and right element
* # by multiplication
- # now, subtract from this
* ~ # 2x
`( # first element
# (and remember 2nd element) of
! # zipping together
$ # left element
_ # and right element
* # by multiplication
: # and join to the rememebered 2nd element
```
[](https://i.stack.imgur.com/EAqMw.png)
[Answer]
# [Scala](https://www.scala-lang.org/), 30 bytes
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=bVHNattAEKY5qi8x9SWr1F5kWbFigwyFXgIuDbilByHMRl4l2653l9WqsQl-kl6aQ3vpO_RB8jTdH9e1oSCYme-bb-ab1befbU04Gf0qewMhH4gWver57IytldQGPIeZxAuzuhZYU7KaM0GjE7ozjOMPehtF8vYzrQ28I0zAYwSwog2sbYGIvmun8EZrsi0XRjNxV8VT-CiYgcJ3AlwbqomRGtdSGCY6wvkW_V0Y-xYAbMgX-umecYqW8KoA0XF-4NZEIUV0S9_K7pbT9kDUknPn6xFq0lJYyDVFnLUmhmIGLoHd8Yz6IGykNVDfI2UdGy4cvov2dx1vQkyozkwhnGYve68Mk6Kc29ll6Kmqw6VfCYfWdipF7aNaoWX8AOzRG00btkG9shcHYNE1Hqh6wZh9anSix63izKDz_nnsD1hiy66xkWF1bDPnxMVgLNwROSP1FB27LGZ7TfGjM83g6vfS_vRVV9M5bQxCm76Ki9nmtRqkF-piE4emp12I359fvCwTPExHVRRiHxJ86Qqb9GHoP5f8Bzq04vzS5flpcQSNRmNXZePchWS4ryaetNGjgRzvhUkelFe-N00zvy0JAyZekWdpWDgZh7GTf77SYb4347lJ0CeJJ5MsgOP0CBxmWRUe5Q8)
```
_.reduceLeft((x,p)=>x+p-2*p*x)
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=bVLNitswEKY9ui8xzWXlbVbYjtfeBFIo9LKQ0kK69GDMojjyrlpZErJcEpY8SS-5tA-1T1NZcrMOFAwz833z881Yv_60FeFkdjz-7kx9dfP8-o41SmoDDsdM4rXZ3gqsKdmumKDBGd0ZxvFXvQ8CuflOKwOfCBPwFABsaQ2NDRDRD-0CPmhN9sXaaCYeynABd4IZWLpMgFtDNTFS40oKw0RHON-jfwNDlwKADflBvz0yTtE9vF2C6Dg_cQ1RSBHd0o-y23DanohKct7reoKKtBTWsqGIs9aEsHwPvQOHcY9KNqozLzNraWVUj0hZ3YaLHj8Ew3bjeYgJW7cAv6Dd77MyTIpiZScUPqcsT_v-JBxam6kUtae1hZZxDbBDv2hasx2aFJPQA-uudkA58cLswdFZPW4VZwZdTC9Ct8Y9tmyDjfSjQ-v1SnrrhY33GHZGoms2VNt_NRZtV_HeSfyQZh_EtqvoitYGod0UlLvoDt6BgitI4NLaS9j5ix0C_7qGR3Z8fvWmiHCczMrA2ylE-LoPrDOF2H298x_olIrz697Pz4MRNJtlfZRmeW-ieIjmjrTWoZ7MhsIo95U3LjdJUjct8g3mriJPEz9wnvm28xddSZwPYhw39_VR5Mgo9WCWjMA4TUt_lL8)
```
import scala.io.StdIn.readLine
import scala.util.Try
object Main {
def main(args: Array[String]): Unit = {
Iterator.continually(readLine)
.takeWhile(_ != null)
.map(parseDoubles)
.collect { case Some(list) => list }
.map(compute)
.foreach(println)
}
def parseDoubles(input: String): Option[List[Double]] = {
val strippedInput = input.stripPrefix("[").stripSuffix("]")
Try(strippedInput.split(',').map(_.trim.toDouble).toList).toOption
}
def compute(numbers: List[Double]): Double = {
numbers.reduceLeft((x, p) => x + p - 2 * p * x)
}
}
```
[Answer]
# [Julia 1.0](http://julialang.org/), 27 bytes
```
p>t...=(t.|>i->p+=i-2p*i;p)
```
[Try it online!](https://tio.run/##ZY9dTsQgFIXfZxVkfKHaEv5/YkrcgCswPjAZJsE0lbTV@OACdJtupFJoHUcJCdzvHO65PL10wZG3eY52Qgi1cELvNjQ23rShofE63MZqPj0PIIDQg8G7Yxd6P8JqB9Jy9QG0wL@6DsF7PzkU3TB6BMfYhQmGet/YfVUVbxxCP3U9dKC1wEKX0lbl6s6Nox@mjYKvzw9w2Pn@OD9gRCh7BI0F@bYroE6VWKlILNU1IHkvl6yQ//zvM6TEgtTGmLqgF5qQNIuMyYVzqZYDk7Uyq40bwwRmWmoiF3tSsq/Y5doUqx@7JARjwrM5PVtkSnmeFJcIkzsoTs8RUmhMFTaKcZ4nNrJMY84fpWQLYUxrhpnU5XPZakpGis4HL1DSX5BwvjaQ1BBJjBaa4jQt/wY "Julia 1.0 – Try It Online")
Based on [xnor's answer](https://codegolf.stackexchange.com/a/262142)
29 bytes with recursion [Try it online!](https://tio.run/##ZY9dTsQgFIXfuwoyT1RbwuWfhxI34AqMD0ymJpimNm01LkG36UYqPx3HUUIC9zuHey7Pr0Pw8L5tk1sJIR2Glk31jcOpqm@nyuG6o9vTy4wCCiOae38awtgvuK5QXL45og71b34g@L5fPZn8vPQEL9MQVhyaQ@sOdV280xzGdRixR51DDvuUUJQ7vyz9vJ4h@vr8QMeqH0/bAyXA@CNqHcq3qoAmVnKnMrJYNwjyTpeswH/@9xnRMiF9Zlxf0StNKpZFzlXiQul0UNgru9uEtVxSbpQBlexRyb5iV3tTqn/sCoBSENkcnyWZMZEnpSXC5g5asEuEkoYyTa3mQuSJrSrT2MtHGZxDODeGU65M@Vy22pIRo/MhClTsFwQh9gaKWVBgjTSMxmnFNw "Julia 1.0 – Try It Online")
28 bytes with `reduce` [Try it online!](https://tio.run/##ZY9LbsMgFEXnWQXJCLe2xf8ziNUNdAVVByQhEhVykO1U7g7abXYjLgYnaVqEBO/cy7uPt7N3Bo/TtPbbzh7OewvhWIaiasbHUJHxIZS@mI6nDjjgWtBZc/CutT0sViAuU@7AFth342v4bAdTB9P1toZ98G6ArtxUzaYosjd0rh18Cw3YNmC9P4UPaBbpyfS97YYrBd9fn2C3su1hekE1JvQVVA1It1UGZaz4QnlksS4BTnu@JAX/53@f1ZLPSF4YlXf0TuOCJJFSMXMm5HwgvFR6sTGtKUdUCYXFbI9K8mW7WJoiebULjBHCLJnjs1kmhKVJUY7QqYNk5BYhuEJEIi0pY2liLfI0@vZRgi8hlCpFERUqfy5Zdc6I0elgGQryC2LGlgaCaCywVlwRFKdlPw "Julia 1.0 – Try It Online")
[Answer]
# Mathematica (Wolfram Language) 18 bytes
This is an infix example of xnor's idea.
```
#1+#2-2#1#2&~Fold~
```
This gives the correct output on all the test cases. I would be interested to know if the arguments could be shortened using some kind of Sequence[].
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
a=>a.map(p=>x+=p-x*p*2,x=0)&&x
```
[Try it online!](https://tio.run/##bU7dCoIwFL73KbwKNR1nc26NWM8g3ooXo1oU1YZF@PaW20KJYLDv53zfORf1Uo99f7bP4m4Ox1HLUcmdQjdlEyt3w1raYshsRvJBQrpaDWMj26gFhEnZ5QHkMaDKsQ/KY@zeBP5p8zDi1UT4D1tqZckmShmfPsCBCe9@gJO9y0IUeMhu3DQh1K0EXyFchFMSlgrmm8V8HcH8e5EzhW8AcC5QLzKyEDGlXdRtI236pI6Njpt0b@4Pcz2iqzklOqnTdDu@AQ "JavaScript (Node.js) – Try It Online")
[Port](https://codegolf.stackexchange.com/a/262142/76323)
[Answer]
# ARM64 machine code, 32 bytes
This function takes as input a pointer to an array of 64-bit doubles in `x0`, and a pointer to the end of the array (one past last element) in `x1`. It returns the result in `d0`. This is consistent with standard calling conventions for a C function declared as `double xor_bernoulli(const double *array, const double *end);`, to be called like `xor_bernoulli(arr, arr+len)`.
```
2f00e400
fc408401
1f418002
1f418403
1e632840
eb01001f
54ffff63
d65f03c0
```
Assembly source:
```
.global xor_bernoulli
.text
.balign 4
// x0 = pointer to input
// x1 = pointer to end
// d0 will accumulate the probability
xor_bernoulli:
movi d0, 0 // = 0.0
continue:
// Compute p(1-q) + q(1-p) = (p-pq) + (q-pq)
// let d0 = p
ldr d1, [x0], #8 // d1 = q, x0 += 8
fmsub d2, d0, d1, d0 // d2 = p-pq
fmsub d3, d0, d1, d1 // d3 = q-pq
fadd d0, d2, d3 // d0 = d2 + d3 = (p-pq) + (q-pq)
cmp x0, x1
b.lo continue
ret
```
The fused multiply-subtract instruction is quite helpful here. It seems a little inefficient that we compute `pq` twice, thus doing two multiplies where only one is really needed, but I couldn't find a way to avoid it without more instructions.
I thought about trying to use SIMD instructions, but the best I could come up with was the following for the loop body:
```
continue:
// on entry, v0 = [0, p]
ld1 {v0.d}[1], [x0], #8 // v0 = [q, p]
ext v1.16b, v0.16b, v0.16b, #8 // v1 = [p, q]
fmls v0.2d, v0.2d, v1.2d // v0 = [q-qp, p-pq]
faddp d0, v0.2d // v0 = [0, q-qp + p-pq]
```
which is the same length. We can do both multiply-subtracts in parallel with vector `fmls`, but we need the extra `ext` shuffle instruction to make a copy with `p` and `q` swapped.
] |
[Question]
[
# AND THE WINNER IS....
>
> Command Master's "Ball Pulling"!
>
>
>
Note: Competition is over, but more submissions are welcome!
Ball game is a game I invented where two players start with 100 energy each. Every turn, each player independently chooses an amount of energy to spend. Whoever spends more energy brings the ball 1 unit closer to their side - if they spend the same, it's a tie. If the ball is on someone's side, 4 units away from the center, the person who's side it's on wins. If both players run out of energy before it has reached one side or the other, it's a draw.
An example game might look like this:
```
rem P1 3 2 1 0 1 2 3 P2 rem
75 25 o 33 67
50 25 o 8 59
25 25 o 8 51
0 25 o 18 33
0 0 o 15 18
0 0 o 6 12
0 0 o 12 0
DRAW
```
Your job is to make a bot for this game, in javascript.
# Rules
The bot is a function taking three values:
The player's energy, as a number.
The player's previous moves, as an array of numbers.
The ball position, as a number between -3 and 3 inclusive. Positive is closer to the player, negative is further.
The function must return an integer between 1 and 100 (Not NaN).
No messing with other bots.
No global variable access, as in standard KoTH rules.
# Controller
This controller can do two things: It can 1v1 two bots, and it can run a tournament with each bot facing every other bot 100 times. The 1v1 setting generates a log of the game, and the tournament setting creates a leaderboard. The tournament is scored by +1 point for winning, nothing for drawing or losing.
Bots should be added to the bots object.
```
var bots = {
"25er": function(myE, myPrev, pos) {
return 25;
},
"random": function(myE, myPrev, pos) {
return Math.floor(Math.random() * 36) + 1;
},
"Ball pulling": function(myE, myPrev, pos) {
return Math.max(1,Math.floor(myE * [0.10808232641486629,0.30174603004818334,0.2358032944932353,0.10406266397506114,0.25013297998583794,0.4608205872385916,0.5635474208925423][3-pos] + [-25.20386503823533,-4.62324162626722,-7.69195538879287,-5.7156191657689925,-3.221187031407233,-16.758418842577605,-4.233010800850232][3-pos] + Math.random() * [23.13539398461274,-3.257894925941551,-0.09547522996644178,-0.09187251666187485,-1.1010525700900573,-9.874021194357677,2.831769191532314][3-pos]));
},
"Decay": (energy, previous, position) => {
return energy == 100 ? 30 : Math.ceil(energy * 0.15);
},
"waiter": (myE, myPrev, pos) => {
if (pos == 3) {
// If 1 space from winning, spend all energy to try and win
return myE;
} else if (pos == 1) {
return Math.max(1, Math.floor(myE * .06));
} else if (pos == -3) {
// If opponent is 1 space from winning, spend 82% energy to try and prevent them from winning, or spend 9 to counter Memory
return myPrev.length < 9 ? Math.ceil(myE * .82) : Math.min(9, Math.ceil(myE * .82));
} else if (myPrev.length < 1) {
// If fewer than 1 turn has been played, "wait" and only spend 1 energy
return 1;
} else {
// Otherwise spend up to 12% of energy
return Math.max(1, Math.floor(myE * .12));
}
},
"Exhauster": function(myE, myPrev, pos) {
return pos == -3 ? 28 - myPrev.length : 3;
},
"Memory": function(myE, myPrev, pos) {
if (myPrev.length == 0) return 2;
prev_pos = 0;
for (i = 0; i < myPrev.length - 1; i++) {
if (myPrev[i] > myPrev[i + 1]) {
prev_pos += 1;
} else if (myPrev[i] < myPrev[i + 1]) {
prev_pos -= 1;
}
}
move = myPrev[myPrev.length - 1]
if (pos == 3) return move;
if (prev_pos > pos) {
move = Math.ceil(move * 2.75);
} else if (prev_pos < pos) {
move = Math.ceil(move * 0.8);
}
return Math.max(1, Math.min(move, myE - 8));
},
"just1": (myE, myPrev, pos) => {
return pos === -3 ? Math.ceil(myE / 4) : 1;
},
"Vague Memory": function(myE, myPrev, pos) {
if (myPrev.length == 0) return 2;
prev_pos = 0;
for (i = 0; i < myPrev.length - 1; i++) {
if (myPrev[i] > myPrev[i + 1]) {
prev_pos += 1;
} else if (myPrev[i] < myPrev[i + 1]) {
prev_pos -= 1;
}
}
move = myPrev[myPrev.length - 1]
if (pos == 3) return move;
if (prev_pos > pos) {
move = Math.ceil(move * 2.75 - 2.4 * Math.random());
} else if (prev_pos < pos) {
move = Math.ceil(move * 0.8);
}
min_move = Math.round(3.5 * Math.random());
if (pos < -1) min_move += 2;
return Math.max(min_move, Math.min(move, myE - 28));
},
"table": (myE, myPrev, pos) => {
if (myE == 0) {
return 0;
}
let w = [
[-5.6544223, 0.06557736, -0.2641703],
[0.75869083, -0.011340193, 1.4130216, -1.2559392],
[0.13409477, 2.9561214, 0.27817196, 0.0030480723, 0.3889832],
[-2.6868086, -0.3014877, 4.818155, 3.9265578, 1.7512726, 0.097844936],
[0.68415153, 0.72050923, 1.334225, -1.6574494, 2.4933205, -0.25133085, -1.4409807],
[1.6410222, -74.064156, -7.7318263, -0.01627013, 2.0059361, -6.7933116, -0.14581795, -1.6378351],
];
let b = [1.8160640001296997, 1.5627140998840332, 3.7942299842834473, -2.4042959213256836, 2.8334028720855713, 312.232177734375];
let log_weights = [];
let log_weight_max = -Infinity;
for (let m = 0; m < myE; m++) {
let f = [m / (myE - 1), (myE - 50) / 29.15475947, 0.5 * pos, 0, 0, 0, 0, 0, 0];
for (let l = 0; l < w.length; l++) {
f[l + 3] = b[l];
for (let i = 0; i < w[l].length; i++) {
f[l + 3] += w[l][i] * f[i];
}
if (b[l] <= 300) {
f[l + 3] = Math.max(f[l + 3], 0);
}
}
let log_weight = f[f.length - 1];
log_weight_max = Math.max(log_weight_max, log_weight);
log_weights.push(log_weight);
}
let Q = 0;
let M = 0;
for (let m = 0; m < log_weights.length; m++) {
let q = Math.exp(log_weights[m] - log_weight_max);
Q += q;
if (Math.random() * Q <= q) {
M = m;
}
}
return M + 1;
},
"Pacemaker": (myE, myPrev, pos) => {
if (myPrev.length === 0) return 4; // https://xkcd.com/221/
if (pos === 3) return Math.round(myE * 0.99);
if (pos === -3) return Math.max(1, Math.round(myE * 0.4));
return Math.max(1, Math.min(myE, Math.round(myE / (7 - pos))));
},
"Fraction": function(myE, myPrev, pos) {
return ((myPrev.length===3)&&(pos===-3))? 25 : Math.floor(myE/(pos+4)*0.395)
},
'chair': function(myE, myPrev, pos) {
let c = 0x69b82a691f395b79b7fb2bb83cb5f2a40ce32e4a4c4a055f7c50e68a3f81e123197280dfbec638e3b036a9b53677122f2fa83447501ece2a63d766e983ff858cda2da01ac621bb3084c1055a2fe83e6a7450c29fa99549d3cc6f1c556550b2397f417e915b65d47a9d6c1b267aaab5171d3e8a7fbad4788e9cb795cdc11759ba232730ad0a3635a8a9c5564afdf5b82c380687a8af1b1f1ca4d36ac668b32cafe39afdda16421be9d955ce70cfab6c987dc407e97792f647a43ecd0f191fecdbc60ef782519410655f3054395cc0e1c68f893f416806ad502b9b945166b61110f7d72c0d5437d32235007c26b64f787f1147e3ce1966a4ff6fb564d47db1b191801e811052dd5c31bee7fed77afae4799debec9349e224155780fbd65684d2503356b0c71805a41994fd48f043ee745d8bc8e12bb8105cb97edef8e08f2d5467649aceb5ee668168420ad4b4b0d9c33cf4577b19827220dec3377c1bdf627fa1b3015b59b0a5e4b456f4d18abbbc4d22bde46c7596a7cbabb4536fa325561e50e1bdffeee5fb17a6222ae7f5d894c824920227b4f45aa369e8d3956b68ad8ba2499c5b4f925b42983544c1c9cbff22bb3774c138c0b04b47be0a91c73164b0729d0fd4521be988e78584d5974fc0083452e6127507a59956104d84ad3bc481325d21295ebfc63ea8c4708251a1df30a3f7e906b9acba9eda44f60091c6765466a6f9dbc5a83862ad358d0a41f7d4d099670b2e6302d9a1d5dbfb54a1698e3f9d9956ad90e53n;
return myE <= 1 ? myE : Number((c / (83n ** BigInt(myE * 7 + pos - 11))) % 83n + 1n);
},
'Indecisive Tracker': (myE, myPrev, pos) => {
const RESULT = { WIN: 0, DRAW: 1, LOSE: 2 }
const RESULT_ENCODING_OFFSET = [0, 1, 2]
const RESULT_WEIGHT = [1, 0, -1]
const MIN_SPENDING = 1
const posToAggressionFactor = [0, 0.3, 0.2, 0, 0, 0, 0.1, 0.8, 0]
const posToRiskAppetite = [0, 1, 0.4, 0.1, 0.1, 0.1, 0.2, 0.3, 0]
let encodeResult = (E, lastResult) => E + RESULT_ENCODING_OFFSET[lastResult]
let decodeResult = (E) => RESULT_ENCODING_OFFSET.findIndex(e => e === (E - MIN_SPENDING) % RESULT_ENCODING_OFFSET.length)
let getResultFromPos = (posBefore, posAfter) => {
return posBefore < posAfter ? RESULT.WIN
: posBefore > posAfter ? RESULT.LOSE
: RESULT.DRAW
}
let BallMove = (prevPos, currE, nextE, finalPos) => {
let currResult = nextE == null ? getResultFromPos(prevPos, finalPos)
: decodeResult(nextE)
let nextPos = prevPos + RESULT_WEIGHT[currResult]
let enemyE = currResult === RESULT.LOSE ? currE + 1
: currResult === RESULT.DRAW ? currE
: 1
return {
enemyE: enemyE,
myE: currE,
posBefore: prevPos,
posAfter: nextPos,
result: currResult
}
}
const GOAL = 8
let normalizedPos = pos + 4
let goalDistance = GOAL - normalizedPos
let minimumReservedEnergyPerTileDistance = 3
let spendableEnergy = myE - ((goalDistance - 1) * minimumReservedEnergyPerTileDistance)
let prevPos = 0
let prevResult = RESULT.DRAW
let gameMoves = new Array()
for (i = 0; i < myPrev.length; i++) {
let currMove = BallMove(prevPos, myPrev[i], myPrev[i+1], pos)
prevPos = currMove.posAfter
prevResult = currMove.result
gameMoves.push(currMove)
}
let myRandom = (min, max, spacing) => {
if ((spacing ?? 0) === 0) spacing = 1
let maxEncodingOffset = Math.max.apply(null, RESULT_ENCODING_OFFSET)
let adjustedMin = Math.floor((min + maxEncodingOffset) / spacing) * spacing
let offset = adjustedMin
let adjustedMax = max - offset - maxEncodingOffset
let adjustedRange = Math.floor(adjustedMax / spacing) + 1
return Math.floor(Math.random() * adjustedRange) * spacing + offset
}
let minE = spendableEnergy * posToAggressionFactor[normalizedPos]
let maxE = spendableEnergy * posToRiskAppetite[normalizedPos]
let nextE = MIN_SPENDING + myRandom(minE, maxE, RESULT_ENCODING_OFFSET.length)
let encodedNextE = encodeResult(nextE, prevResult)
return encodedNextE
},
// add your bot here
}
function game(p1, p2) {
var ballPos = 0,
p1moves = [],
p2moves = [],
p1e = 100,
p2e = 100,
outcome = '';
var str = 'rem P1 3 2 1 0 1 2 3 P2 rem';
function string(pos, e, e2) {
var s = p1e + (p1e < 100 ? (p1e < 10 ? ' ' : ' ') : ' ') + e + (e < 10 ? ' ' : '');
if (pos == -4) {
s += ' P1 WINS '
} else if (pos == 4) {
s += ' P2 WINS '
} else {
s += ' '.repeat((pos + 4) * 3 - 1) + 'o' + ' '.repeat(23 - (pos + 4) * 3)
}
return s + (e2 < 10 ? ' ' : '') + e2 + (p2e < 100 ? (p2e < 10 ? ' ' : ' ') : ' ') + p2e;
}
while (Math.abs(ballPos) < 4) {
var p1out = p1e ? Math.max(Math.min(p1e, bots[p1](p1e, p1moves, -ballPos)), 1) : 0;
var p2out = p2e ? Math.max(Math.min(p2e, bots[p2](p2e, p2moves, ballPos)), 1) : 0;
if (p1out > p2out) {
ballPos--;
} else if (p1out < p2out) {
ballPos++;
}
p1e -= p1out;
p2e -= p2out;
str += '\n' + string(ballPos, p1out, p2out);
if (p1e == 0 && p2e == 0 && Math.abs(ballPos) < 4) {
str += '\n DRAW ';
break
}
p1moves.push(p1out);
p2moves.push(p2out)
}
return {
log: str,
res: (ballPos == -4 ? 1 : (ballPos == 4 ? 2 : 0))
}
}
function init() {
var f = document.getElementById('f'),
f2 = document.getElementById('f2');
for (var x in bots) {
var option = document.createElement('option');
option.innerText = x;
option.value = x;
f.appendChild(option);
var option2 = document.createElement('option');
option2.innerText = x;
option2.value = x;
f2.appendChild(option2)
}
}
init();
function play() {
var f = document.getElementById('f'),
f2 = document.getElementById('f2');
document.getElementById("g").innerText = game(f.value, f2.value).log
}
function tournament() {
var leaderboard = {},
names = [];
for (var x in bots) {
names.push(x);
leaderboard[x] = 0
}
for (var t = 0; t < names.length; t++) {
for (var y of names.slice(t + 1)) {
for (var r = 0; r < 2000; r++) {
var res = game(names[t], y);
if (res.res == 1) {
leaderboard[names[t]]++
} else if (res.res == 2) {
leaderboard[y]++
}
}
}
}
var o = [];
for (var x in leaderboard) {
o.push({
n: x,
s: leaderboard[x]
})
}
o = o.sort((x, y) => y.s - x.s);
var t = document.getElementById('t');
t.innerHTML = '';
t.innerHTML += `<tr><td>Name</td><td>Score</td></tr>`
for (var d of o) {
t.innerHTML += `<tr><td>${d.n}</td><td>${d.s}</td></tr>`
}
}
```
```
<select id='f'></select> vs
<select id='f2'></select><button onclick='play()'>Play</button>
<pre><code id='g'></code></pre>Or start tournament: <button onclick='tournament()'>Go!</button>
<table id='t'></table>
```
# Leaderboard so far:
| Ranking | Name | User |
| --- | --- | --- |
| 1st | Ball pulling | Command Master |
| 2nd | Fraction | qwatry |
| 3rd | Waiter | 79037662 |
| 4th | Chair | user1502040 |
| 5th | Indecisive Tracker | aff |
| 6th | Vague Memory | histocrat |
| 7th | Table | user1502040 |
| 8th | Pacemaker | Ethertyte |
| 9th | Memory | histocrat |
| 10th | Exhauster | Sheik Yerbouti |
| 11th | Decay | Redwolf Programs |
| 12th | just1 | Spitemaster |
| 13th | random | Me (demo) |
| 14th | 25er | Me (demo) |
Command Master's "Ball pulling" mantains its spot in first. qwatry's new "Fraction" has jumped into second. The apparent tie between "waiter" and "chair" has been resolved by a 1v1 - "waiter" beats "chair", but they both score the same amount of points. aff's "Indecisive Tracker" uses the most complicated algorithm yet, but makes it into 5th place.
[Answer]
# Memory
```
"Memory": function(myE, myPrev, pos) {
if (myPrev.length == 0) return 2;
prev_pos = 0;
for(i=0;i<myPrev.length-1;i++) {
if (myPrev[i] > myPrev[i+1]) {
prev_pos += 1;
} else if (myPrev[i] < myPrev[i+1]) {
prev_pos -=1;
}
}
move = myPrev[myPrev.length-1]
if (pos==3) return move;
if(prev_pos > pos) {
move = Math.ceil(move * 2.75);
} else if (prev_pos < pos) {
move = Math.ceil(move * 0.8);
}
return Math.max(1,Math.min(move, myE - 8));
}
```
Infers whether it won or lost last round from how it adjusted in previous rounds, and then adjusts.
[Answer]
# The demo bots
## Random
Outputs a random integer between 1 and 36.
```
function(myE,myPrev,pos){
return Math.floor(Math.random() * 36) + 1;
}
```
## 25er
Outputs 25 all the time.
```
function(myE,myPrev,pos){
return 25;
}
```
Note: These two are built into the controller - no need to add them.
Why is this the most popular?
[Answer]
# Table
```
"table": (myE, myPrev, pos) => {
if (myE == 0) {
return 0;
}
let w = [
[-5.6544223, 0.06557736, -0.2641703],
[0.75869083, -0.011340193, 1.4130216, -1.2559392],
[0.13409477, 2.9561214, 0.27817196, 0.0030480723, 0.3889832],
[-2.6868086, -0.3014877, 4.818155, 3.9265578, 1.7512726, 0.097844936],
[0.68415153, 0.72050923, 1.334225, -1.6574494, 2.4933205, -0.25133085, -1.4409807],
[1.6410222, -74.064156, -7.7318263, -0.01627013, 2.0059361, -6.7933116, -0.14581795, -1.6378351],
];
let b = [1.8160640001296997, 1.5627140998840332, 3.7942299842834473, -2.4042959213256836, 2.8334028720855713, 312.232177734375];
let log_weights = [];
let log_weight_max = -Infinity;
for (let m = 0; m < myE; m++) {
let f = [m / (myE - 1), (myE - 50) / 29.15475947, 0.5 * pos, 0, 0, 0, 0, 0, 0];
for (let l = 0; l < w.length; l++) {
f[l + 3] = b[l];
for (let i = 0; i < w[l].length; i++) {
f[l + 3] += w[l][i] * f[i];
}
if (b[l] <= 300) {
f[l + 3] = Math.max(f[l + 3], 0);
}
}
let log_weight = f[f.length - 1];
log_weight_max = Math.max(log_weight_max, log_weight);
log_weights.push(log_weight);
}
let Q = 0;
let M = 0;
for (let m = 0; m < log_weights.length; m++) {
let q = Math.exp(log_weights[m] - log_weight_max);
Q += q;
if (Math.random() * Q <= q) {
M = m;
}
}
return M + 1;
}
```
Closely approximates the Nash equilibrium. Not exploitative enough to top the leader board.
# Chair
```
'chair': function(myE, myPrev, pos) {
let c = 0x69b82a691f395b79b7fb2bb83cb5f2a40ce32e4a4c4a055f7c50e68a3f81e123197280dfbec638e3b036a9b53677122f2fa83447501ece2a63d766e983ff858cda2da01ac621bb3084c1055a2fe83e6a7450c29fa99549d3cc6f1c556550b2397f417e915b65d47a9d6c1b267aaab5171d3e8a7fbad4788e9cb795cdc11759ba232730ad0a3635a8a9c5564afdf5b82c380687a8af1b1f1ca4d36ac668b32cafe39afdda16421be9d955ce70cfab6c987dc407e97792f647a43ecd0f191fecdbc60ef782519410655f3054395cc0e1c68f893f416806ad502b9b945166b61110f7d72c0d5437d32235007c26b64f787f1147e3ce1966a4ff6fb564d47db1b191801e811052dd5c31bee7fed77afae4799debec9349e224155780fbd65684d2503356b0c71805a41994fd48f043ee745d8bc8e12bb8105cb97edef8e08f2d5467649aceb5ee668168420ad4b4b0d9c33cf4577b19827220dec3377c1bdf627fa1b3015b59b0a5e4b456f4d18abbbc4d22bde46c7596a7cbabb4536fa325561e50e1bdffeee5fb17a6222ae7f5d894c824920227b4f45aa369e8d3956b68ad8ba2499c5b4f925b42983544c1c9cbff22bb3774c138c0b04b47be0a91c73164b0729d0fd4521be988e78584d5974fc0083452e6127507a59956104d84ad3bc481325d21295ebfc63ea8c4708251a1df30a3f7e906b9acba9eda44f60091c6765466a6f9dbc5a83862ad358d0a41f7d4d099670b2e6302d9a1d5dbfb54a1698e3f9d9956ad90e53n;
return myE <= 1 ? myE : Number((c / (83n ** BigInt(myE * 7 + pos - 11))) % 83n + 1n);
},
```
Uses a magic constant as a lookup table. Optimized against the current playing field.
[Answer]
# Decay
```
{
"Decay": (energy, previous, position) => {
return energy == 100 ? 30 : Math.ceil(energy * 0.15);
}
}
```
Starts with 30 energy, which is enough to give it an initial lead. It then uses 15% of its remaining energy each turn.
[Answer]
# Ball pulling
```
"Ball pulling": function(myE, myPrev, pos) {
return Math.max(1,Math.floor(myE * [0.10808232641486629,0.30174603004818334,0.2358032944932353,0.10406266397506114,0.25013297998583794,0.4608205872385916,0.5635474208925423][3-pos] + [-25.20386503823533,-4.62324162626722,-7.69195538879287,-5.7156191657689925,-3.221187031407233,-16.758418842577605,-4.233010800850232][3-pos] + Math.random() * [23.13539398461274,-3.257894925941551,-0.09547522996644178,-0.09187251666187485,-1.1010525700900573,-9.874021194357677,2.831769191532314][3-pos]));
}
```
[JSFiddle](https://jsfiddle.net/sgk1vz5e/5/)
Calculates a linear function of the energy and a random number, with the exact function depending on the ball location.
[Answer]
# Just1
```
"just1": (myE, myPrev, pos) => {
return pos === -3 ? Math.ceil(myE / 4) : 1;
}
```
Waits out its opponent - it bids 1 unless it'd lose if it doesn't spend more - then it spends 25% of its current energy.
[Answer]
# Exhauster
```
"Exhauster": (myE,myPrev,pos) => {
return pos == -3 ? 28 - myPrev.length : 3;
}
```
It uses 3 units of energy in every turn, except when the opponent is at one step from the victory.
[Answer]
# Waiter
```
"waiter": (myE, myPrev, pos) => {
if (pos == 3) {
// If 1 space from winning, spend all energy to try and win
return myE;
} else if (pos == 1) {
return Math.max(1, Math.floor(myE * .06));
} else if (pos == -3) {
// If opponent is 1 space from winning, spend 82% energy to try and prevent them from winning, or spend 9 to counter Memory
return myPrev.length < 9 ? Math.ceil(myE * .82) : Math.min(9, Math.ceil(myE * .82));
} else if (myPrev.length < 1) {
// If fewer than 1 turn has been played, "wait" and only spend 1 energy
return 1;
} else {
// Otherwise spend up to 12% of energy
return Math.max(1, Math.floor(myE * .12));
}
}
```
Update `2021-04-03T21:14:04Z` - Changing 0.3 to 0.2 seems to improve performance against the current bots: <https://jsfiddle.net/jwnsq917/>
Update `2021-04-04T16:47:32Z` - Changing 0.2 to 0.12 improves performance against the current bots, in particular BallPulling: <https://jsfiddle.net/qd80eofc/1/>
Update `2021-04-05T13:26:19Z` - Changing 2 to 1 improves performance against the current bots: <https://jsfiddle.net/3sqftja7/>
The trend of "slightly adjust values to pull ahead" continues.
Update `2021-04-05T13:37:16Z` - Add case for when opponent is 2 spaces from winning: <https://jsfiddle.net/3sqftja7/5/>
Update `2021-04-05T15:10:57Z` - Add hard counter for Memory: <https://jsfiddle.net/egnwLb3r/>
Update `2021-04-07T14:06:56Z` - More minor adjustments to once again take top spot: <https://jsfiddle.net/ceL2as16/1/>
I suspect that due to the fact that minor changes can make a bot win against other bots, the winner of this challenge will simply be the last person to make their bot hard-counter the other bots, possibly by updating their bot in secret.
[Answer]
# Vague Memory
```
"Vague Memory": function(myE, myPrev, pos) {
if (myPrev.length == 0) return 2;
prev_pos = 0;
for(i=0;i<myPrev.length-1;i++) {
if (myPrev[i] > myPrev[i+1]) {
prev_pos += 1;
} else if (myPrev[i] < myPrev[i+1]) {
prev_pos -=1;
}
}
move = myPrev[myPrev.length-1]
if (pos==3) return move;
if(prev_pos > pos) {
move = Math.ceil(move * 2.75 - 2.4*Math.random());
} else if (prev_pos < pos) {
move = Math.ceil(move*0.8);
}
min_move = Math.round(3.5 * Math.random());
if(pos < -1) min_move += 2;
return Math.max(min_move,Math.min(move, myE - 28));
}
```
Same as Memory, this tries to hone in the right value by adjusting up when it loses a round and down when it wins one. But to make it harder to tune against, this one randomly saves energy toward the beginning and randomly spends it toward the end.
[Answer]
# Pacemaker
```
"Pacemaker": (myE, myPrev, pos) => {
if (myPrev.length === 0) return 4; // https://xkcd.com/221/
if (pos === 3) return Math.round(myE * 0.99);
if (pos === -3) return Math.max(1, Math.round(myE * 0.4));
return Math.max(1, Math.min(myE, Math.round(myE / (7 - pos))));
}
```
Tries to pace itself based on how many more rounds it expects the game to last. Goes all in if it's one win away from victory, goes in heavy if it's one loss away from complete loss.
I also tried out similar ideas with nondeterminism, but the hardcoded logic one performed better in all my variations.
Update: Increasing the plan-ahead time from 4 to 7 rounds seems to fair better so I've updated the parameter. Previously, initial rounds were too greedy, spending a lot of energy early on.
[Answer]
# Indecisive Tracker
```
'Indecisive Tracker': (myE, myPrev, pos) => {
const RESULT = { WIN: 0, DRAW: 1, LOSE: 2 }
const RESULT_ENCODING_OFFSET = [0, 1, 2]
const RESULT_WEIGHT = [1, 0, -1]
const MIN_SPENDING = 1
const posToAggressionFactor = [0, 0.3, 0.2, 0, 0, 0, 0.1, 0.8, 0]
const posToRiskAppetite = [0, 1, 0.4, 0.1, 0.1, 0.1, 0.2, 0.3, 0]
let encodeResult = (E, lastResult) => E + RESULT_ENCODING_OFFSET[lastResult]
let decodeResult = (E) => RESULT_ENCODING_OFFSET.findIndex(e => e === (E - MIN_SPENDING) % RESULT_ENCODING_OFFSET.length)
let getResultFromPos = (posBefore, posAfter) => {
return posBefore < posAfter ? RESULT.WIN
: posBefore > posAfter ? RESULT.LOSE
: RESULT.DRAW
}
let BallMove = (prevPos, currE, nextE, finalPos) => {
let currResult = nextE == null ? getResultFromPos(prevPos, finalPos)
: decodeResult(nextE)
let nextPos = prevPos + RESULT_WEIGHT[currResult]
let enemyE = currResult === RESULT.LOSE ? currE + 1
: currResult === RESULT.DRAW ? currE
: 1
return {
enemyE: enemyE,
myE: currE,
posBefore: prevPos,
posAfter: nextPos,
result: currResult
}
}
const GOAL = 8
let normalizedPos = pos + 4
let goalDistance = GOAL - normalizedPos
let minimumReservedEnergyPerTileDistance = 3
let spendableEnergy = myE - ((goalDistance - 1) * minimumReservedEnergyPerTileDistance)
let prevPos = 0
let prevResult = RESULT.DRAW
let gameMoves = new Array()
for (i = 0; i < myPrev.length; i++) {
let currMove = BallMove(prevPos, myPrev[i], myPrev[i+1], pos)
prevPos = currMove.posAfter
prevResult = currMove.result
gameMoves.push(currMove)
}
let myRandom = (min, max, spacing) => {
if ((spacing ?? 0) === 0) spacing = 1
let maxEncodingOffset = Math.max.apply(null, RESULT_ENCODING_OFFSET)
let adjustedMin = Math.floor((min + maxEncodingOffset) / spacing) * spacing
let offset = adjustedMin
let adjustedMax = max - offset - maxEncodingOffset
let adjustedRange = Math.floor(adjustedMax / spacing) + 1
return Math.floor(Math.random() * adjustedRange) * spacing + offset
}
let minE = spendableEnergy * posToAggressionFactor[normalizedPos]
let maxE = spendableEnergy * posToRiskAppetite[normalizedPos]
let nextE = MIN_SPENDING + myRandom(minE, maxE, RESULT_ENCODING_OFFSET.length)
let encodedNextE = encodeResult(nextE, prevResult)
return encodedNextE
}
```
Tries to encode last round's winning/losing information on the spent energy, then deduce (conservatively) the game rounds info. But it fails to decide what to do with the data...
Ultimately, the bot uses *lookup value based on the ball's position* to decide that round's minimum and maximum factors, which will be fed into a random function.
The lookup values themselves are initially based on intuition and then some test run until I got a good-enough result for me. So, you can say that they are partially based on the other bots' behavior.
[Answer]
# Fraction
```
"Fraction": function(myE, myPrev, pos) {
return ((myPrev.length===3)&&(pos===-3))? 25 : Math.floor(myE/(pos+4)*0.395)
},
```
I was just messing around and I discovered this simple solution that surprisingly does fairly well!
¯\\_(ツ)\_/¯
] |
[Question]
[
## Introduction:
Inspired by [the Puzzling-stackexchange post with the same name](https://puzzling.stackexchange.com/q/31679/13190), which I've answered four years ago:
>
> Can you create a perfectly valid English sentence, which makes perfect sense, but which contains the word "**and**" in it, five times consecutively in a row ?
>
>
> "*Something-or-other* **and and and and and** *something-else.*"
>
>
>
[With my answer:](https://puzzling.stackexchange.com/a/31680/13190)
>
> Let's say we have a store owner and his clerk. The store owner want the clerk to make a sign for the shop, which has the name (for example): "*Toys And Puzzles*".
>
> So, the clerk makes the sign and presents it to the owner.
>
>
>
> The owner thinks the spacing isn't really good. It currently looks something like:
>
> `Toys And Puzzles`
>
> but he wanted it to look more like:
>
> `Toys And Puzzles`
>
>
>
> So he says to the clerk:
>
> "The spacing between Toys **and And and And and** Puzzles should be a bit larger. Could you please fix that?"
>
>
>
## Challenge:
Given a string input, replace all occurrences of the word 'and' with five times that word; three in lowercase, interleaved with two of the original cased word.
Some examples:
* `AND` would become `and AND and AND and`
* `and` would become `and and and and and`
* `AnD` would become `and AnD and AnD and`
There is one catch however ([restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'")):
You're not allowed to use the characters `aAnNdD` in your source code. Any other character is still allowed, even if it's the unicode value of these letters, only these six characters themselves are banned.
## Challenge rules:
* Your source code cannot contain any of the characters `aAnNdD`.
* You can assume the input-string only contains spaces and letters (both lower- and uppercase)
* You can assume the input is non-empty
* It is possible that the input-string does not contain the word 'and', in which case it's returned as is
* Instead of a string you are also allowed to take the input as a list/array/stream of characters/code-point-integer (or other similar variations)
* Don't replace substrings of `and` if it isn't a standalone word (see test cases with `stand`, `band`, and `Anderson`)
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: "Toys And Puzzles"
Output: "Toys and And and And and Puzzles"
Input: "and"
Output: "and and and and and"
Input: "AND and anD"
Output: "and AND and AND and and and and and and and anD and anD and"
Input: "Please stand over there and watch" # note that the "and" in "stand" isn't changed
Output: "Please stand over there and and and and and watch"
Input: "The crowd loves this band" # note that the "and" in "band" isn't changed
Output: "The crowd loves this band"
Input: "Toys and And and And and Puzzles"
Output: "Toys and and and and and and And and And and and and and and and and And and And and and and and and and Puzzles"
Input: "Mr Anderson went for a walk and found a five dollar bill" # note that the "And" in "Anderson" isn't changed
Output: "Mr Anderson went for a walk and and and and and found a five dollar bill"
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~179~~ ~~176~~ ~~157~~ ~~152~~ 149 bytes
-3 -3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
-19 bytes thanks to [xibu](https://codegolf.stackexchange.com/users/90181/xibu)
```
L,M,P=543452769;f(s,t)typeof("")s,t;{M=M>>8|*s<<24;t=(M|' '|L<<24)-P?t:memcpy(t-3,(typeof(0)[]){P,M|=1<<29,P,M,P},20)+19;L=M;(*t=*s)&&f(s+1,t+1);}
```
[Try it online!](https://tio.run/##XVDLbsIwEDyTr1hFKthgJJ5tQwgVUi@VSJsDN8IhJA6JGmIUGxCPfDtdR9CiWrK8MzvjWTtsr8Pwep0xl3nOcNAfDHsvz5YdE8kUVcctFzExTYrIPruOO5m8XppyPO4NbOUQ99IAXI3LTDO07b2p0YZvwu2RqHafkZu/QxdLevaYe3G6KLSYp9NK1uvQVteyZ45rk6ZympLW6xjc6jLV6lK7vO5FGsGahElQAHaNs1GrarFT251aWLiWtlHTw944itCobYs0Vzj3R47UCMA3n6Rv@vlXpRn9Yj83GTx6S8Mw0AqbIM1Jlbcm5lwcJUzzCLzd6ZRxaeoQ5IM8upfTz3dAiPv9TnkZDyQHqTQv9rwAlfCCV7JDoMLkLpwnHMJCHCLIUCZRlkpYPVxe5WvbtEr4O//N4xa6wwspcjhwfEUsCggwLPuu5LHYaSPE6Z5DJLIMf3KVZpn2l9cf "C (gcc) – Try It Online")
## Assumptions
* ASCII
* Little-endian
* `sizeof(int) == 4`
* `sizeof(int *) >= sizeof(char *)` (I cannot imagine what absurd platform this would be false on, but you never know.)
* `typeof()` provided by the compiler.
## Breakdown
We step through the input string one character at a time. This character is placed at the top-most byte of `M`, shifting the previous characters to the left. This makes it so that `M` continuously holds a record of the four current characters. That's this part:
```
M=M>>8|*s<<24
```
Next up, we make `M` lower-case, and OR our fourth character with the previous character that we had before `M`. We compare the whole shebang with our magic number `P`, which represents the string "and ". Why ORing with the previous character like that? Well, it will only be true if that character was 0 (as in we are in the beginning of the string) or a space:
```
(M|' '|L<<24)==P
```
If this is true, we know we have an "and" to deal with. We make sure the last character of `M` is a space and not NUL, and build an anonymous array of integers to copy into target string.
This array is built from noting that the word "and" (and whatever arbitrary case variant we picked out of the source string) will always be followed by a space (except for the last instance) when expanded to its final form, which means a neat four bytes, which happens to be the size of an integer. The string "and " is represented by `P` (little-endian makes the string appear reversed when viewed as a number):
```
M|=1<<29 Make highest byte of M a space
t=memcpy(
t-3 Copy to sightly before target string
,(typeof(0)[]){P,M,P,M,P} Integer array of "and " isotopes
,20)
+19 Increment target string
```
Why to we copy to three bytes before the current target string? Because we have already copied those bytes before we knew it was an "and". And since this `memcpy()` is only ever called when we have found the keyword, we will never copy out of bounds.
The rest is straight-forward:
```
L=M; Last = Current
(*t=*s)&&f(s+1,t+1) Copy byte and go to next bytes
in strings if not end-of-string
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p -040 -l`, 35 bytes
This script contains unprintables so the link is to a Bash program that builds the script and runs the tests.
```
$s= ~'...';s/^$s$/$s $& $s $& $s/gi
```
[Try it online!](https://tio.run/##hZDPaoNAEMbvPsVHWOJp/zhaxWoCfYMeei7E7toIi0o2hiSHvPp2W@1FCv1ghhlm5sfMNAd39NerBj@hrmtsWLLBHode88XEaKvIfBwHxJ65HR6xECKunHxnjknmwLb49fKz83EYl9pcZD9ZG43mZMFHcJUpcLsCo4bo@nE6i3M3VP5tuDm89Bqv0/1ujfNq0TMoK1KkmhQKQwVKUyYomxClTShQ@2TmFqxXjGZC8sOgdu4iRRkoD7S/UqzPWhj0zWjzAnmJfxVeEX0B "Bash – Try It Online")
## Explanation
Uses Perl `s///`ubstitution operator, but necessitates that `and` is built outside due to the source restriction. To create `and`, the `$s` is set to [`~"\x9e\x91\x9b"`](https://tio.run/##K0gtyjH9/7@gKDOvpE4ppsIyFYgNgThJ6f9/AA) using the raw bytes (hence using `xxd`). I started with [`"\x61\x6e\x64"`](https://tio.run/##K0gtyjH9/7@gKDOvRCmmwswQiFOB2ETp/38A) and tried to look for shorter approaches. I also looked at [`PWQ^"195"`](https://tio.run/##K0gtyjH9/7@gKDOvRCEgPDBOydDSVOn/fwA) and variants of that, and [`v97.110.100`](https://tio.run/##K0gtyjH9/7@gKDOvRKHM0lzP0NBAz9DA4P9/AA), but `~` was shortest. Once that string is created, it's possible to `s///`ubstitute it surrounded by start and end anchors (`^` and `$`) due to the `-040` command-line switch which uses space (ASCII 32, octal 040) as the record separator (which is also stripped off by `-l`) making `$_` equal just the words themselves, with case-`/i`nsensitivity, with the string (`$s`) and the matched string `$&` as required, `/g`lobally within the input.
---
# [Perl 5](https://www.perl.org/) + `-p040l`, 41 bytes
Without using RegEx. Link shows 50 bytes because I'm using the `\xXX` notation. Will fix when I'm not on mobile!
```
$s= ~"\x9e\x91\x9b";$_=lc eq$s?"$s $_ $s $_ $s":$_
```
[Try it online!](https://tio.run/##NcdBCsIwEEbhq/yE2QoV7EKliAfwBoWQmikEh0lMqu3KoxuzcfE@eImz9LVSGfAx43bk1r41mTPZQe7gJ5WLoQKy@GtOZGu9ZVzVcy5RsbIumGOGw@rkAae@7avpMIc3w0cRlzEFkW9MS4ha6i51h05@ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
-(3+1) from Kevin Cruijssen, -1 from ovs, -1 from Neil's Charcoal answer.
```
#εÐl'€ƒQils‚5∍]˜ðý
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f@dzWwxNy1B81rTk2KTAzp/hRwyzTRx29safnHN5weO///75FCo55KalFxfl5CuWpeSUKaflFCokK5Yk52SAJILcUSCYqpGWWpSqk5OfkJBYpJGXmAAA "05AB1E – Try It Online")
## Explanation
```
# Space split
ε Map:
Ð Triplicate
l lowercase
'€ƒQ == "and"?
i If true:
l Lowercase
s‚Äö Paired with original
5‚àç] Extend to 5 items
(Else: return the current item)
Àú Flatten
√∞√Ω Join by spaces
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 102 bytes
```
k=i‚Åøput().split();o=[]
while k:w,*k=k;o+=([w],[x:=w.lower(),w,x,w,x])["\x61\x6e\x64"==x]
pri‚Åøt(*o)
```
[Try it online!](https://tio.run/##FcxBCsIwEIXhfU8RukpqKIgi0jJ3cB@zKDqQktCEJHXi0pN5Fy8S28XHz9u88M7GL6driLVamH@fb1gzF30Kbt46elC6ITM7ZHYg2Vmwoz8AV6SlKgNQ7zxh5EKSLDstVHsvl@MGN@cWoOgmxP06886LWm8Op4Qs5Wl5Mv/CyLLBiGyfNOWH@QM "Python 3.8 (pre-release) – Try It Online")
---
# [Python 3.8](https://docs.python.org/3.8/), ~~106~~ 104 bytes
-2 bytes inspired by [this answer](https://codegolf.stackexchange.com/a/207567/64121) from Luis Mendo.
```
exec('pri‚Åøt(*sum([([x:=w.lower(),w,x,w,x],[w])["\x61\x6e\x64"!=x]for w i\x6e i‚Åøput().split()],[]))')
```
[Try it online!](https://tio.run/##FYxBCsIwFESv8u2miYSCKCJC79B9zCLULwnUJiS/Ji49mXfxIjFZPIZ5MOPfZNx6vPhQCmacWe@D/X2@xPZxezLJZL6OaVhcwsC4SCI3lJBJcdnd8vlQwcqp241ZPVyABLY5aDd@I8aH6Bdbs64U5z0vZVpQR4RIer2De2EAMhgQWk2aZvMH "Python 3.8 (pre-release) – Try It Online")
Deobfuscated Code:
```
pri‚Åøt(*sum([([x:=w.lower(),w,x,w,x],[w])["and"!=x]for w in i‚Åøput().split()],[]))
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~160~~ ~~151~~ 149 bytes
```
q='\141\156\144'
l='=l\141mb\144\141 x:'
exec(f"f{l}x {q} x[0]+((q+x[:5])*2+q+f(x[4:])if' {q} '==x[:5].lower()else f(x[1:]));g{l}f(' '+x+' ')[1:-1]")
```
[Try it online!](https://tio.run/##HYw7DsIwEER7TrFK410sEIZAEeSCC1DRhRT52CGSyccJwghx9mCn2Rm9edr@Mz269jDPg2R3EYu7OJ58xmxlJJMmoGcRQGjgErZSTpWoI/01Pwff4Qcu3WUcceAuTY4Zrfd84BpdGicZNZotDpNyWbemeyuLpMyoIEjCS3Su/TONDBh33F/yeCOyiObeNu2EVvUWa4xu3WeES1vBOL20hnczPaAILL9WUNrA8raKiGj@Aw "Python 3 – Try It Online")
Since [xnor said it would take imagination](https://codegolf.stackexchange.com/questions/207425/and-and-and-and/207446#comment491739_207425) I've gone ahead and done a python answer. It is more of a proof of concept than anything else since I am quite rusty on python golf.
## Explanation
I wrote the pretty straightforward code:
```
q='and'
f=lambda x:x and x[0]+((q+x[:5])*2+q+f(x[4:])if' and '==x[:5].lower()else f(x[1:]))
g=lambda x:f(' '+x+' ')[1:-1]
```
Which would solve the problem if it were not for the character restriction. Then to get around the restriction I used `exec` with escape codes on all the problematic characters.
```
exec("q='\141\156\144';f=l\141mb\144\141 x:x \141\156\144 x[0]+((q+x[:5])*2+q+f(x[4:])if' \141\156\144 '==x[:5].lower()else f(x[1:]));g=l\141mb\144\141 x:f(' '+x+' ')[1:-1]")
```
And since `and` appeared in the original source 3 times, I moved the definition of `q` outside the exec and inserted `q` in those places to save bytes. I also wrote a substitution for `=lambda x:` since it appears twice.
```
q='\141\156\144'
l='=l\141mb\144\141 x:'
exec(f"f{l}x {q} x[0]+((q+x[:5])*2+q+f(x[4:])if' {q} '==x[:5].lower()else f(x[1:]));g{l}f(' '+x+' ')[1:-1]")
```
[Answer]
# Dyalog APL, ~~99~~ ~~95~~ ~~93~~ ~~92~~ 39 bytes
```
(7⍴'\b',⎕ucs 65 78 68)⎕R(15⍴'\l& & ')⍠1
```
[Try it online!](https://tio.run/##TY47TsNAEIZ7TvFX2UQiRYTyaC1SQAGKEpc0a3sWWxl50a4dK2mRUiA5goKeAyDRcAKOshdx1ishKOb1zzcP@cTjbC9ZP3bdcO7ab/GQiEt3eq9Ti9kU8wVmi5Gv18PJNLR5gAHEyLUfk06546trT@7l2bWfvvvzdeWOb57erK@9j29uN52CiPXeIiozrOrDgcmKCy/KMgsxul/C596WoV4xSUuwVS/qHRlUORkKTCOrNA9UnBNSo5sM7BnrmcIi@d0ZDvYDUVj8F/8/cGd6mYzVJRoqKyhtIP0N3gZW6bqfgip2hEwzS4OkYBZn "APL (Dyalog Unicode) – Try It Online")
Golfed ... a lot of bytes thanks to @Ad√°m
[Answer]
# [PHP](https://php.net/), 97 bytes
Saved 17 bytes thanks to Dom Hastings
```
<?php $b=chr(97);$c=XWT^"990";echo(preg_repl.$b.ce)("/\b$c\b/i","$c \\0 $c \\0 $c",${$b.rgv}[1]);
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0BBJck2OaNIw9Jc01ol2TYiPCROydLSQMk6NTkjX6OgKDU9vii1IEdPJUkvOVVTQ0k/JkklOSZJP1NJR0klWSEmxkABTinpqFQD1RWll9VGG8ZqWv///1/J0c9FITEvBYhdFDLzFEoyUhWSQHwQoQQA "PHP – Try It Online")
---
# [PHP](https://php.net/), 114 bytes
```
<?php $b=chr(97);$c=$b.chr(110).chr(100);$e=preg_repl.$b.ce;echo$e("/\b($c)\b/i","$c \\1 $c \\1 $c",${$b.rgv}[1]);
```
[Try it online!](https://tio.run/##PYpNCsIwEIWvMgyzSKC0yUokFhG69gJGxMShKUgdgrgRzx4TBBfv53s8SVLKbi9JgMIYU1bbjXYURwp9I2uN/hVj6s6jZJ4vmeXetwc7julBrHDwQVHUPgwLdkgRvLfwD@zoXf95fn1O9qxdKQUPxwmu661qgmWFZ2IIjZvhFw "PHP – Try It Online")
# Ungolfed
```
<?php
$b = chr(97);
$c = $b . chr(110) . chr(100);
$e = "preg_repl{$b}ce";
echo $e("/\b($c)\b/i", "$c \\1 $c \\1 $c", ${$b . "rgv"}[1]);
```
`chr(97)` resolves to 'a', `chr(110)` to 'n', and `chr(100)` to 'd'.
PHP allows you to define a variable as a string, then execute a function with the standard function syntax. e.g.:
```
$d = 'print';
$d('hello world'); // Parsed as print('hello world');
```
Using this I am able to execute the preg\_repl**a**ce function by interpolating the `chr(97)` from earlier and run a case insensitive regex to perform the necessary operation.
The final issue comes from input variables in PHP being e.g. `$argv[1]` - and they're always **a**rgv. Fortunately PHP has a variable variable syntax, so `${'argv'}` is the same as `$argv` - so I simply concatontate my `chr(97)` to 'rgv' and execute in variable variable syntax.
Finally, a few bytes are saved by using PHP's assumptions. An unquoted string is how to reference a constant in PHP. Undefined constants are assumed to be their own name.
[Answer]
# JavaScript (ES6), ~~ 76 74 ~~ 73 bytes
*Saved 1 byte thanks to @tsh*
```
s=>s.repl\u0061ce(/\b\x61\x6e\x64\b/gi,(x=(y='\x61\x6e\x64')+' $& ')+x+y)
```
[Try it online!](https://tio.run/##dU/JasNADL33K0QotU3aLFByc8GQa0IOOfoyntHEbsUojLzm592xLy3FPTwEeouePlWrRPvqXr85NjjadJT0QzYe75Q3u91hrzHe5kXeH/YBGPCeF9tb9Rr3aTyk0W8iStYRPL9AmP16SEbNTphwQ3yLbby68iCQOQOX5vEglFWSPP2RKGcWttn5CIEJOC6wF0IlCFJPEm7RQ12ix9nRqVqXC55riaA9dwYoOCQ4KoFi@fpcewrL5go/8/83Tn4SoRd20KGrwbIHFdrQ1@y03EwZYKsWwTCR8lBURCFq/AY "JavaScript (Node.js) – Try It Online")
Without escaped characters, this simply reads as:
```
s=>s.replace(/\band\b/gi,(x=(y='and')+' $& ')+x+y)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~70~~ \$\cdots\$ ~~56~~ 52 bytes
Saved 4 bytes thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)!!!
```
s/\b\x61\x6e\x64\b/& \0 & \0 &/Ig;s/&/\x61\x6e\x64/g
```
[Try it online!](https://tio.run/##TY29DsIwDIT3PIUnNhSQEAtTpS4MoA4dsySN@yOiRIrTFvryIQlCMJwt3Z0/E@r9YOcYiQslnudjEiadhOI7EAf4DH4dLsR3/L/Bhxhb9yKorIZm3jaDxKTVrLrXkHZSzRqDkhAoZMMt6CGM6LHkqwzdyNoRofNu1WBSTimfCFTmFHguVgX2299nN58t9OQsrGgD9M6DTFzzKL3ezfkC@mlB0M4Y6UFNxrwB "sed – Try It Online")
Swaps all occurances of `and` (which is written in escaped hex as `\x61\x6e\x64`) in any case surrounded by word boundaries (`\b`) with: a ampersand (`&`), followed by that occurance, another ampersand, that occurance again, and finally a third ampersand. Since all input only contains spaces and letters, any ampersands present are there because of those swaps. So they're all replaced with `and` (`\x61\x6e\x64`) to complete the process.
[Answer]
## Excel, ~~437~~ 435
Closing quotes and parens already discounted. It's not pretty, but I found some surprising optimizations.
### Setup
Input: `C1`
Cells `B1` to `B9` (One cell per row).
```
[SPACE]
=B1&LEFT(RIGHT(TEXT(,"[$-33]MMMM"),4),3)&B1
=UPPER(B2)
=LEFT(B2,2)&RIGHT(B3,3)
=LEFT(B2,3)&RIGHT(B3,2)
=LEFT(B3,3)&RIGHT(B2,2)
=LEFT(B3,2)&RIGHT(B5,3)
=PROPER(B2)
=LEFT(B2,2)&RIGHT(B6,3)
```
Cells `C2` to `C9`
```
=SUBSTITUTE(B1&C1&B1,B2,REPT(B2,5))
=SUBSTITUTE(C2,B3,B2&B3&B2&B3&B2)
=SUBSTITUTE(C3,B4,B2&B4&B2&B4&B2)
=SUBSTITUTE(C4,B5,B2&B5&B2&B5&B2)
=SUBSTITUTE(C5,B6,B2&B6&B2&B6&B2)
=SUBSTITUTE(C6,B7,B2&B7&B2&B7&B2)
=SUBSTITUTE(C7,B8,B2&B8&B2&B8&B2)
=TRIM(SUBSTITUTE(C8,B9,B2&B9&B2&B9&B2))
```
...where C9 is the final output.
### How It Works
* B2 - `TEXT()` creates the text "Phando" (EN January) in [Venda](https://en.wikipedia.org/wiki/Venda_language), an official language of South Africa. The rest of it extracts the "and" from it and surrounds it with spaces.
* The rest of the Cells in Column B simply enumerate all possible capitalizations of "and".
* C2 - We first surround the input with spaces so edge handling is easier. Then replace "and" with 5 of itself.
* After this, the rest of the cells in column C replace occurrences of the corresponding capitalization permutation in column B with the sandwiched string.
* In the last cell, trim off the surrounding spaces.
### Note
* Nesting the C's gives us no advantage because we trade off the equals sign for the auto-closed parens.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Work in progress
```
r`%ß@%b`È3ÇXvÃqXû5}'i
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cmAl30AlYmDIM8dYdsNxWPs1fSdp&input=IlRveXMgQW5kIFB1enpsZXMi)
## Original (w/ `-S` flag)
```
¸cÈv ¶`ß@`Å?5ogX¸iXv:X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uGPIdiC2YN9AYMU/NW9nWLhpWHY6WA&input=IlRveXMgQW5kIFB1enpsZXMi)
```
¸cÈv ¶`ß@`Å?5ogX¸iXv:X :Implicit input of string
¸ :Split on spaces
c :Map then flatten
È :Passing each X through the following function
v : Lowercase
¶ : Test for equality with
`ß@` : The compressed string "band" ("and" compressed is also 2 bytes but includes the "d")
√Ö : Slice off the first character
? : If true
5o : Range [0,5)
g : Index (0-based) each into
X¸ : Split X on spaces, converting it to a single element array
i : Prepend
Xv : Lowercase X
:X : Else return X
:Implicit output joined by spaces
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 23 22 21 ~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Note: `…ó` is not a `d`!
```
Ḳ,@ṁ5Kɗ€Œlẹ¥¦“2ɼ»Ṗ¤K
```
A monadic Link accepting a list of characters which yields a list of characters.
**[Try it online!](https://tio.run/##AVIArf9qZWxsef//4biyLEDhuYE1S8mX4oKsxZJs4bq5wqXCpuKAnDLJvMK74bmWwqRL////UGxlYXNlIHN0YW5kIG92ZXIgdGhlcmUgYU5kIHdhdGNo "Jelly – Try It Online")**
### How?
Note: `and` is not in Jelly's dictionary, and its compression is `“¡ÞṄɱ»` which we could use, but I decided to go with `“2ɼ»Ṗ¤` which is also five bytes.
```
Ḳ,@ṁ5Kɗ€Œlẹ¥¦“2ɼ»Ṗ¤K - Main Link: list of characters, S
·∏≤ - split (S) at spaces -> list of words
- (implicitly set the right argument to:)
¤ - nilad followed by link(s) as a nilad:
“2ɼ» - compression of "andy"
·πñ - pop -> "and" -
¦ - sparse application...
¥ - ...indices: last links as a dyad - f(words, "and")
Œl - lower-case (all the words)
·∫π - indices of ("and" in the lower-cased words)
ɗ€ - ...action: last three links as a dyad for each - f(word,"and"):
@ - with swapped arguments:
, - pair -> ["and", word]
ṁ5 - mould like five -> ["and", word, "and", word, "and"]
K - join with spaces
K - join with spaces
```
[Answer]
# [Haskell](https://www.haskell.org/), 177 bytes
```
r x|_:z:_<-[x..]=z
(#)=elem.r
f(b:t@(c:e:g:h:s))|u<-b:c:e:g:" ",[b,h]<" !",c#"bB",e#"oO",g#"eE",i<-r<$>"`mc"=b:i++u++i++u++i++f(h:s)
f" "=""
f(b:t)=b:f t
g x|_:y<-f$' ':x++" "=y
```
[Try it online!](https://tio.run/##PY7bCoJAGITvfYrtV0jZ1Qf42Y2Kuq2b7iLMtd11yUN4AJXe3Syhm2EYPmYmS5qnyvNpqkn/jnHEmIfXPopuYnR8NxAqV0VUO9qX2G79FBUazLAJgnfHQ4lLAATYVbLsxoGsgKUuyD0w5UJ1BmZcUEdgloc19zZwL1IQEi2lHaV/1f631NFzkwBY5oIZ06R1zO/ZwEPtrckae0q/1DAViS3Fq7Zl6xlITg9yqYaG7GbTZrY0DUnKA0wf "Haskell – Try It Online")
## Explanation
`r` takes a character and returns the next character in ASCII order. That is to say its successor.
Then we use this to make `(#)` which takes a character and a list and checks if that character's successor is in the list.
Then we use that to make `f`.
Many of the functions I would really like to use from Haskell are missing.
# More boring version, 174 bytes
```
(#)=elem
f(b:t@(c:e:g:h:s))|u<-b:c:e:g:" ",[b,h]<" !",c#"\65\97",e#"\78\110",g#"\68\100",i<-"\97\110\100"=b:i++u++i++u++i++f(h:s)
f" "=""
f(b:t)=b:f t
g x|_:y<-f$' ':x++" "=y
```
[Try it online!](https://tio.run/##PY7BCoJAEIbvPsU2Cim7gh7KGhQKOnfqlhGr7a5LapEKCr67rQldho9vfmb@gjdPUZbT5NpeIkpRWdLNsD24OQpUWGDjeWMX@xkuAgiwa8aKWwxkBSy3Id1u0n0ETBiMdmkYBsDUrA0HhnXsgwnMi59IMtSUdpT@p3TnN5Y0txOApYBnYpK0liL9eMch9qWzJmvsKZ1Tw1RxXSfvj65bRwE/P8jlNTTkaKAtdK0awusTTF8 "Haskell – Try It Online")
This version forgoes using `r` to generate forbidden characters and instead escapes them. Boring but saves 3 bytes.
[Answer]
# Scala 2.12, ~~126~~ 116 bytes
```
"(?i)(\\b\u0061\u006e\u0064\\b)".r repl\u0061ce\u0041llI\u006e(_,m=>{v\u0061l x=m+""toLowerC\u0061se;s"$x $m "*2+x})
```
You do need to assign that function to a variable of type `String => String`, though, and enable postfix operators (to save 1 byte). This adds 21 more characters.
```
def f:String=>String="(?i)(\\b\u0061\u006e\u0064\\b)".r repl\u0061ce\u0041llI\u006e(_,m=>{v\u0061l x=m group 0 toLowerC\u0061se;s"$x $m $x $m $x"})
```
After Scala 2.13, you need to use backticks around variable names when using unicode escapes, hence Scala 2.12.2.
[Try it online](https://scalafiddle.io/sf/HmwMPKD/0)
Prettier version
```
val f: String => String = s =>
raw"(?i)(\band\b)".r.replaceAllIn(s,
m => {
val x = m.group(0).toLowerCase
s"$x $m $x $m $x"
})
```
[Answer]
# GNU sed, 38 bytes
```
s/\<\c!\c.\c$\>/\L&\E & \L&\E & \L&/Ig
```
"and" is written escaped as `\c!\c.\c$`. `\cx` means take the character `x`, convert it to upper case if it is a lower case letter, and then flip bit 6. The surrounding `\<` and `\>` mean word boundaries. `&` corresponds to the matched string. `\L` switches to lowercase, and `\E` switches back. The `I` modifier means ignore case when matching. The `g` modifier means replace all matches, not just the first.
[Try it online!](https://tio.run/##TY3NCsIwEITvfYoVpDftC4hQ0IOg0kOPuaTJ9geXBLJpi335mARED8vAzOw3jPowmDkErsRJqJ1QR6H24lyJeymuUMKfVrchhNa@GWqjoZm3jZALaXRRPy8QNd6laAglI7BPhl3QgR/RYc5X6dVYtCOCcnbVQDHnmE8MXeJkeCrWGfbT79jDJQsdWwMrGg@9dSAjl16519s5fUA/LQjaEkkH3UT0AQ "sed – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
≔“1“$K”η⪫E⪪S ⎇⁼↧ιη⪫⟦ηιηιη⟧ ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RHDXMMgVjF@1HD3HPbH61a/X7P0kerVr3fs1nhUV/7o8Y9j9qWn9sJlnk0f9m57SA2mD9/ucK5nQr//4fkVxYrOOalKASUVlXlpBZz/ddNBAA "Charcoal – Try It Online") No verbose mode because it won't "compress" the string for me. Explanation:
```
≔“1“$K”η
```
Assign the compressed string `and` to a variable. (None of the various ways of compressing the string `and` uses a banned letter; this is just the shortest option, after banning the uncompressed string.)
```
S Input string
‚™™ Split on literal space
E Map over words
ι Current word
‚Üß Lowercased
⁼ Equals
η "and"
‚éá If true then
⟦ηιηιη⟧ Alternate lowercase and original word
‚™´ Join with literal space
ι Otherwise the original word
‚™´ Join everything with literal space
Implicitly print
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-s`, 34 bytes
```
Y Jz@[i13 3]{(gPEyLC@gQy?,5o)}Mq^s
```
[Try it online!](https://tio.run/##K8gs@P8/UsGryiE609BYwTi2WiM9wLXSx9khPbDSXsc0X7PWtzCu@P//4JLEvBSFRL8UhfLEkuSM/7rFAA "Pip – Try It Online")
### Explanation
Non-regex solution taking advantage of the "letters and spaces only" rule. Partially inspired by [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/207432/16766).
```
Y Jz@[i13 3]{(gPEyLC@gQy?,5o)}Mq^s
z is lowercase alphabet; i is 0; o is 1 (implicit)
z@[i13 3] Get the lowercase letters at indices 0, 13, and 3
J Join them into the string "and"
Y Yank that into the variable y
q Read a line of input from stdin
^s Split on spaces
{ }M Map this function:
g The list of arguments: [word]
PEy with y prepended: ["and" word]
( ) Index this list with the following index:
? If
@g the first argument
LC lowercased
Qy equals y
,5 then range(5)
o else 1
```
Here's what the indexing does: If the `word` we're processing is some case-variant of `"and"`, we get the first five elements of the list `["and" word]`. With cyclic indexing, this amounts to `["and" word "and" word "and"]`. If the word is some other word, we get the element at index 1, which is just `word`.
The result is a (possibly nested) list, which the `-s` flag joins on spaces and then autoprints. An example run:
```
q "Stand aNd watch"
q^s ["Stand" "aNd" "" "watch"]
{ }Mq^s ["Stand" ["and" "aNd" "and" "aNd" "and"] "" "watch"]
Output: Stand and aNd and aNd and watch
```
---
## Pip, 34-bytes (no flags)
```
Y Jz@[i13 3]qR-:yWR`\b`yWR` & `WRy
```
[Try it online!](https://tio.run/##K8gs@P8/UsGryiE609BYwTi2MEjXqjI8KCEmKQFEKagpJIQHVf7/H1ySmJeikOiXolCeWJKcAQA "Pip – Try It Online")
### Explanation
My initial solution using regex:
```
Y Jz@[i13 3]qR-:yWR`\b`yWR` & `WRy
z is lowercase alphabet; i is 0 (implicit)
z@[i13 3] Get the lowercase letters at indices 0, 13, and 3
J Join them into the string "and"
Y Yank that into the variable y
q Read a line of input from stdin
R In that string, replace
y the string "and"
WR`\b` wrapped in the regex `\b`: `\band\b`
-: with the case-insensitive flag set: `(?i)\band\b`
with
y the string "and"
WR` & ` wrapped in the regex ` & `: ` & and & `
WRy wrapped in the string "and": `and & and & and`
(where & in replacement context stands for the
full match)
Autoprint (implicit)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 32‚Äâ26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
å╔é╩⌐╬²ßxæ╬:Ö5ò▌@ Θ5YS₧Ñπε
```
[Run and debug it](https://staxlang.xyz/#p=86c982caa9cefde17891ce3a993595dd4020e93559539ea5e3ee&i=and+-+AnD+-+andy%27s+band)
I knew packed stax mutation was good for something.
Saved 6 bytes thanks to an anonymous donor.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~116~~ 112 bytes
*-4 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203)!*
```
Stri\.6egRepl\.61ce[a:Regul\.61rExpressio\.6e["(?i)\\b"<>#<>"\\b"]:>Stri\.6egRiffle@{#,a,#,a,#}]&@"\.61\.6e\.64"
```
[Try it online!](https://tio.run/##RY/BTsMwDIbvPIWVSQhQBUJCHMYorTSOoGrstu6Qts4akSWTk66wac9ekmyiByu/7c@/nS13LW65kzUfBLwOX45kef@MmwXulBePNa74dIGbLmb0/rMjtFaaAK3YzZu8LcuKzdLJLGVBrafp6CGFUJgdJwlPYpzW1xkLPqHt44kNBUntsjsBDxkcrwCALc2vhVw3UHSHg0LLkljmurmo/HMOPvMxZwnEUqGQWwTrQt3skcB/izBiPXd1exldtgg1mb4B5SnrKWmhitYwLg9TeVwwvv/HnLkPCh0kazT0qB0IQ8D9LvUdcWG6MAhC7hEaoxQnqKRS7PQy/AE "Wolfram Language (Mathematica) – Try It Online") An expression that evaluates to a function. Uses the standard regex `(?i)\band\b`. For reference, the shortest equivalent function that doesn't use a regex is 118 bytes:
```
Stri\.6egRepl\.61ce[a=WordBou\.6ed\.61ry;a~~b:#~~a:>Stri\.6egRiffle@{#,b,#,b,#},Ig\.6eoreC\.61se->1>0]&@"\.61\.6e\.64"
```
[Answer]
# [Lua](https://www.lua.org/), 151 bytes
```
b="\97\110\100"_G["lo\97\100"]('pri\110t(\97rg[1]:gsub("%w+",fu\110ctio\110(s)retur\110 s:lower()==b '..b..' (b.." "..s.." "):rep(2)..b e\110\100))')()
```
[Try it online!](https://tio.run/##NY5PC8IgGMa/yosQKoXMLtFgh06d@gTbCG0uRqLjVfPjmxt0ef79Lo9NqhTdkeF6GaRsBtk05HnvifX7UtvI6IrLBiOrG757ObbvkDQjh3wkpzlt7BUXvzkLHE1MuGUIrfXZIONdp4EKoYWgwKoSIEKE3XmLZmVnXimY/wXOKWe8lPJAuLnJYPAOsnERZo@gICv7AeWmWlNVBfPyNTB5axWCXqz9AQ "Lua – Try It Online")
### How It Works
`b` is a string which is equal to "and" via ASCII escape codes.
`_G` in Lua is the "global environment table", the data structure containing all global variables. We can index this with a string, which can contain ASCII codes for the forbidden letters.
`load()` returns a function from the string passed to it (which we immediately call). Again, ASCII codes are used here for forbidden characters.
`arg` is the command-line arguments table
`gsub()` is a Global SUBstitution function, it takes a pattern (in this case a sequence of 1 or more alphanumeric characters) and replaces it according to the second parameter, in this case an anonymous function which it calls for every match.
`and` is a boolean operator which return the right-hand-side of the operation or `false`.
`rep()` is a string repetition function.
### Readable Version
```
-- Match Every Word, Replacing Any "and"s
print(arg[1]:gsub("%w+",function(s)
return s:lower() == "and" and ("and "..s.." "):rep(2).."and"
end))
```
] |
[Question]
[
## Generator functions
*This gives the context for why this challenge came to life. Feel free to ignore.*
Generator functions are a nice way of encoding the solution to a problem of combinatorics. You just write some polynomials, multiply them and then your solution is the coefficient of one of the terms.
For example, how many bouquets of 10 flowers can you make if you want to use 3 or more dandelions, really want to use an even number of lilies and cannot afford more than 5 roses? Easy, just find the coefficient of `x^10` in
$$(x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^{10})\times(1 + x^2 + x^4 + x^6 + x^8 + x^{10})\times(1 + x + x^2 + x^3 + x^4 + x^5)$$
## Task
Compute a specific coefficient from a product of polynomials.
## Example
If `k = 3` and the product given is `"(1 + 3x + 5x^2)(5 + 3x + 2x^2)"` then we have
$$(1 + 3x + 5x^2)(5 + 3x + 2x^2) = (5 + 3x + 2x^2) + (15x + 9x^2 + 6x^3) + (25x^2 + 15x^3 + 10x^4) = 5 + 18x + 36x^2 + 21x^3 + 10x^4$$
And because `k = 3` we get 21.
## Input
You receive an integer `k` and several polynomials. `k` is always a non-negative integer, and so are the coefficients and the exponents in the input polynomials.
`k` may be larger than the combined degree of all the input polynomials.
The input polynomials can be in any sensible format. A few suggestions come to mind:
* A string, like `"(1 + 3x + 5x^2)(5 + 3x + 2x^2)"`
* A list of strings, like `["1 + 3x + 5x^2", "5 + 3x + 2x^2"]`
* A list of lists of coefficients where index encodes exponent, like `[[1, 3, 5], [5, 3, 2]]`
* A list of lists of `(coefficient, exponent)` pairs, like `[[(1, 0), (3, 1), (5, 2)], [(5, 0), (3, 1), (2, 2)]]`
An input format must be sensible AND completely unambiguous over the input space.
## Test cases
```
0, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 5
1, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 18
2, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 36
3, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 21
4, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 10
5, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 0
6, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 8
7, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
8, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 32
9, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
17, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
18, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 160
19, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
20, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 384
```
[Answer]
# [J](http://jsoftware.com/), ~~21~~ ~~19~~ 18 bytes
```
{ ::0[:+//.@(*/)/>
```
[Try it online!](https://tio.run/##rZHBCsIwEETvfsXgpVZts5u0MaYoguDJk1ePYhEvfoAfH5O0SoUcQ9gw2bfMDuTp5nXRY2dRYA2C9VXVOF7OJ/eGtXS1KyHqw2IpSrF35ex@e7zQogqDPRjKPzpfCnJgbALkL/xjSgcmk0xyYCrJmAJrkiyiNoliEh0R@a2EpvPXKKMimG4Uk9avMxzWk02bbHZKBj@TN942mx3raMj5AirTxO@nDI7uAw "J – Try It Online")
*-1 byte thanks to FrownyFrog*
J has a nice geometric idiom for multiplying polynomials, which we
represent as lists of coefficients, with explicit zeroes where needed:
```
+//.@(*/)
```
Let's see how this works using the example:
```
1 3 5 +//.@(*/) 5 3 2
```
First it creates a multiplication table `*/`:
```
5 3 2
15 9 6
25 15 10
```
And `@:` then it computes the sums along each diagonal `+//.` using the Oblique `/.` adverb:
[](https://i.stack.imgur.com/XEQMf.png)
This works because moving down a diagonal is equivalent to decrementing the
power of one *x* while incrementing the power of another, meaning that the
numbers along a diagonal represent all the components of some a factor `x^n`
for some `n`.
The rest of the solution is just mechanics for the problem as stated:
```
{ ::0[: <polynomial idiom> />
```
Since we can have an arbitrary number of polynomials, we represent them as a list of boxes (each box containing one polynomial) and take that as the right arg. The left arg is the index we want.
Now `{ ::0 ...` is a dyadic hook asking for the index specified by the left arg, after transforming the right arg by everything in `...`. And, if you can't find the index, return 0 `::0`.
Finally `[: <polynomial idiom> />` says to first unbox `>` the right arg lists, filling any missing coefficients with 0. Then reduce `/` that list using the polynomial multiplication idiom.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ 15 bytes
```
Y:iWB1G"Y+]2GQ)
```
Input is a cell array of numerical vectors with the polynomial coefficients, followed by an integer (`k`).
[Try it online!](https://tio.run/##y00syfn/P9IqM9zJ0F0pUjvWyD1Q8///6mhDBWMF01iFaFMgbRRby2UAAA) Or [verify all test cases](https://tio.run/##y00syfmf8D/SKjPcydBdKVI71sg9UPO/S1RFyP/qaEMFYwXTWIVoUyBtFFvLZcCFKWaIRcwIi5gxFjETLGKmYDEDBSMgNgGKG8DYCgZgaAEVM0AWUzBAgYZmQIPMqGWQObUMsqCWQZbUMsiQan4zpJrnDKnmOyMDLgA).
### Explanation
Polynomial multiplication is convolution of their coefficients. And
>
> [convolution is the key to success](https://codegolf.stackexchange.com/a/79313/36398)
>
>
>
```
Y: % Implicit input: cell array of numeric vectors. Unbox into its constituents
iWB % Input k. 2 raised to that. Convert to binary. Gives [1 0...0] with k zeros
1G % Push first input (cell array of numeric vectors) again
" % For each. This runs n iterations, where n is the number of polynomials
Y+ % Convolution
] % End
% The first convolution uses one of the polynomials in the input and the
% [1 0...0] vector. This doesn't alter the actual coefficients, but adds k
% zeros. Thus the final product polynomial will contain k zeros after the
% highest-degree nonzero coefficient. This ensures that k doesn't exceed
% the number of existing coefficients
2G % Push second input (k) again
Q % Add 1
) % Index. This retrieves the k-th degree coefficient. Implicit display
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
n%((h:t):l)=h*n%l+(n-1)%(t:l)
0%[]=1
_%_=0
```
[Try it online!](https://tio.run/##VY3BCgIhFEX3fsVbJGjp8BwiYsgvERlkqBxyHtK47NszCQaKw13cs7g3hvVxTalW4kLEocghSRv3xNNBkDaSi9IMQ@68NWzko8WawIJzRqHqW45egcOtKPxy3iT@SoV/mJP3bAkztb38nKnADlx7hhfQRTvsuh69r@/plsJ9rXrK@QM "Haskell – Try It Online")
An infix function taking a number `n` and a lists of lists of coefficients with lowest exponents first.
Here's the key recursive idea. Instead of actually multiplying out the polynomials to get one big polynomial, we only just try to extract the coefficient. Algorithmically, this isn't faster than multiplying out coefficient, but in terms of brevity, it saves us from needing to product lists for the intermediate or final product.
When multiply \$p(x)\cdot q(x)\$, we can split up \$p(x)\$ into its constant and remaining terms as \$p(x)=p\_0(x) +x \cdot p\_{\mathrm{rest}}(x)\$. Then, the coefficient of \$x^n\$ in \$p(x)\cdot q(x)\$ can be written as:
$$
\begin{align}
[p(x)\cdot q(x)]\_n &= [(p\_0 +x \cdot p\_{\mathrm{rest}}(x)) \cdot q(x)]\_n \\
&= [p\_0 \cdot q(x)]\_n + [x \cdot p\_{\mathrm{rest}}(x) \cdot q(x)]\_n \\
&= p\_0 \cdot q(x)\_n + [p\_{\mathrm{rest}}(x) \cdot q(x)]\_{n-1} \\
\end{align}
$$
We can continue expanding this out recursively until we get \$p=0\$, where the remaining result is zero. If \$q(x)\$ is itself expressed as a product of polynomials, we continue to extract coefficients from there. The base case is that the empty product is \$1\$, so its \$x^0\$ coefficient is \$1\$ and the rest are zero.
[Answer]
# Mathematica, 20 bytes
A nice benchmark for other answers:
```
Coefficient[#2,x,#]&
```
Takes the symbolic expressions as input.
You can [try it online!](https://tio.run/##rY@xCsMgFEX3foUQKEod8oxaO3TqD3QPChKUOiSF4uDfWwMNuEpd3uU8DhfuauPLrTaGxWaP7vnxdt6HJbgtzgOjiQ76nJ@fUNDPI0UY0AVNqRyRDCNYHMh21Pp0uNDgsgZ3anB5gysaXPlz938JngwnuIISKhlFcAUlQCYDsi669ipSvYpuvYqg2zboNg66rWPjn035Cw)
[Answer]
# [Python](https://docs.python.org/2/), 67 bytes
```
f=lambda n,p,*q:p>[]and(f(n,*q)if q else n==0)*p[0]+f(n-1,p[1:],*q)
```
[Try it online!](https://tio.run/##VY7NCsIwEITP5in22NQVNkFECvEN@gQhh0gTLdRt@nPx6WMsFJRhDvPNHCa91@fIOudoBv@6dx4YE9ZTk27Wee6qWHGJso8wQRiWAGwMyTpZcsfSnRQmqxr33eTWWKuQUBefHYKlPSBtuu6QfiHSn9TFOSHiOANDzzB7foRKK9mIQ5p7XmG71Mr8AQ "Python 2 – Try It Online")
Takes input like `f(3,[1,2,3],[4,5,6])`, with the polynomials as separate arguments. The idea for the recursion if the same as in my [Haskell answer](https://codegolf.stackexchange.com/a/198786/20260). But, since Python doesn't have as nice pattern matching, we need to check for empty lists explicitly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22 17~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-10 bytes by realising I'd implemented convolution - go upvote [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/198788/53748) too, as that was what made me realise this.
```
æc/ṫ‘}Ḣ
```
A dyadic link accepting a list of coefficient lists on the left and the exponent on the right.
**[Try it online!](https://tio.run/##y0rNyan8///wsmT9hztXP2qYUftwx6L///9HRxvqKBjrKJjG6ihEm4KZRrGx/00B "Jelly – Try It Online")** Or see the [test suite](https://tio.run/##y0rNyan8///wsmT9hztXP2qYUftwx6L/h5frP2pa8/9/NBAY6igY6yiYxuooRJuCmUaxQLZBLJcOTklDfJJG@CSN8Uma4JM0hUka6BgBsQlI2gDG0TEAQwuYoAGyoI4BCjQ0AxlnRl3jzKlrnAV1jbOkrnGGVPatIZW9a0hl/xoZxMb@NwMA "Jelly – Try It Online").
### How?
```
æc/ṫ‘}Ḣ - Link: list of lists, Ps; integer, E
/ - reduce (Ps) by:
æc - convolution
} - use right argument (E) for:
‘ - increment -> E+1
ṫ - tail from (1-indexed) index (E+1)
Ḣ - head (if given an empty list yields 0)
```
---
The 17 (without the convolution atom) was:
```
×€Œd§ṙLC${Ṛð/ṫ‘}Ḣ
```
[Answer]
# [Husk](https://github.com/barbuz/Husk/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
!→⁰+→G(mΣ∂Ṫ*)²∞0
```
First Husk answer. This took so much longer to complete than I thought it would. I'm glad there is [a tutorial](https://github.com/barbuz/Husk/wiki/Tutorial) with good explanation of how the input-order and super-numbers work, otherwise I had to give up. I never programmed in Haskell, and maybe I'm just too used to the left-to-right stack-based 05AB1E, but Husk isn't exactly straight-forward due to its strong-typed nature and right-to-left execution (including input-arguments) imho..
But, it works, which is what counts in the end. :)
First input-argument is a list of lists of coefficients where index encodes exponent, like the third input example in the challenge description. Second argument is the coefficient integer \$k\$.
[Try it online.](https://tio.run/##yygtzv7/X/FR26RHjRu0gZS7Ru65xY86mh7uXKWleWjTo455Bv///4@ONtQx0DECYpNYnWgDGFvHAAwtoGIGyGI6BijQ0Cw29r@RAQA)
**Explanation:**
```
² # Use the first argument,
G( ) # and left-reduce it by:
Ṫ # Apply double-vectorized:
* # Multiply
# (This basically results in the multiplication table of the lists)
∂ # Take the diagonals of this multiplication table
m # Map over these diagonal-lists:
Σ # And sum each together
→ # Only leave the last list after the reduce-by
∞0 # Push an infinite list of 0s: [0,0,0,...]
+ # Merge the two lists together
⁰ # Push the second argument `k`
→ # Increase it by 1 (since Husk uses 1-based indexing instead of 0-based)
! # And use it to index into the list we created
# (after which the result is output implicitly)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~139~~ 131 bytes
```
lambda k,L:sum(reduce(lambda a,(i,c):a*c[i],zip(p,L),1)for p in product(*map(range,map(len,L)))if sum(p)==k)
from itertools import*
```
[Try it online!](https://tio.run/##dU9BboMwEDzXr9gbNuwBEyAEib4gP3BBcgm0VgBbDpFoP09t2lT0UK2snRnt7ozNx/yup2Ttq5d1kOPrRcIVz@XtPlLbXe5tR39UiVRhy0oZtkLV@KkMNXhmyFmvLRhQExir3cZMw1EaauX01qFHQze5QcZUD/6sYVV1ZaS3egQ1d3bWeriBGo22c7gaq6YZAsqjwxJlS5MwmnmYeBgQ76W813ae5iwSWVyX5Ol7TyEE1XOA0LuwQnA8YFYjiMyBpK4Z2cYI@XWBCPxl19KlSRndEdeKpSkY3RHXeL40PN9HETkescAT8iPyAvkJk/8igc8UY@Je6nPFD4LxVsVDjPcixn@K5/4n6xc "Python 2 – Try It Online")
Takes as inputs `k` and then polynomials as a list of lists of coefficents `[c0, c1, c2, ...]`. Forms all tuples of indexes into the polynomials that sum to the desired coefficent; and then sums up the products of the corresponding coefficients.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 55 bytes
```
f=(k,[p,...t],s=0)=>p?p.map((n,i)=>s+=f(k-i,t)*n)&&s:!k
```
[Try it online!](https://tio.run/##tZBNCsIwEEb33sJNSXQaktbWKkQPErIotZXamgRTvH4MRcGCiywMwzA/PN7iu9XP2jaP3kyp0pfWuY6jAYQBQsgkwXKK@cmcDbnXBiEFvT/tlndoSHuY8EbhJLHH9eAaraweWzLqK@oQBSEY5FBIEIWfmZQYr5YMC2CyACYPYHYBTBHAlDNDIfO98xz97EDnqt4/@v0DuihW/hDvY4mrWOJDLDGLlgWLFgaLlkZG/2Z2Lw "JavaScript (Node.js) – Try It Online")
The first argument is `k`. The second argument is "a list of lists of coefficients where index encodes exponent", like `[[1, 3, 5], [5, 3, 2]]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 bytes
```
×þŒJ§SƙFƲ¥/ṫ‘}Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8///w9MP7jk7yOrQ8@NhMt2ObDi3Vf7hz9aOGGbUPdyz6/z/aUMdYxzRWJ9oUSBvFgvgGOkZAbAIUM4CxdQzA0AIqZoAspmOAAg3NYv8bGQAA "Jelly – Try It Online")
A dyadic link taking `k` as the left argument and the list of polynomials as a list of lists of coefficients as the right argument. Returns an integer. If `k` could be 1-indexed, `‘}` could be deleted for 13 bytes.
Adapted to use @JonathanAllan’s revised method for dealing with larger `k`; be sure to upvote his (still shorter) answer too!
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
function(P,k)Re(Reduce(function(x,y)convolve(x,y,,"o"),P,!0:k)[k+1])
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNAJ1szKFUjKDWlNDlVAy5coVOpmZyfV5afU5YK4ujoKOUraeoE6CgaWGVrRmdrG8Zq/k/TyMksLtFI1jDVMdYx1NRJ1jACMkw1NXUMNP8DAA "R – Try It Online")
Convolution is the key to success here, too, since it's a port of [Luis' answer](https://codegolf.stackexchange.com/a/198788/67312).
Takes input as a `list()` of vectors `c()` of coefficients in *decreasing* order, because R's convolve documentation says:
>
> Note that the usual definition of convolution of two sequences `x` and `y` is given by `convolve(x, rev(y), type = "o")`.
>
>
>
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
```
f(k,p)=polcoeff(vecprod(p),k)
```
[Try it online!](https://tio.run/##rY/NCoMwEIRfZfGU2Agm/tQe2hcJKYg1RSp1kVDs06erlBZvOeSyszt8zDLYzkN2R@8tewjkZ5zGbuqtZa@@w3m6MeTiwX2LOL6Zg@wCOA9Px7TT0ghwWhkDyeonYNnf5FyA1jkNCQco0oVmlS5XJaD6GWo1jFmhUFCFgkUoWIaCVShYf8HNIS1J6cvuJG1IG7E/SWVNi6y3pGO0pCZa0ilakoxXT8brJ@MVVHmcKMP9Bw "Pari/GP – Try It Online")
[Answer]
# Sledgehammer, 6 bytes
```
⣈⠲⡎⡒⢢⣑
```
Only works in the interactive app (that requires excessive amounts of tinkering to get it to actually decompress the Braille code itself, but it's possible), because of a bug where the console app doesn't call `postprocess` and ends up replacing all occurrences of `#, #1, #2, ##` by `s1, s2, s3, ss1`.
Accepts input as, for example, `{"(1 + 2x1^2 + 4x1^4)(2x1^2 + 4x1^4 + 8x1^8)(4x1^4 + 8x1^8 + 16x1^16)", 20}` - `x1` is the variable the first undefined variable used gets replaced with.
Obtained from the Mathematica code `Coefficient[ToExpression@#, z, #2]` (where `ToExpression` is `eval` and `Coefficient` simply gets the right coefficient, and `z` gets replaced by `x1` as part of the compression).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å»δ*εā_«N(._}øO}θIÅ0«Iè
```
Definitely not the right language to use for this challenge (no builtins for convolution, polynomials, getting all diagonals of a matrix, etc.).. But with some -rather long- workarounds, it still works (although is too slow for the last test cases).
Input as a list of list of coefficients where index encodes exponent, as well as the integer \$k\$ as second input.
Inspired by [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/198795/52210).
-8 bytes by porting two approaches I've used in [my Husk answer](https://codegolf.stackexchange.com/a/198947/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//cOuh3ee2aJ3beqQx/tBqPw29@NrDO/xrz@3wPNxqcGi15@EV//9HRxvqGOuYxupEmwJpo9hYLmMA) or [verify some more test cases (outputs all coefficients without the indexing part)](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w62Hdp/bonVu65HG@EOr/dwON9bWHt7hX3tux3@d/9HR0YY6xjqmsTrRpkDaKDZWRwFdSAfIB0PskgY6IGgSGxsLAA).
**Explanation:**
```
Å» # Left reduce the (implicit) input-list of lists of integers by:
# 1) Calculate the multiplication table of the current two lists:
δ # Apply double-vectorized:
* # Multiply
# 2) Take the sums of each diagonal:
ε # Map each inner list to:
ā # Push a list in the range [1,list-length] (without popping the list itself)
_ # Convert each to 0, so we'll have a list of 0s of the same length
« # Append this list of 0s to the current list
NF # Loop the 0-based map-index amount of times:
Á # And rotate the current list that many times towards the right
}} # End the loop and map
ø # Zip/transpose; swapping rows/columns
# (We now have a list of all diagonals)
O # And take the sum of each inner list
}θ # After the reduce-by is done, pop and push the final resulting list
∞_« # Append an infinite amount of trailing 0s
Iè # And then use the second input to (0-based) index into this list
# (after which the result is output implicitly)
```
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 9 bytes
`#RC*µS«#@`
Input: nonempty list of polynomials (given as coefficient vectors) followed by index of coefficient that should be computed
Does not work if input list is empty
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=I1JDKrVTqyNA&in=KCgxIDAgMiAwIDQpKDAgMCAyIDAgNCAwIDAgMCA4KSgwIDAgMCAwIDQgMCAwIDAgOCAwIDAgMCAwIDAgMCAwIDE2KSkgOA==)
## Explanation
```
# ; read the list of polynomials
R « ; reduce with
C*µS ; polynomial multiplication
C* ; go through the diagonals of the Cartesian product, multiplying the two elements in the pairs
µS ; sum up the diagonals
#@ ; get the specified coefficient
; implicit output
```
---
# Itr, [10 bytes](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=MSNNQyq1U6sjQA==&in=KCgxIDAgMiAwIDQpKDAgMCAyIDAgNCAwIDAgMCA4KSgwIDAgMCAwIDQgMCAwIDAgOCAwIDAgMCAwIDAgMCAwIDE2KSkgOA==)
Also works for empty input list
`1#MC*µS«#@`
Input: list of polynomials (given as coefficient vectors) followed by index of coefficient that should be computed
## Explanation
```
1 ; push 1
# ; read the list of polynomials
M « ; for polynomial in the list
C*µS ; multiply that polynomial with the top stack value
#@ ; get the specified coefficient
; implicit output
```
---
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 39 bytes
```
{0^({.+/'(*/x@'i)@=+/i:!#'x:(x;y)}/y)x}
```
[Try it online!](https://ngn.codeberg.page/k#eJytUD1vwjAU3N+vMI+qtmPAfvlq6og2azaUFWPoQsWGOlRGBH57HVVIjBky2Kd7ujvf89FejRfXldJcJDo0/CSbtdInO5vzYEWoL/KmLzLcADSYBUNBTLEsxKsIPpWieNB0oMiWH6wAGiekCtJxyqyEbJwyJchHvm6gGKc0UD6EwzBCHnwuxROJUAVfSfFEIlAZPJX/KRW8TZBioJogJUvhfZIyNM1ONMVSVMagadZKzRSfXOXgAFpL+7Z5vYv2c8FRO4eSi9m8tcYevn6+fxlJANHWm7qTVqFDdLwdbIf2JXqcxQXKeRx1wyTpFbKo6GBjr832lVSvk3Nd23q3OtteGd9s61m64+QH/173JNDjOrHSSc4xRC/GoujCLVIpIqc9X8azAejuzB1XnDk1FJLwB5dg6N0=)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
≔⟦E²ι⟧ζFη«≔⟦⟧υFιFζ⊞υEκ⎇ν×μ§λ¹⁺μ§λ⁰≔υζ»I∨ΣEΦυ⁼§ι⁰θ⊟ι⁰
```
[Try it online!](https://tio.run/##XU/BasMwDD03X6GjDBo0oZRCTmVssMNYYLuZHEyXNWaO09rx2Dr27Z6U0kGng95DT7wn7XoTdqNxOW9jtHuP@tEcsCKwqiU4qbp4GwNgr@C7WFxWWEmsLGbJKpjxpKBJscdEIBbvBC9d8CZ8oWdqhy7iQLCdHvxr94mOoFSKoHHp/3yppOq/uHS@46dogvUT3po44VPA5zSgBN1bN3VBtu6OybiIFysrVgTHOWY88KHCxL3OWVdLAq0195Lf0fxxJbgiWLVCrieMG4LNWbmaMJZrNlm3XPnmw/0C "Charcoal – Try It Online") Link is to verbose version of code. Takes input using the last suggestion but with the exponent first, then the coefficient. Explanation:
```
≔⟦E²ι⟧ζ
```
Initialise a variable to the polynomial `1`.
```
Fη«
```
Loop over the input polynomials.
```
≔⟦⟧υ
```
Accumulate terms in a temporary variable.
```
FιFζ
```
Loop over the Cartesian product of both sets of terms.
```
⊞υEκ⎇ν×μ§λ¹⁺μ§λ⁰
```
Multiply the coefficients and add the exponents.
```
≔υζ
```
Move the resulting terms back to the original variable. (Charcoal doesn't have any flattening operators, and this is the golfiest way of flattening manually.)
```
»I∨ΣEΦυ⁼§ι⁰θ⊟ι⁰
```
Filter for the terms with the desired exponent and sum the coefficients, unless there weren't any, in which case the result is `0`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
⟨∋ᵐ{tᵐ+}⟩ᶠhᵐ²×ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FY86uoGs6hIgoV37aP7Kh9sWZADZhzYdng4S@v8/WiEaCAx1DGJ1oo11DIGkqY5RbKwOUNgUSdAIJAgUNQDLkKDBkFQNRqRqMCZVgwmpGkxRNIBEdaJNdEwgGhBcnWgLHQuIIIKrE21opmNoBjbHjErmmFPJHAsqmWNJJXMMqeUxQ2r5zJBaXjMyiFWIBQA "Brachylog – Try It Online")
Takes input as a list of lists of `[coefficient, exponent]` pairs, paired with `k`. Could be trivially modified to accept index-as-exponent coefficient lists by replacing `∋` with `i`, which is in fact what I did originally before I made an error writing out the test cases and switched for my own convenience.
```
⟨ ⟩ Call the first element of the input L and the last element k.
ᶠ Find every
∋ selection of a [coefficient, exponent] pair
ᵐ from each polynomial in L
{ } such that k is
+ the sum of
tᵐ the exponents.
hᵐ² Extract the coefficients from each selection,
×ᵐ multiply the coefficients extracted from each selection,
+ and output the sum of the products.
```
[`{⟨∋ᵐ{tᵐ+}⟩hᵐ×}ᶠ+`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/rR/BWPOrqBzOoSIKFd@2j@ygwg4/D02ofbFmj//x@tEA0EhjoGsTrRxjqGQNJUxyg2VgcobIokaAQSBIoagGVI0GBIqgYjUjUYk6rBhFQNpigaQKI60SY6JhANCK5OtIWOBUQQwdWJNjTTMTQDm2NGJXPMqWSOBZXMsaSSOYbU8pghtXxmSC2vGRnEKsQCAA "Brachylog – Try It Online") is an equally valid solution at the same length, but I'm not sure I remember ever superscripting `ᵐ` before this, so I'm just going with the version that does that.
] |
[Question]
[
The unique-disjointness matrix ( UDISJ(n) ) is a matrix on all pairs of subsets of `{1...,n}` with entries $$ U\_{(A,B)}=\begin{cases}
0, ~ if ~ |A\cap B|=1\\
1, ~ otherwise
\end{cases} $$
Or a bit less mathematical, it is the 2n times 2n matrix with a `0` in all entries where both indices have exactly one common `1` bit in their binary representation and a `1` in all other entries.
## Example:
```
0 1 10 11 100 101 110 111
_______________________________
0 | 1 1 1 1 1 1 1 1
1 | 1 0 1 0 1 0 1 0
10 | 1 1 0 0 1 1 0 0
11 | 1 0 0 1 1 0 0 1
100 | 1 1 1 1 0 0 0 0
101 | 1 0 1 0 0 1 0 1
110 | 1 1 0 0 0 0 1 1
111 | 1 0 0 1 0 1 1 1
```
Write a program or function that takes an integer `n` as input and outputs the corresponding \$2^n \times 2^n\$ matrix.
Rules:
* The values in the matrix can either be 0 / 1 (as numbers) or truthy/falsey
* You are **not** allowed to permute the rows/columns of the matrix
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins
* Your solution only needs to handle `n` between `2` and `10` (inclusive)
First 4 elements:
```
n=1:
1 1
1
n=2:
1 1 1 1
1 1
1 1
1 1
n=3:
1 1 1 1 1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1 1
n=4:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
```
[Answer]
# [Python](https://www.python.org), 72 bytes
```
lambda m:(q:=range(2**m))and(((i&j).bit_count()!=1for i in q)for j in q)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3PXISc5NSEhVyrTQKrWyLEvPSUzWMtLRyNTUT81I0NDQy1bI09ZIyS-KT80vzSjQ0FW0N0_KLFDIVMvMUCjVBzCwIE2re64KiTKA69Zg8db2s_Mw8DXUFOMNQPTorFq4lUxNuUJqGoaamJhd5Wo3I12pMvlYToFaIlxcsgNAA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
o<ÝDδ&b1ö≠
```
Outputs as a matrix with `1`s and `0`s.
Port of [*@mousetail*'s Python answer](https://codegolf.stackexchange.com/a/263366/52210), so make sure to upvote that answer as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/3@bwXJdzW9SSDA9ve9S54P9/YwA) or [verify the first 5 test cases](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO@nw6XkX1oC4/3Ptzk81@XcFrUkw8PbHnUu@G/LpRRQlFpSUqlbUJSZV5KaopAPU61zaLfB4Q1WOoe22f8HAA).
**Explanation:**
```
o # Push 2 to the power the (implicit) input-list
<√ù # Pop and push a list in the range [0,2**input)
Dδ& # Create a bitwise-AND table of it:
D # Duplicate the list
δ # Pop both lists and apply double-vectorized:
& # Bitwise-AND
b # Then convert each inner value to a binary-string
1ö # Vectorized-sum its digits by converting from base-1 to a base-10 integer
≠ # Check for each that it's NOT equal to 1 (0 if 1; 1 otherwise)
# (after which the matrix is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
2ṗ«'`§’n
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4c7ph1arJxxa/qhhZt7///9NAA "Jelly – Try It Online")
```
(input: n)
2·πó nth Cartesian power of [1, 2]: for example,
[[1,1,1,1], [1,1,1,2], [1,1,2,1], ..., [2,2,2,2]] if n=4
¬´'` self-table by vectorized minimum
§ sum each vector
’ subtract 1
n not equal to… (implicit argument: n)
```
Instead of `0b0011 & 0b0110 = 0b0010` we do `1,1,2,2 ¬´ 1,2,2,1 = 1,1,2,1`.
Instead of checking popcount ≠ 1, we check sum ≠ n+1. `§’n` is shorter than `’§n1`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 66 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.25 bytes
```
E Å:v‚ãèbv·π†ƒã
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiRcqBOnbii49iduG5oMSLIiwi4oGLXFwwXFwgViIsIjMiXQ==)
*-4.75 bytes thanks to TheThonnu*
The footer formats the resulting matrix into a nice grid like the test cases. Remove it for just a list of lists. Outputs inverted numbers (0s for 1s and 1s for 0s).
I somehow managed to generate like 3 other fractals while solving this, including an upside down triangle thing with the bottom off-center.
## Explained
```
EDẊ‹sƛƒ⋏bT₃;ẇ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁣⁤‏⁠⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‏​⁡⁠⁡‌­
ED # ‎⁡Push three copies of n ** 2
Ẋ # ‎⁢Cartesian product of the range [1, n ** 2] and [1, n ** 2]
‹ # ‎⁣with all sublists decremented
s # ‎⁤and sorted
ƛ ; # ‎⁢⁡To each pair
ƒ⋏ # ‎⁢⁢ reduce by bitwise and
bT₃ # ‎⁢⁣ is the length of truthy indices 1?
ẇ # ‎⁢⁤wrap into 2 ** n chunks
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
2R·∫âD»∑·ªå‚Ǩ ǂŪQ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPTJSJUUxJUJBJTg5RCVDOCVCNyVFMSVCQiU4QyVFMiU4MiVBQyVDQSU4MiVFMiU4MSVCQlEmZm9vdGVyPSVDNCVCMSVDMyVCMGolM0IlQzYlOUQnMCVDMyVCMHYmaW5wdXQ9MyZmbGFncz0=)
Outputs a nested list. The footer formats it into the grid. Port of Lynn's Jelly answer.
#### Explanation
```
2R·∫âD»∑·ªå‚Ǩ ǂŪQ # Implicit input
2Rẉ # [1,2] to the cartesian power of the input
DȷỌ # Outer product over minimum with itself
‚Ǩ Ç # Sum each inner list
⁻Q # Decrement, not equal to the input?
# Implicit output
```
Old:
```
OLDȷÆ&ıḃ1ȷcḅ # Implicit input
OL # Push [0..2**n)
DȷÆ& # Outer product over bitwise AND
ıḃ1ȷc # Popcount of each
·∏Ö # Equals one?
# Implicit output
```
[Answer]
# [Python](https://www.python.org), 66 bytes
```
lambda m:(q:=range(2**m))and[[(n:=i&j)>n^n-1for i in q]for j in q]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXISc5NSEhVyrTQKrWyLEvPSUzWMtLRyNTUT81KiozXyrGwz1bI07fLi8nQN0_KLFDIVMvMUCmNBzCwIE2pSFEgoDyQUbahjpGOsYxJrxcVZUJSZV6KhHpOnrpeVn5mnoa4AZxiqRyfl5-doZGkiTMvUhNuRppGnqakN0qkJsWHBAggNAA)
[mousetail's answer](https://codegolf.stackexchange.com/a/263366/20260), but with bit operations instead of `bit_count`. We want to check that `i&j` (which we call `n`) doesn't have exactly one set bit, which means that it's a not power of two. We do this by checking that `n>n^n-1`, which is processed as `n>n^(n-1)`. Let's check that this works in every case:
* If `n` is a power of two, then `n-1` has disjoint bits set to `n` and so their
XOR is greater than `n`.
* If `n` is any other positive value, then `n` and `n-1` share the same leading bit, and the XOR cancels this bit making the result smaller than `n`.
* For `n==0`, the result is `0`, the same as `n`.
Annoyingly Python doesn't let us do the walrus assignment `q:=range(2**m)` in the iterable of a list comprehension, so the code has it assigned beforehand. loopy walt points out a better way to handle the two levels of iteration is using the classic [divmod two-loop trick](https://codegolf.stackexchange.com/a/41217/20260) together with the classic [zip/iter chunker](https://codegolf.stackexchange.com/a/184881/20260).
### 61 bytes
```
lambda m:zip(*2**m*[((n:=j&j>>m)>n^n-1for j in range(4**m))])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY1NCsIwEIXXeoqszExshdYupJAcxLZCi0YTmkkpdaFXcVMQvZO30WDp6n3w_h7v7jZcPI1PLcvXddDx7iPb2jXHmrn8bjoQqRBOFACUS7uySjlUdKA40b5nlhlifU3nE2S_GGKF08g-2BTsIonSaBtlVb5cdL2hAXhJfGO9IeBshoQXjfctWKzmZYMBTUANhLgOzelhHP_6BQ)
[Answer]
# [Arturo](https://arturo-lang.io), ~~57 54~~ 50 bytes
```
$->n[map^2n'x->map^2n=>[0<>^and dec<=<=and&-1x-1]]
```
[Try it!](http://arturo-lang.io/playground?FJPeor)
```
$->n[ ; a function taking an argument n
map^2n'x-> ; map over [1..2^n]; assign current elt to x
map^2n=>[ ; map over [1..2^n]; assign current elt to &
0<> ; is zero not equal to
and&-1x-1 ; bitwise and of current elts minus one
<=<= ; duplicated twice
dec ; minus one
and ; bitwise and
^ ; NOS to the TOS power
] ; end map
] ; end function
```
[Answer]
# [R](https://www.r-project.org/), ~~55~~ 53 bytes
```
function(n)(y=outer(x<-1:2^n-1,x,bitwAnd))^0-y%in%2^x
```
[Try it online!](https://tio.run/##Fcw9CoAwDEDh3VMUQUgwBaOb6OA5xA7@FLpEKJXW09e6Pviez1ZNOttHjuBuAUF45/sJl4c0aR57I5op0e5CXORENJ1@GydNb1KWQtVQ2aKq6F244IBa1cS4cvvXjZjKAfMH "R – Try It Online")
Rather than counting the number of on bits (which is very lengthy in R), tests the equivalent characterization of "equal to a power of 2"; then has to do some reshaping of the vector output of `%in%` to get back to the right shape matrix.
[Answer]
# [Nim](https://nim-lang.org/), 119 bytes
```
import bitops
proc f(n:int)=
let r=0..<1 shl n;for i in r:
var s="";for j in r:s&= $int 1!=popcount i and j
echo s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEEX3PcW3iLQLi10I0prD1NjQKW0mTFI9jJuCeihvYzC4ezx4_P94WprX9b0Esz997jQ7loALBXY-c8IaprAN2VCqDFMfIOpQVecafphgW8MCAllIkwG3TuBVnv_0mLTfKWxjj3qjHDvNS2RCZ68YY9LrgeHT_MsUxzLh_9EX)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
2*Ḷ&þ`B§n1
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//MirhuLYmw75gQsKnbjH/w4dv4oG2Rylq4oG@wrbCtv//Ng "Jelly – Try It Online")
## How it works
```
2*Ḷ&þ`B§n1 - Main link. Takes n on the left
2* - 2 ** n
·∏∂ - [0, 1, ..., 2**n)
þ` - To every pair (a, b) in this range:
& - Bitwise and
B - Convert all to binary
§ - Sums
n1 - Does not equal 1?
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~15~~ 14 bytes
```
mmn1s&VdkQ=^U2
```
[Try it online!](https://tio.run/##K6gsyfiflZSbZZ3roKRgqJSd8j83N8@wWC0sJTvQNi7U6P9/EwA "Pyth – Try It Online")
### Explanation
```
mmn1s&VdkQ=^U2Q # implicitly add Q
# implicitly assign Q = eval(input())
=^U2Q # Q = repeated cartesian product of [0,1] Q times
m Q # map lambda d over range(Q)
m Q # map lambda k over range(Q)
&Vdk # d & k, vectorized
s # sum bits
n1 # != 1
```
[Answer]
# [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 45 bytes 22 ‘bytes’
```
{1‚â†+¬¥¬®‚àß‚åúÀú‚•ä‚àæ‚åú‚çü(ùï©-1)Àú‚Üï2}
```
I think the following is slightly more elegant, and it's the same number of characters but, alas, more bytes.
```
{1‚â†+¬¥‚àò‚àß‚åúÀú‚•ä(‚Üï2)‚àæ‚åú‚çüùï©‚ãà‚ü®‚ü©}
```
We operate only on bit-strings, rather than integers. `‚•ä‚åú‚çü(ùï©-1)Àú‚Üï2` gives us the list of binary strings of length `ùï©`, which is then anded into a table, and summed: `+¬¥‚àò‚àß‚åúÀú`. We then take only the `1‚â†` entries.
[Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwYKlpSVpuhY3TR81LArOyC-vNnzUuUD70JZDKx51LH_UM-f0nEdLux517AMyH_XO1_gwd-pKXUNNoGjbVKNaY4hmqBkwswA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72 56~~ 54 bytes
```
->n{(w=0...1<<n).map{|i|w.map{|j|a=i&j;(a&a-1)**a>0}}}
```
[Try it online!](https://tio.run/##JY5BDoIwFAX3nuIlJgQMIhhXaPUgxsUXaCyWlpQ2SChnRwKrN8mbxRj3HmbO5uNdjWHP0iRJsttNRUlD7eiF7zeoPTER1NeQAjpm0eFA93SapnlfkJTgThVWaBXD0reCdrZ1FtSBcC5BxtAAzWGNq7oTJ9lVy6VKcG0aspBCVbB63Ri9sJ9VZRlyrDZLsePPy2tr@fkWvw0HP@CR5UvK/Ac "Ruby – Try It Online")
This employs one of my favourite bit-twiddling hacks. `a&a-1` gives 0 if `a` has only one bit set. Unfortunately it also gives 0 if `a==0` so we use the fact that any number (including 0) raised to the power 0 is 1 to catch this special case: `(a&a-1)**a`.
So now we have distinction between nonzero and zero numbers. The rules require two distinct values, so we use `>0` to convert to `true/false` and we are done.
The footer in the linked TIO formats the output 2d array line by line, and converts the `true/false` to `1/0`.
[Answer]
# [Factor](https://factorcode.org) + `math.matrices math.unicode`, 57 bytes
```
[ 2^ dup [ bitand bit-count 1 ≠ ] <matrix-by-indices> ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU3v0GBPP3crhdzEkgwwoZeUWVKeWZwK4ZTmZSbnp0A5QKIoMzm1WKGgKLWkpLKgKDOvRCE7tSgvNUfBmovLZGlpSZquxU3LaAWjOIWU0gKFaAWgYYl5KSBKNzm_FKjcUOFR5wKFWAUbsGEVukmVupl5KSBT7RRiIQZsSk7MyVEozswtyEnVLUlMyknVg0gsWAChAQ)
```
2^ ! two to the input power
dup ! duplicate
[ ... ] <matrix-by-indices> ! create an MxN matrix with indices on top of stack
bitand ! bitwise and
bit-count ! number of on bits
1 ≠ ! not equal to one
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
oDL<ãε`&b1¢Θ}sô
```
[Try it online!](https://tio.run/##ASUA2v9vc2FiaWX//29ETDzDo861YCZiMcKizph9c8O0/8K7McOwOv8z "05AB1E – Try It Online")
Outputs a nested list. The footer formats it into the grid. Port of lyxal's Vyxal answer.
*-1 thanks to @KevinCruijssen*
#### Explanation
```
oDL<ãε`&b1¢Θ}sô # Implicit input
oD # Push 2 ** n and duplicate
L<√£ # Cartesian product of [0..2**n) with itself
ε } # Map over this list:
`& # Bitwise AND of the pair
b1¢Θ # Is the popcount equal to 1?
sô # Split into 2 ** n chunks
# Implicit output
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 11 bytes
```
.;`,^2$.@!=1+``@`&@$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWW_SsE3TijFT0HBRtDbUTEhwS1BxUIFJQFYujTWOhTAA)
Returns a matrix with truthy values (positive numbers) for `1` and falsy values (`0`) for `0`.
[Answer]
# [Raku](https://raku.org/), 52 bytes
```
{(^$_ X+&^$_).rotor($_)».&{!$_||$_!=1+<.msb}}o 1+<*
```
[Try it online!](https://tio.run/##JcxBCsIwFIThq4yPEJIGHhTEhW3u4cpQwYBiTEndlJCTufNiMdbVfIufma/pcahhhfSwNauzcDgZ2UZziq@YVNPnzTLvmqQUztrejByWiy4lormrA3xM6Jn3yFimFSTckYaNHKZZmU7zPd6eikB6i/3v918QodQv "Perl 6 – Try It Online")
The version of Raku on TIO fails to parse the `!$_||$_!=1+<.msb` bit, presumably due to a bug, so I've expressed it there as `!($_&&$_==1+<.msb)`, which is equivalent by De Morgan's law, but two bytes longer.
This is an anonymous function consisting of two separate anonymous functions composed together with `o`. The right-hand function is `1 +< *`, which shifts the number 1 leftwards a number of bits given by its argument; that is, two to the power of the argument. That number is passed to the left-hand function, where the variable `$_` gets its value.
* `^$_` is a range of numbers from 0 up to one less than `$_`. For example, when the number passed to the first function is 3, this is the range `0..7`.
* `X+&` gives the cross product of one copy of that range with another using the bitwise-and operator `+&`.
* `.rotor($_)` takes that flat crossed list and makes it into a square matrix.
* `».&{ ... }` recursively applies the code between the braces to each element of that matrix.
* `!$_ || $_ != 1 +< .msb` tests whether each number is zero (`!$_`) or consists of only a single binary digit by comparing the number to 1 bit-shifted left a number of places equal to the number's most significant bit (`1 +< .msb`).
[Answer]
# JavaScript (ES6), 74 bytes
```
n=>[...Array(1<<n)].map((_,y,a)=>a.map((_,x)=>(g=k=>k?k%2^g(k/2):1)(x&y)))
```
[Try it online!](https://tio.run/##NczLDoIwEIXhPU8xG2UmYBXiSmiNz@EtDQKB4pQUYiDGZ0dCdPWdf3Nq/dJd5qq237B95FMhJ5bqLIQ4OadHjNKU6SqeukW8h2OoSSr9z2EOLKWRyhzNKr6VaLYxHSLCYT0S0VRYh03eA4OEXTKTwn4mCAjeHkBmubNNLhpbYoFMy68DqcCJ2laMPvhEv3lhnyCAxcT7TF8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
≔X²NθEθ⭆θ¬⁼¹Σ↨&ιλ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jIL88tUjDSEfBM6@gtMSvNDcJyNXU1FEo1LTmCijKzCvR8E0s0CjUUQguAfLSoRy//BIN18LSxJxiDUOgVGmuhlNicaqGU2ZJeWZxqmNeikamjkIO0BgjTQiw/v/f5L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal integer `2`
X Raised to power
N Input as a number
≔ θ Save in variable
θ Saved variable
E Map over implicit range
θ Saved variable
⭆ Map over implicit range and join
ι Outer value
& Bitwise And
λ Inner value
↨ ² Convert to base `2`
Σ Take the sum
¬⁼ Does not equal
¬π Literal integer `1`
Implicitly print
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes
```
n->matrix(2^n,,i,j,sumdigits(bitand(i-1,j-1),2)!=1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LctBCsIwEEDRq4xdzcBkkepClPQoSqSkTKFjSKfgXdwERDyTt1FoV5-3-M9PjkWuQ66vBOG9WHLH715dN0Ur8sD2oszCI8_L1MsgNuNNLGqP4jyPzhO3tAuetpXSvaBCAM9wYMhF1P5uTg2dV2VMqETbUOvaHw)
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes
Golfed version. [Try it online!](https://tio.run/##TY5Ba8JAFITv@yteV@jFDZLQU@pKFBEsFIrN7fEMS5vEBfNW1oW2iL89bpJLTwPfDDPTmXCqOxPsl@n7puAq12vvzR9unDvXmD7p0hd7DnVb@61tbbjixoY1f@MsSdUsS1JSGdGzyo43Vnyn/uIth3cTvP3FbpSKINewdSgAPgYXJUpYruAzuty@Oct4sE0T90o3MVgU4N2PAgmSaMhKkqQgNtxGPjXfBQmxcx4ZNKQKGJYaXqLO52N2WuNYk0t6jeD/uQaZSFD/AA)
```
f@n_:=Array[Boole[1!=Tr@IntegerDigits[BitAnd[#-1,#2-1],2]]&,2^{n,n}]
```
Ungolfed version. [Try it onlinne!](https://tio.run/##TY5BSwMxEIXv@RVjrk3RFE9rI1WKUEEQ3dswlthu1indicSAwtLfvqa7Hjy94XuPN6/z@aPpfOadH4awkm3lav9@bHATsI7ZH3EjuWmbtOaW8xfec76TPfLcmsPcklkQXThrrLki03PRxZucTH/4u2j4TCz5yefEP9iNsiWoHKwjKoDns4saNSxv4bW40j5GFnzhEMqIOk4MLleQ4rcBDZronNWkyUBp6Ec@NZ8UKfUQEwo4sAYElg6ui85mY3b6JqWm0nRTwP9xAYVI0fAL)
```
f@n_:=Table[If[Total[IntegerDigits[BitAnd[i-1,j-1],2]]!=1,1,0],{i,1,2^n},{j,1,2^n}]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 65 bytes
```
n=>[...Array(1<<n)].map((_,y,a)=>a.map((_,x)=>(x&=y)&&+!(x&x-1)))
```
[Try it online!](https://tio.run/##NYxBCoMwEADvvmJ7MbtEQ4XeNELf0ZYSbCyKbiRKUUrfngZpTzNzmd68zNz4blpydg8bWh1Y1xel1Nl7s2FRVUw3NZoJ8Z5tmSFdm3@uMXBN9UZpKg/R1rwgotA6j4NdgEHDsYyo4BQhJcE7AWgcz26wanBPbJFp33nQNXjVu45RgCD66ZUFgYSdZfIJXw "JavaScript (Node.js) – Try It Online")
na
] |
[Question]
[
Given a list of the integers from \$1\$ to some \$n\$, give the minimum number of adjacent swaps required to put the list in ascending order.
You will receive a list as input and should output a non-negative integer. You may if you wish choose to expect a list of the integers from \$0\$ to \$n\$ instead.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
[3,2,1] -> 3
[1,2,3,4] -> 0
[2,1,3,4] -> 1
[2,1,4,3] -> 2
[2,4,1,3] -> 3
[4,2,3,1] -> 5
[4,3,2,1] -> 6
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
-20% thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)!
```
&<Rz
```
[Try it online!](https://tio.run/##y00syfn/X80mqOr//2gTHWMdIx3DWAA "MATL – Try It Online") or [Verify all cases!](https://tio.run/##y00syfmf8F/NJqjqv0FyhEtURcj/aGMFIwXDWK5oQyBtrGACZAH5SCwTBWMwywQkCmSZgNUZglkQvQA)
As long as the list is not sorted, there is always an adjacent pair that is out of order. Swapping this pair yields an optimal strategy as:
* this swap reduces the number of any pairs that are out of order (not just adjacent) by one.
* no swap can remove two of those pairs.
* the list is sorted when there are no such pairs left.
This means counting the number of unordered pairs gets us the minimum number of swaps to sort:
`&<` less-than table
`R` upper triangular matrix
`z` count the non-zero elements
[Answer]
# [Factor](https://factorcode.org/) + `koszul`, 10 bytes
```
inversions
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnV9cVZqjUFCUWlJSWVCUmVeiUJxaWJqal5xarGDNxVXNpQAE1QrGCkYKhgq1UJ4hkGesYALng@TQ@SZAEQTfBKwCxjcB6zdE4sPMr1WI5vqfmVeWWlScmZ9X/D9WITexQKG4JDE5W@8/AA "Factor – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
function(x)sum(combn(c(0,x),2,diff)<0)
```
[Try it online!](https://tio.run/##K/qfkphblFgaD6Myi0sUbHT/p5XmJZdk5udpVGgWl@ZqJOfnJuVpJGsY6FRo6hjppGSmpWnaGGhi0QxUZAxUYaipqaCsoGunYMyFVY0hUI2xjglMlQF2VUBzkFUZ4lZlomMMU2WES5UJyDQC7jIBuwvuelNcqlD8aIbDj5qa/wE "R – Try It Online")
Adaptation of [ovs's answer](https://codegolf.stackexchange.com/a/245806/67312). Test harness taken from [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/245814/67312).
`combn(x,m)` in R generates all size `m` combinations of the elements of `x`1, and has an optional `FUN` argument which it applies to each of those combinations. As luck would have it, it's implemented in such a way as to maintain the order of elements in `x` in each of those combinations; for `x=c(3,1,4,2)`:
```
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 3 3 1 1 4
[2,] 1 4 2 4 2 2
```
Using `FUN=diff` results in a vector which contains the upper-triangular part of the matrix of comparisons:
```
[1] -2 1 -1 3 1 -2
```
These are negative precisely where there is a swapped pair, so count the negatives.
Unfortunately, R will throw an error for `combn(1,2)` since it can't get a combination of 2 out of a single value, so `0` is prepended. This has no impact (since the `diff` will always be positive), and neatly fixes that edge case.
---
1 If `x` is a single numeric, it instead uses `seq_len(n)` which will be `1:floor(n)` for `n>=1` and an empty vector otherwise. R functions sometimes have weird special cases for length-one inputs.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 35 bytes
```
f(h:t)=length[1|c<-t,c<h]+f t
f[]=0
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI8OqRNM2JzUvvSQj2rAm2Ua3RCfZJiNWO02hhCstOtbW4H9uYmaegpWVQkBRak5pSqqep7@ChiYXWNRWISWfSwEICooy80oUVBTSFKKNdYx0DGPRRQ2BosY6JhjiQLU4xU10jLGIm4B0YIibgM03xCIOcc9/AA "Curry (PAKCS) – Try It Online")
A port of [ovs' MATL answer](https://codegolf.stackexchange.com/a/245806/9288).
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
function(x)sum(upper.tri(a<-outer(x,x,`>`))*a)
```
[Try it online!](https://tio.run/##K/qfkphblFgaD6Myi0ts/6eV5iWXZObnaVRoFpfmapQWFKQW6ZUUZWok2ujml5akFmlU6FToJNglaGpqJWpiMUIjWcNYx0jHUFNTQVlB107BmAurGkOgGmMdE5gqA@yqgOYgqzLErcpExximygiXKhOQaQTcZQJ2F9z1prhUofjRjOs/AA "R – Try It Online")
Uses [ovs' approach](https://codegolf.stackexchange.com/a/245806/95126): upvote that!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ¿’Æ!S
```
A monadic Link that accepts the shuffled list of \$[1,n]\$ and yields the swap count.
**[Try it online!](https://tio.run/##y0rNyan8///opEP7HzXMPNymGPz/cLvm///R0cY6RjqGsVw60YZAhrGOCYgJFEFmmugYQ5gmIHEQ0wSs1hDCRDdBx0zHVMdcxwIhZAYURBEyA6tDEjKDakUTAhkOF7LQQRGM5YoFAA "Jelly – Try It Online")**
### How?
```
Œ¿’Æ!S - Link: list of [1,n] in some order, L
Œ¿ - 1-indexed index of L in a sorted list of all permutations of L
’ - decrement -> same but 0-indexed
Æ! - convert to factorial number system (mixed-radix base using ..., 2!, 1!, 0!)
S - sum
```
---
I *think* that the method employed by ovs is also six, but perhaps there is a five or better out there. For example:
```
Œc>/€S
```
or (counting swapping from the other end):
```
<";\FS
```
or
```
>Ṫ$ƤFS
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 3 bytes
```
Sđ>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FkuCj0y0W1KclFwMFVhw0znaWMdIxzCWK9oQSBvrmABZQD4Sy0THGMwyAYkCWSZgdYZgFkQvxCwA)
A port of the [@ovs's MATL answer](https://codegolf.stackexchange.com/a/245806/9288).
```
Sđ>
S Find a subset of the input that
đ has exactly two elements where
> the first is greater than the second.
```
`-n` counts the number of solutions.
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
port of ovs' MATL answer
```
lambda n:sum(a>b for a,b in combinations(n,2))
from itertools import*
```
[Try it online!](https://tio.run/##Tc5BCoMwEAXQfU4xO5OSjcaVoBexLpLW0AGTSDJdFPHsqVEK3T0@w5@/fugVvMq2v@dFO/PU4Lv0dlwPBmyIoKUB9PAIzqDXhMEn7mUjBLMxOECaI4WwJEC3hki3THOiBD2MbFSykfUk2VgfULItPJJ/tlJdbEte2J639cVfw8RYGYNlyvmgWyN64rbacId@gM1yFHsl8hc "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
δ›Åu˜O
```
Port of [*@ovs*' MATL answer](https://codegolf.stackexchange.com/a/245806/52210), so make sure to upvote him as well!
First time I'm using the triangle of a matrix builtin in 05AB1E. :) The `݁u` could alternatively be `܁l` for the same byte-count.
[Try it online](https://tio.run/##yy9OTMpM/f//3JZHDbsOt5aenuP//3@0kY6JjqGOcSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3NbHjXsOtxaenqO/3@d/9HRxjpGOoaxOtGGQNpYxwTIAvKRWCY6xmCWCUgUyDIBqzMEsyB6YwE).
**Explanation:**
```
δ # Apply double-vectorized, implicitly using the input-list twice:
› # Check if the first value is larger than the second
# (this basically creates a larger-than table)
# e.g. [2,4,1,3] → [[0,0,1,0],[1,0,1,1],[0,0,0,0],[1,0,1,0]]
Åu # Pop and leave the upper triangle of this matrix
# → [[0,0,1,0],[0,1,1],[0,0],[0]]
˜ # Flatten it to a list
# → [0,0,1,0,0,1,1,0,0,0]
O # Sum it
# → 3
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 47 bytes (@dingledooper)
```
f=lambda P,*s:s>()and sum(P>Q for Q in s)+f(*s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY1NqsIwFEbnXcXF0b16_amtIkK7Bh2XJ0TaYCBNQlMF1-KkE92Tu3lNq-8ND4fvfI-Xu7cXa7rueW3lfPdeykyL-lwKOPDU732OJEwJ_lrjIT-CtA0cQRnwNJM49fSZnYLQQVhXGVzRoqlEqZWpPNI-AsUWMqiFw-omNOuFd1q1OIF5DhOiCFyjTIuK-6iiLLPQ93AAtvR56d6ySHjN8U-YJVER95BwOuAqKnrzh_GIKScDrgOmwX-36bAdU5uA_-XtePcL)
#### Old [Python](https://www.python.org), 48 bytes
```
f=lambda P,*s:sum(map(P.__gt__,s),*s and[f(*s)])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY1BbsIwEEX3OcWIlQdNooSEqkIKZ2AfQWSUGCw5thUbpJ6lm2zaO3Eb7ATa5Zuv9-b71375q9HT9HPzIv185KJWfDh3HA60djt3G9jALTtkbXvxbUsOwxm47hrB1g6P-PJOwoygQGowttcsx2zseaek7h3DXQKSDNQQU_2dK1KZs0p6toJ0DyvEBOwotWeSQlZiXRsIPTYDGXx9mR6iKWlDxTFqZdIUAUqqZsyTJix_WCxYUTnjJmIV97dbze6S2kb8L38s754)
Takes the splatted input and returns the inversion number.
Just like @ovs's answer this directly computes the [inversion number](https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)). It uses recurrence through the optional initial value to the `sum` function.
This appears to be quite similar to @arnauld's approach (going by comments as I don't read JS).
[Answer]
# APL+WIN, 25 bytes
Prompts for vector of integers
```
+/>/n[⊃(,n∘.<n)/,n∘.,n←⎕]
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@nX5e9KOuZg2dvEcdM/Rs8jT1ISwg2TYBqDr2P1Ah1/80LmMFIwVDrjQuQyBtrGACZAH5SCwTBWMwywQkCmSZgNUZglkQvQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# JavaScript (ES6), 42 bytes
This is based on [ovs' insight](https://codegolf.stackexchange.com/a/245806/58563).
```
f=([x,...a])=>x&&a.map(y=>n+=y<x,n=f(a))|n
```
[Try it online!](https://tio.run/##dc6xDoIwFIXh3afoRNp4LZZWJ8uLkA43SI0GWyLGlMR3r2gZDOj85c85F3xgX9/O3X3j/LGJ0WpaBeCco2G6DFmG/IodHXTp1no4BHDaUmTs6WLtXe/bhrf@RC2tJBQgDCGMkTwncjVjMbIEZRJv5zy2Xyx@sQI5cbFk9e7Nn2312RYT75acvifexxc "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[x, // x = next value from the input list
...a] // a[] = remaining values
) => //
x && // abort if x is undefined
a.map(y => // otherwise, for each value y in a[]:
n += y < x, // increment n if y is less than x
n = f(a) // initialize n to the result of a recursive call
) // end of map()
| n // return n (coerced to 0 if undefined)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 61 bytes
```
c;i;f(a,n)int*a;{for(c=0;n--;)for(i=n;i--;)c+=a[n]<a[i];i=c;}
```
[Try it online!](https://tio.run/##XZLbjpswEEDf9ytGSJFwYtSEW9R62T5U/YoEVcgxW6u7zipGWtSIXy8dGwOOkWCYOXP1mCevnI8jZ5K1cUMVkarbNuzeXm8xr/ZMJQkjRpGVYtIofFc1J1U/NydZM1lxNowYA@@NVDGB@xPgYwyd0J0@nGqo7hlN6WFgqzm15gOaM5r7ILMAvUOQLyCnmQ8KB3IT44PSgtzWeCh@dMB19djwL2Wpln/FtY2nGcgXp26dTsHnacDTgGcBzwKeBzwPeBHwIuBlwMuAHwN@JOvQ22lqO/M0HHUbcjJzMneycLJ08ugdoOg/BO/ExWQDXDrsKWA@TIX/GFg6X35VugP@u7lt8Sv4H3GbQqJz/zM9919/4FtEFHw9i1w0XkaITTmpLqLHsD1zv8/z2HMj6@CLhcFuZ72JTTZd1/UwMN10INanZj4GNVO8JCH3ulp6Mh2pqWBPvFLm@bihcxtHG7254KTo8d0M/C06oegwfV@TNfvw0IfGArhbCoo8NigQLEsIO5wr1pC8wOYCG31WWEvTZQe6qsRcdXgaxn@8fWte9Zh8/gc "C (gcc) – Try It Online")
Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Returns the minimum number of adjacent swaps required to put the list in ascending order.
Uses [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s idea from his [MATL answer](https://codegolf.stackexchange.com/a/245806/9481).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IΣEθLΦ…θκ›λι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBJzUvvSRDwy0zpyS1SMO5Mjkn1TkjHyyVramj4F6UmgiSyNFRyNSEAOv//6OjjXRMdAx1jGNj/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Being a competent call change conductor, I already how many adjacent swaps I would need to get back to rounds (all bells in ascending order) from any given change (permutation), which is basically the same algorithm everyone else is using anyway.
```
θ Input array
E Map over values
θ Input array
… Truncated to length
κ Current index
Φ Filtered where
λ Inner value
› Is greater than
ι Outer value
L Take the length
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
a->sum(i=1,#a,sum(j=1,i,a[i]<a[j]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5UTde2KS3M1Mm0NdZQTdUDMLCAzUycxOjPWJjE6K1ZTE6o0N7GgIKdSI1dB106hoCgzrwTIVAJxlBTSNHI1NXUUoqONdYx0DGOBLEMgw1jHBMQEiiAzTXSMIUwTkDiIaQJWawhhQkyIhVq6YAGEBgA)
A port of [ovs' MATL answer](https://codegolf.stackexchange.com/a/245806/9288).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
\d+
$*
+`(1+(1+)#*),\2\b
$2,$1#
#
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0s7QcNQG4g0lbU0dWKMYpK4VIx0VAyVuZT//zfWMdIx5DIEksY6JlxANpw20TEG0iYgES4TsLwhkAarBwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
(1+(1+)#*),\2\b
$2,$1#
```
Swap two adjacent numbers if the first is bigger, and mark that a swap took place.
```
+`
```
Make as many swaps as possible.
```
#
```
Count the number of swaps.
[Answer]
# [Arturo](https://arturo-lang.io), 36 bytes
```
$=>[combine.by:2&|enumerate=>[<do&]]
```
[Try it](http://arturo-lang.io/playground?XWfhmd)
```
$=>[ ; a function
combine.by:2& ; get all pair combinations in input
| ; then
enumerate=>[ ; count how many pairs
<do& ; are unsorted
] ; end enumerate
] ; end function
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 12 bytes
```
Đɐ>ĐŁřĐɐ≤*ƑƩ
```
[Try it online!](https://tio.run/##K6gs@f//yISTE@yOTDjaeHQmiPmoc4nWsYnHVv7/H22iY6xjpGMYCwA "Pyt – Try It Online")
```
Đ implicit input; Đuplicate
ɐ> for ɐll possible pairs, is the first element greater than the second?
Đ Đuplicate
Ł get Łength
ř řangify
Đ Đuplicate
ɐ≤ for ɐll possible pairs, is the first element less than or equal to the second?
* element-wise multiplication
Ƒ Ƒlatten
Ʃ Ʃum; implicit print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~52~~ 43 bytes
saved 9 bytes thanks to the comment of @att.
Modified from [@alephalpha's answer](https://codegolf.stackexchange.com/a/245858/110802)
---
[Try it online!](https://tio.run/##XYyxCsIwEIZ3n@JowelEo5nUijg4C7odp4TSYkrTlpIOEvLssdV20On@77v/zij7zIyyOlUhT8K1M3Sq6zKjmGi1Y973s2BmdHhrSdxj9ugK9DwPqmnK17mrUqvrisyDYZvApdWVJYMQweIAEUJOhnn204XlEZzbIKwRhEdw4hN7IQca7D/JXowkv@uB5HQnRpp@@vAG)
```
Sum[Boole[#[[0;]]<#[[j]]],{,Tr[1^#]},{j,}]&
```
---
**In this problem, you need to calculate [the inversion number of a permutation](https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)#Inversion_number).**
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
Ṙṗ'L2=;vÞṠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4bmY4bmXJ0wyPTt2w57huaDiiJEiLCIiLCJbMSwyLDMsNF1cblsyLDEsMyw0XVxuWzIsMSw0LDNdXG5bMiw0LDEsM11cbls0LDIsMywxXSBcbls0LDMsMiwxXSJd)
Based on [Kendall tau distance](https://en.wikipedia.org/wiki/Kendall_tau_distance) definition.
May be golfed more, but I don't like direct ports of another answers,
so golfing should be based on the same definition
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 97 bytes
Golfed version. [Try it online!](https://tio.run/##XY7LDoIwEEX3fMWEsGhDTayyqoGlP9F0UStIkT5CSqJfj61Cou7uOZN7M0Y@tJHL0iGDWX0ZnbojrtieWDa29hb66AXp3ASaUQj9NIOFq0PJDEyX3053YLgWjeGDiLq1oJgqKcZE4WLJMun9@DzPVgXtbNwFVoOftA3IEMhh10BOID2Ciywz0qOfAgHOjwQOBKiImb5jFFWiZP@pimKl6nNOVG09utK2KfBpeQE)
```
f(m):=block([c:0,n:length(m)],for i:1 thru n do(for j:i+1 thru n do(if m[i]>m[j] then c:c+1)),c)$
```
Ungolfed version. [Try it online!](https://tio.run/##bU/NbsIwDL73KT4hDonIpAV6CoLjXqLKoSstBBqnilKJPX2XpC0S03yxvz9btvXT2HqaOmY51AnfvWserECsqnEjBYVPAVLoW7qGW3RpkdXOeRglEW5@BOHiMKdW7a7M7n81lelgK6Nxju2uo60lLOdyww7yFeB54vNd34bRE8suXvBtUdTD0P98jdQE42h5Y/CGArMCG3ycsRFI/yWzrQf2FhCoqoPAXkDqOMs8RqJMKLF/URmJBZWznFC55uSC1p2aH6fpFw)
```
f(m) := block(
[count: 0, n: length(m)],
for i:1 thru n do (
for j:i+1 thru n do (
if m[i] > m[j] then count: count + 1
)
),
return(count)
)$
applyFunction(m) := print(m, " -> ", f(m))$
map(applyFunction, [[3, 2, 1], [1, 2, 3, 4], [2, 1, 3, 4], [2, 1, 4, 3], [2, 4, 1, 3], [4, 2, 3, 1], [4, 3, 2, 1]]);
```
[Answer]
# [Uiua](https://uiua.org), ~~14~~ 11 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
/+♭<∩'⊞<.⊛.
```
[Try it!](https://uiua.org/pad?src=RCDihpAgLyvima084oipJ-KKnjwu4oqbLgoKRCBbMyAyIDFdICAgIyAtPiAzCkQgWzEgMiAzIDRdICMgLT4gMApEIFsyIDEgMyA0XSAjIC0-IDEKRCBbMiAxIDQgM10gIyAtPiAyCkQgWzIgNCAxIDNdICMgLT4gMwpEIFs0IDIgMyAxXSAjIC0-IDUKRCBbNCAzIDIgMV0gIyAtPiA2)
-3 thanks to Bubbler
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes
```
\d+
*
rw`\1\b.*,(_+)\b
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8mRZtLi6uoPCHGMCZJT0tHI15bMybp/39jHSMdQy5DIGmsY8IFZMNpEx1jIG0CEuEyAcsbAmmwegA "Retina – Try It Online") Link includes test cases. Explanation: The first stage simply converts to unary. The second stage then counts the number of overlapping matches (`w`) where the first number is not less than the second number. The `r` flag causes the match to be processed right-to-left, so the second number is matched first and the first number then compared against it; if left-to-right matching was used, either the input would have to be reversed, or a negative lookahead used to ensure the second number is less than the first, either way costing more bytes.
] |
[Question]
[
You probably all know the [7-segment display](https://en.wikipedia.org/wiki/Seven-segment_display) which can display among other things all digits from \$0\dots 9\$:
[](https://i.stack.imgur.com/Dcp8o.png)
# Challenge
We only consider the segments \$\texttt{A}\dots\texttt{G}\$, your task is to decode a single digit given which segments are turned on.
This can be encoded as an 8-bit integer, here's a table of each digit with their binary representation and the corresponding little-endian and big-endian values:
$$
\begin{array}{c|c|rr|rr}
\text{Digit} & \texttt{.ABCDEFG} & \text{Little-endian} && \text{Big-endian} & \\ \hline
0 & \texttt{01111110} & 126 & \texttt{0x7E} & 126 & \texttt{0x7E} \\
1 & \texttt{00110000} & 48 & \texttt{0x30} & 12 & \texttt{0x0C} \\
2 & \texttt{01101101} & 109 & \texttt{0x6D} & 182 & \texttt{0xB6} \\
3 & \texttt{01111001} & 121 & \texttt{0x79} & 158 & \texttt{0x9E} \\
4 & \texttt{00110011} & 51 & \texttt{0x33} & 204 & \texttt{0xCC} \\
5 & \texttt{01011011} & 91 & \texttt{0x5B} & 218 & \texttt{0xDA} \\
6 & \texttt{01011111} & 95 & \texttt{0x5F} & 250 & \texttt{0xFA} \\
7 & \texttt{01110000} & 112 & \texttt{0x70} & 14 & \texttt{0x0E} \\
8 & \texttt{01111111} & 127 & \texttt{0x7F} & 254 & \texttt{0xFE} \\
9 & \texttt{01111011} & 123 & \texttt{0x7B} & 222 & \texttt{0xDE}
\end{array}
$$
# Rules & I/O
* Input will be one of
+ single integer (like in the table above one of the two given orders)
+ a list/array/.. of bits
+ a string consisting of characters `ABCDEFG` (you may assume it's sorted, as an example `ABC` encodes \$7\$), their case is your choice (not mixed-case)
* Output will be the digit it encodes
* You may assume no invalid inputs (invalid means that there is no corresponding digit)
# Tests
Since this challenge allows multiple representations, please refer to the table.
[Answer]
# JavaScript (ES6), 26 bytes
Takes input in little Endian.
```
n=>'0958634172'[n*3%77%10]
```
[Try it online!](https://tio.run/##DYhBDoMgEADvfQUXg1Q0LIhIGrn1FcYDoWLbmKXRpt@nJDNzmLf/@TMcr8@3xfRYc5wyTo4Kq8dB9WAknfGqKmMqEEu@zSAH3o8chOUggWvgtqA5gCzDFNVy6WI67j48aySTIyHhmfa129NWRkMoaV1JQ2KNjLH8Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 18 bytes
```
b'~0my3[_p{'.find
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzP0m9ziC30jg6vqC@Wl0vLTMv5X9afpFCpkJmnkK0oZGZjomFjqGBpY6hkaGOqaGOJRCZ6hgaGgEFzIHYONZKoaAoM69EI00jU1PzPwA "Python 3 – Try It Online")
Uses little-endian inputs. Contains a raw `\x7F` byte.
# [Python 2](https://docs.python.org/2/), 27 bytes
```
map(ord,'~0my3[_p{').index
```
[Try it online!](https://tio.run/##DchNCoAgEEDhq7hTYYhG@4dOUhFBSbNIRVoUQR3dhPdtnr/P3VkVTT/GY/HChRX4mx@3Hmb/PVxmZNftisYFRowsG1BVUDSAeQuoEEqENlUCokqjTvTUMR/InsIIkjL@ "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
9[,6,0,8,2,3,1,7,5,4][[#~Mod~41~Mod~11]]&
```
[Try it online!](https://tio.run/##HYixCoAgGAZfRQiaPqjfNHPrBYJ2cZAKarAg3CJf3bTh7uC8C/vmXTgWl@b7OINJ2qBHiwEcHQgKEsIaU8XpWqOgP0TW1qkZ2UO8BxMDGLU6ixOYzOiCzIN4uaqoe236AA "Wolfram Language (Mathematica) – Try It Online")
Uses the little-endian column of integers as input. Ignore the syntax warning.
For an input X, we first take X mod 41 and then take the result mod 11. The results are distinct mod 11, so we can extract them from a table. For example, 126 mod 41 mod 11 is 3, so if we make position 3 equal to 0, then we get the correct answer for an input of 126.
The table is `9[,6,0,8,2,3,1,7,5,4]`. Part 0 is the head, which is `9`. Part 1 is missing, so it's `Null`, to save a byte: we never need to take part 1. Then part 2 is `6`, part 3 is `0`, and so on, as usual.
---
[Jonathan Allan's answer](https://codegolf.stackexchange.com/a/174431/74672) gives us `1[4,9,8,6,2,0,5,3,7][[384~Mod~#~Mod~13]]&`. This isn't any shorter, but it does avoid the syntax warning!
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~27~~ 25 bytes
```
Mod[Hash[")dD}"#]+2,11]&
```
(There's some character here that doesn't quite show up, sorry. Click on the link below and you'll see it.)
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d83PyXaI7E4I1pJM8Wltl5JOVbbSMfQMFbtv76DQrWhkZmOgomFjoKhgSWQMDLUUTAFYksQNgUKGBqBRM1BhHFt7H8A "Wolfram Language (Mathematica) – Try It Online")
This is all about brute-forcing some string to go inside `Hash` so that the hashes end up having the right values mod 11. More brute forcing can probably get us to an even shorter solution.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/Code-page)
```
“0my3[_p¶{‘i
```
Accepts a little-endian integer.
**[Try it online!](https://tio.run/##y0rNyan8//9RwxyD3Erj6PiCQ9uqHzXMyPz//7@pIQA "Jelly – Try It Online")**
This is the naive implementation, there *might* be a way to get a terser code.
[Answer]
# [Python 2](https://docs.python.org/2/), 31 bytes
```
lambda n:'99608231754'[n%41%11]
```
[Try it online!](https://tio.run/##DcgxCoQwEEbh3lNME9yFKfzHRI3gSdTCZQkrrGMQCz19DLyvefE@f7tKCsOU/sv2@S6kfel9U3VSo3W2HNVYGGBOYT/oolVphDRsO0blGQJ2YJ9zDEgebVbPfUEUj1VPCq/rnR4 "Python 2 – Try It Online") takes input as little-endian.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 25 bytes
```
n=>'1498620537'[384%n%13]
```
Accepts a little-endian integer.
**[Try it online!](https://tio.run/##DYm7DoQgFAX7/QoaI0Q0XvBFNtjtF1gaC@J7Yy4Gyf4@S3Jmijlf8zPP7M7b52iXNWw6oO5TqFTXiLKWbTrKrkowATmF92sE0fCq41AqDgJ4DVzF1RxAxNBG5FRs1n3MfFAkuiezxcdea3HZnQ7enbhTZMVtlsEb56lkJCMpyfuojGzxYyz8AQ "JavaScript (Node.js) – Try It Online")**
---
Ports for 31 bytes in Python with [`lambda n:'1498620537'[384%n%13]`](https://tio.run/##HYzBCsIwEAXvfsVeShpYJZukbRKwP6IeIhostGmpuUjpt8cozGPgHWb5pNccZQ7nax79dH94iI6RtqaVolEduyijq1iRuuUwr5Ce7wRDhJpki9ogCYskCRtCW2iQSJajK1PcHQCWdYgJ2CZcr3Y49rDRzk4lNflU/2oI4W/O8xc "Python 2 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 32 bytes
```
n->"99608231754".charAt(n%41%11)
```
[Try it online!](https://tio.run/##NY7LasMwEEX3/orBYLCLIiI/kjhpAqVQ6KKrLEsXqvyoXFsW0jgQgr/dVewGZhhm7r2HafiFr5rid5Kd7g1C43Y6oGxpNSiBslf06eCJllsLH1wquHkAevhupQCLHN249LKAzmnhGY1U9ecXcFPbaLYCvP1znt8VlnVpyOsPN1xgaU5QwXFSq5Of55v1Lk7YNkt9Kpz@gqEKUhYwFk2HGSMVOjCWFi0c4cbiDUl3hK1zwmJGMkZyVxlhLHaHretkXIJVb0IXnqP7BfB4DeB8tVh2tB@Qavc7VqEfJMUeAhEon8xuAhXlWrfX8L5F0UIdvXuP0x8 "Java (JDK) – Try It Online")
## Credits
* Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/174423/16236), much shorter than previous attempt in the post history.
* -1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan), using [Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov)'s [Wolfram Language (Mathematica) answer](https://codegolf.stackexchange.com/a/174419/16236).
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 152 bytes
Obligatory "the S's, T's, and L's aren't really there, they're just visible representations of the commands".
```
S S S T S S L
S S S T S T L
S S S T T T L
S S S T L
S S S T T L
S S S T S L
S S S T S S S L
S S S L
S S S T T S L
S S S L
S S S T S S T L
S S S L
S L
S T L
T T T T T S S S T S T S S T L
T S T T S S S T S T T L
T S T T L
S S L
S L
S L
T S S L
S T L
S T L
S S S T L
T S S T L
S L
L
L
S S S L
S L
L
T L
S T
```
[Try it online!](https://tio.run/##RU3BCYBADHsnU2QFdSKRA/0JCo7fs82JLTRpE9JnP@52nevWIiRBYgEKYDC34Gmb7z8dVr4NIstZeYe@zZz2sT6C4wmdQY4cphIxzUsH "Whitespace – Try It Online")
Ends in an error.
Equivalent assembly-like syntax:
```
push 4
push 5
push 7
push 1
push 3
push 2
push 8
push 0
push 6
push 0
push 9
push 0
dup
readi
retrieve
push 41
mod
push 11
mod
slideLoop:
dup
jz .slideLoop
slide 1
push 1
sub
jmp slideLoop
.slideLoop:
drop
printi
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~474~~ ~~176~~ ~~154~~ ~~151~~ ~~149~~ 137 bytes
Takes an input string of **eight** `0` and `1` including the first `0` for decimal point.
*(like in the second column of the table in the post)*
Outputs digit from 0 to 9.
```
,>,>,>,,,>,>,>+[[->]<++<<<<<<]>[>[>[>[->[>++++++<-<]>[--<]<]>>.>>]<[>
>[>->++<<-]>-[+>++++<]>+.>]]>[>>>+<<<-]>[>>+++.>]]>[>>>[>+++<-]>-.>]
```
[Try it online!](https://tio.run/##PUxBCoAwDHtQ1@HuIx8pPaggiOBB8P0z7cCmtCVJsz3reR/vfo1RkChzi5nCu0jPctiEckhW12CVkxsVdBuoKuJJHWqSVspS4REBRJ7mSeVnMzN/SI2xtJb9AQ "brainfuck – Try It Online")
### Algorithm
By observing state of a particular segment we can split a set of possible digits into smaller subsets. Below is the static binary search tree used in my code.
Left subtree corresponds to segment ON state, right corresponds to segment OFF state.
```
0,1,2,3,4,5,6,7,8,9
|
/-------[A]-------------------------\
0,2,3,5,6,7,8,9 1,4
| |
/-------------[B]----------------\ /----[G]----\
0,2,3,7,8,9 5,6 4 1
| |
/--------[E]--------\ /----[E]----\
0,2,8 3,7,9 6 5
| |
/----[F]----\ /----[F]----\
0,8 2 9 3,7
| |
/----[G]----\ /----[G]----\
8 0 3 7
```
### Some observations useful for golfing
1. Bits C and D are redundant and can be ignored.
2. Leading zero (bit for decimal point) can be (ab)used as value 48, important both for parsing input and preparing output.
3. When leaf is reached and digit is printed, we just need to skip all further conditions. It can be done by moving data pointer far enough to the area of zeros so that it cannot come back.
4. For the compatibility it is better to use zeros on the right, because some BF implementations doesn't support negative data pointers.
5. Hence it is better to store output value in the rightmost cell, so we can easily reach area of zeros to the right.
6. Hence it is better to check bits from left to right: A,B,E,F,G so we can reach output cell easier.
7. Different digits may share output code. For example, 5 and 6 are in the same subtree. We may do `+++++` for both values and then `+` for six only.
8. We may decrease number of `+` commands if we add 2 to output value in advance. In that case we need to decrease it for `0` and `1` only and get advantage for other digits.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 96 bytes
```
^(A)?(B)?C?(D|())(E|())(F)?(G)?
$.($.5*$.8*$(6*$7$2$2)$#6*$.3*$($.2*$(___$7)5*$7)$#4*$(6*$1_3*$8
```
[Try it online!](https://tio.run/##JYo7DgIxDET7XAMj2Sksbfhkuyg/5xYECgoaihUldw9m04xm3rzt@Xm9H8s4YruPG0YKmCjkgOWLRFj3FKWNggFG4IsFXi3g1YIHB47goJVPioCdZu8dPKnm9TpPc@n6r2PElEsVk7KJqdRm/rvpFK25zKyyczPd6Uj7AQ "Retina – Try It Online") May not be the best way, but it's an interesting way of programming in Retina. Explanation:
```
^(A)?(B)?C?(D|())(E|())(F)?(G)?
```
Tries to capture the interesting cases. The positive captures simply capture the letter if it's present. The length of the capture is therefore 1 if it's present and 0 if it's absent. The special cases are captures 4 and 6 which exist only if D or E are absent respectively. These can only be expressed in decimal as `$#4` and `$#6` but that's all we need here. The captures are then built up into a string whose length is the desired number. For instance, if we write `6*$1` then this string has length 6 if A is present and 0 if it is absent. In order to choose between different expressions we use either `$.` (for the positive captures) or `$#` (for the negative captures) which evaluate to either 0 or 1 and this can then be multiplied by the string so far.
```
$.5*$.8*$(6*$7$2$2)
```
`F` is repeated 6 times and `B` twice (by concatenation as it's golfier). However, the result is ignored unless both `E` and `G` are present. This handles the cases of `2`, `6` and `8`.
```
$#6*$.3*$($.2*$(___$7)5*$7)
```
`F` is repeated 5 times, and if `B` is present, it is added a sixth time plus an extra 3 (represented by a constant string of length 3). However, the result is ignored unless `D` is present and `E` is absent. This handles the cases of `3`, `5` and `9`.
```
$#4*$(6*$1_3*$8
```
`A` is repeated 6 times, and `G` is repeated 3 times, and an extra `1` added (represented by a constant character between the two because it's golfier). However the result is ignored unless `D` is absent. This handles the cases of `1`, `4` and `7`.
```
$.(
```
The above strings are then concatenated and the length taken. if none of the above apply, no string is generated, and its length is therefore `0`.
The resulting strings (before the length is taken) are as follows:
```
1 _
2 BB
3 ___
4 _GGG
5 FFFFF
6 FFFFFF
7 AAAAAA_
8 FFFFFFBB
9 ___FFFFFF
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
'/lx2Z^o~z'Q&m
```
Input is a number representing the segments in little-endian format.
[Try it online!](https://tio.run/##y00syfn/X10/p8IoKi6/rko9UC33/39DI2MA "MATL – Try It Online")
### Explanation
```
'/lx2Z^o~z' % Push this string
Q % Add 1 to the codepoint of each char. This gives the array
% [48 109 ... 123], corresponding to numbers 1 2 ... 9. Note that
% 0 is missing
&m % Implicit input. Call ismember function with second output. This
% gives the 1-based index in the array for the input, or 0 if the
% input is not present in the array.
% Implicit display
```
[Answer]
# [Perl 5](https://www.perl.org/) -pl, 24 bytes
```
$_=index'~0my3[_p{',chr
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYzLyW1Qr3OILfSODq@oL5aXSc5o@j/f0MjMy4TCy5DA0suQyNDLlNDLksgMuUyNDQCCpgDsfG//IKSzPy84v@6BTkA "Perl 5 – Try It Online")
Takes little-endian integers.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->n{"0083416243795"[n%23-10]}
```
[Try it online!](https://tio.run/##DYs7CoAwEAWvIoLdKnmbf6EXCSm0sFOCIESMZ4@BmWZgrnt76j7XcTnfXggnFQwrab3uwzmwHCHiVwPYkHIE4QkM0iDf0ARwC7Yp43Ss6S25pC5k2kOObfwB "Ruby – Try It Online")
[Answer]
# Japt, 15 bytes
Takes the big-endian value as input.
```
"~
¶ÌÚúþÞ"bUd
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=In4Mtp7M2voO/t4iYlVk&input=MjU0)
---
## Explanation
The string contains the characters at each of the codepoints of the big-endian values; `Ud` gets the character at the input's codepoint and `b` finds the index of that in the string.
[Answer]
# [Neim](https://github.com/okx-code/Neim), 15 bytes
```
&b·ö´JùïÇùï®Oùêñùêû‚ѧ¬£·õñùï™)ùïÄ
```
Explanation:
```
&b·ö´JùïÇùï®Oùêñùêû‚ѧ¬£·õñùï™) create list [126 48 109 121 51 91 95 112 127 123]
ùïÄ index of
```
[Try it online!](https://tio.run/##y0vNzP3/Xy3p4azVXh/mTm0C4hX@H@ZOmAbE8x61LDm0@OFsIHvqKk0g0fD/v6GhEQA "Neim – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
å╬JÄk☺é[£¿⌐→
```
[Run and debug it](https://staxlang.xyz/#p=86ce4a8e6b01825b9ca8a91a&i=126%0A48%0A109%0A121%0A51%0A91%0A95%0A112%0A127%0A123&a=1&m=2)
Input is little endian integer.
It uses the same string constant as Luis' MATL solution.
[Answer]
# TI-BASIC (TI-83+/84+ series), 15 bytes
```
int(10fPart(194909642ln(Ans
```
Uses little-endian input. Hashes are fairly common in TI-BASIC, so I wrote [a hash function brute-forcer](https://repl.it/@lirtosiast/TI-BASIC-Hash-Generator) for cases like this.
We get a bit lucky here, as the multiplier is 9 digits long rather than the expected 10.
```
fPart(194909642ln(Ans hash function mapping onto [0,1)
int(10 take first digit after decimal point
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~16~~ ~~15~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•NŽyf¯•I41%è
```
-1 byte thanks to *@ErikTheOutgolfer*.
-1 byte by creating a port of [*@MishaLavrov*'s Mathematica answer](https://codegolf.stackexchange.com/a/174419/52210).
-3 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMiv6N7K9MOrQeyPE0MVQ@v@P/f0MgQAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDYv8ju6tTDu0HsiqNDFUPbziv87/aEMjMx0TCx1DA0sdQyNDHVNDHUsgMtUxNDQCCpgDsXEsAA).
**Explanation:**
```
•NŽyf¯• # Push compressed integer 99608231754
I41% # Push the input modulo-41
è # Index this into the integer (with automatic wraparound)
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•NŽyf¯•` is `99608231754`.
[Answer]
# Charcoal, 17 bytes
```
I⌕”y~
¶ÌÚúþÞ”℅N
```
[Try it!](https://tio.run/##S85ILErOT8z5/985sbhEwy0zL0VDqY7n0LZD8w73HJ51eBff4X2H5ynpOAPVJSaXpBZpeOYVlJb4leYmpRZpamr@/29kavJftywHAA)
Port of the [Japt answer](https://codegolf.stackexchange.com/a/174422/8340).
] |
[Question]
[
## Background
It's well known in mathematics that integers can be put into a one-to-one correspondence with pairs of integers.
There are many possible ways of doing this, and in this challenge, you'll implement one of them *and* its inverse operation.
## The task
Your input is a positive integer `n > 0`.
It is known that there exist unique non-negative integers `a, b ≥ 0` such that `n == 2a * (2*b + 1)`.
Your output is the "flipped version" of `n`, the positive integer `2b * (2*a + 1)`.
You can assume that the input and output fit into the standard unsigned integer datatype of your language.
## Rules and scoring
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
These are given in the format `in <-> out`, since the function to be implemented is its own inverse: if you feed the output back to it, you should get the original input.
```
1 <-> 1
2 <-> 3
4 <-> 5
6 <-> 6
7 <-> 8
9 <-> 16
10 <-> 12
11 <-> 32
13 <-> 64
14 <-> 24
15 <-> 128
17 <-> 256
18 <-> 48
19 <-> 512
20 <-> 20
28 <-> 40
30 <-> 384
56 <-> 56
88 <-> 224
89 <-> 17592186044416
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If 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=70299,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~16~~ 15 [bytes](http://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
BUi1µ2*³:2*×Ḥ’$
```
[Try it online!](http://jelly.tryitonline.net/#code=QlVpMcK1MirCszoyKsOX4bik4oCZJA&input=&args=MSwgMiwgNCwgNiwgNywgOSwgMTAsIDExLCAxMywgMTQsIDE1LCAxNywgMTgsIDE5LCAyMCwgMjgsIDMwLCA1NiwgODgsIDg5)
### How it works
```
BUi1µ2*³:2*×Ḥ’$ Main link. Input: n
B Convert n to base 2.
U Reverse the array of binary digits.
i1 Get the first index (1-based) of 1.
This yields a + 1.
µ Begin a new, monadic chain. Argument: a + 1
2* Compute 2 ** (a+1).
³: Divide n (input) by 2 ** (a+1).
: performs integer division, so this yields b.
2* Compute 2 ** b.
$ Combine the two preceding atoms.
Ḥ Double; yield 2a + 2.
’ Decrement to yield 2a + 1.
× Fork; multiply the results to the left and to the right.
```
[Answer]
# Pyth, ~~16~~ 15 bytes
```
*hyJ/PQ2^2.>QhJ
```
*1 byte thanks to Dennis*
[Test suite](https://pyth.herokuapp.com/?code=%2ahyJ%2FPQ2%5E2.%3EQhJ&input=224&test_suite=1&test_suite_input=30%0A384%0A56%0A56%0A88%0A224%0A89%0A17592186044416&debug=0)
**Explanation:**
```
*hyJ/PQ2^2.>QhJ
Implicit: Q = eval(input())
PQ Take the prime factorization of Q.
/ 2 Count how many 2s appear. This is a.
J Save it to J.
y Double.
h +1.
.>QhJ Shift Q right by J + 1, giving b.
^2 Compute 2 ** b.
* Multiply the above together, and print implicitly.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 22 bytes
```
Yft2=XK~)pq2/2w^Ks2*Q*
```
[**Try it online!**](http://matl.tryitonline.net/#code=WWZ0Mj1YS34pcHEyLzJ3XktzMipRKg&input=)
### Explanation
```
Yf % factor
t % duplicate
2= % compare to 2 (yields a logical array)
XK % save a copy of that to variable K
~) % keep only values != 2 in the factors array
p % multiply that factors
q2/ % product - 1 / 2
2w^ % 2^x
K % load variable K (the logical array)
s % sum (yields the number of 2s)
2*Q % count * 2 + 1
* % multiply both values
```
[Answer]
# Python 2, 39 bytes
```
lambda n:2*len(bin(n&-n))-5<<n/2/(n&-n)
```
`n & -n` gives the largest power of 2 that divides `n`. It works because in two's-complement arithmetic, `-n == ~n + 1`. If `n` has *k* trailing zeros, taking its complement will cause it to have *k* trailing ones. Then adding 1 will change all the trailing ones to zeroes, and change the *2^k* bit from 0 to 1. So `-n` ends with a 1 followed by *k* 0's (just like `n`), while having the opposite bit from `n` in all higher places.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 25 ~~26~~ bytes
```
:qt2w^w!2*Q*G=2#f2*q2bq^*
```
This uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1) of the language/compiler.
[**Try it online!**](http://matl.tryitonline.net/#code=OnF0MndedyEyKlEqRz0yI2YyKnEyYnFeKg&input=ODk)
### Explanation
Pretty straightforward, based on brute force. Tries all combinations of *a* and *b*, selects the appropriate one and does the required computation.
```
:q % implicit input "n". Generate row vector [0,1,...,n-1], say "x"
t2w^ % duplicate and compute 2^x element-wise
w!2*Q % swap, transpose to column vector, compute 2*x+1
* % compute all combinations of products. Gives 2D array
G=2#f % find indices where that array equals n
2*q2bq^* % apply operation to flipped values
```
[Answer]
# Julia, 41 bytes
```
n->2^(n>>(a=get(factor(n),2,0)+1))*(2a-1)
```
This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
We define `a` as 1 + the exponent of 2 in the prime factorization of `n`. Since `factor` returns a `Dict`, we can use `get` with a default value of 0 in case the prime factorization doesn't contain 2. We right bit shift `n` by `a`, and take 2 to this power. We multiply that by `2a-1` to get the result.
[Answer]
# Perl 5, 40 bytes
38 bytes plus 2 for `-p`
```
$i++,$_/=2until$_%2;$_=2*$i+1<<$_/2-.5
```
`-p` reads the STDIN into the variable `$_`.
`$i++,$_/=2until$_%2` increments `$i` (which starts at 0) and halves `$_` until `$_` is nonzero mod 2. After that, `$_` is the odd factor of the original number, and `$i` is the exponent of 2.
`$_=2*$i+1<<$_/2-.5` — The right-hand side of the `=` is just the formula for the number sought: {1 more than twice the exponent of 2} times {2 to the power of {half the odd factor minus a half}}. But "times {2 to the power of…}" is golfed as "bit-shifted leftward by…". And that right-hand side is assigned to `$_`.
And `-p` prints `$_`.
[Answer]
# C, 49 bytes
```
a;f(n){for(a=0;n%2-1;a++)n/=2;return 2*a+1<<n/2;}
```
[Answer]
## JavaScript ES6, ~~36~~ 33 bytes
```
n=>63-2*Math.clz32(b=n&-n)<<n/b/2
```
My understanding is that `Math.clz32` is going to be shorter than fiddling around with `toString(2).length`.
Edit: Saved 3 bytes thanks to @user81655.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
2Ǒ:£E/‹½E¥d›*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyx5E6wqNFL+KAucK9RcKlZOKAuioiLCIiLCI4OCJd)
```
2Ǒ # Multiplicity by 2 = a
:£ # Store a copy to the register
/ # Divide the input by...
E # 2 ** A
‹½ # Decrement and halve = b
E # 2 ** b
* # Multiplied by
¥ # a (register)
d› # Doubled and incremented
```
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 38 bytes
```
f(n)=k=valuation(n,2);(2*k+1)<<(n>>k\2)
```
Note that `>>` and `\` have the same precedence and are computed left-to-right, so the last part can be `n>>k\2` rather than `(n>>k)\2`. The ungolfed version would make `k` lexical with `my`:
```
f(n)=
{
my(k=valuation(n,2));
(2*k+1) << ((n>>k)\2);
}
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~24~~ ~~23~~ 18 bytes
```
Wa/2=HV:ai+:2Ui*Ea
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJXYS8yPUhWOmFpKzoyVWkqRWEiLCIiLCIiLCI0Il0=)
Loops, halving `a` and incrementing `i` by 2, until `a` halved (int division) is different from `a/2` (float division), thus indicating `a` had become odd. The way the loop is set up, `a` is now half of that odd number, rounded down: i.e., if the odd factor of the original input is \$2k+1\$, `a` is now \$k\$. Meanwhile, if the largest power-of-two factor of the original input is \$2^n\$, then `i` is now \$2n\$. It remains only to increment `i` to \$2n+1\$ and multiply that by \$2^k\$.
---
The new `U`, `E`, and `HV` operators make a big difference for this one. Here's the original 23-byte version in Pip Classic:
```
Wa/2=Ya//:2i+:2++i*2**a
```
[Try it online!](https://tio.run/##K8gs@P8/PFHfyDYyUV/fyihT28pIWztTy0hLK/H///@GRgA "Pip – Try It Online")
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), 22 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md)
```
1(1.)(1.).
?(%.)(1(12(/.2))?)(()(?(/.2
+(().
```
[Try it here!](https://dloscutoff.github.io/hbl/?f=0&p=MSgxLikoMS4pLgo/KCUuKSgxKDEyKC8uMikpPykoKCkoPygvLjIKKygoKS4_&a=MjQ_)
### Ungolfed/explanation
Here's the same thing in HBL's companion language Thimble:
```
'(cons (head arg1) (head arg1) arg1)
'(cond (odd? arg1)
(cons
(pow 2 (div arg1 2))
nil)
(prev
(recur (div arg1 2))))
'(sum (prev arg1))
```
The first line is a helper function that takes a list and prepends two copies of its first element to it.
The second function does most of the work. If the argument is odd (base case):
* Int-divide it by 2
* Raise 2 to that power
* Return that value wrapped in a singleton list
If the argument is even (recursive case):
* Int-divide it by 2
* Recurse
* Apply the helper function to the resulting list
Thus, given \$n = 2^p \cdot (2k + 1)\$, this function returns a list containing \$2p + 1\$ copies of \$2^k\$.
The third function passes its argument to the second function and then simply sums the result.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ò2¢©o/<;§o®·>*
```
Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/251951/52210).
Should have been 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), but there is a bug in 05AB1E's `o` with certain decimal values.
[Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8OSMsKiwqlvLzw7wqdvwq7Ctz4q//81) or [verify all test cases](https://tio.run/##yy9OTMpM/W9k4HN4TVmlvZLCo7ZJCkr2lS7/D08yOrTo0Mp8fRvrQ8vzD607tN1O67/O/2gjEx0jCx1jAx1jIx0TAx0TCx1TMx0zEx0LCx0LSx1DoJwRSAlQ0NjCRMfU0EjH0NzU0sjQwszAxMTE0CwWAA).
**Explanation:**
```
Ò # Get all prime factors of the (implicit) input
2¢ # Count how many 2s are in this list
© # Store it in variable `®` (without popping)
o # Pop it, and push 2 to the power this value
/ # Divide the (implicit) input by this value
< # Decrease it by 1
; # Halve it
§ # (Cast it to a string - bugfix)
o # Pop it, and push 2 to the power this (strinified) decimal
® # Push variable `®`
· # Double it
> # Increase it by 1
* # Multiply the two together
# (which is output implicitly as result)
```
] |
[Question]
[
I use "suffix" loosely here to mean "any sub-string that follows the prefix".
"Prefix" here means the START of a word, where a word's start is defined as either after a space or from the first character of the input text (for the first word). A "prefix" in the middle of a word is ignored.
E.g. if your input prefix is "arm" and the input text is "Dumbledore's army was fully armed for the impending armageddon" then the output list contains (y, ed, ageddon).
## Test Cases
Assume case-sensitive, strings end after spaces. Input will not start with a space.
Removing duplicates is optional.
---
```
Input prefix: "1"
Input text:
"He1in aosl 1ll j21j 1lj2j 1lj2 1ll l1j2i"
Output: (ll, lj2j, lj2) - in any permutation
```
---
```
Input prefix: "frac"
Input text:
"fracking fractals fracted fractional currency fractionally fractioned into fractious fractostratic fractures causing quite a fracas"
Output: (king, tals, ted, tional, tionally, tioned, tious, tostratic, tures, as)
```
---
```
Input prefix: "href="https://www.astrotheme.com/astrology/"
Input text:
"(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
(div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Nolwenn_Leroy" title="Nolwenn Leroy: Astrology, birth chart, horoscope and astrological portrait")Nolwenn Leroy(br /)
(/div)
(div style="text-align: right; border-left: 1px solid #b2c1e2; border-right: 1px solid #b2c1e2; width: 446px; padding: 1px 1px 0; background: #eff8ff")
(table style="width: 100%")(tr)(td style="width: 220px")
(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
(div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Kim_Kardashian" title="Kim Kardashian: Astrology, birth chart, horoscope and astrological portrait")Kim Kardashian(br /)(span style="font-weight: normal; font-size: 11px")Display her detailed horoscope and birth chart(/span)(/a)(/div)
(/div)
(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
(div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Julia_Roberts" title="Julia Roberts: Astrology, birth chart, horoscope and astrological portrait")Julia Roberts(br /)(span style="font-weight: normal; font-size: 11px")Display her detailed horoscope and birth chart(/span)(/a)(/div)
(td id="cfcXkw9aycuj35h" style="text-align: right")
(/div)"
Output: (Nolwenn_Leroy", Kim_Kardashian", Julia_Roberts")
```
## The Winner
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes wins. :)
Can accept the inputs in any way that works, as long as your code can solve arbitrary problems like the test cases.
[Answer]
# [R](https://www.r-project.org/), 63 bytes
```
function(s,p,z=el(strsplit(s,' ')))sub(p,'',z[startsWith(z,p)])
```
[Try it online!](https://tio.run/##7VXfb5swEH7vX3GimgCJlJD@0EaUh0nVNG3THvaySesUGdsEp47NbDNK/vnsTEjadN2kKg97aSLAdzZ39333YZtNOduUjaJOaBXZpE7WMy4j64ytpXDoCSGM49g2RVQnYZisv1tHjLNfhauidVLHP@JNGQXXzaqQnGnDQwvErDpoiYWykbLzJmdQagOu4iBWNVdMqIX3kwVnTKsgCdAI4pMTSlwUjp75u1EhvopVvOeZUEC0lZBJCctJtsTBcrK99z6ZLScC82XHZysNobceiB84Iu124LH6JxJKJNDGGK5o98An7w1cK5TTO7sZQmjknzhBt1ZjuAVKGutz/WyE40D6GWIRiB8cjSVk4hdY10k@C2rCfHtyGE@hQIQLoxvFcmiMjG7Cyrna5mnatu0ZwTI19nTFz6hepcK306YWC0yJMRq7PL@4HM8rdlarxU0Yg9Ijw2tO3BQcv3MjIsVC5SB5iZ5SKzdquVhULodCSzaFVjBX5YBB6rspVMPc@VV9h4gBIl81lcTaWeCEM/ydoBUP/gByWd/BGP/9exGByvByFvwDSW9KvejSz1q2XKn5J250FwBm8ZEHL/TeHN7ulidQCOMqoBV@IglU2mhLdY39Ugx2QQVFWdTaYIuFC@KDWFFhII1PohSR7REOcB4yZjwT2B5tGDcjz18OGaK0WgoGp8WEZnyynzdb3p5YsCP44soTvCfMr/TXIwWc8rJ8XZY991ibI/jJ76obImXj8Svk2Bm82KO5yWTcNy56EdvTYvsoVvOPxDBiK0HUXm3ohnv3kXI7DLbVW2RronZADphRGvdoOdBlxZpjhzMP7Frg@UA6pMkA444I3PwfFfCgtij1GeIoJfEg7d3jRQpPS@FDIwWZf9EFx7N2r4TeC4P3SCEcxPpvOthuJHgKsllAS/rttn1DOtoszy@r4K8b37YJfYAwCZ/BahhvfgM "R – Try It Online")
The positive-lookbehind implementation is unfortunately 5 bytes longer due to the huge `regmatches/gregexpr` combination :
```
function(s,p)regmatches(s,gregexpr(paste0('(?<=',p,')[^ ]*'),s,,T))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Ḳfṛ"€¥Ḋ€ṫ€L}
```
[Try it online!](https://tio.run/##y0rNyan8///hjk1pD3fOVnrUtObQ0oc7uoD0w52rgaRP7f/Dy7X1gayjkx7unPH/f1pRYnJ2Zl66AohRkphTDGGkpkDozPy8xByF5NKiotS85EoksRwEB6g2M68kH8YvhRqRX1xSlFiSmQzhlRalFiskJ5YWg@wqLM0sSVVIBMskFoPdAAA "Jelly – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
8 bytes if we can take input as an array of words.
```
¸kbV msVl
¸ // Shorthand for `qS`, split into words.
kbV // Filter the words, selecting only those that start with the prefix.
msVl // For each remaining word, remove prefix length chars from the start.
```
[Try it online!](https://tio.run/##TY47EoMwDET7nELjQ9ELxckIjE30KXIzai5mAoYJ1e5baaQdcLZa12XsO5i0S7WGlyCNnN@wG8OkzcRnUy4ZE5CLxEzfW5b@8NvlbOViP08UNUFjauQSFQhd918fZ4uAxwQ1PI4WYQM "Japt – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~57~~ 56 bytes
```
lambda i,j:[w[len(i):]for w in j.split()if w.find(i)==0]
```
[Try it online!](https://tio.run/##TY3NDoJADIRfpeEECSHGIwlPghzq/mhx7eJuN4SnX/nR6Gnm6zQz0yJ3z@dsu0t2@LxqBKrHtp97Z7ikqh2sDzADMYxNnBxJWZGFubHEes277jTkKRAL2LKwAVVR7/IgvsFmBF08jNGHkmd0oFIIhtXyd3M/WH/XTv/l9KnwUQIKqYNSMBEUprhtvRKJAdwTjEWV3w "Python 2 – Try It Online")
-1 with thanks to @mypetlion
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~113~~ ~~109~~ ~~106~~ 105 bytes
*-4 bytes thanks to @LambdaBeta!*
*-3 bytes thanks to @WindmillCookies!*
```
i;f(char*s,char*t){for(i=strlen(s);*t;t++)if(!strncmp(t,s,i))for(t+=i,puts("");*t^32&&*t;)putchar(*t++);}
```
[Try it online!](https://tio.run/##TU47DsIwDL1KyYCcNiwwVlwFyTIpWLRpiZ0BIc5ekhYE0/v4@dm0uxDNM7cd0BVjLW4Btc9ujMBH0dj7AGLbWlttGssdbLIZaJhAnTi2tiS1ObKbkgoYU7Knw367zSs2e6UR6rLcvuYBOUBuB9NFJOMWuHG4VIUo9rISf16Rx4B9RSlGH@jx5/U/kbMcdPzq9KkY85@oTKtK0UtFmKTcuidWX@EyQTHlsTc "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 12 bytes
*[Port of Arnauld Answer](https://codegolf.stackexchange.com/a/168646/78039)*
*-4 bytes from @Shaggy*
```
iS qS+V Å®¸g
iS Insert S value (S = " ") at beginning of first input (Implicit)
q split using
S+V S + Second input
Å slice 1
® map
¸ split using S
g get first position
```
[Try it online!](https://tio.run/##TY5LDsIwDESvYmVLuQyV2FsmVIYoof4sOADXYc26PVigDaisZt7YsueCN6uVexj73RHmx/ScXkOt4SxIV84DLMYwaTPx1JRLxgTkIjHT/S9LG3x2OVv5sX9PFDVBY2rkEhUIXZdfo7NFwHWCGjpYawTYH94 "Japt – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
#ʒηså}εsgF¦
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f@dSkc9uLDy@tPbe1ON3t0LL//9OKEpOzM/PSFUCMksScYggjNQVCZ@bnJeYoJJcWFaXmJVciieUgOEC1mXkl@TB@KdSI/OKSosSSzGQIr7QotVghObG0GGRXYWlmSapCIlgmsZgLRAEA "05AB1E – Try It Online") ([here](https://tio.run/##7VVBjtMwFN3PKb5SoUmlaZN2piNI1QUSmgWDWLBiV/3EP7EZ145sl7RIXII7wA1G7GHHYq5UnDQp01KQ0CzYjCIryrPz/N/7T3Y8wXREm03vx6e7r/b75493t7a4@vZlswmCIGTiPVi3ljQLSmRMqCKBeAopZjeF0UvFElgaGZ5y50qbRFFVVUO0zmjHaUHDTC8iscCCbGSFowiN0YqJ@cUknnM2LFVx2gelB4ZKQjcFRys3QCkKlYCk3CO5Vm5QkSi4SyDVkk2hEszxBDxHuZoCb@fOL8tV0D8BaGrOJFo7C5xwhq5Exin4TcakXEHsn@a/EIEbymfBX4Q0n1IX6@i1lhUpNX9FRq8D8LvUzC0KDZrA8275GaTCOA4ZR@POgGujbaZLAlQMOlKRoYRSG2dQuKC/xxWmBqL@SRh5ZTuFrZz7jpnaCd8cbRiZQe1fAiOv0mopGPTScTai8W7ebH07sqAz@OKyNnhnWL2yHgf971GeP83zxntfm8NUUlddyzSK4yfeY2f8YAdz43HcNO4xakejdi0W82s0DC0XqHZZ8zD8gh8Ytn2ybdpCW6LqhOw5o7RZoGztsuID@f6OamEvhC0lrr1NBhg5FJLYQQH3agujeod@GGG/DXb3egzCsSC8XEqB8zc6JePsLgcNCi36wBjscf23FGwPEQaCzYIsz97eVM9wnS3fnU948MdDb9uEhsDfWif/YOtP) is a demo for multiline strings)
### How does it work?
```
#ʒηså}εsgF¦ Full program.
# Split the first input by spaces.
ʒ } Filter the words by ...
ηså ... "Does the second input occur in the prefixed of the word?"
ε And for each valid word
sg Retrieve the length of the of the second input.
F¦ And drop the first character of the word that number of times.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
·B¬╤²*6&
```
[Run and debug it](https://staxlang.xyz/#p=fa42aad1fd2a3626&i=%221%22+%22He1in+aosl+1ll+j21j+1lj2j+1lj2+1ll+l1j2i%22%0A%22frac%22+%22fracking+fractals+fracted+fractional+currency+fractionally+fractioned+into+fractious+fractostratic+fractures+causing+quite+a+fracas%22%0A%22arm%22+%22Dumbledore%27s+army+was+fully+armed+for+the+impending+armageddon%22%0A%22href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2F%22+%22%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FNolwenn_Leroy%5C%22+title%3D%5C%22Nolwenn+Leroy%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Nolwenn+Leroy%28br+%2F%29%5Cn%28%2Fdiv%29%5Cn++%28div+style%3D%5C%22text-align%3A+right%3B+border-left%3A+1px+solid+%23b2c1e2%3B+border-right%3A+1px+solid+%23b2c1e2%3B+width%3A+446px%3B+padding%3A+1px+1px+0%3B+background%3A+%23eff8ff%5C%22%29%5Cn++++%28table+style%3D%5C%22width%3A+100%25%5C%22%29%28tr%29%28td+style%3D%5C%22width%3A+220px%5C%22%29%5Cn%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FKim_Kardashian%5C%22+title%3D%5C%22Kim+Kardashian%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Kim+Kardashian%28br+%2F%29%28span+style%3D%5C%22font-weight%3A+normal%3B+font-size%3A+11px%5C%22%29Display+her+detailed+horoscope+and+birth+chart%28%2Fspan%29%28%2Fa%29%28%2Fdiv%29%5Cn%28%2Fdiv%29%5Cn%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FJulia_Roberts%5C%22+title%3D%5C%22Julia+Roberts%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Julia+Roberts%28br+%2F%29%28span+style%3D%5C%22font-weight%3A+normal%3B+font-size%3A+11px%5C%22%29Display+her+detailed+horoscope+and+birth+chart%28%2Fspan%29%28%2Fa%29%28%2Fdiv%29%5Cn++++%28td+id%3D%5C%22cfcXkw9aycuj35h%5C%22+style%3D%5C%22text-align%3A+right%5C%22%29%5Cn++%28%2Fdiv%29%22&a=1&m=2)
Explanation:
```
j{x:[fmx|- Full program, implicit input: On stack in order, 1st input in X register
j Split string on spaces
{ f Filter:
x:[ Is X a prefix?
m Map passing elements:
x|- Remove all characters in X the first time they occur in the element
Implicit output
```
I could also use `x%t` (length of X, trim from left), which is equally long but [packs to 9 bytes](https://staxlang.xyz/#p=82df3febef7a1c2a28&i=%221%22+%22He1in+aosl+1ll+j21j+1lj2j+1lj2+1ll+l1j2i%22%0A%22frac%22+%22fracking+fractals+fracted+fractional+currency+fractionally+fractioned+into+fractious+fractostratic+fractures+causing+quite+a+fracas%22%0A%22arm%22+%22Dumbledore%27s+army+was+fully+armed+for+the+impending+armageddon%22%0A%22href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2F%22+%22%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FNolwenn_Leroy%5C%22+title%3D%5C%22Nolwenn+Leroy%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Nolwenn+Leroy%28br+%2F%29%5Cn%28%2Fdiv%29%5Cn++%28div+style%3D%5C%22text-align%3A+right%3B+border-left%3A+1px+solid+%23b2c1e2%3B+border-right%3A+1px+solid+%23b2c1e2%3B+width%3A+446px%3B+padding%3A+1px+1px+0%3B+background%3A+%23eff8ff%5C%22%29%5Cn++++%28table+style%3D%5C%22width%3A+100%25%5C%22%29%28tr%29%28td+style%3D%5C%22width%3A+220px%5C%22%29%5Cn%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FKim_Kardashian%5C%22+title%3D%5C%22Kim+Kardashian%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Kim+Kardashian%28br+%2F%29%28span+style%3D%5C%22font-weight%3A+normal%3B+font-size%3A+11px%5C%22%29Display+her+detailed+horoscope+and+birth+chart%28%2Fspan%29%28%2Fa%29%28%2Fdiv%29%5Cn%28%2Fdiv%29%5Cn%28div+style%3D%5C%22padding%3A+0%3B+background%3A+url%28%27https%3A%2F%2Fwww.astrotheme.com%2Fimages%2Fsite%2Farrondi_450_hd.png%27%29+no-repeat%3B+text-align%3A+left%3B+font-weight%3A+bold%3B+width%3A+450px%3B+height%3A+36px%5C%22%29%5Cn++%28div+class%3D%5C%22titreFiche%5C%22+style%3D%5C%22padding%3A+5px+0+0+6px%5C%22%29%28a+href%3D%5C%22https%3A%2F%2Fwww.astrotheme.com%2Fastrology%2FJulia_Roberts%5C%22+title%3D%5C%22Julia+Roberts%3A+Astrology,+birth+chart,+horoscope+and+astrological+portrait%5C%22%29Julia+Roberts%28br+%2F%29%28span+style%3D%5C%22font-weight%3A+normal%3B+font-size%3A+11px%5C%22%29Display+her+detailed+horoscope+and+birth+chart%28%2Fspan%29%28%2Fa%29%28%2Fdiv%29%5Cn++++%28td+id%3D%5C%22cfcXkw9aycuj35h%5C%22+style%3D%5C%22text-align%3A+right%5C%22%29%5Cn++%28%2Fdiv%29%22&a=1&m=2).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 31 bytes
```
L`(?<=^\2¶(.|¶)*([^ ¶]+))[^ ¶]+
```
[Try it online!](https://tio.run/##7VTRbtMwFH3fV1xlQktgbdpunSClQkiIBzbxwBMSsOLEN7GZa0fX7tIivmsf0B8rTpqUdQwktAdepshKcmwf33PukQmd1Gy42Vx8DV@9nF5@Hq1vwv6P9U30NPx0CeubL8@iqP3YbARhPg2Ec6VN4riqqj6zjowTOMd@ZuZx86tMsYoPQi6vwbqVwmlQMs6lLhIYTCBl2VVBZqF5AgtS4dFf6OScFWhjKx3GjMhoLmen48FM8H6pi6MItOkRlsjcBBwuXY8pWegEFOYeyY12vQplIVwCqVF8ApXkTiTgOcrlBEQ7d3JWLoPoAKCpOVPM2mngpCN8KzOBwW8yxuUSBv5p9oUM/sGX90ZVqPXsAsmsAvCn1MwtCg2awOtu@TGkkpyATDByxyAMGZuZEoFpDh2pzJiC0pAjJl0Q7XGFKUEcHYSxV7ZT2Mq57RjVTvjmGOJIvdq/BIZepTVKcjhMR9kQR7t52vp2z4LO4NOz2uCdYfXKetzp/yHm@fM8b7z3tTmWKuyqa5mGg8ET77EjP/idudFo0DTuMWr3Ru1czmfnjDizQjK9y5qH4Rf8wLDtk23TFtqS6U7InjPa0Jyp1i4rv6Pv77AW9kbaUrGVt4mAo2NSIb9TwK3awrg@IQpjFrXB7l6PQbgvCO8WSrLZB5MiObvLQYNCiz4wBntc/y0F20uEg@TTIMuzj1fVC7bKFt9OxiL446W3bUJD8BM "Retina – Try It Online") First line should be the desired prefix, the rest is the input text. Does not remove duplicates. Would be 25 bytes if any white space was a valid seprator. Explanation: We want to list the suffixes of valid prefixes. The `[^ ¶]+` matches the suffix itself. The prefix of the regexp is a lookbehind that ensures that the prefix of the suffix is the input prefix. As a lookbehind is evaluated right-to-left, this starts by matching the prefix (using the same pattern but inside `()`s to capture it), then any characters, before finally matching the prefix on its own line at the beginning of the input.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~24~~ 21 bytes
```
tṇ₁W&h;Wz{tR&h;.cR∧}ˢ
```
[Try it online!](https://tio.run/##TU45EoIwFL3KnxRWjDOh9QLWNBQMRYwRgplkzFIgQyGFS@cZbGxtLPQKngIugiw62vy3/O0tNKFpLlTit0WzvzVVVT9PZX0/t7Z@HJpqF07SWbgtbNDhlAbN8Vq@Lm0bQRShVbeMYg8GsuYygZ5YIsxI2HJEriQRQJ3WTNL8zxM/0c1yadVXu88JZawmltNROc0MUOJM/2vjuGVAhg4xKAavz4SHQHOGuQSijAAsBGQ@zjqS@WMdPIEzn6M4fgM "Brachylog – Try It Online")
Could have been a few bytes shorter if there was variable sharing with inline predicates.
Input is an array with the prefix as the first element and the text as the second element.
```
tṇ₁W % Split the text at spaces, call that W
&h;Wz % Zip the prefix with each word, to give a list of pairs
{ }ˢ % Select the outputs where this predicate succeeds:
tR % Call the current word R
&h;.c % The prefix and the output concatenated
R % should be R
∧ % (No more constraints on output)
```
[Answer]
# IBM/Lotus Notes Formula, 54 bytes
```
c:=@Explode(b);@Trim(@If(@Begins(c;a);@Right(c;a);""))
```
Takes it's input from two fields named `a` and `b`. Works because Formula will recursively apply a function to a list without the need for a `@For` loop.
No TIO available so here's a screenshot:
[](https://i.stack.imgur.com/8KNh2.png)
[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")
Full program. Prompts for text and prefix from stdin. Prints list to stdout.
```
(5⌽'(\w+)\b',⎕)⎕S'\1'⊢⎕
```
[Try it online!](https://tio.run/##7VXdbtMwFL7vUxxlQk5FuzTdOkGqXiAQQgxxwYTExaTqJHYad64dbIe0ewBAE0Lc8ALwHLxMX2Q4Sdu1g01Cu@BmiZwcHx@fn@98sjEXXbpAoSaXy8@f8kt/sPzyi/in5cP2aUw6y6/f226ckNOQLC9@OLEyu4T6yVvkBQu5BFRGQCgETPvh1AnTfvOtdSKc9jlpkZC0NttSjckZlxOoBIvCNAKjzZ8riQKSQmsmk8WWTlxNnC2XVq3nxcqFMlaj5UkzKzQzkGBhqljvC24ZYL2ChjRZbCXlU/4BjF0INvJypNTtiaA3hNjlOtGqkDSCQgufkMza3ERBUJblPrqAymZsxvYTNQv4DCfMBMaFClBrJSkfHw5644zu53JCSBuk6mqWM7RDsGxuuyj4REYgWOo0qZK2WzI@yWwEsRJ0CCWnNovAOcnnQ8hWawdH@dxrk47sEIA680SgMSPPcqvZc55kzPujmEE@h557670@QqZZOvJuqaaeOm4sgtdKlEzK8Sum1cIDF6XyvNJCrY3gydq8AzHXNoMkQ207kCmtTKJyh76ksHbKE9fkXGnXMG699o4vP9YQNOX5gatup9JVWdvo6QoV1yqlKdPdCssIQletUYJT2Iv7Scj6m3XdYPgXgzXYh0cV2BvgKstqXGPDHkvTR2m66YPLz2Is2DrDlbew13vg8LbaDXptrd/vbRp5T8BbCHjMZ@Nj1BRNxlFuGOjUcKW@IwV3nTUc9E2Ocl3IDjpS6RmKFWSGnzPX6bAq7Bk3ucCFg0oDZRa5cIfVbgJbuflBFaHtB9jeovq2eE@Lm2nxshAcx29UzLQ1G1bUWlhp70iKHV//lRPNAePuPTrykjR5d1Y@xkVSTA8GmXfjoXjVjMbR8uKnXH785m7yt09P3NHUIv@ANvkN "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt (for text)
`⊢` yield that (separates `'\1'` from `⎕`)
`(`…`)⎕S'\1'` PCRE Search and return list of capture group 1 from the following regex:
`⎕` prompt (for prefix)
`'(\w+)\b',` prepend this string (group of word characters followed by a word boundary)
`5⌽` rotate the first 5 characters to the end; `'\bPREFIX(\w+)'`
[Answer]
# [C (clang)](http://clang.llvm.org/), 107 bytes
```
i;f(s,t,_)char*s,*t,*_;{i=strlen(s);_=strtok(t," ");while((strncmp(_,s,i)||puts(_+i))&&(_=strtok(0," ")));}
```
[Try it online!](https://tio.run/##TY9NbsMgEIX3OcUoiwhsKiXdUp@ksqwRxc4oBKcwtKqSnN0FnP6wgO/Nm8eAeTIO/bQspEcRFatBmiOGJqqGVTPoK3WRg7NeRKmHwjyfBKstbKX@PJKzQuSiN@eLGFRUJG@3S@Iohpak3O3Eb2ZfM1Lq@0Ke4YzkRQEMk1FQhkKT@eO1l3DdQF7FJV1xnAMIgg4OGgheaihT2z3L6tceUePUK1ihPfRSb6ofLKfgYa8392UZA5q6nchPUIDRxRXs23rS7NGBSSFYb77@1dyfyL35ifOPTo8r5vxhZDKrSsFGMJhimfWeiC1gdTDm9CPhvwE "C (clang) – Try It Online")
Description:
```
i;f(s,t,_)char*s,*t,*_;{ // F takes s and t and uses i (int) and s,t,u (char*)
i=strlen(s); // save strlen(s) in i
_=strtok(t," "); // set _ to the first word of t
while( // while loop
(strncmp(_,s,i)|| // short-circuited if (if _ doesn't match s to i places)
puts(_+i)) // print _ starting at the i'th character
&& // the previous expression always returns true
(_=strtok(0," "))) // set _ to the next word of t
; // do nothing in the actual loop
}
```
Has to be clang because gcc segfaults without `#include <string.h>` due to strtok problems.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + grep, 20 bytes
```
grep -Po "\b$1\K\S*"
```
Prefix is given as a command-line parameter, and input text is piped in via stdin.
[Try it online!](https://tio.run/##TY4xDsIwDEV3TmFFTEgZOAcLEmsW15g2IkrAdgYk7h7apggmv/dt2R5Qp6Zs4D24myC5HdNUOt9jHmEBw6Qd@NprLBkTUBXhTK@/LP1kno3ZytfrtqKoCVqkblVYgbDqcutZozHg2kF18IbQRuEH@PP8Uhj2x3AKl4Nr7QM "Bash – Try It Online")
[Answer]
# PowerShell 3.0, ~~60~~ ~~62~~ 59 bytes
```
param($p,$s)-split$s|%{if($_-cmatch"^$p(.*)"){$Matches[1]}}
```
Lost some bytes suppressing the cmatch output. Had a janky solution that gained some by purposely causing duplicates. But it also threw redlines if it didn't match on the first but that is not fine now that I think about it. +2 bytes to fix it though.
[Answer]
# MATL, 17 bytes
```
Yb94ih'(.*)'h6&XX
```
[Try it on MATL Online](https://matl.io/?code=Yb94ih%27%28.%2a%29%27h6%26XX&inputs=%27He1in+aosl+1ll+j21j+1lj2j+1lj2+1ll+l1j2i%27%0A%271%27&version=20.9.1)
### How?
`Yb` - Split the input at spaces, place the results in a cell array
`94` - ASCII code for `^` character
`ih` - Get the input (say "frac"), concatenate '^' and the input
`'(.*)'h` - Push the string `'(.*)'` into the stack, concatenate '^frac' and '(.\*)'. So now we have `'^frac(.*)`, a regex that matches "frac" at the beginning of the string and captures whatever comes after.
`6&XX` - Run regexp matching, with `6&` specifying 'Tokens' mode i.e., the matched capture groups are returned instead of the entire match.
Implicitly output the results.
[Answer]
# JavaScript (ES6), 57 bytes
Takes input in currying syntax `(text)(prefix)`. Does not remove duplicates.
```
s=>p=>(' '+s).split(' '+p).slice(1).map(s=>s.split` `[0])
```
[Try it online!](https://tio.run/##7VVNi9swEL3nVwxeSmy6iePsB61DFgqllG7poadCKclEkmNlFcmV5E3SP5@OP5JNdtNS2EMvi7GtmZHfzLx5yAu8R8esLHxPGy622XjrxjfF@CbsQve1i/quUNLXRkGGkkyESdRfYhHSPteEpzD9PvgRbZnRzijRV2YedgCyMPgoEqkBjVOQKAWLYbKgxWLYPGufShZDGURhkARRJ@o8xcgssjup51AtPCrXLARv3tJoVMBKa4VmmwOfejBor9Te7OyyhTDOW/SSNVZphQOGpaty/SylF4B1BF1VXrU6XeE05PIenN8oMQ4K5JwAUhiMYEaFz60pNU@htCrs5t4XLo3j1WrVR0pufC6Wos/MMpZLnAsXO0obo7VGczm5vBpMct4v9LwbgTY9KwqBfgRerH0PlZzrFJTIyJMZ7XsrIee5T2FmFB/BSnKfp0AYxXoEeRu7uC7W1AVAXTNT6Nw48NJb8UGyXARP2rgq1jCgq/4uRMityMbBXxqpTeJmE38xaiW0nnwW1mwCoCwVcuuF2pvCu932c5hJ63NgOVp/DrmxxjFT0BA0hx2oZDTrwliam/RBdIQVzizEUSeMqbN9h207h4zZigkajrFc2F7FXwoJdUlDlRzOZkOWiOE@bhveTmzYEXx5XRG8J6zaWd2P5n8msuxNltXcU20eZ0rsqmuRksHgFXHsLd38UWw4HNSDe5HaSandyuXkFi1Hl0vUe62RGx7czxTbMVijttAVqHeNHDGjjV2iauly8peg@SZVY@8lnZm4IZoscOFRKjqdjgs4qC2MqwxRGGPUCnv3ehHCKSF8KpXEyVczE9a7vQ5qL7TeZ8rgCOu/qaA5ROi3xscBy9i3u9Vb3LBycXGVB3889Joh1ADTiJTx77R26ce3/Q0 "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~64~~ 59 bytes
*-5 bytes from @Shaggy*
```
a=>b=>b.match(eval(`/\\b${a}\\w*/g`)).map(x=>x.split(a)[1])
```
[Try it online!](https://tio.run/##JYlBCsIwEEWvEoqLGcGUZJ@uvYMROo1pTRibYkotiGePQeHzeLwfaaPsnmFZT3O6@TKaQqYb6uSDVncHvxFD31o7HN70sfZ1bKcesb4L7KbbZV44rEB4UVcsLs05sZecJhhBITRnr8IsKGUWillErWKVqP/8NVZRhwaxfAE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
```
p#x=[length p`drop`y|y<-words x,and$zipWith(==)p y]
```
[Try it online!](https://tio.run/##TY5BjsIwDEX3nOJLsAAJbtCymUOwQEhYSWgtMk5IHNEi7l5aCprZ2P/ZX99uKV@d98MQl1199E4abRHPNoV47p99tbuHZDO6LYldPTgeWNt1XW8i@tPwSyyoYcMCOMZtd0K1g2dxGdVqj8bpTxB1onk0xMSiWEcs0W2GSyKzmMqVpcEklHyehbNz5yDkYUpKTkz/b@b/YPSOseHL5RMRsiZSNjOVNH5kqOTp1q2wOtB7Q/kF "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
Pretty much just a port of the [Haskell answer](https://codegolf.stackexchange.com/a/168674/48198):
```
m↓L⁰foΠz=⁰w
```
[Try it online!](https://tio.run/##7VRBbtswEPzKQkERGYgt24mDVkYOBYoemqCHnnowYFDiSmRNkcKSruzceukH@oE@oS/pI/IRl5Ilx3YKA0UOvQQCIWmXO9yZHVAs7WKzKR6@/7h7@PYrM79/3t/4j2qz2QSCMLuZBcK50sZRVFXVgFlHxgkscJCaImp@lcnXUbAJQi6/gnVrhb6oZJxLnccwnELC0kVOZql5DEtS4fkJRFmwHG1kpcOIERnN5fxqMpwLPih1ft4DbfqEJTI3BYcr12dK5joGhZmPZEa7foUyFy6GxCg@hUpyJ2LwGOVqCqLNXV6Xq1nQm2mApu1UMWt92046wvcyFTgLnnKZlCsY@mdbHDL4F4U@GlWh1vM7JLP26P6oBr2NQxOP4W1XcAGJJCcgFYzcBQhDxqamRGCaQwcrU6agNOSISed7OgALE4LIcwwjT/GRa0drXz6qZfGTMsSR@rWYMYw8W2uU5HCWjNMRjnd52or4lw2d2lfXtdo74eqd9Toywxlm2essawfh23MsUbhrsAUbDYevarkd@cWPs@PxsB3li/9O@u9WFvNbRpxZIZneM6BPwGPiuQ48RNtaMLQl0zs6ByJpQwVTrXJW3qOf96ih907aUrG1l4yAo2NSIT/qYa@9MKrP6IUR63V2371ffHHKFx@WSrL5J5MgObtniyYObfy5rjgA@5@m2F4zHCT3h6ZZ@nlRvWHrdPnlciL2pH1yN3ZDaWCCPw "Husk – Try It Online")
## Explanation
```
m↓L⁰f(Πz=⁰)w -- prefix is explicit argument ⁰, the other one implicit. eg: ⁰ = "ab" and implicit "abc def"
w -- words: ["abc","def"]
f( ) -- filter by (example w/ "abc"
z=⁰ -- | zip ⁰ and element with equality: [1,1]
Π -- | product: 1
-- : ["abc"]
m -- map the following
↓ -- | drop n elements
L⁰ -- | n being the length of ⁰ (2)
-- : ["c"]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḳœṣ€ḢÐḟj€
```
A dyadic link accepting the text (a list of characters) on the left and the prefix (a list of characters) on the right which yields a list of lists of characters (the resulting suffixes).
**[Try it online!](https://tio.run/##TU27DUIxEFsl@zDFKRxwj5CIS1K8lgmQGAAJChoqqrz6iUHCIkc@ICgs22frPKAxo0hOj@cpT9fX4Z7TZT7mdB6Klvm2EIl2xaC3BpfKuiorNsi4g4CqZWTXTQQwvotSbkzOglE6MqPV49/N/Ezpkg3u6@PnhfOBIZDuLjJ6pSH6urWPVKahJdDrFRSk0hs "Jelly – Try It Online")** (footer joins with spaces to avoid full-program's implicit smashing)
Note: I added three edge cases to the string in the OP - unfrackled and nofracfracheremate to the beginning, which should not output and fracfracit to the end which should output fracit.
### How?
```
Ḳœṣ€ḢÐḟj€ - Link: text, prefix e.g. "fracfracit unfracked", "frac"
Ḳ - split (text) at spaces -> list of words ["fracfracit", "unfracked"]
€ - for each (word):
œṣ - split around sublists equal to (prefix) ["","","it"] ["un","ked"]
Ðḟ - filter discard items for which this is truthy:
Ḣ - head
- -- Crucially this modifies the list: ["","it"] ["ked"]
- -- and yields the popped item: "" "un"
- -- and only non-empty lists are truthy: kept discarded
- ...so we end up with the list: [["","it"]]
€ - for each (remaining list of lists of characters):
j - join with the prefix "fracit"
- ["fracit"]
```
---
**previous 11 byter:**
```
Ḳs€L}Ḣ⁼¥ƇẎ€
```
Also a dyadic link as above.
[Try it online!](https://tio.run/##TU27DQIxDF0l@8ASVjAQMI5wkuIKCmjoGAIJ0VBRnRAVSOyRWyTkA4Li6X1lL5CoSyn2VzfsLuNN7I/D9v44vfbxdshJep5HKQWeCugl4USxLbJgjoIr8KhqZ3hWhQdyTeRxZWMZSOkggqy7v4x@Jm8Ne/v14XPCOi/gjW4uCDqlIbjyax1Mfg21gTYvMD4VegM "Jelly – Try It Online")
[Answer]
# Perl 5 with -asE, ~~23~~ ~~22~~ 21 bytes (?)
```
say/^$b(.*)/ for@F
```
[Try it online!](https://tio.run/##XY1BC8IwDIX/Sg4eFNmmh51E8OTPELIuk2BtZ9IK@/PWlQ4cnvK9l7yXkcS2KSrBu62Ph1NSnJrbptvW@10Dg5fLNaVB0DzY3SFDQKsFqC@TvUMLJoqQM9PKsz8x37ILHpSeXK1SC8al0msQDGyKikIKBqPm36/IgQCh5@Evj5qq7pwpVR8/5s3soH4B)
Can be [run as a commandline one-liner](https://tio.run/##XY3BCsIwEER/ZQ5CFYn5AsGLfoawSVNdjInuJod@fbS0YPE0b4adHUd6b81WFes42VeQCEN6Rqc02uvGbQ/7ncWQ5XTpYAyMOw5CHjCtTfDgdMMEhaLOEPpZOSeK8FUkJD@usvgz31tOJUPDk82qtWBdXmYtQoX97KoEhaeq0/a7cgkg9Dz89Uk/ "Bash – Try It Online")
as `perl -asE 'say/^$b(.*)/ for@F' -- -b=frac -`, or with a filename in place of the last `-`.
Or from a script file, say `perl -as -M5.010 script.pl -b=frac -` (thanks to @Brad Gilbert b2gills for the TIO link demonstrating this).
The code itself is 18 bytes, I added 3 bytes for the `-b=` option which assigns its value (the prefix input) to a variable named `$b` in the code. That felt like an exception to the usual "flags aren't counted" consensus.
`-a` splits each input line at spaces and places the result in the array `@F`. `-s` is a shortcut way of assigning a command-line argument as a variable, by giving a name on the command-line. Here the argument is `-b=frac`, which places the prefix "frac" in a variable `$b`.
`/^$b(.*)/` - Matches the value of `$b` at the beginning of the string. `.*` is whatever comes after that, until the end of the word, and the surrounding parantheses capture this value. The captured values are automatically returned, to be printed by `say`. Iterating through space-separated words with `for @F` means we don't have to check for initial or final spaces.
[Answer]
# [Perl 6](https://perl6.org), 30 bytes
```
{$^t.comb: /[^|' ']$^p <(\S+/}
```
[Test it](https://tio.run/##7VVRb9s2EH7XrzgoziTBkmW7TbDJcZABxbCtRQdsexgQOwYtURZTmlRJKrbWpX9o/2J/LDtKsmsn2YChD3spDFPH4913d9@dxJIqfv5QaQp354N04jjrGr5KZUZh@vChd2MGqVwvE4ivb/7wwJv3bkq48Ge/9OP7B7S8MlQbmILmlSoHuuTM@O5MRFE0E24wWJMygQ8OwDrGBcD7QZSVgVLRnG0TcD34CB6uvYtWdYlQ17O3/bnTmM9E3zn0M3RrEg9mut9qD/ztUeM9eOr8U2XQOwG/MQ88uL66kI2u8biIrsP5ZX8@78PpKXgheOgWT3D5uM8rtHITA6W//tz7D94wbZx7x7EE/opcTJySEwH9hhhkM5eqIym6BL/XwoU9CxVetSCBJegELMKgEux9RcFIUHQt7yhkFXKaEkRAI6ajjNKS12AbdIwWdL4hdLB7YVBii537h0fcj1zHOaDVcdzv6YgJIFJzGHEOt@PRLQq343ZtdHx0O2bouKeU8xCsSbMGEIFFEDVgzHVliGFSOA6Owy7WPnyuSHqcAWAKVvuOiRVYwRCuW4Fm7RPRCIe0UoqKtD7Q8U8btGUCCez2VQchtVGYTtruKkU1pKTSNtb7ihkKpDkh@rA6m0oINg9caYZLE2335HUrdSeVtdrFQdEGCYHo4HkGChSmbmFMqZM43mw2A4K@0hR0Te1bFzdbLld1/JQoP2N3oE3N6dQtSZZhogkMJ7BE/lZKViJLoFLc9/4Fn63JiupYY/UxUUqKjC1eng0XRTYoxcoLQMhI0ZISM2kCR4SzlUiA0xw1uRQm2lC2KjCjpeTZBDYsM0UCiFFuJ1B0Zy/Oy60b4Pg2OaecaD11DTOKfsfSgrpPyjgrtzDEX@PnE/gPRL2VfEOFWLyhStYuNsVY5E4LjTaBb3fmISyZMgWkBVH4vhRSSZ3KEmdBZLADxbePQykVtpUZNzjC8pcK4sDxY6xsX2FXziFjyjKBzZEqoyqy/CUwwiq15CyDk@U4HdHx/ly1vD1jsCP45bkleE@YtbT/R/0/oXn@dZ433GNuhiw53WXXIY2Gw1Pk2Cj8Z4/OxuNh07gvo/bsqL1m68VrojKiC0bEftZQDZ/Unzlsx2DttPm6xAumK@SIGSHVmvCOLs1@p9jfkS3sFcObmdRIk4KMGsI4fiSPEzjIzY9thMCPSdAN9u7xZRCeG4QfK87I4me5pMro/Rw0Wui0nzkGR1j/2xS0HxG8XbOpm@bpb@8235A6rW5fnBXuP3702iY0AIcX6/F3OoRHL1MIx6QGfwM "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder params $p, $t
$^t.comb: # find all the substrings that match the following
/
[ ^ | ' ' ] # beginning of string or space
$^p # match the prefix
<( # don't include anything before this
\S+ # one or more non-space characters (suffix)
/
}
```
[Answer]
# Java 10, 94 bytes
```
p->s->{for(var w:s.split(" "))if(w.startsWith(p))System.out.println(w.substring(p.length()));}
```
Try it online [here](https://tio.run/##TVC7UgMxDKzvvkJzlc0QfwCBa5iho0pBwVAoji848dnGkhMymXz74XswUEkrrXdXPuAJV4fdcbB9DInhULDKbJ3qstdsg1d367qOeeusBu2QCF7RerjW1TIkRi7lFOwO@rISG07W798/ANOe5MisXhaxx3l3D8/BU@5NWgZtC5S7zn4bgicY4qqlVXvtQhInTHB@IEXRWRYNNFLaTpxVcU1Mb5Y/RZRycyE2vQqZVSx67PxIyVua1EVUzvh9oUop17ehqtYl06@hwhjdRTRdQt1IhVqbyDM8lscwNoyO5sbs5lqOQQc6p2S8vvybuT9QuCVL@MV5kQgl1fRlE8qp3Kwx0@j1lS0bwGmD1MiS81bfhh8).
Ungolfed:
```
p -> s -> { // lambda taking prefix and text as Strings in currying syntax
for(var w:s.split(" ")) // split the String into words (delimited by a space); for each word ...
if(w.startsWith(p)) // ... test whether p is a prefix ...
System.out.println(w.substring(p.length())); // ... if it is, output the suffix
}
```
[Answer]
# [Small Basic](http://www.smallbasic.com "Microsoft Small Basic"), 242 bytes
A Script that takes no input and outputs to the `TextWindow` Object
```
c=TextWindow.Read()
s=TextWindow.Read()
i=1
While i>0
i=Text.GetIndexOf(s," ")
w=Text.GetSubText(s,1,i)
If Text.StartsWith(w,c)Then
TextWindow.WriteLine(Text.GetSubTextToEnd(w,Text.GetLength(c)+1))
EndIf
s=Text.GetSubTextToEnd(s,i+1)
EndWhile
```
[Try it at SmallBasic.com!](http://www.smallbasic.com/program?ZKM462) *Requires IE/Silverlight*
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda i,j:[w.split()[0]for w in j.split(i)if len(w)]
```
[Try it online!](https://tio.run/##TY1LDsIwDESvYnXVSBVCLJE4SenCpAm4hKQ4jqKePvSHYDXzxtbMOMkj@FOxl2tx@Lr1CNQM5zYf4uhIatUeOxsYMpCHYQ9JkQVnfJ1VV0YmL2DryjLqqlnlSf4OixF0cTOm35SCRwc6MRuvp7/M/WD@nTvDl9NeEaIwCumNEpsIGlNctt6JxACuF4yVKh8 "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
hṇ₁∋R&t;.cR∧
```
[Try it online!](https://tio.run/##TU@7TsQwEPyVlQtojpOSFgkaCuproxR7zpI4OPbhh6KAKEgBh2go@QNamivgb5IfCXYCgsLrmfVoZrw1yKtO6jKd7loGJ2fA2vPx8WPs@@HwNnw93w@H16kaPp/G/mHcv2yO3Omab8b9@zRlGbukRChAbSUkUkKdJnUAdbrMeSeTOhVsxRKWrzJ2FfKuhSohAofSLoCK5RZaoQTujSHFu387@UeCViinf7n/sdDWGXSCL8wbssDR25h144UjwPkFbegSwVxnJwktgUUlnLglcFU8whTgyLpgYGkd9K6a1Re@2UoqtKFjC2iaDloM6T62CzR@QpvZQzQ7UkXMDnssqSi0Cj6BsDz/Bg "Brachylog – Try It Online")
Takes input as `[text, prefix]` through the input variable, and [generates each word](https://codegolf.meta.stackexchange.com/a/10753/85334) through the output variable. This was originally sundar's answer, which I started trying to golf after reading that it "could have been a few bytes shorter if there was variable sharing with inline predicates", which is possible now. Turns out that generator output saves even more bytes.
```
R R
∋ is an element of
h the first element of
the input
ṇ₁ split on spaces,
& and the input
t 's last element
c concatenated
; with
. the output variable
R is R
∧ (which is not necessarily equal to the output).
```
My first two attempts at golfing it down, using fairly new features of the language:
With the global variables that had been hoped for: [`hA⁰&tṇ₁{∧A⁰;.c?∧}ˢ`](https://tio.run/##TU9LTsMwEL3K4AVsSqVki0SFxKJ3iLKYJkPi4NjFH0Wl6qJdQIFbICG23cIVOEV9kWAnIFjY897zzLznhcaiXglVpb3fv6w7BueXwLqZfzj43e74@XSy8c9vfX3lt4dTe/x49Lvt2u/fI7@YFrMAN1@vfZ9lLGETNqeES0BlBCRCQJMmTQBNOt6DJpIm5SyfZOwmeIeZWG65rCACi8KMgMqxciVRQOG0Jlms/mnij4ReLq365e5nhTJWo@XFyJwmAwU6E73uHLcEOLygYXnGbB2yLAWhITAoueX3BLaOh@sSLBkbpg1Nh@yo29B@7dqFoFJpOjMQpBV0GLxdzBZo/ILSwxLeLkmW0TnoWFFZKsny/Bs) (18 bytes)
With the apply-to-head metapredicate: [`ṇ₁ᵗz{tR&h;.cR∧}ˢ`](https://tio.run/##TU@7TsQwEPyVlQtojpOSFgkaCuproxR7yZI4OPbhh6Lc6QpS8Ojo6Gloaa6AX@Arkh8JdnIICu/OjPcxu9aYla1QRTzuGgZnF8Cay@HhY@i6/ut53x9exv7zceju@8PrdmdXJ@X5MlsNT@/777dxTCBJ2I0fwdIFTOCWywICsCjMDCifM1cSBWROa5JZ@08Tf8TXcmnVL3fHEcpYjZZnM3OaDGToTNh157glwOkHDUthETxFk6FrirgEVEZAJARUcVR5UMVznDQRVTH3xb7Hlj6zjSA0BAYlt3xLYMvwuM7BkrF@raHlXI@6Dg1Xrl4LypWmUwNea6FBb9uFszwN1ys9jeH1hmQeTHsdC8pzJVma/gA) (16 bytes)
And my original solution:
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
ṇ₁ʰlᵗ↙X⟨∋a₀⟩b↙X
```
[Try it online!](https://tio.run/##TU87TsQwFLzKkxuaBSk5ADQUHAEpSvGSPHYdvPbij6IFIUGKBURDB1TbQrdNCjgCt4gvEuwEBIWfZ8ajmedCY7lYCzVPh6uGwf4hsObIb3a@bfvupf98uO67p6H/uPPt7ddO9N2z37ye@u2bv39E39747XsRlWHIMnZCCZeAyghIhIA6TeoA6nSaoyaSOuVsxhKWzzJ2FtrPuZxDBBaFmQBV082VRAGl05pkuf6niT8SvFxa9cvdT4QyVqPl5cScJgMlOhO7Lhy3BDi@oAm7RDCusxKEhsCg5JZfEthFPFxXYMnYEGDoIPjtYnQfu2UhqFKa9gygXq6hwdDu4naBxk8oPWbw5YpkFbuDjnOqKiVDTiAsz78B "Brachylog – Try It Online")
Same I/O. This is essentially a generator for words with the prefix, [`ṇ₁ʰ⟨∋a₀⟩`](https://tio.run/##TU87TsQwFLzKkxuaBSk5ADQU3CFK8TZ5JA6OvfijKCAkSMFHNJR020K3zRZwBG4RXyTYCQgKP888j2bGa41F3QtVpdN1x@DwGFh34u93fhjG/ev4@XQz7l@m8ePBD3dfO79984/P6Idbv32fpixjZ5RwCaiMgEQIaNKkCaBJlznvRNKknK1YwvJVxs5D4AWXFURgUZgFULncXEkUUDitSRb9v534I0HLpVW/3P1YKGM1Wl4szGkyUKAzMevScUuA8wua0CWCuc5GEBoCg5JbfkVg63i4LsGSscHA0FHQ23pWn7p2LahUmg4MoG576DCku9gu0PgJpWcP3m5IljE77LGislQy@ATC8vwb), modified to remove the prefix.
```
The input variable
ʰ with its first element replaced with itself
ṇ₁ split on spaces
ᵗ has a last element
l the length of which
↙X is X,
⟨ ⟩ and the output from the sandwich
⟨∋ ⟩ is an element of the first element of the modified input
⟨ a₀⟩ and has the last element of the input as a prefix.
The output variable
⟨ ⟩ is the output from the sandwich
b with a number of characters removed from the beginning
↙X equal to X.
```
A very different predicate with the same byte count:
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
hṇ₁∋~c₂Xh~t?∧Xt
```
[Try it online!](https://tio.run/##TU87TsQwFLzKkxuaBSk5ANtQcISVohRv40fi4NiLP4oCYiVSwCIaSm5AS7MF3Ca5SLATEBS2Z94bzYy3Bouqk7pMp7uWwek5sHY9Pn6MfT8c34av5/vh@DpVw@fT2D@Mh5d9ETabau/W4@F946Ypy9glJUIBaishkRLqNKkDqNPlnmcyqVPBVixh@SpjVyH0WqgSInAo7QKIL6/QCiUU3hhSRfdvJv9I0Arl9C/3PxbaOoNOFAvzhiwU6G3MuvHCEeC8QRu6RDDX2UlCS2BRCSduCVwVjzAcHFkXDCydBb2rZvWFb7aSuDZ0YgFN00GLId3HdoHGT2gze4hmR4rH7DDHkjjXKvgEwvL8Gw "Brachylog – Try It Online")
Same I/O.
```
∋ An element of
h the first element of
the input variable
ṇ₁ split on spaces
~c can be un-concatenated
₂ into a list of two strings
X which we'll call X.
h Its first element
~t is the last element of
? the input variable,
∧ and
Xt its last element is
the output variable.
```
[Answer]
# [Red](http://www.red-lang.org), 62 bytes
```
func[p s][parse s[collect[any[p keep to[" "| end]| thru" "]]]]
```
[Try it online!](https://tio.run/##TU07DsMwCN1zCuQbOGNP0LmrlQE5pHWC7BTsIVLunrp1fwzwPvAQGo8LjW7optMxlejdCjq4FUUJ1PnETD47jFs1FqIVcnIGzA4Ux2GHfJNS6VDrWCXEDBMYW5Uz2RABkzJYZph7O1cw962/NLZzH0z3PZsEvWljCfEKT5CRtQEa2wwpIoMvIhT99qfxj9Tdmpk@vLwjkmbBHHxjRUjBY9Hnr3sJmQBfDqo5Hg "Red – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~21~~ ~~20~~ ~~18~~ ~~17~~ 16 bytes
```
AQVcH)IqxNG0:NG"
```
[Try it online!](https://tio.run/##K6gsyfj/3zEwLNlD07Owws/dwMrPXen/f6W0osRkJR0wlZ2Zl64AYpQk5hRDGKkpEDozPy8xRyG5tKgoNS@5EkksB8EBqs3MK8mH8UuhRuQXlxQllmQmQ3ilRanFCsmJpcUguwpLM0tSFRLBMonFSgA "Pyth – Try It Online")
-1 by using `V` instead of `FN` because `V` implicitly sets `N`
-2 after some further reading about string slicing options
-1 using `x` to check for the presence of the substring at index 0
-1 using replace with "" for getting the end of the string
I'm sure this could use some serious golfing but as a Pyth beginner, just getting it to work was a bonus.
**How does it work?**
```
assign('Q',eval_input())
assign('[G,H]',Q)
for N in num_to_range(chop(H)):
if equal(index(N,G),0):
imp_print(at_slice(N,G,""))
```
[Answer]
# Excel VBA, 86 bytes
Takes input as prefix in `[A1]` and values in `[B1]` and outputs to the console.
```
For each w in Split([B1]):?IIf(Left(w,[Len(A1)])=[A1],Mid(w,[Len(A1)+1])+" ","");:Next
```
] |
[Question]
[
Inspired by a real-life scenario, which I have asked for an answer to here: <https://superuser.com/questions/1312212/writing-a-formula-to-count-how-many-times-each-date-appears-in-a-set-of-date-ran>
Given an array of timespans (or startdate-enddate pairs), output a count of how many timespans cover each day, for all days in the total range.
For example:
```
# Start End
1 2001-01-01 2001-01-01
2 2001-01-01 2001-01-03
3 2001-01-01 2001-01-02
4 2001-01-03 2001-01-03
5 2001-01-05 2001-01-05
```
Given the above data, the results should be as follows:
```
2001-01-01: 3 (Records 1,2,3)
2001-01-02: 2 (Records 2,3)
2001-01-03: 2 (Records 2,4)
2001-01-04: 0
2001-01-05: 1 (Record 5)
```
You only need to output the counts for each day (in order, sorted oldest-newest); not which records they appear in.
You can assume that each timespan only contains dates, not times; and so whole days are always represented.
## I/O
**Input** can be any format that represents a set of timespans - so either a set of pairs of times, or a collection of (builtin) objects containing start- and end-dates. The date-times are limited to between 1901 and 2099, as is normal for PPCG challenges.
You can assume the input is pre-sorted however you like (specify in your answer). Input dates are inclusive (so the range includes the whole of the start and end dates).
You can also assume that, of the two dates in any given range, the first will be older or equal to the second (i.e. you won't have a negative date range).
**Output** is an array containing the count for each day, from the oldest to the newest in the input when sorted by Start Date.
So, the output for the above example would be `{3,2,2,0,1}`
It is possible that some days are not included in any time range, in which case `0` is output for that date.
## Winning Criteria
This is code-golf, so lowest bytes wins. Usual exclusions apply
## Pseudo-algorithm example
```
For each time range in input
If start is older than current oldest, update current oldest
If end is newer than current newest, update current newest
End For
For each day in range oldest..newest
For each time range
If timerange contains day
add 1 to count for day
End For
Output count array
```
Other algorithms to get to the same result are fine.
[Answer]
# JavaScript (ES6), 85 bytes
Takes input as a list of `Date` pairs. Expects the list to be sorted by starting date. Returns an array of integers.
```
f=(a,d=+a[0][0])=>[a.map(([a,b])=>n+=!(r|=d<b,d<a|d>b),r=n=0)|n,...r?f(a,d+864e5):[]]
```
[Try it online!](https://tio.run/##ncyxDoIwGATgnaeoE20oTQUxxlBcfIumww8tRoMtKUQX3r2Cs5pIcstd8t0NHjA0/tqPqXXahNAKDFSLBCRXc4ioJLA79BhLoPXSbSI22E9ClzXVJUy6qgn1wgpOJksZY/7ULh/JYb8zBTlKpULj7OA6wzp3wS2WEULSmic6w2hwnHG@Td@JCUWfd0X/NNkKk/8w@QpTfDHzriJFSHgB "JavaScript (Node.js) – Try It Online")
or **[84 bytes](https://tio.run/##nZBBDoIwFET3nKKuaENpKogxhuLGWzRdfGgxGiwEiELC3SuwVhOdzGL@JG8W/wYP6Ir22vShrbVxrhQYqBYguZpNRCaB3aHBWALNl9sGYoPbSeg0pzqFSWc5oa2wgpPJUsZYeyqXieCw35mEHKVSrqhtV1eGVfUFl1h6CElrnugMvcF@xPk2XO0Tit73iv7IRH8w8Rcm/oNJPjBzrzy1fnVAIkPDGsclBiOZ5V4)** if we can take JS timestamps as input (as suggested by @Shaggy)
[Answer]
# JavaScript, ~~75~~ 73 bytes
Takes input as a sorted array of arrays of date primitive pairs, outputs an object where the keys are the primitives of each date and the values the counts of those dates in the ranges.
```
a=>a.map(g=([x,y])=>y<a[0][0]||g([x,y-864e5],o[y]=~~o[y]+(x<=y)),o={})&&o
```
[Try it](https://codepen.io/PeterShaggyNoble/pen/VdMjvN?editors=0011)
---
I was working on this 60 byte version until it was confirmed that dates that don't appear in any of the ranges *must* be included so hastily updated it to the solution above.
```
a=>a.map(g=([x,y])=>x>y||g([x+864e5,y],o[x]=-~o[x]),o={})&&o
```
[Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPdViO6QqcyVtPWrsKusqYmHcjVtjAzSTUFCurkR1fE2urWgShNnXzb6lpNNbX8/8n5ecX5Oal6OfnpGmka0VwK0UpGBgaGumCkpIPMidXBLWuEV9YYXdYYr6wpsqwpSDYW7L8KoL/AjEpbO@281HIFl8SSVI1KTRD4DwA) (or [with human readable dates in the output](https://tio.run/##fZCxDoIwEIZ3n4IwkDYUgiDGpZ0c3RxJhwZLg0GOQKMloq9egcEQE7nccN99t/x3FXfR5W3Z6KCGi7QFtYIyEd5EgxRFmSE9x5QZ1g@DGtE/7HcyHZcEMkNr@XCOQktkcKjhBLmo5MRn3Za1QpjT4D3ecUyAPl/Y88DmUHdQybAChQqUbZzMjaNoG8ztkiVw8t/Gqzb5tcmqTZc2nSyfH2DG4PPQU@Z/s/Z4KvsB))
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 63 bytes
```
@(x)histc(t=[cellfun(@(c)c(1):c(2),x,'un',0){:}],min(t):max(t))
```
[Try it online!](https://tio.run/##hY7BCoQgGITvPkV06f/BDSv2Ygi9R3gINTZI95CGED2723ZsYYOBmYGPYd7KD6tJoyjLMnUQ8TUtXoEXvTLzPAYHHShUUCFXUCONtAiuoAw3vktqJwceuR3iYZi06PTgjQu2Jd@wZCLbeg15zVj1OJVjdumS/CWaW6L@IZrbjeeFOLrcWzLCeRvTBw "Octave – Try It Online")
Now that was ugly!
### Explanation:
Takes the input as a cell array of `datenum` elements (i.e. a string `"2001-01-01"` converted to a numeric value, looking like this:
```
{[d("2001-01-01") d("2001-01-01")]
[d("2001-01-01") d("2001-01-03")]
[d("2001-01-01") d("2001-01-02")]
[d("2001-01-03") d("2001-01-03")]
[d("2001-01-05") d("2001-01-05")]};
```
where `d()` is the function `datenum`. We then use `cellfun` to create cells with the ranges from the first column to the second for each of those rows. We concatenate these ranges horizontally, so that we have a long horizontal vector with all the dates.
We then create a histogram using `histc` of these values, with bins given by the range between the lowest and the highest date.
[Answer]
# [R](https://www.r-project.org/), 75 bytes
```
function(x,u=min(x):max(x))rowSums(outer(u,x[,1],">=")&outer(u,x[,2],"<="))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfUNjcTSGta5SZWACnNovzy4NLcYo380pLUIo1SnYpoHcNYHSU7WyVNNSQxI6CYDVBM83@FbW5iSVFmhUZisZ5LYkmqRrKGkpGBgaEuGCnpEMMxRuaYEqfMCI8Bmpo6OkaaXGlAD/0HAA "R – Try It Online")
Input is a matrix whose first column is Start and second column is End. Assumes Start<=End but does not require Start dates to be sorted.
[Answer]
# [Red](http://www.red-lang.org), 174 bytes
```
func[b][m: copy #()foreach[s e]b[c: s
until[m/(c): either none = v: m/(c)[1][v + 1]e < c: c + 1]]c: first sort b
until[print[either none = v: m/(c)[0][v]](last b)< c: c + 1]]
```
Quite long and literal implementation.
[Try it online!](https://tio.run/##dYxBCoMwFET3nmKgG6VIjaWb0F6i289fmDTBgEZJotDTW5FSSqW7NzPMC@ax3M2DOLNysZPXpJh6CT2MTxzywg7BNLqlCMOKtETMJp9cR/0p14WEcak1AX7wBjfMEltPgmnGEYINrlhfegu8knUhJsQhJKi3agzOJ/pjqlYTc94160sV37LFgkQpyrqqBPZw3jX1bvrA5Rd4eQE "Red – Try It Online")
## Readable:
```
f: func [ b ] [
m: copy #()
foreach [ s e ] b [
c: s
until [
m/(c): either none = v: m/(c) [ 1 ] [ v + 1 ]
e < c: c + 1
]
]
c: first sort b
until[
print [ either none = v: m/(c) [ 0 ] [ v ] ]
( last b ) < c: c + 1
]
]
```
[Answer]
# Groovy, 142 bytes
```
{a={Date.parse('yyyy-mm-dd',it)};b=it.collect{a(it[0])..a(it[1])};b.collect{c->b.collect{it}.flatten().unique().collect{it in c?1:0}.sum()}}
```
##
Formatted out:
```
{ // Begin Closure
a={Date.parse('yyyy-mm-dd',it)}; // Create closure for parsing dates, store in a().
b=it.collect{ // For each input date pair...
a(it[0])..a(it[1]) // Parse and create date-range.
};
b.collect{ // For each date range...
c->
b.collect{ // For each individual date for that range...
it
}.flatten().unique().collect{ // Collect unique dates.
it in c?1:0
}.sum() // Occurrence count.
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ ~~87~~ 93 bytes
-27 bytes thanks to Jonathan Allan
+6 bytes thanks to sundar
Takes input as list of pairs of datetime objects.
Assumes that first pair starts with the lowest date.
```
def F(I):
d=I[0][0]
while d<=max(sum(I,[])):print sum(a<=d<=b for a,b in I);d+=type(d-d)(1)
```
[Try it online!](https://tio.run/##tY69CoMwFIX3PMVdxKSNxR/aweoq@AglZFASMdBoiCmtT2@10KEdCkKFM1zO@fi4ZnRt38XTJGQDBS5JikDkJQv5HAT3Vl0liCzX1QMPN41LyjghqbGqc7AUVZbPcw1Nb6GiNagOSnIW@9yNRmIRCIIjMjW21yAqJ53SEpQ2vXU7hArM2Ls9DM6a5cB@HIZR8IpPwfcugacDT/iEwi/49AlzigDgf/pkW328Wp9s@/1xjf4L5oiT6Qk "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts stdin for a list of pairs of International Date Numbers (like what Excel and MATLAB use). Both list and pairs may be given in any order, e.g. (End,Start). Prints list of counts to stdout.
`¯1+⊢∘≢⌸(R,⊢)∊(R←⌊/,⌊/+∘⍳⌈/-⌊/)¨⎕` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@h9Ybaj7oWPeqY8ahz0aOeHRpBOkCu5qOOLo2gR20THvV06euACG2Qit7Nj3o69HVBfM1DKx71TQWZ8V8BDAq4NIzNLCwNFcCkpgISzxiFZwTlGaPImYJ5ppoA "APL (Dyalog Unicode) – Try It Online")
If this is invalid, a list of (Y M D) pairs can be converted for an additional 21 bytes, totalling 53:
`¯1+⊢∘≢⌸(R,⊢)∊(R⌊/,⌊/+∘⍳⌈/-⌊/)¨{2⎕NQ#'DateToIDN'⍵}¨¨⎕` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@h9Ybaj7oWPeqY8ahz0aOeHRpBOkCu5qOOLo2gR20THvV06euACG2Qit7Nj3o69HVBfM1DK6qNHvVN9QtUVndJLEkNyfd08VN/1Lu19tCKQyuAEiDj/yuAQQGXhoaRgYGhAhhpIrM1FXBIGeOWMkKVMsaty1QTma0JAA "APL (Dyalog Unicode) – Try It Online")
---
`⎕` prompt console for evaluated input
`(`…`)¨` apply the following tacit function to each pair
`⌊/` the minimum (lit. min-reduction), i.e. the start date
`⌈/-` the maximum (i.e. end date) minus that
`⌊/+∘⍳` the start date plus the range 1-through-that
`⌊/,` the start date prepended to that
`R←` assign this function to `R` (for **R**ange)
`∊` **ϵ**nlist (flatten) the list of ranges into a single list
`(`…`)` apply the following tacit function to that:
`R,⊢` the result of applying `R` (i.e. the date range) followed by the argument
(this ensures that each date in the range is represented at least once, and that the dates appear in sorted order)
…`⌸` for each pair of unique (date, its indices of occurrence in the input), do:
`⊢∘≢` ignore the actual date in favour of the tally of indices
`¯1+` add -1 to those tallies (because we prepended one of each date in the range)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
```
Lookup[d=DayRange;Counts[Join@@d@@@#],#[[1,1]]~d~#[[-1,1]],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d8nPz@7tCA6xdYlsTIoMS891do5vzSvpDjaKz8zz8EhxcHBQTlWRzk62lDHMDa2LqUOyNQFs3UMYtX@a1pzBRRl5pU4pDlUcylUKxkZGBjqgpGSjgIyr1YHj7QxurQxfmlU3Ubo0qYo0qZKtVy1/wE "Wolfram Language (Mathematica) – Try It Online")
+35 bytes because OP specified that `0` must be included in the output.
### If omitting an entry in a dictionary were allowed, 27 bytes
```
Counts[Join@@DayRange@@@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d85vzSvpDjaKz8zz8HBJbEyKDEvPdXBwUE5Vu2/pjVXQFFmXolDmkM1l0K1kpGBgaEuGCnpKCDzanXwSBujSxvjl0bVbYQubYoibapUy1X7HwA "Wolfram Language (Mathematica) – Try It Online")
The built-in `DayRange` accepts two `DateObject`s (or a string equivalent) and outputs a list of `Dates` between those dates (inclusive).
[Answer]
# [R](https://www.r-project.org/), ~~65~~ 63 bytes
```
function(x)hist(unlist(Map(`:`,x[,1],x[,2])),min(x-1):max(x))$c
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMjs7hEozQvB0T5JhZoJFgl6FRE6xjGgkijWE1NndxMoDpdQ02r3MQKoAZNleT/Fba5iSVFmRUaicV6LoklqRrJGkpGBgaGumCkpEMMxxiZY0qcMiM8BgBdqmOkyaWRBnLjfwA "R – Try It Online")
This is a collaboration between [JayCe](https://codegolf.stackexchange.com/users/80010/jayce) and myself, porting [Stewie Griffin's answer](https://codegolf.stackexchange.com/a/166820/67312) over to R.
To quote JayCe:
>
> Input is a matrix whose first column is Start and second column is End. Assumes Start<=End but does not require Start dates to be sorted.
>
>
>
Possibly, `$c` is unnecessary but it's not quite in the spirit of the challenge so I've included it.
[Answer]
# Powershell, ~~122~~ ~~121~~ ~~118~~ 113 bytes
```
filter d{0..($_[-1]-($s=$_[0])).Days|%{$s.AddDays($_)}}$c=@{};$args|d|%{++$c.$_};,($c.Keys.Date|sort)|d|%{+$c.$_}
```
save it as `count-timespan.ps1`. Test script:
```
.\count-timespan.ps1 `
@([datetime]"2001-01-01", [datetime]"2001-01-01")`
@([datetime]"2001-01-01", [datetime]"2001-01-03")`
@([datetime]"2001-01-01", [datetime]"2001-01-02")`
@([datetime]"2001-01-03", [datetime]"2001-01-03")`
@([datetime]"2001-01-05", [datetime]"2001-01-05")
```
## Explanation
```
filter d{ # define a function with a pipe argument (it's expected that argument is an array of dates)
0..($_[-1]-($s=$_[0])).Days|%{ # for each integer from 0 to the Days
# where Days is a number of days between last and first elements of the range
# (let $s stores a start of the range)
$s.AddDays($_) # output to the pipe a date = first date + number of the current iteration
} # filter returns all dates for each range
} # dates started from first element and ended to last element
$c=@{} # define hashtable @{key=date; value=count}
$args|d|%{++$c.$_} # count each date in a array of arrays of a date
,($c.Keys.Date|sort)|d|%{+$c.$_} # call the filter via pipe with the array of sorted dates from hashtable keys
# Trace:
# call d @(2001-01-01, 2001-01-01) @(2001-01-01, 2001-01-03) @(2001-01-01, 2001-01-02) @(2001-01-03, 2001-01-03) @(2001-01-05, 2001-01-05)
# [pipe]=@(2001-01-01, 2001-01-01, 2001-01-02, 2001-01-03, 2001-01-01, 2001-01-02, 2001-01-03, 2001-01-05)
# $c=@{2001-01-03=2; 2001-01-01=3; 2001-01-05=1; 2001-01-02=2}
# call d @(2001-01-01, 2001-01-02, 2001-01-03, 2001-01-05)
# [pipe]=@(2001-01-01, 2001-01-02, 2001-01-03, 2001-01-04, 2001-01-05)
# [output]=@(3, 2, 2, 0, 1)
```
[Answer]
# J, 43 bytes
```
(],.[:+/@,"2="{~)&:((>./(]+i.@>:@-)<./)"1),
```
the input is a list of pairs of integers, where each integer is the offset from any arbitrary common 0-day.
## ungolfed
```
(] ,. [: +/@,"2 ="{~)&:((>./ (] + i.@>:@-) <./)"1) ,
```
## explanation
structure is:
```
(A)&:(B) C
```
* C creates a hook that gives the main verb `A&:B` the input on the left and the input flattened on the right
* B aka `((>./ (] + i.@>:@-) <./)"1)` takes the min and max of a list and returns the resulting range, and acts with rank 1. hence it gives the total range on the right, and the individual ranges on the left.
* A then uses `=` with rank `"0 _` (ie, rank of `{`) to count how many times each input appears in any of the ranges. finally it zips every year with those counts.
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWJ19KKttPUddJSMbJWq6zTVrDQ07PT0NWK1M/Uc7KwcdDVt9PQ1lQw1df5rcnFxZeYVlJYo2OopxBtFxygYgqExEBsBSWMFUwVTrtTkjHwFiDJrhTQIi@s/AA "J – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
(a,u=[])=>a.map(g=([p,q])=>p>q||g([p,q-864e5],u[z=(q-a[0][0])/864e5]=-~u[z]))&&u
```
[Try it online!](https://tio.run/##nZCxDoIwFEV3vqITvCYtIohxKZN/0XR4wUI0SIuAJob467XiqiaS3OWem7PcE16xLy9HO/DWHLSrhANko5CKigLjM1qoBUjLuhewRTdN9Vz5brvRuWKjvAvoOMpE@dDVGwv@8IOiNAxHV5q2N42OG1NDBTIgRLb6RvY4aIjSJFnzORFl5DNX7E8nXeBkP5xsgZN/cTxXgX/GPQE "JavaScript (Node.js) – Try It Online")
`undefined` means zero; First element should start earliest
`(a,u=[])=>a.map(g=([p,q])=>p>q||g([p,q-1],u[z=(q-a[0][0])/864e5]=-~u[z]))&&u` is shorter if you only see elements and use more stack
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->s{f,=s.min;(p s.count{|a,b|(f-a)*(f-b)<=0};f+=86400)until f>s[0][1]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664Ok3HtlgvNzPPWqNAoVgvOb80r6S6JlEnqUYjTTdRUwtIJmna2BrUWqdp21qYmRgYaAJVZOYopNkVRxvERhvG1v5Pi47mig7JzE3Vy0st1zAyMDDUASFTTR0FbKKxOthUG2NVbYxDtSEVVBuRpNpQM5YrNvY/AA "Ruby – Try It Online")
### Input:
Array of pairs of dates, sorted by ending date descending.
[Answer]
# R (70)
```
function(x)(function(.)tabulate(.-min(.)+1))(unlist(Map(seq,x$S,x$E,"d")))
```
Presumes a data frame `x` with two columns (`Start` and `End` or possibly `S` and `E`) with dates (class `Date`).
[Try it online](https://tio.run/##dZCxCsIwEIb3PIUUhxwmxbZ2awfBOulidRKHaFMtxFiTK8Snr1FB6uBxBx/3ccP9pq8z3tedPmFz09QB/XIIKI6dEihpyK/NazGJAGinVWORrkVLrbwzNy79FCyoAgDoXcaNFFXob5WkKB3mgRu9q0Rh8IOFrkj0gng6jfi7B0jifyohyT8Vk9mPSoZX6Y9KBxiwkUXT6LOd26U44c3YfDlflQW7@DekybebXQF7xqMDcftDxpVoW/WgjgkbLnw4QGofW/8E)
[Answer]
# [Julia 0.6](http://julialang.org/), 77 bytes
```
M->[println(sum(d∈M[r,1]:M[r,2]for r∈1:size(M,1)))for d∈M[1]:max(M...)]
```
[Try it online!](https://tio.run/##yyrNyUw0@59r@99X1y66oCgzryQnT6O4NFcj5VFHh290kY5hrBWIMopNyy9SKAIKGloVZ1alavjqGGpqaoIEISqB6nITKzR89fT0NGP/J@fnFZcopCSWpOYmlhRlVijYKkRzKWABLkAlGkpGBgaGumCkpIkuZKqkSYxOc0ydFsTpNMLUaQwUggCsBmATjOUChhncv5r/AQ "Julia 0.6 – Try It Online")
Inspired by @DeadPossum's [Python solution](https://codegolf.stackexchange.com/a/166808).
Takes input as a matrix, where each row has two dates: the starting and ending dates of an input range. Assumes the input has the earliest date first, and that each row has the starting date first, but assumes no sorting beyond that between different rows.
---
Older solution:
# [Julia 0.6](http://julialang.org/), 124 bytes
```
R->(t=Dict();[[d∈keys(t)?t[d]+=1:t[d]=1 for d∈g]for g∈R];[d∈keys(t)?t[d]:0 for d∈min(keys(t)...):max(keys(t)...)])
```
[Try it online!](https://tio.run/##yyrNyUw0@59s@z9I106jxNYlM7lEQ9M6OjrlUUdHdmplsUaJpn1JdEqstq2hFYi2NVRIyy9SAEmnx4JY6UBWUKw1hgYrA7jC3Mw8DaiUnp6eplVuYgUyP1bzf3J@XnGJQkpiSWpRYl56arGCrUI0lwIW4AJUoqFkZGBgqAtGSppWmEI6ZGo1Jl@rEZFajcm31RRTqykOrbFcBUWZeSU5eRrJGohA1dT8DwA "Julia 0.6 – Try It Online")
Accepts input as an array of date ranges. Does not assume any sorting among the different ranges in the array.
] |
[Question]
[
### Introduction
As an example, let's take the number `7`. We then duplicate this and place 7 spaces in between. We get this:
```
7_______7
```
After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:
```
7_______7
6543210
```
Then, we just merge the two of them, so:
```
7_______7
6543210 becomes
765432107
```
This will be out output for **N = 7**.
Looks easy, right? Now let's take **N = 12**. We again insert 12 spaces between the two numbers, which gives us:
```
12____________12
```
Then we start the decrement:
```
12____________12
111098765432
```
And this finally gives us:
```
1211109876543212
```
**As you can see, the descending part ends at 2, *not* at 0**.
### Task
Given an integer, **greater than 1**, output the descending sequence as shown above.
### Test cases
```
Input Output
2 2102
3 32103
4 432104
5 5432105
6 65432106
7 765432107
8 8765432108
9 98765432109
10 10987654321010
11 111098765432111
12 1211109876543212
13 13121110987654313
14 141312111098765414
15 1514131211109876515
20 201918171615141312111020
99 9998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150499
100 1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the fewest number of bytes wins!
[Answer]
# CJam, 11 10 bytes
```
q4*~,W%s<\
```
[Try it online.](http://cjam.aditsu.net/#code=q4*~%2CW%25s%3C%5C&input=12%0A) Assumes there is a trailing newline in the input. (Thanks to @jimmy23013 for saving a byte.)
### Explanation
At the end of each line is what the stack looks like at that point (using `4` as an example).
```
q4* e# Push input x 4 times, separated by newlines. ["4\n4\n4\n4\n"]
~ e# Evaluate, separating the 4's and converting them to numbers. [4 4 4 4]
,W% e# Take the range of x and reverse it. [4 4 4 [3 2 1 0]]
s< e# Cast to string and take the first x characters. [4 4 "3210"]
\ e# Swap the top two to get the final result. [4 "3210" 4]
```
[Answer]
# Julia, 30 bytes
```
n->"$n"join(n-1:-1:0)[1:n]"$n"
```
This is an anonymous function that accepts an integer and returns a string. To call it, assign it to a variable.
We construct and join the descending sequence from *n*-1 to 0, and take the first *n* characters from the resulting string. We prepend and append this with the input as a string.
[Verify all test cases online](http://goo.gl/Dcb1XH)
[Answer]
## Haskell, 44 bytes
```
s=show
f n=s n++take n(s=<<[n-1,n-2..])++s n
```
Usage example: `f 14` -> `"141312111098765414"`.
[Answer]
## JavaScript (ES6), ~~55~~ 52 bytes
```
n=>n+[...Array(m=n)].map(_=>--m).join``.slice(0,n)+n
```
Edit: Saved 3 bytes thanks to @WashingtonGuedes.
[Answer]
# Python 2, ~~82~~ ~~72~~ ~~58~~ 53 bytes
```
lambda x:`x`+''.join(map(str,range(x)[::-1]))[:x]+`x`
```
[Try it here!](https://repl.it/BqlF/3)
Thanks to @Alex for teaching me that `repr(x)` = ``x`` saving me a bunch of bytes!
[Answer]
## Pyth, 11 bytes
```
++Q<jk_UQQQ
```
Two alternative versions, which are all also 11 bytes (*sigh*):
```
s[Q<jk_UQQQ
pQp<jk_UQQQ
```
```
Q the input
UQ [0, 1, ..., input-2, input-1]
_ reverse
jk join on empty string
< Q first (input) characters
Q the input again
++ concatenate everything so it prints on one line
```
[Try it here.](https://pyth.herokuapp.com/?code=%2B%2BQ%3Cjk_UQQQ&input=12&debug=0)
[Answer]
# Japt, 13 bytes
```
U+Uo w ¬¯U +U
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VStVbyB3IKyvVSArVQ==&input=MTAw)
### How it works
```
// Implicit: U = input integer
Uo // Create the range [0..U).
w // Reverse.
¬ // Join.
¯U // Slice to the first U chars.
U+ +U // Append U on either end.
```
[Answer]
# Jelly, 10 bytes
```
Ȯ’r0DFḣ³Ḍ³
```
[Try it online!](http://jelly.tryitonline.net/#code=yK7igJlyMERG4bijwrPhuIzCsw&input=&args=MTAw)
### How it works
```
Ȯ’r0DFḣ³Ḍ³ Main link. Input: n
Ȯ Print n.
’ Decrement to yield n - 1.
r0 Create a range from n - 1 to 0.
D Convert each integer to base 10 (array of decimal digits).
F Flatten the resulting array.
ḣ³ Keep the first n elements.
Ḍ Convert from base 10 to integer.
³ Print the integer and set the return value to n.
(implicit) Print the return value.
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 98 110
Longest answer so far :-/
```
.+
$&;$&$*:
+`:(:+)$
$& $1
(:)*
$#1
\d+$
$&0 $&0
T`d`,`\d+$
+`:(.*),
$1
+`. ,
(.+);(.*)
$1$2$1
```
[Try it online.](http://retina.tryitonline.net/#code=LisKJCY7JCYkKjoKK2A6KDorKSQKJCYgJDEKICg6KSoKJCMxClxkKyQKJCYwICQmMApUYGRgLGBcZCskCitgOiguKiksCiQxCitgLiAsCiAKKC4rKTsoLiopIAokMSQyJDE&input=MTI)
[Answer]
# Vitsy, 35 bytes
Since Vitsy isn't aware of how to make strings out of numbers, I implemented finding the length of the number in decimal places in the second line.
```
V0VVNHVv[XDN1mv$-DvD);]VN
1a/+aL_1+
```
Explanation:
```
V0VVNHVv[XDN1mv$-DvD);]VN
V Save the input as a global final variable.
0V Push 0, push input.
VN Output the input.
H Push the range 0...intput.
Vv Push the input, then save it as a temp variable.
[ ] Do the stuff in brackets infinitely or until exited.
X Remove the top item of the stack.
DN Duplicate, then pop as output.
1m Calls the first line index, retrieving length.
v Pop the temp var and push it to the stack.
$ Switch the top two items of the stack.
- Subtract them.
Dv Duplicate, then pop one as a temp var.
D); If it's zero, exit the loop.
VN Output the global var.
1a/+aL_1+
1a/+ Add .1. This makes sure we don't throw errors on input 0.
a Push ten.
L Pop the top item as n, push the log base n of second to top.
_ Make it an int.
1+ Add 1.
```
[Try it Online!](http://vitsy.tryitonline.net/#code=VjBWVk5IVnZbWEROMW12JC1EdkQpO11WTgoxYS8rYUxfMSs&input=&args=MTAw)
Verbose mode for lols:
```
save top as permanent variable;
push 0;
save top as permanent variable;
save top as permanent variable;
output top as number;
push all ints between second to top and top;
save top as permanent variable;
save top as temporary variable;
begin recursive area;
remove top;
duplicate top item;
output top as number;
push 1;
goto top method;
save top as temporary variable;
switch the top two items;
subtract top two;
duplicate top item;
save top as temporary variable;
duplicate top item;
if (int) top is not 0;
generic exit;
end recursive area;
save top as permanent variable;
output top as number;
:push 1;
push 10;
divide top two;
add top two;
push 10;
push ln(top);
replace top with int(top);
push 1;
add top two;
```
[Answer]
# Pure Bash, 49
```
eval printf -va %s {$[$1-1]..0}
echo $1${a::$1}$1
```
Or:
# Bash + coreutils, 48
```
echo $1$(seq $[$1-1] -1 0|tr -d \\n|head -c$1)$1
```
[Answer]
# Retina, 63 bytes
```
.+
$0,y$0$*y$0$*x
x
$'_
(x)*_
$#1
+`(y+)y(.)
$2$1
,(\d+).*
$1$`
```
There is still quite some room for golfing...
[Try it online!](http://retina.tryitonline.net/#code=LisKJDAseSQwJCp5JDAkKngKeAokJ18KKHgpKl8KJCMxCitgKHkrKXkoLikKJDIkMQosKFxkKyl5LioKJDEkYA&input=MTI)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 15 bytes
```
VG:qPVXvG:)GVhh
```
*EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.*
[**Try it online!**](http://matl.tryitonline.net/#code=Vkc6cVBWWHpHOilHVmho&input=MTAw)
```
V % input n. Convert to string
G: % range [1,2,...,n]
qP % convert into [n-1,n-2,...,0]
VXv % convert to string, no spaces
G:) % take first n characters only
GV % push input as a string, again
hh % concat horizontally twice
```
[Answer]
# Java, 93 bytes
```
String x(int v){String o=""+v;for(int i=v-1,c=o.length();o.length()-c<v;i--)o+=i;return o+v;}
```
[Answer]
## Ruby, 41 bytes
```
->n{[n]*2*(r=0...n).to_a.reverse.join[r]}
```
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), ~~27~~ 25 bytes
```
I'::%{K£BCH=}<ΩHG<+<;+!
```
---
### Explanation
```
I ` empty the stack
':: ` push 3 copies of the input
%{K£BCH=} ` dump digits of reversed range(n) as strings [n-1...0]
<ΩHG<+<;+ ` select the first nth digits and pad them with n
! ` output
```
---
### Usage
```
$ ./mw <path-to-code> -i <input-integer>
```
[Answer]
# [Perl 6](http://perl6.org), 31 bytes
```
{$_~([R~] ^$_).substr(0,$_)~$_}
```
```
{
$_ # input
~ # string concatenated with
([R~] ^$_) # all numbers up to and excluding the input concatenated in reverse
.substr(0,$_) # but use only up to the input number of characters
~
$_
}
```
### Usage:
```
for 2,3,7,12,100 {
say {$_~([R~] ^$_).substr(0,$_)~$_}( $_ )
}
```
```
2102
32103
765432107
1211109876543212
1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100
```
[Answer]
## Perl, 43 + 2 = 45 bytes
I'm happy that I didn't used `reverse` and neither `substr`:
```
"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_
```
Requires the `-pl` flags.
```
$ perl -ple'"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_' <<< 12
1211109876543212
```
How it works:
```
# '-p' read first line into `$_` and
# auto print at the end
"@{[1-$_..0]}" # Create a list from -1-n..0 and
# join it on space. This becomes:
# "-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0"
=~s.\D..gr # Remove all but digits:
# "11109876543210"
=~/.{$_}/; # Match the n first characters from
# the generated string
$_.=$&.$_ # Append the match and the input
```
[Answer]
# C, ~~130~~ 125 bytes
```
#define p(x) printf("%i",x);
i,y,h;f(x){for(i=y=x;(i-=h)>=0;){p(y--)h=floor(log10(y))+1;}if(i+=h)p(h=floor(y/pow(10,i)))p(x)}
```
Ungolfed version (with explanation):
```
#define p(x) printf("%i",x); // alias to print an integer
i,y,h; // helper variables
f(x){ // function takes an integer x as arg
for(i=y=x;(i-=h)>=0;){ // i -> the remaining space
// y -> the current descending number
p(y--) // print y (at first y==x)
h=floor(log10(y))+1; // h -> the number of digits in y-1
} // do it until there is no more empty space
if(i+=h) // if needs to chop the last number
p(h=floor(y/pow(10,i))) // chop and print (implicitly cast of double to int)
p(x) // print x at the end
} // end function
```
The implicitly cast from double to int in `h=floor(...)` allowed the use of `#define p(x)` saving 5 bytes.
[Test on ideone.](http://ideone.com/daQou1)
[Answer]
**R, 67 bytes (as function)**
```
# usage example : f(7)
f=function(i)cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')
```
**R, 63 bytes (input from STDIN)**
```
i=scan();cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')
```
[Answer]
## Brainfuck, 265 Bytes
This is only going to work with numbers < 10
Try the golfed version [here](http://fatiherikli.github.io/brainfuck-visualizer/#PiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS1bLT4rPis8PF0+PlstPDwrPj5dPFtbLT4rPis8PF0+PlstPDwrPj5dPC1dPFs8XT5bPls+XT4rPDxbPF0+LV0+WysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4+XSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4+KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLgoK):
```
>,------------------------------------------------[->+>+<<]>>[-<<+>>]<[[->+>+<<]>>[-<<+>>]<-]<[<]>[>[>]>+<<[<]>-]>[++++++++++++++++++++++++++++++++++++++++++++++++.>]++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.
```
Ungolfed. Try it [here](http://fatiherikli.github.io/brainfuck-visualizer/#PgosCi0tLS0tLS0tLS0gQ29udmVydCB0byBiYXNlIDEwCi0tLS0tLS0tLS0KLS0tLS0tLS0tLQotLS0tLS0tLS0tCi0tLS0tLS0tIAoKClstPis+Kzw8XT4+Wy08PCs+Pl08CgpGaWxsIHVwIHRoZSBncmlkClsKWy0+Kz4rPDxdPj5bLTw8Kz4+XSAvL3R1cm4gOCBpbnRvIFs4XVs4XQo8LQpdCgo8WzxdPiBHbyB0byBjZWxsIDEKWwoKPls+XSBTY2FuIGZvciB6ZXJvCj4gTW92ZSBvbmUgbW9yZQorIEFkZCBvbmUKPDwgTW92ZSB0d28gYmFjawpbPF0gU2NhbiBmb3IgemVybwo+IE1vdmUgb25lIGZvcndhcmQKLSBTdWJ0cmFjdCBPbmUKXQoKPiBNb3ZlIG9uZSBmb3J3YXJkIGludG8gYWN0dWFsIG51bWJlcnMKWworKysrKysrKysrIENvbnZlcnQgdG8gYXNjaWkKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrKysKKysrKysrKysKLgo+Cl0KKysrKysrKysrKyBDb252ZXJ0IHRvIGFzY2lpCisrKysrKysrKysKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrCi4KPgorKysrKysrKysrIENvbnZlcnQgdG8gYXNjaWkKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrKysKKysrKysrKysKLgoK):
```
>
,
---------- Convert to base 10
----------
----------
----------
--------
[->+>+<<]>>[-<<+>>]<
Fill up the grid
[
[->+>+<<]>>[-<<+>>] //duplicate number like [5][0] -> [5][5]
<-
]
<[<]> Go to cell 1
[
>[>] Scan for zero
> Move one more
+ Add one
<< Move two back
[<] Scan for zero
> Move one forward
- Subtract One
]
> Move one forward into actual numbers
[
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
]
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 45 bytes
```
param($a)"$a$(($a-1)..0-join''|% su* 0 $a)$a"
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQyVRU0klUUUDyNA11NTTM9DNys/MU1evUVUoLtVSMFAAKlBJVPpfy8WlppKmYGn5HwA "PowerShell Core – Try It Online")
## Explanation
```
($a-1)..0-join''|% su* 0 $a # builds an array from a-1 to 0, joins them with no separators
# and takes the `a` first chars
"$a ... $a" # surrounds the result with the parameter `a`
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ḶUDFṁ;D;@DḌ
```
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4bi2VURG4bmBO0Q7QEThuIz/MTXhuIogOyAyMCw5OSwxMDAgw4figqwgWf8 "Jelly – Try It Online")
There is also [this](https://tio.run/##y0rNyan8///hjm2hLm4PdzZmOegk/Dc0fbijS8FawchAx9JSx9DAQOFw@6OmNQqR/wE) kinda cheaty 9 byter, which only works due to how the `Y` command in the Footer works, so I'm not counting that.
Jelly's dislike of strings really hurts it here, and CJam's stack is just helpful enough to beat Jelly.
## How it works
```
ḶUDFṁ;D;@DḌ - Main link. Takes n on the left
Ḷ - [0, 1, 2, ..., n-1]
U - [n-1, n-2, ..., 1, 0]
D - Convert each to digits
F - Flatten
ṁ - Take the first n
;D - Append the digits of n
;@D - Prepend the digits of n
Ḍ - Convert from a list of digits to a number
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
Î<ŸRJ¹£¹.ø
```
[Try it online!](https://tio.run/##ARsA5P9vc2FiaWX//8OOPMW4UkrCucKjwrkuw7j//zc "05AB1E – Try It Online")
```
Î<ŸRJ¹£¹.ø # full program
.ø # surround...
£ # first...
¹ # input...
£ # chars of...
J # joined elements of...
Ÿ # [...
Î # 0 ... input...
< # minus 1
Ÿ # ]...
R # reversed...
.ø # with...
¹ # input
# implicit output
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~9 8~~ 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
îσQçφ╠♦
```
[Run and debug it](https://staxlang.xyz/#p=8ce55187edcc04&i=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13&m=2)
-1 byte from recursive.
## Explanation (Unpacked)
```
rr$x%sy|S
r range 0..n-1
r reversed
$ converted to string
x( take n characters
y push n as string from register y
|S prepend and append it to the range
implicit output
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 40 bytes
```
print$_,("@{[1-$_..0]}"=~/\d/g)[0..$_-1]
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCVeR0PJoTraUFclXk/PILZWybZOPyZFP10z2kBPTyVe1zD2/39Do3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
] |
[Question]
[
Write a program or function that outputs/returns the first 10000 prime-indexed prime numbers.
If we call the nth prime `p(n)`, this list is
```
3, 5, 11, 17, 31, 41, 59 ... 1366661
```
because
```
p(p(1)) = p(2) = 3
p(p(2)) = p(3) = 5
p(p(3)) = p(5) = 11
p(p(4)) = p(7) = 17
...
p(p(10000)) = p(104729) = 1366661
```
Standard loopholes are forbidden, and standard output methods are allowed. You may answer with a full program, a named function, or an anonymous function.
[Answer]
# MATLAB/Octave, 25 bytes
```
p=primes(2e6)
p(p(1:1e4))
```
It doesn't get much more straightforward than this.
[Answer]
## Python, 72 bytes
```
P=p=1;l=[]
while p<82e5/6:l+=P%p*[p];P*=p*p;p+=1
for x in l:print l[x-1]
```
This terminates with a "list index out of range error" after printing the 10000 numbers, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/4781/20260).
Uses the [Wilson's Theorem method](https://codegolf.stackexchange.com/a/27022/20260) to generate a list `l` of the primes up to the 10000th prime. Then, prints the primes with the positions in the list, shifted by 1 for zero-indexing, until we run out of bounds after the 10000th prime-th prime.
Conveniently, the upper bound of `1366661` can be estimated as `82e5/6` which is `1366666.6666666667`, saving a char.
I'd like a single-loop method, printing prime-indexed primes as we add them, but it seems to be longer.
```
P=p=1;l=[]
while p<104730:
l+=P%p*[p]
if len(l)in P%p*l:print p
P*=p*p;p+=1
```
[Answer]
## J, 11 bytes
```
p:<:p:i.1e4
```
Outputs the primes in the format
```
3 5 11 17 31 41 59 67 83 109 127 ...
```
## Explanation
```
1e4 Fancy name for 10000
i. Integers from 0 to 9999
p: Index into primes: this gives 2 3 5 7 11 ...
<: Decrement each prime (J arrays are 0-based)
p: Index into primes again
```
[Answer]
# Mathematica, ~~26~~ ~~25~~ 23 bytes
```
Prime@Prime@Range@1*^4&
```
Pure function returning the list.
[Answer]
# Haskell, 65 bytes
```
p=[x|x<-[2..],all((>0).mod x)[2..x-1]]
f=take 10000$map((0:p)!!)p
```
Outputs: `[3,5,11,17,31,41,59,67,83,109,127.....<five hours later>...,1366661]`
Not very fast. How it works: `p` is the infinite list of primes (naively checking all `mod x y`s for y in `[2..x-1]`) . Take the first `10000` elements of the list you get when `0:p!!` (get nth element of `p`) is mapped on `p`. I have to adjust the list of primes where I take the elements from by prepending one number (-> `0:`), because the index function (`!!`) is zero based.
[Answer]
# AWK - 129 bytes
...oookay... too long to win points for compactness... but maybe it can gain some honor for the speed?
The `x` file:
```
BEGIN{n=2;i=0;while(n<1366662){if(n in L){p=L[n];del L[n]}else{P[p=n]=++i;if(i in P)print n}j=n+p;while(j in L)j=j+p;L[j]=p;n++}}
```
Running:
```
$ awk -f x | nl | tail
9991 1365913
9992 1365983
9993 1366019
9994 1366187
9995 1366327
9996 1366433
9997 1366483
9998 1366531
9999 1366609
10000 1366661
```
Readable:
```
BEGIN {
n=2
i=0
while( n<1366662 ) {
if( n in L ) {
p=L[n]
del L[n]
} else {
P[p=n]=++i
if( i in P ) print n
}
j=n+p
while( j in L ) j=j+p
L[j]=p
n++
}
}
```
The program computes a stream of primes using `L` as "tape of numbers" holding found primes jumping around on `L` to flag the nearby numbers already known to have a divisor. These jumping primes will advance while the "tape of numbers" `L` is chopped off number by number from its beginning.
While chopping off the tape head `L[n]` being empty means there is no known (prime) divisor.
`L[n]` holding a value means, this value is a prime and known to divide `n`.
So either we have found a prime divisor or a new prime.
Then ths prime will be advanced to the next `L[n+m*p]` on the tape found being empty.
This is like the Sieve of Eratosthenes "pulled thru a Klein's bottle". You always act on the tape start. Instead of firing multiples of primes thru the tape, you use the primes being found already as cursors jumping away from the tape start by multiple distances of their own value until a free position is found.
While the outer loop generates one prime or not prime decission per loop, the primes found get counted and stored in `P` as key, the value of this (key,value) pair is not relevant for the program flow.
If their key `i` happens to be in `P` already (`i in P`), we have a prime of the p(p(i)) breed.
Running:
```
$ time awk -f x.awk | wc -l
10000
real 0m3.675s
user 0m3.612s
sys 0m0.052s
```
Take into account that this code does not use external precalculated prime tables.
Time taken on my good old Thinkpad T60, so I think it deserves to be called fast.
Tested with `mawk` and `gawk` on Debian8/AMD64
[Answer]
# PARI/GP, 25 bytes
```
apply(prime,primes(10^4))
```
[Answer]
# CJam, 19
```
3D#{mp},_1e4<:(\f=p
```
You can [try it online](http://cjam.aditsu.net/#code=3D%23%7Bmp%7D%2C_1e4%3C%3A(%5Cf%3Dp), but you'll need a little patience :p
For the record, the last number is 1366661.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes
**(or [~~6~~ 5 bytes](https://tio.run/##yygtzv7//@HOBbmKRzYU/P8PAA) to list the first 10,000 prime-indexed prime numbers, followed by [the infinite number of] all the rest of them)**
*Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) and [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) for suggesting the ~~6~~ 5-byte version!*
```
↑!4İ⁰Ṡm!İp
```
[Try it online!](https://tio.run/##ARoA5f9odXNr///ihpEhNMSw4oGw4bmgbSHEsHD//w "Husk – Try It Online") (unfortunately times-out on [TIO](https://tio.run/##yygtzv7//1HbREWTIxseNW7IVTyyoQCI/v8HAA "Husk – Try It Online") before printing all 10,000 prime-indexed primes, but at least outputs what it's found so far...)
```
↑!4İ⁰Ṡm!İp
↑ # print the first
!4 # 4th index of
İ⁰ # powers of 10 (so, the first 10,000), of
Ṡ # hook: apply function to its own argument
m! # map index function to
İp # prime numbers
# (implied by hook) to prime numbers
```
[Answer]
# Perl, 55 bytes
```
use ntheory':all';forprimes{print nth_prime$_,$/}104729
```
---
Uses [@DanaJ](https://codegolf.stackexchange.com/users/30069/danaj)'s `Math::Prime::Util` module for perl (loaded with the pragma `ntheory`). Get it with:
```
cpan install Math::Prime::Util
cpan install Math::Prime::Util::GMP
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èj ©°Tj}jL²
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGogqbBUan1qTLI)
[Answer]
# Python 3, ~~76~~ 109 bytes - disqualified - requalified?
edit: I am sorry, I was going for primes but missed the putting, didn´t reach the goal of "primes with primeindex". Your are free to grab and enhance. I'll be glad to be learning from you.
Based on Wilson Theorem
```
def p(x):
c=n=2
for i in range(3,x):
c*=i-1
if c%i!=0:
print(n,i)
n+=1
```
## without index, 62 bytes
```
def p(x):
c=2
for i in range(3,x):
c*=i-1
if c%i!=0:print(i)
```
Anyone can give me an example or good link, how to make a lambda function from it?
## edit: just to have it done right: 109bytes
```
def p(x):
c=n=2
p=[2]
for i in range(2,x):
c*=i-1
if c%i!=0:
p.append(i)
if n in p: print(p[-1])
n+=1
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `H`, ~~8 7 6~~ 5 bytes
Saved 1 + 1 bytes thanks to Aaron Miller
```
²ʀǎ‹ǎ
```
[Try it Online!](http://lyxal.pythonanywhere.com/?flags=H&code=%C2%B2%CA%80%C7%8E%E2%80%B9%C7%8E&inputs=&header=&footer=)
```
H flag - Push 100 to the stack
²ʀǎƛ‹ǎ
² Squared (10,000)
ʀ Range [0, 10,000)
ǎ Map each a in that range to the ath prime
‹ Decrement each, because the challenge uses 1-indexing
ǎ Get the nth prime for each of those
```
[Answer]
# 05AB1E, 7 bytes (non-competing)
Code:
```
4°L<Ø<Ø
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MsKwTDzDmDzDmA&input=), **note** that I have changed the `4` into a `2`. If you have a lot of time, you can change the `2` back to `4`, but this will take a *lot* of time. I need to fasten the algorithm for this.
Explanation:
```
4° # Push 10000 (10 ^ 4)
L # Create the list [1 ... 10000]
< # Decrement on every element, [0 ... 9999]
Ø # Compute the nth prime
< # Decrement on every element
Ø # Compute the nth prime
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ȷ4RÆN⁺
```
[Try it online!](https://tio.run/##y0rNyan8///EdpOgw21@jxp3/f8PAA "Jelly – Try It Online")
Obviously, this times out on TIO. [Here](https://tio.run/##y0rNyan8///EdpNDWw@3@T1q3PVwZ4vm//8A) is a version that prints as it goes, which reaches \$57493\$ (the \$765\$th term) before timing out
## How it works
```
ȷ4RÆN⁺ - Main link. Takes no arguments
ȷ4 - 10000
R - [1, 2, 3, ..., 9999, 10000]
⁺ - Do twice:
ÆN - n'th prime of each
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E "Adriandmen/05AB1E: A concise stack-based golfing language"), 6 bytes
```
тnp<Ø
```
[Try it online!](https://tio.run/##yy9OTMpM/f//YlPe4dYCm8Mz/v8HAA "05AB1E – Try It Online")
```
Ø # prime numbers with...
< # 1-based...
Ø # indices in...
Åp # first...
т # 100...
n # ^ 2...
Åp # primes
# implicit output
```
] |
[Question]
[
This was inspired by [Apply gravity to this matrix](https://codegolf.stackexchange.com/questions/235493/apply-gravity-to-this-matrix)
Your challenge is to input a matrix with non-negative one-digit integers and drop down the 1's down 1 column, the 2's down 2 columns, the 3's down 3 columns, and so on. Once a number has been moved down and there is no number to take its original place, replace that slot with zero.
If the number can't be moved down enough, wrap it around the top. (e. g If there is a 3 in the second-to-last row, it should wrap around to the first row.)
If two numbers map to the same slot, the biggest number takes that slot.
## Test cases:
```
0,1,2,1,0 0,0,0,0,0
0,0,2,0,1 0,1,0,1,0
1,0,2,1,0 => 0,0,2,0,1
0,0,0,1,0 1,0,2,1,0
0,0,0,0,0 0,0,2,1,0
0,0,2,0,1 0,0,2,0,0
0,2,1,1,0 => 3,0,0,0,1
3,0,2,1,0 0,0,2,1,0
0,0,0,0,0 0,2,0,1,0
```
# Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the least amount of bytes wins.
[Answer]
# [J](http://jsoftware.com/), 24 20 bytes
```
[:>./-@,|."0 2,*,=/]
```
[Try it online!](https://tio.run/##ZY8xD8IgEIV3fsVLF1JDKbQbpk0TEycn18Y4mDbq4mAHB/87HkJpUcglj4P3veNuM8lHNAYcAgqGqpDYHQ9725tWlkUn3jJTqMRGNOXJ5mwanpMz9AbD5froRmRyK88V8zfEUEwJLSoqpxQpOjP9VXNPrRRtljMHA@cpZjZ7q7PUP5hgft0m8sZc0FruI8e3dUiPE6Fpsc4K47nX@j9uZvt2Co8YtYwMh6@DWy8fQApK@AhMoewH "J – Try It Online")
-4 thanks to xash!
Solved independently, but seems very similar to ovs's APL solution. This one works for any number, because I didn't notice that the question only required handling 1-9.
The following explanation is slightly out of date, but the high-level concept, which is the interesting part, is still the same.
Consider input:
```
0 0 2 0 1
0 2 1 1 0
3 0 2 1 0
0 0 0 0 0
```
* `~.@, ... ]` - The `...` part is a verb that takes the unique elements of
the input `~.@,` as the left arg and the unaltered input as the right arg:
```
0 0 2 0 1
0 2 1 3 >./@(-@[|."0 2[*=/) 0 2 1 1 0
3 0 2 1 0
0 0 0 0 0
```
* `=/` Checks if the entire input is equal to each of its unique elements, creating
4 masks, each the size of the original input:
```
1 1 0 1 0
1 0 0 0 1
0 1 0 0 1 --> Locations of 0
1 1 1 1 1
0 0 1 0 0
0 1 0 0 0
0 0 1 0 0 --> Locations of 2
0 0 0 0 0
0 0 0 0 1
0 0 1 1 0
0 0 0 1 0 --> Locations of 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 --> Locations of 3
0 0 0 0 0
```
* `[*` Multiply each of those by the unique elements, giving us a "decomposed"
version of the original input:
```
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 2 0 0
0 2 0 0 0
0 0 2 0 0
0 0 0 0 0
Decomposed input
0 0 0 0 1
0 0 1 1 0
0 0 0 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
3 0 0 0 0
0 0 0 0 0
```
* `-@[|."0 2` Rotate each of those matrices down by the required amount:
```
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 --> Rotated 0
0 0 0 0 0
0 0 2 0 0
0 0 0 0 0
0 0 2 0 0 --> Rotated 2
0 2 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 1 1 0 --> Rotated 1
0 0 0 1 0
0 0 0 0 0
3 0 0 0 0
0 0 0 0 0 --> Rotated 3
0 0 0 0 0
```
* `>./@` Reduce the "planes" by max:
```
0 0 2 0 0
3 0 0 0 1
0 0 2 1 0
0 2 0 1 0
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~17~~ ~~16~~ 14 bytes [SBCS](https://github.com/abrudz/SBCS)
-1 byte by looking at [Jonah's J answer](https://codegolf.stackexchange.com/a/235699/64121) and another -2 bytes by implementing xash's suggestion on the same answer.
```
⌈/⊂(-⍤⊢⊖⊣×=)¨,
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TTof@oq0lD91Hvkkddix51TXvUtfjwdFvNQyt0AA&f=q1B41DZBwRQIH/VuUTBQMFQwAmIDMDQC8w3BLJiYARILCLkquNQVgOBR22QQpc71qKs5TQEoqM5lCTRQXVcdxKwAW2ICtwRmNMRgEG2MZgluowE&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
I initially implemented a lot more "by hand", which ended up more than 3 times longer:
```
{{(⊃⍺)@(⊂1↓⍺)⊢⍵}/((↓⊂∘⍒⌷⊢){k,m|(k←≢⍵)0+⊃⍺}⌸⍸⍵),⊂0⍴⍨m←⍴⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q67WeNTV/Kh3l6YDkNFk@KhtMojzqGvRo96ttfoaGiCBrqZHHTMe9U561LMdKKFZna2TW6OR/ahtwqNOkDJNA22IGbWPenY86t0BEtIBajJ41LvlUe@KXJBCEGtrLQA&f=e9Q31dP/UdsEA64KBSClYAqEj3q3KBgoGCoYAbEBGBqB@YZgFkzMAIkFhFwVXOoKQPCobTKIUud61NWcpgAUVOeyBBqorqsOYkIsMYFbAjMaYjCINkazBLfRAA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 16 ~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I thought 16 seemed a bit much!
```
Zµ=Ɱ×ṙ"N»/)Z
```
A monadic Link that accepts a list of lists of integers and yields a list of lists of integers.
**[Try it online!](https://tio.run/##y0rNyan8/z/q0FbbRxvXHZ7@cOdMJb9Du/U1o/7//x8dbaCjAERGYNIwVkchGsIzBCMDkIAxTAVMAKIFimJjAQ "Jelly – Try It Online")**
### How?
```
Zµ=Ɱ×ṙ"N»/)Z - Link: matrix, M
Z - transpose -> columns of M (top to bottom)
µ ) - for each (c in columns of M):
Ɱ - map (across v in c) with:
= - (c) equals (v)? (vectorises)
√ó - multiply by (c) (vectorises)
-> [c with zeroed out non-v's for each v in c] - call this X
N - negate (c)
" - (X) zip (negated c) with:
·πô - rotate left by
/ - reduce by:
» - maximum (vectorises)
Z - transpose -> back to rows
```
[Answer]
# JavaScript (ES6), 82 bytes
```
m=>m.map((r,y)=>r.map((_,x)=>m.map(q=(r,Y)=>q=(Y+(v=r[x]))%m.length-y|v<q?q:v)|q))
```
[Try it online!](https://tio.run/##dY/LCoMwEEX3fkU2hYRGjborjf0OESli1bb4ShRR8N/t@NbSEgZyOXdm7rz92i8D@SoqNcsfYR/xPuV2qqV@gbGkLeG2nMSdNmQhggNzQMLHOeOaS7fxCDmlWhJmcfVU266@ipu41KQThPRBnpV5EmpJHuMIuwpCLmLUoCYUQx5Fug56fjNlQMGzUoOONVJjpMfe0b32sh1d3TvKBoq23oHCBco@6VFtub@TTXqZPszadlvztimZ9TP3/2TmfDMk6z8 "JavaScript (Node.js) – Try It Online")
### How?
For each position \$(x,y)\$ in the input matrix \$M\$ of height \$h\$, we look for all values \$M\_{x,Y}\$ on the same column such that:
$$Y+M\_{x,Y}\equiv y\pmod h$$
and keep the highest one.
[Answer]
# [Python 3](https://docs.python.org/3/) + numpy, 91 bytes
```
def f(a):r,c=a.nonzero();v=a[r,c];r+=v;i=v.argsort();a*=0;a[r[i]%len(a),c[i]]=v[i];return a
```
-23 due to @ovs
[Try it online!](https://tio.run/##RY/BCsMgDIbvfQovA@2k2PY28UnEQ@jsJqxaMit0L@8ytrL8JITvz3/Iuud7imOtVz@zmYO4oJwMdDHFl8fEhS4GLDGn8WyKDqZ0gLdnwkwetEZpsm1wp4ePFJcT7c4Umhp93jAyqDOmhcVtWXcWlpWibQPMMECEnduGUVkllRyoeycPMMiepA4wyi9S/4ufnBPNiiFm/vlA1Dc "Python 3 – Try It Online")
Much Different from the first solution. Takes a numpy array
(slightly outdated explanation) Assume the array
```
[[0 0 2 0 1]
[0 2 1 1 0]
[3 0 2 1 0]
[0 0 0 0 0]]
```
* `r,c=nonzero(a)` First save the x-indices (rows) to `r` and y-indices (cols) to `c` of nonzero elements
```
r: [0 0 1 1 1 2 2 2]
c: [2 4 1 2 3 0 2 3]
```
* `v=a[r,c]` Then get the nonzero elements into `v`
```
v: [2 1 2 1 1 3 2 1]
```
* `n=(r+v)%len(a)` Then increment the each row (`r`) by respective nonzero elements (`v`) and modulo by matrix length (to wrap) and save to `n`
```
n: [2 1 3 2 2 1 0 3]
```
* `i=v.argsort()` Grade up the nonzero elements (To fix the multiple slots problem)
```
i: [1 3 4 7 0 2 6 5]
```
* `j=a*0` Matrix of zeros of shape of a to `j`
```
j: [[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
```
* `j[n[i],c[i]]=v[i]` Assign graded up nonzero elements with new rows and old columns. Final result:
```
[[0 0 2 0 0]
[3 0 0 0 1]
[0 0 2 1 0]
[0 2 0 1 0]]
```
[Answer]
# [Python 3](https://docs.python.org/3/)+numpy, 73 bytes
```
import numpy
def f(A):t=numpy.c_[:len(A)];return(t*(A[t-t.T]==t)).max(1)
```
[Try it online!](https://tio.run/##nZGxbsMgEIZ3ngJlMRdRy5AtFZUyZkmWbq5VodRWkWyM8EVKnt4F20F11KlYIN1//313YHfH797uRoL1gEJtNhtScMFl2AUNq@DLR@IpwxazLPi0iZjk6FZvNHnIXLVAkock3IM9y7FtHEAuA/zqlJixOLonZui1W1CC7NIIa@qqGV2YS7evuqH1Db2@IBtgT6LD13j1lrIpiKsst512zFjkbe60R4OmtyyjGZRFlQ@uNcgyngFUqYY2vactNZYO@YDeOAYP44fNoOJ/0/0TXv4TPxmBkKPgZ0FVuuP0e4EcJT/LJ1kGu@lc75Haa@fu5CT4KZridJOSa@/1nbMAPUqAceWOL9mwA@xRzebLZ7lvaxuk6nV@UoZbdijxBfP3SikEyDt9Y2Gc0flwfdawkwAgKZApmFNKnQXkum3ZKiFjQj4S4w8 "Python 3 – Try It Online")
Note: this probably fails for double wrap around **EDIT** or, more generally, for matrix entries equal to or larger than the matrix height thanks @alephalpha for pointing this out **end EDIT**. I'm just not sure it is a requirement (this is my first post here).
How it works: We first clone the zeroth axis using an auxiliary indexer `t`. `t` is a column, `t.T` a row `t-t.T` is 2D, applied to the zeroth axis of `A` (the input) it creates a new axis. the index `t-t.T` populates this with rotated copies of A taking advantage of broadcasting, advanced indexing and standard python wrap around for negative indices.
We then compare with `t` to find the places where the rotated value matches the rotation. This is a boolean array which we multiply with `t` to mark each match explicitly with its value. It remains to pick out the `max` value along the appropriate axis.
[Answer]
# [R](https://www.r-project.org/), 82 bytes
Or **[R](https://www.r-project.org/)>=4.1, 75 bytes** by replacing the word `function` with `\`.
```
function(m,k=nrow(m),t=0*m){t[((row(m)+m-1)%%k+1+col(m)*k-k)[i]]=m[i<-order(m)];t}
```
[Try it online!](https://tio.run/##XY5NCsIwEIX3c4qCFDJ2CkmrK42ncFe6kGohxDQQIgri2Wv6Y7QmZCDz5r1vXN/Kvr11jVe2Y4a07Jy9M4PkJV8bfPqKsamTmVxgmupMZI29hsZa5xorVdfSVGqfW3e@uNCud/7Vt8ycvFMP1jDgJKgIj9MqCYfTfGGoBQ3yLIjxw0GMwuSQhyTOweSMUXEOYih@IZOyJToiAiw3WoAjYMgZXDMgoMs5V0D5s9OS8M9OPuEcYTPS@zc "R – Try It Online")
Inspired by [@wasif's answer](https://codegolf.stackexchange.com/a/235720/55372).
---
Old solution (shorter for [R](https://www.r-project.org/)>=4.1):
## [R](https://www.r-project.org/), ~~94~~ ~~92~~ ~~89~~ 88 bytes
Or **[R](https://www.r-project.org/)>=4.1, 74 bytes** by replacing two `function` appearances with `\`s.
```
function(m,k=nrow(m))apply(m,2,function(x,t=0*x){t[((x-k:1)%%k+1)[i]]=x[i<-order(x)];t})
```
[Try it online!](https://tio.run/##XY7LCsIwEEX38xUFKWR0CknVjRq/wl3polQLpfZBiBgRvz2mD6M1gcDkzpwzyhbSFrcm12XbsJoq2aj2zmrErOuuD/cTk48NacmXBp86YcxE1U5gGFYrgUmZptIk5SFq1fmimMF0r19oC1ZnWpWG5Qw4CccSxGkRuMNputC/MfXxFIih4CCGYJyQx8D3wTjpUb4PPBS/kjHZEp0QAeYbzcRe0HP6qUng1OuJK2D9s9Pc8O8OPnCOsBns9g0 "R – Try It Online")
-2 bytes thanks to some arithmetic and moving \$nrows-x\$ up instead of \$x\$ down.
-3 bytes taking inspiration from @wasif's `argsort` in [his answer](https://codegolf.stackexchange.com/a/235720/55372) (`order` in [R](https://www.r-project.org/)).
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~248~~ ~~244~~ 236 bytes
```
load linear
mod D is inc MATRIX{Nat0}*(sort Matrix{Nat0}to M). var A B C D : Nat . op d :
Nat M -> M . eq(A,B)|-> C ;(A,B)|-> D =(A,B)|-> max(C,D). eq d(A,(B,C)|-> D ;
X:M)=(B,(C + D)rem A)|-> D ; d(A,X:M). eq d(A,X:M)= X:M[owise]. endm
```
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Sun Sep 26 21:12:35 2021
Maude> red d(5, (1,0) |-> 1 ; (2,0) |-> 2 ; (3,0) |-> 1 ;
> (2,1) |-> 2 ; (4,1) |-> 1 ;
> (0,2) |-> 1 ; (2,2) |-> 2 ; (3,2) |-> 1 ;
> (3,3) |-> 1 ) .
result M: 0,3 |-> 1 ; 1,1 |-> 1 ; 2,2 |-> 2 ; 2,3 |-> 2 ; 2,4 |-> 2 ; 3,1 |-> 1
; 3,3 |-> 1 ; 3,4 |-> 1 ; 4,2 |-> 1
Maude> red d(4, (2,0) |-> 2 ; (4,0) |-> 1 ;
> (1,1) |-> 2 ; (2,1) |-> 1 ; (3,1) |-> 1 ;
> (0,2) |-> 3 ; (2,2) |-> 2 ; (3,2) |-> 1 ) .
result M: 0,1 |-> 3 ; 1,3 |-> 2 ; 2,0 |-> 2 ; 2,2 |-> 2 ; 3,2 |-> 1 ; 3,3 |-> 1
; 4,1 |-> 1
```
### Ungolfed
```
load linear
mod D is
inc MATRIX{Nat0} * (sort Matrix{Nat0}to M).
var A B C D : Nat .
op d : Nat M -> M .
eq (A, B) |-> C ; (A, B) |-> D = (A, B) |-> max(C, D) .
eq d(A, (B, C) |-> D ; X:M) = (B, (C + D) rem A) |-> D ; d(A, X:M) .
eq d(A, X:M) = X:M [owise] .
endm
```
The answer is obtained by reducing the function `d` with the height of the matrix and the matrix entries. In Maude, matrices are specified as a collection of their non-zero entries.
The height must be passed as a parameter because, in Maude's implementation of matrices,
\$(M)\$
is indistinguishable from
\$\big(\begin{smallmatrix}
M & 0\\
0 & 0
\end{smallmatrix}\big)\$ — i.e., all matrices can be infinitely extended with zeroes — but we must know the height to handle wrapping. We can't just assume it's the largest row number seen, because both example inputs have all zeroes for their last row.
One trick we use is to generate the output matrix initially without regard to collisions. It's not an error in Maude for a map to have duplicate keys, as long as you resolve them before you try to access that key from the map. We have a separate equation to resolve those duplicates. (Incidentally, that equation is why we must *include* `MATRIX` rather than *protect* it, which costs an extra byte (`inc` vs. `pr`) — because we're equating matrix terms to resolve collisions.)
---
Saved 4 bytes by dropping the `var` declaration for `X` and using an “on-the-fly” variable `X:M`.
---
Saved 8 bytes because I forgot to replace the module name `DROP-DOWN` with a shorter name before posting. ü§¶
[Answer]
# [Python 3](https://docs.python.org/3/)+numpy, 77 bytes
```
import numpy
b=0*a
for i in range(1,a.max()+1):b[numpy.roll(a==i,i,axis=0)]=i
```
[Try it online!](https://tio.run/##RY1LCsMwDET3PoWWdiuCnewKPknwQoGmFcQf1BSS07shHzrDgHgMmrLO75y6OkqOkL6xrMCxZJmBRGhVBP64dK9gU2/RYrvFBbxAi26zvUCHB7L/xukQTD2/71Nq8PZGaswCDJxAKL2e2iE1kRZt7s48hn5vNpKnSZP3jIy08MdbEzzXIpxmPZj6Aw "Python 3 – Try It Online")
the roll function does it all, and i stole the zeros\_like trick from @ovs
[Answer]
# [Ruby](https://www.ruby-lang.org/), 155 bytes
```
->m{r,c,o=m.size,m[0].size,{}
o.default=0
e="r.times{|y|c.times{|x|"
eval e+"v=m[y][x]
v>o[[(y+v)%r,x]]&&o[[(y+v)%r,x]]=v}}"
eval e+"m[y][x]=o[[y,x]]}}"
m}
```
[Try it online!](https://tio.run/##XY3dCoMwDIXv@xTFMZmYSdXr@iKlF85VEOwcVYud@uyd9WdjSwic5DuHqP5mbEntNZOjggIaKqO2egmQjPBNjTNqorso877uKEGCeirqKinacTJTcchh8pDQeY1F6GkqmeFs4EhnDWMXE@rgrGDg3Pd/d6rn@ZvbU3TxGEcdk7N9qurR4TIq8rq@MIQZAQLJMjEH7OqEjwtZaQLx0uRDU0ecf6EpbJz8ZeM9uzfnwUHXT0DsGw "Ruby – Try It Online")
We build an hash object with 2d-index as key.
Then we iterate input and we set the key corresponding to landing position to the value if greater.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ ~~18~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
˜εQy*yFÁ]øεø€à
```
-5 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f//9JxzWwMrtSrdDjfGHt5xbuvhHY@a1hxe8P9/dLSBjqGOERAbxOoA2QZANlAEyDYEsxHiBihsIIyNBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2l7aLcOl5J/aQlM4NBKpf@n55zbemhdYKVWpdvhxtjDO85tPbzjUdOawwv@K@mFgXQc2mb/Pzo62kDHUMcIiA1idYBsAyAbKAJkG4LZCHEDFDYQxsbqKESjaIFogCgzxtAO12IMMh0kDMZgIQsENxYA).
**Explanation:**
```
Z # Get the flattened maximum of the (implicit) input-matrix
L # Pop and push a list in the range [1,max]
Àú # (`ZL` is now `Àú`: flatten the (implicit) input-matrix)
ε # Map over each:
Q # Check for each integer in the (implicit) input-matrix whether it's equal
# to this integer
y* # Multiply each by this integer
yF # Loop `y` amount of times:
Á # And rotate the rows that many times towards the right
] # Close both the inner loop and map
√∏ # Zip/transpose to get a list of lists of rows
ε # Map each list of rows to:
√∏ # Zip/transpose; so the values of each cell are grouped together now
ۈ # Get the maximum of each list of cell-values
# (after which the matrix is output implicitly as result)
```
Here a step-by-step of an input to output; with the old `ZL` (flattened maximum; [1,max] ranged list) instead of `Àú` (flatten the input-matrix):
```
Z # i.e. [[0,0,2,0,1],
# [0,2,1,1,0],
# [3,0,2,1,0],
# [0,0,0,0,0]] ‚Üí 3
L # ‚Üí [1,2,3]
εQ # → [[[0,0,0,0,1],[0,0,1,1,0],[0,0,0,1,0],[0,0,0,0,0]],
# [[0,0,1,0,0],[0,1,0,0,0],[0,0,1,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]]]
y* # ‚Üí [[[0,0,0,0,1],[0,0,1,1,0],[0,0,0,1,0],[0,0,0,0,0]],
# [[0,0,2,0,0],[0,2,0,0,0],[0,0,2,0,0],[0,0,0,0,0]],
# [[0,0,0,0,0],[0,0,0,0,0],[3,0,0,0,0],[0,0,0,0,0]]]
yFÁ] # → [[[0,0,0,0,0],[0,0,0,0,1],[0,0,1,1,0],[0,0,0,1,0]],
# [[0,0,2,0,0],[0,0,0,0,0],[0,0,2,0,0],[0,2,0,0,0]],
# [[0,0,0,0,0],[3,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]]
√∏ # ‚Üí [[[0,0,0,0,0],[0,0,2,0,0],[0,0,0,0,0]],
# [[0,0,0,0,1],[0,0,0,0,0],[3,0,0,0,0]],
# [[0,0,1,1,0],[0,0,2,0,0],[0,0,0,0,0]],
# [[0,0,0,1,0],[0,2,0,0,0],[0,0,0,0,0]]]
εø # → [[[0,0,0],[0,0,0],[0,2,0],[0,0,0],[0,0,0]],
# [[0,0,3],[0,0,0],[0,0,0],[0,0,0],[1,0,0]],
# [[0,0,0],[0,0,0],[1,2,0],[1,0,0],[0,0,0]],
# [[0,0,0],[0,2,0],[0,0,0],[1,0,0],[0,0,0]]]
€à # → [[0,0,2,0,0],
# [3,0,0,0,1],
# [0,0,2,1,0],
# [0,2,0,1,0]]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 103 bytes
```
r=range
f=lambda A:[*zip(*[[max(i*(c[j-i]==i)for i in r(len(c)))for j in r(len(c))]for c in zip(*A)])]
```
[Try it online!](https://tio.run/##nZFBbsMgEEX3cwqUjRmLRobsIlEpy6xyAOoFdeyWyCEWplLay7uAHdRE7aZYY4nPn/cHe/j07xe7mcC3o@dytVpBxTgToSoSVsWWB@JbhOKzzFkq4EmObvlMsgfmrgWSPZBxN/Ysx9g4gFgG@JGUmbE5uhMzZG0WFIdNHuGeehdGFuaSdmw70l69042nI24hOlzrP5wlNG3iUqo864Ea61m/HrTzxpuLpQUpUFX1ehx642nBCsQ695Du4khPjCXjevTODBRvxhdbYM1@p7sHvPgnPhkRYM/ZgROZ75h@L8JesIN4kAXC5KTT9q2FTvb6/HrUZLdV5Vegl0qd9ZWakjbq9GRqKQ3GEUwcwdG@tbRBTNLpTqqj1EQpYXZYh@GmwYXr0o7uOSLkjcgbOn@T3oyeza6QeOB/nYv5PPZP3w "Python 3 – Try It Online")
This is more or less a one-to-one translation of my [`numpy` answer](https://codegolf.stackexchange.com/a/236422/107561).
The same explanation and caveat apply.
[Answer]
# [Python 2](https://docs.python.org/2/), 157 bytes
```
e=enumerate;l=input();j=[[0]*len(l[0])for _ in l]
for x,y,z in sorted([((n+x)%len(l),m,x)for n,y in e(l)for m,x in e(y)],key=lambda e:e[2]):j[x][y]=z
print j
```
[Try it online!](https://tio.run/##LY5BCoMwEEX3niKbQtLOItqdkpOEoVicUm2MkkZIvHyaaPkMvPeZgVmjfy@2SYkU2W0m13vqjBrtunkuuklpLfFqyHKTQbwWxx5stMxgVThAhL34d3GeBq45t7cgLseBgBnCcWIhliXKXdFcnxoFwoeiMv38HHpGLekGRTvpgDqi2qvVjdazKaX8Bkho8tQIulCdIzPf4TR59P8g/gA "Python 2 – Try It Online")
-7 thanks to @ykcul
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
IEθEι⌈Eθ∧¬﹪⁻⁺§νμξκLθ§νμ
```
[Try it online!](https://tio.run/##VUrLCsMgELz3KzxuYAumPfYUeio0JXfxIDE0UqN5aMnf25Ukh@4wO8yj7dXcemVTambjAtzVEqBWI0zIspgsqxnicKSV0/DyNPI6Wg@1cXGBxtKrwsPpbgWHbCiQrcQP8dm5d@hhKgoyf5v9bikJIThyvBBLiSfGRDYlgW/2ilvAj3aHlDKdv/YH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over rows
ι Current row
E Map over cells
θ Input array
E Map over rows
§νμ Inner cell
⁺ ξ Plus inner index
⁻ κ Minus outer index
¬﹪ Is divisible by
Lθ Height of array
‚àß Logical And
§νμ Inner cell
‚åà Maximum
I Cast to string
Implicitly print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
```
MapThread[Max,RotateRight[#/.x_/;x!=i:>0,i]~Table~{i,Max@#},2]&
```
[Try it online!](https://tio.run/##dYzBCoJAEEB/ZVLwNOVqt0LxB4QQb7LEVKsuZIXsQVjWX99cwyAqGObw5s3rSLWiIyXPZGtIbE6Psu0FXaqcBizuipQoZNOqyg83wzHcD6tE7lKGko8lna5i1BInNfMNxjywh17eJhfBg3UKHkJd@ZwHEGagtWYIEUI8b2YQHGAzcBcHogV8GuwHcGMc@a68E8vT9m/2VTH2CQ "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
from [Wikipedia](https://en.wikipedia.org/wiki/Smooth_number#Powersmooth_numbers), a number is called B-powersmooth if all prime powers \$p^v\$ that divide the number satisfy \$p^v \leq B\$. B-powersmoothness is important, for example, for Pollard's p-1 factorization algorithm.
## Task
your task is to get two numbers, \$n\$ and \$B\$, and output if \$n\$ is \$B\$-powersmooth.
## Rules
* You may take the input in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/9263/which-number-formats-are-acceptable-in-output)
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins.
* You can output a truthy/false value, or any two different values for true/false.
* You can assume \$ 1 < B, n \$.
## Test cases
```
n, b -> answer
3, 2 -> 0
10, 7 -> 1
123, 40 -> 0
123, 41 -> 1
64, 2 -> 0
64, 32 -> 0
64, 65 -> 1
720, 5 -> 0
720, 15 -> 0
720, 16 -> 1
20, 5 -> 1
```
[Answer]
# [J](http://jsoftware.com/), ~~14~~ 13 bytes
```
<[:>./2^/@p:]
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/baKt7PT0jeL0HQqsYv9r/jdSSFMw5jIHkoYGXCYGINrImMvEEMoASZuZcBlDaTNTCA2izI0MAA "J – Try It Online")
*-1 byte thanks to @Jonah*
A dyadic function. The right argument is \$n\$, the left argument is \$B\$. Returns 0 if \$n\$ is \$B\$-powersmooth, 1 otherwise.
### How it works
```
<[:>./2^/@p:] NB. left arg = B, right arg = n
2 p:] NB. Prime factorization of n,
NB. given as a 2-row matrix of [primes, exponents]
^/@ NB. Evaluate all pi^ei for each prime factor
[:>./ NB. Maximum of all prime powers found above
< NB. 1 if the above is greater than B, 0 otherwise
```
[Answer]
# Regex (ECMAScript), 61 bytes
```
^(?=(|x*)\1*(?=\1\b)(?!(((x+)x+)(?=\3+,)\3*\4)\2+,)(x*)).*,\5
```
[Try it online!](https://tio.run/##TU/LbsIwELznKwKX7CYhxAGCRORy6oELh/bYtJIBJ7h1TOQYSnlc@wH9xP4INS2oSJZndmZ3PX5lG9bMtahNp6nFgutqpd74x0lTxd/dB17eb2uAHb3r@qcXGFM4bH3MiW9pTvIZwrgFANsA7TlrvSDEvOfnfcwTS8F2Y@SH@eDkd3cYmdWj0UKVgFEjxZxDGnb6iFmx0lBQkoGkmrOFFIoDYouqtZRZQWPciwJaBdZ22ABmji2hpDJqaikMeKFnn5FclWbZosnhIJopmwKjNdMNn9iR8il@Rrwas1uDWAP39do0RkN7ojZMioUrlFVGbcwuhsRsvlJGqDXPjk5Fwdt6keY1ZwYYBjZBcKPMbJyKmfkStA37v@LCPPf788v1AqjGZBTb/x9PvdBNHBKH7tAhiS368QWJk/bP3vnu/UE6cIaJbb0AuWLq/Ko/ "JavaScript (SpiderMonkey) – Try It Online")
Takes \$n\$ and \$B\$ from input in unary as strings of `x`s whose length represents the number, separated by a `,`.
Uses my [prime power regex](https://codegolf.stackexchange.com/questions/210162/is-it-almost-prime/219939#219939), and the same expression for cycling through divisors of N from largest to smallest as [used in this problem](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#179412).
```
# Take input as N in unary, followed by a comma, followed by B in unary
^
(?=
(|x*)\1*(?=\1\b) # cycle tail through all of the divisors of N, including N,
# from largest to smallest;
# \1 = the divisor, or zero if the divisor is N itself
# Assert tail is a prime power
(?! # Assert that the following cannot match
( # Capture \2 to be the following:
((x+)x+) # Cycle through all values of \4 and \3 such that \3 > \4 > 1
(?=\3+,) # such that \3 is a proper divisor of N
\3*\4 # Cycle through all values of \2 > \3 that aren't divisible
# by \3, by letting \2 = \3 * A + \4 where A >= 0
)
\2+, # where \2 is a proper divisor of N
)
(x*) # \5 = the largest prime power factor of N
)
.*, # tail = B
\5 # Assert that \5 <= B
```
# Regex (ECMAScript), ~~61~~ 59 bytes
Adapting [Neil's idea](https://codegolf.stackexchange.com/revisions/222668/2) of taking the arguments in \$(B,n)\$ order saves 2 bytes:
```
^(x*),(?!(x*)\2*(?=\2\b)(?!(((x+)x+)(?=\4+$)\4*\5)\3+$)x\1)
```
[Try it online!](https://tio.run/##TY9BbsIwEEX3OUVAlTKThJCEABKRy6oLNizaZdNKBpzg1pjIMTSFsu0BesReJHVaUJEsv5n/Z6zvF7qn1VLxUveqkq@Y2mzlK3tvFJHszb5nxV1dAhzIbd9tnqF20Ydpp2UWuzAlWZwtsFUAag/NabXEu8EscbMhZgNT1lmEjds/YKC3D1pxWQAGleBLBiO/lyCm@VZBTqIUBFGMrgSXDBA7RO6ESHMS4pHn0MmxNMsaMLVMCwURQVUKrsHxHcRAMFnodYfEHx@8mtM5UFJSVbGZWSkewyfEi7G4NiJj4LHc6Uor6M7kngq@srk0yqSL6dkQmC63UnO5Y@nJ2hBwaidQrGRUwwI9k8C7UqiJs6F6uQZlwv4/ca4c@/vzy3Y82EyjSWj@f2oGvh1bUejbYyuKTZOEZ0bWKGm99h78YTS0xrEZPSO6cGT9qj8 "JavaScript (SpiderMonkey) – Try It Online")
(For convenience, this test harness takes the arguments in \$(n,B)\$ order and passes them to the regex in reverse order.)
```
# Take input as B in unary, followed by a comma, followed by N in unary
^
(x*), # \1 = B; tail = N
(?! # Assert that the following cannot match
(x*)\2*(?=\2\b) # cycle tail through all of the divisors of N, including N;
# \2 = the divisor, or zero if the divisor is N itself
# Assert tail is a prime power
(?! # Assert that the following cannot match
( # Capture \3 to be the following:
((x+)x+) # Cycle through all values of \5 and \4 such that \4 > \5 > 1
(?=\4+$) # such that \4 is a proper divisor of N
\4*\5 # Cycle through all values of \3 > \4 that aren't divisible
# by \4, by letting \3 = \4 * A + \5 where A >= 0
)
\3+$ # where \3 is a proper divisor of N
)
x\1 # Assert tail > B
)
```
# Regex (ECMAScript 2018 / .NET), ~~54~~ 52 bytes
*-2 bytes by using [Neil's idea](https://codegolf.stackexchange.com/revisions/222668/2) but with the arguments in \$(n,B)\$ order*
```
$(?<!^\4*(?!(((x+)x+)(?=\2+,)\2*\3)\1+,)(x+\5),(x+))
```
[Try it online!](https://tio.run/##TZBNTsMwEIX3OUVaIXmmCVacllZqMFmx6IYFLAmoJnVTI@ME2/2RgC0H4IhcpLgFpErWvPF8b6wZP4uNcLVVnT837ULuHc8Ky29lc73r4M5bZRpqxXa@P4PysvdYjQZQ9gBgl2A4UPIqT1Ks8kE1xIqFNJDqAtODAfdz6rSqJbD0nCEWVr6ulZVArBQLrYwkSOuQezkzXtqlCNY3Zbq1n3a2raVz1PmFMh9IWwPk2JFqfvXWcE1dp5UHkhIs1BLA8IZqaRq/wh7P39@VuxE3IHgnrDs8D8199oD4D55OAQsA/cq22/7MbIRWi9gK08hp3E90EZ3M0q493VrlJYArSWXIlBBMdELi78@vmCQAZEeolV1YCgQmYbzkpPKESF@Er1dgsWTTLPyJ46z4wP0wjfOIZWk8iVgeLqPsT1k0Hh3YIQ5/ZXwRTfJg/RP2r@PoWP0B "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##ZVDRatswFH33V8hhEClRjOWkKVTTMgh7KLRsLIU91B0ojpwIFNmV5MzFzes@YJ@4D5kn2@leJoSOrs659x7dzM6ywohW86OwJc8E2LxYJ45NZaXegzVbF9oWStAhfhC1i76KfaW4@VSXRlgrvYBmilsLjo113MkMnAq5A/dcagBRc@IGWPZx1L6Dq/fh93QxgasQQlhPkd9wxdJkilGaTNI5Som/eia9QrgToHZEu3zDtPgBfGNRQxttqq11xvuBBNvoTui9O8wShHv@c@k6S9G6OJZSiR2igxYomhcGSu2AZjGFiq39T/juTmoBEQqZrpSimhHUyBzqDzFaR9@MdGIQ9DZKpqJNqaSDYzxGtKvF8ZYGPqG8@AhZ8voaeiZ6MC9fuLEClo/xEy4qr0X/U2SgtuitHRzd6hNXfoCG6724AU18HmGFqFBW9MOs@2FshgmM6zHm0@2UIFppy3PR5LIWO5gduJk8sxo1z4/8iXm/9Hz@18LXBL9//gIN6WpjE93ae@6yA6zRitzEyGv9aucYJAGJMbgOSOKDRXxBEiwXHded8wGWV8F14qUXIG@4DPrXP1mu@N62s8HlXw "C# (.NET Core) – Try It Online") - .NET
This works by first capturing \$B\$, then asserting that there does not exist any \$a>B\$ for which \$a\$ is a prime power that divides \$N\$.
```
# Take input as N in unary, followed by a comma, followed by B in unary
$ # head = B
(?<! # Negative lookbehind; assert that it's not possible to find a
# match for the following. Evaluated from right-to-left, so read
# the inside of this from bottom to top (but go back to top-down
# order for reading inside the negative lookbehind)
^\4* # Assert that \4 divides N
# Assert tail is a prime power
(?! # Negative lookahead; assert that the following cannot match
( # Capture \1 to be the following:
((x+)x+) # Cycle through all values of \3 and \2 such that \2 > \3 > 1
(?=\2+,) # such that \2 is a proper divisor of N
\2*\3 # Cycle through all values of \1 > \2 that aren't divisible
# by \2, by letting \1 = \2 * A + \3 where A >= 0
)
\1+, # where \2 is a proper divisor of N
)
(x+\5) # \4 = tail = any divisor of N greater than B; the "^\5*" above
# asserts it to be a divisor of N. Note that in most regex
# engines, putting the "^\5*" later than the negative
# assertion, as is the case here, results in a slowdown, as
# non-divisors of N will be tested for being prime powers.
,(x+) # \5 = head = B
)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
&YF^<a
```
Inputs `n` then `B`.
Outputs `0` if *n* is *B*-powersmooth or `1` otherwise.
[Try it online!](https://tio.run/##y00syfn/Xy3SLc4m8f9/QyNjLhMDAA) Or [verify all test cases](https://tio.run/##y00syfmf8F8t0i3OJvG/S8h/Yy4jLkMDLnMuQyNjLhMDCGXIZWYCFAcSxmDSzJTL3MiAyxQA)
### How it works
```
&YF % Implicit input: n. Factorization with primes and exponents as separate outputs
^ % Element-wise power
< % Implicit input: B. Less-than comparison, element-wise
a % Any: gives true (1) if any value is nonzero, or false (0) otherwise
% Implicit display
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ḋḅ∋×>
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaHWzsedSxXKikqTdVTqgEx0xJzioHs2oe7Omsfbp3w/@GO7oc7Wh91dB@ebvf/f3S0sY5RrE60oYGOOYgyMtYxMYAxDIEMMxOwPJAyhtJmpkDa3MhAxzQ2FgA "Brachylog – Try It Online")
Takes \$n\$ through the input variable and \$B\$ through the output variable; fails if \$n\$ is \$B\$-powersmooth and succeeds if not.
```
ḅ Take the runs of consecutive equal elements from
ḋ the prime factors of n.
∋ For some run,
× the product of its elements
> is greater than B.
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.factors`, 37 bytes
```
[ group-factors unzip v^ supremum < ]
```
[Try it online!](https://tio.run/##PY/NCsIwEITvPsW8gKFN/0DFq3jxIp5EIZRUPaSN2aSgpc8eY0p72f12dwZmG1HbzvjL@Xg6bCCIupqghH3GwrR5KUmsiarpwHo5DdpIaz9B0VqQfDvZ1pKwXQ0YwJFhDL1CmkTIE6R82uXpghxlHiFbqCxmKlDxv3n0VzxM5/R6juHa70ujv4NcCKGcwg43PwRtfGCvhAbzPw "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes `B` and `n` (in that order) as input and returns a (flipped) boolean as output.
* `group-factors` obtain the prime factorization of `n` as a sequence of pairs
* `unzip` get the factors in one sequence and the exponents in another
* `v^` element-wise exponentiation of two vectors
* `supremum` find the maximum value
* `<` is `B` less than this value?
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes
```
≤⁰▲mΠgp
```
[Try it online!](https://tio.run/##yygtzv6fe2j5o6bGR20THrVN@v@oc8mjxg2Ppm3KPbcgveD////R0UY6xrE60eY6hgZAysRAx9AIxDcxhDKMdMxMgJQxlDYzhdCmOuZGBrGxAA "Husk – Try It Online")
```
p # get the list of prime factors of arg2;
g # group equal ones together
mΠ # and multiply them together (to get the prime power divisors);
▲ # get the maximum of these;
≤⁰ # is it ≤ arg1?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆF*/€Ṁ>
```
[Try it online!](https://tio.run/##y0rNyan8//9wm5uW/qOmNQ93Ntj9///f0OC/OQA "Jelly – Try It Online")
Similar to Bubbler's answer. Returns a flipped boolean.
## Explanation
```
ÆF*/€Ṁ< Main link: takes n on the left, and B on the right
ÆF prime factor and exponent pairs
*/€ reduce each by exponentiation
Ṁ maximum
> greater than B?
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
The output is a positive integer for truthy cases and a `0` otherwise.
```
f=lambda n,b,p=2,m=1:b/m*(n<2or f(*[n/p,n,b,b,p,p+1,m*p][n%p>0::2]))
```
[Try it online!](https://tio.run/##RY3NCoMwEITvPsUgBBK7RY1/INUXEQ@KlQoaQ8ylT28TKS0sy7ezszv6bV@7kuc5N@uwjdMARSPpRtLWpPUYbxFXD7kbzDzqVKzJr52B9C2lLdJ9p5huk7qWvRCnfR72QAOeEaQg8DQhVBdIJ@XJH1OPZf71ech@VBaeKumOCxEEs4tXhBGLwpVQB4BxMTP3snCTNouyCNlEYBPure@cTSIEw2Vyte8rN@6xEecH "Python 2 – Try It Online")
**Commented:**
```
f=lambda n,b,p=2,m=1: # recursive function taking 4 arguments
# n, b - inputs from the challenge
# p=2 - candidate for a prime dividing n
# m=1 - a power of p dividing the original input n
b/m*( ... ) # floor division, this is 0 if m>b
n<2or ... # if n==1, return True (1), else:
f(*[ ... ][1::2]) # if n%p>0 (p does not divide n):
== f(n,b,p+1) # try next p
f(*[ ... ][0::2]) # if n%p==0 (p divides n):
== f(n/p,b,p,m*p) # divide n by p, update power of p, m
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~108~~ 107 bytes
```
1!_=[]
n!f|n`mod`f<1=f:(n`div`f)!f|x<-f+1=n!x
g(h:t)x|h`mod`x<1=h*x:t|1>0=x:h:t
n#b=all(<=b)$foldl g[1]$n!2
```
[Try it online!](https://tio.run/##ZY3BjoIwFEX3fMUDXbTTklBUTAjlC8aVS0IEgrVmSjHIzHTBv2PFTZ1ZnvPObWV9/zorNc/MP/Gi9LQvJl11fVuJjHGRIl21159KYOtNFgrCuPaNd0EyHbGZ5JIam8oPk44TyyNuUnvz9KrhtVIo4w1ei161Ci4FK9faj@euvmre1bfDCW7f43EcPjUUd9n/Ik0bTEgAPIeAEHi5VYPBwjA9z3TAWVigDYWYBhDmEAWYIhZR2L@YLRzbYBu5xWKY0yTb9zeevPkrkp2z2Mf2m51TLIL9N4kzcjaWy3J@AA "Haskell – Try It Online")
* saved 1 thanks to @Unrelated String
* `!` finds all prime factors : it divides n by 2 while modulo is 0 then by 3, then by 4.. Wait 4 is not prime! Ah but it was already factorized by 2
* `g` all that to group factors
* `#` finally we return True if all are <= B
[Answer]
# JavaScript (ES6), ~~53~~ 52 bytes
Expects `(b)(n)`. Returns **0** or **true**.
```
b=>g=(n,i=d=1)=>i>b?0:n%++d?d>n||g(n,1):g(n/d,i*d--)
```
[Try it online!](https://tio.run/##fc5LDoIwEIDhvafoxqQj1D6okJC0nAUokBrSGjGuuHtt1AWpj9Usvvwzc27v7dJf7eVGnDdDGFXolJ4UdrlVRnFQ2uquYbXbZ5lpjHbrOkXkUMdBTW4PhhAIvXeLn4fj7Cc8YiQAI1QAIEoR2yVYReTshTxByQBz8aOUfINp@bxZyu9l8Q/L0wY/1kasxPtbFh4 "JavaScript (Node.js) – Try It Online")
### Commented
```
b => // outer function taking b = powersmoothness rank
g = ( // recursive inner function taking:
n, // n = input integer whose b-powersmoothness is tested
i = // i = exponentiation of the current prime divisor,
// which must never exceed b
d = 1 // d = prime divisor candidate
) => //
i > b ? // if i is greater than b:
0 // failure: stop and return 0
: // else:
n % ++d ? // increment d; if it's not a divisor of n:
d > n // stop and return true if it's greater than n
|| // otherwise:
g( // do a recursive call:
n, // pass n unchanged
1 // reset i to 1 while leaving d unchanged
) // end of recursive call
: // else (d is a prime divisor of n):
g( // do a recursive call:
n / d, // divide n by d
i * d-- // multiply i by d, decrement d afterwards
) // end of recursive call
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~63~~ ~~59~~ 58 bytes
```
.+
$*
Mr`^\4*(?!(((1+)1+)(?=\2+¶)\2*\3)\1+¶)(1+\5)¶(1+)$
0
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg819Pm0tFi8u3KCEuxkRLw15RQ0PDUFsTiDTsbWOMtA9t04wx0oox1owxBLGBcjGmmoe2gdSocBn8/2@sY8RlaKBjzmVoZKxjYgChDLnMTIDiQMIYTJqZcpkbGeiYAgA "Retina 0.8.2 – Try It Online") Takes line-separated input `n,B` but test suite converts from comma-separated for convenience. Edit: Saved 1 byte thanks to a hint by @Deadcode. Explanation:
```
.+
$*
```
Convert `n` and `B` to unary.
```
Mr`^\4*(?!(((1+)1+)(?=\2+¶)\2*\3)\1+¶)(1+\5)¶(1+)$
```
Try to find (in `$4`) an integer that is greater than `b`, a power of a prime, and a factor of `n`. The `r` flag makes the expression match from the right, so `$5` is matched to `b` first, then `$4`, then `$4` is checked for the power of a prime (taken from @Deadcode's answer to [Is it almost-prime?](https://codegolf.stackexchange.com/questions/210162), matching left-to-right as it is a lookahead), then it is checked for a factor of `n`. The previous 63-byte version was faster because it checked for factors before prime powers: [Try it online!](https://tio.run/##K0otycxL/K@qEZygw@WvEpegp831H4hVtLh8E@I0DLU1D20DkjGGmhr2tjFGWipA2kbx0LYYY22NGNMYEy0g1xbINdHWBCoDqQcCLoP//411jLgMDXTMuQyNjHVMDCCUIZeZCVAcSBiDSTNTLnMjAx1TAA "Retina 0.8.2 – Try It Online")
```
0
```
Check that there wasn't a match.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
*Ties [Unrelated String's Brachylog answer](https://codegolf.stackexchange.com/a/222678/94066) for #1.*
```
ÒγP@P
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8KRzmwMcAv7/NzQy5jIxBAA "05AB1E – Try It Online")
```
ÒγP@P # full program
P # product of...
# (implicit) list of...
@ # whether...
# implicit input...
@ # is greater than or equal to...
P # products of...
γ # consecutive runs of...
Ò # prime factors of...
# implicit input
# implicit output
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ 64 bytes
```
t;r;p;f(n,B){for(r=p=1;n/++p;r&=t/n<=B)for(t=n;n%p<1;n/=p);t=r;}
```
[Try it online!](https://tio.run/##bVHtaoMwFP3fp7gIDq0p9aPtGGn2o2NPsZZRNXayLQ1JYLLiq8/dtNHZMvEcbnLOuSbXYnYoiq4zVFFJq0CQTXiqjipQTLKEinkUSarumJmLNduEVjFMUOHLtVWZDKlhirbd574WQTg5TQCfWhgwXJtX8bLDJYNTRiCJEWnmaLX4w30ajymNW3rdJu/bpGghsEDTIkEjgQyxWhLAN7FYYTlK80bywvAS85i2ByAw8E2RuFzxtldTZF68c3UJetvmOd02D0@IpUdgvM48l8PZQGA/WouSNxiLqSvXoOtvfqyC/jjh3G1Mhx0KUXR2h3CZYX8FgZ3cLM/6jl7JeS/n/8oaZftXIQ@vBY7CMJ3bpFRoqQLPLwn4JcweLft6K/DuthcBTYYJacb4znVvJ233U1Qf@4PuZl@/ "C (gcc) – Try It Online")
Takes two integers \$n\$ and \$B\$ as input and returns \$1\$ if \$n\$ is \$B\$-powersmooth or \$0\$ otherwise.
### Explanation
```
t;r;p;f(n,B){ // function taking two int inputs
// n and B
for(r=p=1; // loop over prime factors p of n
// also init return value r to 1
n/++p; // loop while p<=n also bump p
r&=t/n<=B) // at the end of each loop check that
// the current prime power factor of
// n (t/n) is less than or equal to B
for( // loop to strip n of all its
// prime factors p
t=n; // save copy of n in t before
// removing all p factors
n%p<1; // loop while p is a factor of n
n/=p); // reduce n by p
t=r; // return r
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~24~~ 23 bytes
```
FkrPE8 aY^@k1@k0;<eSYhE
```
[Try it online!](https://tio.run/##K6gsyfj/3y27KMDVQiExMs4h29Ah28DaJjU4MsP1/39DIwMucwA "Pyth – Try It Online")
# Explanation
```
Fk For loop with the iterator as k
E Take first input.
PE List of prime factors
rPE8 Run length encoding over the list, eg: [2, 2, 3] becomes [[2, 2], [1, 3]]
Y Initialized to an empty list by default.
@k1 Element at index 1 of k.
@k0 Element at index 0 of k.
^ Apply exponentiation.
aY Append element to Y
SY Sort Y
e Last element
hE Take next input and increment by 1
< Is it less than?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->n,b{(2..n).none?{|x|n/(n/=x while n%x<1;n)>b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6law0hPL09TLy8/L9W@uqaiJk9fI0/ftkKhPCMzJ1UhT7XCxtA6T9Muqbb2f3S0sY5RrE60oYGOOYgyMtYxMYAxDIEMMxOwPJAyhtJmpkDa3MhAR8E0NlYvN7GgugZoaU2BQjSQ0kkDkbGxtf8B "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
n=>g=b=>{for(++b,p=1;b%++p;);for(q=b;q%p<1;q/=p);return n%b|q>1&&b<n&&g(b);}
```
[Try it online!](https://tio.run/##TY/NjoMgFIX3PgUbLQSqYv8WFHbzFNNJKhatjQVEaprM9NkdHCeT2X33nC83ObdyLIfKtdavtbmoqeaT5qLhkovP2jiIsSSWUyZjjC1DbM56Llkf2yNlfcYtYk75h9NAx/KrFzRJ5FEnSQMlYq/JAw7O0YaAAqwFyCOaE3CYkUa0CPE2/81/Dro0@@2fP@PmH@93i3IowqPdkp9T79o7ROlgu9bD1UmvUHovLXwCLsAzoK@uMDtdcNYsxTgXeESIRT4Nk97KIMB3TSRRHyhMjyqjB9OptDMNrKFGYQ0BKvgvxKZv "JavaScript (Node.js) – Try It Online")
Return `false` if n is B-powersmooth. Return `0` otherwise. (as per two different values rule)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
NθW¬⁼θΠυ⊞υ§Φ…·²θ¬﹪÷θ∨Πυ¹κ⁰¬›⌈EυXι№υιN
```
[Try it online!](https://tio.run/##TU@7DsIwDNz5ioyOFCRAQgydEC91ACr@ILQRtUgTmsaFvw9OF/Bwlk5353Pd6lB7bVMq3Yvihbq7CdDLYvZu0RoBFx/h0JO2A/RKVME3VEcgySMqGlogJbaxdI35wBFtZHfpaksDjuam3cPASoleKpGDzuy2ngVxjyM2JkdeA/xSlVhKhqfMuJBcowro4tTiFIzO8Wf9wY463q98vPJvJlGJnSdWMoNysv8/lJkipc1qMVun@Wi/ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for smooth, nothing if not. Explanation:
```
NθW¬⁼θΠυ⊞υ§Φ…·²θ¬﹪÷θ∨Πυ¹κ⁰
```
Input `n` and find its prime factors (taken from my answer to [Zeroes at end of \$n!\$ in base \$m\$](https://codegolf.stackexchange.com/questions/220840)).
```
¬›⌈EυXι№υιN
```
Raise each prime factor to its multiplicity and compare the largest to `B`.
[Answer]
# Excel, 149 bytes
```
=LET(q,SEQUENCE(A2),f,(MOD(A2,q)=0)*q,o,(MMULT(1*(MOD(f,TRANSPOSE(q))=0),q^0)=2)*f,p,FILTER(o,o),MAX((MMULT(1*(MOD(f,TRANSPOSE(p))=0),p^0)=1)*f)<=B2)
```
Explanation
```
=LET( 'function that allows variable assignment,
returns the value of the last parameter
q,SEQUENCE(A2) 'q = list of numbers from 1 to n
f,(MOD(A2,q)=0)*q 'f = if n mod q = 0 then q else 0
o,(MMULT(1*(MOD(f,TRANSPOSE(q))=0),q^0)=2)*f 'o = if f is prime then f else 0
1*(MOD(f,TRANSPOSE(q))=0) 'matrix of f by q where 1 indicates f mod q = 0
q^0 'vertical matrix of q 1's
MMULT( ) 'need to use matrix multiplication to sum
each row inside a LET
=2)*f 'if sum of the row is 2 (prime) then f else 0
p,FILTER(o,o) 'p = all o where o <> 0
1*(MOD(f,TRANSPOSE(p))=0) 'matrix of f by p where 1 indicates f mod p = 0
MAX((MMULT( ,p^0)=1*f)<=b2 'TRUE if largest f with one prime factor <= b
```
[Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnA0cp0ESrUoybng-?e=WSAPim)
[Answer]
# [Orst](https://github.com/cairdcoinheringaahing/Orst-Geo), 18 [bytes](https://github.com/cairdcoinheringaahing/Orst-Geo/wiki/Code-Page)
```
κñˋςᏓ{ᏓĖΐÇ}Ñδ
```
[Try it online!](https://tio.run/##yy8qLvn//9yuwxtPd59vetg/uRqIj0w7N@Fwe@3hiee2/P//3/y/geG//IKSzPy84v@6OQA "Orst – Try It Online")
As hex bytes, this is
```
DE 87 FF D0 E7 FF 47 FF A0 FF 47 18 DD 0E FF A5 2F D4
```
Encoding as UTF-8:
```
Þ‡ÿÐçÿGÿ ÿGÝÿ¥/Ô
```
## How it works
```
κñˋςᏓ{ᏓĖΐÇ}Ñδ - Full program. Takes b, then a
κ - Save b in variable $x
ñˋ - Remove and swap. Stack is [a]
ςᏓ - Base-and-powers; Prime decomposition of a
{ }Ñ - Over each pair:
ᏓĖ - Reduce by power
ΐ - Retrieve b
Ç - Less than or equal?
δ - True for all?
```
] |
[Question]
[
As it turns out, Python allows for `1j for` to be [compressed](https://codegolf.stackexchange.com/a/207126/68261) to `1jfor`. However, `jfor` sounds like `xnor`. Since all similar-phonic phrases have *something* in common, there must be some property shared between `jfor` and `xnor`.
If we look at the ASCII representation of the first two characters of `jfor` in binary, we see:
```
j: 1101010
f: 1100110
j&f: 1100010
```
Notice that the bitwise AND of `j` and `f` has a streak of `1`s at the beginning, then some `0s`, then a single `1`.
Definition: A pair of numbers meets the JFor property iff their bitwise AND in binary meets the following regex (excluding leading 0s): `/1+0+1+0*/` (1 or more `1`s, followed by 1 or more `0`s, followed by 1 or more `1`s, followed by 0 or more `0`s)
Do the ASCII codes for `x` and `n` meet the JFor property?
```
x: 1111000
n: 1101110
x&n: 1101000
```
Yes! So my hunch was correct; `jfor` and `xnor` sound similar, and they share a property (This means, of course, that `odor` must have that property too).
## Task
Given a pair of numbers, determine if they meet the JFor property.
The two numbers may not be distinct, but they will both be integers from `0` to `255` respectively.
Output may follow your language's conventions for Truthy and Falsey, or you may choose any two consistent, distinct values to represent truthy and falsey respectively.
Your program/function may take input in any reasonable format to represent an ordered pair of integers/bytes.
## Test cases
```
# Truthy:
106 102
110 120
42 26
17 29
228 159
255 253
# Falsey:
85 170
228 67
17 38
255 255
38 120
21 21
```
(Bounty: 50 rep to the shortest answer on July 24 **if** it somehow uses a XOR or XNOR operation; please mention if your submission qualifies)
[Answer]
# [Python](https://docs.python.org/2/), 34 bytes
```
lambda a,b:bin(a&b).count('01')==1
```
[Try it online!](https://tio.run/##bdDBDsIgDAbgu0/ByUFCDC0ycMmeBHcADXGJsmWZB58e0dNEeuOj@Zt2fq23KWIK/Tnd3cNfHXHcd36M1O09O1ymZ1xpI6BhfQ8pTMvnn4yR2B3ZlAXRchA4bJVbAMEJoCj4iJxgW/bqjKcCEU0OUH@sVG5WsmCTFbSoZbS6Mk6aeq4qWJraFggc4ceG7vualzEfLdB8KcbSGw "Python 2 – Try It Online")
Although this doesn't use `xor`, I'm xnor.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes
Uses XOR, `^`
-1 thanks to Neil (double rather than halve).
```
lambda a,b:bin(a&b^(a&b)*2).count('1')==4
```
**[Try it online!](https://tio.run/##bdDRCsIgFAbg@57CqzZDwnM2nQ18ElugxWhQbox10dOb62qZXgh@/PxyzvRe7qPH0OtzeNinu1limWvd4Eu7d5f1ogekx@v48ktZQEG1rkM/zmuMDJ6YHdkcA1wy4NhtlRkAzgggT7hGRlCm2SbiKUFEFQvEHwsRw6JKWEWFhuc6ZJP5rlL5XpFwpXJTIDCEH@va72uah7izvoybojR8AA "Python 2 – Try It Online")**
[Answer]
# perl -Mfeature=bitwise -alp, 41 40 bytes
```
$_=2==(()=sprintf("%b",$_&$F[1])=~/1+/g)
```
[Try it online!](https://tio.run/##LYvBCoJAFEX38xUPsVBKnPemp9Nitu36gghRGGVAdNCJdn16U0mrC@ec6@0ycoxpY8iYLMvN6hc3hT5Ldl1yTJt9ernhPTevEg/lkMeIsgKUJBAlIElxIqBKYA10FkQakL/LDMRKaAas5Yar@tco/XcslN7uhED4nn1w87TGoh19LK69bcNjsaZz4elW@wE "Perl 5 – Try It Online")
## How does it work?
The program reads lines from `STDIN`, expecting two numbers on each line. `1` is printed for pairs of numbers with the jfor property, an empty line for pairs without the jfor property.
The `-p` switch makes that the program loops over each line of the input, making the line available in `$_`. And the end, it will print whatever is in `$_`. The `-l` switch removes the trailing newline. The `-a` switch makes that the input is split on white space, with the components placed in `@F`. In particular, the second number will be in `$F[1]`.
```
$_ & $F [1]
```
Due to the `-Mfeature=bitwise` switch, this makes `&` treat its operands as numbers, and performs a bitwise and on them. This makes that while `$_` contains both numbers, only the first number is considered, as that is what Perl does with a string which is used as a number: if the beginning looks like a number, this is taken. (`atoi`, `atof`, yada, yada, yada). So, we're doing a bitwise and of the two numbers.
```
sprintf ("%b", ...)
```
This returns the result in a binary representation.
```
() = ... =~ /1+/g
```
Find all the sequences of consecutive `1`s. This is assigned to a list (of 0 variables). We're throwing away the results, but assignment itself does have a return value; for a list assignment, the result is the number of elements on the RHS.
```
$_ = 2 == (...)
```
Compares the result (of the list assignment above) to 2. If equal, set `$_` to `1`, else to the empty string.
**Edit**: Saved a byte by looking at sequences of 1, instead of a full pattern.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 53 bytes
```
f(a,b){for(a&=b,b=0;a;a=~a)for(b++;~a&1;a/=2);a=b^4;}
```
[Try it online!](https://tio.run/##TY/NbsMgEITvPAWKlAhiqgA2tivKk7iuhJ244lAnSnyK5by6Ozg/LeLw7cyy7LRv3207zx3zouFjdzwzv3GNaJy03np38zxqTZLYm98o63dOc@jNV2an@ceHnnE6ktAPdDhchqqudE0dlFHJXFAl9STASoK1jJxpQXW@qAXoPZLWJXxzZ2MgmxRMxhKsCvnqyYvnw7T812wip@XrD62gqmVCpCihz0xksoQgD2Vx4YCM4eMSrodjx@L2fPco4G65DUkSs53OKDu2Wmd7XIqz3n/2K7HkDXUla0GfrMD3WQ/nz@DcEiww/wI "C (gcc) – Try It Online")
Returns `0` if the two numbers do have the JFor property, and truthy otherwise.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), ~~11~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r& ¤ÔèA É
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=ciYgpNToQSDJ&input=WzEwNiAxMDJd)
```
r& ¤ÔèA É :Implicit input of integer array
r :Reduce by
& : Bitwise AND
¤ :Convert to binary string
Ô :Reverse
è :Count the occurrences of
A : 10, which gets coerced to a string
É :Subtract 1
:Implicit output of Boolean negation
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 11 bytes
```
1=01NTBaBAb
```
[Try it online!](https://tio.run/##K8gs@P/f0NbA0C/EKdHJMek/kGdgBsRGAA "Pip – Try It Online") ([Verify all test cases](https://tio.run/##LYuxDoJAEET7/YoJPcnOHnt3JkoivVZacRTQmVjQE7/9VEI1yXtv1tdaR6FGUE1IBU2lM1gUJthJzDLov3WHeRDJDibdeUz/KORDuoS8/40wynTuTW5PbGNpyoyyoO1RmsqL8v4Y5uG61OlTa/v@Ag))
The main trick is borrowed from [xnor's Python answer](https://codegolf.stackexchange.com/a/207226/16766): the property is satisfied if the binary representation of the bitwise AND contains the sequence `01` exactly once.
```
1=01NTBaBAb
a and b are command-line args (implicit)
01 01 (an integer literal, but treated as a string unless used in a numeric operation)
N Count occurrences in:
aBAb Bitwise AND of a and b
TB Converted to binary
1= Test whether the number of occurrences equals 1 (0 if not, 1 if so)
Autoprint (implicit)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 137 bytes
```
def f(x,y):
b=format;z='08b';x=b(x,z);y=b(y,z);a=""
for i in range(8):a+=str(int(x[i])and int(y[i]))
return int(a[7])+a.count("10")==2
```
[Try it online!](https://tio.run/##XYvLDoMgEEXX@hWEjUwkjWAarYYvMS6wasuiaCgm4s9T6KaPxST3nDt3dfa@6NL7cZrRTHbqoEmTQcyLeUjbHiIr6iFrdzGE7oDWheBikALjNAlvSCGlkZH6NpEaGpmLpzVEaUv2TvUg9YgiuAiQJmaym9FvJbuqh1yerssWCLMCgxDcryaWM@HnMw0XRh9T/hlWUX755bL@XjDKGYB/AQ "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
&BḄƝċ1=1
```
A dyadic Link accepting which yields `1` if jfor or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8/1/N6eGOlmNzj3Qb2hr@///f0MAMiI0A "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/1/N6eGOlmNzj3Qb2hr@P7xc/1HTmv//o6MNDcx0DA2MYrl0og0NDXQUDI0MQGwTIx0FIzOwqDmQZQliGRlZAOVNIWxTU6CwqXEsF5BjAWQbmhvA1ZiZwzQaWyApNgWxjS3gdhgZ6hgZxnLFAgA "Jelly – Try It Online").
---
### 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) using XOR
-2 thanks to Neil (double rather than halve).
```
&Ḥ^$BS⁼4
```
[Try it online!](https://tio.run/##y0rNyan8/1/t4Y4lcSpOwY8a95j8P7xc/1HTmv//o6MNDcx0DA2MYrl0og0NDXQUDI0MQGwTIx0FIzOwqDmQZQliGRlZAOVNIWxTU6CwqXEsF5BjAWQbmhvA1ZiZwzQaWyApNgWxjS3gdhgZ6hgZxnLFAgA "Jelly – Try It Online").
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
2=≢⊆⍨∧/⊤⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@R7aPORY@62h71rnjUsVz/UdeSR31TQVL/Oasf9fappz3qbnnUu0a99tCKR72bDY24DA3MFAwNgLShgYKhkQGXiZGCkRmXobmCkSWXkZGFgqEpkDY1VTAyNeayMFUwNDcAC5uZg9QYW0DlTLmMLcDajQwVjAwB "APL (Dyalog Extended) – Try It Online")
### How it works
```
2=≢⊆⍨∧/⊤⎕ ⍝ Full program; input = a vector of two numbers
⊤⎕ ⍝ Binary representation of two numbers
∧/ ⍝ Bitwise AND
⊆⍨ ⍝ Extract chunks of ones
2=≢ ⍝ Test if there are exactly two chunks
```
[Answer]
# [R](https://www.r-project.org/), ~~37~~ ~~34~~ 33 bytes
-3 bytes thanks to Dominic van Essen
```
function(x,y)sum(rle(x&y)$v>0)==2
```
[Try it online!](https://tio.run/##VczNCsIwDMDxe5@iB5EGcmhSu9VDPfgMvoHYMdAO9kX79NVNx/D2S/gnfQm@hCnex7aLKmGGYXqp/vlQ6ZjhMF80eM@lkV7@VTKoNo637tqOg0qAcp8ygGgU6QpJ80rSSKwXnhi5Wnc18nkBs0OyX1qLbA2Ij51FqvUWyKr@HRm3l3ahcdtvJmQCUd4 "R – Try It Online")
Takes input as raw bytes, as given by `intToBits`. In R, this gives a length 32 vector with the least significant bit first, therefore padded with many zeros. Then compute the run lengths, i.e. sequences of consecutive identical elements. The JFor property is verified if there are exactly two runs of 1s.
---
A (dumb) solution with XOR is:
# [R](https://www.r-project.org/), 39 bytes
```
function(x,y)xor(sum(rle(x&y)$v>0)-2,1)
```
[Try it online!](https://tio.run/##VczBCsIwDIDh@56iB5EEIjSp7ephHnwG30DsGOgG3Sbd01c3HcPbl/AnMYcqh7G9DU3XQqIJUxehH58QH3dI@wl3r7PGgxBjrlWl/loVoGmHa3dphh4SktqmCbGogbUj1rKQNbHomUchccuuJDnNEPHE9ktrSazB4mNviUu9BsqVvyPjt9LONH79LUzCWOQ3 "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 19 bytes
```
≔&NNθ⁼⁴Σ⍘⁻|⊗θθ&⊗θθ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DKbOkPLM41TEvRcMzr6C0xK80Nym1SENTRwGFC@QXalpzBRRl5pVouBaWJuYUa5joKASX5mo4JRanBpcAJdI1fDPzSothRvoXabjklyblpKZoFIK16yggWYYqBSSMNIHA@v9/Q0MDBUMjg/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for JFor, nothing if not. Edit: Switched to my version of @JonathanAllan's answer to save 4 bytes. Explanation:
```
≔&NNθ
```
Input the two numbers and take their bitwise AND.
```
⁼⁴Σ⍘⁻|⊗θθ&⊗θθ²
```
Take the bitwise XOR of twice the number with itself (Charcoal has no XOR operator, so I have to do this longhand) and check that the result (in base 2) has exactly four `1` bits.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 58 bytes
```
a=>b=>Regex.Matches(Convert.ToString(a&b,2),"01").Count==1
```
[Try it online!](https://tio.run/##TY8/T8MwEMVn/CmsDsiWQhQ75A8KyVLBBAutxIAYnOjSRgo2sp2SCvWzh2ta0S7W@53f3b1r3F3jumlwnd7Q1d55@ArXMPrwDTZDr@zT@G3Buc5oVxDyPOjmsd57COiVrI3pq4q2tJxUWdVlhb0whq/KN1twbGn0DqwP12blLa5h6rYOJA8WkVjwcGkG7ctSTDh@pyz14LyjJdXwQ9l5Pr7845P8khsmojSgIsL2I4gIQUYz3MuAyvRUz1A@zFLKHC3JGZIEP5J4hhy1yKKLK83@m@P82p/MEOeXXVJgXXByKEhrLKhmS9kxPFOYltNOn87gx8h4vjM9hO@28/DSaWAtU5zVnBfkMP0B "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# APL+WIN, 24 bytes and uses xnor
Prompts for input as a vector of 2 integers:
```
4=+/b≠9↑1↓b←∊×/(⊂9⍴2)⊤¨⎕
```
[Try it online! Coutesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/6b2GrrJz3qXGD5qG2i4aO2yUlAqUcdXYen62s86mqyfNS7xUjzUdeSQyuA@v4DdfxP4zI0MFMwNDDiArIMDRQMjQyALBMjBSMzkIi5gpElkDYyslAwNAWzTE0VjEyNgSwLUwVDcwOopJk5RLWxBVyNKZBlbAE10MhQwciQiwsA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) +`-pl`, 35 bytes
```
$_=unpack(B8,$_&<>)=~/^0*1+0+1+0*$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rY0ryAxOVvDyUJHJV7Nxk7Ttk4/zkDLUNtAG4i1VPT//8/iSuOq4MrjUgOSplz2//ILSjLz84r/6xbkAAA "Perl 5 – Try It Online")
## Explanation
This accepts characters as input to allow using `unpack` to get the first 8 chars of the binary representation of the stringwise `AND` of `$_` (which implicitly contains the input line) and `<>` (which is the following line of input) and checks for the pattern as specified. Prints `1` for JFor pair or the empty string otherwise.
---
# [Perl 5](https://www.perl.org/) + `-pl`, 34 bytes
```
$_=(@a=unpack(B8,$_&<>)=~/1+/g)==2
```
This uses [@Abigail](https://codegolf.stackexchange.com/users/95135/abigail)'s [counting approach](https://codegolf.stackexchange.com/a/207218/9365), thanks [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbDIdG2NK8gMTlbw8lCRyVezcZO07ZO31BbP13T1tbo//8srjSuCq48LjUgacpl/y@/oCQzP6/4v25BDgA "Perl 5 – Try It Online")
[Answer]
# [Io](http://iolanguage.org/), 60 bytes
-1 byte thanks to @DLosc.
```
method(x,y,(x&y)asBinary strip("0")occurancesOfSeq("01")==1)
```
[Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQqdSR6NCrVIzsdgpMy@xqFKhuKQos0BDyUBJMz85ubQoMS85tdg/LTi1EChmqKRpa2uo@T9Nw9DQQMfQyEBToaAoM68kJ@8/AA "Io – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 44 bytes
```
(a,b)=>(a&b).toString(2).match(/^1+0+1+0*$/)
```
[Try it online!](https://tio.run/##ZY4/D4IwEMV3PsUNRlpFbIuFGoOJg05OoqtJIf7BIBhpXIyfHU8NKjrc8Lt377076Isuk3N6Mr2LqrZhRbQT03BMdDumrikic07zHRHUPWqT7El/zbusi9Np9WllNqWBENADMYVwDFcLICnyssg2blbsnoIDf2G42r5MlI6sm2V9e@zlYjW1cf9IJ5z5DnAm3swZsmA1D4QDwn@rAdKwJiEU3soPS4my9JCbjbPJPPpUKrziAWuk@MF3had@ImXNnmp8JziqnI6qOw "JavaScript (V8) – Try It Online")
Takes input as two numbers, returns a binary string if they meet the JFor property, otherwise `null`
```
(a,b)=>(~(a^b)&(a|b)).toString(2).match(/^1+0+1+0*$/)
```
[Try it online!](https://tio.run/##XY4/b8IwEMX3fIobEPGVEGynToxQkBjaqRN/ViQ7IikVJIhYLEC/enptFSAMN/zu3XvvvszJ1Nlxe3DDk27ytGEmsJhO2Tcza4t9Zi4WMXTVwh23ZcEkhnvjsk82WosBH9C89EbYuE3tIAUyg0VIp3D2ALKqrKvdJtxVxZ8QkN63nTBa5f8mxIl39bxHj7@cr9582v@mM8HjAASXNxacWPKWX2UAMr6pCdG4JSk13ao7K0Wyioi7je@zj8W9UtOVSHgnJU4eKyL9FKlajnTnOylIFThpfgA "JavaScript (V8) – Try It Online")
The same function, but instead uses an XOR to get the binary string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (without XOR/XNOR bonus)
```
&b0«ÔCн
```
Outputs `1` for truthy and `0`/`2`/`4` for falsey (only `1` is truthy in 05AB1E, so this is allowed according to rule "*Output may follow your language's conventions for Truthy and Falsey*").
[Try it online](https://tio.run/##yy9OTMpM/f9fLcng0OrDU5wv7P3/39DAjMvQwAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf7Ukg0OrD09xvrD3v87/6GhDAzMdQwOjWJ1oQ0MDHUMjAyDLxEjHyAwkYq5jZAmkjYwsdAxNwSxTUx0jU@NYHYVoC1MdQ3MDqKyZOUS5sQVckSmQZWwBNdHIUMfIMDYWAA).
**8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with XOR bonus:**
```
&x^2вO4Q
```
Port of [*@JonathanAllan*'s Python 2 answer](https://codegolf.stackexchange.com/a/207223/52210).
[Try it online](https://tio.run/##yy9OTMpM/f9frSLO6MImf5PA//8NDcy4DA2MAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf7WKOKMLm/xNAv/r/I@ONjQw0zE0MIrViTY0NNAxNDIAskyMdIzMQCLmOkaWQNrIyELH0BTMMjXVMTI1jtVRiLYw1TE0N4DKmplDlBtbwBWZAlnGFlATjQx1jAxjYwE).
**Explanation:**
```
& # Bitwise-AND the two (implicit) input-integer together
b # Convert it to a binary-string
0« # Append a trailing 0 at the end
Ô # Connected uniquify it
C # Convert it from binary back to an integer
# (which will result in 0/2/10/42; of which only 10 is a truthy test result)
н # Pop and leave just the first digit (0/2/1/4, of which only 1 is 05AB1E truthy)
# (after which the result is output implicitly)
& # Bitwise-AND the two (implicit) input-integers together
x # Double it (without popping)
^ # Bitwise-XOR (a&b) with 2*(a&b)
2в # Convert this to a binary-list
O # Sum that list to get the amount of set bits
4Q # And check if it's equal to 4
# (after which the result is output implicitly)
```
The last four bytes has a few alternatives, like [`5%3@`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf7Wkc5vTTVWNHf7r/I@ONjQw0zE0MIrViTY0NNAxNDIAskyMdIzMQCLmOkaWQNrIyELH0BTMMjXVMTI1jtVRiLYw1TE0N4DKmplDlBtbwBWZAlnGFlATjQx1jAxjYwE) or [`₆ÍÃĀ`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf7Wkc5vTHzW1He493Hyk4b/O/@hoQwMzHUMDo1idaENDAx1DIwMgy8RIx8gMJGKuY2QJpI2MLHQMTcEsU1MdI1PjWB2FaAtTHUNzA6ismTlEubEFXJEpkGVsATXRyFDHyDA2FgA).
[Answer]
# Scala, ~~46~~ ~~45~~ bytes
```
_.&(_).toBinaryString matches "1+0+1+0*"
```
[Try it online](https://scastie.scala-lang.org/iHLpJhHgQFWXUe53m9JMCg)
] |
[Question]
[
Given an input of a single positive integer, output the "cross-alternate sum"
that corresponds to that integer.
Take the example of the input `n=5`. To find the cross-alternate sum, first
create a square grid of width and height `n` that, reading from left to right
and top to bottom, starts at `1` and increases by one each position:
```
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
```
Then, take the sums from the grid that form a "cross" (that is, both diagonals
combined):
```
1 5
7 9
13
17 19
21 25
1 5 7 9 13 17 19 21 25
```
Finally, take the alternating sum of this sequence:
```
1+5-7+9-13+17-19+21-25
-11
```
Another example, for `n=6` (just to show what the cross looks like for
even-numbered `n`):
```
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
1 6
8 11
15 16
21 22
26 29
31 36
1+6-8+11-15+16-21+22-26+29-31+36
20
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Here are the correct outputs for `n=1` to `n=100`, which you can use as test
cases:
```
1
4
-3
10
-11
20
-23
34
-39
52
-59
74
-83
100
-111
130
-143
164
-179
202
-219
244
-263
290
-311
340
-363
394
-419
452
-479
514
-543
580
-611
650
-683
724
-759
802
-839
884
-923
970
-1011
1060
-1103
1154
-1199
1252
-1299
1354
-1403
1460
-1511
1570
-1623
1684
-1739
1802
-1859
1924
-1983
2050
-2111
2180
-2243
2314
-2379
2452
-2519
2594
-2663
2740
-2811
2890
-2963
3044
-3119
3202
-3279
3364
-3443
3530
-3611
3700
-3783
3874
-3959
4052
-4139
4234
-4323
4420
-4511
4610
-4703
4804
-4899
5002
```
[Answer]
# Jelly, ~~21~~ ~~19~~ ~~11~~ ~~10~~ 7 bytes
```
²~³¡H+2
```
[Try it online!](http://jelly.tryitonline.net/#code=wrJ-wrPCoUgrMg&input=&args=NQ)
## Idea
Assume for a second that the first term of the final sum is subtracted rather than added.
Let **n** be a positive integer.
### Even case
```
1 6
8 11
15 16
21 22
26 29
31 36
```
The differences between the diagonal elements on the lower half of the rows are the first **n ÷ 2** odd natural numbers. Since **1 + 3 + 5 + … + (2k + 1) = k2**, they sum to **(n ÷ 2)2 = n2 ÷ 4**.
In this example
```
- 1 + 6 - 8 + 11 - 15 + 16 - 21 + 22 - 26 + 29 - 31 + 36 =
-(1 - 6)-(8 - 11)-(15 - 16)-(21 - 22)-(26 - 29)-(31 - 36) =
( 5 + 3 + 1 )+( 1 + 3 + 5 ) =
9 + 9 = 18
```
Thus, the sum is **2 × n2 ÷ 4 = n2 ÷ 2**.
### Odd case
```
1 5
7 9
13
17 19
21 25
```
The differences between the diagonal elements on the corresponding rows from above and below (`1` and `5`, and `21` and `25`; `7` and `9`, and `17` and `19`) is the same, so they will cancel out in the alternating sum.
In this example
```
- 1 + 5 - 7 + 9 - 13 + 17 - 19 + 21 - 25 =
-(1 - 5)-(7 - 9)- 13 +(17 - 19)+(21 - 25) =
4 + 2 - 13 - 2 - 4 = -13
```
All that's left is the negative of the central element, which is the arithmetic mean of the first and last number, so it can be calculated as **-(n2 + 1) ÷ 2**.
### General case
Since **~x = -(x + 1)** for two's complement integers (**~** denotes bitwise NOT), the formula for the odd case can be rewritten as **~n2 ÷ 2**.
Also, since the first term (**1**) of the original sum is added instead of subtracted, the above formulas leave an error of **2**, which has to be corrected.
Therefore, the nth cross-alternate sum is **n2 ÷ 2 + 2** if **n** is even, and **~n2 ÷ 2 + 2** if it is odd.
Finally, bitwise NOT is an involution, i.e., **~~x = x** for all **x**. This way **~~~x = ~x**, **~~~~x = x**, and, in general, **~nx** (meaning that **~** is applied **n** times) is **x** if **n** is even and **~x** if it is odd.
Thus, we can rewrite our general formula as **~nn2 ÷ 2 + 2** for all positive integers **n**.
## Code
```
²~³¡H+2 Main link. Input: n
² Yield n².
~ Apply bitwise NOT to n²...
³¡ n times.
H Halve the result.
+2 Add 2.
```
[Answer]
# JavaScript, ~~40~~ ~~38~~ 22 bytes
Using that new-fangled, fancy closed form solution that's all the rage!
```
n=>(n%2?3-n*n:4+n*n)/2
```
Thanks to ThomasKwa, I can eliminate my costly recursive function.
[Answer]
# Jelly, 12 bytes
```
RṖµ²+‘×-*$SC
```
Try it [here](http://jelly.tryitonline.net/#code=UuG5lsK1wrIr4oCYw5ctKiRTQw&input=&args=MTAw).
[Answer]
# CJam, 13 ~~15~~ bytes
```
ri2#_{~}*2/2+
```
Two bytes off thanks to Dennis.
[**Try it online!**](http://cjam.tryitonline.net/#code=cmkyI197fn0qMi8yKw&input=NQ)
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), ~~26~~ ~~15~~ 13 bytes
Using Dennis' insane algorithm, and golfed off another two bytes thanks to him. That guy is responsible for halving of byte count!
```
n2;d[~]4+2:N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=n2%3Bd%5B%7E%5D4%2B2%3AN%2E&input=99)
### Explanation
>
> @VoteToClose `n`^2, apply bitwise NOT `n` times, add four, halve. – [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) [7 mins ago](https://codegolf.stackexchange.com/questions/71242/find-the-nth-cross-alternate-sum#comment174457_71247)
>
>
>
See [Dennis' answer](https://codegolf.stackexchange.com/a/71247/12914) for the explanation of why that works. In a comment on this answer, he suggested another improvement that works because `:` is integer division, so I can negate the top of stack and not worry about the +1 from doing the binary complement. Furthermore, n and n^2 have the same parity, which removes the need for a swap.
```
n Take number from input - n
2; n**2
d Duplicates top of stack
[~] For loop that negates the top of stack n times
4+ Add 4
2: Divide by 2
N. Output as number and stop.
```
[Answer]
# GolfScript, 12 bytes
```
~2?.{~}*2/2+
```
This uses the algorithm from [my Jelly answer](https://codegolf.stackexchange.com/a/71247). [Try it online!](http://golfscript.tryitonline.net/#code=fjI_Lnt-fSoyLzIr&input=NQ)
### How it works
```
~ # Evaluate the input.
2? # Square it.
. # Push a copy of the square.
{~} # Push a code block that applies bitwise NOT.
* # Execute it n² times. Since n² and n have the same parity,
# this is equivalent to executing in only n times.
2/ # Halve the result.
2+ # Add 2.
```
[Answer]
## ES7, 17 bytes
```
n=>-1**n*n*n+4>>1
```
Simple port of @Dennis's Python 2 answer.
While writing this answer I managed to golf my ES6 port to 17 bytes too!
```
n=>(n*n^-n%2)/2+2
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 13 ~~27~~ bytes
Using Dennis' amazing formulas:
```
2^t2\?Q_]2/2+
```
[**Try it online!**](http://matl.tryitonline.net/#code=Ml50Mlw_UV9dMi8yKw&input=NQ)
Direct approach (**27 bytes**):
```
2^:GtetXdwPXdhutn:-1w^!*s2+
```
[Answer]
# Pure Bash, 28
Well now that @Dennis has showed us all how to do this, this needs updating:
```
echo $[-1**$1*($1*$1+1)/2+2]
```
---
Previous answer:
# Bash + GNU utilities, 77
Here's a start:
```
a=$1
(seq 1 $[a+1] $[a*a]
seq $1 $[a>1?a-1:1] $[a*a])|sort -un|paste -sd+-|bc
```
N is passed as a command-line parameter.
`paste` is really handy here for producing the alternating sum. The `-d` option allows a list of separator characters, which are used cyclically.
[Answer]
# Julia, ~~41~~ ~~40~~ ~~25~~ ~~19~~ 16 bytes
```
n->-n%2$n^2÷2+2
```
This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
The approach here, devised by Dennis, is as follows. First we get the parity of *n*, i.e. *n* (mod 2), and negate it. This gives us 0 for even inputs and -1 for odd. We then bitwise XOR with *n*2. When *n* is even, this is just *n*2 because XOR with 0 is just the number. When *n* is odd, XOR with -1 is the same as bitwise negation. So at this point we either have *n*2 or the bitwise NOT of *n*2. We integer divide this by 2 and add 2 to get the result.
Saved a byte thanks to Sp3000 on a previous version, and saved 9 thanks to Dennis on this one!
[Answer]
# Jolf, 13 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=wr0_bc-Bai0zUWorNFFq)
```
½?mρj-3Qj+4Qj
?mρj if parity of j
-3Qj return 3 - j*j
+4Qj else return 4 + j*j
½ (and halve the result)
```
[Answer]
# Python 2, 24 bytes
```
lambda n:(-1)**n*n*n/2+2
```
This uses the algorithm from [my Jelly answer](https://codegolf.stackexchange.com/a/71260), with a minor modification:
Instead of applying `~` **n** times, we apply `-` **n** times (by multiplying by **(-1)n**). This is equivalent because **~x = -x - 1** and integer division floors in Python, so **~x / 2 = (-x - 1) / 2 = -x / 2**.
[Answer]
# Pyth, 11 bytes
```
+2/u_GQ*QQ2
```
Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=%2B2%2Fu_GQ%2aQQ2&input=5&debug=0).
### How it works
This uses the algorithm from [my Jelly answer](https://codegolf.stackexchange.com/a/71247), with a minor modification:
Instead of applying `~` **n** times, we apply `-` **n** times (by multiplying by **(-1)n**). This is equivalent because **~x = -x - 1** and integer division floors in Pyth, so **~x / 2 = (-x - 1) / 2 = -x / 2**.
```
+2/u_GQ*QQ2 Evaluated input: Q
*QQ Yield Q².
u Q Set G = Q². For each non-negative integer below Q:
_G Set G = -G.
Return G.
/ 2 Halve the result.
+2 Add 2.
```
[Answer]
# dc, 17
Using the same tried and tested formula from Dennis:
```
?dd*1+r_1r^*2/2+p
```
Try it online Oh, why doesn't the Ideone bash sandbox include `dc`?
### Command-line Test:
```
for i in {1..100}; do echo $i | dc -e '?dd*1+r_1r^*2/2+p'; done
```
[Answer]
# GS2, 9 bytes
```
V,@!α2+''
```
This uses the algorithm from [my Jelly answer](https://codegolf.stackexchange.com/a/71247). [Try it online!](http://gs2.tryitonline.net/#code=VixAIc6xMisnJw&input=NQ)
```
V,@e 7+''
```
is equally short, but notably contains no non-ASCII characters.
### How it works
```
V Parse the input as an integer n.
, Compute n².
@ Push a copy of n².
! Bitwise NOT.
α Make a block of the previous instruction.
2 Execute the block n² times. Since n² and n have the same parity,
this is equivalent to executing in only n times.
+ Halve the result.
'' Increment twice.
```
[Answer]
# J, 16 bytes
```
[:<.2%~4+*:*_1^]
```
This uses the same algorithm as my Jelly answer. Test it with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%5B%3A%3C.2%25~4%2B*%3A*_1%5E%5D)%2010%2011).
[Answer]
# Lua, 33 bytes ([Try it online](http://www.lua.org/cgi-bin/demo))
```
i=(...)print((-1)^i*i*i/2-.5*i%2)
```
How it works:
```
i=(...)print((-1)^i*i*i/2-.5*i%2)
i=(...) Take input and store to i
print(
(-1)^i Raise (-1) to the i-th power: -1 if odd, 1 if even
*i*i/2 Multiply by i squared and halved.
-.5*i%2 i%2 is the remainder when i is divided by 2
if i is odd, then i%2 will be 1, and this expression
will evaluate to -0.5
but if i is even, then i%2 will be 0, which makes
this expression evaluate to 0
)
```
[Answer]
# Dyalog APL, 13 bytes
```
⌊2+.5××⍨ׯ1*⊢
```
This uses the same algorithm as my Jelly answer. Test it on [TryAPL](http://tryapl.org/?a=%28%u230A2+.5%D7%D7%u2368%D7%AF1*%u22A2%29%2010%2011&run).
] |
[Question]
[
Given as input a list of positive integers, your task is to determine if every integer present has exactly two neighbors in the list. The neighbors of a integer \$x\$ are the distinct integers that appear next to an \$x\$ anywhere in the list. For example in the list:
```
[1,3,4,4,3,2,1]
```
The number `3` has 3 neighbors `1`, `4` and `2`. So this input is not valid. The list
```
[1,2,3,1]
```
is valid because every number has exactly two neighbors.
This is a [self-validating](/questions/tagged/self-validating "show questions tagged 'self-validating'") challenge, so in addition your code performing the task it must also be written so that when interpreted as a list of bytes, it passes the test itself. That is, every byte present in your source must have exactly two neighbors in your source.
You may take a list of positive integers for input in any reasonable method. Output one of two consistent distinct values. One value should only be output if the property is satisfied, the other if it is not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the goal is to minimize the size of your source code as measured in bytes.
## Test cases
**truthy**
```
[]
[1,2,3,1]
[1,1,2,2]
```
**falsey**
```
[1]
[1,2]
[1,2,1,2]
[1,3,4,4,3,2,1]
```
[Answer]
# [Python](https://www.python.org), 2955 bytes
```
eval("(lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalal("'[1 :37])mbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbm)]73: 1['"(lalalalalalalalalalalalalalalalalal("'[1 : : : : : : : : : : : : : : :37])mbdsdsdsdsds{u,inzp-+for*}<=2#eval("'"'[1 :3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])mbds{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{sdsdbm)]73: 1['"'"(lave#2=<}*rof+-pzni,u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{sdbmbmbmbmbmbmbmbmbmbmbmbmbmbmbm)]73: 1['"(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l("'[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1['"(l(l(l(l(l(l(l(l(lave#2=<}*rof+-pzni,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,i,i,i,i,inzp-+for*}<=2#eval("'[1 :37])m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)])])])])])]73: 1['"(lave#2=<}*rof+-pzninininininininininininininininininininznznznznznznznznzp-+for*}<=2#eval("'[1 : : : : : : : : : : : :37])mbds{u,inznzp-+for*}<=2#eval("'"'[1 :37])mbds{u,ininininininininininininininininininzpzpzpzpzpzpzpzpzpzni,u{sdbm)]73: 1['"'"(l(l(l(l(l(l(l(lave#2=<}*rof+-pzni,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 :3:3:3:3:3:3:3:3:3: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+for*}<=2#eval("'[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 :37]7]7]7]7]7]7]7]7]73: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-pzni,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 1['"'"(lave#2=<}*rof+-pzni,u{sdbm)]73:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])])])])])]73: 1['"(lave#2=<}*rof+-pzni,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 1['"'"(lave#2=<}*rof+-pzni,u{sdbm)]73:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])])])])])])])])]73: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-pzni,u{s{s{s{s{u,inzp-+for*}<=2#eval("'[1 :37])])])])])])])])])]73: 1['"(lave#2=<}*rofofofofofofofofofofofofofofofofofofoforororororororororororororororororororororororororororof+-pzni,u{sdbm)]73: : : : : : : : : : : : : : :37])mbds{u{u{u{u{u{u{u{u{u{u{u{u{u{u{sdbm)]73: : : : : : : : : : : : : :37])mbds{u,inininininininininininininininininininznznznzp-+for*}<=2#eval("'[1 :37])mbds{s{s{s{s{s{s{s{sdbm)]73: 1['"(lave#2=<}*r*r*r*r*r*r*r*r*r*r*r*r*rof+-pzni,u{s{s{s{s{s{s{s{sdbm)]73: 1['"'"(lave#2=<}*}*}*}*}*}*}*}*}*}*rof+-pzni,u{sdbm)])])])])])])])])])])])])])])])])])])])m)m)m)m)m)m)m)m)]73: 1['"(lave#2=<}*rofofofofofofofofofofofofofofofofofofoforororororororororororororororororororororororororororof+-pzni,u{sdbm)]73: : : : 1['"'"(lave#2=<}*rof+-pzni,u{sdbmbmbmbmbds{u,inzp-+for*}<=2#eval("'"'[1 : : : : : : : : : : : : :37])mbds{u,inininininininininininininininininininininininininininzp-+for*}<=2#eval("'[1 : : : : : : : : : : : : : : :37])mbdsdsdsdsdsdsdsdsdsdbm)]73: 1['"(lave#2=<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<}*rof+-pzni,u{u{u{u{u{u{u{u{u{sdbm)]73: 1['"'"(lave#2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=<}*rof+-pzni,u{sdbm)]73: 1['[1 : :37])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=7ZfNboJAEMfvtg9B8CAoHoAmNkaexHKwRVISBYJiUohP0EfoxaRpH6pPU1cWXNmvsXow6fo7GBcZZv7M7sx8fKdv69ck3n2G3tNXvg6Hjz937_PNbGHoxmJ2IYbem9ra2B355vIZQnARS9MfuWPNnvZAvmPvRFSeB6uaMreiuEiHgzDJ-tuJ53QrqXo4UBHYVAli_zAynENAm3nX8SbbfpaEg2FaxJGVlzKQGRGkYgBQmABY1ljug4hqmMI3-QXCP0JkCuUZiKINxztxZlUZJcop8o8Ar1KKQ6LQ-SR_PeUq4HM0B4C1NZjqM2GoKgPJRnHOMzHXFgK5LtrPjTkAI2A2Q3bZ7UcojhPyDjG8I7zebMBngsj-BEMsSJGSFgKJpTNPmkhy7vEKXrtON5ryIPUQmDoxRkPLCoKqIDeUDdJ9VndVsr7lahlBV6NzaiK752IcQ2TQILwLEDdcvByUwzsXkaFKI6QE7snv7TSL4rURGlPfNDvND9tyLNeyW2to1UFr2uFDXGrfTBmj11zrYY-LrqErnZckmGuepuu6GhPUmKDGBDUmqDFBjQm3EqEaE9SYoMYENSb8szFh3413mqYddegmnhx2u-r7Fw)
D'oh!
### How (if you can be bothered)
The long string slices down to
```
lambda s:{sum([(u,m)in zip(s[:-1]+s[1:],s[1:]+s)for u in{*s}])for m in s}<={2}
```
It was generated (by computer program) by walking up and down the string
```
[1 :37])mbds{u,inzp-+for*}<=2#eval(
```
wasting just the right amount of time to get the right characters at the chosen spacing.
### A few more details:
Lets do a small example:
Let's assume our program is
```
abracadabra
```
The basic idea is arrange the unique letters in some order, UNQ = `abrcd`, say, and then do something like `ababrbrcdabrcrbadadadababrbrcda`. Because this was created by walking up and down UNQ every letter has at most two neighbours. Now, if we slice this with step = 3 we recover `abracadabra`:
`AbaBrbRcdAbrCrbAdaDadAbaBrbRcdA`. Note that in order to break parity we needed UNQ to be of odd length and to wrap around.
With the wrapping around all the spare neighbour slots we might have hoped to harness in the next step are used up. We'll see in a moment that that is a bit of a problem:
We still need to wrap our magic string in an `eval` statement and do the slicing.
But if we try something like `eval("ababrbrcdabrcrbadadadababrbrcda"[ : :3])` then the characters touching the quotation marks are over-booked. They already had two neighbours, so the quotation mark is one too many.
We can try and solve this by integrating the wrapper code into UNQ:
UNQ = `"[ :3])brcdeval(`
It almost works, but, of course, the single quotation mark will cause all sorts of problems when wrapping around. We could try a similar trick to the one we have already tacitly used to manage the double colon in the slicing expression: instead of `[::3]` (`:` has three neighbours) use `[ : :3]`. But with the colon we have used up the "neutral" space character already. We could try and use `tab` or even `newline` but there is one slightly neater way: use two kinds of quotes: single and double. UNQ = `"[ :3])brcdeval('` Then at every other wrap-around we have to add one wiggle over the quotes:
`"...'"'"....'".....'"'"....'` etc. Python will concatenate this into one single string that contains a few occurrences of the character pair `'"`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ṢƝQ⁺€FċⱮ=2PṢ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkXH5gY@atz1qGmN25HuRxvX2RoFAAX/H27XjPz/Pzo6Vocr2lDHSMdYxxDCBHGMwEyoFEwFnGmsYwKExiAhuG4gI78gNU9DXS85PyVVryQzX11Tryg1MSUnMy9VQ1OvuKQos0BDPSZPXTMWAA "Jelly – Try It Online")
Inspired by [AndrovT's port of my original solution](https://codegolf.stackexchange.com/a/257530/85334), and come to think of it, basically ports [Kevin Cruijssen's solution from before porting that](https://codegolf.stackexchange.com/revisions/257542/3). While Vyxal and 05AB1E have a nice single-byte palindromize builtin, Jelly's is a digraph, and flanking the program with `Œ` would effectively comment the whole thing out (though it is still nominally [accessible as a function](https://tio.run/##y0rNyan8///opIc7WnSOzQ10O9L9aOM6W5OAo5P@Gx7Zrxn5/390dKwOV7ShjpGOsY4hhAniGIGZUCmYCjjTWMcECI1BQnDdQEZ@QWqehrpecn5Kql5JZr66pl5RamJKTmZeqoamXnFJUWaBhnpMnrpmLAA), for the same byte count).
```
∆ù For each pair of adjacent elements in the input,
·π¢ yield it sorted.
Q Uniquify the list of pairs
⁺ then do it again
€ to each pair.
Ɱ P For every element of the input,
ċ is its number of occurrences in that list
F flattened
=2 equal to 2?
·π¢ Sort the result (no-op).
```
My original solution, for posterity:
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
```
¹ŒḄ,ƝQFċⱮ=4P¹
```
[Try it online!](https://tio.run/##y0rNyan8///QzqOTHu5o0Tk2N9DtSPejjetsTQIO7fx/uF0z8v//6OhYHa5oQx0jHWMdQwgTxDECM6FSMBVwprGOCRAag4TguoGM/ILUPA11veT8lFS9ksx8dU29otTElJzMvFQNTb3ikqLMAg31mDx1zVgA "Jelly – Try It Online")
*-1 porting AndrovT's Vyxal answer back*
```
ŒḄ Palindromize the input, making all adjacencies bidirectional.
,∆ùQ Find the unique pairs of adjacent elements.
Ɱ P For every element of the input,
ċ is its number of occurrences in that list
F flattened
=4 equal to 4?
¬π ¬π No-ops.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~20~~ 11 bytes
```
‚àû2lUfvO4=A‚àû
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oieMmxVZnZPND1B4oieIiwiIiwiW11cblsxLDIsNCwxXVxuWzEsMSwyLDJdXG5bMV1cblsxLDJdXG5bMSwyLDEsMl1cblsxLDMsNCw0LDMsMiwxXSJd)
This is valid because all characters except `‚àû` are used exactly once and `‚àû` is both at the beginning and the end.
Now uses the same approach as @Unrelated String's Jelly answer.
```
‚àû2lUfvO4=A‚àû
‚àû # palindromize
2l # overlapping pairs
U # uniquify
f # flatten
vO # for each in number input count how many times it occurs
4= # is equal to four?
A # are all true?
‚àû # palindromize
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ûü2Ù˜s¢4QPû
```
-4 bytes thanks to *@CommandMaster*.
-1 byte porting [*AndrovT*'s Vyxal answer](https://codegolf.stackexchange.com/a/257530/52210), which is based on [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/257534/52210), so make sure to upvote both of them as well!
[Try it online](https://tio.run/##yy9OTMpM/f//8O7De4wOzzw9p/jQIpPAgMO7//@PNtQx1jEBQmMdIx3DWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8O7D@8xOjzz9JziQ4tMAgMO7/6v8z86OlYn2lDHSMdYxxDMArGNYnUUoiFcI6g0jGWsYwKExiCR2FgA) or [verify its own source](https://tio.run/##ATYAyf9vc2FiaWX/Iv/Du8O8MsOZy5xzwqI0UVDDu/8iwrZLw5A/IiDihpIgIj/FvsSGc1Nrcy5WP/8).
**Explanation:**
```
û # Palindromize the (implicit) input-list
ü2 # Get all overlapping pairs of this list
√ô # Uniquify the pairs
Àú # Flatten it
s # Swap the (implicit) input-list to the top of the stack†
¢ # Count how many times each value of the input occurs in the list
4Q # Check for each count whether it's equal to 4 (1 if 4; 0 otherwise)
P # Get the product to check if all are truthy
û # No-op palindromize (1 or 0 will remain as is)
# (after which the result is output implicitly)
```
‚Ć Could be just `I` (push input), but with a swap it's easier to write the source verifier. ü§∑
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~21~~ 20 bytes
```
s₂ᶠ{|↔ᵐ}ᵇcdhᵍlᵛ2∨?Ės
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9PDbQuqax61TXm4dULtw63tySkZD7f25jzcOtvoUccK@yPTiv//jzbUMdYxAUJjHSMdw9j/UQA "Brachylog – Try It Online")
This code is self-validating because all symbols are used only once, except `s` used at the very beginning and very end.
3 bytes lost to deal with the empty list.
### Explanation
```
s₂ᶠ Find all sublists of 2 consecutive elements
{|↔ᵐ}ᵇc Append the list of reversed sublists to it
d Remove duplicate sublists
hᵍ Group by the first element of each sublist
l·µõ2 Verify that each group has length 2
∨?Ė Else: the input is the empty list
s Sublist of the empty list, always succeeds (only here for self-validation constraint)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
IΠmo=4`#ΣuẊe§+h↔¹I
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b/nuQW5@bYmCcrnFpc@3NWVemi5dsajtimHdnr@//8/WklJR8nQyNgQRBkaGYEosIghmGlsYmJsBBLAbYhSLAA "Husk – Try It Online")
Outputs `1` if every integer present has exactly two neighbors, `0` otherwise.
Could be [17 bytes](https://tio.run/##yygtzv6f@6ip8b/nudm2JrkJyucWlz7c1ZV6aLl2xqO2KYd2ev7//z9aSUlHydDI2BBEGRoZgSiwiCGYaWxiYmwEEsBphlIsAA) with output as truthy (nonzero) or falsy (zero).
```
I # identity = leave input unchanged
I # identity = leave output unchanged
Π # get the product of
m # mapping over the input:
o # composition of 2 functions:
`# # number of instances
=4 # equals 4
Σ # among all elements from
u # unique
Ẋe # adjacent pairs
+ # in the concatenation of
h # the head (omit last item)
‚Üî # and the reverse
¬π # of the input
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
!!smn2l{fPI<1T.-R]dC,tQQ
```
[Try it online!](https://tio.run/##HUw9D0AwEP0rtZe01dZJbCYbYpNuIgZEoov48fXO8N7d@7i7nrillGX3cZr9Xfuu0VORj2FpZRyGlOaylIKhtQOpmjclhVOsCGQ4VEYKglVBeEyLHllMD@CQkNd/EaGvYFp@hJQ0I3w "Pyth – Try It Online")
Outputs False for truthy and True for falsy. Self validating since each character is used only once except the start and end which are repeated once.
### Explanation
```
!!smn2l{fPI<1T.-R]dC,tQQQ # implicitly add Q
# implicitly assign Q = eval(input())
m Q # map Q over lambda d
C,tQQ # take all pairs of adjacent elements in Q
.-R]d # remove d from each pair once if possible
f # filter for pairs that are no longer pairs by looking at
PI<1T # T[:-1] == T[:-1][:-1]
{ # deduplicate
n2l # number of remaining elements != 2
s # sum (if any elements did not have two neighbors the sum will be non zero)
!! # not not (takes 0 to False and non zero to True)
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 13 bytes (26 nibbles)
```
|$!=2,|`$.!>>@_:`<$?$@ ~39
```
This corresponds to the [Nibbles](http://golfscript.com/nibbles/index.html) program with bytes:
```
93 c0 1a d9 ec 9c 04 51 e3 d4 f3 40 93
```
Output is falsy (empty) if all elements have exactly 2 neighbours, truthy (nonempty list of elements that do not have exactly 2 neighbours) otherwise.
```
|$!=2,|`$.!>>@_:`<$?$@ # main program:
| # filter
$ # the input
# keeping elements for which
,| # the number of
`$.!>>@_:`<$ # of all adjacent pairs
?$@ # that contain them
!=2 # is not equal to 2
`$.!>>@_:`<$ # adjacent pairs:
`$ # get unique elements of
. # map over
!>>@_: # all adjacent pairs
`<$ # sorting them
~39 # finally append nibbles 0 9 3
```
[](https://i.stack.imgur.com/dU9In.png)
[Answer]
# Javascript, ~~202~~ 199 bytes
```
a=>{let o=1;a.forEach(i=>{let n=[];a.forEach((j,y)=>{if(j==i){if(y!=0)if(!n.includes(a[y-1]))n.push(a[y-1]);if(y!=a.length-1)if(!n.includes(a[y+1]))n.push(a[y+1])}});if(n.length!=2){o=0;}});return o}
```
Gets an array as input and return `1` for true and `0` for false
Ungolfed version:
```
let x = a => {
let o = 1;
a.forEach((i) => {
let n = [];
a.forEach((j, y) => {
if (j == i) {
if (y != 0) if (!n.includes(a[y - 1])) n.push(a[y - 1]);
if (y != a.length - 1) if (!n.includes(a[y + 1])) n.push(a[y + 1]);
}
});
if (n.length != 2) {
o = 0;
}
});
return o;
};
```
[Try it online!](https://tio.run/##bYxNCoMwEIX3PYXuEqrB2KVMdz2FuAgxaiRMJGpRxLNbYy200NW8n/leK56il053Q4y2VJtRQzDBJuC@eGmBZ4JV1j2EbIg@U4S8@IpJG810r3RFWgBNvZhDSOh@Q2QapRlL1RORzzEvKEXWjX3zsdn7WzCjsB6amP/Brr@Yt@t6kHhiIaR0sZBkPndqGB0Gdt2kxd4axYytyURyHqXRLfJjlz9NejTbCw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
# Objective
Given a string with single Unicode vulgar fraction, parse it to a rational number.
# Valid inputs
A valid input is one of:
* `¼` U+00BC; one quarter
* `½` U+00BD; one half
* `¾` U+00BE; three quarters
* `⅐` U+2150; one seventh
* `⅑` U+2151; one ninth
* `⅒` U+2152; one tenth
* `⅓` U+2153; one third
* `⅔` U+2154; two thirds
* `⅕` U+2155; one fifth
* `⅖` U+2156; two fifths
* `⅗` U+2157; three fifths
* `⅘` U+2158; four fifths
* `⅙` U+2159; one sixth
* `⅚` U+215A; five sixths
* `⅛` U+215B; one eighth
* `⅜` U+215C; three eighths
* `⅝` U+215D; five eighths
* `⅞` U+215E; seven eighths
* `⅟` (U+215F; fraction numerator one) followed by ASCII decimal digits (U+0030 – U+0039)
* ASCII decimal digits followed by `⁄`(U+2044; fraction slash) followed by ASCII decimal digits
There are exceptions. See below.
# Invalid inputs
If the denominator is zero, the parser must fall in an erroneous state. This includes:
* Monadic failing
* Returning an erroneous value
* Throwing an error
# Rules
1. Encoding of the input doesn't matter.
2. Output type and format doesn't matter either. Though native rational number type is preferred, a pair of integers is permitted.
3. Inputs that are neither valid nor invalid fall in *don't care* situation. This includes:
* Whole numbers
* Improper fractions
* Reducible fractions
* Fractions with zero numerator
* Negative fractions
# Examples
`⅛` (U+215B) parses to one eighth.
`⅟13` (U+215F U+0031 U+0033) parses to one thirteenth.
`24⁄247` (U+0032 U+0034 U+2044 U+0032 U+0034 U+0037) parses to twenty-four 247ths.
`1⁄7` (U+0031 U+2044 U+0037) parses to one seventh. Note that `⅐` and `⅟7` will parse to the same.
`0` (U+0030) falls in *don't care* situation. It's a whole number.
`9⁄8` (U+0039 U+2044 U+0038) falls in *don't care* situation. It's an improper fraction.
`4⁄8` (U+0034 U+2044 U+0038) falls in *don't care* situation. It's reducible to one half.
`↉` (U+2189) falls in *don't care* situation. Its numerator is zero.
`-½` (U+002D U+00BD) falls in *don't care* situation. It is negative.
`1⁄0` (U+0031 U+2044 U+0030) must make the parser be in erroneous state. Its denominator is zero.
# Ungolfed solution
## Haskell
```
import Control.Monad
import Data.Ratio
import Text.ParserCombinators.ReadP as ReadP
import Text.Read
import Text.Read.Lex
fractionParser :: ReadP Rational
fractionParser = choice [
char '¼' >> return (1 % 4),
char '½' >> return (1 % 2),
char '¾' >> return (3 % 4),
char '⅐' >> return (1 % 7),
char '⅑' >> return (1 % 9),
char '⅒' >> return (1 % 10),
char '⅓' >> return (1 % 3),
char '⅔' >> return (2 % 3),
char '⅕' >> return (1 % 5),
char '⅖' >> return (2 % 5),
char '⅗' >> return (3 % 5),
char '⅘' >> return (4 % 5),
char '⅙' >> return (1 % 6),
char '⅚' >> return (5 % 6),
char '⅛' >> return (1 % 8),
char '⅜' >> return (3 % 8),
char '⅝' >> return (5 % 8),
char '⅞' >> return (7 % 8),
char '⅟' >> do
d <- readDecP
guard (0 /= d)
return (1 % d),
do
n <- readDecP
char '⁄'
d <- readDecP
guard (0 /= d)
return (n % d)
]
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 17 bytes
```
{S!\⅟!1/!.EVAL}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Olgx5lHrfEVDfUU91zBHn9r/aflFCtFKh/Yo6Sgd2gsi9gGJR60TwOREMDkJTE4Gk1PA5FQwOQ1MTgeTM8DkTDA5C0zOBpNzwORcMDkPTM43NAbSRib6RibmQIahvjlEGMIxUIpVqOZSKE6sVEhTUInnqlX4DwA "Perl 6 – Try It Online")
Returns a rational number type. Raku actually natively supports unicode literals and operators, though it doesn't do `⅟`, so we need to substitute for that. Also, division by zero won't cause an error, but returns a value that causes an Exception when you try to use or print it.
[Answer]
# [PHP](https://php.net/), 80 bytes
```
preg_match("~(\d+)/ ?(\d+)~",iconv('','US//TRANSLIT',$argn),$m);echo$m[1]/$m[2];
```
[Try it online!](https://tio.run/##K8go@G9jXwAkC4pS0@NzE0uSMzSU6jRiUrQ19RXswXSdkk5mcn5emYa6uo56aLC@fkiQo1@wj2eIuo5KYlF6nqaOSq6mdWpyRr5KbrRhrD6QNIq1/g8SUFCKyYvJU7LmSssvSk0EGh2tdGiPko7Sob0gYh@QeNQ6AUxOBJOTwORkMDkFTE4Fk9PA5HQwOQNMzgSTs8DkbDA5B0zOBZPzwOR8Q2MgbWSib2RiDmQY6ptDhCEcA6VYhcRiBYgXqrkUgADiZLCIgq6dAtDdIFFqhwySVeCwqf0P9Pi//IKSzPy84v@6bgA "PHP – Try It Online")
Just letting `iconv` do all the work for us ^^ this time PHP is competitive :O
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
¿№θ⁄⪫⪪θ⁄¦/¿№θ⅟⭆θ⎇κι1/«§”)⧴≦Y�δ↥1≧Y”℅θ/I⊕§”)¶@≦IG@℅⁵∧ψ”℅θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8zTUHDOb80r0SjUEdB6VFji5KmpkJAUSZQwCs/M08juCAnE0kOSOsDVVhzpeYUpyqgaW6dj9AcXAKk0n0TC0BSIalFeYlFlRrZOgqZQIWGICNgZlRzcUJ0OJZ45qWkVmgoGYKBkaGRsYmhqaGxqbmBgYGhko6Cf1FKZl5ijkYhWDNUF8g5cI5zYnGJhmdeclFqbmpeSWoKkpnGZhaWRkYmQGBqag4EQDON0cwEmVr7//@j1kn/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a pair of integers separated with `/` for convenience. Explanation:
```
¿№θ⁄
```
If the input contains `⁄`,
```
⪫⪪θ⁄¦/
```
then replace it with a `/`.
```
¿№θ⅟
```
If the input contains `⅟`,
```
⭆θ⎇κι1/
```
then replace it with `1/`.
```
«§”)⧴≦Y�δ↥1≧Y”℅θ/I⊕§”)¶@≦IG@℅⁵∧ψ”℅θ
```
Otherwise look up the ordinal of the input in two compressed strings, one for the numerator, one for the denominator, and then increment the denominator (so that `1/10` can be handled).
Alternative version for 73 bytes:
```
¿№θ⁄«≔I⪪θ⁄θI∕§θ⁰⊟θ»¿№θ⅟«I∕¹I✂θ¹»I∕⊕§”)➙⧴ω⪪B⪪◨ιY”℅θ⊕§”)¶@≦IG@℅⁵∧ψ”℅θ
```
[Try it online!](https://tio.run/##bY5NCsIwFITX9hSPrhKIkLT1j66Kbrqy4AlKGzUQ019FEBeCXsALeDcvEtNaRKyze7z5ZibZxmWSxVJrsQY0z/aqRgUB@3m52hjDyRoEVSU2Cs3jqkarXIrvP4EC@9YgKoXBWsdCHETKUVCHKuXHxkqNK8pyVGAj3zoDlxWHn7bbo2vrRzEC724pEt64Ge6SrDapT4QqKfmOq5qnnyE2bcUoc1zqUccbN6dNYFmmQsWynUfgL8rc8XTmOJ7RaDQxMqT7gzaLtH7e7np4kC8 "Charcoal – Try It Online") Link is to verbose version of code. Output is a decimal fraction. Explanation:
```
¿№θ⁄«≔I⪪θ⁄θI∕§θ⁰⊟θ»
```
Handle the `⁄` case by dividing the numerator by the denominator.
```
¿№θ⅟«I∕¹I✂θ¹»
```
Handle the `⅟` case by taking the reciprocal of the denominator.
```
I∕⊕§”)➙⧴ω⪪B⪪◨ιY”℅θ⊕§”)¶@≦IG@℅⁵∧ψ”℅θ
```
Look up the decremented numerator and denominator in two compressed strings and divide their increments. (As I need the numerator as an integer anyway, incrementing it actually makes the string more compressible.)
[Answer]
# JavaScript (ES6), ~~125 120~~ 106 bytes
```
s=>([n,d]=s.split(/\D/),d)?(n||1)/d:'131111121234151357'[i=s.charCodeAt()%63%20]/-~'133689224444557777'[i]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k4jOk8nJda2WK@4ICezREM/xkVfUydF014jr6bGUFM/xUrd0NgQBIwMjYxNDE0NjU3N1aMzgRqSMxKLnIEGOZZoaKqaGasaGcTq69YBlRubWVgaGZkAgampORAAlcf@T87PK87PSdXLyU/XSNNQetQ6W0lTkwtDdL6hMRZxI5NHjS1GJuZYpAyBMrjEDbBaMQko@h8A "JavaScript (Node.js) – Try It Online")
[Answer]
# Groovy, 96 bytes
```
import static java.text.Normalizer.*
def f={s->Eval.me(normalize(s,Form.NFKC).replace("⁄","/"))}
```
[Try it online!](https://tio.run/##Sy/Kzy@r/P8/M7cgv6hEobgksSQzWSErsSxRryS1okTPL78oNzEnsyq1SE@LKyU1TSHNtrpY1861LDFHLzdVIw8mrVGs4wZk6/m5eTtr6hWlFuQkJqdqKD1qbFHSUdJX0tSs/Z9YXJwKtCINKNo6W0lTwdZWwVDfggtZeL6hMUzC0Pg/AA "Groovy – Try It Online")
Uses Unicode Normalization to replace the digits with ASCII digits. Then replaces the fraction slash by an ASCII slash and evaluates the resulting string.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~78~~ 76 bytes
```
lambda s:eval(normalize('NFKC',s).replace(*'⁄/'))
from unicodedata import*
```
[Try it online!](https://tio.run/##Pc67CsIwGIbhvVcRujQpxeNWcBJcBG9AHWKbYiBNSloF3QTdPZ8PN6IOXkpvpLb@4PI@3/hFk2SoZD0LGr1M0HDgUxS7bEwFlkqHVPApw1an1W5aTkxKmkWCegzbVjqbly1CjECrEI0k95TPfJpQxMNI6cTOAqURR1x2DfPzNJ28r1/fRdPFElgBa2ADbIEdsAcOwBE4AWfgAlyBG3AHHrXCav73Pyqm0XdRpLlMcIA5IdkX "Python 3 – Try It Online")
A lazy built-in solution in Python.
2 bytes saved by dingledooper.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 136 bytes
```
T`¼-¾⅐-⅟`L
B
1/2
D
1/7
E
1/9
F
1/10
G|H
$&3
A|C
$&4
[I-L]
$&5
M|N
$&6
[O-R]
$&8
[AGIMOS]
1/
H|J
2/
[CKP]
3/
L
4/
N|Q
5/
R
7/
⁄
/
```
[Try it online!](https://tio.run/##nZPPbtNAEMbv8xRzQJSqNf4TByfHUqAtpC0UeooidRNP6hX2brS7bgTKpVKDxI07h74IcMij5EXCOE6lNOIQcdnxruf7zef9ZENOKrFYfLqa/fJmf@bTH958en/VgZcQ@hG84jWB17y24Q2vYQBHk2N48rQBB5NDrjF0T7xOj5@acDo54/oCuufeRXXSgu7B0cnp@cceK@F48hYiH7qH7973oOFDB2IfziYfoOnDBSQ@zG/vwF8s5tOf@OxyLwqb/V0cCWPJotOoFSHJ68xlzwHYYthYdQ3xci8IGmFdGpsal0njiNRSF8U8JIqTSsrNUa2JuURBHOPmIZdknefGzPniDXVpkCkus8wMGfkADB@Rkk0vlm4qI/uotKucCYd84ShUyvU@wbHM81qynJaxQhTEM4IVP9jFochzi1JhqtWOw4Ew3CVdKZzUah@l27EocJzpnFCVRZ8M69vssbVitB95bG1JVCiLkdEjMjg0YlC9Ym68xo3/h2soLQeyn9PDFWUiH1YBf/tex9tqbwGy1ZeSEU4blBa/ktHM8Ga/a2tRuvTUT7dAVXpF17y/oVW4wT/D5SiK0josxGdaRrXMzWCfKjwZo43SpUXrhKPaZEpKF/y3rdv8Cw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: By transliterating the UTF-8 characters to uppercase letters we can avoid massive UTF-8 encoding penalties which would otherwise make the shortest solution a series of replacements one for each fraction character (154 bytes in total). Instead I can squeeze out a few bytes by sharing replacements between fractions with the same denominator and then again with the numerator, particularly with fifths and eighths.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~90~~ ~~88~~ 65 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
gi•QλÖìʒ¨ù·'á!÷€āW•2ô2ÝƵ∞+14ÝŽX=+«çIkè`>/ëćÇŽX€åizë\ŽW&ç¡`D_iõEë/
```
[Try it online](https://tio.run/##AXcAiP9vc2FiaWX//2dp4oCiUc67w5bDrMqSwqjDucK3J8OhIcO34oKsxIFX4oCiMsO0MsOdxrXiiJ4rMTTDncW9WD0rwqvDp0lrw6hgPi/Dq8SHw4fFvVjigqzDpWl6w6tcxb1XJsOnwqFgRF9pw7VFw6sv///ihZ8yMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf/TMx81LAo8t/vwtMNrTk06tOLwzkPb1Q8vVDy8/VHTmiON4UBZo8NbjA7PPbb1Ucc8bUOTw3OP7o2w1T60@vDyyuzDKxLs9A@vPtJ@uB0oCtRxeGlm1eHVMUf3hqsdXn5oYYJLfObhra6HV@v/r62t1fkfrXRoj5KO0qG9IGIfkHjUOgFMTgSTk8DkZDA5BUxOBZPTwOR0MDkDTM4Ek7PA5GwwOQdMzgWT88DkfENjIG1k8qixxcjEHMg0BLLMIVIwroFSLAA).
**Explanation:**
```
gi # If the length of the (implicit) input is 1:
•QλÖìʒ¨ù·'á!÷€āW• '# Push compressed integer 131133161819122214243444155517375777
2ô # Split it into parts of size 2:
# [13,11,33,16,18,19,12,22,14,24,34,44,15,55,17,37,57,77]
2Ý # Push list [0,1,2]
Ƶ∞ # Push compressed integer 188
+ # Add it to each value
14Ý # Push list [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
ŽX= # Push compressed integer 8528
+ # Add it to each value
« # Merge the two lists together
ç # Convert each to a character:
# ["¼","½","¾","⅐","⅑","⅒","⅓","⅔","⅕","⅖","⅗","⅘","⅙","⅚","⅛","⅜","⅝","⅞"
Ik # Get the index of the input in this list
è # Use it to index into the list we created earlier
` # Pop and push both digits separated to the stack
> # Increase the denominator by 1
/ # And divide them by one another
ë # Else (the length is not 1):
ć # Extract the first character of the (implicit) input
Ç # Convert it to a unicode integer-list
ŽX€ # Push compressed integer 8543
åi # If it's in the list (thus the first character was '⅟'):
z # Push 1 divided by the remaining value
ë # Else (the first character is not '⅟'):
\ # Discard the partial input
ŽW& # Push compressed integer 8260
ç # Convert it to a character "⁄"
¡ # Split the (implicit) input by "⁄"
` # Push both values separated to the stack
D_i # If the top value (the denominator) is 0:
õE # Loop "" amount of times, resulting in an error
ë # Else:
/ # Divide the two values by one another
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how all the compressed integers work.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~273~~ \$\cdots\$ ~~248~~ 240 bytes
Saved 8 bytes thanks to [pppery](https://codegolf.stackexchange.com/users/46076/pppery)!!!
```
lambda s:{'¼':1/4,'½':.5,'¾':3/4,'⅐':1/7,'⅑':1/9,'⅒':.1,'⅓':1/3,'⅔':2/3,'⅕':.2,'⅖':.4,'⅗':.6,'⅘':.8,'⅙':1/6,'⅚':5/6,'⅛':1/8,'⅜':3/8,'⅝':5/8,'⅞':7/8}.get(s[0])or eval(s.replace('⁄','/').replace('⅟','1/'))
```
[Try it online!](https://tio.run/##lZPNbptAFIX3fgrKZkAimJkBBpDcF0mycJ1xasl1EJAqqeVFpbpSd83/f/wiSRZ@FL@Ie@8dElMrldyR7pnvnsOMBzD5cfX5YCSX/c7Octj98mmva5XZmM2fWMbbocfmzyzzI5hfWCbRWEx/Y6SQTpBSpFO4iiOcoSWRzlkmDF1AKBAuAWiLK4AY4RogQbjBdWTdsiwydIcepff440QPmBI9sky1k4m/ryun3A523YPC0l@7Q6f0C50Puz3tsMX3H8xjbeY2rOkMLA6euyysjuUcsp1DocIe8yyDXDK3VemyKjG2YQGXtmfzNk0ihE1FqAADqBS6BOawnhc/f4FuzZ9B509oTGchrUYlGxxBDur8BURSCE/WpIpSRc2JsVKyUmpOjcUDc6iA2jNjmoNKas7xtDVfmDiiOKLmkmLDV3QIw9d4NzXfmGUxLYupuQWNar4zcUIx3f30nnYy/ECXGn4EVTXPzMkD223po1z3Kr2HTzrwAxWnQq5Uev/wUsXjKE15GohEhgH3Ao/7XESQRZ7d7w6GH@y3OfApWEmz1JvwUCSRauj/eGtjc6tRcm1sbMVr431LNCqsK64rqYu/s25TL/n7XOH7lnlJTZVqpbFYaaJede2Fuq0@fOqVp63ByPo2yB36Vr3Xv5KbtSwYVXFsAAd@yX2ncsnQRz2dV1nZYbQfIzMvBqPK6dvjamJtfbTG5cQaF9tlp6N3J7a7/AM "Python 3 – Try It Online")
A straight-up mapping of Unicode vulgar fractions to their values (`↉` (U+2189) falls into the *"don't care"* situation so throws an exception) or failing that, replaces `⅟` (U+215F) with `1/` (ASCII 49 + ASCII 47) and `⁄` (U+2044) with `/` (ASCII 47) and does an `eval`. So either returns the value (for valid input) or throws an exception (for invalid input).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~153~~ 151 bytes
```
lambda s:F(s.translate({8260:47,8543:"1/"}))if s[1:]else F(numeric(s)).limit_denominator()
from fractions import Fraction as F
from unicodedata import*
```
[Try it online!](https://tio.run/##Nc5LTsMwEAbgdXyKUVYxCqEtBapIZQU5BA9FJnGEpdiOxi5KhVggwZ73@3ERYNGj9CJhUMviG43s3zNupv7YmvWuGh90tdBHpQCXZpFLPArjauFldDoabPbS4VY82hiup2F/LTzjXFXg9vvpoaydhCwyEy1RFZHjPKmVVj4vpbFaGeEtRpxVaDVUKAqvrHGgdGPRQ7Y8AOEgW2QmRhW2lKXwYpla6ZZpN3Wssgj03IAWTeQ8JkQ18d8dtaUyPGWBxynVoIUxVPQjFsi2kI2HPYl2R50oRyt3EWkU7ZXtf1a2SZ4XtXAuz6kzQss8Z0GDyvgIZYM0K4ZwdTuMoeXd7IvNvtnsh80vr8g1uSG35I7ckwfySJ7IM3khr@SNvJMP8jlg/fn5xaL2fgE "Python 3 – Try It Online")
---
A not-so-lazy Python solution that returns the correct rational number as a `fraction.Fraction` instead of its floating point approximation.
## Explanation
We need to distinguish between two cases:
### Case 1: input length ≠ 1
```
Fraction( s.translate({ 8260: 47, 8543: "1/" }) )
```
Replace a couple of codepoints
* 826010 (U+2044, `⁄`) → 4710 (U+002F, `/`)
* 854310 (U+215F, `⅟`) → `1/`
and parse the result as a `Fraction`.
### Case 2: input length = 1
```
Fraction(unicodedata.numeric(s)).limit_denominator(10)
```
Convert the input codepoint into its floating point representation using `unicodedata.numeric` and subsequently as a `Fraction`. Unfortunately the intermediate representation as a floating point value loses some precision and we need to approximate the intended value using `Fraction.limit_denominator` and the knowledge of the largest occurring denominator 1,000,000 (actually 10 but the [function’s default argument value](https://docs.python.org/3/library/fractions.html#fractions.Fraction.limit_denominator) is good enough).
Unfortunately we cannot merge the code paths for conversion to `Fraction` of both cases since the denominator limitation will return incorrect results for large denominators in case 1.
[Answer]
Perl5:
```
perl -CiIO -Mutf8 -MUnicode::Normalize -pe '$_=NFKD$_'
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-funsigned-char`, 317 239 234 bytes
Thanks to ceilingcat for the changes!
To save some size, I preload the numerator with `1` (the denominator will usually be set to `0` on test failures so that the function will return an invalid value: generally `NAN` or `INF`, but some of the "don't care" inputs give other values.) I then look for the common cases and return the result.
It's a somewhat brute-forced function, given that I'm not using any character classification or normalization to assist: I decode the first byte to determine whether I'm looking at a precomposed fraction or not, and then apply rules from what is found.
```
#define S(x)strtol(x,&s,0)*!
n,d;float f(char*s){n=1;d=*s<58?n=S(s)0,*s|s[1]?s+=3,S(s)*s:0:*s-194?d=0[s+=2]-144,d<1?7:d<2?9:d<3?10:d<5?n=d-2,3:d<9?n=d-4,5:d<11?n=4*d-35,6:d<15?n=2*d-21,8:S(++s)*s:*++s<191?n=*s-187,4:0;return(n+.0)/d;}
```
[Try it online!](https://tio.run/##LZBLbtswEIb3PIXqIAVJUykpybWe0SG8NLwwRNER4FCGhgYMuF4UaAt01/e7zUWSLHwUH6TqyOjim38ePzgYVv6qqvr@QtemsbU3ozsGrnPtmu7EUxCS8SfECp2Zdbt0nqHVzbLjwPa2UJkuOOSTuLTFjAKTgsMLmKtFCeMiFEOLQypTDr5KolIXco6DYOGrKBI6V@U01XlQJhjDUkmUCb6k/UCEmCfnPBITzJXCIuLaDyfi@VAPxgDrQIk4ndHx@LyKo@YqGczDzngqolRmXe22naV2fCXZM50d@ovmdtN2Lgenm/bq5prcLhtL2d603fk6D@axXAjuMrOqHVAQsRSD2bJss8XGaMTYvjHUFY3V9Q4NSjLGXSGzTddYZ@joErzi2rs0IwHC4Eew7HDoj/fk@ECOj@T0@h3yHvmAfEQ@IZ@RL8hX5BvyHfmB/ER@Ib@RP@R/406FJIhOL18F0ZQo1CmRJEGNSXSOpzdviY/rhpn8W5n1cgW9b7YWmpWttT9c@g8 "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
Prints a representation of a Ruby Rational type.
```
$_=eval $_.unicode_normalize(:nfkc).sub ?⁄,"r/"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6FjcNVeJtU8sScxRU4vVK8zKT81NS4_Pyi3ITczKrUjWs8tKykzX1ikuTFOwfNbboKBXpK0E0QvUv2PeodTbXo9b5hsZcRiZAJUYm5lyGQBpCGkBUAQA)
] |
[Question]
[
In [set theory](https://en.wikipedia.org/wiki/Set_theory), a set is an unordered group of unique elements. A pure set is either the empty set \$\{\}\$ or a set containing only pure sets, like \$\{\{\},\{\{\}\}\}\$.
Your challenge is to write a program that enumerates all pure sets, in some order of your choice. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - you may:
* Output all pure sets
* Take an integer \$n\$ and output the nth set by your definition
* Take an integer \$n\$ and output the first n sets.
(\$n\$ may be 0 or 1-indexed)
Pure sets may be represented in any reasonable format.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins.
[Answer]
# [Python](https://www.python.org), 43 bytes
```
f=lambda x:[f(i)for i in range(x)if x>>i&1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tdNscxJzk1ISFSqsotM0MjXT8osUMhUy8xSKEvPSUzUqNDPTFCrs7DLVDGMhWnZn2hpwlWdk5qRGFxRl5pVogHRpxlplatsaQlTADAcA)
Outputs the \$ n \$th set, starting at \$ 0 \$.
One way of creating a sequence of all pure sets is to encode them as binary numbers, with bits set according to which indices of pure sets they do and do not contain.
For example, the empty set contains no sets, so it has no 1 bits, and its index is \$ 0 \$.
For the set `{{}}`, it contains only one item, the empty set, which has index 0, so we set a 1 bit in the 0th position: \$ 1 \$.
For the set `{{}, {{}}}`, it contains two items: the empty set with index 0, and the previous `{{}}` which has index 1. Therefore, we set the 0th and 1st bits: \$ 11\_2 = 3\_{10} \$
My program does the reverse of this process.
This is essentially the same as [my answer to Output every sublist ... eventually](https://codegolf.stackexchange.com/a/241143) but operating recursively on itself.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 9 bytes
Port of [pxeger's answer](https://codegolf.stackexchange.com/a/248716/64121).
```
{o'&|2\x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rOV1erMYqpqOXiSsstsarWUKpW0lHSUVDSz1ev0NRRqlWq5UowsKoGSiqkKVTUqisoGhkAALvmD1U=)
`|2\x` The argument converted to binary, reversed.
`&` Where, indices of 1s.
`o'` For each of those indices, call the function recursively.
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
-1 thanks to [pxeger](https://codegolf.stackexchange.com/questions/248715/enumerate-all-pure-sets#comment555783_248717)
```
f=lambda x,n=0:x*[1]and x%2*[f(n)]+f(x/2,n+1)
```
[Try it online!](https://tio.run/##BcFBCoAgEADAc71iL4GmkHoMeol4MGxrodYQD/Z6m3m/emV2veN2x2dPEZrmzaxt9jZETtAmN3sULINC0RanWVnZMRcgIIYS@TyENcbIdRzeQlyBNAqS/Qc "Python 2 – Try It Online")
A worse version of [pxeger's answer](https://codegolf.stackexchange.com/a/248716). The input's binary digits encode which sets are included.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÝæΔDè}Iè
```
Outputs the 0-based \$n^{th}\$ value.
[Try it online](https://tio.run/##yy9OTMpM/f//8NzDy85NcTm8otbz8Ir//00B) or [verify the first few test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/Dcw8vOzfF5fCKWs/DK/7rcIFkudLyixQyFTLzFKoN9PQMDWq5UvK5FBT08wtK9CHmQCk0o20UVDKBSvNS/xtwGXIZcRlzmXCZcgEA).
Outputting the first \$n\$ values would be 8 bytes as well by replacing the `è` with `£`:
[Try it online](https://tio.run/##yy9OTMpM/f//8NzDy85NcTm8otbz0OL//00B) or [verify the first few test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/Dcw8vOzfF5fCKWs9Di//rcIFkudLyixQyFTLzFKoN9PQMDWq5UvK5FBT08wtK9CHmQCk0o20UVDKBSvNS/xtwGXIZcRlzmXCZcgEA).
**Explanation:**
```
√ù # Push a list in the range [0, (implicit) input]
√¶ # Get the powerset of this list
Δ } # Loop until the result no longer changes:
D # Duplicate the list
è # And index each inner-most integers into itself
I # After the loop: push the input-integer again
è # And index it into the list
£ # Or alternatively leave that meany leading items from the list
# (after which the result is output implicitly)
```
[Try `‚àû<√¶` online](https://tio.run/##yy9OTMpM/f//Ucc8m8PL/v8HAA) to see (the infinite version of) the list it uses to reduce all inner integers down to `[]`.
[Answer]
# BQN, 20 bytes
```
{ùï䬮(2|¬∑‚åäùï©√∑2‚ä∏‚ãÜ)¬®‚ä∏/‚Üïùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlYrCqCgyfMK34oyK8J2VqcO3MuKKuOKLhinCqOKKuC/ihpXwnZWpfQoo4oCiU2hvdyDigKJSZXBy4oiYRinCqCDihpUxMDA=)
Based on [pxeger's answer](https://codegolf.stackexchange.com/a/248716/64121).
## Explanation
* `‚Üïùï©` range from 0 to input `x`
* `(...)¨⊸/` filter range over predicate...
* `2|¬∑‚åäùï©√∑2‚ä∏‚ãÜ` equivalent to `floor(x / 2^i) mod 2`
* `S¨` recurse on each filtered index.
[Answer]
# Rust, ~~113~~ 79 bytes
*-34 bytes thanks to @alephalpha*
```
struct K(Vec<K>);fn f(x:u64)->K{K((0..x).filter(|v|x>>v&1>0).map(f).collect())}
```
Could save 2 bytes by using `u8` instead but then it generates only 5 numbers before overlow. You could also use 128 bit integers to get more numbers. Algorithm copied from @pxeger.
Try it yourself: <https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1dbb90a9b8347a6cd554723dedbb93e1>
[Answer]
# x86-64 machine code, 28 bytes
```
B0 7B AA EB 0B 0F B3 C6 56 96 E8 F1 FF FF FF 5E 0F BC C6 75 F0 B0 7D AA C6 07 00 C3
```
[Try it online!](https://tio.run/##TVFNb9MwGD77/RUPmao5NJtKBxzadQcQR6Rp2gHU9eA4duLJcaI4HSlV//oyO8DGxR/P52tZXpRSjqPwNTjuEk6XpW1yYaFJr1jdPEHYDOfHc2K@b3xO7LFukZNYsbzvoLzJoMRArN37Cp03xAZZlRHLIktMChvTWNu0E58Hp9f/CR7dbwh66zq9dUXsy8/7b7i9v8O2K8wuw4JYp3pKE6RrempMAc1lJbr38BmM6@ECTmfGSbsvFK59X5jmsrohimQtjOMpHcNcwYNO@b3tt58@LHdrYrrpwKcIbLBYh@16g6tlOMznKbFgYpr/sWRTDWNtF/SaJzOzwsw/uCQQ2d/YKDjRq@TBfReyMk5BNoVaJZGOZUMsy3AI16LB8Z8cs8XyR4g7bDjfO29KpwpMD011uh3m8126PuFXZawCP@BdCBm@XsXQ1wQ@M8gPvfLpNNgQyNM4PkttRenHi/rzx7CEr98EvbIv "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input number in ESI.
This uses the same method as most other answers, with a set's number having 1s in binary positions corresponding to its elements' numbers.
In assembly:
```
f: mov al, '{'
stosb
jmp b
a: btr esi, eax
push rsi
xchg eax, esi
call f
pop rsi
b: bsf eax, esi
jnz a
mov al, '}'
stosb
mov BYTE PTR [rdi], 0
ret
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BṚT’߀
```
A recursive mondaic Link that accepts `n` (0-indexed) and yields the `n`-th pure set using the empty list as the empty set.
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//QuG5mlTigJnDn@KCrP/Dh8WS4bmY//8w "Jelly – Try It Online")**
### How?
```
BṚT’߀ - Link: non-negative integer, n
B - convert to binary
·πö - reverse
T - truthy indices (1-indexed)
’ - decrement (vectorises)
€ - for each:
ß - call this Link
```
[Answer]
# Haskell, 49 bytes
Outputs as a lazily evaluated infinite list. Each entry is encoded as a nested list.
```
import Data.List
data P=P[P]
p=P<$>subsequences p
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
λbṘTvx
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsIs67YuG5mFR2eCIsIiIsIjBcbjFcbjJcbjNcbjRcbjUiXQ==)
Port of Jelly.
```
λbṘTvx
λ # Open a lambda for recursion, f(x)
b # Get the binary representation of x (as a list)
·πò # Reverse
T # Get truthy indices of that (zero-indexed)
vx # For each, recurse
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
FN⊞υΦυ&ιX²λ⭆¹⊟υ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTIaC0OEOjVEfBLTOnBCgCZDlllpRnFqc65qVoZOooBOSXA4WNdBRyNIHAmiugKDOvRCO4BEil@yYWaBiClBRolIIk//@3/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 1-indexed `n`th set using `[]`s. Explanation:
```
FN
```
Repeat `n` times.
```
⊞υΦυ&ιX²λ
```
Extract the existing lists given by the binary decomposition of the current index and push the resulting list to the predefine empty list.
```
⭆¹⊟υ
```
Pretty-print the last list.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes
```
{`\d+
{$&*_}
+`(_+)\1
$1@
_(?=((@)|(_))*)
$#2$.3*,
@
```
[Try it online!](https://tio.run/##BcE7DoAgEAXA/l1DNLtgjOC/MNJ5CRIw0cLGwtihZ8eZ@3jOa9MppzWkGNyuEEUh/QcVyCt2GkJbeFpmIssveWbJEJkRVSNLWKRUQ8OgQYsOPQaMmH4 "Retina – Try It Online") Link includes test cases. Output's the 0-indexed `n`th set. Explanation:
```
{`
```
Repeat until all subsets have been constructed.
```
\d+
{$&*_}
```
Convert all integers to unary, and wrap them in `{}`s. Note that if the integer was `0`, there were no `_`s, so processing stops for this integer here.
```
+`(_+)\1
$1@
```
Partially convert them to binary, but using the "digits" `@_` and `@`. Normally for binary conversion you would then remove the `@`s before `_`s, but we only need the count of "digits", which here is simply the count of `@`s.
```
_(?=((@)|(_))*)
```
For each `1` in the binary representation, calculate its bit position and whether it's the last `1` bit...
```
$#2$.3*,
```
... and replace it with the position and append a `,` if this is not the last `1` bit.
```
@
```
Delete the remaining `@`s.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
f=->n{(0...n).select{|x|n[x]>0}.map &f}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vWsNAT08vT1OvODUnNbmkuqaiJi@6ItbOoFYvN7FAQS2t9j9IhaGBJogPki5QSAMqqP0PAA "Ruby – Try It Online")
Based on pxeger's python answer.
[Answer]
# [Julia 1.0](http://julialang.org/), 28 bytes
```
!k=[!i for i=0:k if k&2^i>0]
```
[Try it online!](https://tio.run/##LcxRCgIhEADQf08xO0RoRFh/LrjROaxAyoVJcWUwcE9vEb0DvNc7kT@23odo3UAwLwxk9RiBZojb050mfeuFQ62rbAoscCjJP4LETcM9MF6Y/XrYna8O7YQOlfgdQBn0aIwR8FWYck1Z/qOBlBIhP/sH "Julia 1.0 – Try It Online")
Port of [pxeger's answer](https://codegolf.stackexchange.com/a/248716)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
f=(x,i=0)=>x?[...x&1?[f(i)]:[],...f(x>>1,i+1)]:[]
```
[Try it online!](https://tio.run/##HctLCsMgEADQfQ9SRrQybms1B5EsQqJlimRKEoK3n3y2D95v2Id1XOi/vWaeskgJ0AwFVCG2Lllr29N1qQCp/p16c0KBFqMzpN1N4h@FFziLp49DRK81qZHnlWu2lb9wZSWCBw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
The aim is to trim elements in from the ends of a list, depending on if they are in a second list of "falsey" results.
For example, if the first list is `[-1, 1, 2, 0, -1, 3, -1, 4, -1, -1]` and the second is `[-1]`, then we would remove all leading and trailing `-1`s from the first input, but not any `-1`s in the middle: `[1, 2, 0, -1, 3, -1, 4]`
You may take input in any [allowed method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 36 bytes
```
f v|g<-reverse.snd.span(`elem`v)=g.g
```
[Try it online!](https://tio.run/##JYpBCoAgEAC/socOBSpZHvMlESS0maQiGp76uxnCwDAwl0o3WlvKCfnVC42YMSZkyR8sBeX7HS26PQ9SM12cMl6GaPwDHZywCkL5BivlBCoTgZHAH3OTaKpP@QA "Haskell – Try It Online")
* -1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
## How?
```
f v -- define a function f that takes as input a list v of falsey values
|g<- -- inside the definition, define a new function g that...
reverse -- reverses...
.snd -- the second element of...
.span -- a tuple (say (x,y)) where x is the longest prefix of elements that...
(`elem`v) -- belong to v...
-- and y is the rest of the list
=g.g -- f is defined as the composition g.g (basically apply g twice)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
.sF
```
[Try it here!](http://pythtemp.herokuapp.com/?code=.sF&input=%5B-1%2C+1%2C+2%2C+0%2C+-1%2C+3%2C+-1%2C+4%2C+-1%2C+-1%5D%2C+%5B-1%5D&debug=0)
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 19 bytes
```
[ '[ _ ∈ ] trim ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQWFycn1yskFZUqZCbWJKhV5qXmZyfkqpQUJRaUlJZUJSZV6JQnFpYmpqXnFqsYM1VrQCCuoYKhgpGCsYgBhDVQoRqwQxcssZg@dr/0Qrq0QrxCo86OhRiFUqKMnMVYv9XA2XALrHLTSxQ0PsPAA "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes two sequences as input and returns one sequence as output.
* `'[ _ ∈ ]` Push a fried quotation to the data stack to be used later by `trim`. Whatever is on top of the data stack gets slotted into the quotation at the `_`. This will be the list of elements to trim.
* `trim` Take a sequence and a quotation and apply the quotation to elements on both ends of the sequence, removing elements for which the quotation returns `t`. Stop when `f` is encountered.
* `∈` Take an object and a sequence and return `t` if the object is in the sequence. Shorthand for `member?`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 4 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous infix function.
```
⌂deb
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPU0pq0v@0R20THvX2PepqftS75lHvlkPrjR@1TXzUNzU4yBlIhnh4Bv8/tN5QIU0BRBoqGCkYgFnGYNIETAIxF0TWBK7OELs6AA "APL (Dyalog Extended) – Try It Online")
A library function: delete ending blanks using the left argument as a list of what is considered "blanks".
[Notes, comments, and APL implementation.](https://dfns.dyalog.com/n_deb.htm)
[Answer]
# Java, 89 bytes
```
a->b->a.dropWhile(b::contains).sorted((c,d)->-1).dropWhile(b::contains).sorted((c,d)->-1)
```
[Try it online!](https://tio.run/##jVDBSsQwEL33K3JMpA2uetpdAyIIgp568CAe0jStqWkSkulCkf32mjZlF3QPDoHHzHsz8yYdP/Ciq78m1TvrAXUxpwMoTV9UgF32p9wMRoCyhl5dIAN4yfuZckOllUBC8xDQK1cGfWcoxloPwCHCwaoa9ZHFJXhl2vcPxH0bSNLO8bSu25fL6P2zAdlKz/ITMfs8l3/JGGvuJ16wqmCc1t66t0@lJa62W2ENxMWB0BBvkDXGIq9JwYoN@bdw2p18lmMA2VM7AHXxEtAGN5Q7p0ecLFHb4GKTo/hucnSdozm5TXCXIE4ka8/5Sx@852OgPMx34kUirNZSAH5MaH2gYBeaEJIsHbPj9AM)
# Java, 125 bytes
```
a->b->{int i=-1,j=a.length;for(;b.contains(a[++i]););for(;b.contains(a[--j]););return java.util.Arrays.copyOfRange(a,i,j+1);}
```
[Try it online!](https://tio.run/##bVBBasMwELz7FTpKjSTqtjclhl4KhZZCcww5rB3ZletIRlqnmOC3u3IcQsFdBMPOrFYzquEEoj58j@bYOo@kjr3s0DTyzQRUyYIuO1ugcVbeqaTt8sYUpGggBPIOxpJzQmJd@YCAEU7OHMgxqnSL3thqtyfgq8Dm2alerjvXxuJuz2/tZGH9alFX2mf8ImZZuRlBZLnIzpEgZiNSXm9ANtpW@KVK56nKZeEsxhcDhd1qZfZMsX8UIeqL4jV23v7J@Ow99CGOtv1H@Qm20hS44fUqZWoY1c33tg@oj9J1KNuYDBtLF0vQzalpKaFtm55a/UMuUc7ROYnngZN7TqbmcYanGUQ6sOudxVYI099QkbJYs6EhGcZf)
[Answer]
# JavaScript (V8), ~~78~~ 62 bytes
*-16 bytes thanks to @Original Original Original VI*
```
(a,s,g=x=>s.includes(x[0])?g(x.slice(1)):x.reverse())=>g(g(a))
```
**Old:**
```
a=>n=>(t=z=>z.findIndex(d=>!n.includes(d)),a.slice(t(a),-t([...a].reverse())))
```
Can probably be shortened by a ton
[Answer]
# Scala, 46 bytes
```
s=>1.to(2)./:(_)((a,_)=>a.reverse dropWhile s)
```
[Try it in Scastie!](https://scastie.scala-lang.org/tM242wDJR5GxvkwdZVjc2Q)
```
s => //The Set of falsy items
1.to(2) //Make a range [1, 2] to trim twice
./: //Fold over it,
(_) //starting with the list to trim
((a, _) => //The list a and the number, which is ignored
a.reverse //Reverse the list
dropWhile //And drop while
s) //Each item is present in s
```
## Same length, but more boring
```
s=>_.dropWhile(s).reverse.dropWhile(s).reverse
```
[Try it in Scastie!](https://scastie.scala-lang.org/SumoSpnoTTOqsNWGB4MVGw)
Boring.
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
f=lambda a,b:a[-1]in b and f(a[:-1],b)or a[0]in b and f(a[1:],b)or a
```
[Try it online!](https://tio.run/##VYtLCoAwEEOvkmULI/jpquBJShdTpFjQKuLG04/FDyIEQl6S9djHJXcisZ94DgODKVh2VeNTRgDnAVGxswVQ0MsGdvW/auzbyLqlvKuoyp1Q1BJqwhMMobuDue3inuC@Qeu1FjkB "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
[#~[:(>./\*>./\.)1-e.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o5Xroq007PT0Y7RAhJ6moW6q3n9NrtTkjHwFjXhDHQUgMgLq0lEAcYwhlAmEijfUVEgDkv8B "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~57~~ 55 bytes
```
function(x,y,`+`=cumprod)x[!+x%in%y&!rev(+rev(x)%in%y)]
```
[Try it online!](https://tio.run/##dY/LCsIwEEX3/YoUaU1oFlZQMNAvEaGPxDZiJ5Kkkn59TCqKXbiZxZ055zLaWy1HAdxU/jpBZ6UC7OhM66Kuuml8aMWJO6eFyyRkc55q8cRFHI4sCbl4V5Ws3CXJBt0mY5EdBBol53eBMFewDUmoQA3MdpDQE5Z8KkPRgR1JJFvRS4CwRvkXftsiG5XGNtqu4Q6XbL8o1g6KwsGPaHG0yg4xN38c9BSeIMS/AA "R – Try It Online")
Finds matching elements (`x %in% y`) as vector of `TRUE/FALSE` values, and calculates the cumulative product (`cumprod`, re-assigned to `+` here to save bytes) to convert everything after the first `FALSE` to zero. Then does the same from the other end (by `rev`ersing `x` and the `cumprod`). Finally, negates (`!`) to select only the non-terminal-matching elements of `x`.
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
a,f=input()
for i in-1,0:
while a and a[i]in f:a.pop(i)
print a
```
The `a and` is necessary if the falsey list, `f`, contains all the elements of `a` and the completely stripped list will be empty. Without it, the program errors with `IndexError: list index out of range`.
[Try it online!](https://tio.run/##NYpBCoMwEEX3OcXfRWEqjXQl9CSSxYCmDpTJECKlp0@t4OLDe7xv37plHVtjSk9R22vXu5QLBKK3QPfJ4bPJewWDdQHPEkWRJh4sWye9syJawa3NgXzxNBIC4UH@5U@/FiLhuODPOGL8AQ "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 5 bytes
*Edit: -2 bytes thanks to Leo*
```
‼(↔↓€
```
[Try it online!](https://tio.run/##yygtzv7//1HDHo1HbVMetU1@1LTm////0YY6pjpmOpY6hgaxII6RjrGOCVjIXMcCIgwA "Husk – Try It Online")
**How?**
`↔↓€` removes the falsy elements from one end of the list, and then flips it:
```
↓ # drop the longest prefix of arg2 with elements that satisfy:
€ # are present in arg1
↔ # then reverse the result
```
So we just need to do this twice (to remove from both ends of the list, and to restore the list to its original orientation):
`(` groups `↔↓€` together (the parentheses are automatically closed at the end of the program), and the higher-order function `‼` runs a function provided as an argument twice.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
t
```
[Try it online!](https://tio.run/##y0rNyan8/7/k////0bqGOgpAZKSjYKCjAOIYQygTCKVrGAtREwsA "Jelly – Try It Online")
A builtin that does exactly this. Works with multiple "falsey" values as well: [Try it online!](https://tio.run/##y0rNyan8/7/k////0bpGOgq6hjoKQARkGUA4xhDKBEiBpWOB6gxBnFgA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Ú
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Kz//6N1DXUUDGO5ILSOgpGOgoGOAohjDKFMIJSuYSwA "05AB1E – Try It Online")
A builtin which trims.
[Answer]
# JavaScript (ES6), 56 bytes
Expects `(a)(b)`, where **a** is the array to trim, using the values in the set **b**.
```
a=>b=>(g=a=>a.reverse().filter(i=c=>i|=!b.has(c)))(g(a))
```
[Try it online!](https://tio.run/##JYzBCsMgEER/xd52QaVpe938RI8lB2NXaxEtKuml/24NgYE3D4Z5m81UW8KnqZSf3B11Q/NKM3gaxejCG5fKgNqF2LhAIEtz@NFp1S9TwSIieDCI3eZUc2QdswcHDzVJMXKR4izFLtcDtwNqWhASf8Wd2z5exlH/Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
#//.{e=#|##&@@#2,a___,e...}:>{a}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1lfX6861Va5RllZzcFB2UgnMT4@XidVT0@v1squOrFW7X9AUWZeiYJDenS1rqGOoY6RjoEOkGEMIkxABEi0VgcsWRv7/z8A "Wolfram Language (Mathematica) – Try It Online")
-6 bytes and correction from @att
[Answer]
# [Red](http://www.red-lang.org), 70 bytes
```
func[b t][while[find t b/1][take b]while[find t last b][take/last b]b]
```
[Try it online!](https://tio.run/##VY1BDsIgEEX3nOKn@6ZimxhdeAi3k1lAgbSxUoMYj4@D7UYWP2/yXkLyrty8I1bhUsI7jmSRmT7TvHgKc3TIsJ1myubuYflPLOYldnPdflguYU3ejBPIVKkgj1oNjSMOEOjrDHVazbvlLeulGaSqvtJJYo2zcM8gWQysmJ5pjhn0WBcHg6a9NvhxQP2Syxc "Red – Try It Online")
# Using `parse`, 123 bytes
```
func[b t][r: copy[]foreach n t[append r reduce['quote n '|]]take/last r
parse b[remove some r to[any r end]remove some r]b]
```
[Try it online!](https://tio.run/##VY1BbsJADEX3OcUXG1YRhERCsOAQ3VpeTDKOiiAzgzOphMTdU09bFvXi60nv21bx64d44mo8r@MSBuqRmfSMIaYn8RhV3PCJgEwuJQkeChW/DELbxxKzmNq@mLO7ye7u5gytktNZ0JPKFL8Ec5zEtnIkF54GdoT/Ke55fT8ih56pgg3VDRocsIdBW6IrUTf8Z/m31lqns1bxhY5WbnAybhlkiY4rpqTXkEFTvHs4bOrLBj88orzk9Rs "Red – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
m`^|$
,
(^)?,(([^,]+,)(?=.*¶.*,\3))*(¶.*)?(?(1)|$)
```
[Try it online!](https://tio.run/##K0otycxL/P8/NyGuRoVLh0sjTtNeR0MjOk4nVltHU8PeVk/r0DY9LZ0YY01NLQ0QU9New17DULNGRZPr/39dQx1DHSMdAx0gwxhEmIAIXUMuXUMA "Retina 0.8.2 – Try It Online") Explanation:
```
m`^|$
,
```
Wrap both lists in additional commas.
```
(^)?,
```
Record whether this match is at the very start, but at the very least start at a comma.
```
(([^,]+,)(?=.*¶.*,\3))*
```
Match any number of terms which exist in the second array.
```
(¶.*)?
```
Optionally match the second array.
```
(?(1)|$)
```
If the match did not begin at the start, then it must end at the end.
```
```
Delete the matching values.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 86 bytes
```
l->b->{while(b.contains(l.peek()))l.pop();while(b.contains(l.getLast()))l.pollLast();}
```
[Try it online!](https://tio.run/##bVBNa8MwDL3nV@hoj8Ss225JA2MwGHSnHscOTupkThzb2EpLKfntmb1k7FMY5Kf39CTU8SPPukM/y8Eah9AFzEaUil3lyZ9aM@oapdGRtGOlZA214t7DM5caLgmEWOseOYZ0NPIAQ2DJHp3U7csrcNd6umhjPK6exU7qXhx20mPxpFG0wpXpg9F@HIQrfpTLEprtrLKyysrL6U0qQSpWG41hjieKWSF6QikNP2MJzf@RtAJ33OOnSqkF5dOcf2x25A5UmAlb0OIE33Yryb1z/OwZ9xGTbJNCeDcpXKcQwe2S7paUbSj9sgw3GILlb4dV0TBurTqTOJgyXtfCIoktK78/exQDMyMyG46JSi/SyE7JNL8D "Java (JDK) – Try It Online")
Uses a `LinkedList` as input/output.
[Answer]
# [Desmos](https://desmos.com/calculator), ~~227~~ 215 bytes
```
z(A)=length(A)
h(l,a,k)=\left\{l[a]=k:0,1\right\}
f(a,b)=\sum_{n=1}^{z(b)}(1-h(b,n,a))
s=f(A,B)
j(A,B)=A[\sum_{N=1}^{z(s)}N(1-h(s,N,0))\prod_{a=1}^{N-1}h(s,a,0)...z(A)]
p=j(A,B)
q=j(p[z(p)...1],B)
m(A,B)=q[z(q)...1]
```
[Try It On Desmos!](https://www.desmos.com/calculator/gslxnrvixl)
[Try It On Desmos!(Prettified Version)](https://www.desmos.com/calculator/dpmeu1owbc)
Final function is \$m(a,b)\$, where \$a\$ is the list that is being trimmed, and \$b\$ is the list of "falsey" values that are trimmed from \$a\$.
Much harder than I initially anticipated because Desmos has limited list functionality. Hopefully it's fine if I output an one-element list with the one element being `undefined`(`[undefined]`) when the output is supposed to be an empty list(`[]`). If it isn't fine then tell me and I can fix(but it would cost more bytes ☹️)
Note: Not too sure why, but you can't directly paste the code into Desmos for some reason. You have to paste each expression one at a time in order for it to work.
[Answer]
# Excel, 70 bytes
```
=LET(x,A1#,r,ROW(x),y,IF(x>-1,r,""),FILTER(x,(r>=MIN(y))*(r<=MAX(y))))
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 13 bytes
```
jn m<rv.^dW<fe
```
# Explanation
To start we want to do the much simpler:
```
f x y=rv$dW(fe x)$rv$dw(fe x)y
```
This drops all things in `x` off the front, reverses it, then drops all things in `x` off the new front and reverses it back.
From here we can start by removing the `y`.
```
f x=rv<dW(fe x)<rv<dw(fe x)
```
Now we have the expression `rv<dW(fe x)` twice so let's fix that. `jn` will take a function on two arguments and pass the same value as both of its arguments.
```
f x=(rv<dW(fe x))<(rv<dW(fe x))
f x=jn m(rv<dW(fe x))
```
Now `x` is at the end so we can eta-reduce it away as well:
```
f x=jn m<rv.^dW<fe
```
## Reflection
Usually I would use `Rv` to reverse a list however `.^` next to `Rv` breaks the Haskell parser, so I had to use `rv` instead. I've been aware of this danger for a while now and this was a pretty close call. I will probably rename `.^` to `<<`.
"Compose a function with itself" achieved here with `jn m` is something that should probably have it's own name. It would have saved a byte here at least.
] |
[Question]
[
A donut distribution (for lack of a better term) is a random distribution of points in a 2-dimensional plane, forming a donut-like shape. The distribution is defined by two parameters: the radius `r` and spread `s`, in which the distance to the origin follows a normal (Gaussian) distribution around `r`, with a standard deviation `s`. The angular distribution is uniform in the range `[0,2π)`.
## The challenge
Given a radius `r` and spread `s`, your code should yield the Cartesian (`(x,y)`) coordinates of a single point chosen from this distribution.
## Remarks
* Running your code multiple times with the same input should result in the specified distribution.
* Outputting polar coordinates is too trivial and not allowed.
* You can output Cartesian coordinates in any way allowed by the default I/O rules.
+ This includes complex values.
## Valid approaches
Several algorithms can be used to yield the desired distribution, including but not limited to
1. Choose `a` from the uniform distribution `[0,2π)` and `b` from the normal distribution `(r,s)`.
Let `x = b*cos(a)` and `y = b*sin(a)`.
2. Choose `a` from the uniform distribution `[0,4)` and `b` from the normal distribution `(r,s)`.
Let `x+y*i = b*i^a`.
3. Choose `a,b,c` all from the normal distribution `(0,1)`.
Let `d = a+b*i` and `x+y*i = d/abs(d) * (c*s+r)`.
## Example distributions (N=1000)
`Below: r=1, s=0.1`
[](https://i.stack.imgur.com/ZyaOqm.png)
`Below: r=3, s=1`
[](https://i.stack.imgur.com/l1ajZm.png)
`Below: r=1, s=0`
[](https://i.stack.imgur.com/QqLjCm.png)
`Below: r=100, s=5`
[](https://i.stack.imgur.com/9kwTjm.png)
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 38 bytes [SBCS](https://github.com/abrudz/SBCS)
Takes `r` on the left and `s` on the right and returns a complex number.
```
{(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)ׯ12○2×○?0}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9Z41LtL@1Hv1sPTNfRMtR71rji03ujw9Ee98@0NNA9PN3w0vRuIgCJg7qH1hkYQLpC0N6gFAA&f=M1RIUzDQM@QyBtKGXIYgHpehgQGQNgUA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Uses the first approach presented in the question. Dyalog doesn't have a builtin for sampling from a normal distribution, so this uses the [Box–Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) to convert to random numbers from \$(0,1)\$ to a normally distributed value:
`(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)` draws a normally distributed value \$b \sim N(\alpha, \omega^2)\$:
`?0` random number \$c \in (0,1)\$
`1○○2×?0`: \$\sin(2\pi c)\$
`?0` random number \$d \in (0,1)\$
`.5*⍨¯2×⍟?0`: \$\sqrt{-2\ln{d}}\$
`‚ç∫+‚çµ√ó` Scale from \$N(0, 1)\$ to \$N(\alpha, \omega^2)\$
`?0` generates a random number \$a \in (0,1)\$
`¯12○2×○?0`: \$e^{i 2\pi a} = \sin(2\pi a)i + cos(2\pi a)\$
The product of these two values is the result.
Plotting code and images:
```
'InitCauseway' ‚éïCY 'sharpplot'
InitCauseway ⍬
sp←⎕NEW Causeway.SharpPlot(700)
sp.SetTrellis(2 2)
sp.TrellisStyle‚Üê4
F ← {(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)ׯ12○2×○?0}
:For r s :In (1 0.1)(3 1)(1 0)(100 5)
sp.NewCell
sp.Heading‚Üê'r = ',(‚çïr),'; s = ',‚çïs
sp.SetAxesScales(1)
sp.DrawScatterPlot↓9 11∘.○{r F s}¨⍳1000
:EndFor
sp.SaveSvg(⊂'plot.svg')
```
[](https://i.stack.imgur.com/3Ql6B.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
Xr*+Jr4*^*
```
Inputs are `r`, then `s`. Output is a complex number.
[**Try it online!**](https://tio.run/##y00syfn/P6JIS9uryEQrTuv/f0MuAz1DAA "MATL – Try It Online") Or see the plot for 1000 points at [**MATL Online**](https://matl.io/?code=xx1e3%3A%22%26G%0AXr%2a%2BJr4%2a%5E%2a%0A%5Dv%27.%27%26XG&inputs=1%0A0.1&version=22.4.0)! (it takes 10‒15 seconds).
### How it works
Uses method 2 described in the challenge.
```
Xr % Push random number with standard Gaussian distribution
* % Implicit input: r. Multiply
+ % Implicit input: s. Add
J % Push imaginary unit
r % Push random number with stantard uniform distribution
4 % Push 4
* % Multiply
^ % Power
* % Multiply. Implicit output
```
[Answer]
# [Factor](https://factorcode.org/), 56 bytes
```
[ normal-random-float 2pi random 2dup cos * -rot sin * ]
```
[Try it online!](https://tio.run/##NYwxDsIwEAT7vGIVKQ0iEUkJD0A0NIgKKCwnBxbOnWVf3m8MEdXuzkpDxqrEfL2czsc9ouFRZsxGX50VTmpYE95T5MmvlBa26sr1myCJJdXxE4eq6rHr@nwDf6lvV1tLXoxiCO6vH8YlwErCBm0URXJc6iNb4z3qhrZo6M41QnSslD8 "Factor – Try It Online")
Verifying correctness:
[](https://i.stack.imgur.com/Azr1Y.gif)
## Explanation
```
! 1 0.1
normal-random-float ! 1.091729295255315
2pi ! 1.091729295255315 6.283185307179586
random ! 1.091729295255315 4.669140230445313
2dup ! 1.091729295255315 4.669140230445313 1.091729295255315 4.669140230445313
cos ! 1.091729295255315 4.669140230445313 1.091729295255315 -0.04323526873134136
* ! 1.091729295255315 4.669140230445313 -0.04720120946224146
-rot ! -0.04720120946224146 1.091729295255315 4.669140230445313
sin ! -0.04720120946224146 1.091729295255315 -0.9990649185802335
* ! -0.04720120946224146 -1.090708439475907
```
[Answer]
# [R](https://www.r-project.org/), 40 bytes
```
function(r,s)rnorm(1,r,s)*1i^runif(1,,4)
```
[Try it online!](https://tio.run/##K/pflJKfV1pi@z@tNC@5JDM/T6NIp1izKC@/KFfDUAfE1jLMjCsqzctMA/J1TDShGjSKbA11im31DDX/AwA "R – Try It Online") or [plot the results at rdrr.io](https://rdrr.io/snippets/embed/?code=rdonut%3Dfunction(r%2Cs)rnorm(1%2Cr%2Cs)*1i%5Erunif(1%2C%2C4)%0Aplot(sapply(1%3A1000%2Cfunction(x)rdonut(r%3D1%2Cs%3D.1)))%0A)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Re[#+#2‚àöLog[16/r^2]I^r]I^r&
r:=4Random[]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyg1Wllb2ehRxyyf/PRoQzP9ojijWM@4IhBW4yqysjUJSsxLyc@Njv0fUJSZV@KQFm2oYxD7HwA "Wolfram Language (Mathematica) – Try It Online")
`RandomVariate@NormalDistribution` is costly (and, [as noted by Ben Izd](https://codegolf.stackexchange.com/a/243780), doesn't work with stdev=0), so this uses [Box-Muller](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) to generate a normal distribution from two uniform ones.
Sample distributions (N=10000):
[](https://i.stack.imgur.com/QVm6e.png)
[Answer]
# [Julia 1.0](http://julialang.org/), 26 bytes
```
r\s=(randn()s+r)im^4rand()
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/vyim2FajKDEvJU9Ds1i7SDMzN84ExNXQ/J@WX6SQqZCZp2BoZWhgwFVQlJlXkpOnYRpjqMmVmpfyHwA "Julia 1.0 – Try It Online")
uses the second formula. output is a complex number. `randn` gives a random number from a normal distribution (0,1), and `rand` from a uniform distribtion in [0,1)
1000 points from `10\1`:
[](https://i.stack.imgur.com/TKIeUm.png?)
[Answer]
## Mathematica - 108 bytes
Following the first method, we could have:
```
fn=AngleVector/@RandomVariate[ProductDistribution[NormalDistribution[#,#2],UniformDistribution[{0,2Pi}]],1000]&;
```
then visualize it by:
```
visualize =
Graphics[{PointSize[.01], Point[fn[#, #2]]}, Frame -> True] &;
```
`r=1, s=0.1`:
[](https://i.stack.imgur.com/aeOD1.png)
`r=3, s=1`:
[](https://i.stack.imgur.com/rNUHo.png)
`r=100, s=5`:
[](https://i.stack.imgur.com/oKlie.png)
Notes:
* `Variance: 0` in `NormalDistribution` is not supported (could be hacked by having a small number)
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
Might not be the shortest, but here is the base-case for python i guess.
Outputs a complex number:
```
lambda r,s:1j**uniform(0,4)*gauss(r,s)
from random import*
```
[Try it online!](https://tio.run/##DcmxCoAgEADQva9w9ERCoynoT1oMuTI6lVOHvt6c3vDyV@8Ul4770V9Hp3eCddnso1SLAROTNHoFdblWihwFE3IiwS76QaCcuKqeOcQqUVptZgvQfw "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 45 bytes
```
function(r,s)exp(runif(1)*2i*pi)*rnorm(1,r,s)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NIp1gztaJAo6g0LzNNw1BTyyhTqyBTU6soL78oV8NQByT/HyihY6BnqPkfAA "R – Try It Online")
Uses the first method in the description, of course using the neat fact that \$e^{i\theta}=\cos(\theta)+i\sin(\theta)\$. Longer than [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/243790/67312) by 5 bytes, though.
[Answer]
# Java 17, 127 bytes
```
(r,s)->{double a=new java.util.Random().nextGaussian(r,s),b=Math.random()*Math.PI*2;return new P(a*Math.cos(b),a*Math.sin(b));}
```
This is a `BiFunction<Double, Double, P>`
where P is a `record P(double x, double y) {}`
[Answer]
# [Desmos](https://desmos.com/calculator), ~~80~~ ~~70~~ 68 bytes
```
b=random(1,t)τ
f(r,s,t)=(normaldist(r,s).random(1,t)(cosb,sinb))[1]
```
Takes an extra argument `t` as the seed, which is the only way to re-use the function to get different samples without pressing the randomize button.
[Try it on Desmos!](https://www.desmos.com/calculator/ila0acz53f)
*-10 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)*
*-2 bytes thanks to [emanrescu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) (`\tau` to `τ`)*
All functions in Desmos are pure, so they can't return a different value when evaluated at different times, even in a list comprehension. This causes an issue with the CGSE policy of functions being re-usable.
There's a randomize button to re-seed all of the random seed-dependent function calls:
[](https://i.stack.imgur.com/raTeN.png). This doesn't vibe with me because it requires user interaction to re-seed, but it would allow the following 53-byte submission:
```
b=random()τ
f(r,s)=(cosb,sinb)normaldist(r,s).random
```
In this submission, I opted to take the random seed as an extra argument, which is a common design decision in Desmos if a program needs to avoid user action when re-seeding. This is the only way to get different outputs from random functions without the user pressing the randomize button.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
9°©D(ŸDÄ®>αÅ1*˜Ω®/*+žq·®*ÝΩ®/DžsŽ‚*
```
Inputs in the order \$r,s\$.
[Try it online.](https://tio.run/##yy9OTMpM/f/f@NCGQytdNI7ucDnccmid3bmNh1sNtU7PObfy0Dp9Le2j@woPbT@0TuvwXLCAy@HWQ/uKgcTeRw2ztP7/N9Az5DIEAA) (With the `9` replaced with `3` so it won't time out.)
**Explanation:**
Uses the first method described in the challenge description.
However, 05AB1E lacks a Gaussian distribution random builtin, as well as a builtin to get a random decimal number given a range. Both of those are therefore done manually.
```
9°©D(ŸDÄ®>αÅ1*˜Ω®/ # Push a random value with Gaussian distribution within the
# range [-1,1]:
9° # Push 1,000,000,000 (10**9)
© # Store it in variable `®` (without popping)
D # Duplicate it
( # Negate the copy
≈∏ # Pop both and push an integer-list list in the range
# [-1000000000,1000000000]
D # Duplicate this list
Ä # Get the absolute value of each in the copy
®>α # Get the absolute difference between each and `®`+1
√Ö1 # Map each inner value to a list of that many 1s
* # Multiply each to the values at the same positions in the
# remaining list
Àú # Flatten this list of lists
Ω # Pop and push a random integer
®/ # Divide it by `®`
*+ # Use the inputs to transform it into s*random+r:
* # Multiply it to the (implicit) input `s`
+ # Add the (implicit) input `r`
žq·®*ÝΩ®/ # Push a random value with uniform distribution within the
# range [0,2π):
žq # Push builtin PI: 3.141592653589793
· # Double it to get tau: 6.283185307179586
®* # Multiply it by `®`
Ý # Pop and push an integer list in the range [0,2π®]
Ω # Pop and push a random integer from this list
®/ # Divide it by `®`
DžsŽ‚* # Calculate the resulting [x,y] pair using the two random
# values:
D # Duplicate it
ž # Pop and push its cosine
s # Swap so the random value is at the top again
√Ö¬Ω # Pop and push its sine
‚Äö # Pair them together
* # Multiply both to the earlier random value
# (after which the result is output implicitly)
```
] |
[Question]
[
## Description
Your input is a list of integers \$[a\_1, \dots, a\_n]\$.
A **magic triplet** is a triplet \$(a\_i, a\_j, a\_k)\$ of values from this list, such that
* the indices \$\{i, j, k\}\$ are all distinct,
* the values are in ascending order (\$a\_i \leq a\_j \leq a\_k\$), and
* the sum of two of the values equals the third.
Your task is to output all *unique* magic triplets, in any order.
## Rules
1. Each number in the input list is guaranteed to be in the range \$-2^{32} \leq a < 2^{32}\$.
2. The input list's length is guaranteed to be at most 1000.
3. The input list's length may be less than 3 (even 0). In this case, there are no magic triplets, and your program should produce an empty result.
4. The shortest answer in bytes wins.
## Test cases
```
[1,2,3,2,4] -> [[1,2,3], [1,3,4], [2,2,4]]
[0,0,0,0] -> [[0,0,0]]
[1,0,-1] -> [[-1,0,1]]
[1,2] -> []
[1,2,4,8,99] -> []
[33,90,7,24,60,32,80,43,15,40,36,90,65,12,91,33,88,1,96,33,40] -> [[7,33,40], [32,33,65], [1,32,33], [1,90,91], [7,36,43], [24,36,60], [12,24,36], [36,60,96], [15,65,80], [40,40,80]]
```
### Notes
* In the second test case, `[[0,0,0], [0,0,0]]` is not a valid answer. No triplet may be listed twice in the output.
* Remember that your program may order the triplets differently. For example, `[[2,2,4], [1,2,3], [1,3,4]]` is also a valid output for the first test case.
* Nonetheless, `[[4,2,2], …]` is invalid: each triplet *itself* must be in ascending order.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46 51~~ 58 bytes
```
->l{l.permutation(3).select{|a,b,c|a+b==c}.map(&:sort)|[]}
```
[Try it online!](https://tio.run/##PU/LCoMwEPyVnIrSjRhjrSnYH5EcVBQKsYqPQzF@u52oLYHs7MzsJDvM5Wdrso0/zWKCvh7aeSqmV/f2pB@MtamrabEFlVTZ4lpmWbUGbdF7l8fYDZNvc71uOcsFsYiY3O9Y068/0Z@IiaXElAIhYVYhsTsE0AmghCNFjSGJG6rjksOWoBfQFYLcaIocQJUcbRwikoPgzrO/AhaicPmY5@5XIR1HHOYTSALmkdZuscUa27MmN9jrCw "Ruby – Try It Online")
Ok, not so straightforward, but now seems to work.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~10~~ ~~9~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{æ3ùêʒxsOå
```
+1 byte as bugfix for test cases like `[1,0,-1] → [[-1,0,1]] (-1+1=0)` and `[-1,-2,-3] → [[-3,-2,-1]] (-1+-2=-3)`.
[Try it online](https://tio.run/##yy9OTMpM/f@/@vAy48M7D686Nami2P/w0v//ow11FIx0FIzBpImOgi6Qrwtk6hrHAgA) or [verify all test cases](https://tio.run/##RU2xDcIwEFwlSn2W/P6PsauMwACRC5AoqCgiISJEywDZAQo2oHbHGCxi3gQJvV5/p7u/O4yb7X5XjlPfNu/r3LT9VM75zvmZH6/5NK7zrVxQhoHgwLqS0CixMLQg9zsQBMRYGTOixQpO4C3YIVgIgzqIUl9F34EcIkG9IYAQfYVi678hGBU1j@FBGqR132KLZehvM5zSBw).
**Explanation:**
```
{ # Sort the (implicit) input-list from lowest to highest value
æ # Take the powerset of this sorted list
3ù # Only keep inner lists of length 3
ê # (Sort and) uniquify this entire list of triplets
ʒ # Filter this list of (individually sorted) triplets by:
x # Double each value in the triplet (without popping the triplet itself)
s # Swap to get the original triplet
O # Take the sum of this triplet
å # And check whether this value is in the doubled list
# (after which the filtered list is output implicitly as result)
```
The last four bytes could alternatively be `œÆ0å` (given by *@Grimy*): [Try it online](https://tio.run/##yy9OTMpM/f@/@vAy48M7D686Neno5MNtBoeX/v8fbaijYKSjYAwmTXQUdIF8XSBT1zgWAA) or [verify all test cases](https://tio.run/##RU0xCgIxEPzKcfUEdrO5mFT3kCOFgoWVhSAcYnsPON@ghT@wDjY@w4/EjSfIsuwMMzuzP6w3u205jn3bvKe5afuxnPJN8iPfX/PzkifK13JGGQaGhei6hEYJwfCC7O/AISDGykQQCStYB08Qi0BwAu7glPoq@g5sERnqDQGM6Ct0VP8Nw6ioeQIP1iCt@xYTluG/zUhKHw).
```
œ # Get all possible permutations of the triplet
Æ # Reduce each by subtracting: [a,b,c] → a-b-c
0å # And check if there are any 0s among the reduced permutations
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Ṣœc3ḤiSƊƇQ
```
[Try it online!](https://tio.run/##PU49DsIgFL7KGxwfCQgiHMM4NQ2TcdD0Aq4uTRx1cW4cPYCdm/YeeBH8KGpIeN/f@@C4b5pTSrHvxttOx9fjsJ0uU7tJQzteY39fvM/PKqWaasW0ZNLzbQL/@Bf9BcPkmLyHoBH2kmkNA7IF1Eg4TANLrTCzZkvMgiv4HkV51aEH0NtCjUSlgCByZn4FKkyV@7Ev8q8kl6MChQ8 "Jelly – Try It Online")
```
Ṣ Sort the input,
œc3 find all length-3 subsequences,
Ƈ filter to only the sets for which
S the sum of all three elements
i is an element of
Ḥ Ɗ the set with all elements doubled,
Q and uniquify.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
{o⊇Ṫ.+/₂∈}ᵘ
```
[Try it online!](https://tio.run/##PY0xDsIwEAS/ckqLgTgxxm7gIVEUAQUUSJFooiiiSQGBipIfIFHRgIDf2B8x6wRofHuze@v5ZrZYlet8GbmqCKg/oaCY2t3N1rV5H2xzMc8HxNbcT67K7XFvXtdBbwjbNg3o2bmEEs4oYhS3r0jZb/@qPxCMFCOtAWKEdchoDANYQsZIKEwBi48wPZNdTGLn8DWK/KlCD6SW3SpCVGYAmc@0v4DC5L4f95lIKf0A "Brachylog – Try It Online")
Takes input through the input variable and outputs through the output variable.
```
{ }ᵘ Output every unique output from:
. the output is
⊇ a subsequence
Ṫ of length 3
{ of the input
o sorted
+ the sum of which
/₂ divided by 2
∈ is an element of
} the output.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á3 k_r-ÃmÍâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4TMga19yLcNtzeI&input=W1sxLCAyLCAzLCAyLCA0XSwKIFsxLCAwLCAtMV0sCiBbMSwgMl0sCiBbMSwgMiwgNCwgOCwgOTldLAogWzMzLCA5MCwgNywgMjQsIDYwLCAzMiwgODAsIDQzLCAxNSwgNDAsIDM2LCA5MCwgNjUsIDEyLCA5MSwgMzMsIDg4LCAxLCA5NiwgMzMsIDQwXSwKIFstMSwgLTIsIDksIDgsIDMsIDYsIDE3LCAyMCwgLTRdLAogWzAsIDAsIDAsIDAsIDFdCl0KLVEKLW0)
```
á3 k_r-ÃmÍâ // input as arrays
á3 // all unique permutations
k_ // save list that..
r-Ã // reduced by - from first element
mÍ // ==mn => sort all
â // remove duplicates
```
Thanks to @Shaggy and @Embodiment of Ignorance for saving 2
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~65~~ 64 bytes
```
*.combinations(3)>>.sort.grep({@$_.sum==2*.any}).unique(:as(~*))
```
[Try it online!](https://tio.run/##VY5NDoJADIX3nqILYxhSJs4MjiCBeA9DDBowJPIjAwti9Opj0QWyafu99r20zbu7ttUImwJisC6/NtWlrLO@bGrjKJYk3DRdz29d3jrP4/rMzVDFsXR5Vo8vxoe6fAy5c8iM83YZs9HKZCMUcBIIEkF9q5/@yRLVAmdYXvkYYBjOmqKscIuwp0gfQdOoKDug7tNK7KhPmv6daWJB@5AemaxBQEyoJ5xTPYGeRG@pAPlFGtkP "Perl 6 – Try It Online")
```
*.combinations(3) # All the combinations of length 3
>>.sort # Sorted
.grep({ }) # Filtered by
{@$_.sum== # The sum is equal to
2*.any # Double any element
.unique(:as(~*)) # And take the unique lists
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~118 116~~ 115 bytes
Returns a set.
```
a=>new Set(a.flatMap((x,i)=>a.flatMap((y,j)=>j-i&&~(k=a.indexOf(x+y))&&k-i&&k-j?[x,y,x+y].sort((a,b)=>a-b)+'':[])))
```
[Try it online!](https://tio.run/##bU/LboMwELz3K3witmIjHCjFlUi/oOqhR8TBSUzFQzgKKIFLf52OoYdKtWTZuzOzs55G3/VwvtXXUfT2YpYqX3R@7M2DfJqR6rDq9Piur5ROvGb58Q8w8wZAI@og@KZtrsO6v5jpo6LTfmYsCFrHtKJ5KyY@c4BlONjbSKnmJ@ckTmy/270WJWNsOdt@sJ0JO/tFK1pITg6cxOudQPD0n484EdJPHTzwr2XCScaJUqVHEmOfgu0LlNClKGOMZHgTUPIZr8PSTZail@AVnN1oBmOUKt3aJPKsEBAIN7N@AyqIpdvn0viCRmvQ7bi0yw8 "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
new Set( // create a set:
a.flatMap((x, i) => // for each value x at position i in a[]:
a.flatMap((y, j) => // for each value y at position j in a[]:
j - i && // if j is not equal to i
~( // and the position k
k = a.indexOf(x + y) // of x + y in a[]
) && // is not equal to -1
k - i && // and k is not equal to i
k - j ? // and k is not equal to j:
[x, y, x + y] // build the triplet (x, y, x + y)
.sort((a, b) => a - b) // sort it in ascending order
+ '' // and coerce it to a string
: // else:
[] // yield an empty array
) // end of inner flatMap()
) // end of outer flatMap()
) // end of Set()
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~94, 89, 88~~, 85 bytes
One byte saved thanks to frank.
```
lambda l:{p for p in combinations(sorted(l),3)if sum(p)/2in p}
from itertools import*
```
[Try it online!](https://tio.run/##bVLbboMwDH3nK/yYTKnWAE1JJb6k6wNtQYsEJCKZpq3qtzM7AbXThoD4HF/i48R9hXc7FnNXv819M5yvDfSHm4POTuDAjHCxw9mMTTB29MzbKbRX1nNRcNOB/xiY4685hrl71k12ABPaKVjbezCDw@iX@dL41kMNxwzwOUoBuYAi/suTSORWwPKujIxwI59w/mxjsoBKgNYrW2BNjTl79KJPoVlgWIVriS65w5U4lcIUYol@jdUotcJiaGqVYLk9Zacsa0b/2U6P9m9s6Z8LIJMiycxTS/wulrBFzoPYJEVyZXwbGP9j3th@3Z/KkgBCarfuF4kFkAwtCeyTrjJ6SD0hFUuQxsTEgipNRkdEM6E5VDGSpkNfFbtG8XQH6PQE4BjoLnwbx@JxRoYGww@xbXCTGQPropfzfzioa8r55eLzDw "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 78 bytes
```
import Data.List
f x=nub[y|y@[a,b,c]<-subsequences$sort x,or[2*z==sum y|z<-y]]
```
[Try it online!](https://tio.run/##pVLBioMwEL33K@bQgy5j0RitQoWF3b3tH4hQayMr26prImjpv3cnsUK37W01gTfvvZnJhHzl8lscDpfq2DadgremVl1zWH0MhWhV1dTgOFA2HWxzKUWntrPxPVf56rOSalHCkNT9Lh3P42ua4w6LbOPIfifFTy/qQsil1AkDNl3KXk5JIvsjjOfTxhmz7HLMqxoS2DcLoK/tqlrBEkpIPWTo0@bZveKi@bPHDBcd7wnNnnHIMcI4fpB8H2MX18g4hi76DCMXuY9egJzCUIthgB7D2EPyRhF6GIcacjqSqaaEVLcDQDoFGWqWjBowI2U3CfNcZJ9A9qeaGY40R0PvTmSk3DHzgH@Ff41H3ddXSBNQMuEwuI6lowlSjdjTcK0rcsNSP8KhSaTqJjRFNEkdDB/o3pHx0GloRfoSbk7vcHQYLXMPMyaHUau67RWIoRWFEnt6VNOTBcu8P6ucDDYkCRhmdtpgdUL1XQ2WbV9@AQ "Haskell – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 38 bytes
```
{?{x@<x}'({z=x+y}.)#x@/:{x~?x}#+!3##x}
```
[Try it online!](https://tio.run/##HY3BEoIwDER/ZZ0egGHQpim1BR34Gi4cvEY79ddr6iGbZDb7ck6vs9ZjyVuW/SGl6/PnKeO7XAcj@23J8t2kmPHCxkipR9cTHFjLryBYTNS6@ws8IlJawYxkcYfzCBbsEC08g2Z4XUMzwwxySNRuY9R0Cm30dlUkJrWUxQggxegbP9Qf "K (oK) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes
```
FLθFLθFLθF¬⌈⟦⁼ικ⁼ιλ⁼κλ›§θι§θκ›§θκ§θλ⟧«≔E⟦ικλ⟧§θνη¿∧№η⊘Ση¬№υη⊞υη»Iυ
```
[Try it online!](https://tio.run/##jY/LasMwEEXX8VdoOQNT8CuujVcmlKTQlkCXxgsRK5GwItevECj9dlfCizTQRXY6ukeaOwfJ@0PL9Twf257BmzCnUUKHyB7ij3aEd35V5@kM5Us3cT2AItYgsRvpGzULbXvBR9FDMb6aWlyhI6bs9R9s8H@tudc0YoW2zLe3KoZBnYxt8wWlq2DD6s417kuJubdSRwaFqWHTTmYESWzH9UXU8Gm3kOg0t9eSTu6NnbCfBrlA7v14@17ZbMMHKyDm81yWUUSZT88UxpT4FIWU@hRHFKwptpi4MFlTEFIWkHXTlALKEneM/aqany76Fw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθFLθFLθF¬⌈⟦
```
Loop through all triples of indices...
```
⁼ικ⁼ιλ⁼κλ
```
... checking whether the indices are distinct...
```
›§θι§θκ›§θκ§θλ
```
... and that the triplet is in ascending order...
```
⟧«≔E⟦ικλ⟧§θνη
```
... if so then save the triplet in a variable...
```
¿∧№η⊘Ση¬№υη⊞υη
```
... and if it contains its halved sum and is unique then remember it in a list.
```
»Iυ
```
After checking all triplets output the unique magic triplets double-spaced with each triplet member on its own line.
[Answer]
# Java 10, 225 bytes
```
import java.util.*;L->{var r=new TreeSet();for(int j,k,a,b,t[],i=L.size();i-->0;)for(j=i;j-->0;)if((k=L.indexOf((a=L.get(i))+(b=L.get(j))))>=0&k!=i&k!=j){Arrays.sort(t=new int[]{a,b,a+b});r.add(Arrays.toString(t));}return r;}
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/195847/52210), just twice as long.. >.>
[Try it online.](https://tio.run/##fVJNb9pAEL3zK6Y5VLtlvLGxQ3FdI/UYKU0O9IY4LGaha8BG6zEtRfx2OjZuExIptrzym3nzdr5yvddevlif7XZXOoKcsarJbtSnBG5voR/EQCXQTwPzAxkvK@uCetlGVxV817Y49gBsQcYtdWbgsYEAP5wxE0OQiQdb0dd79q@MG2uZsPvU46MiTTaDRygghfODNz7utQOXFubXv2ghk2XpBItDjmvUOEeaztCmD6qyfwy7reeN/UQ2rDy1SX6BdinEmkm2WJjfTww0gxXrWSn7Yt6BXPIzTv2P6w@pbY5cHr85pw@VqrgPgtpU@PLp7Nhcrfvzk0yc0ouF6HhUTsjZYiVIyuTkDNWuAJeczklT4a6eb7jCrtB9aRew5X6JS8x0BlpemkWmIhHgAEP@orZF/40@esG1ZfAKYoQjjOOX1jDE2MfPOIhw6GM4wJGPUYjBHUYMh41zeIfBAOMAmTsaYYDxsPmN/Jc6XoAek1g/xCEGLMjpXCXo4@UN3oZ54Zthtz1oKd1CKKVg33Xhee@uVoYnsKuJd6SZxjOnnUBDFK9sldJVa9/LLqfJoSKzVWVNasedp00hbu4b0S9w07@ov8N8qqmjFioTLf0d4a7k0/kv)
**Explanation:**
```
import java.util.*; // Required import for the TreeSet and both Arrays
L->{ // Method with integer-List as parameter & sorted Set as return
var r=new TreeSet(); // Result-set, starting uninitialized
// A Set will automatically remove duplicates
// (and a TreeSet will automatically sort, which is irrelevant,
// but it's the same size as a regular HashSet anyway)
for(int j,k,a,b,t[], // Temp integers
i=L.sisze();i-->0;) // Loop `i` in the range (input-length, 0]:
for(j=i;j-->0;) // Inner loop `j` in the range (`i`, 0]:
if((k=L.indexOf((a=L.get(i))
// Set `a` to the `i`'th value in the list
+(b=L.get(j)) // Set `b` to the `j`'th value in the list
// And add `a` and `b` together
)) // Set `k` to the index of this sum
>=0 // If the index `k` is NOT -1
&k!=i&k!=j){ // And `k` is also NOT `i` nor `j`:
Arrays.sort(t=new int[]{a,b,a+b});
// Create an array `t` with items [a,b,a+b],
// and sort the values of this triplet
r.add(Arrays.toString(t));}
// Then convert this array to a String,
// and add it to the result-TreeSet
return r;} // After the nested loop: return the result-TreeSet
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
{f}csT2T.cSQ3
```
[Try it online!](https://tio.run/##K6gsyfj/vzqtNrk4xChELzk40Pj//2gTHQVjHQVDHQUDHQVdw1gA "Pyth – Try It Online")
Port of the solution thats been floating around.
## How it works
```
{f}csT2T.cSQ3
.c 3 - All combinations length 3 of...
SQ - The sorted input
f - Filtered such that...
csT2 - Half the sum of each combination...
} T - Is an element of the original combination
{ - Remove duplicates
```
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
{mSdfqsPTeT.PQ3
```
[Try it online!](https://tio.run/##K6gsyfj/vzo3OCWtsDggJDVELyDQ@P//aBMdBWMdBUMdBQMdBV3DWAA "Pyth – Try It Online")
Less sophisticated solution. Posting it because I think it can be golfed more
## How it works
```
{mSdfqsPTeT.PQ3
.PQ3 - All 3 element permutations of the input
f - Filtered such that
sPT - The sum of the first 2 inputs...
q eT - Is equal to the last input
mSd - Sort all elements
{ - Remove duplicates
```
[Answer]
### [JULIA](https://julialang.org/)
A solution w/o external package:
```
F(l)=(n=length(sort!(l));a=Set();
for i=1:n,j=1:n,k=1:n i<j<k&&(v=l[[i,j,k]];sum(v) in 2v)&&push!(a,v)end;
[a...])
```
Not a nice one 115 bytes of code (with 2 extra newlines for readability).
A solution using the non-core package `Combinatorics`:
```
using Combinatorics
H(l)=[Set(v for v in combinations(sort(l),3) if sum(v) in 2v)...]
```
Length 85 bytes (or 84 if you omit the space before the '''if''')
You can [REPLIT](https://repl.it/@czylabsonasa/unique-magic-triplets-codegolfstackexchange) online.
] |
[Question]
[
In Elixir, (linked) lists are in the format `[head | tail]` where **head** can be anything and **tail** is a list of the rest of the list, and `[]` - the empty list - is the only exception to this.
Lists can also be written like `[1, 2, 3]` which is equivalent to `[1 | [2 | [3 | []]]]`
Your task is to convert a list as described. The input will always be a valid list (in Elixir) containing only numbers matching the regex `\[(\d+(, ?\d+)*)?\]`. You may take the input with (one space after each comma) or without spaces. The output may be with (one space before and after each `|`) or without spaces.
For inputs with leading zeroes you may output either without the zeroes or with.
Input must be taken as a string (if writing a function), as does output.
## Examples
```
[] -> []
[5] -> [5 | []]
[1, 7] -> [1 | [7 | []]]
[4, 4, 4] -> [4 | [4 | [4 | []]]]
[10, 333] -> [10 | [333 | []]]
```
[related](https://codegolf.stackexchange.com/questions/126410/sugar-free-syntax), not a duplicate as this in part involves adding mode `]` to the end. Additionally, the Haskell answer here is quite different to the one there.
[Answer]
## Haskell, 50 bytes
```
f.read
f(a:b)='[':show(a+0)++'|':f b++"]"
f _="[]"
```
[Try it online!](https://tio.run/##JclLDoMgEADQvaeYzAYIaPrdkHAET0CJGa2gES2RJt307KVpunmbN1FexhhLMLfim32ke@U56V4YZpnO0@PFSR6ElOzNtIdeSnRYeegMWodlpXkDAyultgOe9nl7NkGA/aVCe/yrTuqsLurq0JXP4COFXOohpS8 "Haskell – Try It Online")
The `+0` lets the Haskell type checker know that we are dealing with lists of numbers, so `read` will parse the input string for us.
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
r='%s'
for x in input():r%='[%s|%%s]'%x
print r%[]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPS/yFZdtVidKy2/SKFCITMPiApKSzQ0rYpUbdWjVYtrVFWLY9VVK7gKijLzShSKVKNj/wO1cXGlVqQmK4BM0TL9Hx3LFW0KxIY6CuZAykRHAYRAAgY6CsbGxrEA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 50 bytes
```
s=>eval(s).map(v=>`[${p+=']',v}|`,p='[]').join``+p
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i61LDFHo1hTLzexQKPM1i4hWqW6QNtWPVZdp6y2JkGnwFY9OlZdUy8rPzMvIUG74H9yfl5xfk6qXk5@ukaahlJ0rJKmJhe6oClWUUMdBXOsEiY6CiCEXZOBjoKxsTFI7j8A "JavaScript (Node.js) – Try It Online")
---
# Recursive version, 51 bytes
```
f=(s,[v,...a]=eval(s))=>1/v?`[${v}|${f(s,a)}]`:'[]'
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajWCe6TEdPTy8x1ja1LDFHo1hT09bOUL/MPiFapbqstkalOg2oJlGzNjbBSj06Vv1/cn5ecX5Oql5OfrpGmoZSdKySpiYXuqApVlFDHQVzrBImOgoghF2TgY6CsbExSO4/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~39~~ ~~33~~ ~~32~~ 20 bytes
```
\b]
,]
+`,(.*)
|[$1]
```
Saved 13 bytes thanks to H.PWiz, ovs, ASCII-only, and Neil.
[Try it online!](https://tio.run/##K0otycxLNPz/PyYplksnlks7QUdDT0uTqyZaxTD2//9oEx0gjOWKjgUA "Retina – Try It Online")
### Explanation
```
\b]
,]
```
If we don't have an empty list, add a trailing comma.
```
+`,(.*)
|[$1]
```
While there are commas, wrap things with `|[ thing ]`.
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, ~~31~~ 28 bytes
```
s/\d\K]/,]/;$\=']'x s/,/|[/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyYlxjtWXydW31olxlY9Vr1CoVhfR78mWj/9//9oYx2j2H/5BSWZ@XnF/3ULcv7r@prqGRgaAAA "Perl 5 – Try It Online")
# How?
```
-p # (command line) Implicit input/output via $_ and $\
s/\d\K]/,]/; # insert a comma at the end if the list is not empty
$\=']'x s/,/|[/g # At the end of the run, output as many ']' as there are
# commas in the input. Replace the commas with "|["
```
[Answer]
# [Elixir](https://elixir-lang.org/), ~~111~~ 85 bytes
```
f=fn[h|t],f->"[#{h}|#{f.(t,f)}]"
[],_->"[]"
h,f->f.(elem(Code.eval_string(h),0),f)end
```
[Try it online!](https://tio.run/##S83JrMgs@v8/zTYtLzqjpiRWJ03XTilauTqjtka5Ok1Po0QnTbM2VokrOlYnHiQDZGaA1AClUnNSczWc81NS9VLLEnPii0uKMvPSNTI0dQw0gZpS81L@e/rrFZSWFCsAFStFm@gogFCsElCSC0XG0EBHwdjYGIsMWOg/AA "Elixir – Try It Online")
I have never used Elixir before. Defines a function that takes a string and a reference to itself and returns a string.
[Answer]
# [Ceylon](https://ceylon-lang.org), 113 bytes
```
String p(String s)=>s.split(" ,[]".contains).select((x)=>!x.empty).reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");
```
[Try it online!](https://try.ceylon-lang.org/?gist=e3d815b7459bfe561287963eea4aaef5)
Here is it written out:
```
// define a function p mapping Strings to Strings.
String p(String s) =>
// we split the string at all characters which are brackets, comma or space.
s.split(" ,[]".contains) // → {String+}, e.g. { "", "1", "7", "" }
// That iterable contains empty strings, so let's remove them.
// Using `select` instead of `filter` makes the result a sequential instead of
// an Iterable.
.select((x)=>!x.empty) // → [String*], e.g. [1, 7]
// now invert the order.
// (This needs a Sequential (or at least a List) instead of an Iterable.)
.reversed // → [String*], e.g. [7, 1]
// Now iterate over the list, starting with "[]", and apply a function
// to each element with the intermediate result.
.fold("[]") // → String(String(String, String))
// This function takes the intermediate result `t` (for tail) and an element
// `h` (for head), and puts them together into brackets, with a " | " in the
// middle. This uses String interpolation, I could have used `"+` and `+"`
// instead for the same length.
((t,h)=>"[``h`` | ``t``]"); // → String
```
[Try it online!](https://try.ceylon-lang.org/?gist=60089c0d591e519aa80079ae130ca435)
As noted by ovs in a (now deleted) comment: If one select the "without spaces" options for input and output indicated in the question, one can safe 3 more bytes (the obvious ones with spaces in them).
If we don't need to parse the input, but just could get a sequence as input, it gets much shorter (69 bytes).
```
String p(Object[]s)=>s.reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");
```
[Try it online!](https://try.ceylon-lang.org/?gist=6235914fe86ec21c8ce1c327022165b0)
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes
```
lambda k:"["+''.join(f"{u}|["for u in eval(k))+-~len(eval(k))*"]"
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbSilaSVtdXS8rPzNPI02purS2JlopLb9IoVQhM08htSwxRyNbU1Nbty4nNU8DxtVSilX6X1CUmVeikaahFG2iA4WxSpqa/wE "Python 3 – Try It Online")
If the input could be a list instead, then:
**[Python 3](https://docs.python.org/3/), 53 bytes**
```
lambda k:"["+''.join(f"{u}|["for u in k)+-~len(k)*"]"
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbSilaSVtdXS8rPzNPI02purS2JlopLb9IoVQhM08hW1Nbty4nNU8jW1NLKVbpf0FRZl6JRppGtIkOFMZqav4HAA "Python 3 – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 114 bytes
```
I =INPUT
S N =N + 1
I SPAN(1234567890) . L REM . I :F(O)
O =O '[' L ' | ' :(S)
O OUTPUT =O '[' DUPL(']',N)
END
```
[Try it online!](https://tio.run/##NYw9C4MwFADnl1/xtpfQUIzaLyFDQQsB@xKMmcSlc6lD1/73mKXTwR3c97O9tnebMzi0jkOaRQRGy3hAA6LYGO4sTd20p/PleqsUHnHEaXgWOuge0isBHq1HWqgUwh8SdDIq4cGnuRz/sU9hlLSSZiUG7nNejDa1btYd "SNOBOL4 (CSNOBOL4) – Try It Online")
```
I =INPUT ;* read input
S N =N + 1 ;* counter for number of elements (including empty list)
I SPAN(1234567890) . L REM . I :F(O) ;* get value matching \d until none left
O =O '[' L ' | ' :(S) ;* build output string
O OUTPUT =O '[' DUPL(']',N) ;* print O concatenated with a '[' and N copies of ']'
END
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
É▲²:WlÖ└%ï╪☺╒▓"We↨Φ
```
[Run and debug it](https://staxlang.xyz/#p=901efd3a576c99c0258bd801d5b222576517e8&i=[1,+2,+3]&a=1)
My first Stax post, so probably not optimal.
Unpacked and commented:
```
U, Put -1 under input
{ Block
i Push loop index, needed later
'[a$'|++ Wrap the element in "[...|"
m Map
'[+ Add another "["
s2+ Get the latest loop index + 2
']*+ Add that many "]"
```
[Run and debug this one](https://staxlang.xyz/#c=U,+++++++++++++++++++++%09Put+-1+under+input%0A++%7B++++++++++++++++++++%09Block%0A+++i+++++++++++++++++++%09++Push+loop+index,+needed+later%0A++++%27[a%24%27%7C%2B%2B+++++++++++%09++Wrap+the+element+in+%22[...%7C%22%0A++++++++++++m++++++++++%09Map%0A+++++++++++++%27[%2B+++++++%09Add+another+%22[%22%0A++++++++++++++++s2%2B++++%09Get+the+latest+loop+index+%2B+2%0A+++++++++++++++++++%27]*%2B%09Add+that+many+%22]%22&i=[1,+2,+3])
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
+:'[J"|[":msr¹₁*₁Lr
"]
```
[Try it online!](https://tio.run/##yygtzv7/X9tKPdpLqSZaySq3uOjQzkdNjVpA7FPEpRT7//9/pWhDAx1jY@NYJQA "Husk – Try It Online")
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~22~~ 21 bytes
```
'[,1;@j,]';#$&." |",,
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9Xj9YxtHbI0olVt1ZWUdNTUqhR0tH5/z/aREcBhGIB "Befunge-98 (PyFunge) – Try It Online")
If there weren't weird restrictions on output, we could do this in 18:
```
'[,1;@j,]';#$&.'|,
```
Fun fact, this is technically a program that does nothing in Python.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 39 bytes
Full program:
```
$_[$&]="|[#$2]"while/(,|\d\K(?=]))(.*)/
```
[Try it online!](https://tio.run/##KypNqvz/XyU@WkUt1lapJlpZxShWqTwjMydVX0OnJiYlxlvD3jZWU1NDT0tT////6FiuaFMgNtQxB5ImOkAI4hnoGBsbx/7LLyjJzM8r/q9bAAA "Ruby – Try It Online")
### [Ruby](https://www.ruby-lang.org/), ~~48~~ 45 bytes
Recursive function:
```
f=->s{(s[/,|\d\K(?=])/]&&="|[")&&f[s+=?]]||s}
```
[Try it online!](https://tio.run/##RYxNCoMwEIX3PUVIISiN1RDFVfQAPcI4i/6FLksTF8Xx7GmCNDLw4H3f8D7z7RuCNdXglsJBLWl6TJdiNFjWKIThBLwUwoI7mRGRyK0BDhyQyyOrBgYYS5dbxyiixJTsM1WJ9ptKrpXxsm2T2AO3H9VIrfU@0SQXyX8Fz8/r/bWQp/fsHbPgcQ0/ "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~84~~ ~~71~~ 69 bytes
```
function(x){while(x<(x=sub('(,|\\d\\K(?=]))(.+)','|[\\2]',x,,T)))1;x}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCs7o8IzMnVaPCRqPCtrg0SUNdQ6cmJiYlJsZbw942VlNTQ09bU11HvSY6JsYoVl2nQkcnRFNT09C6ovZ/moZSdKySJheINoUxDHXMYUwTHSCEixvoGBsbA3n/AQ "R – Try It Online")
* -15 bytes thanks to @KirillL.
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 57 bytes
```
k=>"["+''.join(str(u)+"|["for u:(e=eval(k)))+-~len(e)*"]"
```
[Try it online!](https://tio.run/##LcKxCoAgEADQX4lbvMtqagrsR8Sh4QRTVEybol@3Jd7LJdUUu1Xdqx00SCGWM7mIVy3YSMKjwaYytA1Z8X0E9EQk5zdwRKYRDPRcXKxoEfQ6/QwQ9Q8 "Proton – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ŒV©;€⁾|[”[;µ®L‘”]ẋṭ
```
[Try it online!](https://tio.run/##AToAxf9qZWxsef//xZJWwqk74oKs4oG@fFvigJ1bO8K1wq5M4oCY4oCdXeG6i@G5rf///ydbMTAsIDMzM10n "Jelly – Try It Online")
A non-recursive alternative to [Erik's solution](https://codegolf.stackexchange.com/a/163849/59487).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ŒVḢ,ŒṘÇ”|;ƲƊ¹¡⁾[]j
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//xZJW4biiLMWS4bmYw4figJ18O8ayxorCucKh4oG@W11q////J1sxMCwgMzMzXSc "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$
```
A full program printing the result (as a monadic link it accepts a list of characters but returns a list of characters and integers).
**[Try it online!](https://tio.run/##y0rNyan8///opLBDWx817ouOzcoCUjXRD3euNrZ@1DA39uHORpX///@rRxsa6CgYGxvHqgMA "Jelly – Try It Online")**
### How?
```
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$ - Main link: list of characters e.g. "[10,333]"
ŒV - evaluate as Python code [10,333]
µ - start a new monadic chain, call that X
⁾[] - list of characters ['[',']']
j - join with X ['[',10,333,']']
⁾|[ - list of characters ['|','[']
j - join ['[','|','[',10,'|','[',333,'|','[',']']
ṫ3 - tail from index three ['[',10,'|','[',333,'|','[',']']
$ - last two links as a monad (f(X)):
”] - character ']'
ṁ - mould like X [']',']'] (here 2 because X is 2 long)
; - concatenate ['[',10,'|','[',333,'|','[',']',']',']']
- implicit (and smashing) print [10|[333|[]]]
```
[Answer]
# Java 10, 107 bytes
```
s->{var r="[]";for(var i:s.replaceAll("[\\[\\]]","").split(","))r="["+i+"|"+r+"]";return s.length()<3?s:r;}
```
[Try it online.](https://tio.run/##jY9BTsMwEEX3PcXIK1txLSAgpKYFcQC6YZlmYVy3uHWdaOxEQiVnDxOIWKLIY2nG/vP1/kl3ennanwfjdYzwql24LgBcSBYP2ljYjiPAW0IXjmD41ERR0HtPlyomnZyBLQTYwBCXT9dOI@CGlRUrDjXycXSrqNA2nkxfvOes3O2oqopJxoSKjXeJUy/EuMcyl7EvlmHGyAJtajFAVN6GY/rgYp0/xxUW/VD8AjTtuyeAiaOr3R4ulGSCLSstphSfMdmLqtukGvpJPvCgDB85xU@gfyQPMzS38nGW6k7mM3T3ks4MuxuZ539@/aIfvgE)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
var r="[]"; // Result-String, starting at "[]"
for(var i:s.replaceAll("[\\[\\]]","")
// Removing trailing "[" and leading "]"
.split(",")) // Loop over the items
r="["+i+"|"+r+"]"; // Create the result-String `r`
return s.length()<3? // If the input was "[]"
s // Return the input as result
: // Else:
r;} // Return `r` as result
```
[Answer]
# [Standard ML](http://www.mlton.org/), 71 bytes
```
fun p[_]="]|[]]"|p(#","::r)="|["^p r^"]"|p(d::r)=str d^p r;p o explode;
```
[Try it online!](https://tio.run/##HchLCsMgEADQfU8xTDcJWGixq4gnkTEUjBAwOhgTuvDu5rN7vHUJryWUFFvzWwQ2I2mkaoiwcvdEgcOQe43VoGXIFu93d64lg7tWMSSY/hySm1TbfwE8aJiLelweT3OeY@k8oPm8hZRSfAn7dgA "Standard ML (MLton) – Try It Online") Uses the format without spaces. E.g. `it "[10,333,4]"` yields `"[10|[333|[4]|[]]]]"`.
**ungolfed**
```
fun p [_] = "]|[]]" (* if there is only one char left we are at the end *)
| p (#","::r) = "|[" ^ p r ^ "]" (* a ',' in the input is replaced by "|[" and an closing "]" is added to the end *)
| p (d::r) = str d ^ p r (* all other chars (the digits and the initial '[') are converted to a string and concatenated to recursive result *)
val f = p o explode (* convert string into list of chars and apply function p *)
```
[Try it online!](https://tio.run/##NYtBCsMgFET3nmL43SRgocWuAj2J/IaCEQpGxdjShXe3mtBZzOK9mW1159Xl4Gu1b48IPTOO3EFcNDNBAKWp4USSpimNXRVNeDSYWhPTf2J2v7@3nGCOjRCfp4NtMCJg@UYXzFI7mztLL58HC9LXi1RKyRvTWH8 "Standard ML (MLton) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~140~~ 136 bytes
Down 4 bytes as per Giuseppe's sound advice.
```
function(l,x=unlist(strsplit(substr(l,2,nchar(l)-1),", ")))paste(c("[",paste0(c(x,"]"),collapse=" | ["),rep("]",length(x))),collapse="")
```
[Try it online!](https://tio.run/##TYxBC8IwDIXv/oqQUwMZbE7x4n7J8FBL5walK2sLPfjfayZMhEC@l5f3tjrdmzplb9KyeuW4DNm7JSYV0xaDWwTyU1isM3szayFqOmJkQCIKOiarjMIR@cutiML4QGKzOqdDtAPCG0Y5bDYocdhZ/0qzKpL/e0Kqk/RI8rTv6wEdw@3gC8M@P6tl6PteZP0A "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 108 bytes
```
function(l)Reduce(function(x,y)paste0("[",x,"|",y,"]"),eval(parse(t=sub("]",")",sub("\\[","c(",l)))),"[]",T)
```
[Try it online!](https://tio.run/##PYpNCsIwEIX3niLMagaeUIniRi9R3LUuYkxBCLU0ibTg3WMqtMOD@d7PmDt12ecu9Ta@3j17qd0zWcdbMmGWwYToKqaGMIG@hBl0J4H7GM@DGYPjeA3pwSUFCeHPbVv2ZJngpRyoKe1NcscLyW75pxUOUOeVj1CLtqqC0loXm38 "R – Try It Online")
It took almost a year to find a better R solution than previous...should have known `Reduce` would be the answer! Outputs without spaces, input can be with or without spaces.
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
lambda s:'['+'|['.join(map(str,eval(s))+[']'])+']'*len(eval(s))
```
[Try it online!](https://tio.run/##RU7dCoIwFL6upzh3Z8shmoogrBdZu1ilZMw5dAWB724by4LDd873w8exb3cfzXHt@HnVarjcFMwNCkxwEZg@xt6QQVkyu4m1L6XJTGkiUKKkiceDbg3Z9LUbJ@iNZTA@nfUXCIFCIoOAkoFnVaQVLCDkJuYM6qjnQa@jubklgzAxUAbvD/IfyzMGRVF8e7Lgevqrks1@Z6feuPgh8pMPdsQTum3Ow9/p1Fqtri1BQIZI1w8 "Python 2 – Try It Online")
[Answer]
# sed + `-E`, 46 bytes
```
:
s/\[([0-9]+)(, ?([^]]*)|())\]/[\1 | [\3]]/
t
```
A fairly straightforward approach. The second line takes `[\d+, ...]` and changes it to `[\d | [...]]`. The third line jumps back to the first line, if the substitution was successful. The substitution repeats until it fails and then the program terminates. Run with `sed -E -f filename.sed`, passing input via stdin.
[Answer]
# [Red](http://www.red-lang.org), 110 bytes
```
func[s][if s ="[]"[return s]replace append/dup replace/all b: copy s",""|[""]"(length? b)- length? s"]""|[]]"]
```
[Try it online!](https://tio.run/##VY3BCsIwEETv/YplTwqRKlGEgvgPXsMe0mSjhZCGpDkI/nuMoEiZy7yZgUls642tos4N1ZVgVCY1OchwQUWoEi8lBciUOHptGHSMHGxvS4Rv1GvvYRzAzPEJGQXiSyESbjyH@/K4wrjdwc/nVrSeCKnGNIUFHHyOuj@cVnQQ5xUfRdN6sRdSSsL6Bg "Red – Try It Online")
## Explanation of the ungolfed version:
```
f: func[s][
if s = "[]" [return s] ; if the list is empty, return it
b: copy s ; save a copy of the input in b
replace/all b "," "|[" ; replace every "," with "|["
append/dup b "]" (length? b) - length? s ; append as many "]" as there were ","
replace b "]" "|[]]" ; replace the first "]" with "|[]]"
] ; the last value is returned implicitly
```
[Red](http://www.red-lang.org) is so easily readable, that I doubt I needed adding the above comments :)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes
```
{'['~S:g/\s|.<($/\|\[/~']'x$_+1}o&EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wj1avS7YKl0/prhGz0ZDRT@mJiZav049Vr1CJV7bsDZfzTXM0ee/NVdxYqVCmoJStKGOkY5xrBJCwBSZY6hjjsyNVfoPAA "Perl 6 – Try It Online")
] |
[Question]
[
**Inputs:**
Two single digits (let's call them `m` and `n`) and two chars (let's call them `a` and `b`) in your input format of choice.
**Output:**
For the walkthrough, pretend `m=2, n=5, a='a', b='b'`.
Your output will be a string built from your four inputs. Let's call the string `result`, with value `""`. First, concatenate `a` onto `result` `m` times, so concatenate `a` onto `result` `2` times. `result` now equals `aa`. Second, concatenate `b` onto `result` `m` times, so concatenate `b` onto `result` `2` times. `result` now equals `aabb`. Lastly, if result is already longer than `n`, truncate `result` so that it has length `n`. Otherwise, continue alternating with `m` length runs of `a` and `b` until `result` has length `n`. The final `result` is `aabba`, which has length `5`.
**Test Cases:**
```
Input: m = 2, n = 4, a = A, b = B
Output: AABB
Input: m = 3, n = 8, a = A, b = B
Output: AAABBBAA
Input: m = 4, n = 3, a = A, b = B
Output: AAA
Input: m = 2, n = 10, a = A, b = B
Output: AABBAABBAA
```
As all knows, lesser one will rule the world, so the smallest programs, in bytes, win! :)
[Answer]
# [Python](https://docs.python.org/), 32 bytes
```
lambda m,n,a,b:((a*m+b*m)*n)[:n]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVcnTydRJ8lKQyNRK1c7SStXUytPM9oqL/Z/QVFmXolGmoaRjoKJjoK6ozqQcFLX1OSCSRjrKFhglQAqN0aW@A8A "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
Y"i:)
```
Inputs are a string with the two characters, then `m`, then `n`.
[Try it online!](https://tio.run/##y00syfn/P1Ip00rz/391Ryd1LmMuCwA "MATL – Try It Online")
### Explanation
```
Y" % Implicit inputs: string and number m. Apply run-length decoding.
% The second input is reused for each char in the first. Gives a
% string
i % Input number n
: % Push vector [1 2 ... n]
) % Index the string with the numbers in that vector. Indexing is
% modular, so the chars are reused if necessary. Implicit display
```
[Answer]
## Haskell, ~~44~~ 40 bytes
```
f=(.cycle).take
(n#m)a=f n.(f m a++).f m
```
[Try it online!](https://tio.run/##DcYxDoAgDAXQ3VP8FAcICYuLC4PepDEQCdAYZfH01Te9k5@aWlPN0YbjPVpyYXBNkxXTHccMCTajg7134Y92LoKI6y4yMAN2NYsDbQTaCfoB "Haskell – Try It Online")
[Answer]
# Ruby, 29 characters
```
->m,n,a,b{((a*m+b*m)*n)[0,n]}
```
Sample run:
```
irb(main):001:0> ->m,n,a,b{((a*m+b*m)*n)[0,n]}[3, 8, 'A', 'B']
=> "AAABBBAA"
```
[Try it online!](https://tio.run/##jY/LDoIwEEXX9CtmQwo4GAQXbmpSfqPpAgSiiRTCY2HEb6@t1hh142pm7rnzGubyohtgOt63qLDA8hoERdSuyqgNIxWKBJW86X6eRqB@nCYjLODHm884UvBB0JPqKQLt5smGoR7n8@QEYAycIAkRxBMiRdgayK0jp9KmPLeJhRnC7hsamnPuDKY1@zFYJtd1cThC1cFi7kEwyxfiPXcDg0ZERpbE@@ul1wR0xz@K9y@S1KrSdw "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
VîUçW +UçX
```
First try using a golfing language. [Try it online!](https://tio.run/##y0osKPn/P@zwutDDy8MVtIFkxP//xlyGBlxKjkpcSk5KAA "Japt – Try It Online")
## Explanation
```
Vî // repeat the following until it reaches length V (second input)
UçW // third input repeated U (first input) times
+UçX // plus the fourth input, repeated U times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
×J×I£
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8HSvw9M9Dy3@/z9a3VFdR91JPZbLmMsCAA "05AB1E – Try It Online")
**Explanation**
```
× # repeat a and b m times each
J # join to string
× # repeat the string n times
I£ # take the first n characters
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 bytes
```
xFṁ⁵
```
[Try it online!](https://tio.run/##y0rNyan8/7/C7eHOxkeNW////x@t7qiuo6DupB773@i/oQEA "Jelly – Try It Online")
Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for better input format (-2).
[Answer]
# [V](https://github.com/DJMcMayhem/V), 13 bytes
```
ÀäjÀäêÍî
À|lD
```
[Try it online!](https://tio.run/##K/v//3DD4SVZIOLwqsO9h9dxHW6oyXH5/z@RK@m/8X8TAA "V – Try It Online")
`a` and `b` are taken on separate lines in the input, `m` and `n` are taken as argument, reversed (so `n` is the first argument and `m` is the second)
### Explanation
```
Àäj ' duplicate the inputs [arg 1] times
a -> a
b b
a
b
...
Àäê ' duplicate everything straight down [arg 2] times - À cycles arguments
a -> aaa
b bbb
a aaa
b bbb
... ...
Íî ' remove all newlines
-> aaabbbaaabbb...
À|lD ' delete from the [arg 1] + 1 column onwards
-> aaabbbaa
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~36~~ ~~35~~ 29 bytes
Yet another Haskell solution (expects the characters given as a list):
```
(m#n)c=take n$cycle$c<*[1..m]
```
[Try it online!](https://tio.run/##TY/LCsIwEEX3@YpLdZHIUHwtXJhF6tovEJEQA5Y2aUkGxK@vreJjMYs5Z7jDvdnc@LYd6tB3iXHoIqeuLY9dtFdIBNsfL1CDDLOonGbbeMS5e7jWz91@cVqVZTgP7DMfbPYZWgAnyDVhS4WpCkJhTFUVauQEuSHsfnwUlTEftyVs/twHr2m1/I96z8uehZg@QwaK5DIlBf1dmBIlrXk6vN988uCXHXvAZQgRbB1H8m4o@1RHLqc4hW@d4Qk "Haskell – Try It Online")
Thanks @Laikoni for -1 byte.
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 39 bytes
```
function(d,m,n)cat(d[gl(2,m,n)],sep='')
```
An anonymous function; prints the result to stdout. Takes the characters as a vector `d=c(a,b)`. `gl` generates factors (integers) of (in this case) `2` levels of run length `m` with total length `n`! `cat` concatenates and prints them as a string.
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRSdXJ08zObFEIyU6PUfDCMyN1SlOLbBVV9f8n6aRrKGeqK6jnqSuqWOkY2ig@R8A "R – Try It Online")
[Answer]
# Javascript, 55 bytes
```
(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)
```
Example code snippet:
```
f=
(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)
console.log(f(2, 4, 'A', 'B'))
console.log(f(3, 8, 'A', 'B'))
console.log(f(4, 3, 'A', 'B'))
console.log(f(2, 9, 'A', 'B'))
```
[Answer]
# Javascript, 53 bytes
```
(m,n,a,b)=>a.repeat(n).replace(/./g,(i,j)=>j/m&1?b:i)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
Direct Port of my Haskell answer, except that the argument order is different:
```
↑¢Ṙ
```
[Try it online!](https://tio.run/##yygtzv7//1HbxEOLHu6c8f//f@P/So5OSv8tAA "Husk – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~48~~ 43 bytes
```
(m#n)a|r<-(<$[1..m])=take n.cycle.(r a++).r
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/XyNXOU8zsabIRlfDRiXaUE8vN1bTtiQxO1UhTy@5MjknVU@jSCFRW1tTr@h/bmJmnoKtQkq@QkFRZl6JgoqChpGCsoKJpoK6o7qCupM6lwIcwFUYA1VY4FVhAlRhDFfxHwA "Haskell – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~37~~ 27 bytes
```
[:|G=;+G+;][:|G=G+G]?_sG,d
```
## Explanation
```
This takes its arguments as frequency m, A, B, length n
For example: 2, A, B, 8
: Read a cmd line arg as number 'b' ('a' is used by the FOR declaration as loop counter)
[ | Start a FOR loop, from 1 to b
G= G Set G to hold itself
;+ prepended by a cmd line arg read as strig and assigned to A$
+; and followed by a cmd line arg read as strig and assigned to B$
] At the end of the FOR loop, G has had A added to the front twice, and B t the end x2: G$ = AABB
[:| FOR c = 1 to n
G=G+G] Add G to itself G$ = AABBAABBAABBAABBAABBAABBAABBAABB
?_sG,d PRINT the first n chars of G$ AABBAABB
```
---
Previous attempt:
```
(37b) {Z=Z+;┘_LZ|~a=:|_X]~a%:|\C=A┘A=;┘B=C
Takes its arguments as `A, length n, frequency m, B`.
Basically adds A to Z until length % freq = 0, then swaps A for B. Loops until lengtn = n
```
[Answer]
# PHP>=7.1, 77 bytes
```
for([,$x,$l,$f,$s]=$argv;$l-=$z;)echo str_repeat(++$i&1?$f:$s,$z=min($l,$x));
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/f0243b1f9a55bba841671ca2fca5f4e9aaaca95a)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 75 bytes
```
void f(int m,int n,char[]s){for(int i=0;i<n;)System.out.print(s[i++/m%2]);}
```
[Try it online!](https://tio.run/##pY2xDoIwFEVn@AoW0zZURGAwqQ66OzEShoqARSikLRhD@HYsGBcSJ5b3knffuaegHd3WTcqL@3Ns2lvJEispqZTWlTLej13N7lYGGVdWhafJcfKgIool6rNazAE7uYQdOUHhW6q0cupWOY3QCZQRs@1dtfFiRIZfvVRU6TU3V1oCQ6Wf8yimItetpsHT12yHyMmghwM8Hb7WHpwBBhcwIGIaS12pCbLAfXxYgwfYX4N7eO/@4QdzGD8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~63~~ 58 bytes
```
.rr.@u:s?.\.sw).i|>v:.\nB;?(q:Is...;rr/s.uw/....sIB/\/?(qo
```
[Try it online!](https://tio.run/##Sy5Nyqz4/1@vqEjPodSq2F4vRq@4XFMvs8auzEovJs/J2l6j0MqzWE9Pz7qoSL9Yr7RcH8jWK/Z00o/RB8rl//@fmKRjrGNoAAA "Cubix – Try It Online")
[watch the interpreter](http://ethproductions.github.io/cubix/?code=ICAgICAgICAuIHIgciAuCiAgICAgICAgQCB1IDogcwogICAgICAgID8gLiBcIC4KICAgICAgICBzIHcgKSAuCmkgfCA+IHYgOiAuIFwgbiBCIDsgPyAoIHEgOiBJIHMKLiAuIC4gOyByIHIgLyBzIC4gdSB3IC8gLiAuIC4gLgpzIEkgQiAvIFwgLyA/ICggcSBvIC4gLiAuIC4gLiAuCi4gLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCiAgICAgICAgLiAuIC4gLgogICAgICAgIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCg==&input=YWIsMywxMA==&speed=10)
Takes input like `ab*m*n` where the `*` can be any non-digit character.
Cube version:
```
. r r .
@ u : s
? . \ .
s w ) .
i | > v : . \ n B ; ? ( q : I s
. . . ; r r / s . u w / . . . .
s I B / \ / ? ( q o . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
```
* `i|is` : read in the chars, and swap them (so `a` is on top)
* `I:q` : read in `m`, dup, and push to bottom (stack is now `m,b,a,m`)
* `)` : decrement
* `?` : turn right if positive, go straight if zero (duplicates `a`)
* positive branch (loop)
+ `s:rur(/w` : swap, dup, move `m-i` to the top of the stack, decrement `m-i`
* zero branch
+ `B` : reverse stack (which now has `m` copies of `a`: `a... b m`)
+ `n` : negate `m` (so we can use `?` to turn left)
+ `)` : increment
+ `?` : go straight if zero, turn left if negative
* negative branch (duplicates `b`)
+ `s:r\/rw)\` basically the same as the positive branch but with increment and left turns.
* zero branch (prints the output)
+ `>v;` : pop the `0` off the stack (looks like `a...b...`)
+ `/B` : reverse the stack
+ `I` : read `n`
+ `s` : swap
print loop:
* `oq` : print and push to bottom of stack now looks like: `ab...a...n`
* `(` decrement `n`
* `?` : turn right if positive, go straight if zero
* If right, : `/su` : swap top of stack and continue the loop
* if zero, `/` reflects down and the code evaluated is `Iru@`; `@` terminates the program.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
…⁺×ζIθ×εNN
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3PydFwzElRSMkMze1WKNKR8E5sbhEo1BTU0cBIpSqo@CZV1Ba4leam5RapKGpqYnOt/7/34jL0IDLkcvpv27Zf93iHAA "Charcoal – Try It Online") Link is to verbose version of code and includes fourth example. (Annoyingly the deverbosifer won't remove the separator if I add one before the last `InputNumber()`.)
[Answer]
# Mathematica , 61 bytes
```
T=Table;StringTake[""<>Flatten@T[{#3~T~#,#4~T~#},⌈#2/#⌉],#2]&
```
**input**
>
> [2,10,"A","B"]
>
>
>
[Answer]
# Mathematica, 44 bytes
```
StringPadRight[x={##3}~Table~#<>"",#2,x]&
```
# Explanation
`` is the three byte private use character `U+F3C7`, representing the postfix `\[Transpose]` operator in Mathematica. No TIO link because [Mathics](https://mathics.github.io/) does not support ``, `\[Transpose]` has the wrong operator precedence, the second argument to `Table` is required to be a list, and most importantly, `StringPadRight` is not implemented.
```
& (* Function *)
{##3} (* which takes the third and fourth arguments *)
~Table~# (* repeats them a number of times equal to the first argument *)
(* takes the tranpose *)
<>"" (* then joins the strings with the empty string *)
x= (* sets x equal to that string *)
StringPadRight[ (* then pads x *)
,#2 (* to a length equal to the second argument *)
,x] (* with x. *)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 5 bytes
```
⎕⍴⎕/⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKMdSPRNfdS7BUjqAzFI6H86l3pikjqXEZehAQA "APL (Dyalog Unicode) – Try It Online")
Takes the two chars in a string as the first input, followed by `m` and then `n`.
### Explanation
Let the example input be `'ab'`, `2`, `10`.
```
⎕/⎕ Replicate the two-char string `m` times
2/'ab' => 'aabb'
⎕⍴ Shape it so that its length is `n`
10⍴'aabb' => 'aabbaabbaa'
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
KE<*+*EQ*EQKK
```
[Try it online!](https://pyth.herokuapp.com/?code=KE%3C%2A%2B%2AEQ%2AEQKK&input=2%0A10%0A%22A%22%0A%22B%22&debug=0)
**Explanation**
```
# Implicitly store m to Q
KE # Store n to K
*EQ # Perform a * m
*EQ # Perform b * m
+ # Concatenate the two strings
* K # Multiply by n
< K # Take the first n characters of the string
```
[Answer]
# k, 10 bytes
```
{y#,/x#'z}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qulJZR79CWb2q9n@anrqGhpG1ibWSo5OSJpeGsbUFjGlibQxjGlkbGkDZmv8B "K (oK) – Try It Online")
[Answer]
# [Chip](https://github.com/Phlarx/chip), 588 bytes
```
*Z~vZ.*ZZZs z. z. z. z. z. z. z. z.
,'|`-. ZZ--#<,#<,#<,#<,#<,#<,#<,#<
a/mAM/a| `~S `x'`x'`x'`x'`x'`x'`x'`x.
b/mBM/b| *.)/')/')/')/')/')/')/')/'|
c/mCM/cZv--x^x-^x-^x-^x-^x-^x-^x-^x-'
d/mDM/d||A~#M',-',-',-',-',-',-',-'
e/mEM/e||B~#M-',-',-',-',-',-',-'
f/mFM/f||C~#M--',-',-',-',-',-'
g/mGM/g||D~#M---',-',-',-',-'
h/mHM/h||E~#M----',-',-',-'
`v~v' ||F~#M-----',-',-'
* `mz ||G~#M------',-'
Z `---x'H~#M-------'
Z,--z--^----'
Z|z. z. z. z. z. z. z. z.
Zx#<,#<,#<,#<,#<,#<,#<,#<
|`x'`x'`x'`x'`x'`x'`x'`xT
|A| B| C| D| E| F| G| H|
)\')\')\')\')\')\')\')\'
`--^--^--^--^--^--^--'
```
[Try it online!](https://tio.run/##dZG7asQwFETr6CsubCHWWL6QOo3Xz0ZVUolgZHsfTiEIBIwxg3/dsbObJWRlOMXVnCkE03Yfn/McmKk3UWCM@SIaIy@CKJSwKiJjlNq9hD5EzS7WXIPs9Ep2kD4i0bA7aG5AFER7ll4gWnaJ5tb0Sg3VoLxIcWSXaj4C8bTTMlQexIldpvkEHJaOt3Fml2s@A8naePQXdoXmC5D@@H@2Y1dq7oDsav86sv3USwLym7ubgKwbaTHFr7nmhsgu9yDLe76moVKjUtXtha2ZzLC1DWFjkLdFxaADKAGloAyUgwpQCUH7d@lFrJ@sHpDzXDdPz98 "Chip – Try It Online")
Takes input as a 4-character string. The first two are the characters *a* and *b*, followed by the byte value *m*, and then the byte value *n*. For example, the TIO includes input `ab<tab>2`, this corresponds to 'a', 'b', 9, 50. (Since the codes for `<tab>` and `2` are 9 and 50.
### How?
This answer is a bit of a behemoth, but here's the highlights:
The upper left block, with the lowercase `a`-`h`, is the storage mechanism for the characters *a* and *b*, one line per bit. At its bottom, with the `v~v` and `mz` is the switching mechanism, to swap between the two.
In the middle is a column with a bunch of `~#M`'s. This reads in *m* and stores its negative. The big triangle to the right is just wires to bring this value into the upper accumulator.
The upper right block is the accumulator for *m*. It increments every cycle (starting from *-m*) until it reaches zero. When this happens, the output character is swapped, and counting restarts from *-m*.
Meanwhile, there is the lower block, which is the *n* accumulator. Since *n* is only read once, we don't need a bank of memory (`M` and `m`) to store this value. We simply negate it and start counting. When this value reaches zero, the whole shebang is simply terminated.
All the other guff is delays (`Z` and `z`), wiring (`-`, `|`, ...), and other miscellany.
] |
[Question]
[
The **[Fibonacci word](https://en.wikipedia.org/wiki/Fibonacci_word)** is a sequence of binary strings defined as:
* \$F\_0 = \$ `0`
* \$F\_1 = \$ `01`
* \$F\_n = F\_{n-1} F\_{n-2}\$
The first few Fibonacci words are:
```
0
01
010
01001
01001010
0100101001001
010010100100101001010
...
```
Each of these strings is a prefix of the next, so they are all prefixes of the single infinite word \$F\_\infty\$ =
```
010010100100101001010010010100100101001010010010100101001001010010010100101001001010010010100101001...
```
(The definition above is borrowed from [this sandbox challenge by pxeger](https://codegolf.meta.stackexchange.com/a/24969/9288).)
Now we can define a fractal curve based on the Fibonacci words.
Starting from some point on the plane, for each digit at position \$k\$ of the Fibonacci word \$F\_\infty\$:
* Draw a segment with length \$1\$ forward,
* If the digit is \$0\$:
+ Turn 90° to the left if \$k\$ is even,
+ Turn 90° to the right if \$k\$ is odd.
This is called the [**Fibonacci word fractal**](https://en.wikipedia.org/wiki/Fibonacci_word_fractal).
For example, the first 21 digits in \$F\_\infty\$ are `010010100100101001010`, which would give the following shape:
```
┌
│ ┌─┐
└─┘ │
┌┘
│
└┐
┌─┐ │
│ └─┘
```
To be clearer, let's mark the starting point by `^`, and replace the other chars by its corresponding digit in the Fibonacci word:
```
0
1 010
010 1
00
1
00
010 1
^ 010
```
Here are some more steps of the Fibonacci word fractals, taken from Wikipedia:
[](https://i.stack.imgur.com/7laYo.png)
## Task and rules
Given a non-negative integer \$n\$, draw *at least* \$n\$ steps of the infinite Fibonacci word fractal.
You may draw more steps than \$n\$. But the extra steps should still belong to the infinite Fibonacci word fractal.
Or alternatively, you may take no input, and draw every step of the infinite Fibonacci word fractal (as an animation, or an infinite sequence of outputs).
You may output as either [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") or [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'").
For [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), you may choose any characters to draw the curve as long as the output is clear.
The fractal curve consists of a chain of line segments. For each step, you may choose to draw one of the followings, but your choice must be consistent (taking \$n=21\$ as an example):
* the starting point of the segment:
```
# ###
### #
##
#
##
### #
# ###
```
* the ending point of the segment:
```
#
# ###
### #
##
#
##
### #
###
```
* the whole segment.
```
#
# ###
### #
##
#
##
### #
# ###
```
The direction don't need to be consistent. You may arbitrarily rotate or reflect the curve.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [J](http://jsoftware.com/), 79 bytes
```
load'plot'
[:plot 0;/@|:[:+.@([:+/\1*/\@,-.+0j1*]*_1^#\)@;_2&(],<@;@{.)&(1;1 0)
```
[J Playground](https://jsoftware.github.io/j-playground/bin/html2/#code=load%27plot%27%0Af%3D.%5B%3Aplot%200%3B%2F%40%7C%3A%5B%3A%2B.%40%28%5B%3A%2B%2F%5C1%2A%2F%5C%40%2C-.%2B0j1%2A%5D%2A_1%5E%23%5C%29%40%3B_2%26%28%5D%2C%3C%40%3B%40%7B.%29%26%281%3B1%200%29%0Af%2010)
Generates more than required, because it:
* First iterates fib `n` times
* Uses complex numbers with product scans and sum scan to calculate all the coords at once
* plots those coordinates
[](https://i.stack.imgur.com/FGVSS.png)
[Answer]
# [Desmos](https://desmos.com/calculator), 111 bytes
```
p->p+1,d->d+90(1-floor(pk+k)+floor(pk))(1-2mod(p,2)),L->join(L[1]+(cosd,sind),L)
L=[(0,0)]
gg~g+1
k=2-g
p=2
d=0
```
Paste the first line in a ticker, the second line in a collapsed folder, and the rest of the lines in the regular expression boxes. Also make sure Desmos is set to degrees mode, and not radians.
Then click the ticker (the metronome in the top left corner) to run the code.
Theoretically, this can go on infinitely, but due to Demsos's list length cap at 10000 elements, we can only generate 9999 segments before erroring out. But it doesn't really matter, because Desmos already starts lagging pretty badly (at least on my computer) around 3 or 4k segments, so it would take a while to actually get to 9999 segments (I left it running for around 15 minutes or so and got up to around 7000 segments).
Also, the list `L` is stored in a collapsed folder because Desmos lags really, really badly if not collapsed; it is trying to render the entire list while it is constantly being updated by the tickers. Open the folder at your own risk :P
Fun little tidbit: Setting `d`'s initial value to something other than `0` will cause the code to produce a rotated fractal. Try it out!
[Try It On Desmos!](https://www.desmos.com/calculator/jabrjc2pzl)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/tswf6gnl7x)
[Around 7000 segments](https://www.desmos.com/calculator/jmergcbmbu)
---
Here's a longer version without actions (it runs a lot faster!):
### 125 bytes
```
gg~g+1
k=2-g
L=[1...n]
S=∑_{a=0}^L90(1-floor(ak+k)+floor(ak))(-1)^a
C(l)=∑_{i=1}^Ll[i]
f(n)=join((0,0),(C(cosS),C(sinS)))
```
The function `f(n)` will take in a positive integer `n` and output the first `n` segments of the fractal.
The restriction of 9999 segments also applies to this answer; Desmos lists can only contain up to 10000 elements. Theoretically though, the code can produce any amount of segments if there was no restriction on list length.
`f(9999)` takes about 30 seconds to load on my computer.
[Try It On Desmos!](https://www.desmos.com/calculator/suh9azs00t?timeInWorker)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/aqzk4btifa?timeInWorker)
[3000 segments (if you don't want to load the 9999 segments)](https://www.desmos.com/calculator/ouoiystvhq?timeInWorker)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~41~~ ~~39~~ ~~33~~ ~~32~~ ~~31~~ ~~30~~ ~~28~~ ~~26~~ ~~25~~ ~~24~~ ~~23~~ 19 bytes
```
1₀?(~p)yNYdÞR8%2×ø∧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIx4oKAPyh+cCl5Tllkw55SOCUyw5fDuOKIpyIsIiIsIjEwIl0=)
Takes `n` and draws the nth fibonacci number of steps.
Outputs as ascii art.
I may have forgotten you can use any non-whitespace character :p...
*-4 thanks to emanresuA even if I somehow didn't notice it for 4 days*
## Explained (old)
```
1₀?(~p)f:ẏu$ed*ÞR8%2×ø∧
1₀ # Push 1 and 10 to the stack. These will form the initial terms for the Fibonacci words
?( ) # Input number of times:
~p # Without popping the top two items on the stack, prepend the top to the second-top. This gives [1, 10, 101, 10110, 10110101, 1011010110110, ...] - the sequence but with inverted bits
f: # Push two copies of the top of the stack as a list of digits
ẏu$e # Push -1 to the power of each index in the range [0, len(top)]. This determines both a) whether a turn is needed and b) which general direction to make the turn if a turn is needed for each bit in the Fibonacci word. The result will be 0 (no turn, keep going), 1 (turn to the right) or -1 (turn to the left).
d* # Double the list so it can be used with the canvas drawing element and multiply the bit list by the direction list. More on the canvas a little later
ÞR # Take the cumulative sums of the list, remove the last item, and prepend a 0. Yes, that's a thing that's 2 bytes in Vyxal.
8% # Modulo each item by 8. This is so that each number can be mapped to a canvas direction that is one of [0, 2, 4, 6]. 0 = up, 2 = right, 4 = down, 6 = left
2×ø∧ # For each direction in that list, draw a line of *s of length 2 on the global canvas in that direction. Think of the canvas as a kind of turtle but ascii thing, where each direction moves the turtle and leaves a trail of *s behind. The global canvas is implicitly printed at end of execution. This could also be ø^, but ø∧ looks better :p
```
[Answer]
# Python, 83 bytes
```
from turtle import*
a,b=[i:=0],[-1]
while 1:a,b=b,b+a;lt(b[i]**i*90);fd(5);i+=1
```
-6 thanks to tsh
Draws it infinitely.
Very slow because it generates another term of the Fibonacci sequence at every iteration. This is much faster if you want to test it:
```
from turtle import*
a,b=[i:=0],[90]
while 1:
if i>=len(b):a,b=b,b+a
lt(b[i]*(-1)**i);fd(5);i+=1
```
[Try it on repl.it!](https://replit.com/@Steffan153/FibonacciWordFractal)
You can also add a `speed(0)` at the beginning to make it draw faster.
[](https://i.stack.imgur.com/o4vVc.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 26 bytes
```
≔1θFN«#↷∧I§θι⁺²×⁴ι≔⭆θ⍘⊕κ²θ
```
[Try it online!](https://tio.run/##LY6xDoIwGIRneYqmLn@TOkDcnNCJQUPUF6jwC41QoP0hJsZnr626XS53313VKlsNqvM@d043BnjKJZvELrkPlkFhxplOc39DC0KwV7IqrTYEfM1DZFXqZaCzblqC3NRwUC4IKkyNT5gk00JIVnazg0yyq@7Rwfbrilj@D14oEJujGmNjrxz@jDBdWezRENbwCJwswuKxt/dZ6jdL9wE "Charcoal – Try It Online") Link is to verbose version of code. Outputs the start point of each segment. Explanation: Actually calculates the complementary sequence A005614 because it's golfier.
```
≔1θ
```
Start with `1`.
```
FN«
```
Repeat `n` times.
```
#
```
Output the start point of the segment.
```
↷∧I§θι⁺²×⁴ι
```
Calculate the amount of rotation in multiples of 45°. This is `0` if the element of A005614 was `0` or `2` plus `4` times the number of steps so far (`k`).
```
≔⭆θ⍘⊕κ²θ
```
Extend the string holding A005614 by incrementing each digit in base 2 i.e. replace `0` with `1` and `1` with `10`. (Note that this is very inefficient since it calculates the string to length `F(n+2)` which is `28657` for the example of `n=21`.)
Previous more efficient 29-byte version:
```
FN«#W№⍘Lυ²11⊞υω⊞υω↷∧﹪Lυ²⁺²×⁴ι
```
[Try it online!](https://tio.run/##XYyxCsIwGITn9il@4vIH4tDi1kmdBJWivkBtYxNIE0nyt4P47DGOenDDfcddrzrfu86k9HAe8GCfFM803aVHzuFVFq3XNiJbMd6UxaK0kYB7R5ntuiCvMdcjHqUdo0LiAupsVlUsr1sKmQlYvtPfoGcXL3pUEbd2wJMbyLj/l9ZQwFrATU8y4EaA5llN@U6prtJ6Nh8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the start point of each segment. Explanation: The Fibonacci word A003849 is simply the Fibbinary sequence A003714 modulo 2.
```
FN«
```
Loop `n` times.
```
#
```
Output the start point of the segment.
```
W№⍘Lυ²11⊞υω
```
Increase the length of the predefined empty list as necessary so that it reaches a Fibbinary number, i.e. its binary representation does not contain `11`.
```
⊞υω
```
Increase the length of the predefined empty list again. The above loop will then find the next Fibbinary number on the next pass through the outer loop, but this also complements the least significant bit which simplifies the next calculation.
```
↷∧﹪Lυ²⁺²×⁴ι
```
Calculate the amount of rotation in multiples of 45°. This is `0` if the Fibbinary number was odd or `2` plus `4` times the number of steps so far (`k`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ ~~34~~ 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Tηλèì}āsÏV0YvDyÈiÍëÌ])8%AY¥>2šrΛ
```
Takes advantage of the mentioned *at least* in the challenge rules to save 2 bytes.
Outputs using the lowercase alphabet as characters (but could also use any single digit instead by replacing the `A`).
[Try it online.](https://tio.run/##ATkAxv9vc2FiaWX//1TOt867w6jDrH3EgXPDj1YwWXZEecOIacONw6vDjF0pOCVBWcKlPjLFoXLOm///MTA)
**Explanation:**
Step 1: Get the Fibonacci word \$F\_n\$ based on the input \$n\$, but with the 0s and 1s reversed:
```
T # Push 10
η # Pop and push its prefixes: [1,10]
λ # Start a recursive environment,
è # to generate the (0-based) (implicit) input'th value
# Starting with a(0)=1 and a(1)=10
# Where every following a(n) is calculated as:
# (implicitly push a(n-2) and a(n-1)
ì # Prepend a(n-1) in front of a(n-2)
} # Close the recursive environment
```
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f8/5Nz2c7sPrzi8pvb/f0MDAA)
Step 2: Generate a list of \$k+1\$ at the 1-positions:
```
ā # Push a list in the range [1,length] (without popping the string)
s # Swap so the string is at the top of the stack again
Ï # Only keep the 1-based values at the truthy (==1) positions
```
[Try just step 2 online.](https://tio.run/##yy9OTMpM/f8/5Nz2c7sPrzi8ppbrSGPx4f7//w0NAA)
Step 3: Using this list of \$k+1\$ indicating when to turn clockwise/counterclockwise, transform it to a list of [05AB1E Canvas directions](https://codegolf.stackexchange.com/a/175520/52210) (0=↑; 2=→; 4=↓; 6=←):
```
V # Pop and store this list in variable `Y`
0 # Push a 0
Yv # Loop `y` over list `Y`:
D # Duplicate the current value
yÈi # If `y` is even:
Í # Increase the value by 2
ë # Else (`y` is odd):
Ì # Decrease the value by 2
] # Close both the if-else and loop
) # Wrap all values on the stack into a list
8% # Modulo-8 each
```
[Try just step 3 online.](https://tio.run/##ATAAz/9vc2FiaWX//1TOt867w6jDrH0KxIFzw48KVjBZdkR5w4hpw43Dq8OMXSk4Jf//MTA)
Step 4: Modify the list from step 2 to a list of lengths, and using this modified list and the directions-list from step 3, draw the lowercase alphabet in this pattern with the Canvas builtin:
```
A # Push constant "abcdefghijklmnopqrstuvwxyz"
Y # Push list `Y` from step 2
¥ # Pop and push its deltas/forward-differences
> # Increase each value by 1
2š # Prepend a 2
r # Reverse the three values on the stack
Λ # Use the Canvas builtin with these three options
# (after which the result is output immediately)
```
[See this 05AB1E tip of mine for an in-depth explanation about the Canvas builtin `Λ`](https://codegolf.stackexchange.com/a/175520/52210) and how the generated directions- and length-lists are used.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 75 bytes
```
Graphics@Line@AnglePath@Nest[Flatten@{#,p(-1)^Tr[1^(p=#)]}&,p=0;Pi/2,#]&
```
Takes n and draws the nth fibonacci number of steps.
>
> n=14
>
>
>
[](https://i.stack.imgur.com/upcIF.png)
-24 bytes from @alephalpha
-4 bytes from @att
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~28~~ ~~27~~ 26 bytes
*Inspired by [Sanchises' answer](https://codegolf.stackexchange.com/a/187330/36398) to a loosely related challenge. I think the approach is also similar to that in [Jonah's answer](https://codegolf.stackexchange.com/a/251747/36398) here.*
```
JO2B1i:"6Mh]htn:Eq*^YpYsXG
```
The output is rotated 90 degrees clockwise with respect to the examples in the challenge text. The initial segment is not drawn. More steps than necessary are drawn.
[**Try it at MATL online!**](https://matl.io/?code=JO2B1i%3A%226Mh%5Dhtn%3AEq%2a%5EYpYsXG&inputs=11&version=22.6.0)
With input `11` this gives the last image shown in the challenge (rotated):
[](https://i.stack.imgur.com/uXeUH.png)
### Explanation
```
J % Push imaginary unit, j: (*)
O % Push 0: (**)
2B % Push 2 in binary, that is, [1 0]. This is F_1, with 0 and swapped
1 % Push 1. This is F_0, with 1 instead of 0
i % Input n
:" % Do n times
6M % Push first input to the latest function that took more than 1 input.
% In the first iteration this does nothing; in iteration k>1 it gives
% F_{k-1}
h % Concatenate F_k and F_{k-1} to produce F_{k+1}
] % End. The top of the stack contains F_{k+1}
h % Concatenate 0 (**) with F_{k+1}: (***)
t % Duplicate
n: % Range [1 2 3 ... L], where L is the length of the above
Eq % Times 2, minus 1, element-wise. Gives [1 3 5 ...]
* % Multiply with (***), element-wise
^ % Imaginary unit (*) raised to this, element-wise
Yp % Cumulative product. This generates the directions: 1, j, -1 or -j
Ys % Cumulative sum. This generates the path, starting at 0
XG % Plot as complex numbers
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 242 bytes
```
N+A+B+R:-N<1,R=B;append(B,A,C),N-1+B+C+R.
D-X/Y-N-K-Q:-Q=[H|T],(N/\1>0,V=X+2-N;V=X),(N/\1>0,W=Y;W=Y+1-N),new(L,line(X,Y,V,W)),send(D,display,L),M is(N-K*H)mod 4,D-V/W-M-(-1)*K-T;1=1.
\X:-new(D,window()),X+[1]+[1,0]+R,D-0/0-1-1-R,send(D,open).
```
`\X` will calculate the `X`th Fibonacci word and thus draw at least `X` steps.
Uses the [XPCE](https://www.swi-prolog.org/packages/xpce/) toolkit for creating GUI applications in Prolog, here's an example output for goal `\20.`:
[](https://i.stack.imgur.com/SOPaw.png)
In the `A-B-C-D-E` predicate, no expressions are evaluated until calling `new` to create the line, which makes the code very slow:
```
?- time(\16).
% 36,098 inferences, 15.493 CPU in 15.518 seconds (100% CPU, 2330 Lips)
```
Here is a faster and more readable version that evaluates every iteration:
```
_-_-_-_-[]-fast.
D-X/Y-N-K-[H|T]-fast:-
% Flip K (odd/even position)
Z is(-1)*K,
% Calculate the new X,Y location
(N/\1>0,V is X+2-N;V=X),
(N/\1>0,W=Y;W is Y+1-N),
% Send new line to display
new(L,line(X,Y,V,W)),
send(D,display,L),
% Set new direction depending on H and previous direction N
M is(N-K*H)mod 4,
D-V/W-M-Z-T-fast.
fast(X):-
% 0s and 1s are flipped for shorter calculation (if 0 becomes if 1)
new(D,window()),X+[1]+[1,0]+R,D-0/0-1-1-R-fast,send(D,open).
```
```
?- time(fast(25)).
% 3,374,631 inferences, 2.311 CPU in 2.319 seconds (100% CPU, 1460457 Lips)
```
[Answer]
# [R](https://www.r-project.org/), ~~99~~ ~~82~~ ~~76~~ ~~74~~ 73 bytes
*Edit: -2 bytes thanks to pajonk*
```
function(n,`?`=cumsum){while(n<-n-1)T=c(F,F<-T)
plot(?1i^?c(1,3)*T,,"l")}
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=fwf%3D%0Afunction(n%2C%60%3F%60%3Dcumsum)%7Bwhile(n%3C-n-1)T%3Dc(F%2CF%3C-T)%0Aplot(%3F1i%5E%3Fc(1%2C3)*T%2C%2C%22l%22)%7D%0A%0Afwf(24))
`while(n<-n-1)T=c(F,F<-T)` generates the `n`-th Fibonacci word in reverse, with zeros and ones exchanged.
Then, `cumsum(c(1,3)*m)` calculates cumulative sum multiplied by 1 (at odd indices) or 3 (at even indices), to give the current direction.
`i` raised to this power gives a step in the right direction, and the cumulative sum of this gives the position at each step: `cumsum(1i^cumsum(c(1,3)*m))` (the function `cumsum` is re-assigned to the low-precedence `?` operator to save bytes (and obfuscate).
So we just plot this on the complex plane, using `"l"` to join the points with lines.
[](https://i.stack.imgur.com/V8xVl.png)
This would be 66 bytes in [R](https://www.r-project.org/) version ≥4.1 by replacing `function` with `\`, but this isn't currently supported by the online interpreter at rdrr.io.
[Answer]
### HTML+Javascript, ~~228~~ ~~216~~ 210 bytes
`f(n)` draws at least `n` segments. The size adapts so that the fractal does not get too small.
*12 bytes saved thanks to Neil*
```
f=o=>{for(k=b=n=0,l='01';!l[o];)m=l,l+=k,k=m
d='M1,1';p=5;for(w of l)e=1-(b&2),d+='hv'[b&1]+e,b+=w|0?0:n%2*2+1,b%=4,p+=e,n++
document.write(`<svg viewBox=0,0,${p},${p} style=fill:none;stroke:#000><path d=`+d)}
f(2000)
```
-13 bytes with a fixed-size canvas, which limits the number of segments that are visible. (And low `n` are really hard to see.) For `viewBox="0 0 999 999"`, approx. `n ≤ 75000`.
```
f=o=>{for(k=b=n=0,l='01';!l[o];)m=l,l+=k,k=m
d='M1,1';for(w of l)d+='hv'[b&1]+(1-(b&2)),b+=w|0?0:n%2*2+1,b%=4,n++
document.write(`<svg viewBox=0,0,999,999 style=fill:none;stroke:#000><path d=`+d)}
f(75000)
```
**Non-competing bonus:** I was also experimenting with a recursive solution in HTML/[Pug](https://pugjs.org/api/getting-started.html), but it ended at 500 bytes, and it's really slow and memory-heavy. [See it on Codepen](https://codepen.io/ccprog/pen/bGMEBVz).
] |
[Question]
[
aka. implement an easier version of [05ab1e's canvas element](https://codegolf.stackexchange.com/questions/96361/tips-for-golfing-in-05ab1e/175520#175520).
# Description
The canvas element is used to draw ASCII lines on the screen.
The (easier version of the) canvas element takes a list of integers and returns a multi-line string (or a list of strings).
The integers map to the following directions:
```
7 0 1
‚Üñ ‚Üë ‚Üó
6 ‚Üê X ‚Üí 2
‚Üô ‚Üì ‚Üò
5 4 3
0: upwards
1: top-right
2: right
3: bottom-right
4: downwards
5: bottom-left
6: left
7: top-left
```
If given eg. `[6, 4, 2]`, it outputs this:
```
###
#
###
```

1. Start with one hash already drawn (`X`)
2. Draw two hashes towards the left (direction `6`)
3. Draw two hashes downwards (direction `4`)
4. Draw two hashes towards the right (direction `2`)
# Rules
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* Multiple integers or a list of integers will be given as the input
* Output must be a string, a list of strings, or a matrix of characters (like a binary matrix)
* You will not receive directions with intersecting lines
* You can replace `#` with any other constant character, but you'll always have to draw **2** hashes per direction and **start** with a hash
* Excess whitespace is allowed
* The shortest code, as this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), wins
# Examples
```
In: [1, 5, 3, 7, 5, 1, 7, 3]
Out:
# #
# #
#
# #
# #
In: [2, 2, 2, 2, 4, 4, 7, 7]
Out:
#########
# #
# #
##
#
In: [1, 2, 3, 6, 6, 2, 4, 2, 2, 4, 2, 6, 4, 2, 1, 3, 2, 6, 7, 5, 6, 6, 4, 0, 6, 4, 0, 6, 0, 6, 2, 0, 2]
Out:
###
# #
# #####
#
#######
# #
### ### #
# # # #
######### ###
# #
# #
```
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
√ó3√∏^
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDlzPDuF4iLCIiLCJbMiwgMiwgMiwgMiwgNCwgNCwgNywgN10iXQ==)
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
3$Λ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fWOXc7P//o410FODIBIzMgSgWAA "05AB1E – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
FA✳ι##‖↘#
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLREQ1NTIaAoM69EwyWzKDW5JDM/TyNTU0dBSVlZSdOaKyg1LQcoqmHlkl@eF5SZnlECFISoVwIp@P8/OtpIRwGOTMDIHIhiY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FA
```
Loop over the directions.
```
✳ι##
```
Print two `#`s in that direction.
```
‖↘
```
Reflect to switch from Charcoal to 05AB1E coordinates. This is because Charcoal's coordinate system has `0` as right and `2` as up etc.
```
#
```
Print the final `#`.
Boring built-in version:
```
GH✳✳⁻²A³#
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nuXv96x4NGczCDXuPrTp/Z6FhzYr//8fHW2kowBHJmBkDkSxsQA "Charcoal – Try It Online") ~~Link is to verbose version of code~~ Unfortunately the version of Charcoal on TIO has a bug in its deverbosifier meaning that it parses `Directions()` as `Direction(s)`. I could use a capital `S`... or you could just [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjdNA_JzKtPz8zzyc3LyyzVcMotSk0sy8_OKNXwz80qLNYx0FDzzCkpLNDQ1NXUUjHUUlJSVNK2XFCclF0ONWB6tpFuWoxS7KzoaqBiOTMDIHIhiYyEKAQ "Charcoal – Attempt This Online") Link is to verbose version of code. Note that the `PolygonHollow` line drawing code takes the lengths of the lines rather than the number of additional `#`s to draw.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 106 bytes
```
->d{m=2*x=y=d.size*2;c=[]
[-5,*d].map{|k|2.times{(c[y+=k==6?0:k%7<=>2]||=[0]*m)[x+=k<1?0:4<=>k]=1}};c-[p]}
```
[Try it online!](https://tio.run/##ZVFha4MwEP3eX3E4Bq1LJYlWYW26H5Llg9OUdWInrYU64293mmvEUnjkXu4l7@648/Wr6Q@iX@/zthTcv4lG5MHl@Kd9vs2EVFu53hA/V0GZVq0pDA/qY6kv7TKTzZsohIg/6HvxmuzEnitjhKTKL1fyNmg7NkjRIBRKsK7bZmtZqa7P9QGqs67rZpmuFgAVpON5rS@QjlWgBaMN6Bn34MWT2hiuoIPg5/d4gg6D93ny7r8X@pQv6gwEyCEjYwIRAa7IeGEENgRCAoklzJJw0rjVYguO/2YkdoTZZ5hBo9ip9JFQZ0WnFmIMFAN3JbBKZA0T1CKXQrAZsN7dg9oU9h65dpJJo4/@oQVzwyduHMRmBlT5E3C6yZZZHrokxb7UsIJAp9n3uLrM3DcNB5kNu@v/AQ "Ruby – Try It Online") Returns a binary matrix (1 for `#`, 0 for ). A semicolon replaced for a newline for readability's sake (and the same byte count). Produces a lot of leading/trailing spaces in each row (most of the time).
I'm sure there's some more bytes to be shaved but I can't currently see what they are.
## Direction to coordinate formula
I'm not sure if this is the shortest, but I imagine this approach is shorter than an approach by complex exponentiation. For a given direction \$k\$, we want to produce the delta directions \$dx\$ and \$dy\$ to "nudge" our central coordinate along. We can see that, through some formula manipulation, we can do just that:
\begin{array} {|c|c|}
\hline k & dx & dy & k<1 & 4\Leftrightarrow k& & k=6 & k\bmod7 & k\bmod7\Leftrightarrow2 \\
\hline 0 & 0 & -1 & T & 1 & \mathbf{0} & F & 0 & -1 & \mathbf{-1} \\
\hline 1 & 1 & -1 & F & 1 & \mathbf{1} & F & 1 & -1 & \mathbf{-1} \\
\hline 2 & 1 & 0 & F & 1 & \mathbf{1} & F & 2 & 0 & \mathbf{0} \\
\hline 3 & 1 & 1 & F & 1 & \mathbf{1} & F & 3 & 1 & \mathbf{1} \\
\hline 4 & 0 & 1 & F & 0 & \mathbf{0} & F & 4 & 1 & \mathbf{1} \\
\hline 5 & -1 & 1 & F & -1 & \mathbf{-1} & F & 5 & 1 & \mathbf{1} \\
\hline 6 & -1 & 0 & F & -1 & \mathbf{-1} & T & 6 & 1 & \mathbf{0} \\
\hline 7 & -1 & -1 & F & -1 & \mathbf{-1} & F & 0 & -1 & \mathbf{-1} \\
\hline -5 & & & T & 1 & \mathbf{0} & F & 2 & 0 & \mathbf{0} \\
\hline \end{array}
Bolded cells above indicate taking the previous expression, but instead choosing zero if the previous condition holds. In code, we update our coordinates as thus:
```
x += k < 1 ? 0 : 4 <=> k
y += k == 6 ? 0 : k % 7 <=> 2
```
Important to note is that \$-5\$, as well as any other number \$c<1\$ for which \$c\equiv 2\mod 7\$, produces a 0 in both coordinates, and is useful as a placeholder to mean "no action", and hence a useful initialization instruction.
## Commented code
```
-> d {
# x and y are initially set to d.size * 2, guaranteeing us sufficient room
# so that our calculations will not step outside of bounds.
# m is our minimum width for padding purposes for such a bound, and extends
# the distance from 0 to x or y in each direction, that is, 2x or 2y
m = 2 * x = y = d.size * 2
c = []
# to account for the initial cell, we prepend -5 to the input (see above table)
[-5, *d].map { |k|
# since each line is two characters long, we update each cell individually
2.times {
# update y, as per above
y += k == 6 ? 0 : k % 7 <=> 2
# get the current row, defaulting to an appropriate row of 0s
row = c[y] ||= [0] * m
# update x, as per above
x += k < 1 ? 0 : 4 <=> k
# update (x,y) in the output array
row[x] = 1
}
}
# remove all nil rows from the output array
c - [p]
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 25 ~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Saved three bytes using the allowance of excess whitespace (this also fixed a bug that meant an input with only left and/or right movements would have printed incorrectly since no space or newline characters were being introduced in such cases).
```
ı2½*Nx2ŻÆiNṠ+\+L$ŒṬo⁶Y
```
A full program that accepts the list of instructions and prints the result using `1` as the character.
**[Try it online!](https://tio.run/##y0rNyan8///IRqNDe7X8KoyO7j7clun3cOcC7RhtH5Wjkx7uXJP/qHFb5P///6MNdRRMdRSMdRTMwQxDMMM4FgA "Jelly – Try It Online")**
### How?
Jelly has no canvas drawing built-ins, so instead this builds a matrix of zeros and ones, with ones at visited locations and prints it with spaces in place of zeros joined with newline characters.
```
ı2½*Nx2ŻÆiNṠ+\+L$ŒṬo⁶Y - Main Link: list of integers from [0,7]:
ı2 - 2i (twice the square root of -1)
¬Ω - square root
N - negate the input (vectorises)
* - exponentiate (vectorises)
x2 - repeat each element twice
Ż - prefix with a zero
Æi - convert each to [real, imaginary] parts
N - negate (vectorises)
·π† - sign (vectorises)
\ - cumulative reduce by:
+ - addition (vectorises)
$ - last two links as a monad:
L - length
+ - add (vectorises)
ŒṬ - matrix with 1s at the indicated [row, column]s
o⁶ - logical OR with space character
Y - join with newline characters
- implicit, smashing print
```
Note: `ı2` is a hack - `ı` should work but there are floating-point errors - for example, `ı½*-2` gives `2.220446049250313e-16-1j` rather than `0-1j`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~79~~ ~~77~~ ~~71~~ ~~67~~ ~~58~~ ~~53~~ 51 bytes
*Saved 5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)*
```
' '+(¬¨‚ä∏-‚Üë‚Üë‚üú1)‚àò‚ãàÀú‚àò¬¨‚üú-‚àò‚â†{ùï®(ùﮂஂåΩ)¬¥-ùï©}4(‚ä¢√ó‚óã√ó-)2/8|-‚üú2‚ä∏‚ãମ
```
[Try it at BQN online](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgJyAnKyjCrOKKuC3ihpHihpHin5wxKeKImOKLiMuc4oiYwqzin5wt4oiY4omge/Cdlago8J2VqOKIqOKMvSnCtC3wnZWpfTQo4oqiw5fil4vDly0pMi84fC3in5wy4oq44ouIwqgKCkYgMeKAvzXigL8z4oC/N+KAvzXigL8x4oC/N+KAvzM=)
### Explanation
New approach!
```
8|-⟜2⊸⋈¨
```
Turn each number in the initial list of directions into a list containing two numbers, the first number shifted two directions counterclockwise (i.e. minus 2, mod 8). These will become the y and x deltas, respectively.
```
2/
```
Repeat each direction twice.
```
4(⊢×○×-)
```
Turn the directions into deltas. We want to implement the following function:
* 0 or 4 -> 0
* 1, 2, or 3 -> 1
* 5, 6, or 7 -> -1
We almost get the desired result if we subtract the input from 4 and take the sign. The only problem is that 0 becomes 1, which we can fix by multiplying by the sign of the input: `sign(4-x) * sign(x)`, in C-like pseudocode. In BQN, `×○×` is a dyadic function that takes the sign of each argument and multiplies them; `(⊢×○×-)` is a dyadic train that passes its right argument and the difference of its arguments to `×○×`; and so if we give it `4` as its left argument and a direction number as its right argument, it will return the desired delta. Since all of the functions used here are pervasive, we can apply them to a list of lists of numbers and get a list of lists of results.
```
(¬⊸-↑↑⟜1)∘⋈˜∘¬⟜-∘≠
```
Call the length of the original list \$N\$. (The length of the list of deltas is \$2N\$ because we repeated each move twice.) Construct a \$4N+1\$ by \$4N+1\$ array that is filled with 0s but with a 1 in the exact center.
```
{ùï®(ùﮂஂåΩ)¬¥-ùï©}
```
Negate each delta and right-fold the list of deltas using the following procedure: Start with the \$4N+1\$ array constructed above. At each step, rotate the partial result by the current delta, and then logical OR with another copy of the \$4N+1\$ array. The result is a \$4N+1\$ by \$4N+1\$ array of 0s and 1s.
```
' '+
```
Add a space character, converting the 0s to spaces and the 1s to `!`s.
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl043F`, 63 bytes
```
$_=". "[[email protected]](/cdn-cgi/l/email-protection)/./(<#{DA,A,,B,BD,{B,,A}DD}>)[$&]x2/ger;s/\w/.[$&/g
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89XCJcZiBcInhARi5zLy4vKDwje0RBLEEsLEIsQkQse0IsLEF9RER9PilbJCZdeDIvZ2VyO3MvXFx3L1x1MDAxYlskJi9nIiwiYXJncyI6Ii1wbDA0M0YiLCJpbnB1dCI6IjY0MiJ9)
## Explanation
The solution utilises ANSI escape sequences to move the cursor to the required position based on the input commands. First `$_` is reset to `@F` (a list containing each character of the input, which, when interpreted as a scalar, returns the length of the list) repetitions of `\f` (form-feed followed by space) to move the cursor to a position to allow enough space for the output (hopefully...), concatenated with the original input `s///`ubstituting each digit (`.`) with its index into the `glob` list (`<#{DA,A,,B,BD,{B,,A}DD}>`). This results in a string like: `#A#A#BDD#BDD#B#B#DDA#DDA#BDD#BDD#A#A#DDA#DDA#B#B#` where the letters correspond to the ANSI escape sequence to move either left, up or down. These letters are then replaced with the correct ANSI escape sequences in the final `s///`ubstitution.
[Bonus "cat" drawing.](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89XCJcZiBcInhARi5zLy4vKDwje0RBLEEsLEIsQkQse0IsLEF9RER9PilbJCZdeDIvZ2VyO3MvXFx3L1x1MDAxYlskJi9nIiwiYXJncyI6Ii1wRi8uLi4uLi4uLyIsImlucHV0IjoiMjIyMzIyMjIyMjEyMjI2NjYxMjIyNjY2MDA3Njc3NDQ2Njc3NDQ2NTQ0NjY2MjIyMzczNzIyMjIyMjIyMjI2NjY2NDY2MDY3MTM1MjIyMjcxMzUifQ==)
[Answer]
# [C](https://en.wikipedia.org/wiki/C_(programming_language)) ([gcc](https://gcc.gnu.org/)): ~~218~~ 210 bytes
**Edit**: Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for shortening the code to *210 bytes*.
```
p=297,C[800]={[297]=3},d,j=800;f(D,n){d^D?:(C[p+=n]=C[p+=n]=3);}main(c,v)char**v;{for(;d=*v[--c]-48,c;f(0,-40))f(7,-41),f(6,-1),f(5,39),f(4,40),f(3,41),f(2,1),f(1,-39);for(;j--;j%40?:puts(""))putchar(C[j]+32);}
```
[Try it online](https://tio.run/##dVPfb5swEH7nrzh1moAWKAH6E6FqSl76Vml7izLJsU1wFmyEDair@q@Xnc1aVZMWgs9wd999952h8YHSefYuL@FHQ@QvDUYB5eIk5IESA7XqQTeqN1ziGzANB6oYt1HZKoX9s@Has9n@enubpjsfhHZR2QYokSPREKArS3fbAr0h1CdiEIwzUIOxMKsNEMkQVRoipEu2eKquNTdoHNq37@vHR6AN6Qk1vF841L1qIc8g4MkhAf@L/28AUsmvLNgeS01qODHYc9BG9VgemeVhgl1jFP73nJJBY44URpCT@G3bJRJI35NnmIRp8OnZMUNCPYzkNKAMqBmkNl8qg@U56SDQHaE8noTmoWtNSIzDEEosvvFtMWNJGmXxjoM2QBizrUwNSjOiS3LOOEucsp1vR2DZd0pIJ5rVpBWMnfi7Qu9it@LQGNvm1Cvs4P4pTLyuyu5uomVA1csWH3ZV/hqx6Fjhq3IZPhJs1ciX6dGh1zh5y571ZNKQWX310gpK2HEqaoEqMtFzaoSS4G/8xKuDTSTDF/Zz83AfrLfdRSV31bvNw/LVa3HIAY3G0M7q/HwsXzz4@0MaayWxe4Naqba11fEccpzBYWi5NO5wouA@quB/IqfkJwmSDzw8u0HJqvNxG8d0Fxe3ES3rII3iIg3DOrjBzSqM6uA6ip29ivI7a4sIA9Dm0eLPImdWUYz@8jPdp97N43@1j3FcHr8W6cN9NxgdnJ2FIW5s46jNcXeRZwj36s3zvJqzOZ@v8crmAu9lvXbrCj12fzNfuYhiTj/W1GWkc/ZG8cM66Dme/gA) (with explanation)
**Explanation**:
```
// Thanks to ceilingcat for shortening the code to 210 bytes
// 'C[800]' is the 2D canvas ('C[20][40]') flattened out to 1D and contains the
// offset of the ASCII character code from 32 (e.g. '#' character code is 35
// but would be stored as 3). This is because initializing an array with any
// other value than 0 is not cheap (space-wise) and in this case it's better to
// just add 32 whenever needed.
// 'p' should point to the middle of the canvas (might be wrong :P).
p=297,C[800]={[297]=3},d,j=800;
// This moves the cursor and draws 2 '#'s in the specified direction 'D'.
f(D,n){d^D?:(C[p+=n]=C[p+=n]=3);}
main(c,v)char**v;{
// Converts command line arguments to an 'int' and draws on the canvas.
for(;d=*v[--c]-48,c;f(0,-40))f(7,-41),f(6,-1),f(5,39),f(4,40),f(3,41),f(2,1),f(1,-39);
// Print the canvas.
for(;j--;j%40?:puts(""))putchar(C[j]+32);
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes
```
from turtle import*
mode("logo")
def f(l,w=write):
reset();ht();pu();w("#")
for d in l:seth(d*45);fd(9);w("#");fd(9);w("#")
```
] |
[Question]
[
Common words should still be avoided to be used as passwords. This challenge is about coding a very simple program that munges a given password (**M**odify **U**ntil **N**ot **G**uessed **E**asily).
**Input**
A word, which is a string written in the alphabet `abcdefghijklmnopqrstuvwxyz`. It does not matter if the letters are lowercase or uppercase.
**Munging**
1. Change any repeated sequence of a same **letter** to itself preceded by the number of times the letter was repeated (`LLLL` with `4L`)
2. Change the first `a` with `@`
3. Change the first `b` with `8`
4. Change the first `c` with `(`
5. Change the first `d` with `6`
6. Change the first `e` with `3`
7. Change the first `f` with `#`
8. Change the first `g` with `9`
9. Change the first `h` with `#`
10. Change the first `i` with `1`
11. Change the second `i` with `!`
12. Change the first `k` with `<`
13. Change the first `l` with `1`
14. Change the second `l` with `i`
15. Change the first `o` with `0`
16. Change the first `q` with `9`
17. Change the first `s` with `5`
18. Change the second `s` with `$`
19. Change the first `t` with `+`
20. Change the first `v` with `>`
21. Change the second `v` with `<`
22. Change the first `w` with `uu`
23. Change the second `w` with `2u`
24. Change the first `x` with `%`
25. Change the first `y` with `?`
Rule 1 must be applied the needed number of times until it is not possible to apply it more. After that the rest of the rules are applied.
**Output** The munged word
**Examples**
* `codegolf` --> `(0639o1#`
* `programming` --> `pr09r@2m1ng`
* `puzzles` --> `pu2z135`
* `passwords` --> `p@25uu0r6$`
* `wwww` --> `4uu`
* `aaaaaaaaaaa` --> `11a`
* `lllolllolll` --> `3103io3l`
* `jjjmjjjj` --> `3jm4j`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so please make your program as short as possible!
Nothing in this post should be used as password ideas or as any part of password practices.
[Answer]
# Java 8, ~~237~~ ~~321~~ ~~319~~ ~~280~~ ~~247~~ ~~241~~ ~~240~~ 237 bytes
```
s->{for(int a[]=new int[26],i=0,l=s.length,t,x;i<l;i+=t){for(t=0;++t+i<l&&s[i]==s[t+i];);System.out.print((t>1?t+"":"")+(++a[x=s[i]-65]>2?s[i]:"@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x+26*~-a[x])+(x==22?"u":"")));}}
```
+84 bytes because the rules got changes.. (*EDIT: Finally back to my initial 237 bytes.*) Replacing `WWWW` with `222W` is easy in Java, but with `4W` not.. If only Java had a way to use the regex capture-group for something.. Getting the length with `"$1".length()`, replacing the match itself with `"$1".replace(...)`, converting the match to an integer with `new Integer("$1")`, or using something similar as Retina (i.e. `s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1")`) or JavaScript (i.e. `s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))`) would be my number 1 thing I'd like to see in Java in the future to benefit codegolfing.. >.> I think this is the 10th+ time I hate Java can't do anything with the capture-group match..
-78 bytes thanks to *@OlivierGrégoire*.
I/O is uppercase.
**Explanation:**
[Try it here.](https://tio.run/##nZBdT8IwFIbv/RW1fqSzsMAMRBkFERA/9oGbRGXZRZ0Tq3Mja1GImX8du8GV8WptT9Jzmuc9Pe8b/aTVZB7Gb8/v6yCinAOTsvh7BwAWizB9oUEIrDwF4DNhzyBAwStNPR9wRZfVTIY8XFDBAmCBGBCw5tXO90uSIqkAqOeTOPzK1Tyt6VcYqVUiwtUojGfitSIqS521I51hIpQCEqSmYyywrB4eco/5hHBPpr6u6O6Ki/BDTRZCnadSESHRqXcFhrAFoYIRxtRbkhyqNht@R@vm1xY8O0HN473Tvfp1u25atfGp08CTzuKgO@2d9wfDi9Hl7vUNMy17fOvs303a2sPjFKr5nD2BllhrHv1UpbAvOywJ0bQuXBQNFUXPsrW@sWC@eIqkBVsnCq8@pJPIFfKnM2kYVTY2xmqAYN8eDEe2cQFVkfTzRmlKV0gpPAXg75xRjLYvBTx27JHTM80ra1SOn0ynxtAtx/Zc9952BuXoe7lKgYZh2Nso19iW@z8y28nWvw)
```
s->{ // Method with String parameter and no return-type
for(int a[]=new int[26], // Array with 26x 0
i=0, // Index-integer, starting at 0
l=s.length, // Length
t,x; // Temp integers
i<l; // Loop (1) over the characters of the input
i+=t){ // After every iteration: Increase `i` by `t`
for(t=0;++ // Reset `t` to 1
t+i<l // Inner loop (2) from `t+i` to `l` (exclusive)
&&s[i]==s[t+i]; // as long as the `i`'th and `t+i`'th characters are equal
); // End of inner loop (2)
System.out.print( // Print:
(t>1?t+"":"") // If `t` is larger than 1: print `t`
+(++a[x=s[i]-65]>2? // +If the current character occurs for the third time:
s[i] // Simply print the character
: // Else:
"@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x
// Print the converted character at position `x`
+26*~-a[x]) // + 26 if it's the second time occurring
+(x==22?"u":""))); // And also print an additional "u" if it's 'W'
} // End of loop (1)
} // End of method
```
[Answer]
# JavaScript (ES6), 147 bytes
```
s=>[[/(.)\1+/g,m=>m.length+m[0]],..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),["w","uu"],["w","2u"]].map(r=>s=s.replace(...r))&&s
```
## Test Cases
```
f=
s=>[[/(.)\1+/g,m=>m.length+m[0]],..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),["w","uu"],["w","2u"]].map(r=>s=s.replace(...r))&&s
;["codegolf","programming","puzzles","passwords","aabaa","www","lllolllolll","jmnpruz"]
.forEach(t=>console.log(t,"->",f(t)))
```
```
.as-console-wrapper{max-height:100%!important}
```
## Explanation
Runs through a series of replacements on the input string, `s`, in the order specified by the challenge. Each item in the series is an array or string, with two items, that is then spread (`...r`) and passed to `s.replace()`.
```
s=>[
[/(.)\1+/g, m=>m.length + m[0]],// first replacement: transform repeated letters
// into run-length encoding
// string split into length-2 partitions and
// spread into the main array
..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),
// next replacements: all single-char replacements.
// "second" versions are placed at the end so they
// replace the second instance of that char
["w","uu"],["w","2u"] // last replacements: the two "w" replacements
]
.map(r=> s = s.replace(...r)) // run all replacements, updating s as we go
&& s // and return the final string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 69 bytes
-9 bytes thanks to Emigna
```
γvygD≠×yÙ}J.•k®zĀÒĀ+ÎÍ=ëµι
•"@8(63#9#1<1095+>%?!i$<"ø'w„uu„2u‚â«vy`.;
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3OayynSXR50LDk@vPDyz1kvvUcOi7EPrqo40HJ50pEH7cN/hXtvDqw9tPbeTCyij5GChYWasbKlsaGNoYGmqbadqr5ipYqN0eId6@aOGeaWlQMIISMw6vOjQ6rLKBD3r//8LEouLy/OLUooB "05AB1E – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 152 + 1 (`-p`) = 153 bytes
```
s/(.)\1+/(length$&).$1/ge;%k='a@b8c(d6e3f#g9h#i1j!k<l1mio0q9r5s$t+u>v<x%y?'=~/./g;for$i(sort keys%k){$r=$k{$i};$i=~y/jmru/ilsv/;s/$i/$r/}s/w/uu/;s/w/2u/
```
[Try it online!](https://tio.run/##FchBDoIwEADAr2hYBGJkRYPRAOpDvKAUKEWLXQoSAk@3xjlOw1QdGkPo@t4tWKNbs1fRlrDyfAiwYJEtEie93o8PNzuwfW4Vp9LiQbUUcR08udy@TyokaNf63MUfe7g4yYw@FlEuFXCXpGoXgg1kC28ElYAYgU8R8GQesHoqjbymDiNC4AgKJ8Ietf5HjzuNxjQpUS9VRl/ZtFy@yGyaHw "Perl 5 – Try It Online")
[Answer]
Probably not the most golfed it could be, but it works.
-6 bytes thanks to ovs
-77 Bytes thanks to NieDzejkob and Jonathan French
# [Python 3](https://docs.python.org/3/), 329 323 bytes 246 bytes
```
import re;n=input()
for a in re.finditer('(\w)\\1+',n):b=a.group();n=n.replace(b,str(len(b))+b[0],1)
for A,B,C in[('abcdefghikloqstvxyw','@8(63#9#1<1095+>%?','uu'),('ilsvw','!i$<','2u')]:
for a,b in zip(A,list(B)+[C]):n=n.replace(a,b,1)
print(n)
```
[Try it online!](https://tio.run/##TY7RTsJAEEWf5Stq0OxMummoRCMVVOAz2j50YQtTl@m63YL483WrLz5MJjm59@bYqz@2PB8GOtnW@cjpF14R294DTurWRVVEHGhSE@/JawcCigsWRRoLyZipVZUcXNtbwFDkxGlrqp0GJTvvwGgGhRirfFbK9G9wLTdyG0ZzEJXa7XV9ONKHaT87f/66XoQU78/wNJ8upukynS0e49f7twD7XqAEQaY7j5lbuluG9xBomU1ufkWlGlW/ycJaGuo8bDDOtyVm/71CahSxjtgD4zA0TXMK1/wA "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~166~~ 124 bytes
```
(.)\1+
$.&$1
([a-y])(?<!\1.+)
¶$&
¶w
uu
T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.
([ilsvw])(?<!\1.+)
¶$&
¶w
2u
T`i\lsv¶`!i$<_`¶.
```
[Try it online!](https://tio.run/##bczBDoIgAMbxO2/hRIdzsajVcnPZrRfoFi1cmqOhMIhYPpgP4IsRde7yXf77frp98qH2CToyj3BGSQ4gTiEB6Fwv3pcMVWVECc4zME8wDeOAteDExDyxww5t13ERk0dJST8sqSr0Jrd76pLqyuYJB4QL83J/mdWX4TT0QEUclr@L9zfZtJ0Ud6C07HTd93zogLLjKFoDVG2Mk7oxHw "Retina – Try It Online") Explanation:
```
(.)\1+
$.&$1
```
Replace a run of repeated letters with the length and the letter.
```
([a-y])(?<!\1.+)
¶$&
```
Match the first occurrence of the letters `a` to `y` and mark them with a placeholder.
```
¶w
uu
```
Fix the first occurrence of `w`.
```
T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.
```
Fix the first occurrence of all the other letters from `a` to `y` and delete the placeholders.
```
([ilsvw])(?<!\1.+)
¶$&
```
Mark the (originally) second occurrence of the letters `i`, `l`, `s`, `v`, or `w` with a placeholder.
```
¶w
2u
```
Fix the second occurrence of `w`.
```
T`i\lsv¶`!i$<_`¶.
```
Fix the second occurrence of the other four letters.
[Answer]
# [Haskell](https://www.haskell.org/), ~~221~~ ~~218~~ 213 bytes
```
($(f<$>words"w2u li i! s$ v< a@ b8 c( d6 e3 f# g9 h# i1 k< l1 o0 q9 s5 t+ v> wuu x% y?")++[r]).foldr($)
f(a:b)(h:t)|a==h=b++t|1>0=h:f(a:b)t
f _ s=s
r(a:b)|(p,q)<-span(==a)b=[c|c<-show$1+length p,p>[]]++a:r q
r s=s
```
[Try it online!](https://tio.run/##LZDNTsMwEITveYohDZItt6gBgWgUBx4AThzTqnL@ozqxaycNVHl2Qtqy0uzOtyPtYSthD7mUU8O3E/FIEXrRoExm3eGxh6xR38F6OIUQ70hekRJkL8ifUCxQblAtUPs4hJA@1BrHDewzOoZThKHv8X2PnzeXMhabHX0olMwM8ahTEBEklFRBR0fBecUTxrrRj9a8Cm5Z5xTYw3LrmCuPRC@PNFxZLVrCuaAJj9MxnReVGjyfybwtuwp6qaN4t2NMBAZHx1wuTI2oW3A0Qn/uQbZiFem@@@rMRwsPAozBBY/mNrsGgiJ2U5XlpZKFu4SrjSqNaJq6La/Yn88yt1crrL39aoZhrsuUUqp/ubvpNy2kKO20SrX@Aw "Haskell – Try It Online")
Abuses `foldr` to run the string through a sequence of string transformations backwards. The sequence "starts" with `r` which does the repetition count replacement by using `span` to break the tail of the string when it stops being equal to the head. If the first part of that is non-empty it's a repetition so we print the length +1. Next we curry an argument into `f` for each character replacement in (reverse) order. The replacements are encoded as a single string with the first character being the character to be replaced and the rest as the string (since the w replacements are multiple characters) to go in its place. I put these encoded strings in one big string separated by spaces so that `words` can break it into a list for me.
EDIT: Thanks @Laikoni for saving me 5 bytes! That was a clever use of `$` I didn't think of. I also didn't know that `<-` trick.
[Answer]
# [Lua](https://www.lua.org), 173 bytes
```
s=...for c,r in("uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"):gmatch"(.)(.u?)"do s=s:gsub(c..c.."+",function(p)return#p..c end):gsub(c,r,1)end print(s)
```
[Try it online!](https://tio.run/##LYpbDoIwEACvUosmbSSNaDRqRLwKlodVaOtuF5TLVz5M5mcy01EZI@ZKqcYB0ykwYwUnKm/3oxbVod41SXt6JCYzi@fzdemyzvS9tW7j/fsEgHtchvVwHS4j0bilz@pbTBOX57Yvg35woaRQVEheOYY5nluku9BKzfA1TxuyOhhnhZdQBwKb@Lmx2lbyv6aQZnJ25sHYIFDGGH2JODqo8Ac "Lua – Try It Online")
Ungolfed and explained:
```
s = ...
--This string contains every character to replace, followed by
--the character(s) it should be replaced with.
--
--It also contains all characters for which repeated sequences
--of them should be replaced by "<number><character>". That is,
--all letters in the alphabet. This way, a single loop can do
--both the "replace repeated characters" and "encode characters"
--operations, saving a for loop iterating over the alphabet.
--
--Characters that shouldn't be replaced will be replaced with
--themselves.
--
--In order to avoid matching half of the "replace u with u"
--command as the replace part of another command, "uu" is placed
--at the beginning of the string. This ensures that only the
--2-character replacements for "w" get an extra "u".
cmdstring = "uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"
--Iterate over all the search/replace commands.
--The character to replace is in the "c" variable, the string to
--replace it with is in "r".
--
--Due to the dummy search/replace commands (i.e. "mm") placed
--in the string, this loop will also iterate over all letters
--of the alphabet.
for c,r in cmdstring:gmatch("(.)(.u?)") do
--First, replace any occurences of the current letter
--multiple times in a row with "<number><letter>".
s = s:gsub(c..c.."+", function(p)
return #p .. c
end)
--Then, replace the first occurence of the letter
--with the replacement from the command string.
s = s:gsub(c, r, 1)
end
print(s)
```
[Answer]
# **C# (.NET Core), ~~317~~, ~~289~~, 279 Bytes**
```
p=>{string r="",l=r,h=r,c="a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";int i=0,n=p.Length,d,a=1;for(;i<n;i++){h=p[i]+"";if(h==p[(i==n-1?i:i+1)]+""&&i!=n-1)a++;else{d=c.IndexOf(h);if(d>=0&&d%2<1){l=c[d+1]+"";h=l=="u"?"uu":l;c=c.Remove(d,2);}r+=a>1?a+""+h:h;a=1;}}return r;};
```
[Try it Online!](https://tio.run/##ZVFdixMxFH22vyKbdcuEzJZORXGbyVRZWBBWFBV8KH2ISToJpklNMu12h/ntNTOtVvBCPu7NObmHc3m45c7LI0jBDQsBfPau9mwz6ivtsPcRIouag53TAnxk2mYhem3r5QowXwf0F3dhXJhnYJQhBkBBCyB3QtbOrGEO4PbUb5NAQ9o8PxsZhmuSs3deDMk@RX8aY9x5QdCR/9p9PYQoN5OHxvKSK@aXq/wsoQK8Tu2PW1q1pwrwFMLcUJ@rtDiF7N2PtzwTb@Sr9XV9p651oa9@lqYw2k1/3YXX4WXEu2pX7pv97OnmsIBE2wg0neaWbieP0tZR5SJntCBr5zOiS0s0xqhVdLvUKwwTYZ0pmrJMU2pvi4Wea1yg/mk81ld9CTGMiTRBtoLyyQcr5NOnREI9VVR0Oh6Lm1lZoNZQvhS4GL5V1FAKG7iATQPnhvBE/SI3biczkc8Q6TymrCoWLIGxmivSa@w6L2PjLfCkI8fRi399TPol4wqcB508BNqeZoj@mHzvbHBGTr57HeWjtjLjdcJPvrn75Px779khQwhdhtSNuuNv)
I hope it's ok to receive a char array as an input and not a string.
**Ungolfed**:
```
string result = "", casesCharReplacement = result, currentChar = result, cases = "a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";
int i = 0, n = pas.Length, casesIndex, charAmounts = 1;
// For every char in the pass.
for (; i < n; i++)
{
currentChar = pas[i] + "";
// if the next char is equal to the current and its not the end of the string then add a +1 to the repeated letter.
if (currentChar == (pas[(i == n - 1 ? i : i + 1)] + "") && i != n - 1)
charAmounts++;
else
{
// Finished reading repeated chars (N+Char).
casesIndex = cases.IndexOf(currentChar);
// Look for the replacement character: only if the index is an even position, otherwise I could mess up with letters like 'i'.
if (casesIndex >= 0 && casesIndex % 2 < 1)
{
casesCharReplacement = cases[casesIndex + 1]+"";
// Add the **** +u
currentChar = casesCharReplacement == "u"?"uu": casesCharReplacement;
// Remove the 2 replacement characters (ex: a@) as I won't need them anymore.
cases = cases.Remove(casesIndex, 2);
}
// if the amount of letters founded is =1 then only the letter, otherwise number and the letter already replaced with the cases.
result += charAmounts > 1 ? charAmounts + ""+currentChar : currentChar;
charAmounts = 1;
}
}
return result;
```
[Answer]
## C++, ~~571~~ ~~495~~ ~~478~~ 444 bytes
-127 bytes thanks to Zacharý
```
#include<string>
#define F r.find(
#define U(S,n)p=F s(S)+b[i]);if(p-size_t(-1)){b.replace(i,1,r.substr(p+n+1,F'/',n+p)-p-2));r.replace(p+1,F'/',p+1)-p,"");}
#define V(A)i<A.size();++i,c
using s=std::string;s m(s a){s b,r="/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/";int c=1,i=0;for(;V(a)=1){for(;a[i]==a[i+1]&&1+V(a)++);b+=(c-1?std::to_string(c):"")+a[i];}for(i=0;V(b)){auto U("/",1)else{U("//",2)}}return b;}
```
the `"/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/"` string is used to transform from one character to others. 1 `/` means that the first "next char" should be replaced by what follow the next `/`, 2 means that the second "next char" should be replaced by what follows.
[Try it online](https://tio.run/##VVLLbtswEDxbX8HQbUxCsmnaTVBbkpMcmh8ImksbBJREu0QpUeWjbm3o29OVEhspARG7Ozuzy4HKtp3uyvJlrJpSh0qiTBnnrRT15lzLoKCa3SYaV3KrGonukZ1BUJFz5St5SBra5vfIkQcaF9/UE03VlrRTpw7y2ZMpp/RYzKxstSglUQlP7MyFAqRJGzcxT@4nbJI0cUun7XRBaWrPze0JhQDQBGOadufRj@SOquxu1g8iNI1jlZRRcLAwcrnz1Xr9un7qUE0cEvToUJHYHDNxy4rPrCSsumZyybZjtluxH2OmOGPqgv3MmIZIK2bm7NeKuSvG3AfmY/Z7w/YhMLZfBPbnI/t7w3CqGo/KnCcqn6dbY0n6SATNOT0OiQBD8hzumD9dXvK4B@OYpkWck3LKb4Y9vXl@XZWUdA2PjHtW2vUCveojKcBDEbwBuzHDCadSO3nsE8gWtOus9ME2qEi7lyjqN6qFaghFx2g0TFCN8kpocMo@a@V8NlRboWz2zqnkXbzZII3yXmB0xKWp5M7oLU4wmV8vV4aPcZcMUGvNzoq6BgqgrZ2v7O2i5pCdGsLhoKXrwbA48OXVGRDO7Y2tBuh2cRXC3F5/OKF7OAB8CuFU0Vqbtw@AJZ8vlVlq3EWjLo1GYBYipWmcR71Tl0igNdKDA6PBOg@vqYmA/9c6T4ExUltEPLrIkZg5CdSKQvHVr9IEj7IM4S/WgnAlvSy9rFA/ZY1wz/6v7012oMAc3AdDNvneTKC7i7qXfw)
[Answer]
# [R](https://www.r-project.org/), ~~224~~ 219 bytes
```
function(s,K=function(x)el(strsplit(x,"")),u=rle(K(s)))
Reduce(function(x,y)sub(K('abcdefghiiklloqsstvvwwxy')[y],c(K('@8(63#9#1!<1i095$+><'),'uu','2u',K('%?'))[y],x),1:24,paste0(gsub("1","",paste(u$l)),u$v,collapse=""))
```
[Try it online!](https://tio.run/##RU5NT8MwDL3vV0A3lFgEaR0fYqgF7rtxRTukadpFuE2Jm37sz5cEEFiy/Wy/Jz@3oCmcdDNvdH@yJcGqushulsq3qje25SQO@d8wgUZOvaMOTc8nkSQAwucONT9wAoDVmy690vxfIWYgX4Qzk4UqdVWfjPlAtJ9E/TCM4zQzeJ@PQkXK6yN/uF3v1@lllprt/n5z/ZwxEMx7JtgulMC5emHwrZhApE@7O9FJ6vWW1/FNkibB1M@K@w1Ge5tBKIsoO9J5NLyQ7DqcueKJsqWuLVZB1DlbO9k0pq3j5M9n1BSRJBqtKyMeQ4SGwf5vJiAqWL4A "R – Try It Online")
Nasty, but the main part is the iterative substitution in the `Reduce`. `sub` changes only the first occurrence of the match.
*Thanks to JayCe for pointing out a nice golf!*
[Answer]
## [Perl 5](https://www.perl.org/), 123 bytes
**122 bytes code + 1 for `-p`.**
Developed independently from @[Xcali](https://codegolf.stackexchange.com/users/72767/xcali)'s [answer](https://codegolf.stackexchange.com/a/145781/9365), but using a very similar process.
```
s/(.)\1+/$&=~y!!!c.$1/ge;eval"s/$1/$2/"while'a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5t+v>v<x%y?'=~/(.)(.)/g;s/s/\$/;s/w/uu/;s;w;2u
```
[Try it online!](https://tio.run/##FYxLDoIwFAD33IKPgiHyBIORAOpB2CCU0lho5fERFhzdiskkk9mMJB0PlUJwvEPmu2Dt03XWdb3wLB8oicmYcwNhCysAY6oZJ3b@eF4Lp7yQc2XSqDaZz/RXwn3OxOkdYdi7421MPrv5bqfrf7wBNEZAyCzYPMEwbI6nOBiUKkRJqOCVJjtBu7xpWEs1OSwLJ6jJHHESXYlfIXsmWlRH@QM "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~220~~ ~~216~~ ~~194~~ ~~190~~ 188 bytes
```
import re
S=re.sub(r'(.)\1+',lambda m:`len(m.group(0))`+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',list('@8(63#9#1!<1i095$+><%?')+['uu','2u']):S=S.replace(a,b,1)
print S
```
[Try it online!](https://tio.run/##NczBTgIxEIDh@z5FDZCZyTYbitEIAfQd9qgmdKHAxG5buy0FX37loIf/8F@@cEtn7xbjyH3wMYloqnYTTTPkDiNgQx@qBml13x206Fc7axz2zSn6HHBOtKv/R5FkF3JCouroo9CyE@zEDwcE3e0P5ng6M39Z67@HIV0u11spd5iHhPD2gs@Pk@VEPawVz5dP03q7nr0C1e@QM0hYZPikVbtpm2iC1XuDd10qqkJkl0Q7jlBK8X/BLw "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), 187 bytes
```
import re
S=re.sub(r'(.)\1+',lambda m:str(len(m.group(0)))+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',[*'@8(63#9#1!<1i095$+><%?','uu','2u']):S=S.replace(a,b,1)
print(S)
```
[Try it online!](https://tio.run/##NYxLbsIwFADXzSlcQeX3iBXholaA@N0hy9KFAwasOrZ5sTFw@cCiLGak2Uy4xZN3k743bfAUGemiXpKuutQAcahwK0surGqbvWLtvIsEVjtoqyP5FGCMiOUrJArjQoqAWBw8MSUaZhy7mwBcNbu9PhxPxvxZ689dFy@X6y1nLn5GfDOF78lgNpDvC2nGs69huVp8rLngKT31mfgvzutlXZEOVu00PMdCYhHIuAg19n3O2f/z9gA "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~103~~ 102 bytes
```
aR:`(.)\1+`#_.B
Fm"abcdefghiiklloqsstvvwwxy"Z"@8(63#9#1!<1i095$+><WU%?"I#Ya@?@maRA:ym@1aR'W"uu"R'U"2u"
```
[Try it online!](https://tio.run/##K8gs@P8/McgqQUNPM8ZQO0E5Xs@Jyy1XKTEpOSU1LT0jMzM7Jye/sLi4pKysvLyiUilKycFCw8xY2VLZUNHGMNPA0lRF284mPFTVXslTOTLRwd4hNzHI0aoy18EwMUg9XKm0VClIPVTJqFTp////BYnFxeX5RSlAIi8ltSitNAcA "Pip – Try It Online")
### Explanation
The code does three steps of transformation:
```
aR:`(.)\1+`#_.B Process runs of identical letters
a 1st cmdline argument
R: Do this replacement and assign back to a:
`(.)\1+` This regex (matches 2 or more of same character in a row)
#_.B Replace with callback function: concatenate (length of full match) and
(first capture group)
Note: #_.B is a shortcut form for {#a.b}
Fm"..."Z"..."I#Ya@?@maRA:ym@1 Do the bulk of rules 2-25
"..." String of letters to replace
Z"..." Zip with string of characters to replace with
Fm For each m in the zipped list:
@m First item of m is letter to replace
a@? Find its index in a, or nil if it isn't in a
Y Yank that into y
I# If len of that is truthy:*
aRA: Replace character in a at...
y index y...
m@1 with second item of m
aR'W"uu"R'U"2u" Clean up substitution
In the previous step, the replacements each had to be a single character.
This doesn't work for uu and 2u, so we use W and U instead (safe, since
uppercase letters won't be in the input) and replace them here with the
correct substitutions.
aR'W"uu" In a, replace W with uu
R'U"2u" and U with 2u
and print the result (implicit)
```
\* We need to test whether `a@?m@0` is nil. It's not enough to test that it's truthy, since 0 is a legitimate index that is falsey. Pip doesn't have a short builtin way to test if a value is nil, but testing its length works well enough in this case: any number will have length at least 1 (truthy), and nil has length of nil (falsey).
] |
[Question]
[
I am 2/3 twins with my brother, i.e. born on the same day of the same month but twelve years later. When I was 5, he was 17, both primes; the last pair of ages we can reasonably count on is [71, 83] with both of us being alive and able to celebrate this coincidental jubilee.
## Task
Create a code that
* takes two integers as input: the difference between the counter and the "twin" as a positive integer **k** (well yes, I'm the younger) and the upper bound as a positive integer **u** (runtime consideration)
* and gives output as an array or list of all **i** numbers lower than or equal *u* for which both *i* and *i+k* are primes. The output does not need to be sorted.
## Test Cases
```
12, 1000 -> [5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
2, 999 -> [3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
3, 1500 -> [2]
30, 1500 -> [7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]
```
## Edit
Since I failed to specify the upper bound, both inclusive and exclusive solutions are welcome.
## Edit No. 2
The challenge ends on 1st September, one week from the start.
Looks like we have a winner but in case of a tie popularity is the tie-breaker; in this case the "second" will be compensated via bounty.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), ~~27~~ 23 bytes
```
:1f
hS,?tye.:S+:.L*$pL,
```
[Try it online!](http://brachylog.tryitonline.net/#code=OjFmCmhTLD90eWUuOlMrOi5MKiRwTCw&input=WzMwOjE1MDBd&args=Wg)
[Verify all testcases.](http://brachylog.tryitonline.net/#code=OjFhCjoyZgpoUyw_dHllLjpTKzouTCokcEws&input=W1sxMjoxMDAwXTpbMjo5OTldOlszOjE1MDBdOlszMDoxNTAwXV0&args=Wg)
### Predicate 0 (main predicate)
```
:1f Find all solutions of predicate 1
given Input as Input,
Unify Output with the set of all solutions.
```
### Predicate 1 (auxiliary predicate)
```
hS,?tye.:S+:.L*$pL,
hS the first element of Input is S,
?tye. Output is an element between 0 and
the last element of Input,
.:S+:.L The list [Output+S,Output] is L,
L*$pL The product of L, prime-factorized, is still L
```
[Answer]
# Jelly, ~~8~~ 7 bytes
```
+ÆR©_f®
```
[Try it online!](http://jelly.tryitonline.net/#code=K8OGUsKpX2bCrg&input=&args=MTAwMA+MTI)
### Explanation
```
+ add the upper bound and the difference
ÆR find all primes up to that number
© save that in the register
_ subtract the difference from each
f® remove anything not in the original prime list
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes
Code:
```
LDpÏDI+pÏ
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TERww49ESStww48&input=MTAwMAoxMg).
[Answer]
## Pyke, 10 bytes
```
S#_PiQ+_P&
```
[Try it here!](http://pyke.catbus.co.uk/?code=S%23_PiQ%2B_P%26&input=12%0A1000)
```
S# - filter(range(input_2), V) as i
_P - is_prime(i)
& - ^ & V
iQ+ - i + input_1
_P - is_prime(^)
```
Also 10 bytes:
```
S#_DP.IQ-P
```
[Try it here!](http://pyke.catbus.co.uk/?code=S%23_DP.IQ-P&input=12%0A1000)
[Answer]
# Octave, ~~34~~ 33 bytes
```
@(k,u)(a=primes(u))(isprime(a+k))
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 8 bytes
*Credit to @alephalpha for [his approach](https://codegolf.stackexchange.com/a/91044/36398), which helped me save 3 bytes*
```
Zqti+Zp)
```
[Try it online!](http://matl.tryitonline.net/#code=WnF0aStacCk&input=MTAwMAoxMg)
```
Zq % Take input implicitly. Vector of primes up to that. Call this vector A
ti+ % Duplicate, take second input, add element-wise. Call this vector B
Zp % Vector containing true for prime numbers in B
) % Use as an index into A. Display implicitly
```
[Answer]
# Python 3, ~~114~~ ~~92~~ 90 bytes
*Thanks to @Dennis for -2 bytes*
```
def f(k,u):
i=P=1;l={0}
while i<u+k:l|={P%i*i};P*=i*i;i+=1
return{i-k for i in l}&l-{0}
```
A function that takes input via argument and returns an unsorted set. This is exclusive with respect to the upper bound.
This uses the method in @xnor's answer [here](https://codegolf.stackexchange.com/a/27022/55526) to find primes.
[Try it on Ideone](http://ideone.com/38wRpt)
**How it works**
*Prime finding*
We first initialise a test value `i` and a product `P` as `1`, and a list of primes `l` as the set containing `0`. Then, a `while` loop that tests all values of `i` in the range `[1, u+k-1]` for primality is executed. The idea is that by multiplying `P` by `i^2` at the end of each iteration, `P` takes the value `(i-1)!^2` while testing `i`, i.e the product of the integers `[1, i+1]` squared. The actual primality test is then performed by calculating `P mod i`; if this returns zero, then `i` cannot be prime since this implies that `i` is divisible by at least one of the values that make up the product. If this returns `1`, then `i` must be prime since it is not divisible by any of the values in the product. If `i` is prime, it is appended to `l`, and if not, `0` is appended. The squaring of the product prevents false identification of `4` as prime, and is useful here since it guarantees that only `0` or `1` will be returned, allowing the choice of the value to be appended to be made by simply multiplying the result by `i`.
*Identification of 'twin' primes*
We now create a furter set, containing all the elements of `l-k`, element-wise. The intersection of this set and `l` is then found using `&`, which leaves a set containing only the elements common to both sets. A number `i` is only in both sets if both `i` and `i+k` are prime, meaning that this leaves the desired output. However, if `k` is prime, `0` will be present in both sets, meaning that this must be removed before returning.
[Answer]
# R, 98 bytes
```
function(k,u){v=c();for(i in 1:u)if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2){v=c(v,i)};v}
```
**Ungolfed :**
```
function(k,u)
v=c() #Empty vector
for(i in 1:u)
if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2) #If both i and i+k only have
#2 divisors such as the rest of the
#euclidian division is 0
#(i.e., they're both prime) :
v=c(v,i)
v
```
[Answer]
## CJam, 17 bytes
Either as a full program:
```
q~{_mp\W$+mp&},p;
```
[Try it online!](http://cjam.tryitonline.net/#code=cX57X21wXFckK21wJn0scDs&input=MTIgMTAwMA)
Or as an unnamed block:
```
{:X;{_mp\X+mp&},}
```
[Try it online!](http://cjam.tryitonline.net/#code=MTAwMCAxMgoKezpYO3tfbXBcWCttcCZ9LH0KCn5w&input=)
[Answer]
# Java 7, ~~185~~ 175 bytes
```
import java.util.*;List c(int k,int u){List l=new ArrayList();for(int i=1;++i<u;)if(p(i)&p(i+k))l.add(i);return l;}boolean p(int n){for(int i=2;i<n;)n=n%i++<1?0:n;return n>1;}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/EP6SAU)
```
import java.util.*;
class M{
static List c(int k, int u){
List l = new ArrayList();
for(int i = 1; ++i < u; ){
if(p(i) & p(i+k)){
l.add(i);
}
}
return l;
}
static boolean p(int n){
for(int i = 2; i < n; ){
n = n % i++ < 1
? 0
: n;
}
return n>1;
}
public static void main(String[] a){
System.out.println(c(12, 1000));
System.out.println(c(2, 999));
System.out.println(c(3, 1500));
System.out.println(c(30, 1500));
}
}
```
**Output:**
```
[5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
[3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
[2]
[7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]
```
[Answer]
# PARI/GP, 39 bytes
```
k->u->[x|x<-primes([1,u]),isprime(x+k)]
```
[Answer]
# Mathematica, 43 bytes
```
(Prime@Range@PrimePi@#2+#)~Select~PrimeQ-#&
```
Generate all primes less than or equal to the upper bound. Add the difference of ages to the result. Select prime numbers among them. Subtract the difference of ages to the result.
[Answer]
# Swift, 142 bytes
```
func f(a:Int,b:Int)->Array<Int>{let p={(n:Int)->Int in([Int]()+(2..<n)).filter{n%$0<1}.count}
return([Int]()+(2...b)).filter{p($0)+p($0+a)<1}}
```
[Answer]
# [Perl 6](http://perl6.org), ~~39~~ 37 bytes
```
->\k,\u{grep {($_&$_+k).is-prime},2..u}
```
```
->\k,\u{grep {($_&$_+k).is-prime},^u}
```
## Explanation:
```
-> \k, \u {
# find all the values
grep
# where
{
# 「all」 junction of the two values
( $_ & $_ + k ) # 「 all( $_, $_ + k ) 」
# autothread a method call against the junction
.is-prime
},
# from the values up to (and excluding) 「u」
^ u # short for 「 0 ..^ u 」
# for inclusive use 「 2 .. u 」
}
```
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 205 bytes
```
GOTO b
funce
n = p
p - 1
f = 1
lbla
f * p
f % n
p - 1
if p a
return
lblb
readIO
s = i
readIO
i - 2
lblc
i + 1
p = i
GOSUB e
F = f
p = i
p + s
GOSUB e
F * f
if F g
GOTO h
lblg
printInt i
lblh
i - 2
if i c
```
[Try it online!](http://silos.tryitonline.net/#code=R09UTyBiCmZ1bmNlCm4gPSBwCnAgLSAxCmYgPSAxCmxibGEKZiAqIHAKZiAlIG4KcCAtIDEKaWYgcCBhCnJldHVybgpsYmxiCnJlYWRJTyAKcyA9IGkKcmVhZElPIAppIC0gMgpsYmxjCmkgKyAxCnAgPSBpCkdPU1VCIGUKRiA9IGYKcCA9IGkKcCArIHMKR09TVUIgZQpGICogZgppZiBGIGcKR09UTyBoCmxibGcKcHJpbnRJbnQgaQpsYmxoCmkgLSAyCmlmIGkgYw&input=&args=MzA+MTUwMA&debug=on)
Primalty test by [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem).
[Answer]
# [Actually](https://github.com/Mego/Seriously), 12 bytes
Input is `u` then `k`. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWWUmA7cEDilZwrcCpg4paR&input=MTAwMAoy)
```
╖R`;p@╜+p*`░
```
**Ungolfing:**
```
╖ Store k in register 0.
R Range [1..u]
` `░ Start a function f and push values i of the range where f(i) is truthy.
;p@ Duplicate i, check if i is prime, and swap with the other i.
╜+p Push k, add to i, check if i+k is prime.
* Multiply the two if results together.
Similar to logical AND. 1 if both are true, else 0.
```
[Answer]
# R, 104 bytes
Unlike the other R solution posted, this one takes input from stdin.
```
s=scan();sapply(1:s[2],function(i){j=i+s[1];if((all(i%%(3:i-1)!=0)|i==2)&all(j%%(3:j-1)!=0))cat(i," ")})
```
Ungolfed:
```
s=scan(); # Read from stdin
sapply(1:s[2], # For i from 1 to u,
function(i){ # apply this function:
j=i+s[1]; # Define i+k
if((all(i%%(3:i-1)!=0) # Test if i is prime
| i==2) # (i is prime if i==2)
& all(j%%(3:j-1)!=0)) # Test if i+k is prime
cat(i," ") # If i and i+k are prime, print i
}
)
```
[Answer]
## Javascript (ES6), ~~90~~ ~~83~~ ~~80~~ 75 bytes
```
(k,u)=>(r=n=>n++<u+k?r(P[P.every(i=>n%i)*n]=n):P.filter(n=>P[n+k]))(1,P=[])
```
Example:
```
let F =
(k,u)=>(r=n=>n++<u+k?r(P[P.every(i=>n%i)*n]=n):P.filter(n=>P[n+k]))(1,P=[])
console.log(F(2, 999))
```
[Answer]
# Pyth, 13 bytes
```
f&P_TP_+ThQSe
```
A program that takes input of a list of the form `[k, u]` and prints a list.
[Try it online](https://pyth.herokuapp.com/?code=f%26P_TP_%2BThQSe&test_suite=1&test_suite_input=%5B12%2C1000%5D%0A%5B2%2C999%5D%0A%5B3%2C1500%5D%0A%5B30%2C1500%5D&debug=0)
**How it works**
```
f&P_TP_+ThQSe Program. Input: Q
Se 1-indexed range up to Q[1], yielding [1, 2, 3, ..., u]
f Filter that, using variable T, by:
P_T T is prime
& and
P_+ThQ T+Q[0], i.e. T+k, is prime
Implicitly print
```
] |
[Question]
[
Your program/function should
* output exactly one integer
* output **any** integer with positive probability
* output an integer greater than 1.000.000 or less than -1.000.000 with at least with 50% probability.
Example outputs (all must be possible):
```
59875669123
12
-42
-4640055890
0
2014
12
24
-7190464664658648640055894646646586486400558904644646646586486400558904646649001
```
Clarifications:
* A trailing line break is permitted.
* Leading zeros aren't allowed.
* `-0` is permitted.
Shortest code wins.
[Answer]
# CJam, ~~16~~ ~~14~~ 13 bytes
```
0{Kmr(+esmr}g
```
This will run for a *very* long time, because it uses the current timestamp (on the order of 1012) to determine if the loop should terminate. I'm using this as the submission, as it is the shortest, but there are two 14-byte alternatives, which have their own merits:
```
0{esmr(+esmr}g
```
This one is *not* limited by the period of the PRNG, since the range of *all* random numbers depends on the current timestamp. Therefore, this should be able to produce any number whatsoever, although the probability for negative, or even small positive numbers vanishingly small.
Below is an equivalent version that uses `3e5` instead of the timestamp. And `20` for the first range (as the 13-byte submission). It's much faster and also complies with all the rules. It is sort of the limiting case to get the 50% probability for numbers beyond 1,000,000 while keeping a reasonable runtime and small code-size. The explanation and mathematical justification refer to this version:
```
0{Kmr(+3e5mr}g
```
This usually takes a few seconds to run. You can replace the `5` with a `2` to make it run even faster. But then the requirement on the 50% probability will only be met for 1,000 instead of 1,000,000.
I'm starting at 0. Then I've got a loop, which I break out of with probability 1/(3\*105). Within that loop I add a random integer between -1 and 18 (inclusive) to my running total. There is a finite (albeit small) probability that each integer will be output, with positive integers being much more likely than negative ones (I don't think you'll see a negative one in your lifetime). Breaking out with such a small probability, and incrementing most of the time (and adding much more than subtracting) ensures that we'll usually go beyond 1,000,000.
```
0 "Push a 0.";
{ }g "Do while...";
Kmr "Get a random integer in 0..19.";
( "Decrement to give -1..18.";
+ "Add.";
3e5mr "Get a random integer in 0..299,999. Aborts if this is 0.";
```
Some mathematical justification:
* In each step we add 8.5 on average.
* To get to 1,000,000 we need 117,647 of these steps.
* The probability that we'll do *less* than this number of steps is
```
sum(n=0..117,646) (299,999/300,000)^n * 1/300,000
```
which evaluates to `0.324402`. Hence, in about two thirds of the cases, we'll take more 117,647 steps, and easily each 1,000,000.
* (Note that this is not the exact probability, because there will be some fluctuation about those average 8.5, but to get to 50%, we need to go well beyond 117,646 to about 210,000 steps.)
* If in doubt, we can easily blow up the denominator of the termination probability, up to `9e9` without adding any bytes (but years of runtime).
# ...or 11 bytes?
Finally, there's an 11 byte version, which is also not limited by the period of the PRNG, but which will run out of memory pretty much every time. It only generates one random number (based on the timestamp) each iteration, and uses it both for incrementing and terminating. The results from each iteration remain on the stack and are only summed up at the end. Thanks to Dennis for this idea:
```
{esmr(}h]:+
```
[Answer]
# Java, ~~133~~ 149
```
void f(){String s=x(2)<1?"-":"";for(s+=x(9)+1;x(50)>0;s+=x(10));System.out.print(x(9)<1?0:s);}int x(int i){return new java.util.Random().nextInt(i);}
```
## Example outputs
```
-8288612864831065123773
0
660850844164689214
-92190983694570102879284616600593698307556468079819964903404819
3264
```
## Ungolfed
```
void f() {
String s = x(2)<1 ? "-" : ""; // start with optional negative sign
s+=x(9)+1; // add a random non-zero digit
for(; x(50)>0; ) // with a 98% probability...
s+=x(10) // append a random digit
System.out.print(x(9)<1 ? 0 : s); // 10% chance of printing 0 instead
}
int x(int i) {
return new java.util.Random().nextInt(i);
}
```
## Old answer (before rule change)
```
void f(){if(Math.random()<.5)System.out.print('-');do System.out.print(new java.util.Random().nextInt(10));while(Math.random()>.02);}
```
[Answer]
# Mathematica - 47
```
Round@RandomVariate@NormalDistribution[0,15*^5]
```
Basically just generate random number using normal distribution with variance equal to 1500000. This will produce an integer between -10^6 and 10^6 with probability 49.5015%.
[Answer]
# Python 2, ~~75~~ 69 bytes
```
from random import*;s=0;j=randrange
while j(12):s=s*9+j(-8,9)
print s
```
It is trivial to check that the while loop in the middle can generate all integers (albeit biased towards zero). "12" is chosen such that there are roughly half of numbers exceeding ±106.
---
Older solution:
# ~~Python 2, 44 bytes~~
~~Based on the [Mathematica solution](https://codegolf.stackexchange.com/a/42807/32353).~~
```
from random import*;print int(gauss(0,8**7))
```
**Doesn't really work because Python's `float` has only finite precision.**
[Answer]
# Ruby, 70
```
f=->{m=10**6
r=rand -m..m
r<1?(r>-5e5??-:'')+r.to_s+f[][/\d+/]:r.to_s}
```
To make generating very large numbers possible, I'm returning the number as a `String` from a lambda. If that's not allowed, count 8 characters extra (for `puts f[]`) to make it a program instead of a function.
### Explanation
Generate a number between `-1,000,000` and `1,000,000`. If the number is `1` or higher, the number is returned as a `String`.
If the number is lower than `1`, the function is called recursively to return number outside the number range. To make sure negative numbers can also be generated, a `-` is prefixed to the resulting `String` if the initial number is greater than `-500,000`.
I hope I understood the challenge correctly!
[Answer]
## R, 38
```
library(Rmpfr)
round(rnorm(1,2e6,1e6))
```
Draws from the Gaussian distribution with mean 2,000,000, chosen randomly, and standard deviation 1,000,000, so that about 2/3 of the draws will lie within 1,000,000 and 3,000,000. The distribution is unbounded so in theory this can generate any integer. The Rmpfr package replaces R's built in double floats with arbitrary precision.
[Answer]
# Perl, 53 characters
```
print"-"if rand>.5;do{print int rand 10}while rand>.1
```
I certainly don't see any reason to *work* with integers when printing one :)
Has equal probability of printing a number with or without a leading "-".
Prints a 1-digit number 10% of the time, a 2-digit number 9% of the time, a 3-digit number 8.1% of the time, a 4-digit number 7.29% of the time, a 5-digit number 6.56% of the time, a 6-digit number 5.9% of the time, etc. Any length is possible, with decreasing probability. The one-through-five digit numbers account for about 41.5% of output cases, and the number 1,000,000 (or -1,000,000) only 6-millionths of a percent, so the output number will be outside of the range -1,000,000 through 1,000,000 about 54.6% of the time.
Both "0" and "-0" are possible outputs, which I hope is not a problem.
[Answer]
# Perl, 114 Chars
```
use Math::BigInt;sub r{$x=Math::BigInt->new(0);while(rand(99)!=0){$x->badd(rand(2**99)-2**98);}print($x->bstr());}
```
## Breakdown:
```
use Math::BigInt; -- include BigIntegers
sub r{ -- Define subroutine "r"
$x=Math::BigInt->new(0); -- Create BigInteger $x with initial value "0"
while(rand(99)!=0){ -- Loop around until rand(99) equals "0" (may be a long time)
$x->badd( -- Add a value to that BigInt
rand(2**99)-2**98); -- Generate a random number between -2^98 and +2^98-1
}print($x->bstr());} -- print the value of the BigInt
```
The probability of getting a value between -1.000.000 and 1.000.000 are tending towards zero *BUT* it is possible.
>
> Note: This subroutine may run for a long time and error out with an "Out of Memory!" error but it's technically generating *any* integer as stated in the question.
>
>
>
# Perl, 25
```
sub r{rand(2**99)-2**98;}
```
Generates a random integer within the range of +/-2^99.
## Breakdown
```
sub r{ -- Define subroutine "r"
rand(2**99) -- Generate a random integer between 0 and 2^99
-2**98;} -- Subtract 2^98 to get negative values as well
```
Tested with 1 million samples:
```
~5 are inside the range of +/-1.000.000
~999.995 are outside that range
= a probability of ~99,99% of generating an integer outside that range.
Compare that number to the probability of 2.000.000 in 2^99: It is approx. the same.
```
This meets all rules:
* 1 integer
* any integer is possible
* at least 50% (in my case 99,99%) of all generated integers are outside the range of +/-1.000.000.
>
> This works because the underlying random number generator defines equal probability to every bit that is generated, thus doing that on generated integers as well.
> Every integer has a probability of 1/2^99 to be generated.
>
>
>
## Edit:
I had to increase the exponent so that larger integers are being generated. I have chosen 99 because it keeps the code as short as possible.
[Answer]
# C#, ~~126~~ 107 bytes
```
string F(){var a=new System.Random();var b=a.Next(-1E6,1E6+1)+"";while(a.Next(1)>0)b+=a.Next(10);return b;}
```
Ungolfed:
```
string F()
{
System.Random rand = new System.Random();
string rtn = rand.Next(-1E6, 1E6 + 1) + "";
while (rand.Next(1) > 0)
rtn += a.Next(10);
return rtn;
}
```
Chance to generate a number of *n* digits is 1/2^(n-10), which is greater than 0 for all positive n, and 1/2 for n=11. ~~Also creates leading zeros, which do not seem to be disallowed in the original question or any of its comments.~~
[Answer]
# Perl, 62 bytes
`print $n=int rand(20)-10;while($n&&rand>.1){print int rand 10}`
I had the same idea as @Hobbs, of generating a digit at a time, but his code didn't satisfy the added no-leading-zeros requirement. Generating the first digit instead of just the sign solved that. And unless there's a shorter way to exit if we printed a zero, or a shorter way to generate the leading -9 to 9, this should do it for size.
In a shell loop: `while perl -e '...'; do echo;done |less`
I think this is one of the shortest that doesn't require infinite RAM to satisfy the problem. As a bonus, the output is isn't strongly biased towards anything, and runtime is very fast.
I tried using bitwise and to save a character in the while condition, but I think this ends up being true more often, so the loop ends sooner. Would need more chars to adjust other things to counter that, to maintain the probability of generating abs(output) > 1M.
[Answer]
# Bash, 42 bytes
`printf "%d\n" 0x$(xxd -p -l5 /dev/random)`
/dev/random on OSX is just random bytes, and `xxd -p -l5` converts 5 of the ascii characters to hex, and `printf` turns it into decimal format.
[Answer]
# Javascript (73)
This solution uses that you can construct a number with base *n* by multiplying the previous number with *n* and adding a digit in base *n*. We have an additional `..?..:..` in there to be able to create all negative integers. The following code should be tested in a browser console.
```
b=Math.round;c=Math.random;x=0;while(b(c()*99)){x*=b(c())?2:-2;x+=b(c())}
```
The probability to get an integer >= `2^1` (or <= `-(2^1)`) is equal to the chance that the loop is ran 2 times. The chance of that happening is `(98/99)^2`. The chance of getting a number that is greater than `2^20` (or <= `-(2^20)`) is therefore `(98/99)^21 = 0.808` or 81%. This is all in theory though, and assuming that Math.random is truely random. It obviously isn't.
---
Snippet testing this code. Also in a more readable fashion.
```
var interval = 0;
var epic_unicorns = 0;
var unicorns = 0;
function gimmerandom() {
var b = Math.round;
var c = Math.random;
var x = 0;
while( b(c()*99) ) {
x *= b(c()) ? 2 : -2;
x += b(c());
}
return x;
}
function randomcount() {
var a = gimmerandom();
if( a <= -1000000 || a >= 1000000 ) {
epic_unicorns++;
}
unicorns++;
updatedisplay();
}
function updatedisplay() {
$('#num_of_epicunicorns').text( epic_unicorns );
$('#num_of_unicorns').text( unicorns );
var perc = unicorns > 0 ? Math.round( (epic_unicorns / unicorns) * 1000 ) / 10 : 0;
$('#perc_of_unicorns').text( perc );
}
$('#a').on( 'click', function() {
clearInterval( interval );
interval = setInterval( randomcount, 10 );
} );
$('#b').on( 'click', function() {
clearInterval( interval );
} );
$('#c').on( 'click', function() {
epic_unicorns = 0;
unicorns = 0;
updatedisplay();
} );
updatedisplay();
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="num_of_epicunicorns"></span> / <span id="num_of_unicorns"></span> (<span id="perc_of_unicorns"></span>%) were larger than 1.000.000 or less than 1.000.000.
<br><br>
<input type="button" id="a" value="Start">
<input type="button" id="b" value="Stop">
<input type="button" id="c" value="Reset">
```
[Answer]
# GolfScript, 20 bytes
```
0{)8.?rand}do.2&(*4/
```
Yeah, this one is also kind of slow.
Compared to languages like CJam and Pyth, GolfScript suffers from a verbose random number generation keyword (`rand`). To overcome this handicap, I needed to find a way to use it only once.
This code works by repeatedly picking a random number between 0 and 88−1 = 16,777,215 inclusive, and incrementing a counter until the random number happens to be 0. The resulting counter value has a [geometric distribution](//en.wikipedia.org/wiki/Geometric_distribution) with a [median](//en.wikipedia.org/wiki/Median) approximately -1 / log2(1 − 1/88) ≈ 11,629,080, so it meets the "over 1,000,000 at least 50% of the time" test.
Alas, the random number thus generated is always strictly positive. Thus, the extra `.2&(*4/` part is needed to let it become negative or zero. It works by extracting the second-lowest bit of the number (which is thus either 0 or 2), decrementing it to make it -1 or 1, multiplying it with the original number, and dividing the result by 4 (to get rid of the lowest two bits, which are now correlated with the sign, and also to allow the result to become zero). Even after the division by 4, the absolute value of the random number still has a median of -1 / log2(1 − 1/88) / 4 ≈ 2,907,270, so it still passes the 50% test.
[Answer]
# JavaScript, 81 bytes
This code fulfills all the rules:
* Output any integer with positive probability
* Output integers outside the range of +/-1000000 with at least 50% probability
* No leading `0` in the output
As a bonus, the algorithm runs with a time complexity of **O(log10n)** so it returns the integer almost instantly.
```
for(s="",r=Math.random;r()>.1;s+=10*r()|0);r(s=s.replace(/^0*/,"")||0)<.5?"-"+s:s
```
This assumes an REPL environment. Try running the above code in your browser's console, or use the stack snippet below:
```
D.onclick = function() {
for(s="", r=Math.random;r()>.1; s+=10*r()|0);
P.innerHTML += (r(s=s.replace(/^0*/,"") || 0) <.5 ?"-" + s : s) + "<br>"
}
```
```
<button id=D>Generate a random number</button><pre id=P></pre>
```
**Algorithm**:
* Keep appending random digits to string `s` until a `Math.random() > 0.1`.
* Based on `Math.random() > 0.5`, make the number negative (by prepending the string `s` with `-`).
This algorithm does not have a uniform distribution across all integers. Integers with higher digit count are less probable than the lower ones. In each for loop iteration, there is a 10% chance that I will stop at the current digit. I just have to make sure that I stop after 6 digits more than 50% of the time.
This equation by @nutki explains the maximum value of stopping chance percentage based on the above condition:
```
1 - 50%^(1/6) ≈ 0.11
```
Thus 0.1 is well within range to satisfy all the three rules of the question.
[Answer]
# TI-BASIC, [14 bytes](http://tibasicdev.wikidot.com/randnorm)
```
1-2int(2rand:randNorm(AnsE6,9
```
Similar to @ssdecontrol's R answer, this draws from the Gaussian distribution with mean -1,000,000 or 1,000,000, chosen randomly, and standard deviation 9. The distribution is unbounded so in theory this can generate any integer.
**Explanation**:
```
1-2int(2rand - get a random integer 0 or 1, then multiply by 2 and subtract 1
: - this gives the number 1 or -1 (with equal probability) to Ans
randNorm(AnsE6,9 - displays Gaussian distribution with mean (Ans * 1,000,000) and std. dev. 9
```
[Answer]
# Bash, 66
```
LANG=C sed -r '/^-?(0|[1-9][0-9]*)$/q;s/.*/5000000/;q'</dev/random
```
It almost always prints 5000000. But if it found a valid number in `/dev/random`, it will print that number instead.
And this one is faster:
```
LANG=C sed -r '/^-?(0|[1-9][0-9]*)$/q;s/.*/5000000/;q'</dev/urandom
```
[Answer]
# C++, 95 bytes
```
void f(){int d=-18,s=-1;while(s<9){d=(rand()%19+d+9)%10;cout<<d;s=9-rand()%10*min(d*d+s+1,1);}}
```
## Expanded:
```
void f() {
int d=-18,s=-1;
while(s<9) {
d=(rand()%19+d+9)%10;
cout<<d;
s=9-rand()%10*min(d*d+s+1,1);
}
}
```
## Explanation:
The function keeps on printing consecutive random digits until a random valued switch takes the required value to stop the function. d is the variable that keeps the value of the next digit to be printed. s is the switch variable that takes random integer values in the interval [0, 9], if s == 9 then no more digits are printed and the funtion ends.
The variables d and s are initialized in order to give special treatment to the first digit (taking it from the interval [-9, 9] and if the first digit is zero then the function must end to avoid leading zeroes). The value of d could be assigned as d=rand()%10 but then the first digit couldn't be negative. d is assigned instead as d=(rand()%19+d+9)%10 and initialized at -18 so the first value of d will range from [-9, 9] and the next values will always range from [0, 9].
The variable s ranges randomly from [0, 9], and if s equals 9, the function ends, so after printing the first digit the next one will be printed with a probability of 90% (assuming rand() is truly random, and in order to satisfy the third condition). s could be easily assigned as s=rand()%10, however, there is an exception, if the first digit is zero, the function must end. In order to handle such exception, s has been assigned as s=9-rand()%10\*min(d\*d+s+1,1) and initialized as -1. If the first digit is zero, the min will return 0 and s will equal to 9-0=9. s variable's assignment will always range from [0, 9], so the exception can only occur at the first digit.
## Characteristics (assuming rand() is truly random)
* The integer is printed digit by digit, with a fixed probability of 90% of printing another digit after printing the last one.
* 0 is the integer with highest chance of being printed, with a probability of aproximately 5.2%.
* The probability of printing an integer on the interval [-10^6, 10^6] is aproximately 44% (the calculation is not written here).
* Positive and negative integers are printed with the same probability (~47.4%).
* Not all digits are printed with the same probability. For example: in the middle of printing the integer, if the last digit was 5, the digit 3 will have a slightly lower chance of being printed next. In general, if the last digit was d, the digit (d+18)%10 will have a slightly lower chance of being printed next.
## Example outputs (10 executions)
```
-548856139437
7358950092214
507
912709491283845942316784
-68
-6
-87614261
0
-5139524
7
Process returned 0 (0x0) execution time : 0.928 s
Press any key to continue.
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~140~~ 127 bytes
```
()->{int i;var o=System.out;for(o.print(i=(int)(19*Math.random())-10);i!=0&Math.random()<.9;)o.print((int)(11*Math.random()));}
```
`-13 bytes` by sneaking more logic into the loop header - thanks to @ceilingcat
[Try it online!](https://tio.run/##Xc6xCsIwFIXhPU8RF7lXaGhHiXHs5tRRHC5to6k0kfRakNJnj6XooNOBHz44HY2Udc09Oc9ttFS3spzEGFwjLaAWAxO7Wq6hJ@eh4uj89XwhnEQprUmA2XFatHR6pCiDqV4Dt70KT9Y2RAjqsQgGZ2AZhGK/OxHfVCTfhB4QsyJH7TYm3/70g9pr/OIPLf4o6jlpYdV6dRZzegM "Java (JDK) – Try It Online")
[Answer]
# [BSD](https://www.freebsd.org/cgi/man.cgi?query=jot&manpath=FreeBSD%2014.0-current) `jot`, 17 bytes
```
jot -r 1 -9e9 9e9
```
[Try it Online!](https://tio.run/##S0oszvj/Pyu/REG3SMFQwUDBMtUSwdUF8sAiAA) The above code works correctly on MacOS (and presumably BSD), but TIO (and ATO) do not have the same `jot` as I do. Link is to a truncated version that only generates positive integers.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
WOyG~ZtOT)Z
```
Note: this program will probably crash with a memory error on any real computer. To test it, try replacing `G` with a shorter string, such as in this code, which generates numbers averaging around 28000:
```
pyth -c 'WOy"abcdefghijklm"~ZtOUT)Z'
```
This code loops, adding a random number from -1 to 8 to `Z`, with a 2^-26 probability of exiting the loop on each repetition. The 2^-26 probability is attained by selecting a random element (`O`) of the set of all subsets (`y`) of the alphabet (`G`).
Technical details & justification:
The probability 2^-26 is derived from two facts: `y`, when called on sequences, is the power-set function, an constructs the list of all subsets of the input. Since the input, `G`, is 26 characters long, this power-set, `yG` has 2^26 entries. `OyG` selects a random element from those 2^26 entries. Exactly one of those entries, the empty string, will evaluate as falsy when passed to `W`, the while loop. Therefore, there is a 2^-26 probability of exiting the loop each time.
In any fixed number of loop cycles K, the probability of getting the number K\*3.5 + m and getting K\*3.5 - m are equal, because each sequences of addends that achieves one total can be inverted, -1 -> 8, 0 -> 7, etc., to achieve the other. Additionally, numbers closer to K\*3.5 are clearly more likely than numbers farther away. Thus, if K > 2000000/3.5 = 571428.5 the probability of getting a number over 1000000 is greater than 75%, because some of the results above that number can be put into a one-to-one correspondence with all of the results below that number, and the upper less-than-half, can be put into a one-to-one correspondence with those under 1000000. The probability of getting at least 571429 loops is (1-2^-26)^571429, which is no less than (1-2^-26 \* 571429), the expected number of times leaving the loop over the first 571429 tries, which is 99.1%. Thus, on 99.1% or more of trials, there is a 75% or more chance of getting at least 1000000, so there is more than a 50% chance of getting over 1000000.
This code relies on a behavior of `O` where a bug was accidentally introduced 3 days ago and was fixed today. It should work on any version of Pyth 3 from before Dec 22nd, or after today. The following code is equivalent, and has always worked:
```
WOyG~ZtOUT)Z
```
[Answer]
# Java, 113 bytes
```
void g(){String a=Math.random()>0?"10":"01";for(;Math.random()>0;)a+=(int)(Math.random()*2);System.out.print(a);}
```
This program prints a binary number to standard output stream. You might have to wait a while because the probability of it ending the number (or it being positive) is approximately 0. The idea that the absolute value of a number generated is less than 1 million is amusing, yet possible.
Ungolfed:
```
void g(){
String a=Math.random()>0?"10":"01"; //Make sure there are no trailing zeroes.
for(;Math.random()>0;)a+=(int)(Math.random()*2);//Add digits
System.out.print(a); //Print
}
```
Sample output: *Will post when a number is done being generated.*
] |
[Question]
[
Given a positive integer \$n\$ output the integers \$a\$ and \$b\$ (forming **reduced** fraction \$a/b\$) such that:
$$\frac a b = \prod ^n \_{k=1} \frac {p^2\_k - 1} {p^2\_k + 1}$$
Where \$p\_k\$ is the \$k\$ th prime number (with \$p\_1 = 2\$).
Examples:
```
1 -> 3, 5
2 -> 12, 25
3 -> 144, 325
4 -> 3456, 8125
5 -> 41472, 99125
15 -> 4506715396450638759507001344, 11179755611058498955501765625
420 -> [very long](https://gist.githubusercontent.com/orlp/fbe70433285ca8d4aad5/raw/1f787288da7f30cd786b123db59dc0e23d7b7ebd/gistfile1.txt)
```
Probabilistic prime checks are allowed, and it's ok if your answer fails due to limitations in your language's integer type.
---
Shortest code in bytes wins.
[Answer]
## Mathematica, 32 bytes
```
1##&@@(1-2/(Prime@Range@#^2+1))&
```
An unnamed function that takes integer input and returns the actual fraction.
This uses the fact that `(p2-1)/(p2+1) = 1-2/(p2+1)`. The code is then golfed thanks to the fact that Mathematica threads all basic arithmetic over lists. So we first create a list `{1, 2, ..., n}`, then retrieve all those primes and plug that list into the above expression. This gives us a list of all the factors. Finally, we multiply everything together by applying `Times` to the list, which can be golfed to `1##&`.
Alternatively, we can use `Array` for the same byte count:
```
1##&@@(1-2/(Prime~Array~#^2+1))&
```
[Answer]
# [M](https://github.com/DennisMitchell/m), 9 bytes
```
RÆN²‘İḤCP
```
[Try it online!](http://m.tryitonline.net/#code=UsOGTsKy4oCYxLDhuKRDUA&input=&args=MTU)
### Trivia
Meet M!
M is a fork of Jelly, aimed at mathematical challenges. The core difference between Jelly and M is that M uses infinite precision for all internal calculations, representing results symbolically. Once M is more mature, Jelly will gradually become more multi-purpose and less math-oriented.
M is very much work in progress (full of bugs, and not really *that* different from Jelly right now), but it works like a charm for this challenge and I just couldn't resist.
### How it works
```
RÆN²‘İḤCP Main link. Argument: n
R Range; yield [1, ..., n].
ÆN Compute the kth primes for each k in that range.
²‘ Square and increment each prime p.
İ Invert; turn p² + 1 into the fraction 1 / (p² + 1).
Ḥ Double; yield 2 / (p² + 1).
C Complement; yield 1 - 2 / (p² + 1).
P Product; multiply all generated differences.
```
[Answer]
## Python 2, 106 bytes
```
from fractions import*
n=input()
F=k=P=1
while n:b=P%k>0;n-=b;F*=1-Fraction(2*b,k*k+1);P*=k*k;k+=1
print F
```
The first and fourth lines hurt so much... it just turned out that using `Fraction` was better than multiplying separately and using `gcd`, even in Python 3.5+ where `gcd` resides in `math`.
Prime generation adapted from @xnor's answer [here](https://codegolf.stackexchange.com/a/27022/21487), which uses Wilson's theorem.
[Answer]
# Ruby, ~~122~~ ~~77~~ 65 bytes
Thanks to Sherlock for shaving off 10 bytes.
```
require'prime'
->n{Prime.take(n).map{|x|1-2r/(x*x+1)}.reduce(:*)}
```
Defines an anonymous function that takes a number and returns a `Rational`.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 33 bytes
```
n->prod(i=1,n,1-2/(prime(i)^2+1))
```
Alternate version (46 bytes):
```
n->t=1;forprime(p=2,prime(n),t*=1-2/(p^2+1));t
```
Non-competing version giving the floating-point (`t_REAL`) result (38 bytes):
```
n->prodeuler(p=2,prime(n),1-2/(p^2+1))
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
RÆN²µ’ż‘Pµ÷g/
```
[Try it online!](http://jelly.tryitonline.net/#code=UsOGTsKywrXigJnFvOKAmFDCtcO3Zy8&input=&args=MTU) Thanks to @Dennis for -1 byte.
```
R Range [1..n]
ÆN Nth prime
² Square
µ Start new monadic chain
’ż‘ Turn each p^2 into [p^2-1, p^2+1]
P Product
µ Start new monadic chain
÷ Divide by...
g/ Reduce GCD
```
[Answer]
# Pyth, ~~26~~ 25
```
/RiFN=N*MCm,tdhd^R2.fP_ZQ
```
[Try it here](http://pyth.herokuapp.com/?code=%2FRiFN%3DN%2aMCm%2Ctdhd%5ER2.fP_ZQ&input=420&test_suite_input=1%0A2%0A3%0A4%0A5%0A15&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=%2FRiFN%3DN%2aMCm%2Ctdhd%5ER2.fP_ZQ&input=15&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A15%0A420&debug=0).
1 byte saved thanks to Jakube!
Pretty naive implementation of the specifications. Uses the spiffy "new" (I have no idea when this was added, but I've never seen it before) `P<neg>` which returns whether the positive value of a negative number is prime or not. Some of the mapping, etc can probably be golfed...
[Answer]
# Julia, ~~59~~ 42 bytes
```
n->prod(1-big(2).//-~primes(2n^2)[1:n].^2)
```
This is an anonymous function that accepts an integer and returns a `Rational` with `BigInt` numerator and denominator.
We begin by generating the list of prime numbers less than 2*n*2 and selecting the first *n* elements. This works because the *n*th prime is always less than *n*2 for all *n* > 1. ([See here](https://math.stackexchange.com/a/1092552/151436).)
For each *p* of the *n* primes selected, we square *p* using elementwise power (`.^2`), and construct the rational 2 / (*p* + 1), where 2 is first converted to a `BigInt` to ensure sufficient precision. We subtract this from 1, take the product of the resulting array of rationals, and return the resulting rational.
Example usage:
```
julia> f = n->prod(1-big(2).//-~primes(2n^2)[1:n].^2)
(anonymous function)
julia> f(15)
4506715396450638759507001344//11179755611058498955501765625
```
Saved 17 thanks to Sp3000!
[Answer]
## Convex, 28 bytes
Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found [here](https://github.com/GamrCorps/Convex). Input is an integer into the command line arguments. Indexes are one-based. Uses the CP-1252 encoding.
```
,:)_{µ²1-}%×\{µ²1+}%×¶_:Ðf/p
```
You may or may not consider this answer to be competing since I was working on a few features that this program uses before the challenge was posted, but the commit was made once I saw this challenge go out.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 18 bytes
```
:Yq2^tqpwQpZd1Mhw/
```
[**Try it online!**](http://matl.tryitonline.net/#code=OllxMl50cXB3UXBaZDFNaHcv&input=Mw)
Fails for large inputs because only integers up to `2^52` can be accurately represented internally.
### Explanation
```
: % implicitly take input n. Generate range [1,...,n]
Yq % first n prime numbers
2^ % square
tqp % duplicate. Subtract 1. Product
wQp % swap. Add 1. Product
Zd % gcd of both products
1M % push the two products again
h % concatenate horizontally
w/ % swap. Divide by previously computed gcd. Implicitly display
```
[Answer]
# Mathematica, 45 bytes
```
Times@@Array[(Prime@#^2-1)/(Prime@#^2+1)&,#]&
```
Primes? Fractions? Mathematica.
[Answer]
# Haskell, 53 bytes
Anonymous function, **53** characters:
```
(scanl(*)1[1-2%(p*p+1)|p<-nubBy(((>1).).gcd)[2..]]!!)
```
Try it [here](https://tryhaskell.org/) (note: in standard GHCi you need first to make sure `Data.Ratio` and `Data.List` are imported):
```
λ (scanl(*)1[1-2%(p*p+1)|p<-nubBy(((>1).).gcd)[2..]]!!) 5
41472 % 99125
:: Integral a => Ratio a
```
Haskell's list indexing `!!` is 0-based. `(___!!)` is an *operator section*, forming an anonymous function so that `(xs !!) n == xs !! n`.
It's four bytes less to generate the whole sequence:
```
λ mapM_ print $ take 10 $ -- just for a nicer output
scanl(*)1[1-2%(n*n+1)|n<-[2..],all((>0).rem n)[2..n-1]]
1 % 1
3 % 5
12 % 25
144 % 325
3456 % 8125
41472 % 99125
3483648 % 8425625
501645312 % 1221715625
18059231232 % 44226105625
4767637045248 % 11719917990625
:: IO ()
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_j}jU £[X²ÉX²Ä]ÃyÈ×ÃË÷Fry
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=X2p9alUgo1tYsslYssRdw3nI18PL90ZyeQ&input=NQotUQ)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes
```
ʁǎ²₍‹›vΠ:ġḭ # main program
```
```
ʁ # range 0 to input
ǎ² # ith prime, sqaured
₍‹› # push the increment and decrement of that list wrapped
vΠ # take the product of both lists
:ġ # duplicate, get the gcd
ḭ # divide both numbers by the gcd, print implicitly
```
I don't think the strategy of 1-2/p^2-1 works in Vyxal because it would just end with a floating point number rather than a fraction, but feel free to prove me wrong. (If it did work, it would be a literal translation from Dennis' M answer, but with a byte shaved off for the nth primes, coming out to 8)
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CA%81%C7%8E%C2%B2%E2%82%8D%E2%80%B9%E2%80%BAv%CE%A0%3A%C4%A1%E1%B8%AD&inputs=15&header=&footer=)
[Answer]
## Seriously, 25 bytes
```
,r`PªD;⌐k`M┬`π`Mi│g;)@\)\
```
Outputs `a\nb` (`\n` is a newline). Large inputs will take a long time (and might fail due to running out of memory) because prime generation is pretty slow.
[Try it online!](http://seriously.tryitonline.net/#code=LHJgUMKqRDvijJBrYE3ilKxgz4BgTWnilIJnOylAXClc&input=Mw)
Explanation:
```
,r`PªD;⌐k`M┬`π`Mi│g;)@\)\
,r push range(input)
`PªD;⌐k`M map:
P k'th prime
ª square
D decrement
; dupe
⌐ add 2 (results in P_k + 1)
k push to list
┬ transpose
`π`M map product
i│ flatten, duplicate stack
g;) push two copies of gcd, move one to bottom of stack
@\ reduce denominator
)\ reduce numerator
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
Πmo§/→←□↑İp
```
[Try it online!](https://tio.run/##ASEA3v9odXNr///OoG1vwqcv4oaS4oaQ4pah4oaRxLBw////MTU "Husk – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
[:*/1-2%1+*:@p:@i.
```
[Try it online!](https://tio.run/##LYwxqwIxAIP3/oogPA61dzZt014LiiA4Obk6iqIu7w1v8N@fd5xDIPlI8hoWXXPHtqKBhUMd1XY4nE/H4VJXG7b@h@tV3f/V/bMbluZ2ffzivljjXUF4BEQIlLm9n/9NYwig3SFYyPjZ01t4mfBNMVqEMcdvMypZ9ByJZhIZ8zgpZWLUzORSpkJJkwt9VpHLzjFMdyRzyVIinfpY@iLJMSclr@ED "J – Try It Online")
Uses the same formula that Martin Ender's answer does.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2016 Day 2](https://adventofcode.com/2016/day/2), Part 2.
---
You finally figure out the bathroom code (on the weird diamond-shaped keypad) and open the bathroom door. And then you see another door behind it, with yet another keypad design:

For those who can't see the image above:
```
+-----+-----+
|\ | /|
| \ 1 | 2 / |
| \ | / |
| 0 \ | / 3 |
| \|/ |
+-----+-----+
| /|\ |
| 7 / | \ 4 |
| / | \ |
| / 6 | 5 \ |
|/ | \|
+-----+-----+
```
You're given a list of UDLR strings. Each string corresponds to one button. You start at the previous button (or button 0 at the beginning) and move to the adjacent button for each instruction, and press whatever button you're on at the end of each string. `U` means to go up, `D` down, `L` left, and `R` right, respectively. If there's no adjacent button at the given direction, you simply don't move.
Additional clarifications for some diagonal edges: For example, if you're at button 0, both U (up) and R (right) correspond to moving to button 1. The full set of rules are:
```
0, U or R -> 1 | 1, L or D -> 0
2, D or R -> 3 | 3, L or U -> 2
5, U or R -> 4 | 4, L or D -> 5
7, D or R -> 6 | 6, L or U -> 7
1, R -> 2 | 2, L -> 1
3, D -> 4 | 4, U -> 3
5, L -> 6 | 6, R -> 5
7, U -> 0 | 0, D -> 7
```
Any combination that does not appear in the table above results in no movement, e.g. `1, U` results in `1`.
If the instructions read as `["ULL", "RRDDD", "LURDL", "UUUUD"]`, the code is as follows:
```
Start at 0, U: 1, L: 0, L: 0 (nowhere to move) -> 0
Start at 0, R: 1, R: 2, D: 3, D: 4, D: 5 -> 5
Start at 5, L: 6, U: 7, R: 6, D: 6, L: 7 -> 7
Start at 7, U: 0, U: 1, U: 1, U: 1, D: 0 -> 0
```
So the code is `[0, 5, 7, 0]`.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
["ULL", "RRDDD", "LURDL", "UUUUD"] -> [0, 5, 7, 0]
["RRRR", "DLLUURR", "LDDRRUU"] -> [3, 2, 3]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
```
a=>a.map(c=>c.map(c=>n+=9-((n-'RDL'.search(c)*2)%8*.4|0))|n%8,n=8)
```
[Try it online!](https://tio.run/##bYxPC4IwGIfvfYohiJvNKVpkxDztuNNgJ9lhLO0PNkWjk9/dVtTo0HP6Pby8z1U/9GTGy3BPbH9slpYumlaa3PQADa3Md9g13ScQ2iQSjEdkavRoztCgOEdhGZPNnCE027DElpZoMb2d@q4hXX@CLaxrQkggOQ8UBu8tBGPMG5eu6U063E0hdABpCuoMgy0GOwwytfrXFQ7/zDiX8sc5Y0JI@cl5Xt0CgxyDQi1P "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~91 76~~ 74 bytes
```
->l{a=0;l.map{|x|x.bytes{|b|a+=321555525[z=a%8*4+b%5]-0xC45132A8[z]};a%8}}
```
[Try it online!](https://tio.run/##JY09C4MwGIT3/goJuNQq8SMgSAql75gp8E4hQwJ1UpB@QNT429Ooz3TcHXfvn51Dz0N@H1bDaTcUo5lW77wr7Px9fVZvvcl4XZUsUjG1cJO21yazKdM5dc@GlXX1aNWity4m2xampFeKoBDklhApAWAXAiUcDkaAaH05ezKy2yAE4ikFgJSIZ4e6Yz/@hD8 "Ruby – Try It Online")
### Notes:
* ASCII code of `U L D R` mod 5 is "0 1 3 2"
* `0x132A8C45` (or 321555525) is a bitmask: if the element in `a*4+b%5` is 1, then the button number must be increased by 1. If we shift the bitmap 12 bits to the right, a matching bit means button number decreased by 1 (and then wrap around with mod 8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~38~~ ~~37~~ ~~36~~ ~~34~~ 33 bytes
```
≔⁰ηFθ«Fι≧⁺⊖÷⊕׳﹪⁻⊕⊗﹪℅κ¹⁵η⁸¦⁸ηI﹪η⁸
```
[Try it online!](https://tio.run/##VY4xC8IwEIVn/RVHpwQiKCIITmIWocVS7CQOsY3tYUw0SbuIvz22VRFvuPt47x28oha2MEKFsHYOK02mDGq6Gp@NBXKn8BiPBkQKibi9MxlWtSepahwDLgsrr1J7WZKt9hxbLGVHP3WPV@nInEFiykYZkqBu3F@Cm@akuvsJ7GyJWihyoQxmC0pp34jBkn5X32@UWtSebITz3796sDvvGcLhEOVxHDGIsoxz3kOcZ3xQ8m54dDyGSate "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now inspired by @alephalpha's answer.
```
≔⁰η
```
Start on button 0.
```
Fθ«
```
Loop through each string.
```
Fι
```
Loop through each character.
```
≧⁺⊖÷⊕׳﹪⁻⊕⊗﹪℅κ¹⁵η⁸¦⁸η
```
The ordinals of the characters `DLUR` modulo 15 are `8, 1, 10, 7`. If you double this, add `1`, subtract the button number, and reduce modulo `8`, this results in a number which is less than `3` if the button should be decremented and greater than `4` if it should be incremented. The range `0..7` is converted into the range `-1..1` by tripling it, incrementing it, integer dividing by `8`, then decrementing it.
```
I﹪η⁸
```
Output the digit modulo 8. (This doesn't need to happen at the end of the previous step as there is already a modulo `8` operation in effect on its next use.)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 69 bytes
```
a->t=0;[[t=((t-i+=2)%8+3)*3\5+i|i<-Vec(Vecsmall(s))%15*2][#s]%8|s<-a]
```
[Try it online!](https://tio.run/##JYpPC8IgGMa/ihgD321CbQSD5k7v0ZNgF/Mg0UJYIdNLsO9urh544Pf8CW71/BnyTER2fErieDEmCcYS943ooBqaHur@dm785kd@fdxZcXy5ZWERoDqd686aQ7TVsMWRO5tdCMuHOcInElb/TgXpHiiZmQNoiTFUS0lbQpVCxB2kVvhrdBFSW05lVGqvUEqt/ygRldKaWgv5Cw "Pari/GP – Try It Online")
Two observations:
* The ASCII code of `DLUR` is `[68, 76, 85, 82]`, which becomes `[8, 1, 10, 7]` when modulus 15, which in turn becomes `[0, 1, 2, 3]` when modulus 4.
* Going to the right, `[0, 1, 2, 3, 4, 5, 6, 7]` becomes `[1, 2, 3, 3, 4, 4, 5, 6]`, which is a part of OEIS sequence [A057355](https://oeis.org/A057355): `a(n) = floor(3*n/5)`. There are many other sequences on OEIS, but this one seems to be the simplest. If your language has a one-byte built-in for the golden ratio, you may also use the sequence [A060143](https://oeis.org/A060143): `a(n) = floor(n/φ)`.
[Answer]
# C, 126 bytes
```
f(s,n,c,l,z)char**s,*l;{z=48;for(c=0;c<n;){for(l=s[c++];*l;)z="10171020213322343545464577560766"[z*4-192+*l++%5];putchar(z);}}
```
[Try it online!](https://tio.run/##VY7NboMwEITveQrkqoqNncrYBlo59OSjT5Z8ohwiUxIkB6qQ9ADi2SnQH6Vz2h3tfLNud3Rueqgb52/le7DvrmXdPp1epwp2pCGOeNIjdzpcwrAjoZdDn4lnWbUX6DIq3b6RaFg2n3W5w7iQ8w3qMxDRKI0ooyzinDEueCxikYg4TeOEpkkC8j4Uu@iF4dBj/BgX8uN2XXpgj@Q4Tp9tXQbnQ91AtBk2wY8qCNdf8gINwMwCJABKa2u/R62UMdaCkQQcyb/YL3r71mzv7H80q/VCMEYptaKsUatjZ6mFKOboOH0B "C (gcc) – Try It Online")
Character ascii value modulo 5 yields:
```
U - 85%5 = 0
L - 76%5 = 1
R - 82%5 = 2
D - 68%5 = 3
```
In the string "10171020213322343545464577560766", each group of 4 characters corresponds to a key, and within such a group, the above numbers can index a specific character indicating the next key
Un-golfed:
```
//s: strings
//n: num strings
//c: string counter
//l: string character counter
//z: key number (as char)
f(s,n,c,l,z)
char**s,*l;
{
z=48;
for(c=0;c<n;){
for(l=s[c++];*l;)
z="10171020213322343545464577560766"[z*4-192+*l++%5];
putchar(z);
}
}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 115 bytes
Not even close to what tsh and alephalpha have created, but a nice straightforward python solution. I can save 5 bytes if I feed it bytes instead of str.
```
lambda l,y=0:[[[y:=[b'70345566',b'00125677',b'12334456',b'11233470'][ord(c)//7-9][y]-48for c in x],y][1]for x in l]
```
[Try it online!](https://tio.run/##Jcm9CoMwFIbhvVcRsqgQMf7GCm4ZMwUynZ5BK1LBqoiD8eatsd/0nucsdvvMU1ou69nXr3Nsvm3XkJHZmlcAYKsaWk/wNMvzovBY63EeJ3khhOs4SdMsy2@P70NwD2FeO/8dRJEInwgWw6zs55W8yTCRHZlFiNHB7mDE0/XhGoDqa5QRKpUy5p9KSq2NociAGqUcaS2lvH9Gy1vMNUkRqwdZ1mHa/N4/guD8AQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎvyÇv•”^'ζ–$!ǝá₃º8˜•8ôy5%èsè}=
```
-2 bytes by using the modulo-5 trick from [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/238162/52210).
Outputs newline delimited. (Could have been [1 byte less](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g6MLD7ce2n24vexRw6JHDXPj1M9te9QwWUXx@NzDCx81NR/aZXF6DlDK4vCWSlPVwyuKD6/4X1ur8z86WinUx0dJRykoyMXFBUj7hAa5gPihQOCiFKsTDZQJCgIKuPj4hIaCWT4uLkFBoaFKsbEA) if we would have been allowed to output the results with additional leading `0` for the starting position by using a cumulative left-reduce.)
[Try it online](https://tio.run/##yy9OTMpM/f//cF9Z5eH2skcNix41zI1TP7ftUcNkFcXjcw8vfNTUfGiXxek5QCmLw1sqTVUPryg@vKLW9v//aKVQHx8lHaWgIBcXFyDtExrkAuKHAoGLUiwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fw3qCyrPNxe9qhh0aOGuXHq57Y9apisonh87uGFj5qaD@2yOD0HKGVxeEulqerhFcWHV9Ta/q89tM3@f3S0UqiPj5KOUlCQi4sLkPYJDXIB8UOBwEUpVicaKBMUBBRw8fEJDQWzfFxcgoJCQ5ViYwE).
**Explanation:**
```
Î # Push 0 and the input-list
vy # Pop and loop over each string of the input-list:
Ç # Convert the current string to a list of codepoint-integers
v # Loop over each of these integers `y`:
•”^'ζ–$!ǝá₃º8˜•
'# Push compressed integer 11223470001256771233445670345566
8ô # Split it into parts of size 8:
# [11223470,"00125677",12334456,70345566]
y # Push the current codepoint `y`
5% # Modulo-5 ([0,1,2,3] for "ULRD")
è # Use it to 0-based index into the list
s # Swap to get the current value
è # Use it to index into the integer, resulting in a digit
} # After the inner loop:
= # Print the intermediate result with newline (without popping)
```
[See this 05AB1E tip of mine (*How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•”^'ζ–$!ǝá₃º8˜•` is `11223470001256771233445670345566`.
[Answer]
# [J](http://jsoftware.com/), 69 61 bytes
```
([:+/\#&>){0(],((8|]+]{(3 2 3#-i:1)|.~2*[){:))/@|.@,'RULD'i.;
```
[Try it online!](https://tio.run/##JYzBCoJAFEX3fsUjoZlJHU2JYqIQerR6qwdvZcJAJNmmD1D69WnKA5e7OZxXWFk1wMmBghwqcHGFhQvTNejOZeUtXZ/NVOk@1/ow91k/6QZqaNJidFsz20@96czkjCnb2ba5YiFUoz0Gkzzuz3fM7WD/izoYQIg8MyJ6EkbyEsHF@0cXiyMeiUTiEyKzSBK@ "J – Try It Online")
* `(3 2 3#-i:1)` Generates the offsets for `'R'`:
```
1 1 1 0 0 _1 _1 _1
```
+ `|.~2*[` Rotate the required amount for `ULD`.
* `0...@|.@,'RULD'i.;` Prepare the boxed input for a single fold to calculate
what we need: Flatten, append 0, reverse.
+ For the fold, we get the offset list based on step 1 above, index into
that list using the current value (which starts at 0), add the result to the current value, and append the
this new value to the running list. The current value is thus always the last item of the accumulator.
* `([:+/\#&>){` All the above gives us one long list of *every* intermediate
value. So we take the lengths of each instruction block, scan sum them, and
use that to index into the master list. This returns the final answer.
[Answer]
# [Rust](https://www.rust-lang.org/), 140 bytes
```
|i:&[&str]|{let(mut o,mut n)=(vec![],0);for s in i{for c in s.bytes(){let k=|n|321555525>>n%8*4+c as i32%5&1;n+=k(n)-k(n+3)+8}o.push(n%8)}o}
```
[Try it online!](https://tio.run/##bVDRaoMwFH3vV9wKlWSmpdXJSkX3ksc8BfJUZLiiTNpGZ@LGUL/dJZa2rOw8nJzcnHNvkqZVeiwknLNSIgzd7JRrKCCGsS937t5Vukn7zhTRudVQEcsSx@grP8z3KVnjqKgaUFBKKDsrD1aq1fuPzhXCNgnHuJd94G9CAz9MErnYPj17B8hMLPAXobuJpBcfkcRLQ16Ave1QrepWfSBjxUM1jGAQzSzbGaiUdasJZFJ95w22E939dGpxuZtDORNOSmDarVNMHg2CMYeAwzml1AomOJ0qwoDeowRCAi8E/uvBDWyEMibERTJKORf30QEBn0BwDafmj69N6qaU@iTnyOl2rwMsE7CrafL3fdEtkCmVN/ot/5wjt0DuZMMPvmE2jOMv "Rust – Try It Online")
321555525 encodes movement information in its bits, both for increasing and decreasing the number:
```
+ DRLU -
0 0101 5
1 0100 6
2 1100 7
3 1000 0
4 1010 1
5 0010 2
6 0011 3
7 0001 4
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 179 bytes
```
[S S S N
_Push_n=0][N
S S N
_Create_Label_OUTER_LOOP][N
S S S N
_Create_Label_INNER_LOOP][S N
S _Duplicate_n][S N
S _Duplicate_n][S N
S _Duplicate_n][S N
S _Duplicate_n][T N
T S _Read_STDIN_as_char][T T T _Retrieve_input_char][S N
S _Duplicate_input_char][S S S T S T S N
_Push_10][T S S T _Subtract][N
T S T N
_If_0_Jump_to_Label_PRINT][S S S T T T T N
_Push_15][T S T T _Modulo][S S S T S N
_Push_2][T S S N
_Multiply][S N
T _Swap_top_two][T S S T _Subtract][S S S T N
_Push_1][T S S S _Add][S S S T S S S N
_Push_8][T S T T _Modulo][S S S T T N
_Push_3][T S S N
_Multiply][S S S T N
_Push_1][T S S S _Add][S S S T S S S N
_Push_8][T S T S _Integer_divide][S S S T N
_Push_1][T S S T _Subtract][T S S S _Add][S S S T S S S N
_Push_8][T S T T _Modulo][N
S N
S N
_Jump_to_Label_INNER_LOOP][N
S S T N
_Create_Label_PRINT][S N
N
_Discard_duplicated_newline][T N
S T _Print_n_as_integer_to_STDOUT][N
S N
N
_Jump_to_Label_OUTER_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Whitespace doesn't have lists, so input-strings are newline delimiter, with additional trailing newline so we know we're done. Outputs the digits without delimiter.
[**Try it online**](https://tio.run/##bU47CgJRDKwzp5jDpEwVyAFEFtZOUPD4z8xmtRAfeWS@kNd@e26P@@W6rUUSmE9Q6ByD0cxEyIZsPqKUdiZwmLK6LHYI4lMjvymb1B@bH9F@e7pIpwnAMHutikCmuyMqPVD9vJVMeERV73DPrMIb) (with raw spaces, tabs and new-lines only).
### Explanation in pseudo-code:
Just like [my Java answer](https://codegolf.stackexchange.com/a/238188/52210), this uses the formula of [@Neil's Charcoal answer](https://codegolf.stackexchange.com/a/238160/52210):
$$a(n,c) = \left(n + \left\lfloor\frac{(((c\bmod{15})\times2-n+1)\bmod8)\times 3+1}{8}\right\rfloor-1\right)\bmod8$$
where \$n\$ is the previous digit, and \$c\$ is the codepoint of the current character.
```
Integer n=0
OUTER_LOOP:
INNER_LOOP:
Integer c = STDIN as character
If(n == '\n'):
Jump to PRINT
c = c modulo-15
c = c * 2
c = c - n
c = c + 1
c = c modulo-8
c = c * 3
c = c + 1
c = c integer-divided by 8
c = c - 1
n = n + c
n = n modulo-8
Jump to INNER_LOOP
PRINT:
Discard newline c
Print n as integer to STDOUT
Jump to OUTER_LOOP
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 83 bytes
```
lambda L,s=0:[[(s:=s-((2*"DRU".find(i)-~s&7)//3-1)%3+1&7)for i in l][-1]for l in L]
```
[Try it online!](https://tio.run/##PZDBboMwDIbvPIUVaVOymRYabZ2QslOOOaHmlObA1KFFooAATR2HvTpzWNv/5M/@ndjuf6avrpVv/bDU6rg01fnjVIHBUWWFc3ws1JhyvntiurRsU4f2xINIf8fHvdhuZZqLB/mcE9TdAAFCC413ae4jNhGNXw6KMeaYJTEP6Tu43CeOlaQry8iGdOUssiZd@TWypTICtcU8BcaWes3Eh2/ODOEFYY@Q3b8ghzbG2v/QaF2W90Ekwg5BehpwM/ZNmDg7tkwk6zbYxQX4uer553fV4OVmia1MCIiuS/QcRJEAaQYFNd1nhX4I7cQDztgpNYvlDw "Python 3.8 (pre-release) – Try It Online")
To determine the effect (forward/backward/no movement) of an instruction, this uses a lookup on the instructions `L,R,U,D` to rotate the keys such that the three keys which allow backward movement come first, the three forwards next and the two no-movement keys last. The key index is then floor divided by 3 and the three possible outcomes `0,1,2` mapped to `-1,1,0`
[Answer]
# Java 10, ~~115~~ 89 bytes
```
m->{int n=0;for(var a:m){for(var c:a)n+=((c%15*2-n+9)%8*3+1)/8-1;System.out.print(n%8);}}
```
Input as an array of character-arrays; output to STDOUT without delimiter.
-26 bytes porting [*@Neil*'s Charcoal formula](https://codegolf.stackexchange.com/a/238160/52210):
$$a(n,c) = \left(n + \left\lfloor\frac{(((c\bmod{15})\times2-n+9)\bmod8)\times 3+1}{8}\right\rfloor-1\right)\bmod8^{^{†}}$$
where \$n\$ is the previous digit, and \$c\$ is the codepoint of the current character.
*† The final modulo-8 could optionally be done later, which is what I do to save 2 bytes on parentheses.*
[Try it online.](https://tio.run/##ZVFPb4IwHL37KRqSJe2Ehr9qIJoYOTIPGE7GQ1dxw0EhbXExhs/OCoJbZg9tX/t7fe/9eiYXYpyPXy3NiRDgjWTsNgEgYzLlJ0JTsO0gAJcyOwIK6Sfh@8P@AAoUqPNmoiYhicwo2AIGlqAtjNVNsQFbmsGp5PBCOCB@gW4joD5BbKlZlm077tw0Tcv2ZvO5ZTuO66qd6bieN5tpuNNaS0hfvNfFlCHDXQS7q5Bpgcta4oorFchQ0DRt0Nmo6vdc2Rjc9H4LlQbupKr82B8IuieRqZBQS6JIj@MwDPUoicNIT9QINSyqPFO3uob6fGN1rIYeRlGSqDUKwzhOkqfiv83o5XvuKN@jDRHpYOMpyln9BK5lluM15@QqsCzvXPhgTjUfaIOxx09krKql6vwTX0iekuKXjQtSQWGsupc3XW@7MoiQgvft@KTvs/R7kGGYwl5hwP9t5wwO4Zv2Bw)
**Explanation:**
```
m->{ // Method with character-array parameter and no return
int n=0; // Integer, starting at 0
for(var a:m){ // Loop over the character-arrays of the input:
for(var c:a) // Inner-loop over the characters:
n+= // Increase the integer by:
((c // The codepoint of the character
%15 // modulo-15
*2 // doubled
-n // minus the current value of the integer
+9) // plus 9
%8 // modulo-8
*3 // tripled
+1) // plus 1
/8 // integer-divided by 8
-1 // minus 1
System.out.print(n%8);}}// After the inner loop, output the integer modulo-8
```
[Answer]
# [Perl 5](https://www.perl.org/), 84 bytes
```
$p=($p+(UR,R,RD,D,DL,L,LU,U)[$p]=~/$_/-(D,LD,L,UL,U,RU,R,RD)[$p]=~/$_/)%8for@F;say$p
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lwFZDpUBbIzRIBwhddIDQRwcIQ3VCNaNVCmJt6/RV4vV1NVx0fIBIJxSIdIJCwWqR5DVVLdLyixzcrIsTK1UK/v8P9fHhCgpycXHh8gkNcvHhCgUCl3/5BSWZ@XnF/3V9TfUMDA3@6@a4AQA "Perl 5 – Try It Online")
[Answer]
# TypeScript Types, 215 bytes
```
//@ts-ignore
type M<T,P=0,A=[]>=T extends`${infer C}${infer T}`?C extends" "?M<T,P,[...A,P]>:M<T,[[1,1,7,0],[1,2,0,0],[2,3,3,1],[2,3,4,2],[3,4,5,5],[4,4,5,6],[7,5,6,7],[0,6,6,7]][P][{U:0,R:1,D:2,L:3}[C]],A>:[...A,P]
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAWQB4AVAGgAUBeABkoEFaBtAXQD5bzD0APcOkQATSAAMAJAG9YiAGbpUhAMIBfGXMXLya8QH4VfQcLEAiQmf1kq1SqwB0TpjS4AuG-dYBGSr4DslPTs9r4ATEFBIawRAMyU8d7RcZQALJRh0fHpAKyUOdHpuZQAbNGBeSWU-tGMVVU17KzUTdIAqm6MAEpuvgAibhEAMm6xaqwq7CFMnG6Ozq6YS7gEhOTehLQkpGZtQ0OEXV19J4RDbccHbddtfWacmCCEzwB6+tj4RORhm9tmR0dCH19tdAUMTkdrvdHsBnoQ3pggA)
## Ungolfed / Explanation
```
// Lookup table; first index is original position, second is 0123 or URDL, and value is final position
type Lookup = [[1,1,7,0],[1,2,0,0],[2,3,3,1],[2,3,4,2],[3,4,5,5],[4,4,5,6],[7,5,6,7],[0,6,6,7]];
type Main<Input, Pos=0, Code=[]> =
// Get the first char of Input
Input extends `${infer Char}${infer Rest}`
? Char extends " "
// If Char is a space, add this position to the code
? Main<Rest, Pos, [...Code, Pos]>
// Otherwise, consult the lookup table and continue
: Main<Rest, Lookup[Pos][{U:0,R:1,D:2,L:3}[Char]], Code>
// Input is empty return the code
: [...Code, Pos]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes
```
Map[t=0;((t=⌊.6Mod[t-#,8]+1.8⌋+#)&/@Mod[2LetterNumber@#+2,22];t~Mod~8)&]
```
[Try it online!](https://tio.run/##JYnBCoIwGIBfZWwghlNrhxDE8LDjjBjsNHZYNcmDFfJ3En2A8il9kaX1nT6@r7Vwc62F5mJ9jQpf2aeGYpuHIRTz9E721eOqISY0M9EuyebpE5FNkJZrZsIBuO74as@uK0nEKGMmh3F5Y7YJjD91zR00QfEB1ZoYgwKUlqjvsRICU4Sl5JyvIpTkv6IWOB4o6pcp5Zq4EEr9VXAupVJ4GPwX "Wolfram Language (Mathematica) – Try It Online")
A port of my PARI/GP answer.
] |
[Question]
[
# Challenge
Given the name of a PPCG member, output their PPCG ID number. If the user does not exist, you may report an error or return any non-positive number. If there are multiple members with this name, you may choose to output only one ID or all of them.
# Test Cases
```
"musicman523" -> 69054
"Dennis" -> 12012
"xnor" -> 20260
"Leaky Nun" -> 48934
"fəˈnɛtɪk" -> 64505
"Jörg Hülsermann" -> 59107
"Community" -> -1
"Any user that does not exist" -> 0
"Alex" -> 69198 (this is one possible result)
"Leaky N" -> 0
"Jorge" -> 3716
```
[Answer]
# [Stack Exchange Data Explorer](https://data.stackexchange.com), ~~56~~ ~~54~~ ~~53~~ ~~51~~ 46 bytes
*-1 byte thanks to Hyper Neutrino. -5 bytes thanks to Giacomo Garabello.*
```
SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S
```
[Try it online!](https://data.stackexchange.com/codegolf/query/707635/whats-my-ppcg-id)
Not sure if this is completely valid but... Input must be surrounded in single quotes `'`.
Also, I still don't get why SQL programmers like to shout but it's apparently good practise so... `SELECT` EVERYTHING `FROM` EVERYTHING `WHERE` EVERYTHING `LIKE` EVERYTHING!
## Explanation
LET ME EXPLAIN.
```
SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S
--S -- DECLARE AN INPUT PARAMETER NAMED S
SELECT -- FIND...
ID -- ID OF THE USERS...
FROM USERS -- IN THE TABLE USERS...
WHERE -- THAT SATISFIES THE CONDITION...
##S##=DISPLAYNAME -- S EQUALS THE USERS' DISPLAY NAME
```
[Answer]
# JavaScript, ~~155~~ ~~149~~ ~~142~~ 135 bytes
```
i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)
```
```
f=i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)
```
```
<input onchange="f(this.value).then(console.log)"><br>Fill input and press Enter
```
[Answer]
# [Python 3](https://docs.python.org/3/) + [requests](https://pypi.python.org/pypi/requests), 196 bytes
Thanks @Wondercricket for -6 bytes!
```
from requests import*
x=lambda s:all([print(a['user_id'])if s==a['display_name']else''for a in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']])and d
```
Uses Stack Exchange API. Fixed the `Leaky N` and `Jorge` errors.
If there are multiple users with the same name, it prints all of them, which is allowed.
[Answer]
# [Python 2](https://docs.python.org/2/) + [requests](https://pypi.python.org/pypi/requests), 187 bytes
```
from requests import*
def f(x):t=get("http://api.stackexchange.com/users?inname="+utils.quote(x)+"&site=codegolf").json()["items"];print[k['user_id']for k in t if k['display_name']==x][0]
```
Returns the user ID if a single user exists, the first user which matches the requirements if more exist, and reports an error otherwise.
[Answer]
# [Python 2](https://docs.python.org/2/) + [requests](https://docs.python-requests.org), 173 bytes
```
lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
from requests import*
```
## Sample run
```
>>> f=\
... lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
>>> from requests import*
>>>
>>> tests = ['musicman523', 'Dennis', 'xnor', 'Leaky Nun', 'Community', 'Any user that does not exist', 'Alex', 'Leaky N', 'Jorge']
>>> for i in tests: print '%-30r -> %s'%(i, f(i))
...
'musicman523' -> [69054]
'Dennis' -> [12012, 13891, 14912, 24937]
'xnor' -> [20260]
'Leaky Nun' -> [48934]
'Community' -> [-1]
'Any user that does not exist' -> []
'Alex' -> [21536, 69198, 11192]
'Leaky N' -> []
'Jorge' -> [3716]
```
Fun fact: the result is sorted by reputation, highest first.
[Answer]
# JavaScript, ~~128~~ 119 bytes
-9 bytes thanks to [Rogem](https://codegolf.stackexchange.com/users/77406/rogem).
```
n=>fetch("198.252.206.16/users?site=codegolf&inname="+n).then(r=>r.text()).then(t=>t.match(`\\/([^\\/]*)\\/`+n+`"`)[1])
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 169 bytes
```
a←⍞
y←(⎕JSON((⎕SE.SALT.New'HttpCommand').Get'https://api.stackexchange.com/users?site=codegolf&inname=',('\s+'⎕R'\%20')a).Data).items
{a≡1⊃y.display_name:y.user_id ⋄ 0}1
```
This took forever to figure out, lol.
Thanks to @Adám for saving me a lot of time, and a lot of bytes on the HTTP request.
## Explanation
```
a←⍞ ⍝ Store string input
y← ('\s+'⎕R'\%20')a ⍝ Convert spaces to '%20' for query
(⎕JSON((⎕SE.SALT.New'HttpCommand').Get'https://api.stackexchange.com/users?site=codegolf&inname=',).Data).items
⍝ Get and parse JSON from API call using ⎕SE (session namespace)
a≡⊃y.display_name ⍝ Is the input equal to the unwrapped user id?
⍝ (display name comes as an array of strings)
{ :y.user_id ⋄ 0} ⍝ If so, print the user id
⍝ Else print zero
⍝ Call function with placeholder arg 1
```
[Answer]
# JavaScript (ES6) + HTML, ~~154~~ ~~152~~ ~~151~~ ~~202~~ ~~179~~ ~~161~~ 145 bytes
Sacrificed a few bytes to handle special characters.
Needs to be run under the `api.stackexchange.com` domain. Returns a Promise containing the ID or Throws an error in the Promise if the username can't be found.
```
s=>fetch(`/users?site=codegolf&inname=`+s).then(r=>r.json()).then(j=>j.items.find(i=>(o.innerHTML=i.display_name,o.innerText==s)).user_id)
<a id=o
```
Note: This solution was developed independently of Uriel's and its comments; if Uriel decides to use the `find` method, I'm happy to roll back to my longer, recursive version.
] |
[Question]
[
### Your task
Given a numerical string or integer \$\ge 0\$ (which may have leading zeros), convert it to letters using the below rules.
### Rules
Loop through the digits:
* If the digit is `0` or `1`, combine it with the next digit and output that letter of the alphabet (0-indexed).
* If the digit is `2`, combine with the next digit ONLY IF the next digit is between `0` and `5` (inclusive). Otherwise, output `c` (2nd letter of the alphabet, 0-indexed).
* If the digit is `3` or more, output that letter of the alphabet (0-indexed).
### Example
Our input is the number `12321`.
We loop through the digits:
* `1`: this is less than 2, so we keep this and wait for the next digit.
* `2`: combine with the previous digit, `1`, to get `12`. Index into the lowercase alphabet (0-indexed) to get `m`
* `3`: this is more than 2, so we output the 3rd letter of the alphabet (0-indexed), `d`
* `2`: this is 2, so we check the next digit. It is less than 6, so we wait.
* `1`: combine with the previous digit, `2`, to get `21`. Index into the lowercase alphabet (0-indexed) to get `v`
Our output is `mdv`.
### Test cases
#### Random
```
Input Output
132918 ncjs
79411 hjel
695132 gjfnc
800125 iamf
530987 fdjih
144848 oeiei
93185 jdsf
922846 jwieg
187076 shhg
647325 gehdz
```
#### Edge-cases
```
Input Output
0 a
1 b
25 z
26 cg
000 aa
123 md
0123 bx
1230 mda
12310 mdk
12345 mdef
00012 abc
```
Feel free to create your own test cases in [this TIO](https://tio.run/##nZLRbsIwDEXf/RV@o1G1icIYG2q@BE2IgQeWQlqlrmBf34Uk64o2Hro@NbbvzT1W6k85VnbedXyqKyfYiGN7ALDt6Z0camRbt5IpYLuniz9PoWrFl/zvZAJwPrIhjM0SDdksKhU@YLEC9N@eDyzBSVJzHebfVGjzR5oocRYFoRocc41FXzIkEiL5jFmQKMzxxrGfTRlznYAet82OeWOqM7ndtqH1NUw0VFFFpg@i9TCJpYts7jHkRaJIJIPhUuPix@UO01iu/7FFvoZW431inu8VDS1Gywf44Ff1x5u5fS@/NzDqSqjd9Rg1quuK2fxp8bx8eZ1@AQ) of some ungolfed Python code.
### Clarifications
* Everything must be 0-indexed
* You cannot ignore leading 0s (see the 5th and 6th edge-cases)
* If the last digit is 0, 1, or 2, and it has not already been used by the previous digit, output "a", "b", or "c" respectively (see edge-cases)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
// we match all patterns consisting of either:
// +----------> a '2' followed by '0' to '5', or
// | +---> any digit optionally preceded by '0' or '1'
// _|__ _|__
// / \ / \
s=>s.replace(/2[0-5]|[01]?./g,n=>Buffer([+n+97]))
// \_____________/
// |
// and replace each of them with a <----+
// letter in lower case
```
[Try it online!](https://tio.run/##bZDdboMgAIXv9xTGK01XBUSBC7tkr2G8cAgKUWxkf1n27q6L2jZQbr@Pcw7o5rOxfFbn96OZWrHIcrHlySazOA8NF1GKKnDM698KwPolSbtnU55eP6QUc1QdzIGROo4XPhk7DSIZpi6SUQgzxCAN4zhI08BwbZ8cgTAMYRisQq/F4AoFyy8hW0KnpeGuQQGAKN8M1YzSFfIMMEo2QbZa9a4BMaZ4nzkJJZRrsAzSfN@pW@uVMIQoLrYI/aVE55VQAshu2L73hAKT7PqQTvTtj2uAMPg/q9F4Bff0zaWX5Bv1klFxR7m/HWXhFY@tt2vlW/P3g9sgvN1uHnB8/dyxFXL5Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 58 bytes
```
f=lambda s:s and chr(97+int(s[:(I:=1+(s<"26"))]))+f(s[I:])
```
[Try it online!](https://tio.run/##JYtNDoIwFIT37xQNm/YFFlAEtZEDsPIAwqL8BRBr05Yop68QF/NlMvlGb258q/SijfdDschX00lihSVSdaQdDbuew0k5Zh@ClaJIQmZvAc8DxBoxHPa9FDV6bQ6JlkqvrnLkvrq9UITPOC09SQQQZzYxF9MhMATSf9teO9GYXj6B/O9zRCtHo4HNiD6GBHgGPIeEpxAf2BMfOGU/ "Python 3.8 (pre-release) – Try It Online")
This is based on the observation that we can simply compare the entire leftover string to "26" to decide whether to consume one or two characters.
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 83 bytes
```
>i:0(?;'0'-:2(?v:2=?v'a'+o
^ o+'a'+-'0'i*a<
+'a'~$o'c'v?(6:-'0'i<.01o
1o+'a'+*a$<.0
```
[Link](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiPmk6MCg/OycwJy06Mig/djoyPT92J2EnK29cbl4gbysnYScrLScwJ2kqYTxcbisnYSd+JG8nYyd2Pyg2Oi0nMCdpPC4wMW9cbjFvKydhJysqYSQ8LjAiLCJpbnB1dCI6IjI2MTMyOTE4MjE3Iiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9)
[](https://i.stack.imgur.com/mwcI3.png)
Top row is basic reading lines and exiting at the end. Red part at the end is the single digit case.
Middle row is the 0 or 1 case.
Bottom row 2 rows are the 2 case. Top branch is C, bottom is 2 digit number.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes
```
2[0-5]|[01]?.
$*#a
+T`##l`_l`#\w
```
[Try it online!](https://tio.run/##DccxDsIwDAXQ/V8jTEUg27Fje@ISbG1FOjAgVQwIiYW7B972Xvf347mNITOdbP3OxOvljMNUNhyvvZS93/Zels8YXCU54KnMaGn/I4hYDFYpw8GqoYGsHIYUCW3gcPKGpl7Ffg "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
2[0-5]|[01]?.
```
Use @Arnauld's regex to identify the numbers from `0` to `25` inclusive.
```
$*#a
```
Replace each number with a string of that many `#`s followed by an `a`.
```
+T`##l`_l`#\w
```
Repeatedly cycle letters though the alphabet, decreasing the number of preceding `#`s each time, until there are no `#`s left.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.≈ì í‚Ǩg3‚Äπy‚ÇÇ‚Äπ¬´P}Œ∏As√®
```
Output as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f9f7@jkU5MeNa1JN37UsLPyUVMTkDq0OqD23A7H4sMr/v83MDAwNAIA) or [verify all test cases](https://tio.run/##HYs7CsJAFEW3EqZ@yPvM500VbK3sxUJBxMoiIKQQJIULiJsQdAHaKjYWLmI2Mk7SnPvh3n2zWu82@dDWpkrnvjJ1myefy7dP3X0r6fRsU9cVed3mx99j2ryveQZ5QcKRFEK0ROCjKxkUkdiBE4wagKxVqxCF1EFkVuuBNGDw4G2QMkQgKMKlZwFTzmIGiwNopHWlRzQjic3yDw).
**Explanation:**
```
.œ # Get all possible partitions of the (implicit) input
í } # Filter this list by:
€ P # All parts in a partition
g # Should have a length
3‹ # Less than 3
y ¬´ # And in addition should also all be
₂‹ # Less than 26
}θ # After the filter: leave the last valid partition
Asè # Index each inner index into the lowercase alphabet
# (after which this character-list is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->s{eval ['""',*s.scan(/2[0-5]|[01]?./)]*"<<97+"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OrUsMUchWl1JSV1Hq1ivODkxT0PfKNpA1zS2JtrAMNZeT18zVkvJxsbSXFup9n@BQlq0kqGRsZGhUux/AA "Ruby – Try It Online")
[Answer]
# Excel (ms365), 169 bytes
```
=DROP(REDUCE(VSTACK(A1,""),SEQUENCE(LEN(A1)),LAMBDA(a,b,IFERROR(LET(x,LEFT(TAKE(a,1),2),y,IF(--x>25,LEFT(x),x),CHOOSE({1,2},RIGHT(a,LEN(a)-LEN(y)),a&CHAR(y+97))),a))),1)
```
The idea here is to use `REDUCE()` to iterate n-times (length of input) over this input and while doing so keep a shadow-record in the element next to given input with the alphabetic output while we check all numbers in order from left to right.
I do have a feeling this could be shortened though.
[](https://i.stack.imgur.com/FFuCH.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~42~~ 38 bytes
-4 bytes thanks to @coltim
Uses [loopy walt's](https://codegolf.stackexchange.com/a/254737/74062) recursive approach. There is probably some clever way to rewrite it using a fold.
It takes the length 2 prefix and compare it with 26 to decide if we convert 1 or 2 characters. After the conversion, it appends a recursive call on the remaining string.
```
{$[x;(`c$97+.n$x),o(n:1+26>.2$x)_x;x]}
```
[Try it online!](https://ngn.codeberg.page/k#eJxN0N1ugyAYBuBzrsIQD2xqGv4UaJNm97EsGyqobLUHHpR02a59IEjGGQ/v9xPM+bt8dZfqoy8lP56W0h3qe7Wc8ZG01xPx13d3cW8/AFQ1VPBQ/BbmpYYIFtsJ2mXF//QZFZImIoD9CKO0uygVBaHYD8DbEAUTmqRzKZMoZFQOoZ0+M+FggbTJxprNVNfngZhAAJferv5lS1EisfA2Wf2VjEuGsafRmiVVtrLxSW+zupkUE6Fb480Mdp5irqFICu7trmc9p0UYEyyMsMO610qKRSi1j1mn/5GECNZ6W6dp3LcTHPFgo56GZ1qFcRrG/gEItWYU)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~17~~ 16.5 bytes (33 nibbles)
```
``;$$$:+`r<;?\`<`:"26"$$@"a"_>$@
```
```
``; # launch recursive function:
$ # starting with input list of digits,
$ # stopping when argument is empty
$ # and then returning the empty argument,
# otherwise:
`:"26"$ # make a list of "26" and the argument string,
`< # sort this list of strings,
\ # reverse it,
? $ # get the index of the argument in this,
; # and save this as the number of elements
# to take from the argument (1 or 2);
< # now, take that many elements
`r # read this as an integer,
+ "a" # add this to "a",
: # and append onto this
_ # a recursive call with argument:
>$ # drop the saved number of elements
@ # from the current argument
```
[](https://i.stack.imgur.com/vj6IE.png)
[See some more test & edge cases](https://i.stack.imgur.com/LgZse.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒṖẈṀ’ỊƲƇV<26Ạ$ƇṪ‘ịØa
```
**[Try it online!](https://tio.run/##AUAAv/9qZWxsef//xZLhuZbhuojhuYDigJnhu4rGssaHVjwyNuG6oCTGh@G5quKAmOG7i8OYYf///ycwMzAxMDIyMjIn "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##FYo9CsJAEIX7OUUKS4ud/Z0F9RiCpYVNyAXsFpuIdhYSQcFarIJNkjKYe8xeZF2L9z2@xyt3VbVP6Xvh7sr9kbsQw42H09RO9XohLffP2VRz94qh4eE8NtvEw2c@1mUM92K5KmJ4TG08vDcpoZIeCZzXiGC9yQ4kBEoDRglPDlBr0gReIRnwUpK2gOSEs2C1U/koACGXzLtUIP7IEX9o8wM "Jelly – Try It Online").
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
Wθ«≔⊕‹θ26ι§β✂θ⁰ι≔✂θιLθ¹θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUGjUFOhmovTsbg4Mz1PwzMvuSg1NzWvJDVFwye1uFijUEdBychMSVNTRyFT05qLM6AoM69Ew7HEMy8ltUIjSUchOCczORWkzACkQhOkBmoWXCZTR8EnNS@9JANol46CIRAXApXV/v9vaGRsYvpftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @loopywalt's Python solution.
```
Wθ«
```
Loop until the input is empty.
```
≔⊕‹θ26ι
```
Determine how many digits to extract.
```
§β✂θ⁰ι
```
Output the appropriate letter.
```
≔✂θιLθ¹θ
```
Slice off those digits.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~85~~ 75 bytes
* -7 thanks to jdt
* -3 thanks to ceilingcat
Takes strings to preserve leading zeroes.
```
f(*o,*s,u){for(;u=*s++;)*o++=97+((u-=48)>2|u==2&*s>53|!*s?u:u*10+*s++-48);}
```
[Try it online!](https://tio.run/##TVBNcoMgFN7nFK/OtEXQGUCMWIb0ArlBmoW1Y6qTxkwMdmG8ei1CkpYFfO/7eQ8o43JfHHZTfTjDV1EfUN/WHyEMCwBL4Xqz1cM6YAnPmQwiWAdZLhhzaJmnlndQUsp46mCa0FxmDjIhpPCpPGHS6znnUiy9LjOaebgUWTI3sGP/1jqg3uf2a3/uA5ReNZ74@gbseVfYHYn0lmLzjekYAcaNWth5VXtCja4V2BoaQvzjAY4n@wEVCh73HegVvD3bHG5C5cT5u95NtZF0CxqG0bMVstw/l20NaLb2mirn77cKejvj@s6jOZefxQl56ZqyZIcCO8/V42KcKoTbCHeRCYf5tspo3BGiQtwSovOMIGRiLWS44hejNX/C3SpNLg@4ezUvBjNKZntsDWqcpp@y2he7boq/fwE "C (clang) – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 64++ bytes
* Inspired by [ErikF's answer](https://codegolf.stackexchange.com/a/254773/112488).
```
u;f(*o,*s){for(;u=*s++;)*o++=*s<54<u-49|!*s?49+u:u*10-431+*s++;}
```
[Try it online!](https://tio.run/##RZFdb4IwGIXv@yveYYyUj62FysdQd7VsF2ZXS7ZEuWAIWoJgrMxkzr8@Vj7Um/bhnNMT@jY24zwq1nVdBamqlYYm8Ckt92pQTTWh6wHWSl2XOBmzSWUy//dOE0/M16vHSqPEZDbV29y5HvAizqtVAhNxWPHyfjNDN@kYb6J9I6HBKkl5kcD8@e3l/VX9xKAK/pOUKTT8ALePBQkxQrw4oG3EC/W75CuMTghASvBVpQuPhAZkBmh8EcIUGgtgrlDb8qmnGBJdn1HakuOPpd6iRwi1xi2ObeJ7bouUMY/JU32Jb1Ovy/iW5TGny3gucTt0mGv3JaTz2rWXLOdaREjvW3aXvoDcrw69Eus7m39UZMU5QHJtXiSTVyQBZDC5zI7jAHQ9w/3Nj9tkK5KDKkcjK0ZLMjIuSSlhHLSptPP5Igt7ZbeXA01VZWg6uYDpDEbDXIyWhdKljGbWbfSMzvVfnObRWtTmR1GafLvLecwP/w "C (clang) – Try It Online")
If the output not being null-terminated is a problem, it's 1 extra byte to write to `stdout`:
```
u;f(*s){for(;u=*s++;)putchar(*s<54<u-49|!*s?49+u:u*10-431+*s++);}
```
[Try it online!](https://tio.run/##TZHLboMwEEX3/oopURUMobXBvApJV1W7iLqq1EpRFohHYkQgiqGLpvx6qXkk7WZ8Zu74yjOOjbiIyl3XNUGmagKfs@qkBs1SE7oe4GNTx/voJIXQZmFjMP/7RhOPzNebh0ajxGAW1ftWHLTdjJdx0SQphKJOeHW3XyE0S9KMlymsn16f317UDwyq4F9plUHP9/CXbMgWI8TLGh0iXqqfFU8wOiMAWYJ8ARrfbGEJfQVgrVDL9KmnLCS6PqN0IMe3ZX1AjxBq2gPaFvE9d0DKmMfkrcnEt6g39vim6TFn7PFc4o7oMNeaTMioDXEqmc7ViJBJN62x@wLyvCr0Smzy7N@oSIs2QDL2m8/liCSAHMLLyjgOQNdzPE1@PMl9ZKpyaziFgOUK5tKKb/ItDgY9U/8l8vuEqsyVIW1R2/3EWRHtRGe8l5XBD8eCx7z@BQ "C (clang) – Try It Online")
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 32 bytes
```
"2[0-5]|[01]?."\; /#
"&":97+ c>S
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Port of @Arnauld's answer.
For testing purposes:
```
["132918""79411""695132""800125""530987""144848""93185""922846""187076""647325""0""1""25""26""123""0123""1230""12310""12345"] \>S map ; n>< n>o
"2[0-5]|[01]?."\; /#
"&":97+ c>S
```
[Answer]
# [jq](https://stedolan.github.io/jq/) -Rr, 43 bytes
```
[scan("2[0-5]|[01]?.")|tonumber+97]|implode
```
[Try it online!](https://tio.run/##HYo7DoMwEET7PQZVooho117bu1XukBZR5ENBFDAB0vnscQzFvNFo3uuTc7M8buOhMg3Wrk0NUns5V8e0xvE73Lv5pKFN/TC947PLmaxREgjKRODVlQ2CSMaBs6gSgJiFBdSSOFBjhD2QBAwePAdbREAgKG3KYSzghhLcQDu5SHv5IIq/OK19HJdcX@c/ "jq – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~54~~ 50 bytes
```
ic%:a)?v}
<v+*a ~!
^>"a"+o>:2(}:2=}$:@6({*{+l2)*?
```
[Try it online!](https://tio.run/##S8sszvj/PzNZ1SpR076slsumTFsrUUGhTpErzk4pUUk7387KSKPWysi2VsXKwUyjWqtaO8dIU8v@/39DYyNLQwsA "><> – Try It Online")
**Explanation**
`ic%:a)?v}`
Get all the input, mod each by **12** to get numbers and reorder it in the input order.
```
v
~
>
```
Then discard the end-of-input-byte.
If we call the top of the stack **x** and the 2nd top value of the stack **y** then:
`:2(}:2=}$:@6({*{+l2)*?`
**If (x < 2 or (x == 2 and y < 6)) and len(stack) > 1**
`<v+*a ~!`
**Then x = x \* 10 + y**
`"a"+o`
Print **x + 97** as a character.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ 71 bytes
```
lambda s:re.sub('2[0-5]|[01]?.',lambda c:chr(97+int(c[0])),s)
import re
```
[Try it online!](https://tio.run/##LYvLDoIwFET39yu6axuRtCgamxDXrvwAYAFYQpFHUy5REv8daXQxJ5OcGbtgMw6HtU6ytSv68lGQSTkdTnPJaJSKfZx/UiHza0iDv69U1Th2Oe/MgKxKRc55MHEwvR0dEqdX67yht8HOmCG5z7gVyuHVmE4TqYCgW1SbGD9gHIh@V9qiKp0unkB@9zagGdKgZi3nqwAJUQzRCWR0AOGxRXgc4y8 "Python 3 – Try It Online")
Uses Arnauld's Regex expression.
# [Python 3](https://docs.python.org/3/), 117 bytes
```
f=lambda n:n and(chr(97+int(n[:2]))+f(n[2:])if n[0]in'01'or n[0]=='2'and int(n[1])<6 else chr(97+int(n[0]))+f(n[1:]))
```
[Try it online!](https://tio.run/##VYxBDoIwEEX3c4rZtY0s2ioYGzmAKw@ALFBKKOJAao1yeiwaFy7m589k3hun0A60nucm76vbua6QDGFFNb@0nu@2K0eBU2F0KcSqiU2bUrgGqZClIyYVG/xnyXOmWeTwC6hS7DO0/d3in0j@PCp6xDz65cwOND7CKeDxEWJhAp6t6y0qAxj8ZLrcLQ9cANrXxY7BnL2troBfvEvYKbCk4V00SlCgU9AZKL0GuUQcucQmfQM "Python 3 – Try It Online")
Recursive `lambda` function.
# [Python 3](https://docs.python.org/3/), 135 bytes
```
def f(n):
if n=='':return''
d=n[0]
if d in'01'or d=='2'and int(n[1])<6:a,b=n[:2],n[2:]
else:a,b=d,n[1:]
return chr(97+int(a))+f(b)
```
[Try it online!](https://tio.run/##JY5BjsIwDEX3OUV2jkUXSRgYEZEDsOIApYuWJmoLMlVwxXD6TgILf9nP/l@e3zw8aLuufYgyKkIn5BgleQ/gUuAlEYCQvadaN59VL0cCbeCRMvVgoaWCWFFtGjzuXVt1@drZpqLaumwK92f40D4TU8g3WF6HpA6/m2JuETdRdbjOqYxwonnhC8vzwrkBFK9hvAdp8nuc3m7yYzlQmNP/rmFm16XQ3oT82qcKLgxVVBPiqoURdifsXhi7FbpILl3kZ/cP "Python 3 – Try It Online")
Recursive `def` function.
# [Python 3](https://docs.python.org/3/), 212 bytes
```
def f(n,i=0,o='',c=lambda s:chr(97+int(s))):
while i<len(n)-1:
d=n[i]
if d in'01':i+=1;o+=c(d+n[i])
elif d=='2'and int(n[i+1])<6:i+=1;o+=c(d+n[i])
else:o+=c(n[i])
i+=1
if i<len(n):o+=c(n[i])
return o
```
[Try it online!](https://tio.run/##dU5LTsMwEN37FLOzLRvJTmkRpj4AKw5Au0gTR3EITuRMBD198FB1wYLFPI3eZ@bNV@yntNu2NnTQiaSjN3rynOvGj/Xnpa1hcU2fxfOTignFIqV0DL76OAaIxzEkkeSDLRS0Pr3Hc1liBy3ExI3lLipvXyblG9EqkmXRw0gO73nF60ROFEVS9iyPh38CS3C/3J0hF6NH9wp/5BxwzQmmbc50nL@mecUTwtuKZeGS3epTa8xXN/hIBlGS4bsJM7pLDvUHg1t80PyEXHdikHIzzLJqz6oDs9WOGYIyhuBx/wM "Python 3 – Try It Online")
Iterative `def` function.
] |
[Question]
[
Given a multi-line string as input containing characters `"|"`, `"_"` and `" "` (space), count the number of cells it contains.
A cell is the following structure of 3 characters by 2 lines:
```
_
|_|
```
That is, an underscore on one line (the characters to its right and left don’t matter), and `"|_|"` right below it.
Two cells can share the same characters. For example, there are 3 cells here:
```
_
|_|_
|_|_|
```
### Inputs and outputs
* You can assume that the input string will only contain the following characters: `"|"`, `"_"`, `" "`, and `"\n"`.
* You may take a list of strings as input, or a list of lists of chars, instead of a multi-line string.
* You may assume that there are at least 2 lines and 3 chars per line.
* You may pad each line with spaces so that all lines have the same length.
### Test cases
```
Input Output
_
|_| 1
___
|_| 1
|_| 0
_ _ __ __
|_| _| _|_|| 2
_
|_|_
|_|_| 3
_
| |_
|_|_| 1
_
|_|_
|___| 1
_ _
|_|_|
|_|_| 4
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~16~~ ~~14~~ 13 bytes
```
ǰ·üö7%J»232¢
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cPuhDYe2H95zeJu5qteh3UbGRocW/f8fraQQrwBG8SCkoKSjoFQTXwPkg3F8TY1SLAA "05AB1E – Try It Online")
# Explanation
```
Ç convert each character to its ASCII code
° map each number to 10**x
· times two
üö for each consecutive pair of rows, convert the number as a number in
a base of the next number
7% modulo 7
J join each row into a string of numbers
» join the rows together with a newline
232 push the string "232" (pushing it as a compressed number doesn't work due to a bug)
¢ and count how many times it appears in the string of digits
```
| Characters | ASCII codes | 2 \* 10^first number converted from base-2\*10^second number, mod 7 |
| --- | --- | --- |
| | 32, 32 | 4 |
| `_` | 32, 95 | 4 |
| `|` | 32, 124 | 2 |
| `_` | 95, 32 | 4 |
| `_` `_` | 95, 95 | 3 |
| `_` `|` | 95, 124 | 2 |
| `|` | 124, 32 | 1 |
| `|` `_` | 124, 95 | 1 |
| `|` `|` | 124, 124 | 2 |
[Answer]
# [APL (Dyalog Unicode)](https://dyalog.com), 23 bytes
Anonymous tacit prefix function. Takes character matrix as argument.
```
≢∘⍸{'_||_'≡2↓,¯1⌽⍵}⌺2 3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HnokcdMx717qhWj6@piVd/1LnQ6FHbZJ1D6w0f9ex91Lu19lHPLiMF4/9pj9omPOrte9TV/Kh3zaPeLYfWGz9qm/iob2pwkDOQDPHwDAapmQjWNQ@IuBTiuWria7hQBePjsYliEVKIVwCjeAWIDiATjIGuRFUJMwJiHYTAVAKWVsAvDdEdj11aAaYVTAIA)
`{`…`}⌺2 3` on each 2-by-3 submatrix:
`_`
`|_|`
`¯1⌽⍵` rotate the columns cyclically one step to the left
`_`
`||_`
`,` ravel (flatten)
`_||_`
`2↓` drop the first two elements
`_||_`
`'_||_'≡` does the string match?
`≢∘⍸` count the **i**ndices where true
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda a:sum(c+a[n+a.find('\n'):][:3]=='_|_|'for n,c in enumerate(a))
```
[Try it online!](https://tio.run/##XY6xbsMgEIZ3P8VtBqXyko3KY7p2yeZYJ@IcCq19RgSrjeR3dzEkVlQJxPH9H9y5e7iOvF9MfVp6PZwvGrS6TYPodrrhna6M5YsoT1xK1TZq39Z1iTPOpRk98FsHloF4GsjrQEJLuVh2UEPTFj9X2xMc/USqAAj@vh4AvWWKQtSmIGRC1iSqVlhp5yi2XEFOqb/FyHnLQZg0SvU1WhZRllK@w9Ywqr8duQCHz4@D96PPDc@e9PcCCEWcuygQMRcxehQIaeG6EouXtHGeIecJ5y/whcHG/mv41Dbh@fQP "Python 3 – Try It Online")
[Answer]
# [Factor](https://factorcode.org) + `math.unicode`, 66 bytes
```
[| s | "_"s "|_|"s [ start-all* ] 2bi@ 10 s index v-n ∩ length ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fU69SgNBEMb23kH4uFK4Q61Em2AjNjZilYRlvUzM4Wbu3J0LEdfed7C5JoKPpKVP4t5tNIaAwwwz8_0M8_o21YVUtv3c27-5vry6OMU9WSYDRw8NcUEOpiq0cRsgp6VY7TDXMssX1NnXS8NlUU0ItSWRx9qWLDhLkqcEIVIojNgrP-I0AkqpbSDOvbJP1WU0ha0v5TfyThPZ9WW1y-Ef7sentrk_hl_f86qRaXbycT70cPDh99T1_4Y2hBNtJdPGHGCM49tygKPDICt5QkssMsbXyzsM8Z3MMI6XVnNdI49z28b-DQ)
Input is a multiline string padded with spaces so each line is the same length. This answer relies on there being a trailing newline in the input; if that is not allowed, let me know and I will change my answer.
It finds the starting indices of (possibly overlapping) subsequences `"_"` and `"|_|"`, subtracts the index of the first newline from the `"|_|"` indices, takes the intersection between the two sequences of indices, and returns the length of that.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€ü3øεü2ε€ÁJ„_|ºÅ¿]˜O
```
Input as a right-padded list of lines.
-1 byte using the rotate approach from [*@Adám*'s APL (Dyalog Unicode) answer](https://codegolf.stackexchange.com/a/250114/52210)
[Try it online](https://tio.run/##yy9OTMpM/f//UdOaw3uMD@84t/XwHqNzW0HcRq9HDfPiaw7tOtx6aH/s6Tn@//9HKynEKygoKOko1cTXxEPo@PgapVgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLh2VfqOSn9f9S05vAe48M7zm09vMfo3FYQt9HrUcO8@JpDuw63Htofe3qO/38lvTCdQ9s47f9HKynEK8Tk1cTXKOkoKMXHx8PZCgoIcaAaMIoHIYgwkAfG8TVwFRAJqHHxKMIK2IVhquPhwnBlMNWxAA).
`€ÁJ„_|ºÅ¿]˜O` could alternatively be `ćÅs«]˜„|_2×¢` for the same byte-count:
[Try it online](https://tio.run/##yy9OTMpM/f//UdOaw3uMD@84t/XwHqNzW4@0H24tPrQ69vScRw3zauKNDk8/tOj//2glhXgFBQUlHaWa@Jp4CB0fX6MUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLh2VfqOSn9f9S05vAe48M7zm09vMfo3NYj7Ydbiw@tjj0951HDvJp4o8PTDy36r6QXpnNoG6f9/2glhXiFmLya@BolHQWl@Ph4OFtBASEOVANG8SAEEQbywDi@Bq4CIgE1Lh5FWAG7MEx1PFwYrgymOhYA).
**Explanation:**
```
€ # Map over each inner string of the (implicit) input-list:
ü3 # Create overlapping triplets
ø # Zip/transpose; swapping rows/columns
ε # Map over each inner list:
ü2 # Create overlapping pairs
ε # Map over each pair of strings:
€ # Map over each string:
Á # Rotate its characters once towards the right
J # Join the two strings together
„_| # Push string "_|"
º # Mirror it to "_||_"
Å¿ # Check if the string ends with "_||_"
] # Close the nested maps
˜ # Flatten the list of pairs
O # Sum
# (which is output implicitly as result)
```
```
ć # Extract head ([a,b] to [b] and a with `a` on top)
Ås # Pop this head, and leave just its middle character
« # Append it to the string in the remainder-list
] # Close the nested maps
˜ # Flatten the list of list of wrapped strings
„|_ # Push string "|_"
2× # Double it to "|_|_"
¢ # Count how many "|_|_" are in the list
# (which is output implicitly as result)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
&`(?<=(.)*)._.*¶(?<-1>.)*(?(1)^)\|_\|
```
[Try it online!](https://tio.run/##VYy5DYAwDEV7T@EG5KAQiZ5jEcSHgoKGAlF6LgZgsRCSUCDZ//CTfKznti/@vsiStRS8kPl1X84ytJ04UxkHV91XqHXThy6DNGYyo2JU7xmkUCIgB2bOARwHnFCIcaERvqckufK/Jor86UNRHw "Retina 0.8.2 – Try It Online") Link is to test suite that takes double-spaced test cases. Explanation: The lookbehind calculates the column that the left `|` should be in, then the arbitrary character above it is matched, then a `_`, then a .NET balancing group is used to advance the match to the corresponding column on the next line, then then `|_|` is matched. The `&` stage modifier is used to allow the matches to overlap.
[Answer]
# x86-64 machine code, 31 bytes
```
31 F6 6A FF 59 B0 0A F2 AE AE 8B 57 FD 8A 14 0F 81 FA 5F 7C 5F 7C 75 02 FF C6 AE 76 ED 96 C3
```
[Try it online!](https://tio.run/##dVJNb6MwED17fsUsqwhoSNUvVSuS7KXnXnpaKYksYgy4AoMw2XUU8teXDpCkzaGSMZ55b94bxoiqmqVCdF1kCvTwzfHgNs3LbZRjAknIbFmjNCroN2DVzmQ4u59jVVZYCwusKP9ilAforrULrJaVlmhEZLbAxlcdDhwZ2wBXdaxmj5uxKs7HxJR0KCWKaiS53MUW3dZdLH71B06H@@dz6uEJ2HvvAUxpMXRlwpMVe99KrIFZkaWnpiPbN9WA76A/B2kbWWt0Xhw8KN1g4olSmwZFFtV4Y/z5EeAnyea7WOLCNLEqb7PfAF9ZjTQNuUmz2uASDzQw5Agtb8kjAAo5519DxCuUyMPi/RoQCoaHtyPpzBrAUfq6nFL4HXCq4FfAhftZcZxDP4AiUtrz4QAsoXu@mkaDIV6@1QdGHFbVVJR4zkSttRPQ@BqfpsqOcEHW@jUSmaILEmUsQ6eHeyNLs7oLcE9hXOLhTMfJ3cMfUtovPW@njUq1jAf/Gz/xV3Y63dCd4L9M5RK9Pf4gEfvy2IteFLyJwu2eOvWHniyBx677L5I8Sk03K56faKOfe0l8mX8A "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of a null-terminated byte string in RDI, and returns the number of cells in EAX. This requires the lines to be padded to the same length.
In assembly:
```
f: xor esi, esi # Set ESI to 0. ESI will count the cells.
push -1; pop rcx # Set RCX to -1.
mov al, '\n' # Set AL to the ASCII code of the line feed.
repne scasb # Repeatedly compare AL with a byte from the string,
# advancing the pointer each time, until they match.
# Also count down RCX each time. This consumes the first line
# and makes RCX -(linelength+1), with linelength including \n.
scasb # Make one more comparison, advancing RDI once more.
r: mov edx, [rdi-3] # Load bytes from addresses RDI-3 to RDI into EDX.
mov dl, [rdi+rcx] # Replace the first of those bytes with one at address RDI+RCX,
# the position in the previous line above the third byte.
cmp edx, '_' | '|'<<8 | '_'<<16 | '|'<<24 # Compare EDX with the cell's bytes.
jne s # Jump to skip if they are not equal.
inc esi # (If equal) Add 1 to ESI.
s: scasb # Compare AL with a byte from the string; advance the pointer.
jbe r # Jump back, to repeat, if AL ≤ that byte (false only for 0).
xchg esi, eax # Switch the total from ESI into EAX.
ret # Return.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~19~~ 17 bytes
```
C6+¨pe11%ṅ⁋3l⁺↔SO
```
[Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDNivCqHBlMTEl4bmF4oGLM2zigbrihpRTTyIsIiIsIltcIiBfIF8gXCIsIFwifF98X3xcIiwgXCJ8X3xffFwiXSJd) or [verify test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQzYrwqhwZTExJeG5heKBizNs4oG64oaUU08iLCIiLCJbXCIgXyBcIixcInxffFwiXVxuW1wiX19fXCIsXCJ8X3xcIl1cbltcIiAgIFwiLFwifF98XCJdXG5bXCIgXyAgXyAgX18gX18gIFwiLFwifF98ICBffCAgX3xffHxcIl1cbltcIiBfICAgXCIsXCJ8X3xfIFwiLFwifF98X3xcIl1cbltcIiBfICAgXCIsXCJ8IHxfIFwiLFwifF98X3xcIl1cbltcIiBfICAgXCIsXCJ8X3xfIFwiLFwifF9fX3xcIl1cbltcIiBfIF8gXCIsXCJ8X3xffFwiLFwifF98X3xcIl0iXQ==).
-2 bytes thanks to Command Master
[Answer]
# [J](https://www.jsoftware.com), 30 bytes
```
[:+/@,2 3('._.\|_\|'rxE,);._3]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxL9pKW99Bx0jBWENdL14vpiY-pka9qMJVR9NaL944FqLo5gdNLj8nPQUktZhKMVTUxNeo61oZKhgrmCiYVsNUpSZn5CukKcQCeUYKsSAnGXApxCuAUTwQcQG1AZlgHF9Tw6XJhUMLSCGEqFEgrCoeryqouhooqakA8feCBRAaAA)
*+1 thanks to Neil for spotting a subtle bug*
* `2 3...;._3]` Looks at all 2 x 3 squares
* `('._.\|_\|'rxE,)` Checks if the flatten regex matches the required pattern
* `[:+/@,` Sums the matches
[Answer]
# [Ruby](https://www.ruby-lang.org/), 78 bytes
```
->l{a,*l=l;g=0;l.sum{|b|w=a.chars.count{"#{b[g,3]}#{a[g+=1]}"=="|_|_"};a=b;w}}
```
[Try it online!](https://tio.run/##FclBCoMwEADAr8h6s2mweAzrR0IIG8F4SFW0IZTNvj2lc50rh29bsT3nxKSGhMlEHE3Sd35zDbUg6WWj69bLkfcPQ8/BRjU56ZlsfODLCSBC9dWDGMJgikg7u9Va6Dyo/4Bz7Qc "Ruby – Try It Online")
[Answer]
# [lin](https://github.com/molarmanful/lin), 54 bytes
```
2`xp"`,*3`xp \; `'"`', \+ `/
`,* `flat `_`"._.\|_\|"?t
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Takes a list of equal-sized space-padded strings.
For testing purposes, the code below auto-converts a space-padded multiline string:
```
\@..
_ _ __ __
|_| _| _|_||
@ >ls ; outln
2`xp"`,*3`xp \; `'"`', \+ `/
`,* `flat `_`"._.\|_\|"?t
```
## Explanation
Prettified code:
```
2`xp ( `,* 3`xp \; `' ) `', \+ `/
`,* `flat `_` "._.\|_\|"?t
```
* `2`xp (...) `',` pairwise flatmap...
+ ``,* 3`xp \; `'` zip and triplet-wise map...
- ``,* `flat `_`` zip, flatten, convert to string
- `"._.\|_\|"?t` check if matches regex `/._.\|_\|/`
* `\+ `/` sum
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ 20 bytes
```
Ji6\^[aJa;0J0]_Z+4=z
```
Input is a 2-dimensional char array (rows should be righty-padded with spaces so that they have the same length).
[Try it online!](https://tio.run/##y00syfn/3yvTLCYuOtEr0drAyyA2PkrbxLbq//9o9fj4eHVrBfWa@Br1WAA) Or [verify all test cases](https://tio.run/##y00syfmf8N8r0ywmLjrRK9HawMsgNj5K28S26r97srqCelJlhEtURcj/aHWFeAUFdWsF9Zr4GgX1WK5o9fj4eFQBIANMg1SCUDwIwZUoQHB8DUIRTA5uTjy6nAIeOYQ@BYQcsnKEPgA) (this displays each input together with output, for convenience).
### How it works
Modulo 6 is applied to (the ASCII code of) the chars in the input, which gives `5` for `_`, `4` for `|` and `2` for . Element-wise exponentiation with the imaginary unit `j` respectively gives `j`, `1` and `-1`.
Two-dimensional convolution is then used to detect the desired pattern, using the matrix `[-1, j, -1; 0, j, 0]` as kernel (note that convolution flips the kernel in both directions). The pattern is detected whenever the convolution gives exactly `4`. Thus the final result is the number of times that `4` appears in the convolution output.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
WS⊞υιIΣEυ∧κLΦ⌕Aι|_|⁼_§§υ⊖κ⊕λ
```
[Try it online!](https://tio.run/##RYzNCsIwEITvfYolpw3EJ@ip@AMFhUIfIIR2McF0rWmiHvruMYI/e5iBmdlvsCYMV@NzfljnCbDlOcU@BsdnlBK6tFhMCpysq66EEbdmidinCU9mfjcNj3hRcCQ@R4sH5yOFYjw23qNTIFa9Cqlgf0vGLyi0KD@x5ZGe@PWC2dEQaCKOVHCy7Fv@B17@rs4ZNOiqUPX60by5@xc "Charcoal – Try It Online") Link is to verbose version of code. Assumes input is a rectangular list of newline-terminated strings. Explanation:
```
WS⊞υι
```
Input the strings into an array.
```
υ Array of strings
E Map over strings
κ Current index
∧ Logical And
⌕A All overlapping matches of
|_| Literal string `|_|`
ι In current string
Φ Filtered where
υ Array of strings
§ Indexed by
κ Outer index
⊖ Decremented
§ Indexed by
λ Current match position
⊕ Incremented
⁼ Is equal to
_ Literal string `_`
L Take the length
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Dyalog APL](https://www.dyalog.com/products.htm), 23 bytes
```
≢∘⍸1↓'|_|'∘⍷∧¯1⊖1⌽'_'∘=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWtxiD0h61TXjUuehRx4xHvTsMH7VNVq-Jr1EHc7c_6lh-aL3ho65pho969qrHg0RtuR71TQVqSYNQRgrGCo96t6grxCuAtGGXjI-Pxy2poIBVp6EJ1FgwigchkDogG4zja9C1GCuYwlwCVgl2EIbBqKoUiFIFMSsenyqoMRCzIEELDWFYSAMA)
This is an alternative to [Adám’s ⌺-based solution](https://codegolf.stackexchange.com/a/250114) that is exactly as long but quite a bit faster:
```
f←≢∘⍸{'_||_'≡2↓,¯1⌽⍵}⌺2 3
g←≢∘⍸1↓'|_|'∘⍷∧¯1⊖1⌽'_'∘=
m←(,⍨1e3)⍴' _|'[?1e6⍴3]
'cmpx'⎕CY'dfns'
cmpx'f m' 'g m'
f m → 2.1E0 | 0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕
g m → 4.0E¯3 | -100%
```
The basic idea is to find where the top parts (`_`) and the bottom parts (`|_|`) of the squares are, align them, and count how many times they overlap.
We’ll use a modified version of the fifth test case as an example:
```
⎕←m←3 5⍴'__|_||_|_ |_|_|'
__|_|
|_|_
|_|_|
```
First we find where the `|_|`s are:
```
('|_|'∘⍷)m
0 0 1 0 0
1 0 0 0 0
1 0 1 0 0
```
The 1s indicate where the `|_|`s begin. This means that the rightmost two columns will always consist of 0s.
Then we find where the `_`s are:
```
('_'∘=)m
1 1 0 1 0
0 1 0 1 0
0 1 0 1 0
```
We need to move the 1s one step to the left and one step downwards to align them with the 1s in the `|_|` matrix, then AND the two matrices.
We can move the 1s one step to the left by rotating once along the last axis:
```
(1⌽'_'∘=)m
1 0 1 0 1
1 0 1 0 0
1 0 1 0 0
```
The leftmost column wraps around to the right, creating an extra 1 in the rightmost column. Fortunately, this doesn’t matter because the corresponding column in the `|_|` matrix must consist of 0s, so this column will get masked out anyway.
Next we move the 1s one step downwards by doing a -1 rotate along the first axis:
```
(¯1⊖1⌽'_'∘=)m
1 0 1 0 0
1 0 1 0 1
1 0 1 0 0
```
Now the 1s are aligned, but the bottommost row wraps around to the top, creating extra 1s in the topmost row. This is a problem because the corresponding row in the `|_|` matrix can contain 1s. We can fix this by dropping the topmost row after ANDing the two matrices:
```
('|_|'∘⍷∧¯1⊖1⌽'_'∘=)m
0 0 1 0 0
1 0 0 0 0
1 0 1 0 0
(1↓'|_|'∘⍷∧¯1⊖1⌽'_'∘=)m
1 0 0 0 0
1 0 1 0 0
```
Finally, we count the number of 1s:
```
(≢∘⍸1↓'|_|'∘⍷∧¯1⊖1⌽'_'∘=)m
3
```
] |
[Question]
[
For the purpose of this challenge, a Prime Power of a Prime (PPP) is defined as a number that can be defined as a prime number to the power of a prime number. For example, 9 is a PPP because it can be represented as 3^2. 81 on the other hand is not a PPP because it can only be represented as 3^4, and 4 is not prime. The first few PPPs are: 4, 8, 9, 25, 27, 32, 49, 121, 125, 128, 169, 243, 289, 343... This is OEIS sequence [A053810](http://oeis.org/A053810)
## Your Task:
Write a program or function that for an input integer n returns/outputs the nth PPP, either 1-indexed or 0-indexed, whichever you prefer.
## Input:
An integer between 0 and 1,000, received through any reasonable method.
## Output:
The PPP at the index indicated by the input.
## Test Cases:
These are 1-indexed, and so, if your program takes 0-indexed input, the same output should be arrived at for the stated input - 1.
```
3 -> 9
6 -> 32
9 -> 125
```
## Scoring:
This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"),lowest score in bytes wins!
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~9~~ 7 bytes
*Saved 2 bytes thank to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)*
```
µNÓ0Kp»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/w5MNvAsO7f7/3xIA "05AB1E (legacy) – Try It Online")
```
µ # while counter_variable != input:
N # push iteration counter e.g. 125
Ó # get prime exponents -> [0, 0, 3]
0K # filter out zeros -> [3]
p # is prime? -> [1]
» # join with newlines: we use » instead of J
# so that [0,1] is not interpreted as truthy -> 1
# implicit: if 1, increment counter_variable
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!fȯṗ§*ELpN
```
[Try it online!](https://tio.run/##ASAA3/9odXNr/yBt4oKB4bijMTD/IWbIr@G5l8KnKkVMcE7//w "Husk – Try It Online")
## Explanation
```
!fȯṗ§*ELpN Implicit input.
f N Filter the natural numbers by this function:
ȯṗ§*ELp Argument is a number, say 27.
p Prime factors: [3,3,3]
L Length: 3
E Are all elements equal: 1
§* Multiply last two: 3
ȯṗ Is it prime? Yes, so 27 is kept.
! Index into remaining numbers with input.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~95~~ ~~85~~ 80 bytes
*-10 bytes thanks to @Lynn*
*-5 bytes thanks to @WillNess*
0-based
```
(!!)[x|x<-[2..],p<-[[i|i<-[2..x],all((>)2.gcd i)[2..i-1]]],or[y^e==x|e<-p,y<-p]]
```
[Try it online!](https://tio.run/##LU29CoMwGNx9iq/gkIAJ1FG00KFD545pCkGjhiYxxFAUfPamar3h/ji4XoxvqXVUxg0@wGMegzT0Zj/KD9ZIG1Anw9V3I06StnpGdDphNi1TSVhOKc/capha1D9PPBNaI3TBOe3qBhTeWkXOnPNs8Gx@yaqaFlkSl80rcR6NULaCZkhgh1ivoCRwvB6t88qGtAXkpWgghX6TfVoUcLcBx5h/61aLboykdu4H "Haskell – Try It Online")
**Explanation**
```
(!!) -- point-free expression, partially evaluate index-access operator
[x|x<-[2..] -- consider all integers x>=2
,p<- -- let p be the list of all primes <=x
[[ -- list of a list so p ends up as a list
i|i<-[2..x], -- consider all i<=x to be potentially prime
all((>)2.gcd i)[2..i-1] -- if the gcd of i with all smaller integers is
-- smaller than 2 then this i is actually prime
]],or -- if any of the following list entries is true
[y^e==x| -- the condition y^e==x holds for x with ...
e<-p,y<-p] -- y and e being prime, i.e. x is a PPP,
] -- then add this x to the output sequence / list
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 14 bytes
Based on [Mr. Xcoder's Pyth solution](https://codegolf.stackexchange.com/a/144596/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##S0wuKU3Myan8/9@6tOjRzKYA60cdMx/1LMh81Lj/Uc9C32DX//8tAA "Actually – Try It Online")
```
;ur♂P;∙⌠iⁿ⌡MSE
```
**Ungolfing**
```
Implicit input n
;ur Duplicate and push [0..n]
♂P Push the 0th to nth primes
;∙ Push Cartesian square of the primes
⌠iⁿ⌡M Reduce each list in the Cartesian square by exponentiation
SE Sort the list and get the nth index (0-indexed)
```
[Answer]
# Mathematica, 48 bytes
```
Sort[Join@@Array[(p=Prime)@#^p@#2&,{#,#}]][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzi/qCTaKz8zz8HBsagosTJao8A2oCgzN1XTQTmuwEHZSE2nWllHuTY2NjpaOTZW7T9QMq9EwSE92jL2/38A "Wolfram Language (Mathematica) – Try It Online")
but Martin Ender had a better idea and saved 6 bytes
# Mathematica, 42 bytes
```
Sort[Power@@@Prime@Range@#~Tuples~2][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzi/qCQ6IL88tcjBwSGgKDM31SEoMS891UG5LqS0ICe1uM4oNjpaOTZW7T9QNq9EwSE92jL2/38A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 10 bytes
1 byte thanks to Dennis.
```
ÆN€*þ`FṢị@
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//w4ZO4oKsKsO@YEbhuaLhu4tA////OQ "Jelly – Try It Online")
[Answer]
# [R](https://www.r-project.org/) + numbers, 57 bytes
```
function(n,x=numbers::Primes(2*n))sort(outer(x,x,"^"))[n]
```
[Try it online!](https://tio.run/##BcHBCoAgDADQf/G0xQ7VUfAfukdBhYKQU6aCff16TzQ4DZ2fFjMD03Dc0@2lWrtJTL7COjFizdIg9@YFBg0yp0Hc@dB6lfJ@sNhlpoD6Aw "R – Try It Online")
`outer` is such a handy function.
Fairly certain this will always work. Will make a formal argument when I have the time.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~163~~ ~~157~~ ~~137~~ 136 bytes
* Saved six bytes by using `input()` rather than defining a function.
* Saved four bytes thanks to [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista); merging two loops.
* Saved sixteen bytes thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only).
* Saved a byte thanks to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo).
```
p=input();r=i=0;e=lambda p:all(p%d for d in range(2,p))
while~-i<p:
r+=1
for x in range(r*r):y=x%r;x/=r;i+=x**y==r>e(x)>0<e(y)
print r
```
[Try it online!](https://tio.run/##RY7LDoIwEADv@xWbJiQtaAR8U5YLX4JSpQmWZoOxXPx1VC4eJ5lMxk9jN7h8rkkIMXuyzj9HqTSTpVQb6pvHpW3QF03fSx@1eBsYW7QOuXF3I/OVVwpene3Ne21LXwByQhksXvh7HLMqJgoR67Ah1jahEMcTEVdGBlWlpZGTAs/Wjcjzd0abYK5iKWNd/ABrMaeQQQ5b2MEeDnCEE5w/ "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes
```
{⍵⌷∧∊∘.*⍨¯2⍭⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHPdsfdSx/1NH1qGOGntaj3hWH1hs96l37qHczULL2f9qjtgmPevse9U319H/U1XxovfGjtolAXnCQM5AM8fAM/p@mYMyVpmAGxJYA "APL (Dyalog Extended) – Try It Online")
**Explanation**
```
{⍵⌷∧∊∘.*⍨¯2⍭⍳⍵}
⍵ Right argument. Our input.
{ } Wraps the function in dfn syntax which allows us to use ⍵.
⍳ Range [1..⍵].
¯2⍭ Get the n-th prime for each n in the range.
∘.*⍨ Get the prime powers of each prime.
∊ Flatten the list.
∧ In Extended, this is monadic sort ascending.
⍵⌷ Get the input-th index of the list of prime powers of primes.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
e.f/^FR^fP_TSZ2
```
**[Try it here!](https://pyth.herokuapp.com/?code=e.f%2F%5EFR%2aKfP_TSZK&input=6&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0)** or **[Verify more test cases.](https://pyth.herokuapp.com/?code=e.f%2F%5EFR%2aKfP_TSZK&input=3&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0)**
## Explanation
```
e.f/^FR^fP_TSZ2 - Full program. Q means input.
.f - First Q inputs with truthy results. Uses the variable Z.
fP_TSZ - Filter the range [1, Z] for primes.
^ 2 - Cartesian square. Basically the Cartesian product with itself.
^FR - Reduce each list by exponentiation.
/ - Count the occurrences of Z in ^.
e - Last element.
```
[Answer]
# Javascript 137 133 bytes
```
P=n=>{for(p=[i=2];j=++i<n*9;j^i&&p.push(i))
for(;j*j<=i;)j=i%++j?j:i
x=[]
for(i of p)
for(j of p)
x[i**j]=1
return Object.keys(x)[n]}
console.log(P(1000))
console.log(P(800))
console.log(P(9))
console.log(P(5))
```
\*\*normal algorithem(100ms result)
P =n =>
{
```
for(p=[i=2];f=++i<=n*10;!f||p.push(i))
for(j=0;f&&(x=p[j++])*x<=i;)
f=i%x
x=[]
T=0
for(i of p)
for(j of p)
{
l= i**j
if(++T>n &&x.length<l )
break
x[l] = 1
}
return Object.keys(x)[n]
}
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 50 bytes
```
{(sort [X**] (^7028,^24)>>.grep(&is-prime))[$_-1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplmj7v1qjOL@oRCE6QksrVkEjztzAyEInzshE085OL70otUBDLbNYt6AoMzdVUzNaJV7XMLb2f3FipYJaooahpjUXlGmEYBojmCYIpqGBgYHmfwA "Perl 6 – Try It Online")
```
(^7028,^24) # create 2 ranges from 0
>>.grep(&is-prime) # grep for primes in both
[X**] ... # calc each exponential pair (2^2, 2^3, 2^5...)
(sort ... )[$_-1] # sort and get value at index n-1
```
The reasons for the 24 and 7028 are that the largest value (n=1000) is 49378729, which is 7027^2, and the largest prime power of 2 which fits under that is 23. So covering 2..7027 ^ 2..23 includes all the items in the first 1000 (and a lot of spares).
[Answer]
# Pyth - 13 bytes
```
e.f&P_lPZ!t{P
```
[Test Suite](http://pyth.herokuapp.com/?code=e.f%26P_lPZ%21t%7BP&test_suite=1&test_suite_input=1%0A3%0A5%0A9&debug=0).
[Answer]
# Java 8, 211 bytes
```
import java.util.*;n->{List l=new Stack();for(int a=2,b;a<132;a++)for(b=2;b<132;b++)if(p(a)*p(b)>0)l.add(Math.pow(a,b));Collections.sort(l);return l.get(n);}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}
```
Very inefficient method.. It basically calculates all PPP's from 22 through ~~999999~~ 132132 and stores it in a List, then sorts that List, and then gets the `n`'th item from that List.
EDIT: Instead of using 999999 which results in a List of 28,225 items, I now use 132132 which results in a List of just 1,024 items. This improves the performance quite a bit, and is perfectly acceptable since the challenge states we should support an input from index 0 through 1,000. (Changing `1e3` to `132` doesn't affect the byte-count, though.)
**Explanation:**
[Try it here.](https://tio.run/##fVFNTwIxEL3vr5iLSStQFowXy@LBq6AJR@OhXQoUutNmd1ZjyP52nEXUizHpR@a18/re6968mVFMDvfrw8lXKdYEe8ZUSz6oaw0A4zE8G4bjBmjnwH6QG5WxRcqyMpimgYXxeMwAPJKrN6Z0sOxLgCe7dyVBKfgEUGoGO548loBQwAlH8@OjbwhCge4dVmTKg5B6E@tziymmQ6vNbHIz1WYwkD1ui6m2Z8Qy4jciCSOvk7BynsugzHotFoZ2KsV3YYZWSv0QQ2AZPmKjGvYngtS1o7ZGCGrrSLCyLrs4XUaC9LfbXlG6WDl@S/Qsx89QY4FXfjCYTe7zO/zhR92dAFJrgy@hIUO8vUW/hoojEyuqPW5fXsHIr7z6IKHiYPow@kKcMwP4fS3X4GeTW17Z/VcXwOqjIVep2JJKTEkBRaVQce7yQtBl/96b5HkuL//TnT4B)
```
import java.util.*; // Required import for List, Stack and Collections
n->{ // Method with integer as parameter and Object as return-type
List l=new Stack(); // List to store the PPPs in
for(int a=2,b;a<132;a++) // Loop (1) from 2 to 1,000 (exclusive)
for(b=2;b<132;b++) // Inner loop (2) from 2 to 1,000 (exclusive)
if(p(a)*p(b)>0) // If both `a` and `b` are primes:
l.add(Math.pow(a,b)); // Add the power of those two to the List
// End of loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
Collections.sort(l); // Sort the filled List
return l.get(n); // Return the `n`'th item of the sorted List of PPPs
} // End of method
int p(int n){ // Separated method with integer as parameter and return-type
for(int i=2; // Index integer (starting at 2)
i<n; // Loop from 2 to `n` (exclusive)
n=n%i++<1? // If `n` is divisible by `i`:
0 // Change `n` to 0
: // Else:
n // Leave `n` the same
); // End of loop
return n; // Return `n` (which is now 0 if it wasn't a prime)
} // End of separated method
```
[Answer]
# PARI/GP, 48 bytes
```
f(n)=[x|x<-[1..4^n],isprime(isprimepower(x))][n]
```
If you do not count the `f(n)=` part, that is 43 bytes.
---
Another approach without the set notation which does not check so many unnecessary cases:
```
f(n)=c=0;i=1;while(c<n,i++;isprime(isprimepower(i))&&c++);i
```
[Answer]
# J, 21 bytes
```
{[:/:~@,[:^/~p:@i.@>:
```
Zero-indexed anonymous function.
[Try it online!](https://tio.run/##y/r/P03BVk@hOtpK36rOQSfaKk6/rsDKIVPPwc6KKzU5I18hTcEIxjCFMSxgDEtLy///AQ)
Trying to get back into the swing of things but I seem to have forgotten all tricks to make good monadic chains.
### Short explanation
Constructs a table of prime powers from the 0th prime to the prime at the index of the input plus 1 (to account for 0). Flattens this list and sorts it and then indexes into it. I realize now that this might give incorrect results for some values since the table might not be large enough -- in that case I'd edit in a hardcoded value like 1e4 which should suffice. I can't prove it one way or the other (it passes for the test cases given), so do let me know if this is an issue.
### Also 21 bytes
```
3 :'y{/:~,^/~p:i.>:y'
```
] |
[Question]
[
In mathematics, the factorial, shortened "fact" of a non-negative integer **n**, denoted by **n!**, is the product of all positive integers less than or equal to **n**. For example, **5!** is **1 \* 2 \* 3 \* 4 \* 5 = 120**
The factorial of **0** is **1**, according to the convention for an empty product.
---
These are the regular facts we are used to. Let's add some alternatives:
1. The factorial (defined above)
2. The double factorial: **n!! = 1 + 2 + ... + n**
3. The triple factorial: **n!!! = 1 - (2 - (3 - ( ... - n)))...)**
4. The quadruple factorial: **n!!!! = 1 / (2 / (3 ... / n)))...)**. Note: This is floating point division, not integer division.
---
### Challenge
Take a non-negative integer input **n**, directly followed by between **1** and **4** exclamation marks. The input will look (exactly) like this: **0!**, **5!!**, **132!!!** or **4!!!!**. In this challenge, you may not assume a flexible input format, sorry.
### Output
The output should be the result, on any convenient format. The result of the quadruple factorial must have at least 2 digits after the decimal point, except for **0!!!! = 0**.
### Test cases:
```
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
---
0!! = 0
1!! = 1
2!! = 3
3!! = 6
4!! = 10
5!! = 15
6!! = 21
7!! = 28
8!! = 36
9!! = 45
10!! = 55
---
0!!! = 0
1!!! = 1
2!!! = -1
3!!! = 2
4!!! = -2
5!!! = 3
6!!! = -3
7!!! = 4
8!!! = -4
9!!! = 5
10!!! = -5
---
0!!!! = 0
1!!!! = 1
2!!!! = 0.5
3!!!! = 1.5
4!!!! = 0.375
5!!!! = 1.875
6!!!! = 0.3125
7!!!! = 2.1875
8!!!! = 0.27344
9!!!! = 2.4609
10!!!! = 0.24609
```
The shortest solution in each language wins.
[Answer]
## JavaScript (ES6), 88 bytes
```
s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))
```
### Test cases
```
let f =
s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))
for(o = '!'; o <= '!!!!'; o += '!') {
for(n = 0; n <= 10; n++) {
console.log(n + o + ' = ' + f(n + o));
}
}
```
### Formatted and commented
```
s => // given the input string s,
eval( // evaluate as JS code:
( [a, b] = s.split(/\b/), // a = integer (as string) / b = '!' string
g = k => // g = recursive function taking k as input
+a ? // if a is not zero:
k - a ? // if k is not equal to a:
k + '_*+-/'[b.length] + // append k and the operation symbol
`(${g(k + 1)})` // append the result of a recursive call
: // else:
k // just append k and stop recursion
: // else:
+!b[1] // return 1 for multiplication / 0 otherwise
)(1) // initial call to g() with k = 1
) // end of eval()
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 15 bytes
```
§!ëΠΣF-F/#'!oṫi
```
[Try it online!](https://tio.run/##yygtzv6vkHtut/ajxg3aSgq2CkrFj5oagRzNc4sf7lyVoF2upKigCEJgrKiUW/yoYZmBgqHB/0PLFQ@vPrfg3GI3XTd9ZXXF/Ic7V2f@/w8A "Husk – Try It Online")
## Explanation
Indexing into a list of functions: the joys of using a functional language.
```
§!ëΠΣF-F/#'!oṫi Implicit input, say x = "6!!!"
i Convert to integer (parses the leading sequence of digits): 6
oṫ Descending range to 1: y = [6,5,4,3,2,1]
ë Four-element list containing the functions
Π product,
Σ sum,
F- left fold with subtraction (gives 0 for empty list), and
F/ left fold with division (gives 0 for empty list).
! 1-based index into this list with
#'! count of !-characters in input: gives F-
§ Apply to y and print implicitly: -3
```
I use a descending range and left folds, since `-` and `/` take their arguments in reverse order in Husk.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 134 130 128 bytes
```
s=>{double e=s.Split('!').Length,n=int.Parse(s.Trim('!')),i=n,r=n;for(;--i>0;)r=e>4?i/r:e>3?i-r:e>2?i+r:i*r;return n<1&e<3?1:r;}
```
[Try it online!](https://tio.run/##1Y@xTsMwEIb3PMU1A01IHBrKVMfJgMRUpEpFYkAMIXXDSamNzi4SqvrswWkrIK2EWBh6g@98vv/3d5VhlSbZgouqKY2BGemaypXXdTa7swtjS4sVvGtcwH2JKjCWUNVPz1BSbcKvuW9FF/MPY@UquVurKtsLYljo9Usjc1iC8Foj8s2@AVKYZP7WoA2Gg2GYTKWq7WusBCqbzEoyMjDJA@Fq9xzGKFRMQvGlpoAzhvmIhyRkflPgFU1kPi6Qdfm6wIgmeEmcpF2TApWlFzIbF@mE@LblXg/YuUHgfgQEASPuUgZp6nIUhb3B/p4/dr3VyuhGJo@EVk5RyQAhAn/g/HxXLA9XPwx5z2Lr/cnMZ4z5R9L/gz6mPhfsE@6zAT8l/w19X23bTw "C# (.NET Core) – Try It Online")
The best part of code golfing are the things you learn while trying to solve the challenges. In this one I have learnt that in C# you can trim other characters besides whitespaces from strings.
* 4 bytes saved thanks to LiefdeWen!
* 2 bytes saved because I do not need to substract 1 to `s.Split('!').Length`, just fix the limits in `e>4?i/r:e>3?i-r:e>2?i+r:i*r` and `n<1&e<3?1:r`.
[Answer]
# [Perl 5](https://www.perl.org/), 62 bytes
**61 bytes code + 1 for `-p`.**
```
$_=/^0!$/+eval join(qw{| *( +( -( /(}[s/!//g],1..$_).")"x--$_
```
Thanks to [@G B](https://codegolf.stackexchange.com/users/18535/g-b) for pointing out a miss on my part!
[Try it online! (this uses `-l` for readability)](https://tio.run/##LczLDoIwEIXh/TxFh3RRxLag4mXhkxhtXBCDIYBi1ER9dSsz4/r83@mra1PGqMPWH3LUPqvux0adu7o1l8frrSZGZUZZo7z57AaP3p/208I5HVKXpMnTWh1izBEKhBnCHGGBUCIsEVYIa4TNOI1zjpRQQxFVlFFHIZWUcssx15xzz4AFEzaMWAkTJ1CkULGCRQsXLwf/B/x2/a3u2iHavvkB "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~113~~ 111 bytes
```
function(s){z=strtoi((n=strsplit(s,'!')[[1]])[1])
n=length(n)
`if`(z,Reduce(c('*','+','-','/')[n],1:z,,T),n<2)}
```
[Try some test cases!](https://tio.run/##fcvBCoMwEATQu1@hXrLbrlR78CD6E6U3ERSbtAFZg4mHWvrtaUqvxcMMA49ZvIrrLPZq5dHpmcHia2usW9ysAfi7rJm0A0siEdi2RddhKIy4mSTf3QMYo16rHja6yNs6ShhBHASJY0gWcgo37qioNqIrEtdnfHs7GDM9wQzWyRzyqqQ4TVIkhdFf2rV9/Kn/AA)
ungolfed:
```
function(s){
n <- strsplit(s,"!")[[1]] # split on "!"
z <- strtoi(n[1]) # turn to integer
n <- length(n) # count number of "!"
FUN <- c(`*`,`+`,`-`,`/`)[[n]] # select a function
right <- TRUE # Reduce (fold) from the right
if( z > 0) # if z > 0
Reduce(FUN, 1:z,,right) # return the value
else
(n < 2) # 1 if n = 1, 0 if n > 1
}
```
[Answer]
# Python3, 124 130 ~~121~~ 119 bytes
At this point, I believe that recursion is the key to further byte saving.
```
s=input()
l=s.count('!')
v=int(s[:-l])+1
print(eval((" *+-/"[l]+"(").join(map(str,range(1,v)))+")"*(v-2)or"0")+(l<2>v))
```
Try the testcases on [Try it online!](https://tio.run/##Lc69boMwFIbhuecqOF5yHEIaSH9R6ZauXbpFGRC1GioXW7ahydVTjt3R@t7Htr2Gsxn2c2c@VSOEmH3TD3YMJEE3ftuZcQi0wpWEaRkC@WNd6JPMS7COz2pqNZHI1nlxK476lAsScvtt@oF@Wks@uI1rhy9F5WaSUuZCijVNRSWNEzshc9Iv1euyzMvbENy1hpvfc69V9uFGVauL6oi/JkFdOmVDdnh/OzhnXJ3Z1vt5h1AiVAh7hDuEe4QHhEeEJ4TnZVrmHXLCDUdcccYdh1xyGtsYxzrmsY8gikiiiSiqxJJLMMlEk0046cSTTxf834B/)
-9 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)!
-2 bytes thanks to [@Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista)!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~34~~ 30 bytes
```
+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!
```
[Try it online!](https://tio.run/##K6gsyfj/X7u0TFvbw0FJX0tbV0k/MEbRPb4k1FuvLNC7UMlA8f9/JUMDRSBQAgA "Pyth – Try It Online")
### Explanation
```
+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!"Q Implicit: append "Q
Implicit: read input to Q
.vQ Evaluate Q as Pyth code. This evaluates the integer,
any !'s are parsed as unary NOT for the next expression
and discarded.
K Save the result to K.
U Get a list [0, 1, ..., K-1].
t Drop the first item to get [1, 2, ..., K-1].
_ Reverse to get [K-1, K-2, ..., 1].
u K Starting from G = K, for H in [K-1, K-2, ..., 1] do:
/Q\! Count the !'s in Q.
@"/*+-" Get the correct operator.
+H Prepend the current H.
+ G Append the previous value G.
v Evaluate as Python code.
q"0!"Q See if Q == "0!".
+ If so, add 1.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
þL"/*+-"¹'!¢©è".»"ì.VD_нi®Θ
```
[Try it online!](https://tio.run/##ATEAzv8wNWFiMWX//8O@TCIvKistIsK5JyHCosKpw6giLsK7IsOsLlZEX9C9acKuzpj//zAh "05AB1E – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~83 80~~ 79 bytes
```
->s{z=s.count ?!;s<?1?1+1<=>z:eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)}
```
[Try it online!](https://tio.run/##LcxJDoJAEIXhfZ3CIi6AlpZ2HsA@CCFGjUYTFWI7RByujlSV6/d/73JbP@tdWkcL96pSpzfF7XxtWZy7xBprlEnSRTXb3ldHPwuN1o@muRbLQx76no495S1DFXW9rMqV9QNlg/AbPYJP3U70aVW@3u5dtrLmdl@cys4uc3n@qWMEg9BD6CMMEIYII4QxwgRh2kzNHCMl1FBEFWXUUUglpdxyzDXn3DNgwYQNI1bCxAkUKVSsYNHCxcvB/wF/ "Ruby – Try It Online")
### Explanation:
```
->s{
# Get number of !
z=s.count ?!
# Special case: if the number is 0, then output 0 or 1 depending on z
s<?1?1+1<=>z:
# Otherwise build the full expression as a string and then evaluate it
eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)
}
```
[Answer]
# Java 8, ~~141~~ ~~136~~ 134 bytes
```
s->{float q=s.split("!",-1).length,n=new Float(s.split("!")[0]),i=n,r=n;for(;--i>0;r=q<3?i*r:q<4?i+r:q<5?i-r:i/r);return n<1&q<3?1:r;}
```
-5 bytes (141 → 136) thanks to [*@CarlosAlejo*'s C# answer](https://codegolf.stackexchange.com/a/137334/52210).
**Explanation:**
[Try it here.](https://tio.run/##dVBNU8IwEL3zK9YenMZ@SEe9NA3cvMGFI@MhloALZVuSgDpMf3tNbQ4oOpOP2d03b997W3mSSd0o2q52XVlJY2Amkc4jACSr9FqWCuZ9CbCuammhDBdWI23AMO7arbvuGCstljAHAgGdSSbnAX0QJjVNhTYMboI4yVhaKdrYt5gEqXd47kHhBYQtxy8sRkGxFsTXtQ55kuBkzLU4FA9TvNP5oXicYtT/T1NMdI73mnGt7FETUJHd9rgs17zt@KCtOb5WTpuXeKpxBXvn0ftYvoBkg0GrzCCCX5ZX9XXDd3wWjcaTtOrHwm@oD059uKD3blbTTOqd8dt7sy5zQDHmWIjMvVHkZwCLT2PVPq2PNnX8ZCsKMfrNFAU5BBGl5R8z5kW3o3/ovIW2@wI)
```
s->{ // Method with String parameter and float return-type
float q=s.split("!",-1).length, // Amount of exclamation marks + 1
n=new Float(s.split("!")[0]),
// The number before the exclamation marks
i=n, // Index (starting at `n`)
r=n; // Return sum (starting at `n`)
for(;--i>0; // Loop from `i-1` down to 1
r= // Change the result (`r`) to:
q<3? // If `q` is 2:
i*r // Multiply
:q<4? // Else if `q` is 3:
i+r // Addition
:q<5? // Else if `q` is 4:
i-r // Subtraction
: // Else (if `q` is 5):
i/r // Division
); // End of loop
return n<1&q<3? // Edge case if the input is `0!`:
1 // Then return 1
: // Else:
r; // Return the result
} // End of method
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24 23 26~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+~~3~~ 2 bytes patching up to fix after misinterpretation :(
```
×
+
_
÷
ṣ”!µḢVRṚȯL©Ị$®ŀ@/
```
A full program (a monadic link with helper links referenced by program location)
**[Try it online!](https://tio.run/##ATcAyP9qZWxsef//w5cKKwpfCsO3CuG5o@KAnSHCteG4olZS4bmayK9Mwqnhu4okwq7FgEAv////MTAh "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8///wdC5trniuw9u5Hu5c/KhhruKhrQ93LAoLerhz1on1PodWPtzdpXJo3dEGB/3/jxrmKAIBUJF1zMOdax81rTk8AUgYGj7cse3QkqiHu/rcgNxDW4/uOdwOZGQBMVCLgq6dAlBL5P//AA "Jelly – Try It Online").
### How?
```
× - Link 1, multiply: number, number
+ - Link 2, add: number, number
_ - Link 1, subtract: number, number
÷ - Link 1, divide: number, number
ṣ”!µḢVRṚȯL©Ị$®ŀ@/ - Main link: list of characters, a
ṣ”! - split s at '!' characters
µ - monadic separation, call that b
Ḣ - head - pop and yield the digit list from b, modifying b
V - evaluate as Jelly code (get the number, say N)
R - range = [1,2,3,...,N]
Ṛ - reverse = [N,...,3,2,1]
$ - last two links as a monad:
L - length of modified b (number of '!' characters)
© - (copy to register)
Ị - insignificant? (1 when just one '!', 0 when two or more)
ȯ - logical or (1 for "0!", 0 for "0!!...", the reversed-range otherwise)
/ - cumulative reduce by:
@ - with swapped arguments:
ŀ - dyadic call of link at index:
® - recall value from register (number of '!' characters)
```
[Answer]
# Self-modifying x86\_64 machine code, 123 bytes
```
0f b6 0f 31 c0 eb 11 0f be c9 8d 04 80 8d 44 41 d0 0f b6 4f 01 48 ff c7 83 f9 21 75 ea b9 21 21 21 a1 33 0f 0f bc c9 81 c1 ff 07 00 00 c1 e9 03 0f b6 c9 89 ca 09 c2 74 35 55 48 89 e5 c7 45 fc 59 58 5c 5e 8a 4c 0d fc 88 0d 15 00 00 00 f3 0f 2a c8 83 f8 02 5d 7c 1f ff c8 0f 57 c0 f3 0f 2a c0 f3 0f 5e c1 83 f8 01 0f 28 c8 7f eb c3 f3 0f 10 05 03 01 00 00 c3 0f 28 c1 c3
```
Why would interpreted languages be able to dynamically run code with fancy `eval`s, but not plain machine code?
Try it with:
```
#include <stdio.h>
#include <sys/mman.h>
#include <errno.h>
char ff[] = "\x0f\xb6\x0f\x31\xc0\xeb\x11\x0f\xbe\xc9\x8d\x04\x80\x8d\x44\x41\xd0\x0f\xb6\x4f\x01\x48\xff\xc7\x83\xf9\x21\x75\xea\xb9\x21\x21\x21\xa1\x33\x0f\x0f\xbc\xc9\x81\xc1\xff\x07\x00\x00\xc1\xe9\x03\x0f\xb6\xc9\x89\xca\x09\xc2\x74\x35\x55\x48\x89\xe5\xc7\x45\xfc\x59\x58\x5c\x5e\x8a\x4c\x0d\xfc\x88\x0d\x15\x00\x00\x00\xf3\x0f\x2a\xc8\x83\xf8\x02\x5d\x7c\x1f\xff\xc8\x0f\x57\xc0\xf3\x0f\x2a\xc0\xf3\x0f\x5e\xc1\x83\xf8\x01\x0f\x28\xc8\x7f\xeb\xc3\xf3\x0f\x10\x05\x03\x01\x00\x00\xc3\x0f\x28\xc1\xc3";
int main()
{
char* page = (char*)((unsigned long)((char*)ff) & (~0xfffLL));
if (mprotect(page, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) {
perror("mprotect");
return -1;
}
float (*f)(char*) = (float (*)(char*))ff;
char* testcases[] = { "0!","1!","2!","3!","4!","5!","6!","7!","8!","9!","10!",
"0!!","1!!","2!!","3!!","4!!","5!!","6!!","7!!","8!!","9!!","10!!",
"0!!!","1!!!","2!!!","3!!!","4!!!","5!!!","6!!!","7!!!","8!!!","9!!!","10!!!",
"0!!!!","1!!!!","2!!!!","3!!!!","4!!!!","5!!!!","6!!!!","7!!!!","8!!!!","9!!!!","10!!!!",
};
for (int i = 0; i < 44; i++) {
printf("%s -> %f\n", testcases[i], f(testcases[i]));
}
}
```
Assembly:
```
_f:
100000d4f: 0f b6 0f movzx ecx, byte ptr [rdi]
100000d52: 31 c0 xor eax, eax
100000d54: eb 11 jmp 17 <_f+18>
100000d56: 0f be c9 movsx ecx, cl
100000d59: 8d 04 80 lea eax, [rax + 4*rax]
100000d5c: 8d 44 41 d0 lea eax, [rcx + 2*rax - 48]
100000d60: 0f b6 4f 01 movzx ecx, byte ptr [rdi + 1]
100000d64: 48 ff c7 inc rdi
100000d67: 83 f9 21 cmp ecx, 33
100000d6a: 75 ea jne -22 <_f+7>
100000d6c: b9 21 21 21 a1 mov ecx, 2703302945
100000d71: 33 0f xor ecx, dword ptr [rdi]
100000d73: 0f bc c9 bsf ecx, ecx
100000d76: 81 c1 ff 07 00 00 add ecx, 2047
100000d7c: c1 e9 03 shr ecx, 3
100000d7f: 0f b6 c9 movzx ecx, cl
100000d82: 89 ca mov edx, ecx
100000d84: 09 c2 or edx, eax
100000d86: 74 35 je 53 <_f+6E>
100000d88: 55 push rbp
100000d89: 48 89 e5 mov rbp, rsp
100000d8c: c7 45 fc 59 58 5c 5e mov dword ptr [rbp - 4], 1583110233
100000d93: 8a 4c 0d fc mov cl, byte ptr [rbp + rcx - 4]
100000d97: 88 0d 15 00 00 00 mov byte ptr [rip + 21], cl
100000d9d: f3 0f 2a c8 cvtsi2ss xmm1, eax
100000da1: 83 f8 02 cmp eax, 2
100000da4: 5d pop rbp
100000da5: 7c 1f jl 31 <_f+77>
100000da7: ff c8 dec eax
100000da9: 0f 57 c0 xorps xmm0, xmm0
100000dac: f3 0f 2a c0 cvtsi2ss xmm0, eax
100000db0: f3 0f 5e c1 divss xmm0, xmm1
100000db4: 83 f8 01 cmp eax, 1
100000db7: 0f 28 c8 movaps xmm1, xmm0
100000dba: 7f eb jg -21 <_f+58>
100000dbc: c3 ret
100000dbd: f3 0f 10 05 03 01 00 00 movss xmm0, dword ptr [rip + 259]
100000dc5: c3 ret
100000dc6: 0f 28 c1 movaps xmm0, xmm1
100000dc9: c3 ret
```
Explanations will be added later. The basic idea is to modify the `divss xmm0, xmm1` instruction at `0x100000db0` and replace it with a `mulss`, `addss`, `subss` or `divss` according to supplied operand. A small trick is also used to parse the input string.
Assembly generated with:
```
float f (char* s)
{
int x;
for (x=0; *s != '!'; s++) {
x=10*x + (*s-'0');
}
unsigned char op = (__builtin_ctz(*(unsigned int *)s ^ 0xa1212121)-1) >> 3;
if (x == 0 && op == 0) {
return 1;
}
unsigned int lookup = 0x5e5c5859;
unsigned char new_code = ((unsigned char*)&lookup)[op];
asm("movb %0, 0x15(%%rip)" : : "r" (new_code));
float sum;
for (sum = x--; x>0; x--) {
sum = x / sum;
}
return sum;
}
```
[Answer]
# Haskell, ~~105 102 98~~ 96 bytes
```
0!3=0
x!y=foldr([(*),(+),(-),(/)]!!y)([1,0,0,1]!!y)[1..x]
f s|[(n,b)]<-lex s=read n!(length b-1)
```
Saved 9 bytes thanks to Zgarb and nimi.
[Try it online.](https://tio.run/##bZC9DoIwFEZ3nuLWOLQK2oq/iTwJYcAAQqzVAAMkvjsSN3u/NHfomc756rx7lNZOkxZxooNBjEn1skUrU7lSoVzPF823VZkQo5KpCfX8zO@Xms1myIKKuk8qXXhT2TWy5UBd0pZ5QU5IW7p7X9MtMmp65o2jhIpXQPRuG9fTkipaaLH4B8YHOx/EPtj74OCDow9OPjj74MLEmKoWXJ7bc33uzwN4AU/gDTwCVIAM0AFCQAkQB55AC0kgC6SBPMCmUA7sCo3BtjAD7TvD6Qs)
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~26~~ 25 bytes
```
ẋ)@d┅v;l“×+⁻÷”=“ₔ⊢”+e¤ḥ!∨
```
[Try it online!](https://tio.run/##S0/MTPz//@Gubk2HlEdTWsuscx41zDk8XftR4@7D2x81zLUFch81TXnUtQjI0U49tOThjqWKjzpW/P9vqggA "Gaia – Try It Online")
### Explanation
```
ẋ Split the input into runs of the same character.
) Get the last one (the !'s).
@ Push an input (since there's none left, use the last one).
d Parse as number (ignores the !'s).
┅v Get the reverse range: [n .. 1]
; Copy the ! string
l“×+⁻÷”= Get its length and index into this string of operators.
“ₔ⊢”+ Append 'ₔ⊢' to the operator.
e Eval the resulting string, which is "reduce by <operator> with
swapped arguments." Reducing an empty list gives 0.
¤ Bring the !'s back to the top.
ḥ! Remove the first character and check if it's empty.
∨ Logical OR; turns 0 from 0! to 1, doesn't change anything else.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
×
+
_
÷
³ċ”!
ḟ”!VRṚ¢ŀ@/¢Ị¤¹?
```
[Try it online!](https://tio.run/##y0rNyan8///wdC5trniuw9u5Dm0@0v2oYa4i18Md80F0WNDDnbMOLTra4KB/aNHD3V2Hlhzaaf///39DA0UA "Jelly – Try It Online")
Got the idea of separating the links into lines from Jonathan Allan's [answer](https://codegolf.stackexchange.com/a/137386/41024) for -2 bytes.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 30 bytes
Inspired by [lstefano's solution](https://codegolf.stackexchange.com/a/137381/43319).
```
{0::0⋄(⍎'×+-⌹'⊃⍨≢⍵~⎕D)/⍳⍎⍵∩⎕D}
```
[Try it online!](https://tio.run/##Vc47CsJAGEXhPquIVRQJ5v2qxX0EBZuAFjYi2ijiK8FG7K20Fgtrd/JvJEYGSc503zDMPek0M0fzNJuMy3KQDmeyPS@sJLHkuGlLXhifa9eU09uQw1ryu@xvkr9WUlz6nZ7kz@pFZdk9fjdL9YNuWC1Dr46mZEMO5EIe5EMBFEIRFHNdxWj/sqZsyIFcyIN8KIBCKIJirquYuqwhG3IgF/IgHwqgEIqgmOsqplFWy4YcyIU8yIcCKIQiKOa6ivkC "APL (Dyalog Unicode) – Try It Online")
`{`…`}` anonymous function where the argument is represented by `⍵`:
`0::` if any error happens:
`0` return zero
`⋄` now try:
`⍵∩⎕D` the intersection of the argument and the set of **D**igits (removes exclamation points)
`⍎` execute that (turns it into a number)
`⍳` **ɩ**ndices of that
`(`…`)/` insert (APL is right associative, as needed) the following function between terms:
`⍵~⎕D` argument without **D**igits (leaves exclamation points)
`≢` tally that (i.e. how many exclamation points)
`'×+-⌹'⊃⍨` use that to pick from the list of symbols\*
`⍎` execute (turns the symbol into a function)
---
`⌹` (matrix division) is used instead of `÷` (normal division) to cause an error on an empty list
[Answer]
# [Perl 5](https://www.perl.org/), 96 bytes
```
s/(\d+)//;@a=1..$1;$"=qw|* + -( /(|[$l=-1+length];$_=$1?"@a".($l>1?')'x($1-1):''):$l?0:1;$_=eval
```
[Try it online!](https://tio.run/##FcrdCsIgGADQV1H5QE38@YjdOMy9QE9QEUJSgWzWRnWxZ8/oXJ@an6VrbbbieFHS2n5IAY0B7IGFx3vdEEW0IFasByhBoyp5vC63Uw/nABjZkJgRUHYYueQfAahRes6lhxKdx3/Lr1Ra21JKv1Nd7tM4N73vjEPXdP0B "Perl 5 – Try It Online")
[Answer]
## Dyalog APL, at least 29 chars
```
{(⍎i⊃'×+-÷')/⍳⍎⍵↓⍨-i←+/'!'=⍵}
```
The expression is ALMOST correct. It passes all the test cases EXCEPT `0!!!!` for which it gives `1` instead of the required `0` and that's because in APL the reduction of an empty vector is supposed to return the neutral element for the function used to reduce. For the quotient that's 1. At the moment I don't have time to try and fix it but I'll leave it here for a rainy day.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 24 bytes
```
þDLðýs¹'!¢<"*+-/"ès<×J.V
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8D4Xn8MbDu8tPrRTXfHQIhslLW1dfaXDK4ptDk/30gv7/9/QQBEIAA "05AB1E – Try It Online")
[Answer]
# Mathematica, 152 bytes
```
(T=ToExpression;If[#=="0!!!!",0,s=T@StringCount[#,"!"];t=T@StringDrop[#,-s];{#!,i~Sum~{i,#},Sum[-i(-1)^i,{i,#}],N@Product[1/i^(-1)^i,{i,#}]}[[s]]&[t]])&
```
[Answer]
# Javascript, ~~111~~ 163 bytes
```
s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))
```
Readable Version
```
s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=
[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-
(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))
```
] |
[Question]
[
# Introduction
This question is inspired by this great [question](https://codegolf.stackexchange.com/questions/266255/finding-the-power-sandwich).
# Challenge
Given a number \$N>0\$, output the largest integer \$a^b\$ that is smaller or equal to \$N\$, and the smallest integer \$c^d\$ that is greater or equal to \$N\$, where \$b>1\$ and \$d>1\$.
Output should be a list of two integers, the first being smaller or equal to \$N\$, the second being greater or equal to \$N\$, and both being a perfect power. The two outputs can be in any order.
If \$N\$ is a perfect power already, the output should be the list [N, N].
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (as measured in bytes) wins.
# Example Input and Output
Input:
>
> 30
>
>
>
Output:
>
> [27, 32]
>
>
>
Explanation: \$27=3^3\$ is the largest perfect power less than or equal to \$30\$ and \$32=2^5\$ is the smallest perfect power greater or equal to \$30\$. Note that exponents b and d are not the same in this case.
# Test cases
```
2 -> [1, 4]
30 -> [27, 32]
50 -> [49, 64]
100 -> [100, 100]. 100 is already a perfect power.
126 -> [125, 128]
200 -> [196, 216]
500 -> [484, 512]
5000 -> [4913, 5041]
39485 -> [39304, 39601]
823473 -> [822649, 823543]
23890748 -> [23887872, 23892544]
```
[Answer]
# [R](https://www.r-project.org/), ~~62~~ 60 bytes
```
function(n,y=outer(1:n,2:n,"^"))c(max(y[y<=n]),min(y[y>=n]))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPp9I2v7QktUjD0CpPxwiIleKUNDWTNXITKzQqoyttbPNiNXVyM/NAHDsQR/N/moahJleahhGIMAERxgYg0hRMGhpAKCMzzf8A "R – Try It Online")
Brute force approach: generate all powers of `1..n` raised to `2..n` and find and return least upper bound and greatest lower bound.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆEŻg/’
ÇƇṪ;Ç1#
```
A monadic Link that accepts a positive integer and yields the sandwich of perfect powers.
**[Try it online!](https://tio.run/##y0rNyan8//9wm@vR3en6jxpmch1uP9b@cOcq68Pthsr/dQ63H530cOcMlaxHDXMUbO0UHjXM1Yz8/99Ix9hAx9RAx9AAiI3MdIwMQFwwNgAA "Jelly – Try It Online")** (Excluded the three largest test cases since the implementation is inefficient.)
### How?
```
ÆEŻg/’ - Link 1, perfect power?: positive integer, X
ÆE - prime factor exponents of X (e.g.: 1 -> [], 8 -> [3], 63 -> [0,2,0,1])
Ż - prefix a zero (to allow the following reduction when X=1)
/ - reduce by:
g - greatest common divisor (Note that 0 GCD N = N GGD 0 = N)
- non-perfect powers will result in 1
perfect powers will result in an integer greater than 1, except X=1 -> 0
’ - decrement -> non-zero (truthy) iff X is a perfect power
ÇƇṪ;Ç1# - Main Link: positive integer, N
Ƈ - filter {[1..N]} keeping those for which:
Ç - call Link 1
·π™ - tail
-> perfect power less than or equal to N
1# - starting with k=N find the first integer k for which:
Ç - call Link 1
-> perfect power greater than or equal to N
; - concatenate
```
### How?
[Answer]
# [Desmos](https://desmos.com/calculator), 55 bytes
```
f(n)=[floor(L)^I.max,ceil(L)^I.min]
L=n^{1/I}
I=[2...n]
```
[Try It On Desmos!](https://www.desmos.com/calculator/3wtygqdlao)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/y2rlifygj8)
Eh, pretty sure this can be golfed.
[Answer]
# JavaScript (ES6), 78 bytes
```
n=>eval("for(M=[m=1,x=p=2];(x*=p)>n|x<m?0:m=x,x<n?1:x>M?(x=++p)<n:M=x;)[m,M]")
```
[Try it online!](https://tio.run/##bdDBboMgGAfw@56C9IQrW@EDEa3oE/gExoNpddmiaNql4bB3d2gXE2UcOMAvH/z/X/Wjvl9un@P3mxmuzdTqyeisedQdPrTDDRe67DUjVo8aqjO2r3oMMvNj0z6nSa8tsanJWWKzIsdWH49jkJqk0PYclD0pqkMwXQZzH7rmvRs@cIshCNDfOp1QyQgS1cuWcLqamUBEEIc9CrdIxARJbxKjq1oeo5Qgt3kM5IZB6BioPYPdtFgSBEz6P9swoQRBIfsnwOqeARh3jgrm1RELFT7lDHnMqZvIY0k9qoCLiC92pgpAzsW441BwLw5XMY2EcnypmSsVqQhcJncBoRDV9As "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 79 bytes
A faster version without `eval()`, also easier to comment.
```
n=>{for(M=[m=1,x=p=2];(x*=p)>n|x<m?0:m=x,x<n?1:x>M?(x=++p)<n:M=x;);return[m,M]}
```
[Try it online!](https://tio.run/##bdDNboQgFAXgfZ@CpXZoBy4/goo@gU9gXEym2rQZ0TjThqTts1t0GhO1LFjAlwvnvJ8@T9fz8Nbfnmz3Uo@NGa3JvppuCApTtoZiZ3oDVRK4R9OHmf12aZuTuDUOu9TmNHZZkQfOHA59mNq4MC4Jk6G@fQy2bHFR/Yznzl67S/186V6DJoAwRH/reEQlxYhXD2vCyGImAhFGDLZIrBHXGMndJEoWNT9GCEZ@2zGQKwbCM1BbBptpWmIEVO5/tmJccYwE/SfA4u4BKPOOcLqrQ3Ml7nKCTDPiJzItyY4qYDxis52oApBTMf5YcLaLw5QmEVeezzUzpSIVgc/kL0BwXo2/ "JavaScript (Node.js) – Try It Online")
```
n => { // n = input
for( // loop:
M = [ // M = high bound
m = 1, // m = low bound
x = // x = current result
p = 2 // p = current multiplier
]; //
(x *= p) // multiply x by p
> n | // if x is greater than n
x < m ? // or less than m:
0 // do nothing
: // else:
m = x, // set m to x
x < n ? // if x is less than n:
1 // continue
: // else:
x > M ? // if x is greater than M:
(x = ++p) // increment p and set x to p
< n // continue if x < n
: // else:
M = x; // set M to x and continue
); // end of loop
return [m, M] // return the final bounds
} //
```
[Answer]
# [Python](https://www.python.org), 85 bytes
*This solution is designed to solve all test-cases in less than 1 second, for a slightly shorter but slower approach see [corvus\_192's solution](https://codegolf.stackexchange.com/questions/266293/finding-the-power-sandwich-version-2/266313#266313)*
*-21 bytes thanks to xnor's suggestion on corvus\_192's solution*
```
lambda n:[i*max(i*int(n**(1/p)//i*i)**p for p in range(2,len(bin(n))))for i in(1,-1)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVJLTsMwEJVYRhxiVDZ25Lb-xbGRyi1YlS5SmoClxrHSIKgQJ2FTCcEBOAK3gNPgUJEY4cXE9vv4eeLnN7_vbht3eKkWV693XTXVn5fbol5vCnDnS5vWxQOyqXUdcmmK2Nzj-TyscZp6qJoWPFgHbeFuSsTJtnRobR1yOIwetQFFjEwZXh3Nv05OE1v7pu2gs3WZJB1d9JNZXxBOfNsfVSGOMZzB9AKWjIBcDfuCDgDPCQg-QtkISUNARSpGRyzMCYSymvUV7A6KbVsWmz0U4Mu2Kq878M192c5GOVejnGdBzvVozmNzowhwpuJUUSwtCWTsT-YYNkwEnEoW3ddInQ0MYQQNFsIoGnE0FzIXA0lzrvoGhO1Miiin0IbmUo8NFFrnOuchcYB4JkPHojsLmalcG52rYMPZj2wB7Hd8vP_n0og9WE0eUfSHpx3FaWg8fap3E3x8FIfD8fsN)
Goes through floor/ceil of p-th root to power of p for all possible powers p and picks the highest lower and lowest upper bound
---
# [Python](https://www.python.org), 115 bytes
*solves all test cases in less than a minute*
```
lambda n:[next(q for q in x for b in r(2,len(bin(q)))if q==round(q**(1/b))**b)for x in[r(n,0,-1),r(n,3*n)]]
r=range
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVFBTsMwEBTXvmIlLnbklnjtODZS-EjJIaEJRCpO4qaifQuXSggu3HgCv4DX4LRqY3ywRzs74_H69aPbD0-tPbzV2f37dqjn-mezLp7LVQH2dmmr3UB6qFsHPTQWdkdYjtARZOvKkrKxpKeUNjX0WebarV2RPooIvykpjaKSjoqdVywdsSxmc07ZiERkaZ7PXOYK-1idrv69-uxcYwdSE6QUrmF-B0vOQOazc13EFwJTBgInKpkoaRioQMXjifOYgd_yxbhDs4Fi7apitYcCusrV1cMAXftSucUkRzXJMfFy1JM5huZGMUCuwlRBLC0ZJPxf5pA2XHg-ljx4r5E6uXQII2JvIYyKgx6NQqbi0qQR1TgAX06kCHIKbeJU6mmAQutUp-gTewoTGU7MeyYq1UanyrsgP6oy4Of1_XX6s8PhdP4B)
## Explanation
*uses a less golfed version of the same approach*
```
# check if a given number is a perfect power
p=lambda q:any(q==round(q**(1/b))**b for b in r(2,len(bin(q))))
# brute-force: check for all exponents b if q is a power of b
# due to rounding errors: q**(1/b)%1==0 and q==int(q**(1/b))**b) give the wrong result for the last two test-cases
# checking all numbers takes to much time
# only check up to log2(q)+2 with is larger than the largest possible power p for which 2**p <= q
# find the power sandwich
lambda n:[next(filter(p,x))for x in[r(n,0,-1),r(n,3*n)]]
# find the first number x less/greater than or equal to n that satisfies p(x)
# use 3*n as upper bound for the next perfect power: if n is not a square number then the next square number is less than 3*n
# (clear for n <9=3², if m=k*k for k >= 3 then (k+1)²=k²+2*k+1 <= k²+3*k <= 2*k² <= 2*m < 3*m)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
2r⁸*þFfȯ_İ¥Þɗ⁸.ị
```
[Try it online!](https://tio.run/#%23y0rNyan8/9@o6FHjDq3D@9zSTqyPP7Lh0NLD805OBwrpPdzd/d/6UcMcBV07hUcNc60Ptz/cuU@F63D7o6Y1kUB9OsYGOqYGOoYGQGxkpmNkYAAA "Jelly – Try It Online")
A monadic link taking an integer argument and returning a list of two integers. Will time out for large n, since internally a table of all powers of \$a^b\$ where \$a\$ is from 1 to n and \$b\$ is from 2 to n.
## Explanation
```
2r | Range from 2 to the input
⁸*þ | Table of powers from 1 to the input raised to the power of from 2 to the input
F | Flatten
ɗ⁸ | Following as a dyad, using the input as the right argument and the power table as the left:
f | - Filter (keep the input if present in the power table)
ȯ ¥ | - Or the following as a dyad
_ | - Subtract the input
İ | - Invert
.ị | Take the last (power above or equal) and first (power below or equal) elements of this list
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 120 bytes
```
.+
$*
((1+)((\2(1+))(?=(\4*)\2*$)\4*(?=\5$\6))+)?1$
$&¶$&
O`
+`¶(?!((1+)((\2(1+))(?=(\4*)\2*$)\4*(?=\5$\6))+)?1$)
¶1
%`1
```
[Try it online!](https://tio.run/##lYsxDsIwEAT7/QXSJbqzJeQzJF3kMhXiA1eYgoKGAvE2P8Afc44nUOzu7Er7eX5f78eYeK/jHEEBzBqF2fIvhcvGdg1iOZA4eLeFbBWJUpRAc280414Ra29cTn/dBb0ppqrD/VYV5MPIuCQsCZpceUVO6QA "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
((1+)((\2(1+))(?=(\4*)\2*$)\4*(?=\5$\6))+)?1$
$&¶$&
```
Find the largest perfect power that does not exceed `N`. This is based on my answer to [What's next, Achilles?](https://codegolf.stackexchange.com/q/219525/) but also allowing `N=1`, which that question didn't have to handle.
```
O`
```
Sort the numbers back into order. (This is shorter than trying to get the above stage to output the numbers in ascending order.)
```
¶(?!((1+)((\2(1+))(?=(\4*)\2*$)\4*(?=\5$\6))+)?1$)
¶1
```
If `N` is not a perfect power then increment it.
```
+`
```
Repeat until a perfect power is reached.
```
%`1
```
Convert to decimal.
[Answer]
# [Python](https://www.python.org), 77 bytes
```
lambda n:[i*max(i*int(n**(1/p)//i*i)**p for p in range(2,n+2))for i in(-1,1)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJLTsMwEJVYZsMVRu3GDk7rXxIbqdyAE0AXgSbFUpNYqRFUiJOwqYTgAByBW8BpcKiaGAkvxpN5n8xM8vJud-6ubfav1eL67d5Vifq63BT1zaqA5vzKxHXxiExsGoeaOEZsbvF87p9xHFuo2g4smAa6olmXiJPmjGPcV42vooQRhpcH0--TU1PbtnPgTF1GkaOLPpn1AeHIdv0bKuTlMIXkAq4YAbkc6oIOAM8JCD5C6QhJTSALVIyOmM8J-LCc9RHMFopNVxarHRRgy64qbx3Y9qHsZqOcZ6Ocp17O1WjOQ3OdEeAsC7sK2lKSQMr-9BzCmgmPU8mCebVU6cAQWlBvIXRGPWd6JCkuZC4GluI86zfgy6kUAY8LpWku1bhCoVSucu579hBPpd_Zkb72YwuZZrnSKs-8EWe_ugWw4_n8-IdMA3p0nGPyhIKvnDiKY798-lxvJ_jwX-z3h_sH)
-16 bytes thanks to xnor and bsoelch
## Previous version, 93 bytes
```
lambda n:[(g:=lambda f,i:f(int(abs(n**(1/p)//i))**p for p in range(2,n+1)))(max,1),g(min,-1)]
```
The core algorithm is from bsoelch: [https://codegolf.stackexchange.com/a/266303>](https://codegolf.stackexchange.com/a/266303%3E) I just spent around 2 hours optimizing.
This version with a helper function is actually 2 bytes shorter than my alternative eval hack:
```
lambda n:eval(f"%s(int(abs({n}**(1/p)//%d))**p for p in range(2,{n}+1)),"*2%("max",1,"min",-1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJLTsMwEJVYZsMVRu3GDk7rXxK7UrgIdJHSJERqPkqNoEKchE0lBAfgCNwCToNDSWIkvBiP_d6bn_381h7MbVMfX_Lk-vXO5IH6XO_SarNNoV5doWKV_J5yUq5yVNYGpZs9qn0fsWWLl8sSY99vIW86aKGsoUvrIkOc1BcMY4yq9IEwTApUlTUJGF6fknydnZdV23QGTFllnmdo0juL3iDstV2fKEccY5hDcAlXjIBcj_eCjgCPCQg-QeEESU0gclSMTpj1CVizXvQWyj2kuy5LtwdIoc26PLsx0Db3WbeY5Dya5Dy0cq6m4NwNriMCnEVuVU5ZShII2Z-aXVgzYXEqmdOvliocGUILakMIHVHLmQ8kxYWMxchSnEf9BOx1KIXD40JpGks1jVAoFauY25otxENpZzbQC9u2kGEUK63iyAbi7EeXABvWx_s_ZOrQvaGP2SNyXjkwFPt2-PSp2s_w6V8cj6f9Gw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LÂZ+‚εR.ΔÓ0š¿≠
```
-2 bytes porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/266312/52210) instead.
[Try it online](https://tio.run/##ASQA2/9vc2FiaWX//0zDglor4oCazrVSLs6Uw5MwxaHCv@KJoP//MzA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf99DjdFaT9qmHVua5DeuSmHJxscXXho/6POBf9ra3X@RxvpGBvomBroGBoAsZGZjpEBiAvGBjrGliYWprEA). (Times out for the largest two test cases, so those are omitted.)
**Original 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
L¦©zmDï®màsî®mß‚
```
Port of [*@AidenChow*'s Desmos answer](https://codegolf.stackexchange.com/a/266311/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/f59CyQyurcl0Orz@0LvfwguLD60D0/EcNs/7/NzYAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf59Dyw6trMp1Obz@0LrcwwuKD68D0fMfNcz6r/M/2kjH2EDH1EDH0ACIjcx0jAxAXINYAA). (Times out for the largest four test cases, so those are omitted.)
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
 # Bifurcate it; short for Duplicate & Reverse copy
Z+ # Add the input to each value in the reversed copy
‚Äö # Pair them together: [[1,2,...,n-1,n],[2n,2n-1,...,n+2,n+1]]
ε # Map over both inner lists:
R # Reverse the list
.Δ # Pop and find the first value that's truthy for:
Ó # Push the exponents of its prime factorization
0š # Prepend a 0 (edge case for value=1)
¬ø # Pop this list, and push its Greatest Common Divisor (GCD)
≠ # Check that it's NOT equal to 1
# (after which the pair is output implicitly as result)
```
```
L # Push a list in the range [1, (implicit) input]
¦ # Remove the leading 1 to make the range [2,input]
© # Store this list in variable `®` (without popping)
z # Pop and convert each value in the list to 1/value
m # Take the (implicit) input to the power of each of these 1/value
D # Duplicate this list
ï # Floor each to an integer
®m # Take each to the power [2,input] (at the same positions)
à # Pop and leave its maximum
s # Swap so the list is at the top again
î # Ceil
®m # To the power [2,input]
ß # Pop and leave its minimum
‚Äö # Pair this maximum and minimum together
# (which is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 98 bytes
*-1 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
Adapted from [my JS answer](https://codegolf.stackexchange.com/a/266309/58563). Prints the bounds separated by a space.
```
m,M,x,p;f(n){for(M=n*n,m=1,x=p=2;m=(x*=p)>n|x<m?m:x,x<n?:x<M?M=x:(x=++p)<n;);printf("%d %d",m,M);}
```
[Try it online!](https://tio.run/##fdBRa4MwEAfw932Ko1BI2itNYnRqzPwEfoKxh6LYCUsqrtsCXb/6XFqdT7p7CBz8@Ofuyt2xLPveYIEOW1UTSy/1qSOFthuLRnN0utVCGU3cRrf0yX67zOQmdegym6cuK/JCu5Q4vd22NLOKqrZr7Lkmq3UF62qFPpuqa/95aiowh8YSCpcHgJoIqqD9OJevh45w5puh9nt45gjy5Y4CNqtuSDwiBGJg4TKTCUI0pnE26@5fMobgnxGKaBGK0EMRD1D8k5hECIJHfxMuQhlLhJBPq8zKYRUeeMkkH4@TyDicDjfVjQZJwHxqkETM42v/U9Zvh@N7v/v6BQ "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 91 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 11.375 bytes
```
⇧ḢĖe:⌊>g)₍<>
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4oen4biixJZlOuKMij5nKeKCjTw+IiwiIiwiMjEiXQ==)
Bitstring:
```
1101001100110001001011011110000101000101000100101011000010000101000011011110111001000110010
```
## Explained
```
⇧ḢĖe:⌊>g)₍<>­⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
)₍<> # ‎⁡Find the first numbers >= and <= the input where:
g # ‎⁢ The minimum of
> # ‎⁣ comparing whether
⌊ # ‎⁤ the floor of:
e # ‎⁢⁡ the number to the power of each item in
Ė # ‎⁢⁢ the reciprocals of items in
⇧Ḣ # ‎⁢⁣ the range [2, number + 2]
: > # ‎⁢⁤ is greater than the original list
g # ‎⁣⁡ is 0
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
NθFθFθ⊞υX⊕ι⁺²κI⟦⌈Φυ¬›ιθ⌊Φυ¬‹ιθ
```
[Try it online!](https://tio.run/##bYy7CgIxEAB7vyLlBiIc11oKyoF3pBeLGFcumIe3SdS/j2uhldU@mBk7G7LJ@NaGeK9lquGMBIvcrK6JBC/iO3XNM1QldHoyMURLGDAWvICT/PU1Q6/ETUp2NblYYGtygeNoXi7UADvnC4tcmFKBPaH5nE6JhRUujC7@4Q6Y8w86cbu1vuva@uHf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Guiseppe's R answer.
```
Nθ
```
Input `n`.
```
FθFθ⊞υX⊕ι⁺²κ
```
Generate a list of perfect powers from `1²` to `nⁿ⁺¹`.
```
I⟦⌈Φυ¬›ιθ⌊Φυ¬‹ιθ
```
Find the largest one not greater than `n` and the smallest one not less than `n`.
42 bytes for a less inefficient version:
```
NθFE⊕₂θX⊕ι…·²⎇ιL↨θ⊕ι²Fι⊞υκI⟦⌈Φυ¬›ιθ⌊Φυ¬‹ιθ
```
[Try it online!](https://tio.run/##bY5Na8JAEIbv/RV7nIUUShS0eKugCEaCeis9TONoFpNdM7vrx69fJzkUD53bOzzvR1UjVw6blFb2EsMmtr/E0OnZ29GxggIvsLIVU0s20AF2XUSmrXNBGJ2p0t0EfyWMfEU30ZsrbdGeCPJM7Ykt8gNMptZkT6GGL/QE3cC@ePvMXPenhn6jVRl9DTFTZ9lUsrEB5ugDfBd4N21sYWGaIBuE2MiqJRP2Uoo6PcQVxv7Drcn7P@hH61lK@Wj6@TEZT9P7tXkC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above but only loops up to `⌊√n⌋` and only powers up to `1+⌊logᵢn⌋` (or `2` if `i=1`).
33 bytes for a more efficient version that can suffer from floating-point inaccuracy:
```
NθIE⟦¹±¹⟧×ι⌈E₂θ×ιX×ι⌊×ιXθ∕¹⁺²λ⁺²λ
```
[Try it online!](https://tio.run/##ZYzLCsIwFET3fkWWNxDBVsFKl4rgoqWoO3FxrUEDSdO8qn8fQwUpOLszM5z2ibbVKGM8dH3wdVA3bsHQctZY0XnYovNQYQ@XjJGaP9BzyOiVkbNQ3IFgpMK3UEGNp5MJaPlRa58Uk0@jX8n6w73UeoLf1TCyE4O4J3@qZHCQMyLpmL8ipYwxXxabxXpVxPkgPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @bsolech's golf to @corvus\_192's Python answer.
```
Nθ Input `N` as a number
¬π Literal integer `1`
¬π Literal integer `1`
± Negated
‚ü¶ ‚üß Make into list
E Map over units
θ Input `N`
‚ÇÇ Square root
E Map over implicit range
θ Input `N`
X Raised to power
¬π Literal integer `1`
‚àï Divided by
λ Current value
⁺ Plus
² Literal integer `2`
√ó Multiplied by
ι Current unit
‚åä Floored to integer
√ó Multiplied by
ι Current unit
X Raised to power
λ Current value
⁺ Plus
² Literal integer `2`
√ó Multiplied by
ι Current unit
‚åà Take the maximum
√ó Multiplied by
ι Current unit
I Cast to string
Implicitly print
```
[Answer]
# [Scala](http://www.scala-lang.org/), 149 bytes
A port of [@Giuseppe's R answer](https://codegolf.stackexchange.com/a/266294/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##bY89b4QwDIZ3foXHROIioB8DkJM63HBDp6pTVVXmLlyDwEHBaosQv53mWKqWLq/sx49leThhi4urGnNieERLMEUAZ1NDFxqB/jLk8OA9ji9P7C1dXmUOz2QZ9GoC9IFyS6IWqZR/SLYhtxtyk2zQ3RalyT8su1/ZHEUhP7CFOgdxJNb7a8YQQkrQC@n9dB2PunZ@suUuBXZARVPusrWaR2vac3iZ31XvPoWNG1mEDYFxJfWoevRs2ToSb6UmWQhbC1Tk6ND1PEpUHX4pduEemHYwkMRBqH6ESnWWfglyXublGw)
```
n=>{val y=for{i<-1 to n;j<-2 to n}yield math.pow(i,j);val(a,b)=y.partition(_<=n);(if(a.nonEmpty)a.max.toInt else 0,if(b.nonEmpty)b.min.toInt else 0)}
```
Ungolfed version. [Try it online!](https://tio.run/##bZHNa4MwHIbv/hXvMYITdR8HaQcdbLDDTmOnMUZakzYSE9HQToZ/u8tSP7D2lOTJm@f3S1LvqKRdp7c52xm8UaHw6wEZ4yjsgtBqX6fYVBVtPt9NJdT@y0/xoYTB2iWB0lIjFeEk9v0LkizI3YLcRgt0v0RxdIUlD461Xt8yJyrFqzK2RWKHwM3HRo9UorErrqueAAKrG8QwGqon@T9JJtKiEUxm9jnMISz1iYgAue9NxhchDatY9sSkPll9E3JHyDdWayh/mdxs9ZHNk48uOUYL@jPoBAeZ1wiVVs9FaRr/onhoj4VG20uDyZohmnxCDUVnPgev@c4b9tjc54Rk6C4YvedfaLvuDw)
```
object Main {
def main(args: Array[String]): Unit = {
println(f(1))
println(f(2))
println(f(4))
println(f(30))
println(f(50))
println(f(100))
println(f(126))
}
def f(n: Int): (Int, Int) = {
val y = for {
i <- 1 to n
j <- 2 to n
} yield math.pow(i, j)
val yFilteredBelow = y.filter(_ <= n)
val yFilteredAbove = y.filter(_ >= n)
val maxBelow = if (yFilteredBelow.nonEmpty) yFilteredBelow.max.toInt else 0
val minAbove = if (yFilteredAbove.nonEmpty) yFilteredAbove.min.toInt else 0
(maxBelow, minAbove)
}
}
```
[Answer]
# APL+WIN, 63 bytes
Prompts for integer:
```
(↑(n=⌊/n←|m-i)/m←(⌊i*÷p)*p),↑(n=⌊/n←|m-i)/m←(⌈(i←⎕)*÷p)*p←1↓⍳30
```
Increase the 30 at the end of the code to handle higher integers than the examples.
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv8ajtokaebaPerr084CiNbm6mZr6uUCWBlAoU@vw9gJNrQJNHTyqOjQygQygsZpQ1SDDH7VNftS72djgP9ASrv9pXEZcaVzGBkDCFEQYGoBJIzMgaWQAEYaSIMrY0sTCFEhbGBmbmBuD1BhbWBqYm1gAAA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Given two strings, find the translation table ([substitution cipher](https://en.wikipedia.org/wiki/Substitution_cipher)) between the two, if the translation is not possible, output false. The answer must be minimized and created from left-to-right. The first character to be translated between words must be the first in the translation table. In addition to this, any letter that is not translated (in the same place as it was originally), should NOT be in the translation table.
Probably most easily defined through examples:
# Valid Cases
```
"bat", "sap" => ["bt","sp"]
```
Notice the ordering, an output of `["tb","ps"]` is not valid for this challenge.
```
"sense", "12n12" => ["se","12"]
```
Notice how the `n` isn't translated because it is a 1 to 1 relation.
```
"rabid", "snail" => ["rabd","snal"]
```
Notice how the `i` isn't translated because it is a 1 to 1 relation.
```
"ass", "all" => ["s","l"]
```
A is not included, it stays the same, `s` can map to `l` due to pattern match.
```
"3121212", "ABLBLBL" => ["312","ABL"]
```
Matches pattern perfectly.
# Falsy Cases
```
"banana", "angular" => false
```
(not the same length, impossible).
```
"animal", "snails" => false
```
(each character can only be used ONCE on each side of the translation).
```
"can","cnn" => false
```
(n is implicitly used in translation, therefore, defining a translation table with n->a would be invalid)
Thusly, `[aimal,sails]` is an invalid answer, making this falsy.
```
"a1", "22" => false
```
See "caveats", this is listed as falsy. In this case, it's because `a` and `1` cannot both map to `2`. (Each character can only be used ONCE on each side of the translation).
---
This answer seems to be a good benchmark: <https://codegolf.stackexchange.com/a/116807/59376>
If you have questions about the functionality of two unlisted word pairs, defer to this implementation.
---
# I/O rules
* Input may be as a 2 element array or as 2 separate inputs.
* Output can be as an array or newline/space delimited, similar to how I have it shown.
* False output may be 0, -1 or false. Erroring/Empty output is also fine.
* You are guaranteed that `a` will not equal `b` and neither `a` nor `b` will be empty.
* `a` and `b` are printable-ASCII-only sequences of letters.
# Caveats
* Translations must occur from left to right, see example 1.
* You must not output characters that remain the same.
* Your program may only take in two strings `a` and `b`.
* Each character can only be used ONCE on each side of the translation. This is what makes the translation from `snails` to `animals` impossible.
* Recursive replaces should not occur. Example of recursive replace: `"a1","22"->[a1,12]` where a is first replaced by a 1, then both resultant 1's are replaced with 2's. This is not correct, assume all translations occur independent of each other, meaning this is falsy. Meaning: ***"a1" with translation table of [a1,12] evaluates to 12 (not 22)***
[Answer]
## JavaScript (ES6), 128 bytes
```
f=
(s,t)=>!t[s.length]&&[...s].every((c,i)=>n[d=t[i]]==c||d&&!m[c]&&!n[d]&&(n[m[c]=d]=c,c==d||(a+=c,b+=d)),m={},n={},a=b='')&&[a,b]
```
```
<div oninput=o.textContent=f(s.value,t.value)><input id=s><input id=t><pre id=o>
```
[Answer]
## JavaScript (ES6), ~~108~~ ~~107~~ ~~105~~ 106 bytes
***Edit***: Fixed to support inputs such as `"22" / "a1"` that should be falsy.
---
Returns either `0` or an array of two strings.
```
f=(a,b,x)=>[...a].some((c,i)=>d[C=b[i]]?d[C]!=c:(d[C]=c)!=C&&(s+=c,t+=C,!C),s=t='',d=[])?0:x||f(b,a,[s,t])
```
### Formatted and commented
```
f = ( // given:
a, // - a = first string
b, // - b = second string
x // - x = reference result from previous iteration,
) => // or undefined
[...a].some((c, i) => // for each character c at position i in a:
d[ // if we already have a translation
C = b[i] // of the character C at the same position in b,
] ? // then:
d[C] != c // return true if it doesn't equal c
: // else:
(d[C] = c) != C && // store the translation C -> c in the dictionary
( // if the characters are different:
s += c, t += C, // append them to the translation strings s and t
!C // return true if C is undefined
), //
s = t = '', d = [] // initialize s, t and d
) ? // if some() returns true:
0 // there was a translation error: abort
: // else:
x || // if this is the 2nd iteration, return x
f(b, a, [s, t]) // else do a recursive call with (b, a)
```
### Test cases
```
f=(a,b,x)=>[...a].some((c,i)=>d[C=b[i]]?d[C]!=c:(d[C]=c)!=C&&(s+=c,t+=C,!C),s=t='',d=[])?0:x||f(b,a,[s,t])
// truthy
console.log(f('bat','sap'))
console.log(f('sense','12n12'))
console.log(f('rabid','snail'))
console.log(f('ass','all'))
console.log(f('3121212','ABLBLBL'))
// falsy
console.log(f('banana','angular'))
console.log(f('animal','snails'))
console.log(f('a1','22'))
console.log(f('22','a1'))
console.log(f('aaa','bab'))
console.log(f('abc','abcd'))
console.log(f('abcd','abc'))
```
[Answer]
# PHP >=7.1, 130 Bytes
18 Bytes saved by [@Titus](https://codegolf.stackexchange.com/users/55735/titus)
```
for([,$x,$y]=$argv;a&$o=$y[$i];)$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p;echo$y==strtr($x,$c)&$x==strtr($y,$k)?join($k)." ".join($c):0;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/f1495dd6e5e3c907caac5359f57670ac2d2989e3)
Expanded
```
for([,$x,$y]=$argv;a&$o=$y[$i];)
$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p; # if char string 1 not equal char string 2 make key=char1 value=char2 and key array
echo$y==strtr($x,$c) # boolean replacement string 1 equal to string 2
&$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
?join($k)." ".join($c) # output for true cases
:0; #Output false cases
```
# PHP >=7.1, 148 Bytes
prints 0 for false Output true as string
```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;echo$y==strtr($x,($f=array_flip)($k=$f($c)))&$x==strtr($y,$k)?join($k)." ".join($c):0;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/51cb3e3bea320b1d8a1523d6bd9f3b6f83cd1766)
Expanded
```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo$y==strtr($x,($f=array_flip)($k=$f($c))) # boolean replacement string 1 equal to string 2
&$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
?join($k)." ".join($c) # output for true cases
:0; #Output false cases
```
## PHP >=7.1, 131 Bytes
The second answer can be shorted to this if associative arrays are allowed
prints 0 for false Output true as associative array instead of string
```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;print_r($y==strtr($x,($f=array_flip)($f($c)))&$x==strtr($y,$k)?$c:0);
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/dfcf0e872e4fe53b4c317fb5160fbf3266ba0ced)
## PHP >=7.1, 227 Bytes
prints 0 for false
```
[,$x,$y]=$argv;echo strlen($x)==strlen($y)?strtr($x,$c=array_filter(($f=array_flip)($z=$f(array_combine(($p=str_split)($x),$p($y)))),function($v,$k){return$k!=$v;},1))==$y&$x==strtr($y,$z)?join(array_keys($c))." ".join($c):0:0;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/6a534098437c1c67d4f2df102a2ae9bc7c0c4ba5)
Expanded
```
[,$x,$y]=$argv; #
echo strlen($x)==strlen($y) #compare string lengths
?strtr($x, # replace function
$c=array_filter( # filter
($f=array_flip)($z=$f( # # remove doubles like in testcase: a1 => 22
array_combine(($p=str_split)($x),$p($y)) # replacement array keys string 1 values string 2
))
,function($v,$k){return$k!=$v;},1)) # remove all keys that equal to values in array
==$y # boolean replacement string 1 equal to string 2
&$x==strtr($y,$z) # boolean replacement string 2 equal to string 1
?join(array_keys($c))." ".join($c) # output for true cases
:0 # Output if replacement from string 1 is not equal to string 2
:0; #Output for different lengths
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẠaQ⁼µ€Ạ
z0EÐḟQZẋÇ$
```
Unnamed monadic link (one-input function) taking a list, which returns:
an empty list in the falsey cases; or
a list containing two lists of characters in the truthy cases.
**[Try it online!](https://tio.run/nexus/jelly#@/9w14LEwEeNew5tfdS0BsjhqjJwPTzh4Y75gVEPd3Ufblf5f7jd@///aKXi1LziVCUdJUOjPEMjpdivefm6yYnJGakA "Jelly – TIO Nexus")** (the footer splits the list with a space to avoid printing a smushed representation)
...or see a [test suite](https://tio.run/nexus/jelly#@/9w14LEwEeNew5tfdS0BsjhqjJwPTzh4Y75gVEPd3Ufblf5f7jdWwUoF/n/f3S0UlJiiZKOUnFigVKsTrRScWpecSqQb2iUZ2gEFilKTMpMAanIS8zMAYskFhcD@Yk5EJ6xoREIAkUcnXxAECyalJgHhCBleemlOYlFEI15mbmJOTCziiFihkC@EdCq2K95@brJickZqQA).
### How?
```
ẠaQ⁼µ€Ạ - Link 1, valid?: mapping list
µ€ - perform the code to the left for €ach mapping entry
Ạ - none of mapping entry falsey? (this & Main's z0 handle unequal input lengths)
Q - deduplicate mapping entry
⁼ - is equal to mapping list? (non-vectorising)
a - and
Ạ - none falsey (both mapping lists must pass that test)
- The whole function returns 1 if the mapping list is acceptable, 0 if not
z0EÐḟQZẋÇ$ - Main link: list of strings
z0 - transpose with filler 0 (unequal lengths make pairs containing zeros)
Ðḟ - filter discard:
E - all equal? (removes the untranslated character pairs)
Q - deduplicate (removes the repeated translation pairs)
Z - transpose (list of pairs to pair of lists)
$ - last two links as a monad:
ẋ - repeat list this many times:
Ç - call last link (1) as a monad
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~194~~ ~~191~~ ~~185~~ ~~229~~ ~~225~~ 241 bytes
```
.+
$&;$&
+`^\w(\w*;)\w
$1
^;\w.*|.+;;.*|;;
^((.)*)(.)(.*;(?<-2>.)*(?(2)(?!)))\3
$1$4
+`((.)(.)*)\2((.)*;.*(.)(?<-3>.)*(?(3)(?!)))\6((?<-5>.)*(?(5)(?!)))$
$1$4$7
^(.)*(.)(.)*(\2)?.*;(?<-1>.)*(?(1)(?!))(.)(?<-3>.)*(?(3)(?!))(?(4)(?!\5)|\5).*
```
[Try it online!](https://tio.run/nexus/retina#bY3BasMwDIbveouBV2SHGew020FjOe4lTKhCQxvIzBp3@NJ3z5TEuw1jW/8vfb@e8fO02ArUgdQBqlMXMoZsSIcMykFHIVvzsBWRfEQAHaLVRsuD1hC27y/@Qwxs0Wtsn7TWoRZSHSUMtymZDn6jJGN1hKkLU/8xr7jaTbGbYqstSb3J1rWxp2Hwui27XQHcDvyfLtVxrUKjH3KtgWXp@U6JvyENMQ3kfHQeZu7HM6XI4wQ9Rzkzcbz8TFxkUTNwHL942kcTcDqny5VuecjzHRJvKt82xY68/wU "Retina – TIO Nexus")
Takes input `;`-separated. Output is also `;` separated. False inputs are signified by empty outputs.
I know this is painfully verbose, I am still trying to cut down bytes. Most of these bytes go into deleting false inputs.
### Edits
* It turns out that I had a significant flaw with my program. It's fixed now, but at the cost of over 40 bytes.
* Another mistake was found where my program did not declare the input `a1;22` false, but I was able to keep the program under 250 bytes after fixing it
### Explanation
(a more detailed explanation will be coming shortly)
First we have to check if the lengths of strings `a` and `b` are the same or not. If they are not, we delete everything.
Duplicates the input to preserve it while we do some length-testing.
```
.+ Matches everything
$&;$& $& indicates the match, so $&;$& will duplicate the match and separate it with a semi-colon
```
Now in a loop, we delete the first character of `a` and the first character of `b` until one of the strings become empty.
```
+` Repeatedly (until no more substitutions could be made) replace
^\w A word character (letter or number) at the beginning
(\w*;) Capture Group 1: matches any number of word characters and a semicolon
\w And a word character after the semi-colon
with
$1 The result of the first capture group
```
Now there are there possibilities for the "pattern space".
* `;;abc` Both strings are of equal length
* `def;;abc` `a` is longer than `b`
* `;def;abc` `b` is longer than `a`
Now we have to empty the input if the strings are not of the same length (scenarios 2 and 3). This is what this substitution below does. It removes text that matches scenarios 2 and 3.
```
^;\w.*|.+;;.*|;;
```
This removes characters that are not transliterated in strings `a` and `b`. `abc;1b2` => `ac;12`
```
^((.)*)(.)(.*;(?<-2>.)*(?(2)(?!)))\3
$1$4
```
After that, we have to remove duplicate characters. `sese;1212` => `se;12`, but this preserves inputs like `aba;123`
```
+`((.)(.)*)\2((.)*;.*(.)(?<-3>.)*(?(3)(?!)))\6((?<-5>.)*(?(5)(?!)))$
$1$4$7
```
Finally, we delete the input if there are duplicate characters that map to different characters like `aba;123` or `a1;22`.
```
^(.)*(.)(.)*(\2)?.*;(?.)*(?(1)(?!))(.)(?.)*(?(3)(?!))(?(4)(?!\5)|\5).*
```
And finally, remove duplicate characters.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 26 bytes
```
QL$€⁼L€
EÐḟQZK0Ç?
ZÇ0L€E$?
```
[Try it online!](https://tio.run/nexus/jelly#@x/oo/Koac2jxj0@QIrL9fCEhzvmB0Z5Gxxut@eKOtxuABJ2VbH///9/tJKxoREIKukoKDk6@YCgUuzXvHzd5MTkjFQA "Jelly – TIO Nexus")
```
QL$€⁼L€ Checks validity of mapping
QL$€ number of unique characters in mapping
⁼ equals
L€ number of characters in mapping
EÐḟQZK0Ç? Writes valid mapping or 0
EÐḟ filter maps where a = b
Q filter duplicate maps
Z zip by column [["ac"],["bd"]] => ["ab","cd"]
K0Ç? print if valid map, else print 0
ZÇ0L€E$? main link: takes an array of 2 strings
Z zip by column: ["ab", "cd"] => [["ac"],["bd"]]
Ç ? print mapping if
L€E$ all pairs are same length (returns 0 if initial strings were
0 else 0
```
[Answer]
# Ruby, 133 bytes
```
->a,b{a.size!=b.size||(m=a.chars.zip b.chars).any?{|i,j|m.any?{|k,l|(i==k)^(j==l)}}?0:m.select{|x,y|x!=y}.uniq.transpose.map(&:join)}
```
[Try it online!](https://tio.run/nexus/ruby#LcZLCsIwEADQq7Qbk0AcXBdiDyIKkxpw2iTGpkI/k7NXUFfv7ak6nlHbDSHT6mpjvzLLYBC6B44ZVkqV/V0BxqXdmHTP4f9Be5ZkzKBusjfGq1LaUxMgO@@6aeNZLzzXZinwjvSCacSY0zM7CJjkoemfFFW5iBEt3YWuRI5IXlz3/QM "Ruby – TIO Nexus")
More readably:
```
->a, b{
# Pair the letters in each string - [AB, AB, AB,...]
pairs = a.chars.zip(b.chars)
# If there's any combination of two pairs that share one character but not both,
# or if the strings have different lengths, then the input's invalid.
if a.size != b.size || pairs.any?{|i,j| pairs.any? {|k, l| (i==k)!=(j==l) }}
return 0 # 0 isn't actually falsy in Ruby, but this challenge allows it anyway
end
return pairs.select{|x,y| x != y} # Remove unchanged letters
.uniq # Remove duplicates
.transpose # Change [AB, AB, AB] form to [AAA, BBB] form.
.map(&:join) # Convert the arrays back into strings
}
```
Just for kicks, here's an 84 byte version in Goruby, which is Ruby, but with a golf flag set when compiling the interpreter. Among other things, it allows you to abbreviate method calls to their shortest unique identifier.
```
->a,b{a.sz!=b.sz||(m=a.ch.z b).ay?{|i,j|m.y?{|k,l|(i==k)^(j==l)}}?0:m.rj{|x,y|x==y}.u.tr.m(&:j)}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~198,193,189,182,179,175,169,~~165 bytes
```
def f(a,b):
r=([""]*2,0)[len(a)!=len(b)]
for u,v in zip(a,b):
if r:
q,w=r
f=q.find(u)
if u!=v:r=(([q+u,w+v],r)[f>-1 and w[f]==v],0)[f<0 and v in w]
print r
```
[Try it online!](https://tio.run/nexus/python2#NY7BTsMwDIbP61NkuTTZAlrCbSJIcOYNqh5cmoxIwbRJ0wIvP5wJ5IP9/fZv@zo6z7wANchzw5IVHef9waiT7KJDAXJvax5k3zD/mVhRKwvIfsL059kFzxKl3aw2myh7O9/7gKMokoi6ZW/XM20W3XwsajuuvUqy8093mgGObOt8by2JdNI/nm7a7cZGJ6cUcGHpuqRvem97D9ExTRW9fAg4lUVI2bivNzctpE6Q85UPsHDFM0y84dlhdkTaoDbECYYw1i5CiMRkIIJY6wdtahA/v7zWIG0ApKgjeCkRUrVg@ID4vyNXRRMZWt9qaFVrdPsL "Python 2 – TIO Nexus")
* -4 bytes! thanks to mbomb007 for suggesting the use of tab instead of space.
* modified the input format, again thanks to mbomb007.
[Answer]
# Python 3.6, ~~211~~ ~~185~~ ~~181~~ 178 bytes
Exits with an error for falsy results.
```
def f(x,y,d={}):
for a,b in zip(x,y):1/(a not in d or b==d[a]or len(x)-len(y));d[a]=b;1/([*d.values()].count(b)<2)
return map(''.join,zip(*[x for x in d.items()if x[0]!=x[1]]))
```
This requires Python 3.6, which you can run in a shell [here](https://www.python.org/shell/).
You can test it *without the correct output ordering* on TIO [here](https://tio.run/nexus/python3#PVDBcpwwDD3vfoVCDrF3KCn0timHdpqc8gVhOAgQjTpewVgmgXT67Rt7m3Z08HtPetIbnwcaYTRrvuVD/fuPPe534@QB8w5Y4I3n1LLH8tYgyBSSOEAc6Op6aLCNyJGY1X5Kz2btXVLr7i4amsNQvKBbSI1ti35aJJjOfq3sfucpLF7ghLO5uSl@TSx5OnVoVkjX18uZggOdopdHWJvP7VW9NmXbWnt@fWZHUMao15BCAytM4jYQ6kkV/QYd9bgoAQc4LRoiB09KCYRXIoFAUe1RSYv9LvjtOHuO@RxrMKM5UAxuWOYlGGv//oyNuWntaQ7wRH76wS@sPMm995P/cD@gU7LnrMOQ5ZApztk@UxKlRMtKyioKHjseLn1BdlFATQyHCL@UVarEv31/TBXFDiXWZUZ@Lg598gif0P3fokkqszyrqn8obnkH). (TIO doesn't have 3.6).
**Ungolfed:**
```
from collections import*
d=OrderedDict() # keep order
x,y=input()
if len(x)!=len(y):1/0 # equal lengths
for a,b in zip(x,y):
if a in d and d[a]!=b:1/0 # no duplicate keys
else:d[a]=b
if d.values().count(b)>1:1/0 # no duplicate values
print map(''.join,zip(*[x for x in d.items()if x[0]!=x[1]])) # format, no no-ops
```
If only order didn't matter...
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~108~~ 119 bytes
```
{c=[{_<>_|[[_,_]]|orderedUniq}()]d=[]e=[]c|_|{{d+=a;e+=b}if[a!=b]}for a,b[d,e]if[0,1]|{|n|c|[_[n]]|sort|count|[_2=1]}_}
```
[Try it online!](https://tio.run/nexus/roda#LYy9TsQwEITr@CmWK9BFl4KEEowENS2Vsaz1Tw5LvnWwc1WcZw@Ogr4daTSanRt6goU1I//eFsPFol7fVBFCdUrKEpN1ydkv8r/ruZWWC@mqTFFlWeyF44u7cL36UeAD13IdYwLstLCdkzV86npZlkLFFKEE1cEc01xMvNNck4H3clXr1uQp@BkKHO@gwUbWNEKYH0z5jK3s4N/rVsq9WDUlT/NZPZ5OHRy3@5Y1NpJj66ZxhowTy46yg36gfmAJtbeQCX1gmDNgCOy5H3bg/eNzhyH5G4ajlBlqMIZppAogXe8B0x8 "Röda – TIO Nexus")
This is a function that takes two lists of characters from the stream and pushes two lists to the stream.
This could be sorter if I was allowed to return pairs.
Explanation (out-dated):
```
{
c=[{
_<>_| /* pull two lists and interleave them */
[[_,_]]| /* "unflat", create lists from pairs */
orderedUniq /* remove duplicates */
}()] /* c is a list of the pairs */
d=[]
e=[]
c| /* push the pairs to the stream */
_| /* flat */
{ /* for each pair (a, b): */
{ /* if a != b (remove "1-to-1 relations"): */
d+=a;
e+=b
}if[a!=b]
}for a,b
/* return d and e if no character is mapped to more than one character */
[d,e]if c|[_[0]]|sort|count|[_2=1]
}
```
Here's an underscore solution that contains no variables (114 bytes):
```
{[[{_<>_}()|[[_,_]]|unorderedUniq]]|[[_()|_|[_]if[_1!=_2]],[_1()|_|[_2]if[_1!=_2]]]if[[_1()|_][::2],[_1()|_][1::2]]|[sort(_)|count|[_2=1]]}
```
That's a lot of underscores.
[Answer]
# AWK, 140 bytes
```
BEGIN{RS="(.)"}RT~/\W/{S=1}RT~/\w/&&S{if(RT!=x=A[++b]){if(B[z=RT]==""){B[z]=x
c=c x
d=d z}a=B[z]!=x?0:a}}!S{A[++a]=RT}END{if(a==b)print c,d}
```
Usage:
Place code in `FILE` then:
```
awk -f FILE <<< "string1 string2"
```
The input strings need to be whitespace separated.
The output is empty if they fail, or 2 strings separated by a space.
[Answer]
# k, 28 bytes
```
{$[(y?y)~x?x;+?(~=/)#x,'y;]}
```
Explanation:
```
{ } /function that takes in two strings, x and y
$[ ; ;] /if statement (to check if there is a mapping)
x?x /first index of [each letter in x] in x
(y?y) /first index of [each letter in y] in y
~ /make sure they match
x,'y /zip together the two strings
(~=/)# /remove equal pairs
? /unique pairs only
+ /transpose ("unzip", in a way)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/) with [AGL](https://github.com/abrudz/agl), 22 bytes
```
{≡/⍳⍨¨⍺⍵:↓⍉↑∪⍺(≠é,¨)⍵}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#NYy9CsJAEIR7X@QUxCNnl04LRfABbDfmh8C5CblYiNgGU5woYq9dtBUbS32TfZG4V8g0883sDh0uk9lCxKmOfClllpcSEi1H0/kg3IDOEtHGVB23VN8k2SfZ5tOQfZN9@VSdydZUnWj/4KhL9fV773@aHpe7thUBlCIWBnLRESZCEzF5Cj3FXECQhq5FSDUzGMME2vmhp5yYR@O5E2cBIMudYLLWULgXTFeg/xuGkyUg4xLRtR5bpcQP "APL (Dyalog Unicode) – TIO Nexus")
`{`…`}` anonymous function:
If…
`⍺⍵` the arguments
`⍳⍨¨` when self-indexed (i.e. the first occurrences of their elements in themselves)
`≡/` are equivalent
`:` then:
`⍺(`…`)⍵` apply the following tacit function to the arguments:
`,¨` concatenate corresponding elements (errors on mismatching lengths)
`é` then filter by (`é` is just the primitive function `/`)
`≠` where the strings are different
`∪` unique (remove duplicates)
`↓⍉↑` transpose list-of-pairs to pair-of-lists (lit. mix into table, transpose table, split into lists)
else, do nothing
[Answer]
## CJam, 38 bytes
```
{_:,~={1\/;}:K~z{)\c=!},L|z_{_L|=K}%;}
```
Input and output are arrays on the stack.
[Answer]
# PHP (>=7.1), 165 bytes
```
for([,$x,$y]=$argv;a&$c=$x[$i];$t[$c]=$d)$z+=($d=$y[$i++])&&$d==($t[$c]??$d);foreach($t as$a=>$b)$a==$b?:$r[$a]=$b;print_r($z<$i|array_unique($r)<$t||a&$y[$i]?0:$t);
```
prints `0` for falsy, associative array else. Run with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/47b3099c006ecc0c19e264c4bfb76437c414d6d6).
**breakdown**
```
for([,$x,$y]=$argv; # import arguments to $x and $y
a&$c=$x[$i]; # loop through $x
$t[$c]=$d) # 2. add pair to translation
$z+= # 1. increment $z if
($d=$y[$i++])&& # there is a corresponding character in $y and
$d==($t[$c]??$d); # it equals a possible previous replacement
# remove identities from translation
foreach($t as$a=>$b)$a==$b?:$r[$a]=$b;
print_r(
$z<$i # if not all tests passed
|array_unique($t)<$t # or there are duplicates in the translation
||a&$y[$i] # or $y has more characters
?0 # then print 0
:$r # else print translation
);
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 96 bytes
Throws an error for a negative result.
```
->a,b,**h{a.chars.zip(b.chars){(h[_1]&&h[_1]!=_2)?fail: h[_1]=_2}
h.map(&:join).grep_v(/(.)\1/)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BTsMwEEX3OYXxIrIr15XNBlUqCBZdcYMQhUnq1kGpa9kxElQ9CUKKEByK22AnrdBf_Jmn0cyfj28X6rfha736Cf12fvP7PL8FVrPZTB-BNxqc5--tJfVU0yPRRSXKPB_talVJereFtluiEcT-lGm-B0vy5cuhNZTvnLLVK1kQTp_Egp7Odz6LDKECe2W8wgwLaYTEJRthDX1EHuwFXAuZFOH9w2PS_6SJihzMLnTgLhxMu4cuLTExnE-45AoajTaHOGDROqZllSyRU74JCtnQe4TTJzhTZjOFHIbJ_wA)
] |
[Question]
[
Given a multidimensional, rectangular array and a list of dimensions, such as:
```
[ [1, 2],
[3, 4] ]
[3, 4]
```
Your challenge is to extend the matrix to the dimensions given in the list.
To extend an array to a length in a single direction, simply repeat its elements; for example, if we want to extend `[1, 2, 3]` to length 7, the result would be `[1, 2, 3, 1, 2, 3, 1]`.
For example, with the above, we can extend it to length 3:
```
[ [1, 2],
[3, 4],
[1, 2] ]
```
Then extend each row to length 4:
```
[ [1, 2, 1, 2],
[3, 4, 3, 4],
[1, 2, 1, 2] ]
```
However, your code should work for arrays with arbitrary dimensions. For example, if we take the 3D array
```
[ [ [1, 2],
[3, 4] ],
[ [5, 6],
[7, 8] ] ]
```
And dimensions `[3, 3, 5]`, the result is:
```
[ [ [1, 2, 1, 2, 1],
[3, 4, 3, 4, 3],
[1, 2, 1, 2, 1] ],
[ [5, 6, 5, 6, 5],
[7, 8, 7, 8, 7],
[5, 6, 5, 6, 5] ],
[ [1, 2, 1, 2, 1],
[3, 4, 3, 4, 3],
[1, 2, 1, 2, 1] ] ]
```
You can assume that the dimensions will be strictly greater than the corresponding dimensions of the array, and that there will be the same amount as the list has dimensions. You may take dimensions in reverse.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
```
[[1, 2], [3, 4]], [3, 4] -> [[1,2,1,2],[3,4,3,4],[1,2,1,2]]
[[[1,2],[3,4]],[[5,6],[7,8]]], [3, 3, 5] -> see above
[1, 2, 3], [5] -> [1, 2, 3, 1, 2]
[[4], [3], [2]], [4,3] -> [[4,4,4],[3,3,3],[2,2,2],[4,4,4]]
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~13~~ 8 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
A bit closer to 4 bytes. Takes the array as left argument and the shape vector on the right.
```
(⍉⁼⥊⎉1)´
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKNieKBvOKliuKOiTEpwrQKCuKfqApbWzEsMl0sWzMsNF1dICAgICAgICAgICAgICAgICBGIFszLDRdCltbWzEsMl0sWzMsNF1dLFtbNSw2XSxbNyw4XV1dIEYgWzMsMyw1XQpbMSwyLDNdICAgICAgICAgICAgICAgICAgICAgICBGIFs1XQpbWzRdLFszXSxbMl1dICAgICAgICAgICAgICAgICBGIFs0LDNdCuKfqQ==) <- This uses the new array notation using `[]`.
The reduction `´` iterates over the shape vector from right to left, using the large array as a starting value. `⥊⎉1` resizes the trailing axis by cycling elements, then `⍉⁼` rotates this axis to the front.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
##~PadRight~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19ZuS4gMSUoMz2jpE5Z7X9AUWZeSXS1snKtgq6dQlq0snJsrIKagoODA5dCNRAY6igY1eooVBvrKJjUIjG4FLBLV5vqKJiBGOY6Cha1MB1AZArTBNICFAHJwMWqTcAKQYQRWI8JSEVt7X8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, ~~65~~ 63 bytes
```
[ [ swap '[ _ cycle ] [ '[ _ map ] ] repeat call ] each-index ]
```
[Try it online!](https://tio.run/##bVDPa8IwFL73r/huOynMVh2OeVQ8qDDxVMoI2asWY1qTjK2W/u3da1pYGeZB3vt@hSSpkC43zfGw2a0XSE2JCxlNCpZuX6QlWVyFO6Mw5FxZmEw7CGtzaXEiTUao7C5clmuL12D1vt8u/pJjQwWxqE94W0KWUhGbgioAr8rXMyaouYeIuA@mgeeRq8IUMz/N8eK5Tg@ZH6bbZOi16b9Toz7R7pM@H3lcB3UTI4b9FgWeYnz0V0@Y8/DKfMLVPQ9SKMWIhDyPMv1JP0iatPukZWsdN78 "Factor – Try It Online")
This is very unlike how my Factor golfs usually turn out (what with constructing multiple functions and calling them in turn). I noticed that every solution follows this pattern:
* `[[1, 2], [3, 4]], [3, 4]` ->
`3 cycle [ 4 cycle ] map`
* `[[[1,2],[3,4]],[[5,6],[7,8]]], [3, 3, 5]` ->
`3 cycle [ 3 cycle ] map [ [ 5 cycle ] map ] map`
So curry each dimension into the innermost quotation with `cycle`, then build up the nested map quotations around it based on its index in the list of dimensions and call it. Since recursion is extremely verbose in Factor, this iterative approach is all but guaranteed to be shorter.
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
f=lambda m,d:d and[*map(f,m*d[0],d[0]*[d[1:]])]or m
```
[Try it online!](https://tio.run/##PY5LCsMwDETXzSm0tIMWza8NgZ5EaOEiTAO1E0I2Pb0rpR8QI2neILS@9seSu1Li7RnSXQIklEkgZKE6hdVFTLXQmdGkJqFmYva8bJBKNEUQmDNQ5YgahJYRqEPo@T94NKZQmTpGiAa8aLviyL@g1vDJ2hndzf861B8hk/bI99gZ4ak6rducdxedPu59eQM "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„∍ε«J.V
```
First input is the list of lengths; second the matrix.
[Try it online](https://tio.run/##yy9OTMpM/f//UcO8Rx2957YeWu2lF/b/f7SxjrGOaSxXdHS0oY5RrA6QbxILpKJNdcyAlLmORWxsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkAAX/P2qY96ij99zWQ6u99ML@6/yPjo421jGJ1YmONtQxAlIgTmysjgJI2FjHFCSBLAPkmuqYASlzHYtYqEKQIqASHWMI1wTIACoDmQliGIGUAQA).
**Explanation:**
```
„∍ε # Push string "∍ε"
¬´ # Append it to each integer of the first (implicit) input-list
J # Join this list together to a single string
.V # Evaluate and execute it as 05AB1E code
# (after which the result is output implicitly)
```
`∍` is the extend buildin, which does exactly what this challenges asks: given a list and integer arguments, extend the list to the given integer's length. `ε` is the map builtin, which stays open until we close it with `}` or `]` (which we don't want to do in this challenge).
For example: `„∍ε«J` will convert the list of lengths `[3,3,5]` from the example of the challenge to string `"3∍ε3∍ε5∍ε"`. Evaluated and executed as 05AB1E code, this will:
```
3‚àç # Extend the (implicit) 3D input-matrix to 3 inner matrices
ε # Map over each inner matrix:
3‚àç # Extend the matrix to 3 inner rows
ε # Map over each inner row:
5‚àç # Extend the row to 5 values
ε # No-op map
```
Luckily `'∍ε` isn't a [dictionary word](https://codegolf.stackexchange.com/a/166851/52210), otherwise the `„∍ε` would had to be `"∍ε"` instead.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
⊞υθFη«≔⟦⟧ζFυ«≔⁺ζκζF…κ⁻ιLκ⊞κλ»≔ζυ»⭆¹θ
```
[Try it online!](https://tio.run/##PY7JCoMwEIbP@hRzTCA9dLEteCpeKwg9hhxErAmGaI0p1OKzpxNrOwzM8v2zVLIcqq7U3hfOSuIYPGga37sBiKTwjqOLtaoxhAsGE5JoQW5BP1ZoZ8nEoKWr5ivKXpWuM9n1pGWQK4MixeBam2aUpKVosNxEqsPU/D@Guxx25rgYlBnJbcTQ5GVPtuE9mnrP0bDY4Vd8z@AgQsITBseQnBichVgZeiKE3zz1Bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υθ
```
Start by considering the first dimension.
```
Fη«
```
Loop over the new dimensions.
```
≔⟦⟧ζ
```
Start collecting the elements of that dimension.
```
Fυ«
```
Loop over all of the lists of that dimension.
```
≔⁺ζκζ
```
Collect the elements of the list.
```
F…κ⁻ιLκ⊞κλ
```
Cyclically append sufficient elements to reach the desired length.
```
»≔ζυ
```
Save the elements as the list of lists of the next dimension.
```
»⭆¹θ
```
Pretty-print the expanded array.
[Answer]
# [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), ~~59~~ ~~57~~ 56 bytes
```
lambda m,d:tile(m,d)[[*map(slice,d)]]
from numpy import*
```
[Try it online!](https://tio.run/##PY5JDoMwDEXX5RReBuRNCbQVUk/iZkELUSORQSFdcPrUoYNkefjv23LY0tM7mfX1lpfR3qcRLE5DMsssuKmJGjsGsS7mMfOoVKWjt@BeNmxgbPAxNVn7yFswgXFAlSA6IrQKgSRCp/5NjYUxZMZKIUQ9nric8aJ@Ro7@4y1neC76V6FuN5XU7v4OZSFqqA4hGpeE3t@u8xs "Python 3 – Try It Online")
‚àí2 thanks to loopy walt, and another ‚àí1 by changing back to the deprecated use of a list for indexing.
[Answer]
# [R](https://www.r-project.org), ~~62~~ ~~55~~ 51 bytes
*Edit: -7 bytes thanks to Giuseppe, and -4 bytes thanks to pajonk*
```
\(a,d,`*`=array)a[t(t(which(T*d,T)-1)%%dim(a)+1)]*d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHa1IqS1LyU-MSiosRK26WlJWm6FjeNYzQSdVJ0ErQSbMHimonRJRolGuUZmckZGiFaKTohmrqGmqqqKZm5Goma2oaasVopUK2aiRAtGoZWRiY6RlYmmlwptsZWplzI9oBM14RoWLAAQgMA)
---
# [R](https://www.r-project.org), 49 bytes
```
\(a,d)array(a[t(t(which(!a*0,T)-1)%%dim(a)+1)],d)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHa1IqS1LyU-MSiosRK26WlJWm6FjcNYzQSdVI0wWIaidElGiUa5RmZyRkaiolaBjohmrqGmqqqKZm5Goma2oaasUClUI2aibYQTYZWRiY6RlYmmlwptsZWplzItoDNhmhYsABCAwA)
Works with arrays of finite numbers. In this case, we don't need to create a new array of `TRUE` elements to get the indices, as we can just multiply the elements by zero and take the logical NOT.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 22 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{‚ü®‚ü©ùïäùï©:ùï©;(1‚Üìùï®)‚ä∏ùï䬮ùï©‚•äÀú‚äëùï®}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHvin6jin6nwnZWK8J2VqTrwnZWpOygx4oaT8J2VqCniirjwnZWKwqjwnZWp4qWKy5ziipHwnZWofQoKCuKAolNob3cgM+KAvzQgRiDigKJKcyAiWyBbMSwgMl0sCiAgWzMsIDRdIF0iCgrigKJTaG93IDPigL8z4oC/NSBGIOKAokpzICJbIFsgWzEsIDJdLAogICAgWzMsIDRdIF0sCiAgWyBbNSwgNl0sCiAgICBbNywgOF0gXSBdIgoK4oCiU2hvdyA1IEYgMeKAvzLigL8zCgogNOKAvzMgRiDigKJKcyAiW1s0XSwgWzNdLCBbMl1dIg==)
recursive is shorter `¯\_(⌾‿⌾)_/¯`
# [BQN](https://mlochbaum.github.io/BQN/), 26 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{ùï©{a‚Äøbùïäùï©:a‚•ä‚öábùï©}¬¥ùﮂãମ‚åΩ1+‚Üï‚â†ùï®}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHvwnZWpe2HigL9i8J2VivCdlak6YeKliuKah2LwnZWpfcK08J2VqOKLiMKo4oy9MSvihpXiiaDwnZWofQoKCuKAolNob3cgM+KAvzQgRiDigKJKcyAiWyBbMSwgMl0sCiAgWzMsIDRdIF0iCgrigKJTaG93IDPigL8z4oC/NSBGIOKAokpzICJbIFsgWzEsIDJdLAogICAgWzMsIDRdIF0sCiAgWyBbNSwgNl0sCiAgICBbNywgOF0gXSBdIgoK4oCiU2hvdyA1IEYgMeKAvzLigL8zCgogNOKAvzMgRiDigKJKcyAiW1s0XSwgWzNdLCBbMl1dIg==)
[Answer]
# Brev, 99 bytes
```
(define(j l . m)(j((over(apply j x(cdr m)))l)(car m)))
(define(j l k)(take(apply circular-list l)k))
```
(Displayed with one unnessecary newline for clarity.)
Example usage:
```
(pp (j '(((1 2) (3 4)) ((5 6) (7 8))) 3 3 5))
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 58 bytes
```
def r($r):[.[range($r[0])%length]|r($r[1:])? //.];r(input)
```
[Try it online!](https://tio.run/##NYrBDoIwEETv/Yo5aEKTAqIiBg9@yGYPRitCTMFab36762LizFxe3gwPkYu/ImaLaFsqKJ5C5xVoxXZ596FLN37PlqqW7RFlWfAhZn2YXsmKELSVw5qdgYY2DlvGj9TUDru/aRz2asDGzC9dzZ9xSv0YnpKfvw "jq – Try It Online") ~
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3BZtJJuslLsgqWlJWm6FjetUlLTFIo0VIo0raL1oosS89JTgZxog1hN1ZzUvPSSjNgakGy0oVWspr2Cvr5erHWRRmZeQWmJJsQEqEELbtpHKwChoY6CUawOlwIQRBvrKJjEKoB5QBlTHQUzmIy5joIFUEYhlosLpAqITGMh5gAA) ~
[jqplay.org](https://jqplay.org/s/ZkWpJCZdwmP)
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 20 bytes
```
aH:PObb?fMZa[b]RL#aa
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWWxI9rAL8k5Ls03yjEqOTYoN8lBMTIVJQFTd1opWio6MNrY1iraONrU1igVS0qbUZkDK3toiNjVXSUVACShhbm8bCjQUA)
### Explanation
Kinda ugly, too bad Pip doesn't have any way to do currying or partial application.
```
aH:PObb?fMZa[b]RL#aa
b ; Second argument, the list of dimensions
PO ; Pop the first element (call it N)
a ; First argument, the matrix
H: ; Take the first N elements (cyclically) and assign back to a
b? ; Is b still nonempty?
; If so:
a ; Take the array
[b] ; and a list containing b
RL#a ; repeated len(a) times
MZ ; Zip together and map to each pair
f ; a recursive call to the main function
a ; If not, just return a
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=), 8 bytes
```
∧(⍉↙⊃∘▽)
```
[Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAg4oinKOKNieKGmeKKg-KImOKWvSkKCmYgM180IFsxXzIgM180XQoKZiAzXzNfNSBbCiAgW1sxIDJdCiAgIFszIDRdXQogIFtbNSA2XQogICBbNyA4XV1dCg==)
Pretty much the same thing as ovs' [BQN answer](https://codegolf.stackexchange.com/a/248800/97916).
] |
[Question]
[
To be able to challenge the Elite-4 of top programmers, you need to show your badges first, that qualify you as a potential programmer-master. However, there's a twist. Once you show a badge, it is collected, which means you can't re-show it. So better come prepared! There are `n` badge collectors, each has a known list of `accepted_badges`. Given a list of your `badges`, your task is to find out, if you can access elite-four or if you require more badges. You can indicate this by printing a truthy-value for the first case or a falsey-value in the second case.
**Example**
```
accepted_badges: [ [a, b, c], [a, b, d], [d, e, f]]
```
If you have the badges `[a, b, d]` you can pass. Simply give your `a` badge to the first collector (`accepted_badges[0]`), your `b` badge to the second and your d badge to the last collector. So this is a truthy case.
If you have the badges `[a, b, c]` you are in bad luck. The last collector doesn't accept any of it.
If you have the badges `[b, c, d]` you can also pass. Here you will need to give your `c` badge to the first collector, the `b` badge to the second and the final collector will get the `d` badge.
If you have the badges `[a, e, f]` you will not be admitted, because you would have to use your a badge twice (since the first collector takes it away from you), which is not possible.
**Input:**
>
> A list\* of your badges
>
> A 2Dlist\* of badge collectors and their accepted badges
>
>
>
\*list can be the following:
```
1. a list, i.e. [a, b, c, ...] or [[a,b,c],[c,d,e]]
2. a list with first element = number of elements i.e. [3, a, b, c] or [ [2], [3, a, b, c], [1, a]]
2. a string "abcd..."
3. a string with leading number of elements i.e. "3abc"
4. a seperated string i.e. "abc,def,ghi"
5. a separated string with leading numbers of elements i.e. "3abc,2ab,5abcdef"
6. or any other convenient input format you can think of
```
**Assumptions:**
You may assume:
* any list to never be empty
* input letters to always match `[a-z]`
* your number of badges matches the number of badge collectors
You may not assume:
* that any list is sorted
**Test cases (list format):**
```
['a','b','c','d']
[['a','b','c'],['d','e','f'],['b','c','d'], ['c', 'g']]
Truthy
['a', 'a', 'a']
[['a', 'b', 'c'], ['a', 'd', 'e'], ['a', 'b', 'e', 'f']]
Truthy
['a', 'a', 'f']
[['a', 'c', 'f'], ['a', 'd'], ['b', 'c']]
Falsey
['x', 'y', 'z', 'w']
[['x', 'y'], ['x', 'y'], ['z', 'w'], ['x', 'y']]
Falsey
['p', 'q', 'r', 's', 't']
[['p', 'q', 'r'], ['r', 'q', 'p'], ['r'], ['s', 't'], ['p', 'q', 'r', 's', 't']]
Truthy
['p', 'q', 'r', 's', 't']
[['p', 'q', 'r', 's', 't'], ['p', 'q', 'r', 's'], ['p', 'q', 'r'], ['p', 'q'], ['p']]
Truthy
```
**Test cases (String format):**
```
"abcd"
"abc def bcd cg"
Truthy
"aaa"
"abc ade abef"
Truthy
"aaf"
"acf ad bc"
Falsey
"xyzw"
"xy xy zw xy"
Falsey
"pqrst"
"pqr rqp r st pqrst"
Truthy
"pqrst"
"pqrst pqrs pqr pq p"
Truthy
```
Lastly, this is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") so the answer with the least number of bytes wins. Please refrain from using any standard-loopholes.
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
One of the few cases where itertools is useful.
```
lambda b,a:s(b)in map(s,product(*a))
s=sorted
from itertools import*
```
[Try it online!](https://tio.run/##nY7BDoMgDIbvPgU3cPG04xKfxHkAlc1EhQHL5l7eWURXNV52@Wm@0q/Vvbur7jzI9Do0vBUlJyLhF8tEXHek5ZrZRBtVPgvHTjyOI5taZVxVRtKoltSuMk6pxpK61SM/DdrUnSOSZZTThFABUUCUNE9ItsZAxsZYVxByAtuZqb7RPI@jjT7EgZlPDq//AYH3HSglVhboNo7OmletHG@APcQH4hVEAfs5XKNPC1/5NMAHhIGwEC5Icc8bzAL0DPyDpo6Efy1d9/atHcUg1OPm4Qs "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda s,l:l and any(f(s.replace(x,'',1),l[1:])for x in l[0])or''==s
```
[Try it online!](https://tio.run/##bZA9DoMwDIV3TuHNIEVV6YiUk6AMgSQtUhpCEqnQy9P8oNKhg/2e7M8ent3CYza3fVdU8@cgOHiiOw3ciFhbrWp/cdJqPsp6JYikbYju2441anawwmRA91fWzA6RUr8H6YMHCn0F0CMfRoGkmKgopEpSpjjekTFSQM5/OS5kliHyEYGDUYUZVWHKqxNYt/crE@uWVqXnUfJfzC7Oh8xFl5ZusVlSy5sD@X9xEocWyT2eVKyqUjSegE7p5EC6@Ma6yQSIeRLd7B8 "Python 2 – Try It Online")
Tries every possible character from each list entry in turn, removing it from the target string `s` if present, and checking if we end up with the empty string. The `s.replace(x,'',1)` removes at most one copy of `x` in the string `s`.
An annoying issue is that in the base case where `l==[]`, we get an error when we try to read `l[0]` even if the result doesn't matter, making it hard to cut the `l and`. It "almost" works to save a byte as below, but we get an error when `l` becomes empty because the `l[0]` is evaluated before the `if l` is tested and fails.
```
f=lambda s,l:s==''or any(f(s.replace(x,'',1),l[1:])for x in l[0]if l)
```
[Try it online!](https://tio.run/##bZCxDoMwDER3vsKbQYqq0hGJL0EZAiQtUgohiVTSn6dOgkqHLr6T79nDmeAfy3zbd9Vq8exHAY7pxrUt4mJBzKFUpbtYabQYZLkxRFZXTHd1wytFxAbTDLq78kmBrnYvnXfQQlcAdCj6YUSWDSmOUkXJWxzuyDnLoBC/nBhlkp54QuBgVGYGlZn86gS28H4lYgsxyjOtov9iZrXOJ45cDO1qksSRkgP5f3ESh2ZJk04KXhSxF8dAx2pSIQ29MXaaPVCZjGr6AA "Python 2 – Try It Online")
**69 bytes**
```
f=lambda s,l:any(f(s.replace(x,'',1),l[1:]+[[]])for x in l[0])or''==s
```
[Try it online!](https://tio.run/##bZDNDoIwEITvfYq9LcTGiEcSnqTpoUCrJBVq20Tw5Wt/iHjwsjPZ@XYPYzZ/X@ZrCKrT4tGPAhzVrZi3SlXubKXRYpDVShFpU1PNmpafGOO8VouFFaYZNLvwerGIXeeCl8476IARAIaiH0akxUTFUaokZYvDDTmnBRTilxOjzNJHPiKwM6owgypMeXUA6/Z@ZWLdUlRmXiX/xczTOp@56FJonyZLGjnZkf8XB7FrkTzjCeGEpGocBZ3ayYW08Y2x0@whlkp1HT4 "Python 2 – Try It Online")
Pad `l` to the right with empty lists.
**69 bytes**
```
f=lambda s,h,*t:t and any(f(s.replace(x,'',1),*t)for x in h)or s in h
```
[Try it online!](https://tio.run/##bZBBjsIwDEX3PYV3aZCFxCyROAnqwm0SWimUkESinct3HKcaWLCw/5f97MUPax4f88@2uYune28IEo54yOcMNBuutXVtOkYbPA22XVApPGkGtHtEWGCaYdTskrgt25QTXODaAFwV9YNRWA2rMtYVqVM13FTXYQWJPjkyVqRnnhHYGVeZwVWmvnoDy/r7EmJZy6p2GRX/j4VnTFk4dmUZn0GkNNnsyPeLN7FrFel80nRNU5JJCL5EIoGc@U2I05yBs8TDnULrp5TRa739AQ "Python 2 – Try It Online")
Takes input as the target string, followed by a splatted list of lists.
---
## 69 bytes
```
f=lambda s,l:any(f(s.replace(x,'',1),l[x in l[0]:])for x in s)or[]==l
```
[Try it online!](https://tio.run/##bZBNDsIgEIX3PcXsaBNi1GWTnoSwoC1oE2wRSAQvjzA01oWb9@bnm1k8E/19W68pqUGLxzgLcFT3Yo2tat3JSqPFJNtACaGXjmoWYFlBszPveac2C9i7brOMD4NOXjrvYADWADAixmkmtBbZySxVsTol041wTisoxC8nZok2Zj4jsDOqMpOqTH11ACG@X0iEWFZVcVTqL2ae1nnkclWW9mnQiuBmR/5fHMTu1VDzScObpuTiKOgSDQbS5zfGLquHHCrVXfoA "Python 2 – Try It Online")
A "dual" method based on [ovs' solution](https://codegolf.stackexchange.com/a/203503/20260), iterating over characters in the target string and removing from the list.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
import Data.List
(.permutations).any.flip elem.mapM id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzVZDryC1KLe0JLEkMz@vWFMvMa9SLy0ns0AhNSc1Vy83scBXITPlf25iZp5tQVFmXolKWnS0kY6hjkGsTrSxjqWOEYiOjQWygaKx/wE "Haskell – Try It Online")
# Without imports, 85 bytes
```
x#[]=[[x]]
x#(a:b)=(x:a:b):map(a:)(x#b)
(.foldr((=<<).(#))[[]]).any.flip elem.mapM id
```
[Try it online!](https://tio.run/##FYtBCsMgEADveUXAHnZBpE1PlfiEvmDZgyFKpWol6cG83pjTDAPzsfvXxdhaFcSGqDIPVYDVCxqo@qJOtvSAUMWCgzeg/C@uG4CZZ1QgEImYUdl8KB9DGV10SfXpPYa1JRuyKVvI/5snmuRD3lnSU77kdJG5e6/cTg "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 79 bytes
```
f=lambda a,b:a==[]or any(f(a[x in a[0]:],b[:i]+b[i+1:])for i,x in enumerate(b))
```
[Try it online!](https://tio.run/##bZCxbsMwDER3fwU32bCGpqMAf4mggbSlVECjOLKC2vl5R6KMukMX3oH3yOHmLX3dw@e@u@EbbzQhoCSFw6DNPQKGrXUt6hV8ANQfRhlJWnnTk/b9RZnOZcpLzm143mzEZFvquj3ZJS0wgG4AtEAaJyGrySom64rUrRivwhhZQcS/HE6WhTKfETgYV5nRVaa@OoF1e/0wsW4lqpNXxf9i8yMuibnsShgfM0sZnBzI/xcncWgVnvmkMU1T2iEJWOrhQlR@M0cfEuRaJXX7Gw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
*-1 byte thanks to @KevinCruijssen*
```
œεøε`¢]PZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6ORzWw/vOLc14dCi2ICo///T0pK4opUSk5KVdBSUElNSwVRSappSLAA "05AB1E – Try It Online")
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 138 bytes
Aaargh! Erlang's cartesian product is eeeeevil! (It saved 20 bytes anyway.)
```
f(A,B)->lists:member(lists:sort(A),[lists:sort(tuple_to_list(C))||C<-sofs:to_external(sofs:product(list_to_tuple([sofs:set(I)||I<-B])))]).
```
[Try it online!](https://tio.run/##hZDbisIwEIbvfQrJ1QRSH6CIoF75DEVKmkwk0JNJxCq@e52Jy66woIH8mflnvpwwtLo/FRhN8GOaF7ODrdrJYtP6mGLZYddggFcSh5BgK1X1lqbL2GKdhpo92Ev5eOzXRRxcLMnEKWHodQvZGMNgLybl3RjJLFS5FjHBgeDDutgdpZRHuZo77Xuo5bLYLJY0/FBeg08IDoRujBWq4lUoYdGRZkuYkyBeUXPfglT/Sa3/QG2RtSH@C@QyZFyG8mGfiel2vzIy3ag5C@ccfcTGc4iJOQqoPZxHVprs5uqXi/Kzfl/X2J/PeWNW8xM "Erlang (escript) – Try It Online")
# Explanation
Here `...` stands for nest the previous line inside this position.
```
f(A,B)-> % Take 2 items.
[sofs:set(I)||I<-B] % Convert every item of B into a sofs set
list_to_tuple(...) % Convert the input list into a tuple
sofs:product(...) % Cartesian product of this set tuple
sofs:to_external(...) % Pick the value of the cartesian product
C<-... % Assign it to the variable C
[lists:sort(tuple_to_list(C))||...] % For every item, convert the tuple to a list
% And then sort that list
lists:member(lists:sort(A),...). % Is argument 1 a member of the processed list?
```
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~66~~ 65 bytes
Port of my Python answer.
-1 byte thanks to @AdHocGarfHunter.
```
b#(a:s)=or[x!b#s|x<-a,elem x b]
b#x=1>0
x!(a:b)|a==x=b|w<-x!b=a:w
```
[Try it online!](https://tio.run/##hczBCsIwDAbg@57it/Wg4ECvYn0R8ZCunYrTzXbQbuzda5QdNi9CEviTj1zJ321VpaTlivZ@rWp3igst/RAPOW1sZR@I0OdMy6h2x20WF@z0eiClotJDOOTMFe1DetDtCQVTZ0Djbs8WSwjShRGQCLUz/hthbAneoriImST6gWQsSNtSYO7KqStKdvxvjmLXh4mKHbj6wHPumpfz7QRyhns1cPAtxuMfP8LP4EYj0hs "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 170 168 bytes
*Edited: Switched to returning 1 from inner `main` calls to save a byte not needing to negate the return value when assigning into `u`. Also another byte saved thanks to @ceilingcat for reminding me about `index` instead of `strchr`.*
```
f;char*l,*u;main(n,x)char**x;{if(f++){if(n){for(int i=0;l[i];i++)if(u[i]&&index(*x,l[i])){u[i]=0;u[i]=main(n-1,x+1);}return 1;}exit(1);}u=strdup(l=x[1]);main(n-2,x+2);}
```
[Try it online!](https://tio.run/##LY7LCsMgEEV/JaugxkDNVvIlIQvjox1IbbEKAyHfPtW0q3s5Z2YYO96tJQraPkwSuxRFPw1EFiXyCwnUBwQWhoG3jPwIr8Qg5g7mm94XWDVUV1Wpve8hOo9MoGyK86PROnjF7/KoJA6K6zP5XFLslD49QmYNlfmTkytvts@4qJX/nxmnujJVT0Rms46MJecDtfYF "C (gcc) – Try It Online")
A relatively straightforward recursive backtracking search. Takes input as command-line arguments, the first being the list of badges you have in a single character string (e.g. `abcd`) and each other argument being the list of badges accepted by each station in similar format. Contrary to traditional exit code logic the program's exit code is 0 when you cannot pass and 1 when you can pass, mainly because the return value of `main` is used in the program and it works out better that way. There is no output on stdout.
Originally I'd written a subroutine for the search part after initializing some state in `main` but when I abstracted the globals and saw the function signature was `int (int, char**)` I couldn't resist pulling it all back in and recursing on `main`.
Degolfed somewhat for viewing pleasure:
```
f;char*l,*u; // Declare some storage. f is a counter used to only run the setup code on the original call to main. l gets assigned to be a pointer to the list of badges held. u is used as a buffer to track which badges are currently still available to be used.
main(n,x)char**x;{ // Typical golfed main declaration.
if(f++){ // Only run the code in the if statement on subsequent calls to main (as a global f defaults to being initialized to 0).
if(n){ // Catch the recursion base case (if n == 0 there are no stations left to pass).
for(int i=0;l[i];i++){ // Iterate over the badges we have available. i needs to be declared here since each recursive call needs to iterate over badges separately.
if(u[i]&&index(*x,l[i])){ // If the badge is available to be used (the entry in u for the badge is nonzero), and the badge is accepted by the next station...
u[i]=0; // Mark the badge as unavailable for the recursive call
u[i]=main(n-1,x+1); // Recursively call main with the current station removed. If a sequence passing all stations is found the program exits immediately, so if main returns on an inner call it will always return 1; by assigning this into u we mark the badge as available again afterwards if we backtrack out of this call to continue searching.
}
}
return 1; // If we went over all our badges and couldn't get through this station, we need to backtrack the search so return 0 and continue.
}
exit(1); // If there are no stations left we passed through all of them so immediately exit with code 1.
}
u=strdup(l=x[1]); // Initialize storage for u. Initially I used calloc here, but since the needed length of u is the length of the list of badges held, strdup gets the job done while saving on bytecount (Just with the parity of the usage checks inverted since strdup means all the entries we care about are initialized to nonzero values).
main(n-2,x+2); // Make the first recursive call, with our new args starting at the first station's accepted badge list.
} // If we made it to the end without exiting the program, main will default to returning 0 since no return call was specified.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~85~~ 84 bytes
```
f=lambda b,r:b==""or any(B in r[0]and f(b[:i]+b[i+1:],r[1:])for i,B in enumerate(b))
```
[Try it online!](https://tio.run/##dZHPasQgEMbveYohPZiwFlp6C6SHHvoEvYkHjUoDu24ycemmIc@ezmS3f1JYwY8Z/X4qn92Y3o/xaVlCvTcH6wxYiZWt6zw/Ipg4Fi/QRkD1oE10EAqrqlbvrGp3j5WWqEjLQNZWrkYfTwePJvnCluWS/JAGqEFlShjrhATgohFSOB9IbeOEhs3QEu7gDU@eGWOY@YGM86yWWH2bCd9ME1Zmvef/NRfm1ewHhs7j58fldeeR7KvwClf6FtT1OCSi1oq82HesNHn5uq23r9swf2zyekbXswj9y@gs43w5Sg54jbTKgP4JkKLlnroO25iKkE92ljDhDPfPMNFvSSznvFy@AA "Python 3 – Try It Online") Golfed 1 byte by switching to an explicit enumeration.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
Sθ⊞υθFθ«Sι≔υη≔⟦⟧υFηFΦκ№ιλ⊞υΦκ¬⁼λμ»¿υ¹
```
[Try it online!](https://tio.run/##TU27DsIwDJybr/DoSGFg7oQQSCwIiRExVBVtIkLSPMyC@PbgVELt4LPPd/b1uou972wpJzdRvuZo3IhBtuJCSSMpqPPgI/ASPqJZ2wxLzS4lM7rq1Ct6uyugyudTLWHuR2PzI@JTwd6Ty2gUWCkl/LMW/ewzHgJ1NqFV8GITP/sKMwAS@zk@41a2pUwhpiwWrMAlprJ52x8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` if you can challenge the Elite Four. Explanation:
```
Sθ
```
Read the badges.
```
⊞υθ
```
Start with a single entry with all badges remaining.
```
Fθ«
```
Loop over each guard.
```
Sι
```
Input the badges he accepts.
```
≔υη≔⟦⟧υFη
```
Save the list of badges remaining so that we can clear it and still loop over the list.
```
FΦκ№ιλ
```
See whether this guard will accept any of these badges.
```
⊞υΦκ¬⁼λμ
```
If so then push the possible sets of remaining badges to the list. (If e.g. two guards both accept the same two badges then this could create duplicates depending on which badge you give to which guard but this does not affect the final result.)
```
»¿υ¹
```
If it was possible to give all the guards a badge then print a `-`.
[Answer]
# JavaScript (ES6), ~~69~~ 68 bytes
Takes input as `(b)(a)`, where \$b[\:]\$ are the collector badges as a list of sets and \$a[\:]\$ is our list of badges.
```
b=>g=a=>1/a||a.some((v,i)=>b[a.length-1].has(v)*g(a.filter(_=>i--)))
```
[Try it online!](https://tio.run/##ZZBNa8MwDIbv/RXvzfaWePS64YwdNhgb7LBjCENJ7TQjTVLb6xdlf71TSvdFwZZeiUcSvO@0olD5Zohp18/swZlDabLakMmmV7Tfkw79wkq5ShplsjIn3dqujvN0Wug5BblSF7Uk7Zo2Wi/fTNakqVLqcJNPgByCymomkmPGzDpwiarmTvQfFkVyooi@IZpZUGndOeKOSOUY4TVcOGrDL7DZ7tYjsdmC327N8YwZlj7EEWIBvxzgESK@u//u/UVPzBj4Y/hhJ8VEu97fUzWXMqcEZQJvQ6FgMlR9F/rW6rZnh3AJgVxwKkdZ4DPjLR4GTpY6DG0TpYBQekED0zze2TVebZTEdspca02FOk6Y8QRuIeTLkxK4ZvFw9/isBNv@BQ "JavaScript (Node.js) – Try It Online")
### Commented
```
b => // b[] = collector badges as a list of sets
g = a => // g is a recursive function taking our list of badges
1 / a || // yield +Infinity if a[] is empty
a.some((v, i) => // otherwise, for each badge v at position i in a[]:
b[a.length - 1] // test whether the collector at index a.length - 1
.has(v) * // accepts the badge v
g( // multiply by the result of a recursive call where:
a.filter(_ => i--) // the i-th badge is removed from a[]
) // end of recursive call
) // end of some()
```
[Answer]
# [Perl 5](https://www.perl.org/) `-lpa`, ~~86~~ 79 bytes
```
$"="}{";@a=<>;chomp@a;map{$b=$F[0];$\|=!grep!$_,map$b=~s/$_//,/./g}glob"{@a}"}{
```
[Try it online!](https://tio.run/##HcyxDsIgFEDR3b8oeSMtOHRCDJObX6CmebQETai8tG6Iny5il7Pc5JJbQl8KMM1yYsqgPhzVeI8zGVQzUgKr4XSRNwXXt2784qiBgddSw2cVMAjBRSd89iFalgzmOioFueXT7u@46Tanb6TXIz7X0p77Tu5laQPhDw "Perl 5 – Try It Online")
First line of input is the badges you hold. Subsequent lines are the ones needed. On each line, badges are comma separated.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{@^a.permutations.map(*Z∈@^b).max.min}
```
[Try it online!](https://tio.run/##jZBBCsIwEEX3nmJAMCqlSzciuPIEriwVUk1UsBrTiq3ivuf0IjWTNnXEii7yO3mTvAlVQu9HZZxDT8IEytt0yX0ldHxOebo7HhI/5qo/XDyKYrqMBmaX@fHucC/HnU7Cc5D9gHHmscislVlrFnoBRWZroMeEWdLu6FEIsAS2YWE4GEMX5vqcbnOqBhdODGgAq4YarDEEAVEFTMifZknMKwdeZlu7iZVqxveJeKkybOYYV4xL5aupvU7r5gzhrVqFzROGxkgw0spNW1akG6AcsJ/mEnz1tf6dP2fTVtuED0pBXb89oHwC "Perl 6 – Try It Online")
## Explanation
Basic approach is to work out every possible combination of our collectors badges against the other collectors badges and see if any combination is possible.
`@^a.permutations` computes all permutations of the list of your badges `[abcd] -> [[abcd],[abdc]...]`
`.map(*Z∈@^b)` For each of these permutations, zip each element of the resulting list (`*Z`) with whether each item is present in the corresponding other badge collector's badges (`@^b`). `[abcd],[[abc][def][bcd][cg]] -> ((True False True False) (True False True True) ...)`
`.max` Return the highest element in the list, i.e. the one with the most Trues.
`.min` Return the lowest element in this list, i.e. true if all the elements are true, else false.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
.»â€˜JIå
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79Duw4seNa05PcfL8/DS//@jlSoqlXQUoGRVOZQdy1VRWVUOAA "05AB1E – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda a,b:any(all(map(str.count,b,c))for c in permutations(a))
from itertools import*
```
[Try it online!](https://tio.run/##ddDNasQgEAfw@z7FQA/RIr30ttBrn6C3XQ8To1TwK2ropi@fOjZtdwsb8M8wmZ@Kaa3vMTxv5uW8OfTjhIBiPGJYGTrHPCZWan5ScQlVjEJxbmIGBTZA0tkvFauNoTDk/GBy9GCrzjVGV8D6FHN93Ai0PYmcDqcBRzUNAqBXgxgmbVpSU8L1JwU8wFteNBlEIr8GJ005NirvG/NjlOmmH/PvlN28oiuELuvnx/flLmsb70EdquQ9lOZcalO9arN5TpRtUXv/LW9vd2OuxsS@R5opBvln5BFStqEyw9prcr59AQ "Python 3 – Try It Online")
*-7 bytes thanks to xnor*
] |
[Question]
[
# Quine Relay!
A quine relay of order \$n\$ is a series of programs \$P\_1\dots P\_n\$ in **distinct** languages such that each program \$P\_i\$ outputs \$P\_{i+1}\$ and \$P\_n\$ outputs \$P\_1\$.
For example, a 2-quine relay can be seen here:
### Ruby → Perl 6:
[This Ruby program](https://tio.run/##KypNqvz/X8XOxkapoCgzr0RBQ4mrQEHDxTHEUa8oNTFFy0hTLzkjsahYLzexQEPNKr8oRZMLrBwkYKWglpxRpKmXlZ@Zp8TFFR/v6ucSH89FZeP@/wcA):
```
$><<"print ("
p (DATA.read*2).chars.map(&:ord)
$><<".map: &chr).join"
__END__
$><<"print ("
p (DATA.read*2).chars.map(&:ord)
$><<".map: &chr).join"
__END__
```
outputs [this Perl 6 program](https://tio.run/##7VDLDgIhDLz7FZyMJmRDF@iCv2I8GGPiGl03xP/HdqFc1JNXD1OaYTp9zOd0w5znNE5Ptdlb1Ap7gimwTiuAngNnxnNmOJDQEu9EZKpQSAwEkgdXXofNBLSKAyckcyT3/EKRxMgfrioWPUi1iUJLY@rhAxPQzKsXz/NpmXcjNuCh2ax1X8xkJjAoPdoB2s6E6AuQqodQVhfu2xz/o/501MOqux/nnVqfLmnbXR/jlPML):
```
print ([36, 62, 60, 60, 34, 112, 114, 105, 110, 116, 32, 40, 34, 10, 112, 32, 40, 68, 65, 84, 65, 46, 114, 101, 97, 100, 42, 50, 41, 46, 99, 104, 97, 114, 115, 46, 109, 97, 112, 40, 38, 58, 111, 114, 100, 41, 10, 36, 62, 60, 60, 34, 46, 109, 97, 112, 58, 32, 38, 99, 104, 114, 41, 46, 106, 111, 105, 110, 34, 10, 10, 95, 95, 69, 78, 68, 95, 95, 10, 36, 62, 60, 60, 34, 112, 114, 105, 110, 116, 32, 40, 34, 10, 112, 32, 40, 68, 65, 84, 65, 46, 114, 101, 97, 100, 42, 50, 41, 46, 99, 104, 97, 114, 115, 46, 109, 97, 112, 40, 38, 58, 111, 114, 100, 41, 10, 36, 62, 60, 60, 34, 46, 109, 97, 112, 58, 32, 38, 99, 104, 114, 41, 46, 106, 111, 105, 110, 34, 10, 10, 95, 95, 69, 78, 68, 95, 95, 10]
.map: &chr).join
```
which in turn outputs the original Ruby program.
# The challenge
The first answer will be an order \$1\$ quine relay: a normal quine. It can be in any language.
The next answer will choose a different language and create an order \$2\$ quine relay using those two languages.
And so on. The \$k\$-th answer will create an order \$k\$ quine relay using the previous \$k - 1\$ languages and a new, different language.
## Winning
If, after 2 weeks, no more answers have been added, the winner is the person who answered with the highest-order quine relay.
## More rules
* No person may answer twice in a row.
* No person may answer within an hour of their most recent post.
* Languages which differ by version are considered distinct. Thus, Python 2 and Python 3 can both be part of the chain.
* Languages which differ by compiler or interpreter are **not** considered distinct. So, [Python 3 (Cython)](https://tio.run/##K6gsycjPM9ZNBtP/gQAA) and [Python 3](https://tio.run/##K6gsycjPM/4PBAA) are considered *interchangeable* but not distinct.
* Each answer may order the languages in any way. If the third answer has an order of Ruby → Perl 6 → JavaScript, you are not restricted to appending a language to the end. If you were adding Java to the mix, then you could write JavaScript → Ruby → Java → Perl 6 if you so desired.
## Format for answers
>
> # n. Language1 → Language2 → … → Languagen
>
>
> ## Language1
>
>
>
> ```
> language 1 code
>
> ```
>
> ## Language2
>
>
>
> ```
> language 2 code
>
> ```
>
> ## Language3
>
>
>
> ```
> language 3 code
>
> ```
>
> …
>
>
> ## Languagen
>
>
>
> ```
> language n code
>
> ```
>
>
Feel free to add explanations anywhere in your answers.
[Answer]
# 10. Javascript → Foo → brainfuck → Wumpus → Gol><> → RAD → ><> → Python 2 → Brain-Flak → 4
Edit: For the next answer, I've golfed how the Python generates the Brain-Flak a bit more [here](https://tio.run/##jVTLbuM2FN3rK1jbGJOhJb/dkRUZk5nCHRQoareLLgKjoWXKUsOQMkXNKDW87Qf0E/sj6dUjlp3ZVIDE@zj33BehLUujlxepdhw5sUwy45hYoQX6iX1haaDjxPySGWuXITt6Y@urxPRDpYr32gXhS6WauFopA7aaxTLMgsdGqv3oFvV3/EtfZkIAw9nd8FyZdLZ9RiXl1@wpydL6cPT2CgdMv5eOhqbRk2cTKTmuaPZKhHEa9VMdvMpO8tyggan1oxKL2wUorZrr0lKyaLbr/3r3AwqzSx/EgrEpoVau8pfJX7NWgCLlm3yvahV61gG5Ki1NjkZvBh8xGPzHQvoMUgNB9h0wlI5QsIuRX5muyp3A3jNd1HqJKVef6cvdVxoPIoVay1gygTRPM2HmLStg5gywBJP7jO156uPmNllwN6zzPq1qGVY92ZYFY7JapdSqekGjllXWYy@hIGtCysTVp6rBhqG1UcsKlUYYx8hHAw/FcPk6x/a5hPsPmxNYKSXE2ikLwROH6Dt0jzoxsvkBDdDGQybiEpVOeM7k6N@//wH@whbG1pWrc2wydOLNCbaqJK8Ks9r/u6I2lNQ@E0M33/KW7hgBfdegR6m@ogheo9CeS66Z4UXxSMTysWCT/OUFh/4f/uJ48HHg/2Z0LPdOqNXTp4jpT/B3IHjsEm/tB3g8Id4WTndGvNwfeIGSqRLcEWqP1/TecZyHznF9cl36zvt@ejO0xWj@3n6nPujkc@d4OMFLDyedJAt1u@Mhkjgn871QW7gZwtN@QhMa0iVd0QPFCV2RGyzsnNA1XRVLyG8F4iLlqMHVqNwWhK484eee5ibTEmmv22XdbuIHkcaTAfFWlTQk3qGU3GHZUyGNiReW0nAE4rIWpwT4Jl4C8zCwHNIjN9NRLzUaE@dPFUv8xBIse8VXsKftjqF8rvQOWrIn79/iakQw7xy3p9lgUBwUF6DAdl3i/BXGQuARoYXDdacVojYPB6RoP1i4btV/GfcmqA4hvfuHahOw1c4xPBFMHjZOUUPgLwInqJd6ZzAh9GFDyP18bg83dWLXnZUshPSqliezWpgOiw3WVClQ4cmYOJonnBn8MzMROHJs5zS9ytEbQBrATr/F5jbO/Wv0GT4j9fACMALaBBHuO8dhbzQdn/r7sxNGQ9eEFF3@Bw "Bash – Try It Online"), but I can't be bothered to update the links.
Added Gol><>. It's just a short `rpH` after the Wumpus code. I've also optimised the brainfuck and Brain-Flak code somewhat.
[Verification!](https://tio.run/##jVTdkps2FL7nKVTsiaXI4P9tMIsnm3ScTGc6xe1FLzyeGmMwdLUIC5Gw9fg2D9BH7ItsD4IF27kpHsT5@fSdT@dovPOy6OUl4fsAmXGS5tKUMUcL9LP3xct8Eafy11xq@xwZ0U1swFM5CDkv3@sUbF9y3u6rHbVhJ7w4CXP/sbXqPLpHg33wZZDkjAFDk255rkIi3z0jRfk1f0rzrP6YYneFA6Y/VKKlaf30WUY8mVQ0B87COIsGmfBfbTN9btHApH/ibHG/AEevuS4jikV4@8FvDz@hML/MwV4IthJq56q@Kv5atQKUJW/qvbrV1sYHpKsibY3WbxsfedD4D6X1GawWgowHYFCJkHkXLb8KXcmdwtxzUWq9xKjR5@Jy9pUX@BFH@jJOPIZEkOVMznXN92QD0JiXHHLvEGQObm@TBndDa@apVcPQ6s7qGrRJ05WlV2dBY11TeowlCNKmRBWulkqDAU3rIF0LuUAYx8hBQxvFcPm6p04jYf1@c4YopYRoe64heOIQ/YDWqBsjIziiIdrYSEZBglQSnoYc/fvtH@AvY2GsXaW6p7ZCN96cYao8CTSto/R1/rekDmjqNMxwnO@JVTpGwN@T6DHhX1EEr@ToECSB8GRQqkcsTh5LNhDx8oJD509ncTo62Hd@lyJODmYo@NPHyBMf4f@B4IlF7JXj48mU2Dv4WnfELpyh7fMk4ywwGT/gFV2bprntnlZny6Jv7B9nb0cGG8/fGW/4e5F@7p6OZ3jp8SzSdMHv90GIElyQ@YHxHdwNZgsnpSkN6ZK69EhxSl3yFjOjIHRF3XIMxT1DAcsC1OJqVGEwQl2bOYUtApmLBAm71/N6vdTxI4GnQ2K7lTUi9lFZ1kidqbQmxA6VNRqDuazNGQG@qZ1CP6Sq@Ppzm9etVZTrre/2MykwMf/icYKfvBQn/XJl3tNu76FizsUeTm9M393iaoQ/755257vhsPxQXIJ8w7KI@XcYM4bHhJYJy5pViDo8GpKyU/7CsqpWqX03m@otpL/eVkODC9A9hWeCyXZjlhp8Z@Gbfj3/B4kJodsNIev53Bht6sKWdadYCOl3TyVNL60eN3XdcHmzuBfx3kaddku35Y041zUzqImnE2KKIA08iX/xZASJAhsFza7E9IegB7Cz77GFgQvnGt3A70jdZR@CgJZ@hAfmadQfzybnwaFJQg/pipCyHf8B "Bash – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org)
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);b=c(96);x=0;console.log(Q+[...`${Q}99+&;75*1-l2:8-&o@rpH${q}${q+q}rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:${b}600${b}+(str(c-99).zfill(2)+${b}99500${b}.zfill(10) if c>99 else str(c).zfill(2)+${b}500${b}),[`+[...`(f=${f})()`].map(c=>c.charCodeAt())+`]))[::-1]+${b}99996${b}))),${[...'pppppppPpPPfFpPPfFpPPfFpPPfFPppPpPPfFpPP'].join`+`}${q}`].map(s=>c(43).repeat(Math.max(-x+s.charCodeAt(),0))+c(45).repeat(Math.max(x-(x=s.charCodeAt()),0))+c(46)).join(c()).match(/.{1,253}/g).join(c(10)+Q))})()
```
[Try it online!](https://tio.run/##ZVLbjpswEP0VHqLFswYv5NY1XketVor2pZKjPkZRIQ4kWTngGFqhIr49NYSm3RTL42HmzO3Y78nPpJTmqCs/L3bp5YIy/p0vmjNHkn@rzDHfk8wUp9dDYl4tANCEAltxiSZTYFt70jmwmgdMFnlZqJSoYo9WeE0IiUfNqqUUP7BPs8fQV@Po2X8oPhv9NmrOrd343BqtF8XLLs2cHNUQ7VWxTZSjmOEaa5zhJRb4jJHGAh6R8mvAKyycY@bUL8pJVZk6f3EDqvYVYMEUr5lJqx8mdwxz3cR1NZcHg6YBMHHVQmDnXqNhP1OnTYBlvRaOrboc1BnYfFOmLR9VX/HPErcthi46ef8vvLIyCMh7cczRKdEo9zqpktN2lzh1VJidnd6fPt/jBoSMRs22nQdBd2DUgaRPKZBf2VEpNAbcOSidXRGDOQygY0ouKL1S1cfdBQ0h4K3j66XZBzBqshYQxBvS9SD5QhI53P@XCgHgeAOwjiI/3AyFKZ33WQC8UdOlcfX1E1qIbHknxD92d9NPG@O4exHtULO0NdF0AsSkOk0q9DWpDtZRI7/G5YdmvMD2Y7Gz/7G1j2r@EX2Dz2FgWVqjRVfygJ5IE3rj2aR92t@clkO8AujouFx@Aw "JavaScript (Node.js) – Try It Online")
# [Foo](https://esolangs.org/wiki/Foo)
[Try it online!](https://tio.run/##5V1HcuM4FN37GN6y@I41277/ymNlhPcTAgnJ7Kp2WaaInzOB//79@/n53swL0ufYs@v2K78b9xvSryD729Z3FbA4r6/vHOYSwgLS/isKJpqWgB99@1ZgHPo36Bp4hRmUvnO/aR1c/u1DrpHkjYgYQX8mXNsoeikARkD@@n7cjwo2ZM/GXKAPpShS9A/gHk6TE5jcXweaeRBARR/dEONIoR9lcK@mD2uZNQxd6@qc0C/8I/DDai4kc3xwew2cwcgJVPz6xu6PEfeDg4QhnEbc8i/o5FH@ZPlWl/CvHOdhCixW0Psm/rvVe1fC7/Tf@2f4S4X7usdcIeXpL5G0Cv/e4i9xXCLvXMET9uAUFkF9yq3SgL3Ta1PuYx3PDV59GgVIUPiBUwmCSIgAx1otug9WwpXAgxv34bi1CH@FG/YobnM0YQp1otyHjEsDnbCfLAUi@iKeUAHFFCGYRpEI9yGVuA0y4FT1VpG4VnoNQh8Ql9SNr9assHwUVIh6o743zw@tqG/lbHUALOE6/2dRphR@vJ0Ed1XYD@ryrNo7SNF/V8w6nuXm/kIVqoGU9KK/LvZdkAf8/ltJdajN8XlS7ZSMrqhvAew7FSTRfURGony91Z6iQJb9ZFH8wNynI@qjXMKsuvacyYA24cen0MzHfaiVvqTcP6RbfGCjOFrpbVbgIQ3ZCf39GS3tB4hZ8QIzMOi013Sqc32LPUoPHuivbbGn2R5B9zHF0PQWcsPFQ7MpRSx/49zmYJM9Pgg7IePLJRX8z/MHfPFwP4OGWyBU8TFVTZA0FOPNVrQkvCeypreN8eq8itj0xPyLTQQiYBSB6eMNUwbx5iW8x9vd6XU207S2CP@hGjzXtDLhH2lavbhilrN4/fewh2ks/uI@UtQ3cX6FcAb04zzeTzri90@Sbqz1xBIHIZCwAcv/8Pvz8TZHlZW8gNyKsQ1UKczj3orMNYJgi@QckZYFCBC1JKCwYDuFPrH8Fa/Jlwg88goloAVVCG8d7AbjJ4R0CPzeilS56cvjBI8wiQLox6BUlAD0Bd8QVYVLnT8Cv5R7ggw2hXB4eVrTECilE5tEnPuFvOZaDK7pgioSyJjESzZAfghZEB6eyVJ9GWmGIEnCNzY60xT7mIXM4HVByXEoeKF4hia8r1qfaERAp45axA8UJjIUCmIONCOPWjhVSXp@/HiBHXJZFtzMK2srJMpFuHI1mt/bULM/c@NBAQLSFqcuOYFHwhKg@ia@qocKlCok7AJ3Zle/73XSdXyS4MasJjFGxMRLLkIwohXtAhaz5Mgz5vfEPoY@lZSw1U90g2KUVRu6mv1E2qRbXlEfYy0xfJW9Ne4tfEhAI/gjK2mCE2gKyNXy87AT1sIWd4k9dkm@AT72dqqXAnqx/DyBcei5HKlFyER0JhBRQQIeuolKTF@D0iyiMr3a8GxyOZIwUxuIaMfjEXTKt2ZRq7VJjw8sjAysIZQIUImsUF6gPT0eA@iKLbgPEPTLQXoeXcKoL0gus/2xcljjT7/zCkdGnWSwzUzVaRjulmAzG5VkeSC2Fa6/ji@E7aZUBxCJarx1vjFoStWLfKxxAqqD60gjcEZW6NaLUTG2Mjd4OIoq71JgUBa60c1nHK/AHSTIK71C6SHIfn1yj9OBGRvVeMDjbM16/MX0CU5YjBQ748SFbnkKvz8v68ivjnhg7O6L5T830R29/JCYfymM5i3/Cnp7AIArCw30EQVz7iu8P@0vzF5BtWGdt2TnaTEqHUMze4RF4iEApGFPuJzjKgvG@3J5vdXKpewSDOQi6E34Ve85onKLTehwMGdPmwlz9OuK/mwNW1S/0qD3bcTbHO0Q21SkVXPbqFZoIAqwyy1E1ubWKsEBQMeBmXq1nPuY77z0mQhnYzY@2wFOz2e@L47ZaIVwtaNvFjTp8EdLG6BdWDLLH2iM2@MeO95AD4qtS563LyMTRl8/UG1kLchnkyvY4XGO1qFXjia3gF4JL46I2s1hMJ/FGiabeZvjXSyWzws7rE8W85/lh2tSYQ8NXGmzUlL2er3/cTbHwfNbmzFqrBUGvXM2tU7UDEiLXfZkKYKEr1regdG@KXF@KV5suMU9p20HcYpY@MvbE6eN71GfOH2ZK7LuAPwlGncPu1GufB2LpMe3@6er9D/RsB0eaRYwmeoviPA3RLgNMTFO9y63keYGLxSGdN58cGA0gP1ehD2Ob9iTprQgHLhVewr3j6xg7lrw1/QdveRKCz7QDywZYPHy0lHqfsOS3pGfeOwzqogqu9B7whtwusNnvuWsZX5Aybjf0ZrZJETGRZLOSSTfuMb9SDL3C3zaMDUNGtVg1R06lvToWCALrG9tjnlZCO8B2bOf7HtwlHKCmcazxXlwrnFGpgFe6gxN1/qTlQHK60pmelQ3M31vqLydqpvu19eovK5Bbt/3hLdV@nVcolv2Du@H6LhP7fPhlsXUHq0gxaLI5yvMnc34BswH4NNYESz8fl8dTuhMwVv9o4UCvbcFY1RXcx5ZOPjw@2KZhL9bIb8/vcJciF8Uk3x/XDMx/Cqa@VG0isX0bCOXvHFN2@kxbSeGm0@teYIhS2h7ds3efwzBTe6aN8aBuDVOfNuijzquglr@06A5HBZ7v76Ppsy0LcrXpIx3t8Y/ckSJaPoO2Bx/EkUiW@O37tb4IceYBE5key@@@q6a@3/qeJqg8H/aAS1xx/dRB7QM2aD@fQ9oOVf3T/cvZanzT8R6ku4vc1zQUZqYof/HDuOrdD9wosDXz8// "Foo – Try It Online")
# [brainfuck](https://github.com/TryItOnline/brainfuck)
[Try it online!](https://tio.run/##7V3bjhMxDH3nV6qefwIkJITEAxLfvwiWbifJsWMnTpNpM0iLtjuT2I6vx2775dfn7z@//f764@3tUr0gvY5rcr3/yu/G/xuOjyD526XvymjxXDisgYKfftLaiUTTFuZd6jcCccy/04aO8xmqDOZd8PffNeSKFG6fDQykKowuhUAfyfj4icweMIpqzJUnHnpymKYjWEhfMYkCNK6LQMqwlkOLNMBHKgfMqyGIQyzk5waEDYTujDFsxOabqyYFIaeMqToVFG3y/71J@olzuh2vF4nXO0LOjlBYgBZzhMSkQh3TBBRTQaHEEm4uPjjbwTqRGhxZmoP1Yao44EkJMMTRgMGyEnEwc74iZ7h6ORujeqvJJl28QUo4G5dQycQQBVhKHhloXREC1mUiWzrEstEc0NDlTVBKGmOgj10Dblo2LWsXqZuvZ@RrvIxeuVe0Lu9bn7c@vxzvURkmXGNMJvS3p@hPapwkW1@qj6QCjYsVEViBkhNJDCqCd4DvQ5DkNZu9rXQhuKl6jvm4BJrA9tLbSz@/z4kHZ92gIB40koJgRxRvzA/3h6mOgv95/CAubiEHwXKEv0/fPC5xaAw@RKPPeyy4908HcLPYBB8crlAR9CsPzj2Hr90O1S8@PDRBuMttSIC4/7h5wSzrPizH3hgI0WMKzxwfQNHT/v/KoaNaWzHnQEgcLMzgWo7RoKg9Dq9nIxcoCpXbvYWIS/bANilOg24LECJKLUDmua6UemGMhL7nk1Ejr5@TmcmEnKvhqMHOEkLRA36vOt2XZgU2mxCWs9Ofm0gj7YekZhD1UnUJMo7k4uAeW6sOQCnH6wKie6eamlovuIULJkjoYrou2b68CNkQlhOTNRrCAGE2YKYS7X6ZJcfgeJ8ULBSu8kEji@KKrgN0VqhF8UApIgOcIG5Ac@woFVPVosymIEOt4K5d2VkRUKq8RXjRIh3JTdKw7VSeMtOQdKZ5QaI81l0tMqAyIUkWhACWpSZKUGa5IfJdMk0q8svSrUthQXCdheQcfrIeFsVMp2JHuRzqZicGPjGnKt1befRE06q3sJSfB4PEx9YCRxo3HLbAlyw0CUaiZUJYgonatrWTJT7YpPMV4tHBqqCcqFYb5aNyVuYREiHIkT9BIh66a3oCY1nIDohS@7MPdGq25kerLph5VKLfLk9dqLIGH9DeHI/5ukELIUNJQqEBBKigB1KQbF9WTmLsJSrHLwTZSKU4TbfNumsGE2yV7QxeL0r1D08OY8XvRjIp1XJhjAZjRMM4pjCT70jdwPAIBtWTE0rZXs61aH4SAaDPmlsiqeRkVKcBS3g1IOxC0B2VEy50i7v2WnxB5/aTS9no7bc4H7k9THWmox8ouHAblP7hdWHB/msuUUcy/Kk@1cy8MK0JeDQB9bhlgPv8/bUURa1VTHWABaYWEI@WEWgsLkK/ggV32hzYlvXyil0dyxBbTr42oEC53AhkjWoN3Z1Cpg0HHGJU@kxAVHPVZrgfdIjjMRq0rXbkqzAlrStbYP3B@uyVPa8P17OAxfWh0pd3oIhx3RrjKBx6dWhSO2eCu9t@Ki7unsLrEEHJA5JXdUoWpqmiyTNXl46BYOuETGkNHvGbtFllsWhaO0bxhuTzzSPL3H3rCZuiEnbAetpUcGrANbjXWiT6hiH9OmXrQKheBPooEezpOSx6LPCxfC7bkP1iekSxvdRP57iY4mjtj/5dAXkdt2qr8IjIMOi9YfiGjuN9fs2wjur4M50oaLQ5@4XVo4YPep8seeSFcHDWaJwgsg5bwPGGOm3gmSaIalpqThNzaXRsIKbQ8erC@zn1OU32HAwwza4ozCCBb5LQU5IEGK2pZNlGO8toTcPWtueE95Fs2@5CC85l7mglaUYzvYHvAG4akzVJsxosRugxwYrqUSBA71KhY6K0TP20Vp748QPNgWhFNQxrCbrfHFZ9KQJyvziutu9bafve7Oqq5YmM5mX0p3zBeSDNH0WDlg@jCSUhQrCblk3LpsVPy/6iiBVktL8sYZ/pPtN9pvtM95k@f2ze@c@2we1Xz3Cm/9b79Pb2Bw "brainfuck – Try It Online")
# [Wumpus](https://github.com/m-ender/wumpus)
```
"99+&;75*1-l2:8-&o@rpH'''rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,120,61,48,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,57,57,43,38,59,55,53,42,49,45,108,50,58,56,45,38,111,64,114,112,72,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,45,120,43,115,46,99,104,97,114,67,111,100,101,65,116,40,41,44,48,41,41,43,99,40,52,53,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,120,45,40,120,61,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,44,48,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,99,40,41,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`))),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P'
```
[Try it online!](https://tio.run/##pRZdb9Mw8K9UPNCYuMiOPxI3DPGEeAzPCGllW2Eoa0O2iYo/P@7O5zTtmk0MtUnO5/N9f/j3/U13f/vw8CqE/HVdujd60RbLavF6@6HvPs3n877r3m/fXV6tZ5tsJ5bf2@23VTtr6/6sy7t8nX/Mm/xXnnV5I95k7WIn8s95M7tez3bv2tlVe3s129Mx1W7Riryp27Nd3V/d3febWV/P56v5vDu7@NFnVom6iZAW9S@CAkCfI2REvSZIFwB@ZNAJ4Gfrrr/e3JHE9GuGp2Et8H28buTtXZ@Jtz@315vsZtVlG4nvdnXz7XI12y23/SVYv7DVMR1TXCzPvVLneYbbF4sQxNs/6@u2zQqRn4fgYI8RWgn0zsX7EKJ76MSYHImF/GKV1KqQXsvg8O0LCRZLrQ2uYDcEBCpEeXgskDv44jEjrafThNYaYCAu4WNlKAmLK9pAeuBHLJ2WrkTYBVlpkh0SvmB8qEb4UjrLeF0oUqwiohC5ozbasaQqSvIRJJRBLiDJGhloK/6Dl8aTubAHwSVBJVIZYu8AA0dBJVDDET8H2sDb49pE9t6y/YUsi8QQ/YccR0u7xyZ6fNDhyEUNTkKPmoKswuiAwWh6RXYkm8A96GFYIaUidcnfmpiSrPhR9CkVviuVtLDkEqapSALaqYgX2hqlWsNuAxIS5AbtMA5qrwF7HqMAsCmeV2NCPgqOvrZJMtqmKB9wly0lkZSSJfszqgggUBj6g4siQI6mdMLcRBpMqwLTiNNQnd4PKe1iPRwRlHuCIY8P951ODNQJDeC0U3uaUk2SmIEN@QFUc4FTaFSR4I7Hnn/ik/JhasGoEyk0Rr3gCKIs16wfTOWq9Vy1bigBFWI/iRmi4@FDpOKCoM6BlYSxj2nquA2Qp8Y1BXmGjvT/ocuEWIghSOXixx1sLpbS7RidKuFAfKCGw@0oqlIUsdUqxz2uohRLZXoki05i1pySOMkNs5kq4rDWcQQUzHOq2B@p/xKtJ/TVGCBo3NCvH3fw/QBLvRbl8TGSA0SBR9U4dnGweTIPWYUn5paP5nFixEESudIyUH921DnBh8FMRqTkYfbYQs12pp2RlSYM0@LUU6n0qaIvyhchmM3zHE0Y/HlYHhwffzz5cDkRBEycfRSo58Z2aP2oy8eco1MUhLJMCwzZiGlBNZrmlyH2/xZbyxXAQR6UMv@rFA82hmhOu3/Puyn1bEKebFqRbkQRkqosHXfLWLCGuoDlqePixciW8Rb1jIDUPvjaQP9xKX4V4styudBf8bYagj8XQsjxNfrwEv001Jymnz88/AU "Wumpus – Try It Online")
# [Gol><>](https://github.com/Sp3000/Golfish)
```
"rpH'''rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,120,61,48,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,57,57,43,38,59,55,53,42,49,45,108,50,58,56,45,38,111,64,114,112,72,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,45,120,43,115,46,99,104,97,114,67,111,100,101,65,116,40,41,44,48,41,41,43,99,40,52,53,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,120,45,40,120,61,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,44,48,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,99,40,41,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`))),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P'
```
[Try it online!](https://tio.run/##pRbZbtsw7FeCvcSalUGyDlvJusdhj@5zMaDpkTaDl3huBwT7@Y6kKMdJ4xZtkdimKIr3obtts1o/3D89feraH9PptGvbb9uvN7erySbbiflds71aNpNm0Z21eZuv8u95nf/Jszavxeesme1Efp7Xk/VqsvvaTG6bh9vJno6pdrNG5PWiOdstutvHv91m0i2m0@V02p5d33eZVWJRR0iLxR@CAkDnETJisSJIFwB@Z9AJ4GcXbbfePJLE9Kv7p2Yt8H28ruXDY5eJL7@26032e9lmG4nvZvn76mY52c233Q1YP7PVMR1TXM8vvVKXeYbb17MQxJd/q3XTZIXIL0NwsMcIrQR65/pbCNE9dGJIjsRCXlgltSqk1zI4fPtCgsVSa4Mr2A0BgQpRHh4L5A6@eMxI6@k0obUGGIhL@FgZSsLiijaQHvgRS6elKxF2QVaaZIeELxgfqgG@lM4yXheKFKuIKETuqI12LKmKknwECWWQC0iyRgbaiv/gpfFkLuxBcElQiVSG2DvAwFFQCdRwxM@BNvD2uDaRvbdsfyHLIjFE/yHHwdLusYkeH3Q4clG9k9CjpiCrMDpgMJpekR3JJnAPehhWSKlIXfK3JqYkK34UfUqF70olLSy5hGkqkoB2KuKFtkap1rDbgIQEuV47jIPaa8CexygAbIrX1RiRj4Kjr22SjLYpygfcZUtJJKVkyf6MKgIIFIb@4KIIkKMpnTA3kQbTqsA04jRUp/dDSrtYD0cE5Z6gz@PDfacTA3VCAzjt1J6mVKMkpmdDfgDVXOAUGlQkuOO551/4pHwYWzDqRAoNUe84gijLNet7U7lqPVet60tAhdhPYoboePgQqbggqHNgJWHsY5o6bgPkqWFNQZ6hI/0HdBkRCzEEqVz8uIPNxVK6HaNTJRyID9RwuB1FVYoitlrluMdVlGKpTI9k0UnMmlMSR7lhNlNFHNY6joCCeY4V@zP136P1iL4aAwSNG/r18w6@H2Cp16I8PkZygCjwqBrGLg42T@Yhq/DC3PLRPE6MOEgiV1oG6s@OOif4MJjRiJQ8zJ5bqNnOtDOw0oR@Wpx6KpU@VfRF@S4Es3mdowm9Pw/Lg@PjjycfLkeCgImzjwL13NgOrR90@ZhzdIqCUJZpgSEbMC2oRtP8MsT@bbG1XAEc5F4p81GleLAxRHPavT3vxtSzCXmyaUW6AUVIqrJ03C1jwRrqApanjosXI1vGW9QrAlL74GsD/Yel@FOIi/l8pn/ibTUEfymEkMNr9OEl@mWoPk0/fXr6Dw "Gol><> – Try It Online")
# [RAD](https://bitbucket.org/zacharyjtaylor/rad)
```
'''rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,120,61,48,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,57,57,43,38,59,55,53,42,49,45,108,50,58,56,45,38,111,64,114,112,72,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,45,120,43,115,46,99,104,97,114,67,111,100,101,65,116,40,41,44,48,41,41,43,99,40,52,53,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,120,45,40,120,61,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,44,48,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,99,40,41,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`))),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P'
```
[Try it online!](https://tio.run/##pRbZTuMw8Ff61njjIjs@ErfAI8/hGa1EKXSXVWhLYKVqf56dGY/T9AgIUJtkPB7Pfbid37@9jcfjdrO5XJ/fPyxHq2wrpr@a9d28GTWz9mKTb/JlfpXX@XOebfJa/MiayVbk13k9elyOtufN6KF5eRjt6JhqO2lEXs@ai@2sfXj9265G7Ww8no/Hm4vF7zazSszqCGkxeyYoAHQdISNmS4J0AeAVg04APzvbtI@rV5KYfnX31KwFvg/XtXx5bTNx9mf9uMqe5ptsJfHdzJ/u7uej7XTd3oP1E1sd0jHFYnrrlbrNM9xeTEIQZ/@Wj02TFSK/DcHBHiO0EuidxWUI0T10ok@OxELeWCW1KqTXMjh8@0KCxVJrgyvYDQGBClEeHgvkDr54zEjr6TShtQYYiEv4WBlKwuKKNpAe@BFLp6UrEXZBVppkh4QvGB@qHr6UzjJeF4oUq4goRO6ojXYsqYqSfAQJZZALSLJGBtqK/@Cl8WQu7EFwSVCJVIbYO8DAUVAJ1HDEz4E28Pa4NpG9t2x/IcsiMUT/Icfe0u6wiR4fdDhyUZ2T0KOmIKswOmAwml6RHckmcA96GFZIqUhd8rcmpiQrfhR9SoXvSiUtLLmEaSqSgHYq4oW2RqnWsNuAhAS5TjuMg9ppwJ7HKABsio/VGJCPgqOvbZKMtinKB9xlS0kkpWTJ/owqAggUhv7gogiQoymdMDeRBtOqwDTiNFSn90NKu1gPBwTljqDL4/19pxMDdUIDOO3UjqZUgySmY0N@ANVc4BTqVSS449jz73xSPgwtGHUihfqoLxxBlOWa9Z2pXLWeq9Z1JaBC7CcxQ3Q8vI9UXBDUObCSMPYxTR23AfJUv6Ygz9CR/hu6DIiFGIJULn7cweZiKd0O0akS9sQHajjcjqIqRRFbrXLc4ypKsVSmB7LoJGbNKYmD3DCbqSL2ax1HQME8h4r9SP2vaD2gr8YAQeOGfn3cwXcDLPValMfHSA4QBR5V/djFwebJPGQV3plbPprHiREHSeRKy0D92VHnBB8GMxiRkofZsYWa7Uw7PStN6KbFqadS6VNFX5RfQjCbjzma0Plzvzw4Pv5w8uFyIAiYOLsoUM@N7dD6XpePOUenKAhlmRYYsh7Tgmo0zS9D7D8XW8sVwEHulDLfVYoHG0M0p93n825IPZuQJ5tWpOtRhKQqS8fdMhasoS5geeq4eDGyZbxFfSAgtQ@@NtC/X4o/hbiZTif6J95WQ/C3QgjZv0bvX6Lfh@rT9OO3t/8 "RAD – Try It Online")
# [><>](https://esolangs.org/wiki/Fish)
```
'rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;'a'p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,120,61,48,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,57,57,43,38,59,55,53,42,49,45,108,50,58,56,45,38,111,64,114,112,72,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,45,120,43,115,46,99,104,97,114,67,111,100,101,65,116,40,41,44,48,41,41,43,99,40,52,53,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,120,45,40,120,61,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,44,48,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,99,40,41,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`))),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P
```
[Try it online!](https://tio.run/##pRbLTuMw8L5f0RvxxkV2/EjcAkfO4YxWanl06SqUElip2p/vzozHaVoaEKA2yXg8nvfDi@XLw3Z70q7XF09nd/eL0SrbiMnv5ulm3oyaaXu@ztf5Ir/M6/w5z9Z5LX5mzXgj8qu8Hi0Xo81ZM7pvXu5HOzqm2owbkdfT5nwzbe9f/7arUTs9mZ@sz28f2swqMa0jpMX0maAA0FWEjJguCNIFgJcMOgHc7HTdLlevJC/96u6pWQd8H65r@fLaZuL0z9NylT3O19lK4ruZP97czUebyVN7B7aPbXVIxxS3k5lXapZnuH07DkGc/lssmyYrRD4LwcEeI7QS6JvbixCic@hEnxyJhby2SmpVSK9lcPj2hQSLpdYGV7AbAgIVojw8FsgdfPGYkdbTaUJrDTAQl/CxMpSExRVtID3wI5ZOS1ci7IKsNMkOCV8wPlQ9fCmdZbwuFClWEVGI3FEb7VhSFSX5CBLKIBeQZI0MtBX/wUvjyVzYg@CSoBKpDLF3gIGjoBKo4YifA23g7XFtIntv2f5ClkViiP5Djr2l3WETPT7ocOSiOiehR01BVmF0wGA0vSI7kk3gHvQwrJBSkbrkb01MSVb8KPqUCt@VSlpYcgnTVCQB7VTEC22NUq1htwEJCXKddhgHtdOAPY9RANgUH6sxIB8FR1/bJBltU5QPuMuWkkhKyZL9GVUEECgM/cFFESBHUzphbiINplWBacRpqI7vh5R2sR4OCModQZfH@/tOJwbqiAZw2qkdTakGSUzHhvwAqrnAKdSrSHDHW8@/80n5MLRg1JEU6qO@cARRlmvWd6Zy1XquWteVgAqxn8QM0fHwPlJxQVDnwErC2Mc0ddwGyFP9moI8Q0f6b@gyIBZiCFK5@HEHm4uldDtEp0rYEx@o4XA7iqoURWy1ynGPqyjFUpkeyKKTmDXHJA5yw2ymitivdRwBBfMcKvY36n9F6wF9NQYIGjf067cdfDfAUq9FeXyM5ABR4FHVj10cbJ7MQ1bhnbnlo3mcGHGQRK60DNSfHXVO8GEwgxEpeZi9tVCznWmnZ6UJ3bQ49lQqfaroi/JLCGbzMUcTOn/ulwfHxx9OPlwOBAETZxcF6rmxHVrf6/Ix5@gUBaEs0wJD1mNaUI2m@WWI/edia7kCOMidUua7SvFgY4jmtPt83g2pZxPyaNOKdD2KkFRl6bhbxoI11AUsTx0XL0a2jLeoDwSk9sHXBvr3S/GXENeTyVj/wttqCH4mhJD9a/T@Jfp9qD5O/2O7/Q8 "><> – Try It Online")
# [Python 2](https://docs.python.org/2/)
```
def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;
p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,str().join(map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,120,61,48,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,57,57,43,38,59,55,53,42,49,45,108,50,58,56,45,38,111,64,114,112,72,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,45,120,43,115,46,99,104,97,114,67,111,100,101,65,116,40,41,44,48,41,41,43,99,40,52,53,41,46,114,101,112,101,97,116,40,77,97,116,104,46,109,97,120,40,120,45,40,120,61,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,44,48,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,99,40,41,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`))),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P
```
[Try it online!](https://tio.run/##pRbLUtsw8N6vyNGqFUayHrbi0iNnc2aYSYCk0DFJCHQm7c/T3dXKcR6GASaxvVqt9v3Q@u/L/WpZvL7ezRejZbYVk1/t6mbWjtp6c77O1/kiv8ib/CnP1nkjvmfteCvyy7wZPSxG2x/taN4@z0c7OqbajluRN3V7vq0385c/m@VoU39bn9/ebzKrRN1ESIv6iaAA0GWEjKgXBOkCwAsGnQBetl5vHpYvJC39mu5pWAN8H64b@fyyycTZ79XDMnucrbOlxHc7e7y5m422k9XmDiwf2@qQjiluJ1Ov1DTPcPt2HII4@7d4aNusEPk0BAd7jNBKoGduf4YQXUMn@uRILOSVVVKrQnotg8O3LyRYLLU2uILdEBCoEOXhsUDu4IvHjLSeThNaa4CBuISPlaEkLK5oA@mBH7F0WroSYRdkpUl2SPiC8aHq4UvpLON1oUixiohC5I7aaMeSqijJR5BQBrmAJGtkoK34D14aT@bCHgSXBJVIZYi9AwwcBZVADUf8HGgDb49rE9l7y/YXsiwSQ/Qfcuwt7Q6b6PFBhyMX1TkJPWoKsgqjAwaj6RXZkWwC96CHYYWUitQlf2tiSrLiR9GnVPiuVNLCkkuYpiIJaKciXmhrlGoNuw1ISJDrtMM4qJ0G7HmMAsCmeF@NAfkoOPraJslom6J8wF22lERSSpbsz6gigEBh6A8uigA5mtIJcxNpMK0KTCNOQ3V6P6S0i/VwQFDuCLo83t93OjFQJzSA007taEo1SGI6NuQHUM0FTqFeRYI7jj3/xiflw9CCUSdSqI/6xBFEWa5Z35nKVeu5al1XAirEfhIzRMfD@0jFBUGdAysJYx/T1HEbIE/1awryDB3pv6DLgFiIIUjl4scdbC6W0u0QnSphT3yghsPtKKpSFLHVKsc9rqIUS2V6IItOYtackjjIDbOZKmK/1nEEFMxzqNiP1P@M1gP6agwQNG7o18cdfDfAUq9FeXyM5ABR4FHVj10cbJ7MQ1bhjbnlo3mcGHGQRK60DNSfHXVO8GEwgxEpeZgdW6jZzrTTs9KEblqceiqVPlX0RfkpBLN5n6MJnT/3y4Pj4w8nHy4HgoCJs4sC9dzYDq3vdfmYc3SKglCWaYEh6zEtqEbT/DLE/mOxtVwBHOROKfNVpXiwMURz2n0874bUswl5smlFuh5FSKqydNwtY8Ea6gKWp46LFyNbxlvUOwJS@@BrA/37pXgtxNVkMtbXeFsNwU@FELJ/jd6/RL8NNafpX1//Aw "Python 2 – Try It Online")
# [Brain-Flak](https://github.com/Flakheads/BrainHack)
[Try it online!](https://tio.run/##7Z1BbtwwDEX3PUWW9qKH6DkML9JuWhTootsgZ58mGTToeCxZDUyKn3pNMUWazMiWqS/yk/z6@vvxx6/vj99@Xi7T25/59Wt@en75@/ff@WGaXl6X68@meZ3fvr@@Tu9f8@5v1X62/YS732sfbTOew4gu93f73c67dz7j/nU6vItFeI4ijFb5tPNHfx85k41X7NJwRd3jRwaM@ghq5L/DPVzcvF8HtwvvjnHN2/mMPbMF1D59du8RHO@kFSvOudab96z4bC1@TQnhz/ZlzEcqeG2mo667NiDsy5iteBOb9sFcP2TR9bPaVpue5@vkjRj5URXsDTpTd@t6xT8bl4sjziXOJc4lzk2HoyWG9/x7qt0Re8PgzHzmPIB9dI6vR6S1G7OEjkNLPEw0X3YZ2C/c@XwBbqOI7INzGpnZMS/@1TgGNbDVpT0jEZZPKO8WWr5FEU@ZdyF2y2ZW4MkzYHrEnXXcPFBllkAzcoGpotVinQOzGTyWTJrH8Ky4IrtAdoHsAnw/fD8eFHw/fD9xC3z/yHy/uQenwKjas@0w2TDZMNmwmDDZ2ABMNkw2TPYYFfkw2nK9VEfPj4qrvtVpkj6H/S5FHNVlf1mbPseI1ZpmTZbRRz/EUAsmfHelq47Fdo0Nb3e@q9OLx9XEHPrM6TNP12feyeto4M3cVLKqd53oCnSikKO5suWkjebpdJTApjPZNHPFUwUrwUrWPzaNTWPT2DQ2jU1j09g0cRpxGlfKlXKlca/Ug8P3qmnPM8rysZ2MWgTrXBTqrFKd9Zr1SpVebVa54yq3rKWe6jsJIwUaCRwBR0Kr48SqBTLzir0UUavnpsmO1j@mSO/dDtEJgOoXvdPoVqFbhW4VulVokNjv6/GUYOiwDjuv9EbTG02XUo@IKHH0QOYmT00bTG1GDZY@VZB5@sypT5HkktMpHoSY11Q1LuRv8QpOy875Zh4dYzPqJ1h/A9dPBIjd0e08yje2@z9c/9jKVDoMym4uEo1l8ipymWPN6hIHnLTrdF1r3hhVMXGfH96FvWX4rZFsHQ/@FRq9a1DiKxfrZAR9YgWfJ5j5LGD/7g1YCK4fFgIWgjwfeQbyfBnzfPR@gylgCrlLogaiBqIGogZyl/l9JC9NDjK@ZHw5@da558uhvp4IiwgL1qaXAiFrj7WnoZKWsTpAUW3FVj9IbV1bajRoq/F4s0bon6B/kt9WOMlcUXHOgSlRPskc3U2YvZGZPWO9haripWnVuHLWQVOloozdeE1L@Ey1Errb@0yR@aVOaw9OCk4KTgpOCk4qIydlHgfE5qBYLawWGFwYXBhcGFwYXBhcGNyWzptqRKPaz1S4z2PUHKvi1Vz1vfsTx7KxbCyb@0xr3Va9IiAaiMZKx7KxbCybvZq9mufOc@e5D/LcmQ/mg/lgPgaZDyklb82MGlULZIS96pwalDZk@1b0T5rurwjoaBWeVS0uKr19NDwbqjGoE5KvE6rbj7AOoCtW980@DIG0x6gA4oK4IO4giKuSCwWbLZ6865l6oCPoqOqPtnuj@KOB/TQwD8wD8zpp/ubizNNiZKecADgJTqbiKvEPBU@LBPfAPXAvdz3FPYqIj9hPGyfvnPruq3rYrFV7qFLBp6mPUs/Lo@5ipPZEbacwUrtoVVNnqRFNj9J5K6Um38sOY54pnF9v/57/ya4aSB9s174tb9um4xqNFDRS6JGlRzZwj6xOdO@jL5srqoxpGbp95J5Psr7rKzArOc5o0utW0Ojs93mCY3Ne8Hq5UVCHu4u3i8LrgaTwetmfgH1HAFwnXCdcJ1znwPuPdN0HVUNhvXYYwoC12GondN@MTMbA09s2PSN@Sd15S5WU1Dna5CGGy0vv2xJ5P@v9dmnTraIDcZgrVe1kqsSDcKnwy9ZXa2RvFe@ctYjdSdvd0s53squr9JWvVQ5tSDbrQP1Lqn6lOIbtrHXq4ySnEKVWqo92nv6pKQX7ks/GeWGqXwzlo2zrO5JeVBFJM5oo4TYH45WXrawPRvnvNePxzIbpChDWnPTIZVPdYF3d4INaI/bjyne2KmaJOLk41bNPEMl28NJG737uqB3n1Wu2FutMOZ0nIBb1XKu9KpLTngrY@Xx21qHaOuTcOmsbct6nEq9IVXXYcSuidaK/Sq3B8LWz/U4N0TjJR8l26isepid39bptB5EWX6@TJ1I5k8ZDe47uk/o1LIaVY8655/DccYboSUvzg86Jvv2UfWzo8P5YKd7aUicgV6lyeHPtD9P1z@vvPj1vXuZ//v/T5XL5/OUP "Brain-Flak (BrainHack) – Try It Online")
# [4](https://github.com/urielieli/py-four)
```
3.6999960040500600030000099500600615006009550060061500600625006002400000995006001400000995006006150060040500600995006006150060083500600170000099500600150000099500600060000099500600110000099500600040000099500600465006000300000995006001500000995006001200000995006001000000995006006750060005000009950060097500600150000099500600675006001200000995006000100000995006000200000995006004150060040500600515006005750060041500600595006008150060061500600995006004050060051500600525006004150060059500600985006006150060099500600405006005750060054500600415006005950060021000009950060061500600485006005950060099500600120000099500600110000099500600160000099500600120000099500600090000099500600020000099500600465006000900000995006001200000995006000400000995006004050060081500600435006009150060046500600465006004650060096500600365006002400000995006008150060026000009950060057500600575006004350060038500600595006005550060053500600425006004950060045500600090000099500600505006005850060056500600455006003850060012000009950060064500600150000099500600130000099500600725006003650060024000009950060014000009950060026000009950060036500600240000099500600140000099500600435006001400000995006002600000995006001500000995006001300000995006001300000995006006250060012000009950060060500600010000099500600020000099500600030000099500600325006001100000995006004050060021000009950060041500600585006000400000995006000900000995006001200000995006009850060097500600090000099500600325006000900000995006005950060015000009950060061500600130000099500600435006001300000995006004350060003000009950060043500600705006004350060080500600435006001400000995006004350060040500600130000099500600435006008050060041500600425006004050060009000009950060045500600210000099500600415006004350060081500600435006008050060032500600060000099500600030000099500600325006002100000995006006050060009000009950060032500600020000099500600090000099500600160000099500600020000099500600325006001300000995006004350060013000009950060043500600030000099500600435006007050060043500600805006004350060040500600130000099500600435006008050060041500600425006004050060021000009950060045500600090000099500600415006004350060080500600595006000900000995006006150060021000009950060059500600150000099500600020000099500600170000099500600180000099500600150000099500600110000099500600325006001500000995006005950060039500600395006009750060039500600395006001300000995006006150060099500600050000099500600150000099500600405006005250060048500600415006005950060080500600615006009950060005000009950060015000009950060040500600525006004950060041500600595006001400000995006006150060099500600050000099500600150000099500600405006005750060049500600415006005950060081500600615006009950060005000009950060015000009950060040500600575006005150060041500600595006000300000995006006150060099500600050000099500600150000099500600405006004950060050500600515006004150060059500600705006006150060099500600050000099500600150000099500600405006004950060050500600535006004150060059500600090000099500600615006005250060059500600130000099500600150000099500600060000099500600110000099500600170000099500600325006001300000995006004350060013000009950060043500600130000099500600435006001300000995006004350060013000009950060043500600130000099500600435006008050060043500600130000099500600435006008050060043500600130000099500600435006008050060043500600805006004350060003000009950060043500600705006004350060080500600435006000300000995006004350060070500600435006001300000995006004350060080500600435006008050060043500600030000099500600435006007050060043500600805006004350060003000009950060043500600705006004350060080500600445006001600000995006001700000995006001500000995006004050060041500600465006000700000995006001200000995006000600000995006001100000995006004050060010000009950060097500600130000099500600405006001100000995006004450060010000009950060097500600130000099500600405006000900000995006009750060010000009950060098500600010000099500600975006003250060021000009950060058500600120000099500600150000099500600010000099500600405006002100000995006004150060045500600525006005650060044500600160000099500600170000099500600150000099500600405006004150060046500600070000099500600120000099500600060000099500600110000099500600405006001000000995006009750060013000009950060040500600090000099500600975006001000000995006009850060001000009950060097500600325006009950060058500600365006002400000995006009850060026000009950060054500600485006004850060036500600240000099500600985006002600000995006004350060040500600160000099500600170000099500600150000099500600405006009950060045500600575006005750060041500600465006002300000995006000300000995006000600000995006000900000995006000900000995006004050060050500600415006004350060036500600240000099500600985006002600000995006005750060057500600535006004850060048500600365006002400000995006009850060026000009950060046500600230000099500600030000099500600060000099500600090000099500600090000099500600405006004950060048500600415006003250060006000009950060003000009950060032500600995006006250060057500600575006003250060002000009950060009000009950060016000009950060002000009950060032500600160000099500600170000099500600150000099500600405006009950060041500600465006002300000995006000300000995006000600000995006000900000995006000900000995006004050060050500600415006004350060036500600240000099500600985006002600000995006005350060048500600485006003650060024000009950060098500600260000099500600415006004450060091500600965006004350060091500600465006004650060046500600965006004050060003000009950060061500600365006002400000995006000300000995006002600000995006004150060040500600415006009650060093500600465006001000000995006009750060013000009950060040500600995006006150060062500600995006004650060099500600050000099500600975006001500000995006006750060012000009950060001000009950060002000009950060065500600170000099500600405006004150060041500600435006009650060093500600415006004150060091500600585006005850060045500600495006009350060043500600365006002400000995006009850060026000009950060057500600575006005750060057500600545006003650060024000009950060098500600260000099500600415006004150060041500600445006003650060024000009950060091500600465006004650060046500600395006001300000995006001300000995006001300000995006001300000995006001300000995006001300000995006001300000995006008050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060080500600130000099500600130000099500600805006001300000995006008050060080500600030000099500600705006001300000995006008050060080500600395006009350060046500600070000099500600120000099500600060000099500600110000099500600965006004350060096500600260000099500600365006002400000995006001400000995006002600000995006009650060093500600465006001000000995006009750060013000009950060040500600160000099500600615006006250060099500600405006005250060051500600415006004650060015000009950060002000009950060013000009950060002000009950060097500600170000099500600405006007750060097500600170000099500600050000099500600465006001000000995006009750060021000009950060040500600455006002100000995006004350060016000009950060046500600995006000500000995006009750060015000009950060067500600120000099500600010000099500600020000099500600655006001700000995006004050060041500600445006004850060041500600415006004350060099500600405006005250060053500600415006004650060015000009950060002000009950060013000009950060002000009950060097500600170000099500600405006007750060097500600170000099500600050000099500600465006001000000995006009750060021000009950060040500600210000099500600455006004050060021000009950060061500600160000099500600465006009950060005000009950060097500600150000099500600675006001200000995006000100000995006000200000995006006550060017000009950060040500600415006004150060044500600485006004150060041500600435006009950060040500600525006005450060041500600415006004650060007000009950060012000009950060006000009950060011000009950060040500600995006004050060041500600415006004650060010000009950060097500600170000099500600995006000500000995006004050060047500600465006002400000995006004950060044500600505006005350060051500600260000099500600475006000400000995006004150060046500600070000099500600120000099500600060000099500600110000099500600405006009950060040500600495006004850060041500600435006008150060041500600415006002600000995006004150060040500600415004
```
[Try it online!](https://tio.run/##3VkJjiMxCPzRCt/t/z8sOztp0FIN7suJMhMpsnwAdnEY0/nxSH9q//pVokyF6KulRP9@vT@7NTzbXnS/xmcbs1oesknNzHF8SStZ01yK6n7//5sNelaLzNU8B7AMUXdJb7utPDRRbyYvXg08CbapZzMgU9Z@aXq@rOuXAProDn206fuyQ7/KLdmmj8FW7AJiHHw1dagjZVAfAlfNVcgDjII0inm1ux40U2z72qZqWjuzi/o8gmXT0hKAVVafKut8Zt3xrot51MIqY3ZVL2cxAEnNtidoP2lxeGLwbzj4MSKGY8xrvE3ocjTCI9MRV4RIkaJps2xC4AjiJ4tpeGMrZafkwAKreSeofxshdkmARtC2h8kebqT7Cw11x8MMkiNMuAQweDIPygbtQC5cgy1F4KtH1I0BjsYqGYYsiG@wWAzsHYq6qRGE3o5I2dFAseFhSwXmjl0DepgqLMOoEWzkiyk4QctuiePBSZG6mTWAMLlwo75BNxc@TeHebe5OnnZSSBsL8XKWc9w5s0HuNEMLGe9UR1ijqVKScyTbT1iZxbkLz2TL4D7XYtErhzc3zdRl2L8YVQ@SfeSmhCzbyXg7ZNGQOFMbZuNDk5QriuzXVrJXA5N8hQk4nKwmM02DNFKuBzuDKHYajt56Ksvk@1ciQv0VupyqBsTfeZQwN3y7ZbiWL3HZZF9X9IJJ1@ZZCXqLaZTnYhbcR125g8lO8E5iChuX6@8exq87tiQ0kJude1Hg4xRhmPqWuGVgP8aQ5hhO0EGTi0Bc7DlbHNqpnDqbg9XeHgE3ltmT3su5eItbrGCxcsL@8jpoLabFbu4mLNwhDrCuQ1mGW46l7OFCPyewNbuYetE@g22vHrcdc02HKmkTuwsNhxfbbdqPoXLO904UUrfDwZ0UbhMG641aLxDNCV9w2blRDGoh@LYX4eN6UxrNyk7t8NXacBnE1R00op1qe1XSZIL1gaE928nWJuR7ak2/Uq1O5dWZluL/x2t7ltazQzfxEbt7hp3opbfgWQczb5CEwxcWqHNgKbHYnyKZK34PfQdaziNq89kG2iOZcH48/gI "4 – Try It Online")
[Answer]
# 3. JavaScript → Python 2 → Foo
## JavaScript
Classic JS quine. This is a full program which outputs to console:
```
(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fI8023tYuOT@vOD8nVS8nP10joaAoM69EQ6U6uATISNdLK8rPdc5ILHIGqtcwttSsxSFjolkLNEylOq1WU0MTtxrc5momaAJ1/v8PAA)
## Python 2
Python code basically prints out the JS code with quotes:
```
print('"(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()"')
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQ11JI8023tYuOT@vOD8nVS8nP10jASKlUh1cAmSk66UV5ec6ZyQWOeenpGoYW2rW4pAx0awFGqZSnVarqaGJWw1uczUTNIE6ldQ1//8HAA)
## Foo
Foo code is JS code with quotes:
```
"(f=_=>console.log(`print(${String.fromCharCode(39)}${String.fromCharCode(34)}(f=${f})()${String.fromCharCode(34)}${String.fromCharCode(39)})`))()"
```
[Try it online!](https://tio.run/##S8vP//9fSSPNNt7WLjk/rzg/J1UvJz9dI6GgKDOvREOlOrgEyEjXSyvKz3XOSCxyzk9J1TC21KzFIWOiWQs0TKU6rVZTQxO3GtzmaiZoAnUq/f8PAA)
[Answer]
# 1. Foo
## Foo
A simple [Foo quine:](https://codegolf.stackexchange.com/a/160963/31957)
```
>&41>&60>&99>&36>&40>&60>&41>&62>&105>&36>&34>&38>&62>&34>&40>&62>&41>&60>&40(<)>(">&"$i>)<($c<)
```
[Try it online!](https://tio.run/##S8vP///fTs3E0E7NzMBOzdLSTs3YDMg3gPDB4kZ2aoYGphAJYxMgtoAIgthghUYIA0wMNGw07TSU7NSUVDLtNG00VJJtNP//BwA "Foo – Try It Online")
[Answer]
# 2. Python 2 → Foo
i used the basic python quine, then added the quotes
python:
```
_='_=%r;print chr(34)+_%%_+chr(34)';print chr(34)+_%_+chr(34)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P95WPd5Wtci6oCgzr0QhOaNIw9hEUzteVTVeG8pRx5CDS/3/DwA "Python 2 – Try It Online")
foo:
```
"_='_=%r;print chr(34)+_%%_+chr(34)';print chr(34)+_%_+chr(34)"
```
[Try it online!](https://tio.run/##S8vP//9fKd5WPd5Wtci6oCgzr0QhOaNIw9hEUzteVTVeG8pRx5CDSyn9/w8A "Foo – Try It Online")
[Answer]
# 5. ><> → JavaScript → brainfuck → Python 2 → Foo
Obligatory brainfuck answer.
## ><>
```
'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print(${q+Q+s+q}rpp>o<(f=${f})()${Q+q})`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()
```
[Try it online!](https://tio.run/##PY3NCoMwEIRfRugugT1UKYiNUHwC6bGUKmniD2piklvw2dMUSk/DzPDNqMmNMZ6sMbW@guIvXoedg@B3b6dtIGX12oy9bfRbIuQlVi0XkBdYuaTlGSuhN6cXSYse4EFEnUmghyzsrGWO7cd/OwvqQMAstCnF7klrb8DxWkCRI1lpZO/Bkfjd3TwgslReEGnW05bsl4/xAw "><> – Try It Online")
## JavaScript
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print(${q+Q+s+q}rpp>o<(f=${f})()${Q+q})`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()
```
[Try it online!](https://tio.run/##LU3dCoIwFH4ZL85hdC5SArEJ4RNIlxE51ixFt7mNbobPvhZ09fH9z@IjvHSTDQdtniolGPmDt3HjIPk1uEm/aHRm7d7CdTmAUNbY9FxCWWHjM9ZHbKTR3iyKFvOCGxENNhcDFHFjPfNs2521rTnn7SKOOwIWsc8qDndahQXPWwlVieSUVSKAJ/m/uwRAZNk8IdJsJp3pr5/SFw)
## brainfuck
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.
```
[Try it online!](https://tio.run/##7VtbCsMwDPvfVTJ6p21QGIN9DHb@7AoNnWRZdr8D8kN@xen9c3u@9@/jNecgf9t1DGNMtnoR5lxBPXzyyEGssn8VNb@f8yHSJT4HCAiiWAfAxQyWLybXxoHTzE3RTZHc6tW7WzAlvFWgJGWjQq2PgePJTEBKyzJTqpLUWoABNxwnFIYowfGJ@kwg6/jEPm9WQDWxYoZ7I5YyvtQB9XoHXyNID6pQkdDu16NXhS1B3yXJx2tflAvPaPr9TL5VR2dRT8TeKGe4JyhRbvJkKAgLazKhyyaflKK20L7L8FwA6tVTfnEN1hntAvRCSDxsmZi2A4fp4we7/Ge2D@s3NzaDu19CM0pYqGpft3/SsD@Zpc4rfd01mQbP4swdZinE33TbZc4f "brainfuck – Try It Online")
## Python 2
```
print('"\'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print(${q+Q+s+q}rpp>o<(f=${f})()${Q+q})`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()"')
```
[Try it online!](https://tio.run/##PY3NCoMwEITfRQR3CexBpSA2QvEJpMe2VEn9K5rEJJciPrtNaelpmPmYGf1yg5LxvmszSgdRcI2M1oU6QsfvvFgXDoKfnYc9dUbN5dCYUj1ahCTDvOICkhRz6zWLMRdKWjW1NKkeLkRUf1fDdWEVs2zZ/tvh2m0IGK6VT7G@0dxosLwQkCZIptVt48CS@N2dHCAyDw@I9FSj9PbTDyLc9zc "Python 2 – Try It Online")
## Foo
```
"'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print(${q+Q+s+q}rpp>o<(f=${f})()${Q+q})`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()"
```
[Try it online!](https://tio.run/##PY3BCoMwEETv/QwRuouwhyoFsRGKXyA9ltJKGq1F3ZjkFvz2NIXS0zAzvJmeOYRkb7Su@QS9uIvarwKkuDgzLgP1hufm1ZmGnwohL7FqhYS8wMpGLQ9YSV4sT4omHuBKRA8dQQepX7M2s9m6/bdT328ImPo2pvi40dxpsKKWUORIRmnVObAkf3dnB4hZLI@I9OZxifbLJ7sQPg "Foo – Try It Online")
[Answer]
# 9. JavaScript → Foo → Brainfuck → Wumpus → RAD → ><> → Python 2 → Brain-Flak → 4
This... was.. fun.
No idea why I decided that 4 should be added, no idea why I remade the entire thing (of course, copy-pasting stuff around), but I did it :D
## JavaScript
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);b=c(96);console.log(Q+[...`${Q}76+&;l2:6-&o@${q}${q+q}rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:${b}600${b}+(str(c-99).zfill(2)+${b}99500${b}.zfill(10) if c>99 else str(c).zfill(2)+${b}500${b}),[`+[...`(f=${f})()`].map(c=>c.charCodeAt())+`]))[::-1]+${b}99996${b})),${[...'pppppppPpPPfFpPPfFpPPfFpPPfFPppPpPPfFpPP'].join`+`}${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join().match(/.{1,253}/g).join(c(10)+Q))})()
```
[Try it online!](https://tio.run/##XVLBjpswEP0VDmjx1MEbQkJrvEStVsrZUY9RtBAHElYOOIZWqIhvT21Cu6uAPH543sx43vCe/c4aoUvV@lV9zG83VCRvybq/JkgkP1tdVidS6Pryes70qyEACimwbSJQuAR2MDuNgIm6amqZE1mf0BbvCCGp22@HrxF@YnIRR/5T/d3tr4NZ@Dpopdb1yzEvnAp1EJ9kfcikI5lOFFa4wBvM8RUjhTl8QdLvAG8xd8rC6V6kk8smdz54E6vzJWDOZNIxnbe/dOVo5nmZ56lEnDVazoHxOwqAXUdEg7EPi0JgxYiChYGbCa7A5FsyZTRox4r/Xv5/8ekW1j5@89klU6garcwuh2PmdHGtj6Zlf/lt1rQaAXmvywp9YojY7Q9DNJ/bDSNLEj6lQP4UpZRoAdg6KF3dGdNxMAcrj1hTetdnjHsImkJgtkvvEzKTdvtiAATpntg7iGQtiJgG/aNFADjdA@zi2A/2U2FKozELzNzeZvHU/eGK82LzYPinc28/Npvi1P4Fw1SyMSXRMgSic5VnLWoe6htnBJNMYCJacUbPpA9mi1U4PJ8mj7AK4C2AbeZ2@ws "JavaScript (Node.js) – Try It Online")
Since the output is too big for TIO to return, [Here's](https://tio.run/##XVJbb9owFH7vr7AqVOyZmGvZQhq0rhOa9rKwPuyhQiMxCclmYuMkGwzx25ntuA0Asv2dc75zTxQW6emU81UMSJaLqiRlxsEUfH3@VpU3qwo4qcVdLspuwrk@tUrRZpw3PCsYYiTDLE8q@rtB1g4eQHcV/@nmFWMqwpu5iXOhklW0Bybk32ojqsI@REYXPBXphzE0YRrZuMtw1f3@@BkkVWNRXkrVuFhB7MuU58M6bZIVqbmI2FuCblwpzjq3Uu34KipaYBQNsZGbKaWhmtInjb4o1FCA86giGEPCwrP5XKguah2p5VRSF3rOMXuq5PmiaimmKQe3sywPGZBxUbFycntDw/KVcDrBxP/pTw9bH1L/uZRZviaJ5JunNJRP6ptBcOgib@5TOBwhL1KvO0Ye5XnBWUwYX8M5fiGELFuH@fH9GN95bDAZO3f8Y@uwPaqDt0cpxJQ/rOIE5HCHJmvGI1UO86QvsMAJnuEAbzEUOEDvIHN2CM9xALIE7B4YiFkRg4ZnWTuHIRx4zN95Mi4rmQPptdthuy18mko46iEvqFEfeVuD3L7pQ6Mh8hKD@gMFZxbeIxVv5Ak1g9JkfP0HbyewVej7Wg46m1DA3Nws3ESrEOwmXK5Uy87oQ6coJUTkF89yeMagk9YhOo57Pf1gqEnUcV1E/iUZY3CAsDa47n3NsOp@D@nx0Knr1vMxfldO1gV1Xpb1htSmW4fkiCBaLoiugfpTSqhd9GMJEcLLBUIvk4nTX9jErjs2UVCnddBR2qL@BSIIktnVFZzp2wvT7BIv9VdwtCkLlRKOhojIWMRhCYur/Mo4RnZMSHmUNIVdcuh3BvfDY3dtLVRPAM8R0s38Bw "Bash – Try It Online") a tester that cycles trough all the languages.
## Foo
[Try it online!](https://tio.run/##7V07diQ3DMx1DKXtt8dy6vtH8v5sSauZ6SZQKFSBo3ioJkgQfxT@/ueft7fX4/Tv219H7C@6cGnd1R/f/N3LazUtvJMLrPlAPuWukreF/vt8@/lPXv4PjT8MMb/GowB/8TL52W/ST@nSBx@Qz9kw6VjufCbP/AGC2Jxw/3tfyee/5cCXM5v8uLbg9p2MhTT5DALrvgEwe5wlxMfbT32vQ2Qkv/l9efHbJ7kzSLNHa4O1mzq7/eazqP482ea//mMOWyU8vta7Xvn4g99@uX1pQwW@uQXmr7JJCw788r/8RX4HHxPZbMXlmebuPfzyEvnzzOKL5OuHeQHk90ZeOuiPenziAc6rP5a1@jgfDZNvbet@Jn87W/fL7VsEOPEbPWd@H1s36fBaKXfMZmOib0xUEB7r6xEi0a9axPnrvnmVfE1PLv0I0S4P4RCQe@nT@x6Sn3cuHa/n5bXaHl9fRUp0lyS5JHj68kfqc3zSGuE7@SyeZjI1zewx5fp65te2g379Mkj@DNZHGr2CrF349h1YO0h@iDRJ5k7d/lCODzP/DI4P2vwDX8fj2x/P/YuSfxr3B23@4DHI8T/I6G15JYAT4ha1yr0dfm2P1PcKjV6HCghyRbdaBUmuqtO@xAV/@1bn1xDnVzqfvMNrfT6E/L7y@TBifcINLwjRZ8wLKoHupnpHeiObFq88FZ8Ts@LJ36lr8UzxWdVlAr4vF@jmegGrnVza4Yzl3WUVnzk/3CNflR/AX7tNPpnF@wAwmsMdVZ/gtTJhD6Chl8e7KDv1lTbkluBZgDt/8pK/3XLLbPGZ5OKwIZV0dob3EIEjqHJ5ZL0CSqBbOZuV2VuE@Qe5vf@T7w08F/2Ke34/aWCX630S@HFwhVgzC1vBLJPv1aObI19M2@ORDu6TnyDIx3QWLWql6v2pmEznX8sD1Bvh2CH1Pkc2FJsCWaRWCh0UlOZt5N2HT7GCXaLSNdbO0NyTT4326PB@RXVHwWf4SiF6fEVv38WQSpHvD26Zu31777cEpVnN@12HKe7Ld1JVDS/HJykNYeTXPo0qtzLWwe3q4KmTzy4OKEBvqL41pI8CnsjGuT3cAdwlXz2Ygzm6kgQ38VaTO7tEviK8B@YNlJHvIQbqYn2CCuDr0oDV5ybdH/2ah9jWqd4fmT2c@6FQs7wkhtOrFhxOuDyi98K5EU51B0NahlYFEtyynE@Q/JyXQrsSOfK5vFVf1Mr0f5YXBnt5WGqs@qQRvTzG9k9yFqc0Z8eKWyTtoKIP/Em@U5wSsCL89hVh7dc/kGhnoEiJ4vNKNLHqaoqo5Fe90LL9IeP8hlEwOHyB0t2eryoIdGsKudu/FklzdKnRKswu8Tfw31LScArVaH8i0G0n5y5Jfm3dT/D4dKMT2nrfRN6tKj5p7za1pA6@wCITVNPOoFrdE5rINiy2H3j7M9Jgq8zPHRnScMbQAfR@auIa808pflgVfdOKugh1fUSBkd7YdatPNPiXk7Ol5CtrgVS4o8lDga/LgVbZlwTmwSvapHZBuIPk3si4RMgObuEw2b1VncEu3qlFWpkMLjW9v7JojzjQ7@9lS3pfnA9I7QyDguC0en7N55Cx@gZUQNCLW7Ts5E/kz21XLCNfMqIXH06xF//ni1qtmQZBvnEssMXh1TljKlbnUOb3TfvzJb@U6nsn3wdxQsjsUS3vIwS6ORD65Q5vU2lBu4CIZXlEzeLQtspHkWomuyMwxda@3e0VSsA1DaFU/6rOlHDBz@RiU5K6lhKkVn076mDCFnU0TBBsfv/UVz7cYS0O08MpvDsf7rz9Ofg0j9c9En0bRD6AxS2O8W4c81uGu1G3L4vKtSz5tcv7sOcMAq45TEsiWyV//6H1gVdInDEQod2x86PX6ms/X9QsTmahNnBnWHx@VWG5avPPn8sAt/mldeV6D69FoP759iusPq2Wm7JTA8MWuem/EtQmn@AnuoHdLFQAnsDuxitQye9X6AODLfLM@LjN5AKfMkbv23JLI/MrVAPDPD5NY@9sEeL2jQt7AQlu53aOZEW3qaMHvH3T9BaO@S3TW7fI3yi91Sr5VQ4NZfaYqsqm0iaV99Jk9alUSUP0vq@1kC9vsE4HfCS/P@lCP2OIzf98@6aWD6i4xbWyF1jcov94VKFK21QB@PY1WPr6kgqYYmGmGcP8mNdfgtFNpCZ5NVVTmUyeSxH5Ll3eeIhyK1apmc0hzgTvSwvBKh1OLwdSbXHD9R6fkZ137e2rRq@esziRx1A1mcXETjaezSGs95WncqyDV4zFblkHrxhV4xzC7pBHJFm3@mwCNNBV0hjd9ZeSS3LJJgNWkVvYukd2DPETuWVW/3awg1sfmEp0EK2Pl2Tr8WHupWQYpXTkbBms0sGXC25rlXyDIeuEwTQSgTrABxAlzcbOEgC@wNlZ6hhPIGRZ21V2YfcFTHM4uko4zC6igUzp4T0mBfXuLC0LdHs4SpvV9hwxhHbtrE18e9XTGcT152XyZ@a5CFkeqbbNP35NAajX1YgOM7kK390H8ndMc2X9fXONiHF4bTWiVQc3fltgsEo3yXmm@IZHQD3x@iY6vB0nXTSSzCXJWdfOYBEth5Pv1MaGlvzK4nIVpVla8IOupTnS233EFeUNRsICSr4f8kN7lqf3iLtvv/mIsQjtdqICC1L9xOf3Cpi1@/u9jx85lOrwgy@SmM7Qd2gKRu9zNoduF6cxDuv5Co2C9jY1s1sP7ypolXJ2nkD@bAlYW9win/JSuv2GE14obhmU/F9tZpka86xhfht5WUq@/qHVdnLJH1oxZJm6xbh4@3PqOQnk60vAl9eNZjGwRZ@8uKyu5xe3GJUL2gmHFitoHwNi9/Jq0JJe9@gAJc3O0XAAVKlzHiwOWsWszS/b2Tv5zEkUMlIDV9xiKTWA9fyOUiMNWeatCAuqOp2EyIrVJ8wW0SOvdHkUzbycv6/s9sbw@QchdK6v/MH8shq7nmEizD9oRpMmSLVkpFdnhCbseOvIt5jsSYjzKyuK7@Rv6OY3SH5Juyce6hwRDfj99ucOHxGw@riQHZJGr@Yb@8n8Uyz48gT3LMEnm99nnW79OEKi6be@9BP5GwT2b5K/T2Afo/i0Wfr6QsQwSuPsYMUE9sMHu0oAvqCUu09@XVfQboHXvOrwSkftgza/qkNSz3bs4hYxXgDl91XjX2fLWotb@hmhrotTeTa5ZicXv/Kd0c4grCNkoz0cXojG@YfUvu4d66OlOUThTgcxf2QpH59fyka8pfikR0lidweGKzzMMoZ4lGZhA1ESqbUzkgSbwqzs9kbInx/mVXn7fXZEBWaX0WQPCcXXFxopmMfnFBopAaj3kZ2M8gZhWzhQ2jRpKH1uJJl9MPwP5rcM1icWAfP7jsFwPEa3lbVcNYdXXS4QJrH2ufGXf10HWGfR6Vk0k8vF7y3D6hQvkFOdwsyVlwHUpklVD7wsj2S5A8flkY2aljO/rA6MjiB3qNZcBa0ijpBVCi8AYIucwx/QuTx@IrRpBneDgXeZfOlhqoRuDsrdSFhB@du35hUfrM6Si/l6@3Mmbgff/iSz7uTX@Dm8VsgG3eQ321jo0iYzYxFe2@NlMPaPI2y1fytGkB8@CIiuo0h3HkCP03wSOL19x1w7lErVgYqOJVIOhEV2Vo3VKS5FucA1cp3y8QZ2bdVwcSmsnl9ZRbBKm@z8Y6THxw18kOr5BQUWTvrUmz3SL0J2JBmH4YjVHYrSpCvSKxIS@Ez@nFGrwRbmzexeQD2/82j6LPOb28Yu8AUEj@8Y3rL5iPyGTKWADdDby9N@dmCoUjccZ7UJ7KKR3qHoPrEpzEp2a2pjUcyuIdC1Ph5fyd7w6A2qIjKa45sMVK3WxUmWqhHJP0T5/1hSPI@PYTcSkFqn1HgfwRbmSRZv5O1v38Q6MQ5Ue/vyJgNpOoPqAcanM4x4C/FhlMLKbXUolfAGa7cHxu3RhjYgVXRrq4pgqHNi9vM6@SOr/oKhzilVfzH4gjGIhfkEt/XpIfr3jU9PBKW5K@4Nj/R6@YfV7Qzihd6iU5hZ5p/g7R/EDAGvl0fy0QT9/SmF/vEpzCNq/J3GEhXsDTSLU/h9x0Cq9xhG3wVcI1Ib0wNbJMNbMyu6Y5J/j/f@lXxW2F3ujFMV3Szbr@6Ms1Cl5vf//vaFr1/y9ifoyITkn/D6U8zv3/WofvssxTdAiwV@rd/IVrql8EwuQS2WuP0pnl5Q72/6@jOKb4Cd@Lz9Y9brZ4m@CdzCKmoVPeMcYpv9/WeiPQN0hfjts0Tfnh4PGbaIWvZ0sObwskjD55Ob4Qp58Bi310EB6hWXhIZSyQ7QA3@giXwVlCAYUK28BLy5tKqdwQS2t6yD@7CoACzu31e3i5eqOufxf20rk/orSALW2ddAhtMcZJv1oECVpndpFgHoxOcXsC5BsziVW56DYJWyoHTAnYGHUrm9nqJGtsNkOncRcotLx1ely2OgB81Bq7IfqXn7Nvm/Askvi9V2ZKI9EwHb9oMpJsEVejjEZczvYTr@JJ/ltjugNM@RcBdWJSu63YMjPf6@jEVIH0ukZUbFC9ukFWJoLs@sqYOrzL/J/M0Hb19@emS53p8e3rvg8U0O7604vNMHlIGnMrklPXvJb9e2yLJGQ4MZWtbo5zCiyDcNhuHy@5aVHl3ki5hXdSlOCzEgNpuDzRUBkOpJgdEIWqM0CP/mA@hjrUzjqhoPVqBbOOURMXt00dYpWJ1T4vxX1kCsPmnhHoIqJSl32TbGPfB6QeS7mgKNXZwKXmVjuEOS/KGj1oP@/vCQFzrQ7eEOULo4DSKGUiXN/FNbi/aMG9mpNoGdnFzZ9PZVS5oz2ibw72EpztJtZ/55yuxZ/bL8fZ@RX7ybQyoDUvv2iY5w7As1SS6aP8Mxehs3WLu98CBa1gZrt5cDr3C44Pjtj7jghz@OM/@I84EUtMuez2KOj3VBLaey2MO7gzDM1PMPeCsFZk8ls6I/mpL8/rwyUPEtDqZxYlb09uAV3V5vRUDxdcpVQrhD@a08In@@x2Ot@ABfzDexWhsGxR6fuhHJVHyCp5JweBvfyre3t38B "Foo – Try It Online")
## brainfuck
[Try it online!](https://tio.run/##7d1Rjhw3DATQA3XgOyUBAhgB/GEg598cwTs7bnWx@PZ7tKIoslikJPZfP//8/uOf//7@9@Pj@uXftz@ur/19deBL4z774y@v4u3BR2Z7R8Ij@3Rop57Z3U//hwd/GKWw/hmHWfEZcQ8p5ZTufz3PaSv4/HxP4MbLMz8R1QrJQfyEB@ZI26VBVjOQYoTzBeI9J9TDmgi3k7vkW2fxN7GcVI3fVAuYwz5vWFG8BR/cxb0p3awMP06P5dlZlCbRWqx7FevGartZ7RiGO4fVlp/DzieKxQeKz@zIQ3aw4WA4M1s7435JNwQarjVMQPtzWsn2m69J9/qoQ0fVaTSLNVda82BzZu/r7X2h0TNqRr0Fy9l6ta0fe9MwzS/YPbv/PUroZPeP@Mew7Ke81Jv7iOLsrO4vEI94xKMd2jF9gVA2wkawE2ZqI2zEfQnqYbyqe8v92ozZxQq20GsLfcouaT2RsjczL6RXNjxJt8LG7kCnj4KiI/OT21xzyPvqQk4uvBk2dVXDr/Fr/Hojv86m0odaCR8acesM4WQcNZzh4KfvnVeR5KfmruXKqbPdfA037GQsHhOWh34oB@VCUO7hN/E6SKYuNzWGaBs5bNLQc0n5bT4wIVVIldRxQuq4LokLOtwPbIYVmIsc3rnbl59eqKlTXKStJbbVOLaSzIUkW3Eg6B8fWojouz26ai0lJKtmT1r2IzO6SCyA0ODwe7SGkZvldCk7n/ECGope55od@BJKwxbXHlLT@lzQalRadK3GiUX4voK2@ck1VHvIQ6EbdKsjSMH5MJTr9NS1tYSOYsLuY7auWr1aVRadYy5cGKfeBxTJvHA1upLtmTzkgIBNV/iyUacke4t@jtAn2@ZgHV6k7qou1Sk73AZgThkjUhjoME2M2OPBnfyZ5bN8GoYtczelZiXWQcOjFewRS8oivNeFI0P5YgnHck20hMq1JApKnN5ZvD@UYa9kF05llUGacpGm940UjM7R76osLvkCIydu2HuvMkRHWDS4EtFjYdLhM9IpvG/0eY8WRbyCyLK5ZbqD9Y0xCJViwoNDrwPsxeGH6y7M4yl4pYLpd3HVQ3H4arF@2M1TslTmGEVpJcd95cybfX45euuLdNQM9raVY8y@crxzP7rWwlFG@5aSfCYzyP5AC@nOTkR/OJ3cRJYqol4@rBf9VQb9UsKZR88dSNFGtBFtlkcb4WZ3KiQ6iU6i097oJEQJUcczIkFH0BF0BJ1I6USbzagkMrEBkakhMqUz5554LmIm52cOrMRAMVAMFAPvHSYK7sZLkTM233bOK5oHAob3MlmW5e1PAdhrx0XBFEzBFEzBFHw@OdWAjk2ySTZJwWySyka5MS9mkZyYE3NiGsMOoSSVcWNeLLBwYk7MiWlspcq6Lihq0Lk8g3HnDFpAC2ix0JoZM/BoVDi7vnquVfd9CagkQntAsw70fFoyK73a/MXL5Lwi@bnV@uYH3uftDMKAf61JLvcuD8QnL15pM5Z/vjVUoZ41M2bgsVjh7Dq5iDHBiaIxtSntyL5eV3YaU1d09YlRUAWqQNUAj5POTt95xy/MvizP6eODpLuc/KXyE@8Uk5ZxqeYvXsxVdANYTFH4UPhQ@MDJ26RT3lbehvJQXpouTZemy2yl6fN5CdoUWkwAsqLeYLFG4FLjx0vXS7cXOJG5wJyPda1zXZfGXBpryCpLU0tlS4xKRo0crlnM5XbR2pji3LlDyY3pdN/tIocpbshAKkiFrQQXW5K1lg1TjaizuhpENp5aV1WJvTmA4TbEmrWFZyy4AoSR3wcEdOZ4RW6PNrLZPMvFiDaGermyLCUuD0RiUNf1PIrWiT0GX6IN3hVm9QFiqacsraco3mXKFv5VosorXfoe9OGbM0zkoE3ZnsyTjnRgHsyDeTnjAPoOm5Zjk2vRZCsrFrRc2bEO67AO65iyji@PpOHxGm7a@@Ct51t8i2/xLb7Ft/gW3@JbfMvOqxlALxqGEuID32LB8ZK5aPyGdBpTeAaatiMdG@IV2eX9XSw7mRCg3dhLWzzLbwNo7FTbtNM1AW3TlkYP3dV0V7vWfyYrVzDPnfYyex24djGRon5omCv2WsNeNZEdkJbDNU1kuxStiewy0qSJrCayxLpvFD6W7ABVZTveKY/Ly5FQ47gdcbEObQN1g8mUUgV6/YB9Q1y4m5VcTTCB5X1aq1L/vVd2NIHuCubylM15ipJM2I4oyQxnE5UUEa/u@@7b@pNS51dyESpeFC7eiDC/@d/f89OjMffk2NF7fbssQ7jq00OjduE2ALh/leGuQDziEW@CeLRj@gFCMVPTM1N2wkyZKTNlpqgx8WjH9CCOmT4//bePj/8B "brainfuck – Try It Online")
## Wumpus
```
"76+&;l2:6-&o@'''rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,55,54,43,38,59,108,50,58,54,45,38,111,64,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`)),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P'
```
[Try it online!](https://tio.run/##nRZdT@Mw7K9M98Caa4aS5qPNCuieeC7PCGnjY3ecylYK6Kb785ztJF23tXBC6xrH33Zsp3/enpq3l/f3b7lNT8o6m9vZyebHdDptm@Zic3b/sJqsky2b/6w3t8t6UpfteZM26Sq9TKv0OU2atGLfk3q2ZelVWk0eV5PtWT15qF8eJju@wLWd1Sytyvp8W7YPr2/tetKW0@lyOm3O7361iRasrDwkWflMkAPoykOKlSuCZAbgZQANA326bNrH9StZjL@q@1fBC3wf7iv@tGySNb3r5dPt/XKynW/aewh5pgv@8tom7PT35nGd9Dju5gsrxCJNkHw3c46d/l091nWSsXThnAFaQEjBMCV3F875nJBEnx2ZGb/WgkuRcSu5M/i2GYcwuZQKd0B1DoECURb@GtgNrCimuLYkTWgpAQbmHBbNXU5Y3BEB@UEfqTSSmxxh43ghybaL@CzgXdHD59zoiHdeITogTVBeeOXWg4RSKAjKteKOSP5xlitLEQINDpEbQ7oVVwWqRwUGLBaENYhFfVZHMUwMyvW2eof1icjoj5lEUdFFj6lSGfmOac8ExVSQt9FziBtTBzvkFN4pTKQkpWTLL4KWXOC7ENELTYEHnoIs6IxQoAsCCla1CskBFjJkOu@AwYqdByG/mGuAVfa5GyP20bDxbkTLIeEYWyZipGSSai0P@fQuAggcih5IkQco0VQnWHTIg/UCBotYX2KY7gI9FPoBQ75j6Ap0n25kVCAGPABpI3Y8uRhlUZ0aygO4ZlwooV6rQTqOM//BEuthbBNQAyXUR31BBFGa5gANAH/ycggpQqFTq2OH4Jn68jOhiSkD/V6B@sEEWVJH3W@7dIb@t6H/Tddm/2UWzgashqZGSubnQoHPPjpW@J55HFSG6iKPrmSZn43ChAlVUOnE9juwRZJYDUMWR7VhlVKl7/cwzuws6Bxr4iP3v@L1iL8SDwjGLkzb4/m7u3HiDEV7QYzsAJMLd0v/7PxNZCk8VOU@uGisDy8Uhr8GvFbaOpq7hiYi5NCp0RPJw@1zHCEFGdG9EJXrroChfyHiUvhE5F9CBDWfa1SuS@Z@b4TDsYfXGW5HTgCrZncENEj9jNO2N7p9wZGUjVJfOa/OhI7IwQaPBBdNBkNIyn1NK2oUHQau8Te/zv1nwpheb7/rsHBj0tOv1hvGrufzmbzBLzDn7IIx3v8c3P8Y/Biqhvmn7@//AA "Wumpus – Try It Online")
## RAD
```
'''rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;''a''p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,55,54,43,38,59,108,50,58,54,45,38,111,64,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`)),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P'
```
[Try it online!](https://tio.run/##nRbZbtsw7FfyZmtWCsk6bMVtH/vsPhcFmubYMrhJ6nZAsJ/PSEpynMPtEMSxKN6kSMrtdL7fJ0nSbrf3m9v5Yjlapzs2@dlsXqfNqKnau222zZbZQ1Zn71m6zWr2I23GO5Y9ZvVotRztbpvRovlYjA58gWs3blhWV83drmoXn3/a9aitkmSaJNu72a821YJVtYckq94JcgA9ekixakmQzAF8CKBhoE9X23a1/iSL8Vd3/zp4ge/Tfc3fptt0Te9m@vY6n452k007h5DHuuQfn23Kbn5vVuu0xzGbvFghXrIUybOxc@zm73LVNGnOshfnDNACQgqGKZndO@dzQhJ9dmRm/EkLLkXOreTO4NvmHMLkUircAdU5BEpEWfhrYDewopji2pI0oaUEGJgLWDR3BWFxRwTkB32k0khuCoSN46Uk2y7i84B3ZQ9fcKMj3nmF6IA0QXnplVsPEkqhICjXijsi@cdZrixFCDQ4RG4M6VZclageFRiwWBLWIBb1WR3FMDEo19vqA9YnIqc/ZhJFRRc9pkrl5DumPRcUU0neRs8hbkwd7JBTeKcwkZKUki2/CFoKge9SRC80BR54SrKgc0KBLggoWNUqJAdYyJDpvAMGKw4ehPxirgFW@fduDNhHw8a7ES2HhGNsuYiRkkmqtSLk07sIIHAoeiBFHqBEU51g0SEP1gsYLGN9ict0F@ih0E8YigNDV6DHdCOjAnHBA5A24sBTiEEW1amhPIBrxoUS6rUapOM8818ssR6GNgF1oYT6qCtEEKVpDtAA8CcvLyFFKHRqdewQPFNffiY0MWWg3ytQP5ggS@qo@22XztD/NvS/6drsv8zC2YDV0NRIyf1cKPE5RscKPzKPg8pQXRTRlTz3s1GYMKFKKp3Yfie2SBKr4ZLFQW1YpVTpxz2MMzsPOoea@Mz9a7we8FfiAcHYhWl7Pn8PN06coWgviJEdYHLhbumfnb@JLIWHqtwXF4314YXC8NeA10pbR3PX0ESEHDo1eCJFuH3OI6QgI7oXonLdFXDpX4q4lD4RxVWIoOZ7jcp1yTzujXA49vQ6w@3ACWDVHI6ABqmfcdr2RrcvOJKyUeqa8@pM6Ii82OCR4KLJYAhJha9pRY2iw8A1/ubXhf9MGNLr7XcdFm5MevrV@szY02Qyls/4BeacfWGM9z8Hjz8Gv4bqy/zJfv8P "RAD – Try It Online")
## ><>
```
'rpp>o<def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;'a'p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,55,54,43,38,59,108,50,58,54,45,38,111,64,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`)),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P
```
`><>` outputs a newline in the middle with `'a'` so the python function would be separated from the rest of the code.
[Try it online!](https://tio.run/##nRZdb@Iw7P1@Rd/WXMOUNB9tYNvjnrvnaRKMwY1TB6zbSej@PGc7SSnQbidEaRx/27GdLlcfr/v9VbPd3m1uXhbLZJ3u2PhXvXme1Uk9aW632TZbZvdZlb1n6Tar2M@0Hu1Y9pBVyWqZ7G7qZFF/LJIDX@DajWqWVZP6djdpFp9/mnXSTK5mV9vb@WuTasEmlYckm7wT5AB68JBikyVBMgfwPoCGgTY92Tar9SfZi7@q/VfBB3yf7iv@Ntuma3rXs7fnl1myG2@aFwh4pEv@8dmk7Pr3ZrVOOxzz8dQKMc1SJM9HzrHrv8tVXac5y6bOGaAFhBQMEzK/c85nhCS67MjM@KMWXIqcW8mdwbfNOYTJpVS4A6pzCJSIsvDXwG5gRTHFtSVpQksJMDAXsGjuCsLijgjID/pIpZHcFAgbx0tJtl3E5wHvyg6@4EZHvPMK0QFpgvLSK7ceJJRCQVCuFXdE8o@zXFmKEGhwiNwY0q24KlE9KjBgsSSsQSzqszqKYWJQrrPVB6xPRE5/zCSKijZ6TJXKyXdMey4oppK8jZ5D3Jg62CGn8E5hIiUpJVt@EbQUAt@liF5oCjzwlGRB54QCXRBQsKpVSA6wkCHTegcMVhw8CPnFXAOs8u/dGLCPho13I1oOCcfYchEjJZNUa0XIp3cRQOBQ9ECKPECJpjrBokMerBcwWMb6Ev10F@ih0E8YigNDW6DHdCOjAtHjAUgbceApxCCLatVQHsA140IJdVoN0nGe@S@WWA9Dm4DqKaEu6gIRRGmaAzQA/MnLPqQIhU6tjh2CZ@rLz4Qmpgx0ewXqBxNkSR11v23TGfrfhv43bZv9l1k4G7AamhopuZ8LJT7H6FjhR@ZxUBmqiyK6kud@NgoTJlRJpRPb78QWSWI19Fkc1IZVSpV@3MM4s/Ogc6iJz9y/xOsBfyUeEIxdmLbn8/dw48QZivaCGNkBJhfulu7Z@ZvIUnioyn1x0VgfXigMfw14rbR1NHcNTUTIoVODJ1KE2@c8QgoyojshKtdeAX3/UsSl9IkoLkIENd9rVK5N5nFvhMOxp9cZbgdOAKvmcAQ0SP2M07Yzun3BkZSNUpecV2tCR2Rvg0eCiyaDISQVvqYVNYoOA9f4m18X/jNhSK@333ZYuDHp6VbrE2OP4/FIPuEXmHN2yhjvfg4efwx@DVX9/D/2@38 "><> – Try It Online")
## Python 2
```
def n(x):global l;r=p+p+f+F+P+q+(p+P)*(l-x)+Q+P if x<l else p+p+f+F+P+(p+P)*(x-l)+P;l=x;return r;
p=chr(40);P=chr(41);q=chr(91);Q=chr(93);f=chr(123);F=chr(125);l=4;print p+p+p+p+p+p+P+p+P+p+P+P+f+F+P+f+F+p+P+P+f+F+P+f+F+P,map(n,map(lambda x:ord(x)-48,str().join(map(lambda c:`600`+(str(c-99).zfill(2)+`99500`.zfill(10) if c>99 else str(c).zfill(2)+`500`),[40,102,61,95,61,62,123,113,61,40,99,61,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,41,40,51,57,41,59,81,61,99,40,51,52,41,59,98,61,99,40,57,54,41,59,99,111,110,115,111,108,101,46,108,111,103,40,81,43,91,46,46,46,96,36,123,81,125,55,54,43,38,59,108,50,58,54,45,38,111,64,36,123,113,125,36,123,113,43,113,125,114,112,112,62,111,60,100,101,102,32,110,40,120,41,58,103,108,111,98,97,108,32,108,59,114,61,112,43,112,43,102,43,70,43,80,43,113,43,40,112,43,80,41,42,40,108,45,120,41,43,81,43,80,32,105,102,32,120,60,108,32,101,108,115,101,32,112,43,112,43,102,43,70,43,80,43,40,112,43,80,41,42,40,120,45,108,41,43,80,59,108,61,120,59,114,101,116,117,114,110,32,114,59,39,39,97,39,39,112,61,99,104,114,40,52,48,41,59,80,61,99,104,114,40,52,49,41,59,113,61,99,104,114,40,57,49,41,59,81,61,99,104,114,40,57,51,41,59,102,61,99,104,114,40,49,50,51,41,59,70,61,99,104,114,40,49,50,53,41,59,108,61,52,59,112,114,105,110,116,32,112,43,112,43,112,43,112,43,112,43,112,43,80,43,112,43,80,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,112,43,80,43,80,43,102,43,70,43,80,43,102,43,70,43,80,44,109,97,112,40,110,44,109,97,112,40,108,97,109,98,100,97,32,120,58,111,114,100,40,120,41,45,52,56,44,115,116,114,40,41,46,106,111,105,110,40,109,97,112,40,108,97,109,98,100,97,32,99,58,36,123,98,125,54,48,48,36,123,98,125,43,40,115,116,114,40,99,45,57,57,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,57,57,53,48,48,36,123,98,125,46,122,102,105,108,108,40,49,48,41,32,105,102,32,99,62,57,57,32,101,108,115,101,32,115,116,114,40,99,41,46,122,102,105,108,108,40,50,41,43,36,123,98,125,53,48,48,36,123,98,125,41,44,91,96,43,91,46,46,46,96,40,102,61,36,123,102,125,41,40,41,96,93,46,109,97,112,40,99,61,62,99,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,96,93,41,41,91,58,58,45,49,93,43,36,123,98,125,57,57,57,57,54,36,123,98,125,41,41,44,36,123,91,46,46,46,39,112,112,112,112,112,112,112,80,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,112,80,80,102,70,80,112,112,80,112,80,80,102,70,112,80,80,39,93,46,106,111,105,110,96,43,96,125,36,123,113,125,96,93,46,109,97,112,40,115,61,62,99,40,52,51,41,46,114,101,112,101,97,116,40,115,46,99,104,97,114,67,111,100,101,65,116,40,41,41,43,99,40,52,54,41,41,46,106,111,105,110,40,41,46,109,97,116,99,104,40,47,46,123,49,44,50,53,51,125,47,103,41,46,106,111,105,110,40,99,40,49,48,41,43,81,41,41,125,41,40,41]))[::-1]+`99996`)),p+p+p+p+p+p+p+P+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+p+P+P+f+F+P+p+p+P+p+P+P+f+F+p+P+P
```
[Try it online!](https://tio.run/##nRZdc9ow7H2/Io/xYnp2/JGYrHvsc/rc2x0thZVdCjRld2x/nkmyHQIk7Y4jxLK@JUtytn92L5t1fjg8L5bJOt2z6c9m8/TYJE3V3m6zbbbM7rI6e8vSbVazr2kz2bPsPquT1TLZf2uSRfO@SI58gWs/aVhWV83tvmoXu9/tOmmrL9vb@UubasGq2kOSVW8EOYDuPaRYtSRI5gDeBdAw0KWrbbta78ha/NXdvw4e4Pt8X/PXx226pnfz@Pr0/Jjsp5v2GcKd6JK/79qU3fzarNZpj2M@nVkhZlmK5PnEOXbzd7lqmjRn2cw5A7SAkIJhOubfnfP5IIk@OzIz/qAFlyLnVnJn8G1zDmFyKRXugOocAiWiLPw1sBtYUUxxbUma0FICDMwFLJq7grC4IwLygz5SaSQ3BcLG8VKSbRfxecC7socvuNER77xCdECaoLz0yq0HCaVQEJRrxR2R/OMsV5YiBBocIjeGdCuuSlSPCgxYLAlrEIv6rI5imBiU6231EesTkdMfM4miooseU6Vy8h3TnguKqSRvo@cQN6YOdsgpvFOYSElKyZZfBC2FwHcpoheaAg88JVnQOaFAFwQUrGoVkgMsZMh03gGDFUcPQn4x1wCr/HM3RuyjYePdiJZDwjG2XMRIySTVWhHy6V0EEDgUPZAiD1CiqU6w6JAH6wUMlrG@xDDdBXoo9DOG4sjQFegp3cioQAx4ANJGHHkKMcqiOjWUB3DNuFBCvVaDdFxm/oMl1sPYJqAGSqiPukIEUZrmAA0Af/JyCClCoVOrY4fgmfryM6GJKQP9XoH6wQRZUkfdb7t0hv63of9N12b/ZRbOBqyGpkZK7udCic8pOlb4iXkcVIbqooiu5LmfjcKECVVS6cT2O7NFklgNQxZHtWGVUqWf9jDO7DzoHGviC/ev8XrEX4kHBGMXpu3l/D3eOHGGor0gRnaAyYW7pX92/iayFB6qch9cNNaHFwrDXwNeK20dzV1DExFy6NToiRTh9rmMkIKM6F6IynVXwNC/FHEpfSKKqxBBzecaleuSedob4XDs@XWG25ETwKo5HgENUj/jtO2Nbl9wJGWj1DXn1ZnQETnY4JHgoslgCEmFr2lFjaLDwDX@5teF/0wY0@vtdx0Wbkx6@tX6g7GH6XQif@AXmHN2xhjvfw6efgx@DNXD/IfDPw "Python 2 – Try It Online")
Python generates the brain-flak somewhat optimized, reusing the previous item on the stack, because otherwise the brain-flak code would be around a megabyte..
## Brain-Flak
[Try it online!](https://tio.run/##7d1NjhxFEAXgPaeYnbslOATnaNXCsAEhsWBr@eyNzQgMdnVXdjNVERnxeSzPaOwpZ2ZlvPh/8dMf73/9/Zf3P/92vZ7@@nX@/HH@8PHT778/n18u706nT58vr397Oi/nd9@/vH7vy1enfz6@fG/tJ0b@zdpTV3/mudWsrCd4RSnO59vv3Hjinefe/@o0fAqXhuc/y2o2/ofjVveflXljw3IVhCbr@NsZ/98CcZ3Q/9VJN55dX98OPHW@/d56h/Xe6B0NfOhbva2VWdJ734PR3e23z2@esfBdou3zLY1@lE0eupI73kvYqpa797OhTR6GlIfLaw49mQexe/oajyNQD88zieUc4C8M6MtCb@EmHi78FBgs3iPeI94j3iNz93Z@ZrAPPnIiNF2W3I@MKmuN17ax601sLXPyIzGyCn7AhV28b5RxqS0ng1kh8SQR1QPPPku@ITjmcbAMstLE1lls@92yu6jmLbKXxDIr1hWJJM5WRT56f8J7WTr4pmzj7laLOpN2NsXy0LMD4hKnZjGqHJXjgd0JZesz0lUXr@EOWSqPZjmy@B0xXlWh7KmqQlZzQOdWiK7f6rFLwhGSeoU9og8j7@ExDCrwDg5FV7JKVr0HeWa3je6iu2AmO5OsklWySlbJKlklq2SVrJJVHrX3YJd2aZd2aZcz7jI6J56l59YqxqeY9Kk/VqOag4UZx5EK4ttnDY8641FUV@tpTF9biZXAZ/jcC5@z8GLOV5ke4vNtMs9FTWIMxewsq8nvkfPP9JXjU8anjKkPnzJeN3zK@JTxKeNTxqdchU8Z19@cuMn2xcSHiQ@nSOmIieiASo3mvImRnSayi0EsSi2ZqfP2VGFNVEesmhn/aKP3piqadavOrTl398BNbLiatRiO@lu4BJfUUeWLTZqMFlVP9Zwdb@9mIojXpdxjvM41kVTthKo8VdIZdFoMl9ky6pGoDHevWMa9b3MezMAckL1SeIZa6rozPHtUOeWID@S4WRm9ylz5rkwsCqK5ormiuaK5orl6BtUMqBlQy6SWSZQEVsNqWK2@S32XiICIgIiAiICIgPoufkBVDmNVd6ruVN01rLrLxnuToKdcZEZkRhRdFD3X1CaYBJPaY9LE2Zrq1c89WLNjue874WEkn2xfNvhsGQD81firq@NNzzu@HQOXUzQ1Z6KI9cFvVX4RjsocyRyFZI6COWSHpqSFdTp3rSTox@w7po9pO7MnafKMPkOl/MIEWCVfIV8hfuhey1fIV5CBmfMV4f5/3fwEBIEgECS683bTqujWL33nnB7Lh@kYmHaK5hS3kdSSWlJLap0TyZ3ZH6FJ3EeaBEKSWlJLap2Tc2L/uZPupDvpTrqTztpZO2tn7aydtbM2abBnX6Aeet0/sPHNJzHqJ73bzfn80/UWlLyxmfgfUky8yjnX5QEOAYwdNP3@u53OhquvX3NXDtCAz98pmpAmpAlpQppQfRh9Oqs@zTO5jMaisWislL7b454b3y0hX2G0T0LX0DV0DV2Tah6WPDG9NWcene6iu@iuSXJcfKX8OifRjFj6hr6hb@gb9bRj1ffxnknYinJzjHpn@W2xXvq0Tw9Th26eflPqxuolzecrNMtIbxptXG/OnD4wfWAYeUzILCFD8dNS2@iNNHHo9Tg9HIDe4rjp5RbrIO5pSIJ7GmY7a5xqopr7M4yVz0tkjmjVus09eRgz3bBtq7RyJDtBHKjJ3c/VzV@blTPHzRIXqNCdLD/UTzP1yAHNaZHJD8kPiX/JD3n7@Tri5ePk48iufBwd6awT2SNt65NV5fOsZZuy5TPz9flu6KNy0nknvuf21/SEA/a54Y3LHehu0KHOolFD0KaucFs21DhVs/cuj82JEP2xS9GkrHVsy9HWpNyhXG2xnQbI0IAnDrvIElmaRJYuY9O8@S97MmqHvPn4ytzLtpUS91aSsjzJ9GICy4UjaSrwEmDJhnywjNvPY2TNHrWKZ7XIrqcS1AFlFeN4EX1ndJKqDMhej6OqrKqvk0NTqI9Qtwg/sGp1mdsy@31twryfhSkgSdR8wFbgC5jYOG2/DNyZYALvaDUoHIJDJTIIUCm5HQKR9M/pw@GXvzWyLXg2LuaHH336gZwOte/8YygKOyFW757pPpnJHln@2hmdPAz@sHDP3Pr2emM6PlNVaZVjDewapenB9qgHMnJuUeZsQNSqhs8HQnRgmN5JW4x0M63tfXk5vf76/NMfPn71x/lf3//uer3@8OOf "Brain-Flak (BrainHack) – Try It Online")
## 4
```
3.699996004050060003000009950060061500600955006006150060062500600240000099500600140000099500600615006004050060099500600615006008350060017000009950060015000009950060006000009950060011000009950060004000009950060046500600030000099500600150000099500600120000099500600100000099500600675006000500000995006009750060015000009950060067500600120000099500600010000099500600020000099500600415006004050060051500600575006004150060059500600815006006150060099500600405006005150060052500600415006005950060098500600615006009950060040500600575006005450060041500600595006009950060012000009950060011000009950060016000009950060012000009950060009000009950060002000009950060046500600090000099500600120000099500600040000099500600405006008150060043500600915006004650060046500600465006009650060036500600240000099500600815006002600000995006005550060054500600435006003850060059500600090000099500600505006005850060054500600455006003850060012000009950060064500600365006002400000995006001400000995006002600000995006003650060024000009950060014000009950060043500600140000099500600260000099500600150000099500600130000099500600130000099500600625006001200000995006006050060001000009950060002000009950060003000009950060032500600110000099500600405006002100000995006004150060058500600040000099500600090000099500600120000099500600985006009750060009000009950060032500600090000099500600595006001500000995006006150060013000009950060043500600130000099500600435006000300000995006004350060070500600435006008050060043500600140000099500600435006004050060013000009950060043500600805006004150060042500600405006000900000995006004550060021000009950060041500600435006008150060043500600805006003250060006000009950060003000009950060032500600210000099500600605006000900000995006003250060002000009950060009000009950060016000009950060002000009950060032500600130000099500600435006001300000995006004350060003000009950060043500600705006004350060080500600435006004050060013000009950060043500600805006004150060042500600405006002100000995006004550060009000009950060041500600435006008050060059500600090000099500600615006002100000995006005950060015000009950060002000009950060017000009950060018000009950060015000009950060011000009950060032500600150000099500600595006003950060039500600975006003950060039500600130000099500600615006009950060005000009950060015000009950060040500600525006004850060041500600595006008050060061500600995006000500000995006001500000995006004050060052500600495006004150060059500600140000099500600615006009950060005000009950060015000009950060040500600575006004950060041500600595006008150060061500600995006000500000995006001500000995006004050060057500600515006004150060059500600030000099500600615006009950060005000009950060015000009950060040500600495006005050060051500600415006005950060070500600615006009950060005000009950060015000009950060040500600495006005050060053500600415006005950060009000009950060061500600525006005950060013000009950060015000009950060006000009950060011000009950060017000009950060032500600130000099500600435006001300000995006004350060013000009950060043500600130000099500600435006001300000995006004350060013000009950060043500600805006004350060013000009950060043500600805006004350060013000009950060043500600805006004350060080500600435006000300000995006004350060070500600435006008050060043500600030000099500600435006007050060043500600130000099500600435006008050060043500600805006004350060003000009950060043500600705006004350060080500600435006000300000995006004350060070500600435006008050060044500600100000099500600975006001300000995006004050060011000009950060044500600100000099500600975006001300000995006004050060009000009950060097500600100000099500600985006000100000995006009750060032500600210000099500600585006001200000995006001500000995006000100000995006004050060021000009950060041500600455006005250060056500600445006001600000995006001700000995006001500000995006004050060041500600465006000700000995006001200000995006000600000995006001100000995006004050060010000009950060097500600130000099500600405006000900000995006009750060010000009950060098500600010000099500600975006003250060099500600585006003650060024000009950060098500600260000099500600545006004850060048500600365006002400000995006009850060026000009950060043500600405006001600000995006001700000995006001500000995006004050060099500600455006005750060057500600415006004650060023000009950060003000009950060006000009950060009000009950060009000009950060040500600505006004150060043500600365006002400000995006009850060026000009950060057500600575006005350060048500600485006003650060024000009950060098500600260000099500600465006002300000995006000300000995006000600000995006000900000995006000900000995006004050060049500600485006004150060032500600060000099500600030000099500600325006009950060062500600575006005750060032500600020000099500600090000099500600160000099500600020000099500600325006001600000995006001700000995006001500000995006004050060099500600415006004650060023000009950060003000009950060006000009950060009000009950060009000009950060040500600505006004150060043500600365006002400000995006009850060026000009950060053500600485006004850060036500600240000099500600985006002600000995006004150060044500600915006009650060043500600915006004650060046500600465006009650060040500600030000099500600615006003650060024000009950060003000009950060026000009950060041500600405006004150060096500600935006004650060010000009950060097500600130000099500600405006009950060061500600625006009950060046500600995006000500000995006009750060015000009950060067500600120000099500600010000099500600020000099500600655006001700000995006004050060041500600415006004350060096500600935006004150060041500600915006005850060058500600455006004950060093500600435006003650060024000009950060098500600260000099500600575006005750060057500600575006005450060036500600240000099500600985006002600000995006004150060041500600445006003650060024000009950060091500600465006004650060046500600395006001300000995006001300000995006001300000995006001300000995006001300000995006001300000995006001300000995006008050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060013000009950060080500600805006000300000995006007050060080500600130000099500600130000099500600805006001300000995006008050060080500600030000099500600705006001300000995006008050060080500600395006009350060046500600070000099500600120000099500600060000099500600110000099500600965006004350060096500600260000099500600365006002400000995006001400000995006002600000995006009650060093500600465006001000000995006009750060013000009950060040500600160000099500600615006006250060099500600405006005250060051500600415006004650060015000009950060002000009950060013000009950060002000009950060097500600170000099500600405006001600000995006004650060099500600050000099500600975006001500000995006006750060012000009950060001000009950060002000009950060065500600170000099500600405006004150060041500600435006009950060040500600525006005450060041500600415006004650060007000009950060012000009950060006000009950060011000009950060040500600415006004650060010000009950060097500600170000099500600995006000500000995006004050060047500600465006002400000995006004950060044500600505006005350060051500600260000099500600475006000400000995006004150060046500600070000099500600120000099500600060000099500600110000099500600405006009950060040500600495006004850060041500600435006008150060041500600415006002600000995006004150060040500600415004
```
[Try it online!](https://tio.run/##1VmJjhshDP2jytzw/x@Wbjdjq35jkznItllphWCwDc8nTn480q86vv4qUaZC9DVSoj9/YzynNTzHUfS8xucYs9oesknNzHG9p42saS5FTb////oa9FctMlfzHsAyRD0lfey28dBEo5m8eDfwJDim/poBmbLNS9Pfy7a/B9DHcOijTT/6C/pNbskOvQOcvmSoM5RpTBGp5i7kAdomDU/eDGoEzRTHsY2pmmbM7KK@TykA0iYtdQ0WXKEwxh3IiyaHq9Y8PSO4Ghz1GBFfYM4LfSfNphwY8DJ0xCvAaVM0rYyVHoPpUgwzmMrcrtg/2MdhN58ENWsjxE4G0Aja9jLZy430vNNUd7zMIDnChAs7StRkcFE2VQdy4RpsKQJfPaJuEFJprpJpkIGIBJvFwH5CUTc1gtAXW1GOBpzQxJYKzB27BvQwa/dp1Ag28sUUnGBkt8T14FQrw0zgIExyHyPdndxLS7gPm7tTMp0U0uZCvPLhHHcuMpA7rdBCxmzpCGu0VEpyrmT7CSuzOLnwTOEK7nMtFr1zeZdplm7D@cWoepDsvzyUkGXzGSLvjWSaMlZFl5iAnctuMqsjqN4kKtuJu9h1LTrJqeKO0544YoXb12mKcoICvBaoTZ8gU68W7fw7NSD@zluAueEjJ0M2vMRlV/Rc0QvWOpKHmq23mGblJRafYzaV1Ed2XXUSUzi4ZJ17GL/v2lJHQEl0rpDHNyHCsLSEv2VgH2NIawwn6KDJ3RLuipztorzoHTqHg93eGQE3ljmSPsu5eItHrGCxcsPx9k5gLabF7nITdrgQB9g3oBvCI8dS9nChXxPYmt1OvGifYKcelxdmmg41rhZOO02Xu@0u7WOonPv9JApp2GHgTum2C3/1RmsViNaELUhybvSC1gM@pUX4vL2TZl/lpO3IST8gnnrYZYdu4Vthpxc6ArWDpTBtUNNAnxiejdgQKfZPIMwVf4d5AypHa9Jd8xnGI4VFfjx@Aw "4 – Try It Online")
[Answer]
# 4. ><> → JavaScript → Python 2 → Foo
# [><>](https://esolangs.org/wiki/Fish)
```
'rpp>o<(f=_=>console.log(`print(${String.fromCharCode(39,34,92,39)}rpp>o<(f=${f})()${String.fromCharCode(34,39)})`))()
```
[Try it online!](https://tio.run/##S8sszvj/X72ooMAu30YjzTbe1i45P684PydVLyc/XSOhoCgzr0RDpTq4BMhI10srys91zkgscs5PSdUwttQxNtGxNNIxttSshZugUp1Wq6mhiUOLCVixZoImUMn//wA "><> – Try It Online")
I've added the classic wrapping string literal, appending `'rpp>o<` to the start, and editing it into the center part too.
# [JavaScript (Node.js)](https://nodejs.org)
```
(f=_=>console.log(`print(${(a=String.fromCharCode)(39,34,92,39)}rpp>o<(f=${f})()${a(34,39)})`))()
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fI8023tYuOT@vOD8nVS8nP10joaAoM69EQ6VaI9E2uATITtdLK8rPdc5ILHIGatHUMLbUMTbRsTTSMbbUrC0qKLDLtwGaolKdVqupoalSnagBlAVJaSZoAgX@/wcA "JavaScript (Node.js) – Try It Online")
I've shortened the `String.fromCharCode` part as per comments on the last answer. I know this challenge isn't actually code-golf, but it makes me feel better.
# [Python 2](https://docs.python.org/2/)
```
print('"\'rpp>o<(f=_=>console.log(`print(${(a=String.fromCharCode)(39,34,92,39)}rpp>o<(f=${f})()${a(34,39)})`))()"')
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQ10pRr2ooMAu30YjzTbe1i45P684PydVLyc/XSMBokSlWiPRNrgEyE7XSyvKz3XOSCxyzk9J1dQwttQxNtGxNNIxttSshZuiUp1Wq6mhqVKdqAGUBUlpJmgCBZTUNbn@/wcA "Python 2 – Try It Online")
Added the `\'` for the start of the ><> quine.
# [Foo](https://esolangs.org/wiki/Foo)
```
"'rpp>o<(f=_=>console.log(`print(${(a=String.fromCharCode)(39,34,92,39)}rpp>o<(f=${f})()${a(34,39)})`))()"
```
[Try it online!](https://tio.run/##S8vP//9fSb2ooMAu30YjzTbe1i45P684PydVLyc/XSOhoCgzr0RDpVoj0Ta4BMhO10srys91zkgscs5PSdXUMLbUMTbRsTTSMbbUrIWbolKdVqupoalSnagBlAVJaSZoAgWUuP7/BwA "Foo – Try It Online")
[Answer]
# 6. ><> → JavaScript → brainfuck → Python 2 → Brain-Flak → Foo
Obligatory Brain-Flak answer.
# [><>](https://esolangs.org/wiki/Fish)
```
'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()
```
[Try it online!](https://tio.run/##PU7LisMwDPyVHgqV1kWHpiy0iQ2lXxD2uJSt13k0JYkdO4eC8bendlj2MtKMRtI0nXssy84aI3QBDf/hwk8cFP@abTe21Fg9XB/SXnVVI2QnzEuuIDti7mI9HTBXenS6r6nXLXwT0d3ExXkzSAO9HH4ruXmdt34KkIBpW8ELP1YBVyXB2u0jsJI5NoX/OFvfBEzGMqqYHMGDD4XAQkRM/H6j9MtxoeCYIdna1HIGR@ov9mUGRBaHn4j01N0YaTq6LG8 "><> – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org)
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()
```
[Try it online!](https://tio.run/##LU7BasMwDP2VHnqQ5s2HphS6xIbSLwg7jtG6TtKlJLFjm1Ew/vZMDr086T09Se@h/pTXrrfhYzJNuyzQiYuQcRagxVdw/XTnnTPj@Ve5MxkQiiOWtdBQ7LH0VI87LLWZvBlaPpg7fHPOr5YWw2ZUFgY13hq1eX5u45wgAzOugSe@rQKuSoa1eydgNfNsTs5aaSqKs41dwmysScXsSBFiqiRWkjDz6w/Pv7yQGvYFctfaVgXwXL9inwIgMhoeEPnD9BPRfHRZ/gE "JavaScript (Node.js) – Try It Online")
# [brainfuck](https://github.com/TryItOnline/brainfuck)
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.
```
[Try it online!](https://tio.run/##7VxbDgJBCPv3Kmv2TmpiYkz8MPH84xVmH0Bb6v/aDmUAWfD@vb0@z9/jPcaS/FmvyyKMmX28CnPOoCbzSoDLt/Q8Yi43PWNnwOUcCUKbmqB0FHn62YB7uYl3unl1czZqiN2JvIVkpbuX34xypud@baxzBllAvyxDQSRLGHhB@SBOOM1ifnW5sQY8zdwpZ0N0btS2BjWmbG9qKxBJ2uiQ62vg8jhLNibpVADtKeC1BXZxP3DgoN5GhibovwlghSfW3F4RehIpz5Dv0jPeL3RAvNpB1wjQP1RDKUXLj@deHd4SuJdUgOo5J5mo2MDYnnNivvwnIc8963d61DHQ8uHCe35PvnTYiXz@/J7jAH8pa6V7RHwryB2XrR8wvCVErFux62YGhlSXkBXTI//BgE1H/lukG7Uyz7Wj0yakUzruuEhiSK16EiVWazREu6rk2CoGH4yAPYvpiSM@n6YI8tESRC@0gF/bTEzZfpzo8qZc/BPb5/HOMBDxrjvDDQJWVLbvWz9h2D/ZS5XHOXHXfDD8rM7cZZYq/Y/FMAbtamw@jw8g77671OHXyxh/ "brainfuck – Try It Online")
# [Python 2](https://docs.python.org/2/)
```
print map(lambda x:'('+ord(x)*'()'+')','"\'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()"'),'{({}<>)<>}<>'
```
[Try it online!](https://tio.run/##bU7BasMwDP2VUgqS5uBDUwZdYkPpF4Qet7FmTtJ2JLHj@NAR/O2ZHbaxwy5P0tOT3jOf7qr77Twbe@vdqisNtmX3XpWr@xMgMG0rvNMDIAEDggTWL2CNkTrHRrwJOQ0ClTi5cH3hjdXd8Vrao65qwnRPWSEUpjvKxlD3W8qU7kfd1rzVF3zmnJ//sd1Mg8cIP@YLQQsTYemSAKxgIxv8b5zN1HiKwiKwFBV@wsnnknIZMM7nVx69RiEV7lLitjZ16XDk6jv2wSERC8tHIv6hb30Y49M1UAJ/v8E8fwE "Python 2 – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)
[Try it online!](https://tio.run/##7d1NasJQFIbhuatwZgJ1B0FwHcWBDgSxdOBUuvbbbkFqjPc7DwGHCe93fu75iXq6HS/f2/PX8dra52YYxv9f4@Zj/Zw7zXvP97xqkKKkcwbjPE/Ps9vSRAmK0rBOHVCXPdPLk6wnD4lafVomab4FEwnnZ9KRIMWIL1frFCp5jeoY61lsLp7@5yFLWbovi2RFjRmVDLCUNcQ9f6d14jbldc@VQ@QIjAixYjSxoJiIxpSrVEImkM1kLVs4XAiTab1ngkMlSTMc@GpaSvzUraGWp37uk32fECd@ccg/cfbMbxOE1PnDM95PTXUCdpy5@VJ8Y8eZ2QeIRpz4RSIPxdk7v3jEbl5LAzrSED9SlFUo7UZNrFlJD8Q3WTNls25qKZ50pmwtd8p1/B8nfj0uRfGby9FVXLG/uhY7zlr8vVP4/Tx8NuO0q7pPrW7thHhI@E8b5zBSJzOr4XAeUlD9hQpHVVLvjqPBo/aq2bF7N9TkyvxKN4GsMqP/QZLf1Hy86/E7Hdb34f4z7cZp9/e5aq1t978 "Brain-Flak – Try It Online")
I've excluded the code since it's 41568 bytes and reaches the character limit of the answer. The code is similar to the brainfuck code and is in the format:
```
[
'( ()*byte value )', Repeated for each character
] '{({}<>)<>}<>' To reverse the stack
```
# [Foo](https://esolangs.org/wiki/Foo)
```
"'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log([...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join())})()"
```
[Try it online!](https://tio.run/##PU7BasMwDL3vK0opTJqLDksZdIkNpV8Qdhxj9Zyk60gix86hYPztmR3GLk96T0/S65iXZfvorFVcQSc/pQqTBCPfZncbr9Q5Hs7f2p25aRGKI5a1NFAcsPSpHp@xNDx67lvq@QrvRHSxaXHeDNpCr4evRm/ur7swRcgg2DVwx6dVwFXJsHb7BKIWXkzxP84udBGzsU4qZkcMEGKlsFIJM798UP7lpTJwKJBca1s9gyfzF/s0A6JIwxdE@uHbmGg@un1Yll8 "Foo – Try It Online")
[Answer]
# 7. ><> → JavaScript → RAD → brainfuck → Python 2 → Brain-Flak → Foo
## ><>
```
'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()
```
[Try it online!](https://tio.run/##PY7LasMwEEV/JYtAZ6oyizgUUluCkC8wXZaSKLKduNjWy4uA0Le7kgnZnJm5c@fR9f6@LG/OGKEr6PiZi2A5KP49u366Uef0eLpLd9JNi1AcsKy5gmKPpU/xsMNS6cnroaVB38CyHyK6mDQ6b0ZpYJDjtZGbx9c22AgZTLsGHvi@CrgqGWv2kcBq5pmNr4e2oYuYjXVSMTtigBArgZVIzPXll/Itz4WCfYHkWtPKGTyp5@PHGRBZan4i0p/uJ0BmMa9dln8 "><> – Try It Online")
## JavaScript
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()
```
[Try it online!](https://tio.run/##LY7LasMwEEV/JYssZqp2FnEopLYEIV9guiylUWU7dbCtJyUg9O2uZLo5M3PnzuMuf6VXbjThZdFdv64w8C8uouWg@Htw43Kjwen58iPdJRsQqhPWLVdQHbH2OZ4OWCu9eD31NOkbWPZBRFeTR8NulgYmOX93cvd420eboIBp18EDnzYBN6Vgy54zWMs8s8kZI3STH9rHIWExtlnF4kgRYmoENiKz1NdPKrc8FwqOFZLrTS8DeFL/j58DILLcfEWkux4XQGaxrF3XPw "JavaScript (Node.js) – Try It Online")
## RAD
```
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.'
```
[Try it online!](https://tio.run/##7VzLDYNQDLt3EQ5U7FSpE3R/ia7AL47tuHewX/7kJf19vvu@rODf9l5XY0z08TrEeQQVzAsAh5f0cUQsNz9hI@AwR6LQTU9Quot8@NkCvzzFGy5e35zNGmIvIp8h2Wnu7Z7RzvTZ19YaZ5EE/MsyFkSxhMEXlG/ilNNs5teXG3vAYeKGnI3RuFnbGtKYtr2ps0AiaWNCru@Bw3G2bEzKaYG0p8DXFrjE/caBi3obCJ2wfxPQKl5Y57GK0pNYWYZ9l17Rv9gB@WoHXyFQf6iyd7VK@VWbJ5/5T7jFSK@rATVzWL5RO3NYvEfKHFbxs7lzlI6BUd/Q2n5WLZr5wsQB5zAeTQ@K@NGgdlyO/ojho0LGupW7blZgKOWEqphZSSgGHLqSMCLduJV5qR2TNimNMnEnRZJCavVTEbBakyE6VUuJrWbwxQjcs6KZONKzaYkgX62C6oUbcrdFYtr240yXS@3in9m@UXaaiYhP3WkeELCqsv3c@olD/mArdR7n5F3zkXZemB8oMH34pa3/UVnGYNw3gJ7FF5DPvYDV4bflte9/ "RAD – Try It Online")
## brainfuck
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++.
```
[Try it online!](https://tio.run/##7VxJbsNADLv3Ky78p6ZAgSJADgXyfvcL3kSRFHO3ydFujZTH39fv6@f9/dy2BfxbP5fFGBN9vA5x7kEF8wLA4SW9HxHLzU/YCDjMkSh00xOUriLvfrbALw/xhovXN2ezhtiTyEdIdpp7u2e0M733tbXGWSQB/7KMBVEsYfAF5Ys45TSb@fXlxh5wmLghZ2M0bta2hjSmbW/qKJBI2piQ63vgcJwtG5NyWiDtKfC1BU5xv3Dgot4GQifs3wS0ihfWeayi9CRWlmHfpVf0L3ZAvtrBVwjUH6rsXa1SftXmyWf@E24x0utqQM0clm/UzhwW75Eyh1X8bO4cpWNg1De0tp9Vi2a@MHHAOYxH04MifjSoHZejP2L4qJCxbuWumxUYSjmhKmZWEooBh64kjEg3bmVeasekTUqjTNxJkaSQWv1UBKzWZIhO1VJiqxl8MQL3rGgmjvRsWiLIV6ugeuGG3G2RmLb9ONPlUrv4Z7ZvlJ1mIuJTd5oHBKyqbD@3fuKQP9hKncc5edd8pJ0X5gcKTG9@aet/VJYxGPcNoGfxBeRzL2B1@PVj2/4B "brainfuck – Try It Online")
## Python 2
```
print map(lambda x:'('+ord(x)*'()'+')','"\'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()"'),'{({}<>)<>}<>'
```
[Try it online!](https://tio.run/##bU7LasMwEPyVEAK7Wxkd4lBIbRlCvsDk2JZG9SNJsS1Z8iFF6NtdybSlh15md2d3Z0Z/Tlc1bOdZm9swrXqpsZP9ey1X9ydAYMrUeKcHQAIGBAmsX8BoXagcW/EmCjcKrMRpCt8X3hrVH6/SHFXdEKZ7ykpRYbqjzIa631JWqcGqruGduuDInjnn53@MN270GOHHfiFoYSIsXRKAlcyy0f8G2rjWUzwsA0vxwjt0Pi8oLwLG@fzKo5cVRYW7lLhpdCMntLz6Dn6YkIiF5SMR/1C3AYmNFGXXQAn81YN5/gI "Python 2 – Try It Online")
## Brain-Flak
[Try it online!](https://tio.run/##7d0xbsJAEIXhnlPQ2ZbCDRAS54hSkAIJJaKgRZx9kzuEjdk3n5AoMf97M7M7swZ/3k6X6@78ffpq7X2a5@Xvr2V62z7nk/p@5mu@apCipHMGY5@r5/m2NlGCojSssw@oy54Z5UnuqUOyVp@WSZrvYCJhfyYdCVKM@HK1TqFS16iOsZ5jvXjGn4es5fRYjmRljRmVCrCWG/JevNM68TTl/66rhqgRGBFixWhiQTEZjUk09OYcWcOEampFkOtOMnEhTKZ1rw4Ou3Ga4cBX0yn5U3cPtT71c6/sN5k48ctD8YnT7F/8IDWjqBgZ/dS0T8COM7deym/sODP7ANmIE79MFKE4R@eXj9jNa2lARxriR4qyCqWzURNrLumBxCY3U07WTS3lk86U12qnWif@ceLX41IUv7kcXeUV/@1rseOsxT86hf/Pw@dknHZVz1Oru52QDwnPBbIOI7Uycw2H9ZCC9l@ocFQlde84Gjz2XjU7dveGmlyZX@kmkFVm9BwkqzLH6Zen6@t/22X62N7n@2N/WPaH3/dNa213/AE "Brain-Flak – Try It Online")
## Foo
```
"'rpp>o<(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:${q}(${q}+ord(x)*${q}()${q}+${q})${q},${q+Q+s+q}rpp>o<(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()"
```
[Try it online!](https://tio.run/##PY7LasMwEEX3/YoQAp2pghZ1KKS2BCFfYLoMIVFlO02xPXp4ERD6dlcyoZszM3fuPDqieV6/OmMkVdCJi5DBCtDia3L38cY7R8PxR7kjNS1CsceyFhqKHZY@xf07lppGT33Le7qBZSfO@dWk0Wk1KAO9Gr4btXp8boKNkMHINfDAt0XARclYsm0Cq5lnNv4/tAldxGysk4rZEQOEWEmsZGKur2eeb3khNewK5K41rZrAc/18/DABIkvND0T@S/cRkFnMa9cv8/wH "Foo – Try It Online")
[Answer]
# 8. ><> → Wumpus → JavaScript → RAD → brainfuck → Python 2 → Brain-Flak → Foo
Adding in another 2D language, Wumpus.
# [><>](https://esolangs.org/wiki/Fish)
```
'rppp:1->o#13&;l2:6-&o@(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:(ord(x)*${q}()${q},),${q+Q+s+q}rppp:1->o#13&;l2:6-&o@${Q+s}n${Q}(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()
```
[Try it online!](https://tio.run/##bY/NasMwEIRfJRCT7FaJIHEIxI5ES57A9FhKo8h24mJbfz4EhJ7dlUqPvcywDN/ubNu5xzyvrda62G25Wu7yVdnvi@N2pV6hZV@Me8NAsvfJduOdtlYNl4ewF1U3CPkJy4pJyA9YuuinPZZSjU71De3VHQz5oJRedUSnxSA09GK41WLxLEDZGp74knkTAJNucBONVMQRE/7vk/mYhjFaiNUy3wZMbBWBXzh48OHM8cyjpvn6SdNVx7iEQ47UNroREzgq/154mwCRxPCISL9VNwISg2ntPP8A "><> – Try It Online")
This now prints an extra `"` before the Wumpus code.
# [Wumpus](https://github.com/m-ender/wumpus)
```
"#13&;l2:6-&o@(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:(ord(x)*${q}()${q},),${q+Q+s+q}rppp:1->o#13&;l2:6-&o@${Q+s}n${Q}(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()
```
[Try it online!](https://tio.run/##VY/dasJAEIVfRWyQma4uaEQwcZcWnyD0spS6bhKrJNm/SIVlnz3dLb3pzTkMh2/mzPe913c3TfOndb4ou02xWy3UC7Tsk3FvGEj2NtrrcKGtVf3xS9ijqhuEfI9lxSTkWyxd9P0GS6kGp7qGduoChrxTSk86ouOsFxo60Z9rMXsUoGwND3zOvAmASZe4jEYq4ogJVmtdrFdc/euT@ZiGIVqI1TLfBkxsFYFfOHjw4cDxwKOm@fRB01XHuIRtjtQ2uhEjOCr/XngdAZHEcIdIb@o6ABKDae00/QA "Wumpus – Try It Online")
Similar to the `><>` quine, this wraps a string literal around the code and printsonly the javascript section
# [JavaScript (Node.js)](https://nodejs.org)
```
(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:(ord(x)*${q}()${q},),${q+Q+s+q}rppp:1->o#13&;l2:6-&o@${Q+s}n${Q}(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()
```
[Try it online!](https://tio.run/##LY/vasIwFMVfRbDIvYsNaEWwNcHhE5R9HGNmaesqbZImYQghz96lY1/O4XLu7/55iB/hpO2Nz5Vu2nmGjn0yHiYGkr1526s77awer9/CXlMDQnHCqmYSigNWLvlpj5XUyumhpYO@w0TeKaU3k1C/GoWBQYxfjVg9S9C2gSe@ZGGKgItucZuM1MSRKVpjTLnLuV7vik017MtjvtGXLKQ0qmQxnZaFLuLC1gn4g2OAEM8czzzpUt8@6LLVMS7hUCC1rWmFB0fl/wuvHhBJCo@I9KF7BUgmXMbO8y8 "JavaScript (Node.js) – Try It Online")
# [RAD](https://bitbucket.org/zacharyjtaylor/rad)
[Try it online!](https://tio.run/##7VzLrcMwDLt3kR7y0J0KdIK3P5CukE9JkxR7bkJ9aFmS5fy/P/v@3Mi/19@2BWOy1VthziOoZLkIcHxLH0fkypZnbAYcRyUJ36wJSneRVZdb9KYpbPQryGeEPPxfiI0A6EBb/VheLJdAps1PY2YiXnj25CN37aG53@Htdu6hW1bSz@DJFEfy3DB/M9rViHh62eNNHLiYi@Vbl8SvAaeZm6KbIrlVG6DWmLFd7LNAJttGUFYvBseTOfIIw84LVECSWpCeHLSUZinB8Yl6TSDreGOflxVQTaKYEX@c6Li@1AH1codcI0gXqupdLah8aHrq0X/CaWp7XQtQO7GZG7U7samrUic2E5OkTmyOndjsGbf/nltPW3saGAPKDc2egE5PwlVCq9WdXyHOROww/DXADsNT0ToMv9K7MzOwsAzHH740TCn3Vxqk5aRh/GjTqWWxMSkbd5rCOGyteS4idh9sBJ3qpcbWMHgwgvYsbie6/DhtEeTRLkBfaBJftkzM2NOv0Mu7cfEv7D5X74wLCT71zviAgIXa7efmTxr2J7M0eQpd9xqV9eKlrQMHSX/8UsR3ehd@1HhqDeDHeIDwPReIUv71fOz7Fw "RAD – Try It Online")
I'm excluding very long sections of code from the chain, so as to not fill up the answer.
# [brainfuck](https://github.com/TryItOnline/brainfuck)
[Try it online!](https://tio.run/##7VxbTsRADPvnKkV7J0BCQkh8IHH@coU@1h7b8X5v6zw8mSST6fvv29fP59/H975v5N/jdduCMdnqrTDnEVSyXAQ4vqWPI3JlyzM2A46jkoRv1gSlu8iqyy160xQ2@hXkM0Ie/i/ERgB0oK2eLC@WSyDT5qcxMxEvPHvykbv20Nzv8HY799AtK@ln8GSKI3lumL8Z7WpEPL3s8SYOXMzF8q1L4teA08xN0U2R3KoNUGvM2C72WSCTbSMoqxeD48kceYRh5wUqIEktSE8OWkqzlOD4RL0mkHW8sc/LCqgmUcyIP050XF/qgHq5Q64RpAtV9a4WVD40PfXoP@E0tb2uBaid2MyN2p3Y1FWpE5uJSVInNsdObPaM23/PraetPQ2MAeWGZk9ApyfhKqHV6s6vEGcidhj@GmCH4aloHYZf6d2ZGVhYhuMPXxqmlPsrDdJy0jB@tOnUstiYlI07TWEcttY8FxG7DzaCTvVSY2sYPBhBexa3E11@nLYI8mgXoC80iS9bJmbs6Vfo5d24@Bd2n6t3xoUEn3pnfEDAQu32c/MnDfuTWZo8ha57jcp68dLWgYOkT34p4ju9Cz9qPLUG8GM8QPieC0Qp/3jZ938 "brainfuck – Try It Online")
# [Python 2](https://docs.python.org/2/)
```
print map(lambda x:(ord(x)*'()',),'"\'rppp:1->o#13&;l2:6-&o@"\n"(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:(ord(x)*${q}()${q},),${q+Q+s+q}rppp:1->o#13&;l2:6-&o@${Q+s}n${Q}(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()"'),'{({}<>)<>}<>'
```
[Try it online!](https://tio.run/##fVDLasMwEPyV4Jpot0oEiUMgdmRa8gWmxyY0rh9Jii3Jsg8pQt/urksPPZReZliGmZ1d8zlctVqPo7E3Ncza3ECTt@9lPrvHoG0Jd3xkgGyBCxYcmTXGxKtlqh9W0Txp1vF2OddPwVEFUMs3mbpOQiFfBgq7iNrq9nDN7UGXFUK0wySTBUQbTHri3RqTQqteN5Vo9AU6/iqEOP/TI3SdB5yQ2hDxjPe88393Ch2pXhF5qha62uPkzcjwbfYOnN@nuE8Jp/l8EtPWXqYFbCIUtjJVPkAvip8TngdA5CRuEcWHvilA3uEUGzD6zu88No5f "Python 2 – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)
[Try it online!](https://tio.run/##7d09bgIxEMXxPqegY1eCGyCknCNKQYpIKBEFLcrZN5wgTfbDnvcTEqW9/zczz17bmI/75Xo7fn5fvqbpbdgP4/8/@8N42M3T1MKNtvkJQYUJs6@uF@@ogVyJSNdZIeuk38KdbZpaxfN6RbwEp@/b83l4l4/xR1Pr9CLn2kIqoSkVoxYvguGrZnqpALIjtQu3MGpADEsirgDlHQUqSIDV1S6Dxd08DMjQmC0GVGGZZLNo9xaVYsVj@YoTbBoQ9S/rqV1406XCSSJeAgakAQ4kPPtbFARpjky/iirWcFVjg5K38QkMYgKuMz5ATM@pBgRgeKzUUPSEqgFsYx9IvkultHMMMzftF@72IUS6uoGoclUu0onTBWaixhxdoAIlqUgAqDBh2hFovCM3X3YI6Tr5HlLL2RZOn@L5PLzbx7DGZnXI6pCchyhlWKRIJeha7XojBiU/xbSiRzIKMxneAjTBRHmeIgBKAK@@EooApY9mkFZ1SQHzXOUENFOA7jFcSAkwzZW8Ztp7FfCSRVHjD7kMylDFTtyAGBppaDomDYBAzdHdHaSAVEP/E7E@FwjMo7KXtRRFot@aWAHj5MbolMR2AseP82Zv@NnU@@4xPH5O5/F0fn6/TNN0fP0F "Brain-Flak – Try It Online")
# [Foo](https://esolangs.org/wiki/Foo)
```
"'rppp:1->o#13&;l2:6-&o@"
"(f=_=>{q=(c=String.fromCharCode)(39);Q=c(34);s=c(92);console.log(q+[...`print map(lambda x:(ord(x)*${q}()${q},),${q+Q+s+q}rppp:1->o#13&;l2:6-&o@${Q+s}n${Q}(f=${f})()${Q+q}),${q}{({}<>)<>}<>${q}`].map(s=>c(43).repeat(s.charCodeAt())+c(46)).join()+q)})()"
```
[Try it online!](https://tio.run/##bY/BasMwEETv@YrgmnS3SgSJQyB2JFryBabHUhpXttMU2ytLPgSEvt2VSo@9zLAMb3e2JZrn5NForfPtRtLDNlsV3S4/bFb0nCwSaMWHkG4UoMTrZG7DlbeG@vNXZc5UNwjZEYtSKMj2WNjgxx0WigZLXcM7usLI3jjnFx3QadlXGrqq/6yr5T0HMjXc8Sl1oweMusZ1MFYyy0b/f6XUhdQPwXyolrrWY2TLAPzC3oHzJ4knGTTOl3cer1ohFewz5KbRTTWB5ervhZcJEFkID4j8m24DIBsxrk0W8/wD "Foo – Try It Online")
This was actually the most annoying part of the code. Foo only supports string literals of 254 length for some reason, so I had to golf a bit and split up the Javascript from the 2D code to keep it short. The next person will probably have to split up the Javascript.
] |
[Question]
[
*There have been a lot of prime-/prime factorization-related challenges recently, so I thought it might be interesting to go the other way.*
Given:
* a positive integer `n`, and
* a non-empty list of positive integers `f`
write a full program or a function to find the smallest integer `i` such that `i >= n` and `i` is a product of nonnegative, integer powers of elements in `f`.
## Examples:
* Suppose `n = 11, f = [2, 3, 5]`.
The first few products are:
```
1 = 2^0 * 3^0 * 5^0
2 = 2^1 * 3^0 * 5^0
3 = 2^0 * 3^1 * 5^0
5 = 2^0 * 3^0 * 5^1
4 = 2^2 * 3^0 * 5^0
6 = 2^1 * 3^1 * 5^0
10 = 2^1 * 3^0 * 5^1
9 = 2^0 * 3^2 * 5^0
15 = 2^0 * 3^1 * 5^1
25 = 2^0 * 3^0 * 5^2
8 = 2^3 * 3^0 * 5^0
12 = 2^2 * 3^1 * 5^0 => smallest greater than (or equal to) 11, so we output it.
20 = 2^2 * 3^0 * 5^1
18 = 2^1 * 3^2 * 5^0
30 = 2^1 * 3^1 * 5^1
50 = 2^1 * 3^0 * 5^2
27 = 2^0 * 3^3 * 5^0
45 = 2^0 * 3^2 * 5^1
75 = 2^0 * 3^1 * 5^2
125 = 2^0 * 3^0 * 5^3
```
* Suppose `n=14, f=[9, 10, 7]`.
Again, the first few products:
```
1 = 7^0 * 9^0 * 10^0
7 = 7^1 * 9^0 * 10^0
9 = 7^0 * 9^1 * 10^0
10 = 7^0 * 9^0 * 10^1
49 = 7^2 * 9^0 * 10^0 => smallest greater than (or equal to) 14, so we output it.
63 = 7^1 * 9^1 * 10^0
70 = 7^1 * 9^0 * 10^1
81 = 7^0 * 9^2 * 10^0
90 = 7^0 * 9^1 * 10^1
100 = 7^0 * 9^0 * 10^2
```
## Test cases:
```
n, f -> output
10, [2, 3, 5] -> 10
17, [3, 7] -> 21
61, [3,5,2,7] -> 63
23, [2] -> 32
23, [3] -> 27
23, [2, 3] -> 24
31, [3] -> 81
93, [2,2,3] -> 96
91, [2,4,6] -> 96
1, [2,3,5,7,11,13,17,19] -> 1
151, [20,9,11] -> 180
11616, [23,32] -> 12167
11616, [23,32,2,3] -> 11664 = 2^4 * 3^6
5050, [3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210] -> 5103 = 3^6 * 7
12532159, [57, 34, 12, 21] -> 14183424 = 12^5 * 57
```
## Rules
* You may assume that `f` will contain at least one element, and that all elements of `f` will be greater than 1.
* You may optionally assume that `f` is sorted in decreasing/increasing order if you would like (but please specify).
* You may optionally take the number of elements of `f` if you would like.
* Output as a string is allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes in each language wins!
* Default I/O rules apply, and standard loopholes are forbidden.
* Explanations are encouraged.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ḟṠ€ȯmΠṖṘ
```
Extremely slow.
[Try it online!](https://tio.run/##ASQA2/9odXNr///huJ/huaDigqzIr23OoOG5luG5mP///1szLDRd/zU "Husk – Try It Online")
## Explanation
```
ḟṠ€ȯmΠṖṘ Implicit inputs, say L=[3,4] and n=5.
ḟ Find the lowest integer k≥n that satisfies:
Ṙ Replicate L by k: [3,3,3,3,3,4,4,4,4,4]
Ṗ Powerset: [[],[3],[4],..,[3,3,3,3,3,4,4,4,4,4]]
mΠ Product of each: [1,3,4,..,248832]
Ṡ€ȯ k is in this list.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~68~~ ~~65~~ ~~62~~ 61 bytes
```
If[#^#2<=1,1~Max~-Log@#2,Min[#0[#,#2-1,##4],#0[#/#3,##2]#3]]&
```
[Try it online!](https://tio.run/##fYyxCsIwFEV3f@OB0y32vTSIaKGrYEHn8IQgrWZoBEnBqb8e4yw43OFwDnfy6TFMPoWbz@Mc23wcHV1JDi2Dl96/l@r0vHck6EN0VDsCScUgahRf3JApIEpGdZ3PrxCTu8xhSF25c1zDQMqs6n71Y/mvFWuE7Q4N7BamAQuES5k/ "Wolfram Language (Mathematica) – Try It Online")
## How it works
Takes input as `[n,k,f1,f2,f3,...,fk]` (e.g., `[11,3,2,3,5]`): the first value is the target `n`, the second is the number of factors, and all the frctors follow.
The other number-theory challenges recently all folded to fancy built-ins (at the very least, they used `FactorInteger`) so I thought I'd try something that used only basic tools. This solution basically says that to write `n` as a product of the factors, we either use the first factor `f1` (and recurse on `n/f1`, then multiply by `f1`) or don't (and recurse on a shorter list of factors), then take the min.
The recursion bottoms out when the target is less than 1 or when the number of factors is 0, which we check for with `#^#2<=1` at once, and then generate 1 in the first case and `Infinity` in the latter with `1~Max~-Log@#2`.
The function gives a whole bunch of warnings (but still works) unless you run it with `Quiet`, because it eventually recurses to cases where `#3` doesn't exist, making the unused second branch of `If` sad.
---
*-3 bytes: taking the number of factors as input.*
*-3 bytes thanks to @ngenisis: using `∞`.*
*-1 byte, and no `∞` ambiguity: the `#^#2` check.*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ ~~88~~ 84 bytes
```
f=lambda n,l:n<2or any(n%x<1and f(n/x,l)for x in l)
g=lambda n,l:n*f(n,l)or g(n+1,l)
```
[Try it online!](https://tio.run/##ZZHRbsIwDEXf@xV@mYDtTquTJm0R7Ee6PhQNGFIJqBQJvr6zUwRDe4vPteNr@3jtfw7BDMNm2Tb71XdDAe08LMyhoyZcp@HlsuAmfNNmGj4uaGcbES60C9TOku1TzaukSILo22l4Y3kOmhzO@9W6Q7s79ejWp3PbS/VXUlWcgioDsiBXg9MaScW5MAF5DTKsxHMkDgYKvVVorJZKaM09tFqSP1QRlWRKLN8SivhnOSYYKCp9RBxRBn9HDAHaOQcz2ELMcSly/INdrEhRiqqwGAdgz14FC/VGbNjn/4Rba2E@@nOpS@OYXvYAlmEZpoD1yBycg/fIC4hHTh1YmrJI7NSSsDKVfOlOjtO4HjbOGnalfOlkoTZTH@NCiTMubCZrqecJHbtd6Kn6c6Iak/fPCeSCDzYDPcfL5XjI4Rc "Python 2 – Try It Online")
The function `f` checks recursively if `n` is a product of powers of elements in `l`, `g` is just a wrapper to control the iteration
[Answer]
# Python, 55 bytes
```
f=lambda n,l,x=1:min(f(n,l,x*e)for e in l)if x<n else x
```
[Try it online!](https://tio.run/##ZZFNbsJADIX3nMI7oHqVxjOZSYKaXiTNAtREjRQGFIJET5/aEwStuvT3/PNsn7@nr1O089xVw/54@NxTxIBbxbtjHzfdJkUv7bY7jdRSH2nY9h3d3iK1w6Wl26xCvB4P7Yihv0wY28t1mCTzY1XXbEC1BTmQb8CmwarmXJiAvAFZVhI4EQ8LhcEptE5LJXT2ETotyZ@qiEoyJY7vCUXqWS4JForKkBAnlCE8EEOATs7BDHYQc1yKnHqwTxUGpagKi2UBDhxUcFBvxJZD/k@4jxYWkj9vvElrBrkDWJZl2AIuIPPwHiEgLyAe2XiwDGWR2KslYaWRfJlOnk06D1vvLPtSWno5qMvUx3JQ4owLl8lZmt2KzmMfJ6p/vajB@vV9Dfntk21Bf@OqWh45/wA)
Shamelessly copied [Rod](https://codegolf.stackexchange.com/users/47120/rod)'s footer script for testing
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L⁹ṗ’⁸*P€ḟ⁹Ḷ¤Ṃ
```
A dyadic link taking the list, `f`, on the left and the number, `n`, on the right which yields a number.
**[Try it online!](https://tio.run/##y0rNyan8/9/nUePOhzunP2qY@ahxh1bAo6Y1D3fMB4nt2HZoycOdTf///4820jGO/W9kDAA "Jelly – Try It Online")** Golfily inefficient - will time out for inputs with higher `n` and/or longer `f`.
### How?
We know that the powers of the individual (strictly positive) factors will never need to exceed `n-1`
...so let's just inspect all the possible ways!
```
L⁹ṗ’⁸*P€ḟ⁹Ḷ¤Ṃ - Link: list, f; number, n
⁹ - chain's right argument, n
L - length of f
ṗ - Cartesian power ...e.g.: len(f)=2; n=3 -> [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
’ - decrement (vectorises)
⁸ - chain's left argument, f
* - exponentiate (vectorises) - that is [f1^a, f2^b, ...] for each [a, b, ...] in the list formed from the Cartesian power
P€ - product for €ach - that is f1^a * f2^b * ... for each [a, b, ...] in the list formed from the Cartesian power
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument, n
Ḷ - lowered range -> [0,1,2,3,...,n-1]
ḟ - filter discard - that is remove values less than n
Ṃ - minimum
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 76 bytes
```
\d+
$*
1+;
$&$&
{+`;(1+)(\1)*(?=;.*\b\1\b)
;1$#2$*1
}`(1+);11+;
1$1;1$1;
\G1
```
[Try it online!](https://tio.run/##JY29TgQxDIR7vwbhtD8jlInP2YssRHkvkWI5QUFDgegQz744XGH789gef71/f3y@Ho/TdT/62yppEa4u6ZRO8rPuPnGdp855mV6e/Wnpt85@m8WZHkpaKL/72HCOIyb6COlXHgezFyhMuLlik8oohhJY1MtI@k9Q0ZhJGzy6xoAzqvDugA0kqGBAE1roGS1EISurF4XeTy1bjjcVzGA8I8oFWnE2mKFWbBe08MoGhgdjRBvGobUc@/kP "Retina – Try It Online") Link excludes the slowest test cases, but it's still a little slow, so try not to hammer @Dennis's server.
[Answer]
# Pyth - 10 bytes
Runs out of memory very quickly.
```
f}T*My*QTE
```
[Try it online here](http://pyth.herokuapp.com/?code=f%7DT%2aMy%2aQTE&input=%5B2%2C+5%5D%0A3&debug=0).
Reasonable answer for 16 bytes: `fsm.A}RQ*Md./PTE`
[Answer]
# Mathematica, 85 bytes
```
Min@Select[Flatten[1##&@@(s^#)&/@Tuples[0~Range~⌈Log[Min[s=#],d=#2]⌉,#3]],#>=d&]&
```
**Input**
>
> [{list f},n,number of elements of f]
>
> [{57, 34, 12, 21}, 12532159, 4]
>
>
>
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
_k e!øV}aU
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=X2sgZSH4Vn1hVQ==&input=MTE2MTYsIFsyMywzMl0=)
Doesn't work on the last test case due to an iteration limit designed to keep the interpreter from running forever (didn't help much here though, as it froze my browser for an hour...)
### Explanation
```
_k e!øV}aU Implicit: U = input integer, V = array of factors
_ }aU Starting at U, find the next integer Z where
k the factors of Z
e are such that every factor
!øV is contained in V (e!øV -> eX{VøX}, where VøX means "V contains X").
Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
xŒPP€ḟḶ}Ṃ
```
**O(2n•length(f))** runtime and memory usage make this a theoretical solution.
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//eMWSUFDigqzhuJ/huLZ94bmC////WzMsIDVd/zY "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
This is a port of [KSab's excellent Python answer](https://codegolf.stackexchange.com/a/144833/47581). Thanks to Laikoni for their help in debugging and golfing this answer in the PPCG Haskell chatroom, [Of Monads and Men](https://chat.stackexchange.com/rooms/66515/of-monads-and-men). Golfing suggestions welcome! [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0PZUJNLI0e5QjOvpsImzzY3My8ztzQ3GiikUaGVqgkUTrXRzYmtMbQzsK34n5uYmadgq1BQlJlXoqCikKYQbaRjrGMaq2Bo8P9fclpOYnrxf93kggIA "Haskell – Try It Online")
```
(#1)
(l#x)n|x<n=minimum[(l#(x*e))n|e<-l]|1>0=x
```
[Answer]
## Mathematica, 73 bytes
```
1±_=1>0;n_±f_:=Or@@(#∣n&&n/#±f&/@f);n_·f_:=NestWhile[#+1&,n,!#±f&]
```
Essentially a port of [Rod](https://codegolf.stackexchange.com/users/47120/rod)'s Python [answer](https://codegolf.stackexchange.com/a/144783/61980). Defines two binary operators `±` and `·`. `n±f` returns `True` if `n` is a product of elements of `f` and `False` otherwise. `n·f` gives the smallest integer `i`. If someone can figure out a way to eliminate the divisibility test, I could save 10 bytes by using the ISO 8859-1 encoding.
# Explanation
```
1±_=1>0; (* If the first argument is 1, ± gives True. *)
n_±f_:=Or@@(#∣n&&n/#±f&/@f); (* Recursively defines ±. *)
(* For each element of f, check to see if it divides n. *)
(* For each element # that does, check if n/# is a product of elements of f. *)
n_·f_:=NestWhile[#+1&,n,!#±f&] (* Starting with n, keep incrementing until we find an i that satisfies i±f. *)
```
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
function(n,f)min((y=(x=outer(f,0:n,"^"))%o%x)[y>=n])
```
[Try it online!](https://tio.run/##K/qfrmCj@z@tNC@5JDM/TyNPJ00zNzNPQ6PSVqPCNr@0JLVII03HwCpPRylOSVNTNV@1QjO60s42L1bzf7qGoaVOsoaxjomOqabmfwA "R – Try It Online")
It's been 3 weeks, so I thought I'd finally post my own solution. This is a brute force approach.
There is, however, a builtin:
# [R](https://www.r-project.org/), 5 bytes
```
nextn
```
[Try it online!](https://tio.run/##K/qfrmCj@z8vtaIk73@6hqWhTrKGkY6ZpuZ/AA "R – Try It Online")
From the R docs:
>
> `nextn` returns the smallest integer, greater than or equal to `n`, which can be obtained as a product of powers of the values contained in `factors`. `nextn` is intended to be used to find a suitable length to zero-pad the argument of `fft` to so that the transform is computed quickly. The default value for `factors` ensures this.
>
>
>
Some testing revealed a bug in the implementation, however, as the TIO link above shows.
`nextn(91,c(2,6))` should return 96, but returns 128 instead. This obviously only occurs when `factors` are not all relatively prime with one another. Indeed, the [C code underlying it](https://github.com/wch/r-source/blob/af7f52f70101960861e5d995d3a4bec010bc89e6/src/library/stats/src/fourier.c) reveals that `nextn` greedily tries to divide each `factor` in turn until `1` is reached:
```
static Rboolean ok_n(int n, int *f, int nf)
{
int i;
for (i = 0; i < nf; i++) {
while(n % f[i] == 0) {
if ((n = n / f[i]) == 1)
return TRUE;
}
}
return n == 1;
}
```
static int nextn0(int n, int \*f, int nf)
{
while(!ok\_n(n, f, nf))
n++;
return n;
}
This can be solved by taking input in decreasing order.
[Answer]
# JavaScript (ES6), ~~53~~ 50 bytes
*Saved 3 bytes thanks to @DanielIndie*
Takes input in currying syntax `(n)(a)`.
```
n=>m=a=>(g=k=>k<n?a.map(x=>g(k*x)):k>m?0:m=k)(1)|m
```
### Test cases
```
let f =
n=>m=a=>(g=k=>k<n?a.map(x=>g(k*x)):k>m?0:m=k)(1)|m
console.log(f(10)([2,3,5])) // -> 10
console.log(f(17)([3,7])) // -> 21
console.log(f(61)([3,5,2,7])) // -> 63
console.log(f(23)([2])) // -> 32
console.log(f(23)([3])) // -> 27
console.log(f(23)([2, 3])) // -> 24
console.log(f(31)([3])) // -> 81
console.log(f(93)([2,2,3])) // -> 96
console.log(f(91)([2,4,6])) // -> 96
console.log(f(1,)([2,3,5,7,11,13,17,19])) // -> 1
console.log(f(151)([20,9,11])) // -> 180
console.log(f(11616)([23,32])) // -> 12167
console.log(f(11616)([23,32,2,3])) // -> 11664 = 2^4 * 3^6
console.log(f(5050)([3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210])) // -> 5103 = 3^6 * 7
console.log(f(12532159)([57,34,12,21])) // -> 14183424 = 12^5 * 57
```
### How?
```
n => a => ( // given n and a
g = k => // g = recursive function taking k
k < n ? // if k is less than n:
a.map(x => g(k * x)) // recursive calls to g with x * k for each x in a
: // else:
k > m ? // if k is greater than m and m is not set to NaN:
0 // ignore this result
: // else:
m = k // update m to k
)( // initial call to g with:
1, // k = 1
m = +a // m = either NaN or the single integer contained in a
) | m // return m
```
] |
[Question]
[
It's 2050, and people have decided to write numbers in a new way. They want less to memorize, and number to be able to be written quicker.
For every place value(ones, tens, hundreds, etc.) the number is written with the number in that place, a hyphen, and the place value name. "zero" and it's place value does not need to be written.
The number 0 and negative numbers do not need to be handled, so don't worry about those.
#### Input:
The input will be a positive integer up to 3 digits.
#### Output:
The output should be a string that looks like something below.
Test cases:
```
56 => five-ten six
11 => ten one
72 => seven-ten two
478 => four-hundred seven-ten eight
754 => seven-hundred five-ten four
750 => seven-hundred five-ten
507 => five-hundred seven
```
[This question](https://codegolf.stackexchange.com/questions/155995/convert-a-number-to-korean) would not be a dupe because that one has a bit more requirements.
"One" does not need to be printed unless it is in the ones place value.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so normal golfing rules apply.
Shortest answer wins!
Good luck!
###### Imagine if numbers are actually written like this in the future...
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 100 bytes
```
$a="{,{one,two,three,four,five,six,seven,eight,nine}";$_=(<"$a-hundred }$a-ten }$a}">)[$_];s/one-//g
```
[Try it online!](https://tio.run/##FYzLCoMwEEX38xU2zaKFEU0wTcXaHylFBMcHSJQYbUH89jRdHM7hLu5MdlT@fJqDo3gePa9LtuM@GUL3mdD1lgjbabXYDhvhMnxxoY0M0tD1Ds1g6GAFr8rLg/E67lfTWGqiI7Qj8/fBntcXr97FkoTXOEk679UNhAAtIdN30CoLpKBSDSLsAqSUkOf5Dw "Perl 5 – Try It Online")
Readable version:
```
#!perl -pl
$a="{,{one,two,three,four,five,six,seven,eight,nine}";
$_=(<"$a-hundred }$a-ten }$a}">)[$_];
s/one-//g
```
The idea here is simple: instead of trying to generate the number on the fly, generate a list of all 2050 numbers using a glob expression (which is much easier) and then index into that list. If $n is the list of numbers, we construct the glob `{,{$n}-hundred }{,{$n}-ten }{,{$n}}`. The only problem is that this glob expression will generate `one-ten` and `one-hundred`, which we can simply strip at the end with `s/one-//g`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 25 bytes
```
ẏṘ↵Z'h;ƛ∆ċ1∆ċ-';\-jȧ1∆ċ$∨
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwi4bqP4bmY4oa1WidoO8ab4oiGxIsx4oiGxIstJztcXC1qyKcx4oiGxIsk4oioIiwiIiwiNTYiXQ==)
[or try a test suite.](https://vyxal.pythonanywhere.com/#WyJhIiwixpsiLCLhuo/huZjihrVaJ2g7xpviiIbEizHiiIbEiy0nO1xcLWrIpzHiiIbEiyTiiKgiLCI7XFwgajvCtmoiLCI1NlxuMTFcbjcyXG40Nzhcbjc1NFxuNzUwXG41MDciXQ==)
Thank goodness for built-in number to word support
## Explained
```
ẏṘ↵Z'h;ƛ∆ċ1∆ċ-';\-jȧ1∆ċ$∨ # example input → 701
ẏṘ # range(len(input) - 1, -1, -1) → [2, 1, 0]
↵ # 10 to the power of each item in that range → [100, 10, 1]
Z # zip that with the digits of the input → [[7, 100], [0, 10], [1, 1]]
'h; # keep only items where the digit of the input isn't 0 → [[7, 100], [1, 1]]
ƛ # to each item in the remaining [digit, power10] list:
∆ċ # convert both digit and power10 to words → [["seven", "one hundred"], ["one", "one"]]
1∆ċ- # remove any occurances of the word "one" from each → [["seven", " hundred"], ["", ""]]
'; # and remove any empty strings - this makes it so that you have singleton lists for hundreds and tens and an empty list for ones if one is present → [["seven", " hundred"], []]
\-j # join the result of that on "-" → ["seven- hundred", ""]
ȧ # remove whitespace → ["seven-hundred", ""]
1∆ċ$∨ # get the first truthy item from that and "one" - this works because an empty string means that we want the word "one" → ["seven-hundred", "one"]
# The -S joins the result on spaces → "seven-hundred one"
```
[Answer]
# [Python](https://www.python.org) + [num2words](https://pypi.org/project/num2words/), ~~162~~ ~~138~~ 137 bytes
```
lambda N:' '.join([((num2words(n)+'-'*(w>''),'')[n=='1'<w]+w)for n,w in zip('%3s'%N,['hundred','ten',''])if'0'<n])
from num2words import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Vc5fCoJAEAbw906xLzE7aaGlGaEdoQuYQaFLGzkr28pSN-gMvQhRd-o2Cf3BHmaGH9_DN9dHdTI7Rc1NJKt7bcRw9rwcNuU237DlHBiM9koSTzmnuhxbpfMjJ3RgCANuFwDotpNSkoAPsc0ci0JpRq5lkthZVhz6kyP0l24Ku5pyXeTggimo3ZChFOBBTBn2hFYl-1UwWVZKm8HnoXWlJRkueDhF7H3h-x1E4w6CaNaNwuBPXkehFyG-W5rmfV8)
Requires the package `num2words` to be installed, so won't run in the ATO link.
-24 bytes thans to **Jonathan Allan**
-1 byte, replaced `'%03s'%N` with `'%3s'%N`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 74 bytes
```
⪫Φ⮌E⮌S⪫Φ⟦§⪪”↶⌈↶?#λ<∕CSG∨⮌№¤"~^hφ﹪▶U⊕hU⦄w↷” ∧∨⊖ι¬κIι§⪪”↶↧WaKπ⁵1✂” ∧Iικ⟧λ-ι
```
[Try it online!](https://tio.run/##XY3BisJAEER/pZlTB@JtwQVPsrKg4O6iR/EQMq1pHHtCpxP9@3Eisqi34lH1qm4qrWMVUvpTFsNVZMFvDkaKGxpIO8J11f7npbS9bS13j1gUJTz3d3NbiqcrbtvAhg6iENglgjVKBIfYKxx4IOj4Cl0WChAfGwNhIVeCA5eNc/H4q7igWulMYuSRM/6Jhqfx8avqLJMxvv9ZNja9eCX/ontMSsiCfQkhJzdxd8VIx2IxS@lj@pkmQ7gB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input as a string
⮌ Reversed
E Map over digits
⟦ ⟧ Tuple of
”...” Compressed digits string
⪪ Split on spaces
§ Indexed by
ι Current digit
⊖ Decremented
∨ Logical Or
κ Current power of 10
¬ Is zero
∧ Logical And
ι Current digit
I Cast to integer
”...” Compressed places string
⪪ Split on spaces
§ Indexed by
ι Current digit
I Cast to integer
∧ Logical And
κ Current power of 10
Φ Filtered where
λ String is not empty
⪫ Joined with
- Literal string `-`
⮌ Reversed
Φ Filtered where
ι String is not empty
⪫ Joined with spaces
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~193~~ ~~171~~ 169 bytes
* -2 thanks to ceilingcat
Recursively divides the input number, looking up each digit (except for `1` in non-ones position and `0`) and and appending the suffix (except for ones position.)
```
g(v,s,i){v&&g(v/10,s?"hundred":"ten"),(i=v%10)&&printf("%3$.5s%2$s%s "+(i<2&&s)*10,s?:"",!s+"-","one\0 two\0 threefour\0five\0six\0 seveneightnine"+~-i*5);}f(v){g(v,0);}
```
[Try it online!](https://tio.run/##PZBRb4MgFIXf@yvubqqBihu6uq51bj@k3UOjYEk2bITSJcb99DmwSV9Ozvkul0Oo07aup6kljhmm6ODi2PunjDPzgaeLbnrR4A6t0EgZUZWLMk7j@NwrbSXB6Hn5WJgoX5rIACZEveVxbOhq3t8hsgeTYIoMOy0OHOy1C3rqhZDdpT9wqZznRv14bIQTWqj2ZLXSApPfVK0KWo6SODqEB3IfJt8L30elietUQ2FYAARkhbFm/1kNULwwyDIGm5zBevPqTbEOwhkUfOMlDLObeJZx77ZbBnkI/ri3nnAYGaxsufD3y64ntpobysDAJsmtGeD@EQ1U74Bhh5bzRJK7PV@sIYhzGhfj9FfLr2NrpvT6Dw "C (gcc) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.text.english math.text.utils`, ~~138~~ ~~136~~ 126 bytes
```
[ 1 digit-groups [ 10^ [ number>text ] bi@ "-"glue R/ one[- ]|-one$|zero.*/ ""re-replace ] map-index reverse harvest " "join ]
```
[Try it online!](https://tio.run/##TU5BTsMwELz3FSOLE5LTBLUEgYS4IS4cQJyqIKXp1jE4tlmvqwDl7SEVFw47mt2Z0ey@7STw9PL88Hh/jaGVvhAapchiXfrb99l3YoNP/2TyxtnU453Yk0OKzopYb5DoI5PvKIHJ0BgRmUQ@I1svuFksvrG@RFWhvsCqvkK9Xs1TYl3W@Jk2qLCzxoo2HHJMmA/l64w@D1vi21M1GmztHZRWxmXC0xLB00ajOeqZnB2/iENxvoRSTJopurajOTO0UVu/o3H@60CcCH3LB0oCBfUWrEcznUwopl8 "Factor – Try It Online")
## Explanation
```
Code | Data stack | Comment
============================================================================================================
! 478
1 digit-groups ! { 8 7 4 }
<<inside the map-index quotation now; first iteration>>
! 8 0 (digit, index)
10^ ! 8 1
[ number>text ] bi@ ! "eight" "one"
"-"glue ! "eight-one"
R/ one[- ]|-one$|zero.*/ ! "eight-one" R/ one[- ]|-one$|zero.*/ (push a regexp literal on the data stack)
""re-replace ! "eight"
<<outside the map-index quotation now>>
map-index ! { "eight" "seven-ten" "four-hundred" }
reverse ! { "four-hundred" "seven-ten" "eight" }
harvest ! { "four-hundred" "seven-ten" "eight" } (remove empty strings)
" "join ! "four-hundred seven-ten eight"
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~162~~ ~~153~~ ~~151~~ 148 bytes
-3 bytes thanks to Arnauld.
-6 bytes by merging the handling of 10's and 100's.
-2 bytes thanks to Arnauld, again.
-3 bytes by moving the floor operation, thanks to Shaggy.
```
f=(n,p)=>n>9?f(n/(m=n>99?100:10)|0,m%4?'ten ':'hundred ')+f(n%m):n?--n|!p?'one,two,three,four,five,six,seven,eight,nine'.split`,`[n]+[p&&'-'+p]:p:''
```
[Try it online!](https://tio.run/##PY7LboMwEEX3fIW7SAYLkzoJKQ8J@JAoUiJigiMYW9jQSk2/naIWs7pHukcz93kbb6bqpbbhmExTnfvINM0LLNKy9vHd7/IZ03LPebbn9MVZt4lKsAIJZNAMeO/FnQANZnnT0QzLMMTXmy5BoWD2UzHb9EKwWg09q@UomJFfzIhRIBPy0ViGEgXsjG6lvbLrGS/BWW@3EEKgL5nOAKZ6wMpKhcQKY32k5NsjpFJoVCt2rXrMkwnkBTAyj6DU@/G8P3NP/zNect6/gGtOH045rM4q8dTR4egoce1x9aI4cde4@xSf@ErRQmma0ukX "JavaScript (V8) – Try It Online")
Ungolfed
```
f = (n, p) =>
n > 9 ? // check if we should handle 10's or 100's
f(
n / (m = n > 99 ? 100 : 10) | 0, // check what mod to use, then floor divide
m % 4 ? 'ten ' : 'hundred ' // check what place to use
) + f(n % m) :
n ? // if 9 >= n > 0
--n | !p ? // if n > 1 or p ('ten' or 'hundred') is not defined we need to find the name of n
'one,two,three,four,five,six,seven,eight,nine'.split`,`[n] +
[p && '-' + p] : // add p if we have it
p : // return p if n = 1
'' // return '' if n = 0
```
[Answer]
# [Python](https://www.python.org), ~~198~~ 188 bytes
```
lambda m:" ".join([r[int(i)]for i,r in zip('%3s'%m,[[c+s for c in",one,two,three,four,five,six,seven,eight,nine".split(",")]for s in['-hundred','-ten','']])if"0"<i>" "]).replace("one-","")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY_dSsQwEIXvfYoSWJLgtHR1axdRXyT2orYTO9ImJUnXn1fxpiD6FL6Ib2OWKnQvhsPHYc6cef8aX0Nnzfyhb-8_p6DT_c93Xw8PbZ0M1yxh2ZMlI5RTZIIgWWnrEoI4JnmjUfDNpeebAZRqzn1yNJtoMbAGITxbCJ1DBG0nB5oOCJ5ewOMBDSA9dgEMGWSZH3sKggFb8n2MUDztJtM6bDnwNKCJwqtKkmY5u6G7WK2SmcOxrxsULN5L4z6Tfz_0ozsW1qK4kvLsH7bbFZQXK9iV-7VV7E4oX1GRlyeJ0VtuzvOivw)
Inspired by [Sisyphus's answer](https://codegolf.stackexchange.com/a/245783/110555). Generates three lists of the number string for each of the hundreds, tens and ones. Indexes each list by it's respective value in the input, then gets rid of `one-`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 147 bytes
```
n=>['hundred','ten',''].flatMap(t=>(c=',,two,three,four,five,six,seven,eight,nine'.split`,`[p=(n*=10)/1e3%10|0])?t?c+'-'+t:c:p?t||'one':[]).join` `
```
[Try it online!](https://tio.run/##DYuxboMwFAB/xUtlu7y4RtmSOuyV2g4ZERIW2PAiZFv2C20l/p2ynG64e9jVliFjolOIo9u92YO5tXx@hjG7kQMnFw7yTvnF0qdNgsxNDIYD0E8EmrNz4OMzg8fVQcFfKG51ARxOM0HA4LgqaUHqoW@TEeHV1Fq@1e78UutNd7KhZqj4iVd0GS6poW3j8ZgubSfVI2LoWb/7mJlAZlh9ZcjeWa21PqyqJBtiKHFxaomTOJKKcS5VsuOdbCZxlsA@7t9fqlDGMKH/E16glHL/Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 223 bytes
```
o,i,z;main(a,c)char**c;{for(o=strlen(c[1]);z=c[1][i]-49,printf("%s%s%s ",z|o-i==1?"zero\0one\0two\0three\0four\0five\0six\0seven\0eight\0nine"+"059=CHMQW]"[z+1]-48:"",z&&o+~i?"-":"",o-i-2?o-i-3?"":"hundred":"ten"),++i-o;);}
```
[Try it online!](https://tio.run/##TY1PT4NAEMXvfopmjA2UXQPVJq0rcvDixYMnD8CBLAM7SbtrlqUa/PPVcbg1k7z5zcvkPS17redrsvo4trh6HEJL7tY8XV1anmzP3uwEiUmdGrJRI3SsTeM3G62@O@cjl/PfEW2ky6yO1ZQvu6Ra3h/EBweELoKbYZkViOnHScrzrIAJvatSZ7FKwydTMB6ZOzd6VjozD/TFgme0VYrUm1CllixCAunukD@/vL6911BOScZd@wfg9PXaJX9UgITl5Cq5LRa9K4AdM9rWY8sU0EIskoSkU7H6ned5l23/AQ "C (gcc) – Try It Online")
Thanks to Mukul Kumar for basis, fixed what I perceived to be incorrect output, and shaved down by switching to C and embracing the sketchiness of golf C.
Updates based on issues found and golf contributed by Arnauld
Thanks to ceilingcat for some more C golf sketchiness.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), no library, 184 bytes
Late to the party, but here's my answer. [jezza\_99 answer](https://codegolf.stackexchange.com/questions/245778/numbers-in-2050/245782#245782) using library is unbeatable!
```
n=input()
for i,o in zip([' one two three four five six seven eight nine'.split(' ')[int(d)]for d in n],['-hundred','-ten',''][-len(n):]):
if i:print((i+o).replace('one-',''),end=' ')
```
[Try it online!](https://tio.run/##xZA/b4MwEMVn@BS32VYhAnVpkIgUVdmykaUChrQc4SRytoxJ/3x5ahele6dOlnz3fu@9M59u0Pz4ZOxiLLGT4kXPFojN7IDn6yvaAoRauPz5kirutR8n2q/AFxlZC9CM4N41uMEiQh/0Pd0QJvqACW/IgHQZPI4YxWYyI3kbD62DX6faQOwCj9ukFukwc2exE4lIHbJ/RFunI7JkVbSqiIF6oGJNK@lBq41FM57fUAqfJA0ClSB3ZfC4t2q44f3xCKdDdYLnfXWoIIN0B9vttmGh4rVWCGHPfEGZZ1nmveJo1VMCotyJBO5cP@FyclaSiqP/P0kU/eUov7XUkmf5Nw "Python 3.8 (pre-release) – Try It Online")
---
***Commented code***
```
# input: get number to be rewritten in words
# n will be a string
n = input('Input number n to be translated into words (0 < n < 1000): ')
# list of literal digit
# specify split(' ') to have empty string corresponding to 0
literal_digit = ' one two three four five six seven eight nine'.split(' ')
# we will get
# ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
# list of literal digit corresponding to the input number
# expanded list comprehension [literal_digit[int(d)] for d in n]
literal_number = []
for d in n:
literal_number.append(literal_digit[int(d)])
# for example '438' -> ['four', 'three', 'eight']
# list of literal orders of magnitude
# we have to consider only the elements according to the length of the number
ord_mag = ['-hundred', '-ten', ''][-len(n):]
# for example '43' -> len = 2 -> start at -2
# we will get only ['-ten', '']
# build the number string translated into words
# loop over the literal number and the corresponding order of magnitude
for i, o in zip(literal_number, ord_mag):
# check if digit is 0 -> '': don't print
if i:
# not 0
# we must print the literal digit and its order of magnitude
string = i + o
# if digit is one
# we must print only the order of magnitude,
# otherwise only 'one' if the magnitude is unit
string = string.replace('one-', '')
# this can be done because the '-' is defined in the order of magnitude
# print the string, concatenating the digit on the same line
print(string, end=' ')
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
“0€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“#ISèāR… —¿°¡#sèøʒнa}€á'-ýðý„€µ-K
```
[Try it online](https://tio.run/##AXUAiv9vc2FiaWX//@KAnDDigqzCteKAmuKAouKAnsOt4oCgw6zLhsOIxZLFocOvwr/FuMKvwqXFoOKAnCNJU8OoxIFS4oCmIOKAlMK/wrDCoSNzw6jDuMqS0L1hfeKCrMOhJy3DvcOww73igJ7igqzCtS1L//81MDc) or [verify all test cases](https://tio.run/##AYEAfv9vc2FiaWX/4oKER04/IiDihpIgIj//4oCcMOKCrMK14oCa4oCi4oCew63igKDDrMuGw4jFksWhw6/Cv8W4wq/CpcWg4oCcI05Tw6jEgVLigKYg4oCUwr/CsMKhI3PDqMO4ypLQvWF94oKsw6EnLcO9w7DDveKAnuKCrMK1LUv/LP8).
**Explanation:**
```
“0€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“
# Push dictionary string "0 one two ... eight nine"
# # Split it on spaces
I # Push the input-integer
S # Convert it to a list of digits
è # Index those into the list
ā # Push a list in the range [1,length] (without popping)
R # Reverse it to range [length,1]
… —¿°¡ # Push dictionary string " ten hundred"
# # Split it on spaces: ["","","ten","hundred"]
s # Swap so the [length,1] integer-list is at the top
è # 0-based index into the ["","","ten","hundred"]
ø # Create pairs of the two lists
ʒ # Filter, to only keep the pairs where:
н # the first item
a # only contains letters
# (this removes ["0","hundred"], ["0","ten"], and ["0",""] pairs)
}€ # After the filter: map over each remaining pair:
á # Only keep strings consisting solely of letters
# (this removes the "" from the last pair)
'-ý '# Join each inner pair with "-" delimiter
ðý # Then join these strings with " " delimiter
„€µ- # Push dictionary string "one-"
K # Remove all those substrings
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“0€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“` is `"0 one two three four five six seven eight nine"`; `… —¿°¡` is `" ten hundred"`; and `„€µ-` is `"one-"`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 102 bytes
```
\B
-ten¶
ten(¶..)
hundred$1
A`0
¶
1-
1
one
2
two
3
three
4
four
5
five
6
six
7
seven
8
eight
9
nine
```
[Try it online!](https://tio.run/##DckxDoIwGEDh/Z3CQRMcIBSpxVEXL@GACT/S5ScpBT0ZB@BileF9ywsSvb7TKXu26fUgj6Lbym62rUVxZpi1C9IdDfe2ZF8HTA6GUYWK@B25EIcgQk0/zgFL7xfhyuR/OCZZRGkQ/xkiN9SrpGSvGIOrqF2Ds/VeiS3dHw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\B
-ten¶
```
If there is more than one digit then assume the leading digit is a ten. Also split the digits onto their own line.
```
ten(¶..)
hundred$1
```
If there's a second digit then correct it to a hundred.
```
A`0
```
Delete any lines containing a `0`.
```
¶
```
Join the lines together again.
```
1-
```
`10` and `100` should just be ten and hundred.
```
1
one
2
two
3
three
4
four
5
five
6
six
7
seven
8
eight
9
nine
```
Turn the remaining digits into words.
Bonus: Here's a version that works up to `9999` for 116 bytes: [Try it online!](https://tio.run/##DYwxDoIwFED3dwoHjS41FCjFURcv4QAJX9ulTUpBT@YBvBh2eHnJG16S7MO4HU73YXvcUPvz8fflOlQU7VAalSWgapRbwpRkQjWlubjMY5jQCjQxCDX5HWnILonQ8oxLwvD0q9Ax@w@WWdYy6xH/cpkLwQfZNtOhNbamtT3WtIUKU1lMZ@s/ "Retina 0.8.2 – Try It Online") Link includes test cases. (Sadly the three digit version is 103 bytes.)
[Answer]
# [Python 2](https://docs.python.org/2/), 209 bytes
```
i=input();t,n="0 one two three four five six seven eight nine".split(),map(int,"00"+`i`)[-3:]
print ("",t[n[0]]+"-hundred ")[n[0]and i>99]+("",(t[n[1]]+"-","")[n[1]<2]+"ten ")[n[1]and i>9]+("",t[n[2]])[n[2]>0]
```
[Try it online!](https://tio.run/##LY/RboMwDEXf8xWWX0hGOgVaRruN/giK1Kq4JdLmRBC67utZYH2wLF@dI@uG39h7LueL76jJsmx2jeMwRak@ouYGDXgmiD8eYj8QwdVPA1zdnWB0DxjpTgzkbn0Edkz4OoYvl2T9fQ7ScdRoDOYnd1LtZvtuRRhSCBJRx5ZbY22Om37ibqAOUK3RmTtwx8PB5gsmF65YOdS4IoX9LNMd0@fn/VT@jUUorVXrOho7p1aCHnSRS0f1sp@3onoTRSHqUuzqvairXRojKlP/AQ "Python 2 – Try It Online")
Python 2 because:
1. Accepts integers directly as input
2. `` converts integer to string
3. Can directly index the result of map without converting to a list
4. No () required by the print
[Answer]
# PHP, 195 bytes
```
<?php foreach(str_split(substr("00".fgets(STDIN),-3))as$i=>$c)echo trim($c>0?[0,$i>1?"one":"","two","three","four","five","six","seven","eight","nine"][$c].["-hundred","-ten",""][$i]." ":"","-");
```
Input via STDIN, output via echo
[Try it online!](https://tio.run/##JYzNDoIwEIRfhWx6aBMgEOPFH7h48eJFb4QYrQvdRGnTFvTta6uX@TKzO2OUCWHXGmWyQVu8ScWdt1dnnuS5m@/RcKgqKIcRvePny@F4EnmxEuLmGO0bJgVKpTNv6cWZbKq2q3JGTd2CnhA2ADn4t06qLGLkoGebQEtyjj5JccEpEmlUPnKi2O07Jvuyg0LN08PiI@aF/72lE/UlZP/9AsQ2hHq1Dl8)
---
De-golf:
```
<?php
$inp = substr("00".fgets(STDIN),-3);
// here I take input and append leading zeros, so as the total lengh is 3
// (for example, 13 becomes 013)
$arr = str_split($inp);
// string to array of chars
foreach($arr as $index => $digit){
$num_array = [0, $index > 1 ? "one":"","two","three","four","five","six","seven","eight","nine"]; // here one is hidden unless it's on the last position
$name_array = ["-hundred","-ten",""];
$chunk = $num_array[$digit].$name_array[$index]." ";
$chunk = $digit > 0 ? $chunk : ""; // empty string if it's zero
$trimmed = trim($chunk, "-"); // to dispose of "-" at the beginning of the string (this could happen if we drop "one" in "one-ten", so just "-ten" left)
echo $trimmed;
}
?>
```
---
***Fun note** - I didn't expect PHP doesn't complain here:*
[](https://i.stack.imgur.com/5CEeJ.png)
[Answer]
# C++, 277 bytes
```
#include <iostream>
main(int a,char*c[]){char s[9];int q[]={0,4,7,10,15,19,23,26,31,36,40},n,m,o=strlen(c[1]),i=0;do{m=c[1][i]-48;n=q[m];strcpy_s(s,"zeroonetwothreefourfivesixseveneightnine"+n,q[m+1]-n);std::cout<<((o-i==2)?"ten-":(o-i==3)?"hundred-":"")<<s<<' ';}while(++i<o);}
```
## Ungolfed
```
#include <iostream>
int main(int a, char* c[]) {
char s[9];
int q[] = { 0,4,7,10,15,19,23,26,31,36,40 }, n, m, o = strlen(c[1]), i = 0;
do {
m = c[1][i] - 48;
n = q[m];
strncpy_s(s, 9, "zeroonetwothreefourfivesixseveneightnine" + n, q[m + 1] - n);
std::cout << ((o - i == 2) ? "ten-" : (o - i == 3) ? "hundred-" : "") << s << ' ';
} while (++i < o);
}
```
**Input** comes from [command-line arguments](https://en.cppreference.com/w/cpp/language/main_function)
**Reason for using C++ over C**
* apparantly some compilers include `string.h` header in `iostream`
[](https://i.stack.imgur.com/zBGmp.png)
[Answer]
# [Julia](https://julialang.org), ~~185~~ 158 bytes
```
n+m+s=!(n÷m)*"-$s "*!(n%m)
!n=replace(n<10 ? split(" one two three four five six seven eight nine"," ")[-~n] :
n<100 ? n+10+:ten : n+100+:hundred,"one-"=>"")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBBTsNADEX3OcXPCKSkaaQMakmVkHIMFlUXFXHIoMSJZpzCiosgoW56Bg7AKbgNkwJe2P6y_5Pl9_Pz1JnD6XSepEk33x-c9Imrwoi_Pvt4odIrB7Xw8rqPg5ArS2N3eKSI73SGe7ixMxIpDEyQlwHSWiI0w2TRmCPBmVc4OhKDzFMrYMOklgoq3qVvvEcRzKCZxInOkkL8ZnHpvWgnri3VS-Xpqaq2SsV_Vz4IOXGosNOFvimxvi2R-6q1LrHKN16tV3PK_CzL90EzWAgM42IM4GO0hqXjSFBtEUocENe_-P9n_AA)
] |
[Question]
[
To get this sequence I just made up, which will subsequently be referred to as TSIJMU, consider the harmonic series:
\$ \frac{1}{2} + \frac{1}{3} + \frac{1}{4} ...\$
But what if you only add a term if it doesn't make the sum so far over 1, and otherwise subtract? Let's see an example here, starting at \$\frac{1}{2}\$:
Sum so far: 0, term: \$ \frac{1}{2} \$
\$ 0 + \frac{1}{2} = \frac{1}{2}\$, which is less than 1,so we add.
Sum so far: \$ \frac{1}{2} \$, term: \$ \frac{1}{3} \$
\$ \frac{1}{3} + \frac{1}{2} = \frac{5}{6}\$, which is less than 1,so we add.
Sum so far: \$ \frac{5}{6} \$, term: \$ \frac{1}{4} \$
\$ \frac{1}{4} + \frac{5}{6} = \frac{13}{12}\$, which is more than 1,so we subtract, yielding \$\frac{7}{12}\$.
If you do this forever, TSIJMU is the sequence of integers that are *added* when doing this. This goes 2,3,5,6,8, etc.
# Rules
Your code **must not** fail due to floating point errors. As pointed out by Arnauld, this means your code *may* fail due to integer overflow errors. If this is the case, please provide a version which works for arbitrary input size.
As with all [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, there are three ways you can output:
* Take a number \$n\$ and return the nth item of TSIJMU
* Take a number \$n\$ and return the first n items of TSIJMU
* Print TSIJMU infinitely.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
# Testcases
These are 0-indexed, but you can take 1-indexed.
```
0 => 2
3 => 6
9 => 17
25 => 48
58 => 113
90 => 177
156 => 308
352 => 700
479 => 953
```
As requested by Bubbler, the first 20 terms are:
```
2,3,5,6,8,10,12,13,15,17,19,21,23,25,27,29,31,33,34,36
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 54 bytes
*-1 byte thanks to @ovs*
*-4 bytes thanks to @att*
Outputs the sequence indefinitely.
```
a=b=n=2
while a:=a*n+[b,-b][a*n>b!=print(n)]:b*=n;n+=1
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9E2yTbP1oirPCMzJ1Uh0co2UStPOzpJRzcpNhrItEtStC0oyswr0cjTjLVK0rLNs87TtjX8/x8A "Python 3.8 (pre-release) – Try It Online")
Although the code is heavily golfed, the idea is a straightforward implementation. `a` and `b` are the numerator and denominator of the current fraction. To add two fractions, we can use a simple formula: `a/b + c/d => (ad + cb) / bd`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
W<Goḟε§e+≠1İ\
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//9XPEdv4bifzrXCp2Ur4omgMcSwXP// "Husk – Try It Online")
An infinite list.
woo, it works.
-2 bytes from ovs.
-4 bytes from Dominic Van Essen.
## Explanation
```
Wo<0-Goḟε§e+`-1İ\
1İ\ [1/2,1/3,1/4...
Go 1 scan with 1 as intial value
§e+`- [a+b,a-b]
ḟε first element <=1
Wo indices of pairs where
- difference is
<0 < 0 (negative)
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 45 bytes
```
2.FatRat...{($!+=1/$_)>1??($!-=2/$_)!!.say}&1
```
[Try it online!](https://tio.run/##K0gtyjH7/99Izy2xJCixRE9Pr1pDRVHb1lBfJV7TztDeHsjTtTUC8RQV9YoTK2vVDP//BwA "Perl 6 – Try It Online")
Full program that outputs the sequence infinitely.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~35~~ 34 bytes
```
#0[#+1/If[++i#>1,-Echo@i,i]]&[i=1]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/1/ZIFpZ21DfMy1aWztT2c5QR9c1OSPfIVMnMzZWLTrT1jD2/38A "Wolfram Language (Mathematica) – Try It Online")
Outputs the sequence indefinitely (up to `$IterationLimit`, 4096 by default).
Subtracts terms from 1 instead of adding from 0.
---
Without overriding `$IterationLimit`, **40 bytes**:
```
i=0;Do[i+=1/If[i>1/j,-Echo@j,j],{j,∞}]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/T1sDaJT86U9vWUN8zLTrTzlA/S0fXNTkj3yFLJytWpzpL51HHvNrY//8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 58 bytes
*Edit: -1 byte thanks to emanresu A*
```
c=1
repeat`if`((F=F*(c=c+1)+T)>(T=T*c),F<-F-2*T/c,show(c))
```
[Try it online!](https://tio.run/##K/r/P9nWkKsotSA1sSQhMy1BQ8PN1k1LI9k2WdtQUztE004jxDZEK1lTx81G103XSCtEP1mnOCO/XCNZU/P/fwA "R – Try It Online")
Prints the sequence until it reaches the TIO output limit.
The numerator & denominator of the fraction so far are stored in `F` and `T` respectively. These won't error when they get too large, but [R](https://www.r-project.org/) will assign them as `Inf`, beyond which point every integer will be (incorrectly) output, since `Inf>Inf` is evaluated as `FALSE`.
A non-overflowing version, using **[R](https://www.r-project.org/)+GMP** to handle large integers, is [93 bytes](https://tio.run/##K/r/P9k2xDY9t8DKKrFYLykzvUrDUJPLDVXEQJOrKLUgNbFEISEzLUFDw83WTUsj2TZZ21BTO0TTTiPENkQrWVPHzUbXTddIK0Q/Wac4I79cI1lT8/9/AA) (the [R](https://www.r-project.org/) version installed on TIO seems to give an error, so [here](https://rdrr.io/snippets/embed/?code=c%3DT%3Dgmp%3A%3Aas.bigz(1)%0AF%3Dgmp%3A%3Aas.bigz(0)%0Awhile(c%3C100)%60if%60((F%3DF*(c%3Dc%2B1)%2BT)%3E(T%3DT*c)%2CF%3C-F-2*T%2Fc%2Cshow(c))%0A) is a link to a working version on rdrr.io, with `repeat` exchanged for `while(c<100)` to force output).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
«efy}á╤2╧8ßÇæ→╔y¬µ!
```
[Run and debug it](https://staxlang.xyz/#p=ae6566797da0d132cf38e180911ac979aae621&i=)
Making a husk answer for this turned out to be very difficult. Here's a stack based one for the moment.
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
```
from fractions import*
v=i=Fraction(1)
while 1:i+=1;v-=(v>1/i!=print(i)or-1)/i
```
[Try it online!](https://tio.run/##LcgxCoAwDAXQ3VPUrVWkBDcljt5DRPGDNiWWiqevi2988U2HhL6UXeUyuy5rgoTb4Iqiqakyg@d/LbnqOXBuhga0TGPu2OaJPGqOipAsnGhHzqOUDw "Python 3 – Try It Online")
-8 bytes thanks to ovs
-1 byte thanks to Jo King (the number can't be exactly 1, also thanks to Bubbler for the pseudo-proof of this)
[Answer]
# [Perl 5](https://www.perl.org/), 42 bytes
This prints TSIJMU infinitely:
```
$i=1;1while$s+=1/++$i*($s+1/$i<1?say$i:-1)
```
[Try it online!](https://tio.run/##K0gtyjH9/18l09bQ2rA8IzMnVaVY29ZQX1tbJVNLA8g21FfJtDG0L06sVMm00jXU/P//X35BSWZ@XvF/Xd8yUz1DAwA "Perl 5 – Try It Online")
...or until Try It Online reaches its limit of 128 KiB of output. Exploits that `say$i` prints that sequence number and then returns 1.
This is seven bytes longer and takes *n* from stdin:
```
$i=1;$s+=1/++$i*($s+1/$i<1?$_--&&say$i:-1)while$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l09bQWqVY29ZQX1tbJVNLA8g21FfJtDG0V4nX1VVTK06sVMm00jXULM/IzElVif//38jgX35BSWZ@XvF/3bz/ur5lpnqGBgA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, ~~20~~ 19 bytes
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
```
λN*N<!©+DN!‹iN,ë®·-
```
[Try it online!](https://tio.run/##AS4A0f9vc2FiaWX//867TipOPCHCqStETiHigLlpTizDq8Kuwrct////LS1uby1sYXp5 "05AB1E – Try It Online")
There is no builtin fraction type, so everything is integers. (Ab)uses the recursive environment `λ` as an infinite loop that starts the iteration counter `N` at 1 and pushes a `1` to the stack initially.
```
λ # recursive environment
# generate infinite sequence of sums starting with a(0)=1
# pushes the last value to the stack, lets call this x
N* # push N*x
N<!© # calculate (N-1)! and store a copy of the result in the register
+D # calculate N*x + (N-1)! and make a copy of the result
N!‹ # is N*x + (N-1)! < N! ?
iN, # if so, N*x + (N-1)! / N! < 1 and print N
ë®·- # otherwise subtract (N-1)!*2 to get N*x - (N-1)!
```
[Answer]
# JavaScript (with `alert`), 52 bytes
```
for(p=q=i=1n;;p*=i++)q*=i,p*i-p>q?alert(i,q+=p):q-=p
```
[Try it online!](https://tio.run/##HctLCoAgEADQ6/jJoG0xdRYxiwlxZkzC21u0eqt3@cffoSBXl2mP3adYKjRYA@WbUhwTnarpflBRDAIIU14WNoDWavkY2KDjVbZ/KhzEAutZHHDvLw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 47 bytes
```
02s>n[<1f/+1G:![p:lu' o>,<]p[p1l/2*-0]pl`s>]>
```
[Try it online!](https://tio.run/##y6n8/9/AqNguL9rGME1f29DdSjG6wCqnVF0h307HJrYgusAwR99IS9cgtiAnodgu1k5B4f9/QyMA "Ly – Try It Online")
```
02s>n[<1f/+1G:![p:lu' o>,<]p[p1l/2*-0]pl`s>]>
02 # Init stack w/ "0" (sum) "2" (divisor)
s> # Stash the divisor, change to iterator stack
n # Read number of output items "N" from STDIN
[ >,< >] # Loop, iterates until "N" is 0
< # Switch to accumulator stack
1f/+ # Calculate "(1/divisor)+accumulator"
1G: # Compare "accumulator>=1", duplicate answer
![p: ]p # If-then, runs if "accumulator<1"
lu' o # Load the divisor, print as num, add " "
>,< # Switch to iterator stack, decr, switch back
[p o]p # If-then, runs if "accumulator>1"
1l/2*- # Calc "2*(1/divisor)" and subtract
l`s # Increment divisor, stash it
> # Switch to empty stack to suppress printing
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
Nθ≔¹η≔⁰ζ≔¹εW‹Lυθ«≦⊕ε≧×εζ¿›ζ×η⊖ε≧⁻ηζ«≧⁺ηζ⊞υε»≧×εη»Iυ
```
[Try it online!](https://tio.run/##fZBNC8IwDIbP26/IMYUK6tWTKIjgZIh/oM64Frqq/VCY@Ntr1eHXwRwC4U3ePEklha32Qsc4N4fgl6HZkMUjG@Vj51RtcMBBvqs@h/ZLo1SdpdIEuCDnUjK1lxgYhyNjcMmzQhy69rmpLDVkPG2fg29tpWrpca0ackl6LsnUDnBmSfhE1HJ4qCg5TOnlg8RSwI9PoUxIPrLzIe3oTvK7rtSfXVkZXALvyK5/4O7/uOalVcbjRDifrmWjGIf92DvpGw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
Nθ
```
Input `n`.
```
≔¹η≔⁰ζ≔¹ε
```
Start with a running total of `0/1` and the last fraction as `1/1`.
```
W‹Lυθ«
```
Repeat until enough terms have been collected.
```
≦⊕ε
```
Increment the denominator to get the next unit fraction.
```
≧×εζ
```
Multiply the running total by the denominator.
```
¿›ζ×η⊖ε≧⁻ηζ
```
If incrementing the running total would make it exceed the denominator then decrement it.
```
«≧⁺ηζ⊞υε»
```
Otherwise increment it and push the denominator to the list of results.
```
≧×εη
```
Divide the running total by the denominator.
```
»Iυ
```
Print the found terms.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Just ... hideous!
```
@¶Xõ!÷1 åÈ+Y§1©X+YªnXÃäÎèÉ}a2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=QLZY9SH3MSDlyCtZpzGpWCtZqm5Yw%2bTO6Ml9YTI&input=NDc5)
[Answer]
# [Zephyr](https://github.com/dloscutoff/zephyr), 108 bytes
```
set s to 0
set i to 2
while 1=1
if(s+(/i))<1
set s to(/i)+s
print i
else
set s to s-(/i)
end if
inc i
repeat
```
Outputs infinitely. [Try it online!](https://tio.run/##PYtBCoAgEEX3c4pZKhJl6zpM1IgDYuIIUZc3XdTufd77DyV/51qFCgqWEyfoyB1nuDwHQrtaYKfEqJG1Xix8cd9GIGWO7QIUhH6HMnQNFA9kBxz3VmRKtJVaXw "Zephyr – Try It Online")
Implements the spec directly, using Zephyr's built-in rational numbers. Here it is ungolfed:
```
set sum to 0
set i to 2
while true
if (sum + (/i)) < 1
set sum to sum + (/i)
print i
else
set sum to sum - (/i)
end if
inc i
repeat
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 26 bytes
```
Wt*:oYt*o>y*Uo?t+y*Poy*o-t
```
Outputs infinitely. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 27-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/vETLKj@yRCvfrlJLWzvfvkS7Uisgv1IrX7fk/38A "Pip – Try It Online")
### Explanation
Pip doesn't have rational numbers, so we'll use integer math instead. We store the numerator of the running sum in `y` (initially `""`, which evaluates to 0 in a numeric context); the denominator in `t` (initially `10`, but any denominator greater than 0 will do, since the numerator is initially 0); and the index in `o` (initially `1`). Each time through the loop, we want to:
* Increment \$o\$
* Test whether \$\frac y t + \frac 1 o \lt 1\$
+ If so, output \$o\$ and add \$\frac 1 o\$ to \$\frac y t\$
+ If not, subtract \$\frac 1 o\$ from \$\frac y t\$
For the test, observe that
$$
\frac y t + \frac 1 o \lt 1 \\
\frac{y \cdot o + t}{t \cdot o} \lt 1 \\
y \cdot o + t \lt t \cdot o \\
y \cdot o \lt t \cdot (o - 1)
$$
We can combine this expression with the increment of \$o\$ by calculating \$t \cdot o\$ first, then incrementing \$o\$, then calculating \$y \cdot o\$.
For the update, we need
$$
y := y \cdot o \pm t \\
t := t \cdot o
$$
Observing that `t*:o` is always truthy, does not depend on the value of `y`, and is a no-op if executed before the first time through the loop, we can use it as the while-loop header.
```
Wt*:oYt*o>y*Uo?t+y*Poy*o-t
t is 10, o is 1, y is "" (implicit)
t*:o Multiply t by o and assign the result back to t
W and loop while the result is truthy (non-zero):
t*o> Is t*o greater than
Uo o, incremented
y* times y?
? If so:
Po Print o
t+y* and calculate t+y*o
Else:
y*o-t Calculate y*o-t
Y Set y to the calculated value
```
[Answer]
# C (GCC), 75 bytes
```
n,d,i,j;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i)n=n*++j+d,d*=j;return j;}
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3fsUgFBITsXXXTod@izi1TKBjibYb8dvTCH2czV3cw@nrW9@npJ69@ICT6ewyjNEoCR08U6AWu0ZQG75oTW3FTTg5J1ZJK@eCY88VBYzX@RkVAq5JdIZ7J2peo7AtlgI@5C6Y7RUg2GOeMxwRthr8rS@PmNXBlDuG0sNkxFr8SWuxpjc)
Overflows when the input is greater than 8.
How it works:
```
// n is the numerator, d the denominator, i the amount of numbers that have been added and j the denominator of the fraction that is supposed to be added.
n,d,i,j;
s(a)
{
// The update statement of the for loop is moved to the end of the loop body for clearness (it's executed at the end of the loop anyways).
// a / i is equivalent to a >= i, so we loop until i is greater than a
for(n = i = 1, d = j = 2; a / i;)
// Both n and d are multiplied by j, and the previous value of d is added to n.
// The new fraction is (n*j + d) / (d*j).
// (n*j)/(d*j) = n/d, so what's actually added to the fraction is d/(d*j), which can be rewritten as 1/j.
n = n * ++j + d,
d *= j,
// n / d is non-zero iff n >= d, and n >= d iff n/d >= 1
// If n/d >= 1, subtract what was previously added to n, twice.
// Otherwise, increment i
n / d ? n -= 2 * d / j : ++i;
return j;
}
```
---
This 70-byte version also seems to work, although I'm not sure if it always does:
```
n,d,i,j;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i)n=n*++j+d,d*=j;a=j;}
```
The 70-byte version stores `j` in `a`, which seems to have the same effect as returning `j`. If anyone knows, please tell me if that behavior is consistent and I'm allowed to use it.
[Try It Online!](https://tio.run/##RYzNCoMwEITvPsUiFBITsfVWt0ufJbhYNtC1aOlF8uxphP4MDHOYj29sb@OYs3r24iOuJthtmhejJHTyTJF6DJ2gdnzVlvqGuzg4J1ZJG@eiY88NRQylKYs@4R5EzWsWttVWwSdFCWZ/BQiOWOYCZ4RdBH/qm8dS0MnUB4baw2rEWvxBqUr5DQ)
---
Here's a 127-byte version that overflows at a number of terms somewhere between 21 and 57:
```
long long n,d,i,j,k;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i){n=n*++j+d,d*=j;for(k=1;k<99;)n%++k||d%k||(n/=k,d/=k);}return j;}
```
[Try It Online!](https://tio.run/##RY3LDoJADEX3fEVjQjLDjEHZaW38FkLVdEaLAXWDfDsOxsddnLvoadssT00zTedWT/CGevbig4/Ym9oOx7YzSkJrzxSowroU1JL3uqSq4DJsnRM7KGnhXHDsuaCA81KkNcbdZoNWc@fi88l5gtGSoucEi2N3uN07hYDjJHqDSy1qHq2wzYYMPkmnwMxTAYIVptpBlXp@C3/tm2uX3KNZ5AwLD70Ra/Enjdk4vQA)
It's pretty much the same as the first one, except the variables are long long integers rather than integers, and it includes `for(k=1;k<99;)n%++k||d%k||(n/=k,d/=k);`, which, for each number `k` from 1 to 98, divides `n` and `d` by `k` if they're both divisible by `k`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ 73 bytes
```
p=2#1$0
(n#y)x=(n?y)(x*n)$(n+1)#(y*n)
(n?y)a f|a+y>y*n=f$a-y|1>0=n:f(a+y)
```
[Try it online!](https://tio.run/##HcgxCoUwDADQ3VME2iFRhNZRiP8sGSyKGoo6GPDu/cXt8Ra5tnnfS8k8uOhDg@qMHkb9GeHTKnnULpJDq26@FkivdDbV4eSltzdOgXVMWJfKIasCQz5XvcHDLdsMQ4Bc/g "Haskell – Try It Online")
] |
[Question]
[
# The challenge
Given point and a path of points, say whether or not the point is in the polygon that is created by the path.
Also return `true` if the point is on an edge of the polygon.
# Input
A list of pairs of integers.
The first 2 integers represent the point.
The remaining pairs (3rd and 4th, 5th and 6th etc.) represent the vertices of the polygon.
The edges are in the order of the input pairs.
The path is assumed to loop back to the first point of the path.
The input is assumed to be valid.
No three points in the path are collinear.
ex. `123 82 84 01 83 42`
# Output
A truthy/falsy value.
# Test cases
Input -> Output
`0 0 10 10 10 -1 -5 0` -> `true`
`5 5 10 10 10 50 50 20` -> `false`
`5 5 0 0 0 10 1 20 6 30 10 -40` -> `true`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 50 bytes
```
≔⪪A²θF⟦E³§θ⊖ιθ✂θ¹⟧⊞υ↔ΣEι⁻×§κ⁰§§ι⊕λ¹×§κ¹§§ι⊕λ⁰⁼⊟υΣυ
```
[Try it online!](https://tio.run/##jVA9C8IwEN39FTdeIIXWr8VJ0KGDUKhb6VBrtME0/UhO/PcxQUsHF4/7gHv37h1XN9VYd5Vybm@MvGvMeyUtproni4zD0sfAdotbNwIWp6rHFYe9TfVVvHDgcBD1KFqhrbiiZCxMc8iVrEVAE1YyyMg0SJ51MZ0iKzCnFsMmyeEkNRk8y1YYnLY@OMRsFpmqn071LKaCVhLSDzv5kx2zj@0W2Si1xeNAlTKYdT2Sh8OZFGDnimLDwXs8eRLCf8eXLYfVtxOt47J00VO9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪A²θ
```
Split the input into pairs of coordinates.
```
F⟦E³§θ⊖ιθ✂θ¹⟧
```
Calculate the area of three polygons: the one formed by taking the last, first and second points; the one formed from all of the points (including the test point); the one formed from all of the points except the test point.
```
⊞υ↔ΣEι⁻×§κ⁰§§ι⊕λ¹×§κ¹§§ι⊕λ⁰
```
Use the shoelace formula to calculate the area of that polygon.
```
⁼⊟υΣυ
```
Check whether the last area equals the sum of the first two. If this is the case, then the point lies within the polygon.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Polygon@#2~RegionMember~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyA/pzI9P89B2aguKDU9Mz/PNzU3KbWoTlntf0BRZl6JQ3p0taG@sQ4Q1@pUVxsa6BgaABlAWtcQSOua6hjU1sYqcMEVm@qYoik0BdGmBjpG2FUa6IDkYcpBqnSqzXSMYbaYgHX9/w8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 123 bytes
```
(x,y,...p)=>p.map((_,i)=>p.concat(p).slice(i,i+4)).reduce((n,[a,b,c,d],i)=>i%2<1&&a<x!=c<x&&y<b+(d-b)*(x-a)/(c-a)?!n:n,!1)
```
Ungolfed
```
(x, y, ...p)=>
p.map((_, i) => p.concat(p).slice(i, i + 4)) // Group points into edges
.reduce(
(n, [a, b, c, d], i)=> // for every edge
i % 2 < 1 && // if it's actually an edge
a < x != c < x && // and x of point is within bounds
y < b + (d - b) * (x - a) / (c - a) ? // and point is below the line
!n : n, // then invert whether it's inside
false
)
```
TIO seems to be down for now, I'll add a link when I can (or if someone else happens to first)
[Answer]
# [PostgreSQL](https://www.postgresql.org) 12, 91 bytes
```
create function f(a polygon,b point,out o bool)as $$begin return a~b;end$$language plpgsql;
```
PostgreSQL has [built-in polygon and point types](https://www.postgresql.org/docs/12/datatype-geometric.html), and [a built-in operator `@>`](https://www.postgresql.org/docs/12/functions-geometry.html) (also spelt `~` to save a byte) to test containment.
...Is this too boring?
[Answer]
# Java 10, ~~142~~ 141 bytes
```
a->{var p=new java.awt.geom.Path2D.Float();p.moveTo(a[2],a[3]);for(int i=3;++i<a.length;)p.lineTo(a[i],a[++i]);return p.contains(a[0],a[1]);}
```
[Try it online.](https://tio.run/##ZZAxb8IwEIV3fsWJKVGcU4CmQ1MqVaq6FVWiG2I4ggFTx46cSxBC/PbUSaAdKlmW7e/57r07UkPxcfvd5pqqCj5ImcsIQBmWbke5hEV3BdhYqyUZyAOPVmugMPPv15HfKiZWOSzAwBxail8uDTko50ae4OjLI50Y99IW@El8mL7hu7bEQZiVWNhGftmAVtO1oNVsHWY767oOoOazLIrUM6GWZs@HLCxRKzOoVaf21Oud5NoZKDG3hr35yuOkwxMPr23WGSzrjfYGbz4bq7ZQeGmwZKfMvg8zhGRZcZCIREzuK56IOBVJH/bGU5H@8bRf03@CRNzLeCgexWyo9pD8G1tvp//nYyPir5nluWJZoK0ZS@@TtQn6adasNL46R@cK2Q4ZAgqj8ROMI4O5P9@aXNsf)
**Explanation:**
```
a->{ // Method with integer-array parameter and boolean return-type
var p=new java.awt.geom.Path2D.Float();
// Create a Path2D object
p.moveTo(a[2],a[3]); // Set the starting position to the third and fourth values in the list
for(int i=3;++i<a.length;) // Loop `i` in the range (3, length):
p.lineTo( // Draw a line to:
a[i], // x = the `i`'th value in the array
a[++i]); // y = the `i+1`'th value in the array
// (by first increasing `i` by 1 with `++i`)
return p.contains(a[0],a[1]);}
// Check if the polygon contains the first two values as x,y
```
[Answer]
# [Scala](http://www.scala-lang.org/), 139 bytes
If the input is a `(Int, Int)` and a `List[(Int, Int)]` that doesn't have to be parsed, it's a bit easier
```
(x,p)=>(p.last->p.head::p.zip(p.tail)count{q=>(q._1._2<=x._2&x._2<=q._2._2|q._1._2>=x._2&x._2>=q._2._2)&(x._1<=q._1._1|x._1<=q._2._1)})%2>0
```
[Try it online!](https://tio.run/##bZDRS8MwEMbf81ccBUcOutBU60OxBX0T9MlHkZGtWa3ENFsyKW792@uts5sPwjXku@/H9b74lTJqaJcfehXgWTUWdBe0rTzcOwd7xr6UgXUOnD/aENOH8VPjw@tZviEUJTy0rdHKQjHwLnZYlNwJo3yYl068a1XluRPfjaNuUI3BVbuzYb8hbCMWUizSu6Kjc9aNV@qlVIdfr7x45eThjJOWI0uMPJwVuRJ7vErLZGCVXkPNfQ4vYdvYmlalSADHTB2tRNIL70wTeAQRik/l@EKE9phL1Nt253TF01Nf0bKKJxgrLhGRqOM70LA1JQaHrGfM0U@CsbzmUQIJyKnmEuYZJBHiXySD7IJkY6X/MQlMw8iHW7g@zbwZWdYPPw "Scala – Try It Online")
## Using winding number, 140 bytes
```
x=>y=>_.sliding(2).map{case Seq((a,b),(c,d))=>val(e,f,l)=(b>y,d>y,(a-x)*(d-y)-(c-x)*(b-y))
if(!e&f&l>0)1 else if(e& !f&l<0)-1 else 0}.sum!=0
```
[Try it online!](https://tio.run/##dVBNS8NAEL3nV0xzKDOyCWk1HoIb0Jugpx5FyibZlMg2WbtbSSj97XESW8SDsB@zj8f7WFcqo8au@NClh1fVtKB7r9vKwaO1cAq@lIE6g@fWg8yvF740zr8hv8QE0TtN6FPXGa1akGMv80Hm29iZpmraHa4p3it7KpXTsNGfiEoUJLAUFZHM2QK1qIUhiUU@iIo3qqinG6yigSIs57ngmYKmxoVe1kuTJ7QCbViRIb2EBWMPCUUXMDnH7rhfyGSsdA1eO48ug40/cB5Oy80Apm7Yi4GyzDLkYmdN4zGEcM6L29h3U714d@iOVleXHmhkbpCt@FwRMWn6DtarsSccCC0F5yCwbOVNi7N3mEACq@vikFEKSch9/rJSSH9Z6bzW/9ASuEoyBe7h9kf5bqYH5/Eb "Scala – Try It Online")
Uses the algorithm described [here](http://geomalgorithms.com/a03-_inclusion.html)
## With input as string, 186 bytes
```
i=>{val x::p=i split " "map(_.toInt)grouped 2 toList;(p.last->p.head::p.zip(p.tail)count{q=>(q._1(1)<=x(1)&x(1)<=q._2(1)|q._1(1)>=x(1)&x(1)>=q._2(1))&(x(0)<=q._1(0)|x(0)<=q._2(0))})%2>0}
```
[Try it online!](https://tio.run/##bY/BSsQwEIbvfYqh4JIcGtJqPVQT0JugJx9giW12jcQku52VYLfPXmPXuh6EIfwz3zcD6Vtl1eRf3nSL8KSMAx1Ru66HuxBgyLIPZWHTwDPujduCkHDvvdXKgZiMkMM3jk0ThIE@WIOQQ/6uAlkz9A8O6XbvD0F3UAH6R9PjDQnMqh4LGdirVl1aZZ8mpCkqY2nrDw6HnZBkx9YlKemtiOldxTmmWZXC8YfJM5MLoysSCT@5ZQrH365KgY70opJ8nLKQvoPWkQ3JOXAolypKKGrgOaV/lRrqs1LPVf3ncFiOJQ7XcHm6eTW72Th9AQ "Scala – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~171~~ \$\cdots\$ ~~129~~ 126 bytes
Saved a whopping ~~13~~ ~~19~~ 35 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved ~~2~~ 5 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!!!
```
W,i,l;f(x,y,V,n)int*V;{for(W=i=0;i<n-2;W+=V[i-2]>y^V[i]>y?(l>0)-(l<0):0)l=(V[i++]-x)*(V[i+2]-y)-(V[i++]-y)*(V[i]-x);return W;}
```
[Try it online!](https://tio.run/##VVLBjpswEL3zFV5LkWwYS@CUlbpeZw9V73tKDoRWq4RsLVEnAiqBEN@ezhiWdiUz2PNm3jw9@6TeT6f7/QAOanMRPQywBy@d7@K9GS/XRhyss6lxz15pc0jsvnBKl7vhB27w9yLqXSqVqJ9T@ZTK2grMJ0mpehmHrS7VgPiSHeYswaapuj@NZwcz3V8FDawBI/MyjKXtMtgkiZO3BjMXwTft5szBvXDGnziHGsmkmaLfb84LOUaM@m5XjG2xLQtd2nFMIZ1gzCFf4gQRY13VdmmBcJbCvFQGKqfSBc0@oXlY@h@sCUZqmCsQgkfYzkxf5rL4dq2H96tvqTQMhEAcol6ZfnrCH7E9m/uq/lb1XXUOAoh/ArIiYmTM6ddbEzcE8WP/XR/7r9/wyzn8f9zyCZ3bGnKELImDJXYxxpU0ZZVnV5kL4O0iazlXdlVEt4hC2KsIXKAlnT4uB0cxLj/wQIqPycwaWGsvYhYCIRZZCZ@rVh61Y5sz27RHz6GFpnh4aK2tSiqaoun@Fw "C (gcc) – Try It Online")
Uses the winding number algorithm: if the winding number is truthy, the point lies inside the polygon, otherwise its falsey.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 134 bytes
```
lambda x,y,p:sum((p[i+3]>y)^(p[i+1]>y)and(0<(l:=(p[i+2]-p[i])*(y-p[i+1])-(x-p[i])*(p[i+3]-p[i+1])))-(l<0)for i in range(0,len(p)-2,2))
```
[Try it online!](https://tio.run/##VY/RasQgEEXf8xXi00wzgkmaUsJmfyS1kLJJK2RdMRbi12fVdEsrAw73zFyvNvivm2lerdvn/m1fxuvHZWQbBbLd@n0FsIMuG3UO@J7bKrWjuYA8wdL1WauViJfCJwjimEEB20M7DB4AI1pOEuebY5ppw9xoPieQtEwGLIqaasTdT6tfWc@GgrFBkqShknSUqEi0JJWixFpq/7A2V/0Ppu2DR0Av1Bwuz3GoUEWKkT@bouRXu7hpnTYeuPg5HH@11TvYsOTEy9QGJK4NJ0u84zRDtor57w "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 105 bytes
```
function(P,m=matrix(c(P,P[3:4]),,2,T))!sd(sapply(3:nrow(m)-1,function(k)sign(det(diff(m[c(1,k+0:1),])))))
```
[Try it online!](https://tio.run/##hY69CoNAEIR7n@JCml2ygr8pBNvUFnYiQTwNh3qKpyR5@sspUZImWWaKXfYbZtRCXYVUglexrmdZTqKXkFAXd8U0igeUZkkyPwpyJPIoRTwoDqoYhvYJfiTH/g4d2i7tcINK3CTwagIu6hq6rASXmpMTuUg5LqOFHOYpLsEhZuR@2CQxOzRnZEeWjnNl7QVhpdCyNtq8hd90@La34peiVf95Z9MasrDEzsT8rVDwo4p@AQ "R – Try It Online")
Assumes no three points are collinear. Extends the algorithm described, e.g., [here](https://cp-algorithms.com/geometry/oriented-triangle-area.html).
If we call the query point \$Q\$ and the ordered points of the polygon \$P\_1\dots P\_n\$, this traverses the points of the polygon, checking to see which side of the segment it's on by computing the signed area of the triangle (using the shoelace method) formed by \$Q,P\_{i},P\_{i+1}\$: A positive sign means to the left, and negative to the right if you're going counterclockwise, otherwise it's reversed. If all the signs are the same (i.e., the standard deviation of the signs is 0), then the point is within the polygon.
My computational geometry professor would be somewhat ashamed it took me four days for me to remember this point-in-polygon method. If I can find my textbook/notes, I'll post its description of the algorithm...
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 63 bytes
```
{⍵∊⍺:1⋄(¯1∊×d)∨1<|+/⍟d←(⊢÷1∘⌽)⍺-⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHHV2PendZGT7qbtE4tN4QyD08PUXzUccKQ5sabf1HvfNTHrVN0HjUtejwdqDkjEc9ezWB6nWBOmv/pwGlHvX2PepqftS75lHvlkPrjR@1TXzUNzU4yBlIhnh4Bv83NMgyNFAAkkDDFQ6tN80yUEhTMMgy4IJLmBoomBpkGYHETbNMuYByChApkJhZljFUtwlUAQA "APL (Dyalog Unicode) – Try It Online")
[Taken directly from an APLcart snippet.](https://aplcart.info/?q=Is%20ns%20inside%20closed%20pol#) I'm not awfully sure of what's going on it it, and would be glad if someone could give a better explanation.
Input is taken as complex points.
Takes polygon on the left and point on the right.
## Explanation
```
{⍵∊⍺:1⋄(¯1∊×d)∨1<|+/⍟d←(⊢÷1∘⌽)⍺-⍵}
{⍵∊⍺:1 } return 1 if point is in list, otherwise:
⋄ ⍺-⍵ subtract the point from each edge
(gives all lines to from vertices to the point)
(⊢÷1∘⌽) divide it by itself rotated by 1
d← save it in d
⍟ take the natural logarithm of each point
+/ and sum the vectors
| take the modulus
(I think this gets the sum of angles)
1< check if 1 is lesser than it
∨ or
(¯1∊×d) any of the points' signums equal (-1,0)
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 92 bytes
```
l[l0$21.>&-0=n;
{$&:2-&?!v{:{:{:@*{:}@@}@@}@@*-@@+
:0$0(?$-v>]
3pl2-00.>&08
{{{{600.>&-&084p
```
Implements Neil's shoelace formula technique.
[Answer]
# Python 3, 133 bytes
Spatial packages to the rescue:
```
from shapely.geometry import*
def f(s):
c=list(map(int,s.split()))
o,*p=zip(c[::2],c[1::2])
return Point(o).intersects(Polygon(p))
```
The geometric operation to use was a small gotcha. `Polygon.contains(Point)` does not cover the edge cases.
[Answer]
# [R](https://www.r-project.org/), ~~139~~ ~~127~~ ~~118~~ 116 bytes
*Edit: -23 bytes by improving shoelace calculations thanks to goading by Giuseppe*
```
function(i,S=function(m)abs(sum(m*c(1,-1)*m[2:1,c(2:ncol(m),1)])))S(P<-matrix(i,2))==S(P[,-1])-S(P[,c(1:2,ncol(P))])
```
[Try it online!](https://tio.run/##hY7BCsIwEETv/YqAl2xJoInWQzFXz4V6K0VqrBBoUmla8O/jGmzRi8IO7A77hhmD8WfjvLl2KtxmpyczOGpYpdbDQnvx1M@W2lRTwbiA1NayEExTWTg99PjCBDQAUNHywG07jeaBIRJAKbRqZBrgccOEQrJIlYBMMO4@T0rTjBEc8SEuUDnaQDbkNM5dsnalkYIkWWh8y7/p/C0Z8WPb@/98tkwMebGM7BnZLoV2P6qE8AQ "R – Try It Online")
Implements [Neils beautiful approach](https://codegolf.stackexchange.com/questions/210004/is-it-in-the-polygon/210005#210005) of testing whether the 'slice of cake' formed by the triangle with the test-point + two perimeter points as vertices is equal in area to the area of the whole 'cake' (the test polygon) minus the area of the 'cake' with the 'slice' removed (the polygon using all points including the test point).
```
inside=
function(i)
{ # S is helper function to calculate 2x the cake area using
# the 'shoelace' formula:
S=function(m)abs(sum(m*c(1,-1)*m[2:1,c(2:ncol(m),1)])/2)
P=matrix(i,2) # 'cake with missing slice' = polygon including test point
T=P[,c(1:2,ncol(P))] # 'slice of cake' = triangle of test point + adjacent polygon vertices
O=P[,-1] # 'the cake' = outer polygon excluding test point
S(P)==S(O)-S(T) # do the areas add-up?
}
```
] |
[Question]
[
### Challenge:
Output the 'integer-digits' of one of the following six arithmetic-tables based on the input:
- addition (`+`);
- subtraction (`-`);
- multiplication (`*`);
- division (`/`);
- exponentiation (`^`);
- modulo operation (`%`).
### Rules:
* What do I define as 'integer-digits': Every result of the arithmetic operand which is exactly one of the following: `0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`. This means you *exclude* every result of `10` or higher, every result of `-1` or lower, and every non-integer result.
* ~~How do we calculate the arithmetic results: By using the top digit first, and then use the operand with the left digit.~~ You are allowed to do this vice-versa (i.e. `y/x` instead of `x/y`), as long as you're consistent for all six of the outputs! (So you aren't allowed to use `y-x` and `x/y` in the same answer.)*†*
* We won't output anything for divide by 0 test-cases (for the division and modulo operation tables)
* We won't output anything for the edge-case `0^0`.
### Output:
So output the following (table format is somewhat flexible (see below): so the lines are optional and mainly added for readability of the test cases):
Addition:
```
+ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 1 2 3 4 5 6 7 8 9
1 | 1 2 3 4 5 6 7 8 9
2 | 2 3 4 5 6 7 8 9
3 | 3 4 5 6 7 8 9
4 | 4 5 6 7 8 9
5 | 5 6 7 8 9
6 | 6 7 8 9
7 | 7 8 9
8 | 8 9
9 | 9
```
Subtraction:
```
- | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 1 2 3 4 5 6 7 8 9
1 | 0 1 2 3 4 5 6 7 8
2 | 0 1 2 3 4 5 6 7
3 | 0 1 2 3 4 5 6
4 | 0 1 2 3 4 5
5 | 0 1 2 3 4
6 | 0 1 2 3
7 | 0 1 2
8 | 0 1
9 | 0
```
Multiplication:
```
* | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 0 0 0 0 0 0 0 0 0
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0 2 4 6 8
3 | 0 3 6 9
4 | 0 4 8
5 | 0 5
6 | 0 6
7 | 0 7
8 | 0 8
9 | 0 9
```
Division:
```
/ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 |
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0 1 2 3 4
3 | 0 1 2 3
4 | 0 1 2
5 | 0 1
6 | 0 1
7 | 0 1
8 | 0 1
9 | 0 1
```
Exponentiation:
```
^ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 1 1 1 1 1 1 1 1 1
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0 1 4 9
3 | 0 1 8
4 | 0 1
5 | 0 1
6 | 0 1
7 | 0 1
8 | 0 1
9 | 0 1
```
Modulo:
```
% | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 |
1 | 0 0 0 0 0 0 0 0 0 0
2 | 0 1 0 1 0 1 0 1 0 1
3 | 0 1 2 0 1 2 0 1 2 0
4 | 0 1 2 3 0 1 2 3 0 1
5 | 0 1 2 3 4 0 1 2 3 4
6 | 0 1 2 3 4 5 0 1 2 3
7 | 0 1 2 3 4 5 6 0 1 2
8 | 0 1 2 3 4 5 6 7 0 1
9 | 0 1 2 3 4 5 6 7 8 0
```
### Challenge rules:
* Trailing new-lines and trailing spaces are optional
* The horizontal and vertical lines in the test cases are optional. I only added them for better readability.*†*
* The spaces between each result are NOT optional.
* The symbol for the arithmetic may be different, as long as it's clear which one it is. I.e. `×` or `·` instead of `*` for multiplication; `÷` instead of `/` for division; etc.*†*
And as long as it's a *single* character, so sorry Python's `**`.
* The input format is flexible. You can choose an index from 0-5 or 1-6 for the corresponding six tables; you could input the operand-symbol; etc. (Unlike what you display in the result, you are allowed to input complete strings, or `**` in Python's case.)
Just make sure to state which input-format you use in your answer!
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
*† Example of valid output without horizontal and vertical lines, `÷` as symbol, and using `y/x` instead of `x/y`:*
```
÷ 0 1 2 3 4 5 6 7 8 9
0 0 0 0 0 0 0 0 0 0
1 1
2 2 1
3 3 1
4 4 2 1
5 5 1
6 6 3 2 1
7 7 1
8 8 4 2 1
9 9 3 1
```
[Answer]
## JavaScript (ES7), 128 bytes
```
f=
c=>[...c+`0123456789`].map((r,_,a)=>a.map(l=>l==c?r:r==c?l:/^\d$/.test(l=c<`^`?eval(l+c+r):l|c?l**r:l/r)?l:` `).join` `).join`
`
```
```
<select onchange=o.textContent=f(this.value)><option>><option>+<option>-<option>*<option>/<option>%<option>^<option>&<option>,<option>.</select><pre id=o>
```
Special-casing `0^0` cost me 8 bytes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 45 bytes
*Collaborated with @ETHproductions*
```
AÆAÇU¥'p«Z«XªOvZ+U+X)+P r"..+"SÃuXÃuAo uU)m¸·
```
[Run it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=QcZBx1WlJ3CrWqtYqk92WitVK1gpK1AgciIuLisiU8N1WMN1QW8gdVUpbbi3&input=Iisi)
Takes input as:
`"+"` for addition
`"-"` for subtraction
`"*"` for multiplication
`"/"` for division
`"p"` for exponentiation
`"%"` for modulo
### Explanation (With expanded shortcuts):
```
AÆ AÇ U¥ 'p« Z« Xª OvZ+U+X)+P r"..+"SÃ uXÃ uAo uU)m¸ ·
AoX{AoZ{U=='p&&!Z&&!X||OvZ+U+X)+P r"..+"S} uX} uAo uU)mqS qR
A // By default, 10 is assigned to A
o // Create a range from [0...9]
X{ } // Iterate through the range, X becomes the iterative item
Ao // Create another range [0...9]
Z{ } // Iterate through the range, Z becomes the iterative item
// Take:
U=='p // U (input) =="p"
&&!Z // && Z != 0
&&!X // && X != 0
|| // If any of these turned out false, instead take
Ov // Japt Eval:
Z+U+X // Z{Input}X
)+P // Whichever it was, convert to a string
r"..+"S // Replace all strings of length 2 or more with " "
// (this makes sure the result !== "false" and has length 1)
uX // Insert X (the row number) into the front of the row
u // Insert at the beginning the first row:
Ao // [0...9]
uU) // with the input inserted at the beginning
mqS // Join each item in the final array with " "
qR // Join the final array with "\n"
```
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~343~~ ~~333~~ ~~303~~ 301 bytes
```
f={o=_this;s=o+" 0 1 2 3 4 5 6 7 8 9\n";i=0;while{i<10}do{j=0;s=s+format["%1",i];if(i<1&&(o=="/"||o=="%"||o=="^"))then{if(o=="^")then{if(j<1)then{s=s+" ";j=1}}else{s=s+"\n1";i=1}};while{j<10}do{r=call format["%1%2%3",j,o,i];if(r>9||r<0||r%1>0)then{r=" "};s=s+format[" %1",r];j=j+1};s=s+"\n";i=i+1};s}
```
**Call with:**
```
hint ("+" call f)
```
**Ungolfed:**
```
f=
{
o=_this;
s=o+" 0 1 2 3 4 5 6 7 8 9\n";
i=0;
while{i<10}do
{
j=0;
s=s+format["%1",i];
if(i<1&&(o=="/"||o=="%"||o=="^"))then
{
if(o=="^")then{if(j<1)then{s=s+" ";j=1}}
else{s=s+"\n1";i=1}
};
while{j<10}do
{
r=call format["%1%2%3",j,o,i];
if(r>9||r<0||r%1>0)then{r=" "};
s=s+format[" %1",r];
j=j+1
};
s=s+"\n";
i=i+1
};
s
}
```
**Output:**
[operator +](https://i.stack.imgur.com/msmGC.jpg)
[operator -](https://i.stack.imgur.com/FbwDp.jpg)
[operator \*](https://i.stack.imgur.com/QEgYd.jpg)
[operator /](https://i.stack.imgur.com/11E7L.jpg)
[operator ^](https://i.stack.imgur.com/8BRvs.jpg)
[operator %](https://i.stack.imgur.com/w9fVY.jpg)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~240~~ ~~231~~ ~~226~~ ~~224~~ ~~203~~ ~~202~~ ~~200~~ 197 bytes
```
a=i=input()
R=range(10)
for z in R:a+=' '+`z`
print a
for x in R:
try:
d=`x`
for b in R:c=eval("b%s(x*1.)"%('**',i)[i<'^']);d+=' '+(' ',`int(c)`)[(i<'^'or x+b>0)and c in R]
except:pass
print d
```
[Try it online!](https://tio.run/nexus/python2#Jc7RCoMgFMbx63yKgxBqxVa3be4huo2Gpm0Iw4m54Xr5Vnlzbn7w/84queHGuk@gDHXcS/ucaFMz9Hh7WMBY6FpZcgKkFItAzhsbQB4akyII/teiTHMRBcp2GZMoPn3li@Ixn2ksmhPDOSVFQSrDenMldzKwi05tup1KbG2qmGA9PXjfKMdbzaTVoI7mgGCKanKhdXKeEaR/9LriM/4D "Python 2 – TIO Nexus")
Takes input as one of "+", "-", "\*", "/", "^" or "%".
**Edits**
~~-9~~ -16 with thanks to @FelipeNardiBatista for some great hints
Down to 221 with more help from @FelipeNardiBatista and then down to 203 by losing `and E(c)==int(E(c))`. If we are checking if `E(c)` is in `range(10)` it will always be an integer if it is there. No need for the duplicate check.
This **has** to go below 200 without switching to Python 3 and declaring `P=print`. Any ideas? I am always happy to learn.
Yesss! I knew it could be done. 197. Time for bed now. I have spent enough time on this one. Thanks for the interesting challenge @KevinCruijssen.
[Answer]
# Mathematica, 150 bytes
```
r=0~Range~9;p=Prepend;±i_:=Grid@p[p[If[0<=#<=9,#]/._@__->""&/@<|Thread[Characters@"+-*/^%"->{Plus,#-#2&,1##&,#/#2&,Power,Mod}]|>[i][r,#],#]&/@r,r~p~i]
```
Defines a unary function `±` taking one of the characters `+-*/^%` as its input `i` (so for example, `±"^"`), and returning a `Grid` object that looks exactly like the last output in the OP.
`<|Thread[Characters@"+-*/^%"->{Plus,#-#2&,1##&,#/#2&,Power,Mod}]|>` associates, to each possible input character, the corresponding (listable) binary function (where `#-#2&,1##&,#/#2&` are golfed versions of `Subtract,Times,Divide`); therefore `<|...|>[i][r,#]` calculates the binary operation with all possible first arguments and `#` as the second argument. `If[0<=#<=9,#]/._@__->""&` converts each result to a `Null` or `""` if it's not a single-digit result (`/._@__->""` is necessary because some results like `1/0` can't be processed by the inequalities `0<=#<=9`). Finally, we prepend the various headers and footers and display the answer.
[Answer]
# Python 3, ~~343~~ ~~335~~ ~~363~~ 362 bytes
The saddest part about this is that a Java answer is beating me... I'll golf this more in the morning.
```
o=input()
r=range(10)
g=[['']*10 for i in r]
for x in r:
for y in r:exec('if"/"!=o and(o!="%"or x)and(o!="**"or x or y):k=str(y'+o+'x);g[x][y]=k')
if'/'==o:
for x in r:
for y in r:
if x and y%x<1:g[x][y]=str(round(y/x))
if'**'==o:o='^'
print('\n'.join([' '.join([o]+list(map(str,r)))]+[' '.join([str(q)]+[' 'if len(x)!=1else x for x in g[q]])for q in r]))
```
[ReplIT](https://repl.it/Gr4z/36)
-8 bytes by switching to list comprehension rather than a double loop
+28 bytes to avoid edge case `0 ^ 0`. -.-
-1 byte by changing `==0` to `<1` thanks to @StewieGriffin
[Answer]
# Java 10, ~~312~~ ~~305~~ ~~297~~ 238 bytes
```
o->{var r="+-*/^%".charAt(o)+" 0 1 2 3 4 5 6 7 8 9\n";for(int i=-1;++i<10;r+="\n"){r+=i+" ";for(double j=-1d,t;++j<10;r+=t%1!=0|t<0|t>9?" ":((int)t)+" ")t=o<1?j+i:o<2?j-i:o<3?j*i:o<4&i>0?j/i:o<5&j!=-i?Math.pow(j,i):i>0?j%i:-1;}return r;}
```
Uses no horizontal/vertical lines, and the characters are as displayed in the challenge-examples (`+-*/^%`).
Uses an index of `0-5` for the six mathematical operands as input.
-7 bytes thanks to *@Frozn*.
-8 bytes thanks to *@ceilingcat*.
**Explanation:**
```
o->{ // Method with integer parameter and String return-type
var r="+-*/^%".charAt(o) // Get the current mathematical operand character based
// on the input index
+" 0 1 2 3 4 5 6 7 8 9\n";
// Append the column header and a new-line
for(int i=-1;++i<10; // Loop `i` in the range (-1,10):
r+="\n"){ // After every iteration: append a newline to the result
r+=i+" "; // Append the left-side row-nr
for(double j=-1d,t;++j<10;
// Inner loop over the cells of the current row
r+= // After every iteration: append the result String with:
t%1!=0 // If `t` has decimal values
|t<0 // Or `t` is below 0
|t>9? // Or `t` is above 9:
" " // Append an empty cell
: // Else:
((int)t)+" ") // Append `t` as integer in the current cell
t= // Set `t` to:
o<1? // If the given operand is 0 ("+"):
j+i // Add `j` and `i` together
:o<2? // Else-if the operand is 1 ("-"):
j-i // Subtract `i` from `j`
:o<3? // Else-if the operand is 2 ("*"):
j*i // Multiply `j` by `i`
:o<4 // Else-if the operand is 3 ("/")
&i>0? // And `i` is larger than 0:
j/i // Divide `j` by `i`
:o<5 // Else-if the operand is 4 ("^")
&j!=-i? // And `j` is not `-i`:
Math.pow(j,i) // Take `j` to the power `i`
: // Else (the operand is 5 ("%")):
i>0? // If `i` is larger than 0:
j%i // Take `j` modulo-`i`
: // Else:
-1;} // Set `t` to -1 instead
return r;} // After the loops, return the result-String
```
[Answer]
# Haskell, ~~230~~ ~~199~~ 182 + ~~53~~ ~~47~~ 46 + 1 byte of separator = ~~284~~ ~~247~~ ~~232~~ 229 bytes
```
f=head.show
g=[0..9]
h=(:" ")
y(%)s=unlines$(s:map f g>>=h):[f y:[last$' ':[f(x%y)|x%y`elem`g]|x<-g]>>=h|y<-g]
0?0=10;a?b=a^b
a!0=10;a!b|(e,0)<-a`divMod`b=e|1>0=10
a&0=10;a&b=mod a b
```
Function is `(zipWith y[(+),(-),(*),(!),(?),(&)]"+-*/^%"!!)`, which alone takes up 53 bytes, where 0 is addition, 1 is subtraction, 2 is multiplication, 3 is division, 4 is exponentiation, and 5 is modulo.
[Try it online!](https://tio.run/nexus/haskell#rczJboMwEIDhu59iSFIMCRDT5RDCwLlSbj0iotjBLGKrgLSJxLtTp1X7AmUun8bW/FOKueSJ0@ftJ8nR8BawMEmGadfWr80gs45XpF@2eGmqopH9yui9iDLqOHRH4yDA3PSiFG5eVKRQ@i7T9TJABkMuG1AvIKteAgU6Xn07Yo6zi61KDlBiC1e4fRfG2@9XTFjI0HX3PBTIj4JwTa1szzUxnn07A24ld4QlfZufkuLjJKwMJOJ5m6Ac3eB@Tbj@c6ULrNsEOIip5kUDCEkL75fhbegODazAiOiGLo2NaVFbaSvXyrVyq9SUR2WofFDqZqxpJiPwN/9tuTO2HmdsPc3Yep6x9TJ9AQ "Haskell – TIO Nexus")
## Explanation
Coming later (possibly) . . . . For now some little tidbits: ? is the exponentiation operator, ! is the division operator, and & is the mod operator.
EDIT: Part of the bulk might be because most (?) of the other answers use eval, which Haskell doesn't have without a lengthy import.
EDIT2: Thanks Ørjan Johansen for -31 bytes (Wow!) off the code and -6 bytes off the function! Also changed some of the 11s to 10s for consistency purposes. [Try the updated version online!](https://tio.run/nexus/haskell#rYxLboMwFEXnXsWDpNhOgJp@BqEYNtCMOugAEcUWRrYgOCqkDRV7T2mjdgEVTzqDd@/VuVRcK1GGnbYfSHMSu@BS1C0sP7WNaVW3JF2cY4bDEG9wkaZc0zivYIhzU0GdRMzz6pQz6LVqYUpANZ0CDHg8J0HOwnBT@I3qoeYWzjD8GMbhtyoQyxiP2JPIJBc7iYRzfR05EuUzmgRiX5r3rS33kqsxSr9rJLzrypP8YEsQIC8HYVrgUFo4nvqX/u25hSWQT3N8Nb0mC@qug9Xt7sbNyZr6JJhYTTgT2YRHC8ehDMHf/d8SzWK5m8VyP4vlYRbL4@UL "Haskell – TIO Nexus")
EDIT3: Same person, seventeen more bytes! [Try the updated, updated version online!](https://tio.run/nexus/haskell#rYzLboMwEEX3/ooxAmIngZo@FqUx/EC76qILRIQtzEPipZq0oeLfqVGkfkDFSGc0V3N1loJXSuS@rvpvVPKE@f5ziipOQgssiibiUM0vXVN3SttEh60YoIAyinhFw6SAKUwaoUd7BzsTydWZ6GxWphrVZmU6X09ema7teVovxGLGA/YiYsnFWSKBbxHLmagjoydPZHn99dbnmeRqDqL1jYR7a7mSt30OAuTSiroDDnkPw2V8Hz9fO7CB/NTDRz1WMCXkQI/EM@wN2BAbXJpaB29/d3YsjClD8Df/lgRbSO63kDxsIXncQvK0/AI "Haskell – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), 197 bytes
```
p=input()
r=range(10)
s=' '
print p+s+s.join(map(str,r))
for i in r:print str(i)+s+s.join(eval(("s","str(j"+p+"i)")[i and(j%i==0 and'/'==p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r])for j in r)
```
[Try it online!](https://tio.run/nexus/python2#RY7BCsIwEETv@YolULLbVK1XIV8iHgJW2aDpsqn@fk2q4G3gDW9mlcBZXguS0aAx3yc8jmRKcOCMKOcFxBdf9mnmjM8oWBYdlMjcZgUGzqCnb68CZPqXp3d8INpiB9tQsl68ZbJ0Zoj5iqnjEMYW3cGFIDCr61qgapZqdn3vd65y2FT2Z7DURi/UDqTtAK1rVXwA "Python 2 – TIO Nexus")
**Input: Python 2**
`'+'` Addition
`'-'` Sbtraction
`'*'` Multiplication
`'/'` Division
`'**'` Exponentiation
`'%'` Modulo
# [Python 3](https://docs.python.org/3/), 200 bytes
```
p=input()
r=range(10)
s=' '
print(p+s+s.join(map(str,r)))
for i in r:print(str(i)+s+s.join(eval(("s","str(j"+p+"i)")[i and(j%i==0 and'/'in p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r])for j in r))
```
[Try it online!](https://tio.run/nexus/python3#RY7BCsIwEETv@YqwUHa3qVqvQr5EPASsskHTJan@fk2q4G1gHm9mVS9JXwuxyT6HdJ/oOLIpHi0azZIWUldc2cdZEj2DUlnykJnZ3OZsxUqy@fQFa0PCf3p6hwcRFBigVRGcOhAGPosN6UqxE@/HFvGA1aN2ztih98pVrVWNfe92WAG7ueCnAG6rF24P4vaAeV37Dw "Python 3 – TIO Nexus")
**Input: Python 3**
`+` Addition
`-` Sbtraction
`*` Multiplication
`//` Division
`**` Exponentiation
`%` Modulo
# Explanation
storing `range(10)` to a variable `r`, we can get the first line of output of the format
```
operator 0 1 2 3 4 5 6 7 8 9
```
by mapping every int in `r` to string and joining the string list`['0','1','2','3','4','5','6','7','8','9']` with space `s` with `p` operator
```
p+s+s.join(map(str,r)
```
With that,
for every `i` in `r`(range), for every `j` evaluate `i` and `j` with your operator
```
eval("j"+p+"i")
```
here, an exception might be thrown if unhandled - division or modulus by 0. To handle this case(`i and(j%i==0 and'/'==p or'%'==p)`) and the output format by described in the problem statement(the result for each evaluation shouldn't be a negative number nor a number greater than 10 - `eval("j"+p+"i")in r`),
```
i and(j%i==0 and'/'==p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r
```
Thus printing the arithmetic-table!
Happy Coding!
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~68~~ 76 bytes
Requires `⎕IO←0` which is default on many systems. Prompts for input and expects a single character representing the operand.
```
t←'|'=w←⎕
(w,n),n⍪⍉⍣t∘.{(⍺w⍵≡0'*'0)∨(t∧⍵≡0)∨⍺w≡0'÷':⍬
n∊⍨r←⍵(⍎w)⍺:r
⍬}⍨n←⍳10
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wQDrkcd7Wn/S4BM9Rp123IgDZTi0ijXydPUyXvUu@pRb@ej3sUljzpm6FVrPOrdVf6od@ujzoUG6lrqBpqPOlZoAKWWQ8VAfLASkPzh7epWj3rXcOU96uh61LuiCGRy71agEX3lmkBFVkVcQNlaoEweWGazocF/oFP@p3Gpa6tzAUldMHl4OoTaDqa0wGSNOgA "APL (Dyalog Unicode) – TIO Nexus")
Much of the code is to circumvent that APL's results for `÷0` and `0*0` and to counteract that APL's modulo (`|`) has its arguments reversed compared to most other languages. Would have been only **41 bytes** otherwise:
```
w←⎕
(w,n),n⍪∘.{0::⍬
÷n∊⍨r←⍵(⍎w)⍺:r}⍨n←⍳10
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wQDrkcd7Wn/y4FMoBCXRrlOnqZO3qPeVY86ZuhVG1hZPepdw3V4e96jjq5HvSuKQMp6t2o86u0r13zUu8uqqBYomgcW3Wxo8B9o1v80LnVtdS4gqQsmD0@HUNvBlBaYrFEHAA "APL (Dyalog Unicode) – TIO Nexus")
[Answer]
# [R](https://www.r-project.org/), ~~194~~ 177 bytes
*-17 bytes switching to manipulating matrix output*
```
function(o){s=0:9
y=sapply(s,function(x)Reduce(o,x,init=s))
dimnames(y)=list(s,rep('',10))
y[!y%in%s|!is.finite(y)]=' '
if(o=='^')y[1]=' '
cat(substr(o,1,1),s)
print(y,quote=F)}
```
[Try it online!](https://tio.run/##Xc3PTsMwDAbwe59iO1SOIYP2OCRfeQBOSNsq9U9aWdqSEqdi0eDZuwASh9ysn7/P9utE67jYPrCzyuFNqHrZF5GknedzVKL/l1d8M8PSG@X0VbPlQIJYDHyx7cWIikhnlpAa3swKQNdVWsfDNpZsS/nasjyNPzWToieCDRQ8KkcEDWA81H/Ut@nC0knw6U2ta9SCxezZBhX1x@KCoVf8XicFZQn4G4ejTVOS5xwec9jl8JBDk0PH4fPdecD1Dg "R – Try It Online")
Changing to this approach has some downsides, namely it can't be optimised by using `pryr` and is a little clunky to set up the original matrix, but it can be output perfectly with some trailing spaces on the first line.
I still have to use the `substr` trick because of the `%%` mod operator. Will continue to trim this when I get a chance, it still feels very clunky dealing with the special cases.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~37~~ 35 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
*Look, Ma, no `eval`!*
Was hoping to do a little better than [Oliver](https://codegolf.stackexchange.com/a/115047/58974) than this but special-casing `0**0` kicked my ass. Will take another pass at it later on see if I can make any further improvements.
Uses `p` for exponentiation. Tables are transposed for subtraction, division and modulo.
```
Ao
ïNg)£øX «Nø²|Y?X:SÃòA íi iUiN)m¸
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QW8K705nKaP4WCCrTviyfFk/WDpTw/JBIO1pIGlVaU4pbbg&input=Iisi) (or use [this version](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QW8K705nKaP4WCCrTviyfFk/WDpTw/JBINXtaSBpVWlOKa5pfDHDabBUMjPnLSltuA&input=Iisi) to see the transposed tables with dividing lines, as they appear in the spec) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QW8K71c9Z1Ypo/hYIKtX%2bLJ8WT9YOlPD8kEg1e1pIGlVaVcpbbg&footer=UmlWtw&input=WyIrIiAiLSIgIioiICIvIiAicCIgIiUiXQotbQ) (with transposed tables).
```
Ao\nïNg)£øX «Nø²|Y?X:SÃòA íi iUiN)m¸ :Implicit input of string U
A :10
o :Range [0,A)
\n :Reassign to U
ï :Cartesian product with itself reduced by
N : Array of all inputs
g : First element (the original input string)
) :End Cartesian product
£ :Map each X at 0-based index Y
øX : Does U contain X
« : Logical AND with logical NOT of
Nø : Does N contain
² : "p"
|Y : Bitwise OR with Y
?X : If truthy, return X
:S : Else return space
à :End map
òA :Partitions of length U
í :Pair with 0-based indices
i : Prepend index to array
i :Prepend
UiN : U prepended with N
) :End prepend
m :Map
¸ : Join with spaces
:Implicit output, joined with newlines
```
[Answer]
# PHP, 191 Bytes
`**` instead of `^` as input `+ - / % * **`
```
echo$k=$argn,$k=="**"?"":" ",join(" ",$d=range(0,9));foreach($d as$r){echo"\n$r";foreach($d as$c){echo" ";($k=="/"|($m=$k=="%"))&$r<1?print" ":eval("echo in_array($c$k$r,\$d)?$c$k$r:' ';");}}
```
[Online Version of both Versions](http://sandbox.onlinephpfunctions.com/code/b2e4a0f8ac0f60ff7e1a5ad38600a05af6425c42)
## PHP, 245 Bytes without eval
input `+ - / % * ^`
use `bcpowmod($c,1,$r)` instead of `bcmod($c,$r)` because I need a third parameter in the division input. `$c**1%$r==$c%$r`
[BC Math Functions](http://php.net/manual/en/ref.bc.php)
```
echo$k=$argn," ".join(" ",$d=range(0,9));foreach($d as$r){echo"\n$r";foreach($d as$c)echo" ",in_array($s=($k=="/"|($m=$k=="%"))&$r<1?-1:("bc".["+"=>add,"-"=>sub,"/"=>div,"*"=>mul,"^"=>pow,"%"=>powmod][$k])($c,$m?1:$r,$m?$r:9),$d)?round($s):" ";}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~56~~ 55 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
9ÝDãεðýì„/%Iåyθ_*I'mQyO_*~iðë.VD9ÝQàiïëð]«TôεN<š}®I:ðý»
```
Outputs without lines and with reversed `x` and `y`. Input/output are using `+`, `-`, `*`, `/`, `m`, `%`.
[Try it online](https://tio.run/##yy9OTMpM/f/f8vBcl8OLz209vOHw3sNrHjXM01f1PLy08tyOeC1P9dzASv94rbpMoORqvTAXoNrAwwsyD68/vPrwhthDq0MObzm31c/m6MLaQ@s8rUAmHNr9/78@AA) or [verify all tables](https://tio.run/##yy9OTMpM/a@krauln6uqVFYZ9t/y8FyXw4vPbT284fDeyOLDax41zNNXjTy8tPLcjnitSPXcwEr/eK26TKD0ar0wF6DqwMMLMg@vP7z68Iba2tpDq0MObzm31c/m6MLaQ@sirUCmHNr9X@fQNvv/AA).
21 bytes are used to fix edge cases `/0`, `%0` and `0^0`, which result in `0`, `0`, and `1` respectively in 05AB1E.. Here without that part (**34 bytes**):
```
9ÝDãεðýì.VD9ÝQàiïëð]«TôεN<š}®I:ðý»
```
[Try it online](https://tio.run/##yy9OTMpM/f/f8vBcl8OLz209vOHw3sNr9MJcgAKBhxdkHl5/ePXhDbGHVocc3nJuq5/N0YW1h9Z5WoGUHdr9/78@AA) or [try all tables](https://tio.run/##yy9OTMpM/a@krauln6uqVFYZ9t/y8FyXw4vPbT284fDeyOLDa/TCXIBCgYcXZB5ef3j14Q21tYdWhxzecm6rn83RhbWH1kVagVQe2v1f59A2@/8A).
**Explanation:**
```
9Ý # Push list [0,1,2,3,4,5,6,7,8,9]
D # Duplicate it (for the header later on)
ã # Take the cartesian product with itself (creating all pairs):
# [[0,0],[0,1],[0,2],...,[9,7],[9,8],[9,9]]
ε # Map each pair `y` to:
ðý # Join the pairs with a space
ì # Prepend it before the (implicit) input-char
„/%Iå # If the input is "/" or "%"
* # and
yθ_ # The last value of the pair is exactly 0
~ # OR
I'mQ '# If the input is "m"
* # and
yO_ # The sum of the pair is exactly 0 (thus [0,0])
i # If that is truthy:
ð # Push a space character " "
ë # Else:
.V # Execute the string as 05AB1E code
D # Duplicate the result
9ÝQài # If it's in the list [0,1,2,3,4,5,6,7,8,9]:
ï # Cast it to an integer to remove any trailing ".0"
# (since dividing always results in a float)
ë # Else:
ð # Push a space character " "
] # Close both the if-else clauses and the map
« # Merge the resulting list with the duplicated [0,1,2,3,4,5,6,7,8,9]
Tô # Split the list in parts of size 10
ε } # Map each list to:
N< # Get the map-index + 1
š # And prepend it at the front of the list
®I: # Then replace the "-1" with the input-character
ðý # And finally join every inner list by spaces
» # And join the entire string by newlines (which is output implicitly)
```
] |
[Question]
[
**Write a function f(n,k) that displays the k-dimensional countdown from n.**
A 1-dimensional countdown from 5 looks like
```
54321
```
A 2-dimensional countdown from 5 looks like
```
54321
4321
321
21
1
```
Finally, a 3-dimensional countdown from 5 looks like
```
54321
4321
321
21
1
4321
321
21
1
321
21
1
21
1
1
```
## Formal definition
The 1-dimensional countdown from any n is a single line with the digits n, n-1,...,1 concatenated (followed by a newline).
For any k, the k-dimensional countdown from 1 is the single line
```
1
```
For n > 1 and k > 1, a k-dimensional countdown from n is a (k-1)-dimensional countdown from n followed by a k-dimensional countdown from n-1.
## Input
Two positive integers k and n <= 9, in any format you choose.
## Output
The k-dimensional countdown from n, with a newline after each 1-dimensional countdown. Extra newlines are permitted in the output.
## Scoring
Standard golf scoring.
## Bonus example
Here's an example with k > n, a 4-dimensional countdown from 3 (with extra comments that are not to be included in actual solutions):
```
-- 3-dimensional countdown from 3
321
21
1
21
1
1
-- 4-dimensional countdown from 2:
---- 3-dimensional countdown from 2:
21
1
1
---- 4-dimensional countdown from 1:
1
```
**Clarifications:**
Digits on a line do not need to be adjacent, but they must be evenly-spaced.
You may write a full program instead of just a function, if you prefer.
[Answer]
# Python, 60 bytes
```
f=lambda n,k:n>1<k and f(n,k-1)+f(n-1,k)or'987654321\n'[~n:]
```
Test it on [Ideone](http://ideone.com/8vYOFe).
### How it works
The ***k***-dimensional countdown from **n** can be defined with a single base case:
>
> If **n = 1** or **k = 1**, the output is **n || n-1 || ... || 1 || ¶**, where **||** indicates concatenation.
>
>
>
Using the recursive definition from the question, `f(n,k)` returns `f(n,k-1)+f(n-1,k)` if **n > 1** and **k > 1**; otherwise it returns the last **n + 1** characters from `'987654321\n'`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R¡UḌFṚp⁷
```
This is a full program that expects **n** and **k** as command-line arguments.
[Try it online!](http://jelly.tryitonline.net/#code=UsKhVeG4jEbhuZpw4oG3&input=&args=NQ+Mw)
### How it works
```
R¡UḌFṚp⁷ Main link. Left argument: n. Right argument: k
¡ Repeat the link to the left k times.
R Range; map each integer j in the previous return value to [1, ..., j].
U Upend; reverse each 1-dimensional array in the result.
Ḍ Undecimal; convert each 1-dimensional array from base 10 to integer.
F Flatten the resulting array.
Ṛ Reverse the result.
p⁷ Cartesian product with '\n'. (Join is weird for singleton arrays.)
```
[Answer]
# Javascript, 40 38 37 bytes
Saved 1 bytes thanks to @edc65:
```
f=(n,k)=>k*n?f(n,k-1)+f(n-1,k):n||`
`
```
*Previous answers*
38 bytes thanks to @Neil:
```
f=(n,k)=>k&&n?f(n,k-1)+f(n-1,k):n||`
`
```
40 bytes:
```
f=(n,k)=>k&&n?f(n,k-1)+f(n-1,k):n?n:'\n'
```
[Answer]
# Python, ~~76~~ 75 bytes
-1 byte thanks to @Sp3000
```
c=lambda n,k:k>1and'\n'.join(c(n-i,k-1)for i in range(n))or'987654321'[-n:]
```
Caries out the procedure as described in the OP: joins the decreasing `n` results for `k-1` on newlines with a base of the recursion of the `'n...1'` string when `k` is `1` (`k` not greater than `1` since we are guaranteed positive `k` input).
Test cases on [**ideone**](http://ideone.com/xHnZeB)
[Answer]
# Python, ~~86~~ ~~81~~ 80 bytes
```
o=lambda d,n:"987654321"[-n:]if d<2else"\n".join([o(d-1,n-x) for x in range(n)])
```
`d` is the number of dimensions, `n` is the countdown number.
Will post an explanation soon.
EDIT #1: Changed it to lambda.
EDIT #2: Saved 1 byte thanks to @DestructibleWatermelon.
[Answer]
## Haskell, 57 bytes
```
n#1='\n':(show=<<[n,n-1..1])
1#_=1#1
n#k=n#(k-1)++(n-1)#k
```
Usage example: `5 # 3` -> `"\n54321\n4321\n321\n21\n1\n4321\n321\n21\n1\n321\n21\n1\n21\n1\n1"`.
A direct implementation of the definition.
[Answer]
# Racket 215 bytes
```
(define(g n k(s(number->string n)))(cond [(< k 2) n]
[else(define o(for/list((i(string-length s)))
(string->number(substring s i))))(for/list((x o))(g x(- k 1)))]))
(define(f n k)(for-each println(flatten(g n k))))
```
Testing:
```
(f 54321 3)
54321
4321
321
21
1
4321
321
21
1
321
21
1
21
1
1
```
[Answer]
# J, ~~38~~ ~~37~~ 32 bytes
```
a:":@>@-.~&,0<@-."1~0&(](-i.)"0)
```
This is a function that takes *k* on the LHS and *n* on the RHS.
Saved 5 bytes with ideas from @Adám.
## Usage
```
f =: a:":@>@-.~&,0<@-."1~0&(](-i.)"0)
3 f 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
4 3 2 1
3 2 1
2 1
1
3 2 1
2 1
1
2 1
1
1
```
## Explanation
```
a:":@>@-.~&,0<@-."1~0&(](-i.)"0) Input: k on LHS, n on RHS
0&( ) Repeat k times on initial value n
( )"0 For each value x
i. Make the range [0, x)
- Subtract x from each to make the range [x, 1]
] Return the array of ranges
0 -."1~ Remove the zeros from each row
<@ Box each row
&, Flatten the array of boxes
a: -.~ Remove the empty boxes
>@ Unbox each
":@ Convert it into a string and return
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 18 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Prompts for **n**, then for **k**.
```
~∘'0'⍤1⍕(⌽⍳)⍤0⍣⎕⊢⎕
```
`~∘'0'⍤1` remove (`~`) the (`∘`) zeros (`'0'`) from the rows (`⍤1`) (padding with spaces as needed) of
`⍕` the character representation of
`(⌽⍳)⍤0⍣⎕` the reversed (`⌽`) count until (`⍳`) each scalar (`⍤0`), repeated (`⍣`) input (`⎕`) times
`⊢` on
`⎕` numeric input
[TryAPL online!](http://tryapl.org/?a=%28%7E%u2218%270%27%u23641%u2355%28%u233D%u2373%29%u23640%u23633%u22A23%29%20%28%7E%u2218%270%27%u23641%u2355%28%u233D%u2373%29%u23640%u23633%u22A22%29%20%28%7E%u2218%270%27%u23641%u2355%28%u233D%u2373%29%u23640%u23634%u22A21%29&run)
[Answer]
# C 93 Bytes
Iterative implementation.
```
m,i,j;f(n,k){for(;m<k+2;m++)for(j=0;j<n;j++){for(i=m;i<n-j;i++)printf("%d",n-j-i);puts("");}}
```
# C ~~67~~ ~~65~~ ~~61~~ ~~56~~ 52 Bytes
Recursive implementation
```
f(n,k){n*k?f(n,k-1)+f(n-1,k):puts("987654321"+9-n);}
```
[Answer]
## Batch, 117 bytes
```
@setlocal
@set/an=%1-1,k=%2-1,p=n*k,s=987654321
@if %p%==0 (call echo %%s:~-%1%%)else call %0 %1 %k%&call %0 %n% %2
```
Port of Dennis♦'s Python answer.
[Answer]
## Ruby, 56 bytes
```
f=->n,k{n>1&&k>1?[f[n,k-1],f[n-1,k]]:[*1..n].reverse*""}
```
### Usage
When you display any solutions, you should use "Kernel#puts".
Example:
```
puts f[9,3]
```
] |
[Question]
[
This challenge is simple, given a decimal number, convert to binary, and calculate the sum of the sub-strings of the binary number, whose length is shorter than the original number. Here is an example:
```
Input:
11
Binary:
11 -> 1011
Substrings:
101 = 5
011 = 3
10 = 2
01 = 1
11 = 3
1 = 1
0 = 0
1 = 1
1 = 1
Sum:
5+3+2+1+3+1+0+1+1=17
Output:
17
```
Your program should take a single decimal integer as input and output the sum of the binary sub-strings, as seen above. You may assume the input will always have more than two digits in its binary representation and that in input will not cause any errors during your program's execution.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins!
Test cases:
```
2 => 1
3 => 2
4 => 3
5 => 5
6 => 7
7 => 9
8 => 7
9 => 10
10 => 14
11 => 17
```
[Answer]
# Jelly, ~~10~~ 7 bytes
```
BṡRḄFS_
```
[Try it online!](http://jelly.tryitonline.net/#code=QuG5oVLhuIRGU18&input=&args=MTE)
### How it works
```
BṡRḄFS_ Main link. Input: n
B Convert n to base 2.
R Yield [1, ..., n].
ṡ Get all overlapping slices of lengths 1 to n.
This yields empty arrays if the slice size is longer than the binary list.
Ḅ Convert each binary list to integer.
F Flatten the resulting, nested list.
S Compute the sum of the result.
_ Subtract n from the sum.
```
[Answer]
# Pyth, 10
```
sPiR2.:.BQ
```
[Try it online](http://pyth.herokuapp.com/?code=sPiR2.%3A.BQ&input=11&test_suite_input=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=sPiR2.%3A.BQ&input=11&test_suite=1&test_suite_input=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11&debug=0)
### Explanation:
```
sPiR2.:.BQ ## Q = eval(input())
.BQ ## get binary string of Q
.: ## get all substrings of that
iR2 ## convert them all to base 10
sP ## sum all but the last element, which is the input number
```
[Answer]
# CJam, ~~27~~ 21 bytes
Shoutout to Dennis for helping me save 6 bytes!
```
q~:Q{)Q2bew2fb~}%1bQ-
```
Works only with the newest version of CJam (available on TIO). [Try it online](http://cjam.tryitonline.net/#code=cX46UXspUTJiZXcyZmJ-fSUxYlEt&input=MTE)!
**Old version:**
```
qi2b_,,0-\f{ew}{{2b}%}%e_:+
```
[Try it online](http://cjam.aditsu.net/#code=qi2b_%2C%2C0-%5Cf%7Bew%7D%7B%7B2b%7D%25%7D%25e_%3A%2B&input=11).
[Answer]
## Python 3, 111 characters
```
N=bin(int(input()))[2:];L=len(N);r=range;print(sum(int(n,2)for n in[N[j:j+i]for i in r(1,L)for j in r(L-i+1)]))
```
**EDIT**: Explanation:
```
N=bin(int(input()))[2:]
```
Convert input string to an int, then the int to a binary string and remove its first two characters, since the `bin` method returns a string in the format of `0b...`
Take all substrings of the binary string, convert them to decimal using `int(n, 2)` and sum them.
```
[N[j:j+i]for i in r(1,L)for j in r(L-i+1)]
```
is a list of all substrings. Ungolfed version:
```
def all_substrings(N):
result = []
for i in range(1, len(N)):
for j in range(len(N) - i + 1):
result.append(N[j:j+i])
return result
```
Hope this helps.
[Answer]
## CJam (22 bytes)
This is one byte longer than the current best CJam answer, but the approach can probably be adapted to some other languages quite profitably.
```
3,ri_2b_,,:).*\+fbW%:-
```
[Online demo](http://cjam.aditsu.net/#code=3%2Cri_2b_%2C%2C%3A).*%5C%2BfbW%25%3A-&input=11)
### Analysis
Suppose that the question were
>
> calculate the sum of the sub-strings of the binary number
>
>
>
without the bit
>
> whose length is shorter than the original number
>
>
>
Then it's not too hard to show that the most significant bit occurs with total weight `1*(2^B-1)` where `B` is the number of bits; the second-most significant bit occurs with total weight `2*(2^(B-1)-1)`; down to the Bth-most significant bit, which occurs with total weight `B*(2^1-1)`.
Taking into account now the subtraction of the original number, `x`, we end up with the sum
```
sum_i (x & 2^i) * 2^i * 2*(B-i) - sum_i (x & 2^i) * (B-i) - x
```
### Dissection
```
3, e# Put [0 1 2] on the stack - we'll need it later
ri_ e# Get the input x and copy it
2b e# Convert the copy to base 2
_,,:).* e# Pointwise multiply by 1 plus the index
\+ e# Append x to the resulting array, giving A
fb e# Map a base conversion
W%:- e# Reverse and fold a subtraction
```
The conversion to base 2 gives the first part of the main sum plus `x`; to base 1 gives the second part plus `x`; and to base 0 gives just `x`, so subtracting the base-1 from the base-2 the `x`s cancel, and subtracting the base-0 gives the desired result.
[Answer]
## JavaScript (ES6), 78 bytes
```
n=>[...n.toString(2)].map(c=>[...s+=c].map((_,i)=>n-='0b'+s.slice(i)),s='')|-n
```
The outer `map` builds up leading substrings of `n`'s binary representation; the inner one extracts trailing substrings of the leading substrings, thus covering all possible substrings, including the original binary representation.
Each substring is converted from binary back to decimal and subtracted from the original input as this is slightly shorter than adding them together and subtracting the original input.
[Answer]
# C, 71 bytes
```
f(n){int a=0,m=0,i;for(;++m<n;m+=m)for(i=n;i+i>m;i/=2)a+=i&m;return a;}
```
We maintain an accumulator `a` and mask `m`. The mask starts at 1 and gets one bit longer each time around the outer loop. In the inner loop, a copy `i` of the input is successively shifted right until it is shorter than the mask, accumulating the masked value each time.
### Test program
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
while (*++argv) {
int n = atoi(*argv);
printf("%d -> %d\n", n, f(n));
}
return 0;
}
```
### Test output
```
./73793 $(seq 0 11)
0 -> 0
1 -> 0
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 7
7 -> 9
8 -> 7
9 -> 10
10 -> 14
11 -> 17
```
[Answer]
# Mathematica, ~~73~~ 70 bytes
```
Tr[FromDigits[#,2]&/@StringCases[#~IntegerString~2,__,Overlaps->All]]&
```
Function. Integer->Integer
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 53 bytes
```
$\=-$_;$_=sprintf'%b',$_;/.*(?{$\+=oct"0b$&"})(?!)/}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlZXJd5aJd62uKAoM68kTV01SV0HKKKvp6VhX60So22bn1yiZJCkoqZUq6lhr6ipX1v9/7@h4b/8gpLM/Lzi/7q@pnoGhgb/dQsA "Perl 5 – Try It Online")
```
-p # <cli> Read input and output result automatically
$\=-$_; # This method will count the full length entry, need to offset that
$_=sprintf'%b',$_; # Convert input to a binary string
/ # Pattern match
.* # Any number of characters
(?{ # Execute code, within this pattern match
$\+= # Add to the result
oct"0b$&" # What has been matched, converted to decimal
})
(?!) # Look ahead, do not match anything
/
}{ # Close the implicit loop, suppressing output of $_, but outputting $\
```
The key part is the `(?!)` in the pattern match. It forces the match to fail, causing the system to backtrack and try again. However, the code block within the match has already executed before this check, so the candidate match will be added to our total.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 64
```
.*
$*
+`(1+)\1
$1a
a1
1
r&!M`.*
&!M`.*
^.*
+`1(a*)\b
a$.1$*1;
;
```
[Try it online!](http://retina.tryitonline.net/#code=LioKJCoKK2AoMSspXDEKJDFhCmExCjEKciYhTWAuKgomIU1gLioKXi4qCgorYDEoYSopXGIKYSQuMSQqMTsKOw&input=MTE)
A high level stage by stage description: convert decimal to unary, unary to binary, get prefixes, get suffixes of prefixes, dump the original number, convert binary to unary, return count. I'll write a more detailed description once I'm done golfing, a lot of these stages seem suspicious...
[Answer]
**C#, 148 bytes**
```
int x(int i){int s,r=0,j=i,p=System.Convert.ToString(i,2).Length+1,k;for(;--p>-1;){k=j;s=-1;for(;++s<p;)r+=(k>>=1);j=(i&((1<<p-1)-1))<<1;}return r;}
```
Or, if I add Import "using static System.Math;" then 138 with
```
int x(int i){int s,r=0,j=i,p=(int)Round(Log(i,2)+1.49,0),k;for(;--p>-1;){k=j;s=-1;for(;++s<p;)r+=(k>>=1);j=(i&((1<<p-1)-1))<<1;}return r;}
```
OOP languages like C# won't win such a race, but I wanted to try it anyway. Here is a more beautified version + tester.
```
class Program
{
// Tester: 50 bytes
static void Main(string[] args)
{
int i=2;
do System.Console.WriteLine($"{i} -> {x(i++)}"); while (i < 12);
System.Console.Read();
}
// Function: 65 bytes (size according to ILDASM.exe)
static int x(int iOrg)
{
int pos, shift, retVal=0, iPrev=iOrg, iTemp;
pos = System.Convert.ToString(iOrg, 2).Length;
do {
iTemp = iPrev; shift = 0;
do retVal += (iTemp >>= 1); while (++shift < pos);
iPrev = (iOrg & ((1 << pos - 1) - 1)) << 1;
} while (--pos > -1);
return retVal;
}
}
```
The nested do-while adds the right-shifted value of iTemp (after assigning it) as long as shift+1 is smaller then pos.
The next line calculates the next shifted value of iPrev
```
x1 = 1 << p -1; // 1 << 4 -1 = 8 [1000]
x2 = x1 - 1; // 8 - 1 = 7 [0111]
x3 = i & x2; // 1011 & 0111 = 0011
x4 = x3 << 1; // 0011 << 1 = 00110
i2 = x4;
```
x1 und x2 calculate the mask, x3 applies it and then left-shifts it, since the last digit is always dropped. For 11, it looks like this:
```
START -> _1011[11]
101
10
1 --> X0110[6], r=0+5+2+1=8
011
01
0 --> XX110[6], r=8+4=12
11
1 --> XXX10[2], r=12+4=16
1 -> XXXX0[X], r=16+1=17
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `s`, 6 bytes
```
bṢḶṪᵛB
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJzIiwiIiwiYuG5ouG4tuG5quG1m0IiLCIiLCIxMSIsIjMuNC4yIl0=)
[Answer]
## PowerShell v2+, 138 Bytes
```
param($a)$a=[convert]::ToString($a,2);(($b=$a.length-1)..1|%{$l=$_;0..($b-$l+1)|%{[convert]::ToInt32($a.substring($_,$l),2)}})-join'+'|iex
```
Ooof. That conversion to/from binary is expensive.
Takes input `$a`, then uses the [.NET call `[convert]::ToString($a,2)`](https://msdn.microsoft.com/en-us/library/14kwkz77(v=vs.110).aspx) to turn it into the binary representation. From there, we go through two loops -- the first counts backwards from the end of the string down to `1`, and the second counts upward from `0`. (The first is how long of a substring to pull out, and the second is the index of where in the string to start the substring.) We set a helper `$l` along the way to pass that through to the inner loop.
Inside the inner loop, we use another [.NET call `[convert]::ToInt32()`](https://msdn.microsoft.com/en-us/library/1k20k614(v=vs.110).aspx) to convert the appropriate `.substring()` from base `2` into an integer. Each of those is then left on the pipeline. We encapsulate all of that with parens `()` and `-join` them together with a `+`, then toss that off to `iex` (short for `Invoke-Expression` and similar-ish to `eval`).
I *think* this technically requires v2 or newer to properly call the .NET calls.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
n¢ã xÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bqLjIHjN&input=MTE)
```
n¢ã xÍ
n The input subtracted from:
¢ The input as a binary string
ã Substrings, including the original string
x Sum this list after mapping each substring to:
Í It converted to decimal
```
The `n` is only necessary because `ã` includes the original string.
It should be 5 bytes:
```
n¢ãÍx
```
As according to the docs, when passed a function `f`, `ã` “returns all substrings of `S` after passing each through `f`.”
But there's a bug in the interpreter, and Japt isn't maintained anymore, so 6 bytes it is.
[Answer]
# [Scala 2](https://www.scala-lang.org/), 156 bytes
A port of [@DW.com's C# answer](https://codegolf.stackexchange.com/a/74043/110802) in Scala.
156 bytes, it can be golfed more.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=PY_RSsMwFIbv9xSHMSRhtLO7kqUpqFcDheHwSnYR12weaZOSZLq19En0Yl7oO-1FvDZLixDy5z_5OPz_x49di0JMj6df_fwq1w7uBSpoBgC53EDpDRFma2dwbYw4PC2dQbVd0Rk8KnTAAwnwJgygd9Pgct2PASqPu0IROxwhRBmMmj1B2g5p_48w5pAE08L7CxYSCEIKybQjQroYdbx0-VzFRor8DpUkFCYTcBpKLHENy4N1soxvtbK6kPGDpzyx0QYqsbM-sN_VDgbnnAXsZ2SuHM_8RYF_79wmujp9Is-ac4uK-7ncShM7fYNKmENX2aeOLdaSnSHLL4OaXhccg9be57qp-YLZ_pllPGFmzGtmxzxpQ0Vi04qyBSd4QUiSplWUUH9omiasiv6pKgM_ZabtMn71ejx2-gc)
```
i=>{var p=Integer.toBinaryString(i).size;var s=0;var r=0;var P=i;var z=0;do{z=P;s=0;do{z>>=1;r+=z;s+=1}while(s<p);P=(i&((1<<p-1)-1))<<1;p-=1}while(p> -1);r}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZVLLSsNAFAWX_YpDKZKhJDVdSWkD6qqgKFbdiIuxmaQjyUyYmbaWki9x40Y_yq9xMnmUahYD99xzT859fHzrJc3o-PPza20S__znZCtf39jS4IZygX0PiFmC3AYeVame4EIpunteGMVF-kImeBTcYOaYwIYqcBuNXRTLBgYKSzeZ8HR_wOFHGOzfPU7KPmnyHMMZQheU2K54xuBxTBGOa4ZzGXAZLEw8F4FiNL7mgnkEoxGMRM5zvsRipw3LgysptMxYcG9ZlpFIhYKutTVstcpe05M1cKvSCebCEPcedVFIbWOLspSpwMhLLqja1W27QhJkTKRm1VXoFU8qjbMOUcw80ewI4neKbSxSKRzAB5YXjvZ3bG3GlTXY8X-O6G1BFLXDrL7Ghh2wy3Z4LTQ8ULvJ15lpNYRuQY1x1ztO4Xkhpo4BHyFxD6mQVsxl_u20QiP4YS1bO3NLKev7a86wPcdf)
```
object Main {
def main(args: Array[String]): Unit = {
var i = 2
do {
println(s"$i -> ${x(i)}")
i += 1
} while (i < 12)
scala.io.StdIn.readLine() // to mimic System.Console.Read() for pausing
}
def x(iOrg: Int): Int = {
var pos = Integer.toBinaryString(iOrg).length
var shift = 0
var retVal = 0
var iPrev = iOrg
var iTemp = 0
do {
iTemp = iPrev
shift = 0
do {
iTemp >>= 1
retVal += iTemp
shift += 1
} while (shift < pos)
iPrev = (iOrg & ((1 << pos - 1) - 1)) << 1
pos -= 1
} while (pos > -1)
retVal
}
}
```
] |
[Question]
[
# Appended Numbers Game
Write a function/program that takes 2 integer parameters *integer parameters or integer variables*, a start number, and a max iterations count. The code should perform the following game example to construct a new number, and repeat until the number is a single digit left. eg.
```
3 7 2 = (3 + 7) & (7 + 2) = 10 9
1 0 9 = (1 + 0) & (0 + 9) = 1 9
1 9 = (1 + 9) = 10
1 0 = (1 + 0) = 1
```
Basically, taking each individual digit and adding it to its neighbour, then appending the result of the next addition as well.
Max iteration count is to safeguard infinite loops, and when the max is hit, code should dump the last 5 number steps. The same output should occur when finishing by reaching a single digit. If less than 5 steps occurred, only output the valid numbers.
Output should appear like (`Step: Number`) including the last 5 steps of the finished or terminated steps:
`func(3541, 50)` would produce this exact output format:
```
6: 1411
7: 552
8: 107
9: 17
10: 8
```
`func(3541, 5)` would produce:
```
1: 895
2: 1714
3: 885
4: 1613
5: 774
```
The entire calculation being:
```
1: 895
2: 1714
3: 885
4: 1613
5: 774
6: 1411
7: 552
8: 107
9: 17
10: 8
```
If there are less than 5 steps, just print those steps taken.
Only use built-in libs, parameters can be from anywhere (whatever's easiest for your language of choice). No limit on maximum integer size, and if there are overflows, let it crash.
Given this isn't too difficult from a puzzle point of view, I will give until Sunday 25th, 8PM (UTC+8) for submissions to be considered for the accepted answer, at which point the shortest of any language will be the winner.
**EDIT:**
Congratulations to Howard, winning with a 48 GolfScript [answer](https://codegolf.stackexchange.com/a/28413/16278).
Special mention to 2nd place marinus with a 66 APL [answer](https://codegolf.stackexchange.com/a/28266/16278).
My personal favourite (being biased towards JavaScript) was core1024's [answer](https://codegolf.stackexchange.com/a/28341/16278).
[Answer]
## APL (66)
```
{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}
```
The left argument is the maximum iteration count and the right argument is the start number.
Explanation:
* `∆←⍺{`...`}⍕⍵`: pass the left argument as a number and the right argument as a string to the function that calculates the list of numbers, and store it in `∆`:
+ `(1<⍴⍵)∧⍺>0:`: if the amount of digits is more than 1 and the amount of iterations left is more than `0`:
- `⍎¨⍵`: evaluate each digit
- `2+/`: sum each pair
- `⍕¨`: format each number as a string
- `∆←,/`: concatenate the strings and store in `∆`
- `∆,(⍺-1)∇⊃∆`: return `∆`, followed by the result of applying this function to `∆` with one less iteration allowed
+ `⋄⍬`: if not, return the empty list
* `∆,⍪⍳⍴∆`: pair each element of `∆` with its index in `∆`
* `{`...`}/`: for each pair:
+ `(⍕⍵),': ',⍺`: return a string with the index, followed by `:`, followed by the number
* `↑¯5↑`: turn the list of strings into a matrix so they display on separate lines, and take the last 5 items
Test:
```
5{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
1: 895
2: 1714
3: 885
4: 1613
5: 774
50{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
6: 1411
7: 552
8: 107
9: 17
10: 8
```
[Answer]
## Mathematica, 172 characters
This is way too long, thanks to Mathematica's function names and ugly string handling (the actual "game" is only 76 of those characters), but here it is anyway:
```
""<>ToString/@(f=Flatten)@Take[Thread@{r=Range@Length[s=Rest@Cases[NestList[FromDigits[f@(d=IntegerDigits)[Tr/@Partition[d@#,2,1]]]&,n,m],i_/;i>0]],": "&/@r,s,"\n"&/@r},-5]
```
It expects the input number in variable `n` and the maximum number of iterations in `m`.
With less golf:
```
"" <> ToString /@
(f = Flatten)@
Take[
Thread@{
r = Range@Length[
s = Rest@Cases[
NestList[
FromDigits[
f@(d = IntegerDigits)[Tr /@ Partition[d@#, 2, 1]]] &,
n,
m
],
i_ /; i > 0
]
],
": " & /@ r,
s,
"\n" & /@ r
},
-5
]
```
[Answer]
## Ruby, 106 characters
```
f=->n,m{s=0
$*<<"#{s}: #{n=n.to_s.gsub(/.\B/){eval$&+?++$'[0]}.chop}"until n.to_i<10||m<s+=1
puts$*.pop 5}
```
I'm not 100% clear on the input rules, but if I can take `n` as a string I can save 5 characters, and if I can use predefined variables and write a program instead of a function, I can save another 9.
Creates a function `f` which can be called as follows:
`f[3541, 6]`
```
2: 1714
3: 885
4: 1613
5: 774
6: 1411
```
`f[372, 50]`
```
1: 109
2: 19
3: 10
4: 1
```
`f[9999, 10]`
```
6: 99999999999
7: 18181818181818181818
8: 9999999999999999999
9: 181818181818181818181818181818181818
10: 99999999999999999999999999999999999
```
[Answer]
### GolfScript, 48 46 characters
```
{.`n*[~]n\{:s++s}*;~}*].,,\]zip{': '*}%1>-5>n*
```
Thank you to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for a two-character improvement.
Expects both numbers on the stack. [Try online](http://golfscript.apphb.com/?c=OzM1NDEgNTAKCnsuYG4qW35dblx7OnMrK3N9Kjt%2BfSpdLiwsXF16aXB7JzogJyp9JTE%2BLTU%2Bbio%3D&run=true).
Examples:
```
> 4 50
> 141 50
1: 55
2: 10
3: 1
> 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8
> 3541 5
1: 895
2: 1714
3: 885
4: 1613
5: 774
```
[Answer]
# J - 96 92 char
I'd first solved this assuming that all games terminated, and this came back to bite me in the ass during testing. Left argument is the number of steps, right argument is the starting position, which can be given as a number or a string.
```
([(-@(<.5<.#){.])(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".@(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":))
```
This is a little too golfed and convoluted to degolf satisfyingly, so I'll say this:
* `(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":)` This part runs the game for the specified number of steps. `2+/\` is responsible for adding each pair of digits, and `<@>:@[` in tandem with `^:` controls capturing the intermediate steps of the game.
* `(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".` This part formats all the results as `step: result`. `({.~,i.0:)` is making sure we don't take too many steps, `#\` is the step numbers, and the `(,': '&,)&":"0` bit adds the colon and space.
* `(-@(<.5<.#){.])` This portion cuts the relevant five-or-less steps out of the full list. `<.` means 'minimum of'.
It works, but if you start with a large enough number, the game's results quickly start growing in size, which makes J switch from integers to the imprecise doubles. Here are some examples:
```
f =: ([(-@(<.5<.#){.])(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".@(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":))
5 f 3541
1: 895
2: 1714
3: 885
4: 1613
5: 774
50 f 3541
6: 1411
7: 552
8: 107
9: 17
10: 8
100 f 372
1: 109
2: 19
3: 10
4: 1
```
[Answer]
# Javascript 139 ~~144 150~~
```
function f(a,n){for(r=[a+=''];n--&&a[1];r.push(a=t))for(t='',i=0;a[++i];)t+=a[i-1]- -a[i];for(i=0;r[++i];)r[i+5]||console.log(i+': '+r[i])}
```
**Ungolfed**
```
function f(a,n)
{
for (r=[a+='']; n-- && a[1]; r.push(a=t))
{
for (t = '', i = 0; a[++i]; )
{
t += a[i-1]- -a[i]; /* -char force conversion to number */
}
}
for (i = 0; r[++i];) r[i+5]||console.log(i+': '+r[i])
}
```
[Answer]
## Perl, ~~86~~ 84
With newlines for readability:
```
$s+=$_=<>;
print+(map$s=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $s$/":(),/ /..$')[-5..-1]
```
**+ Edit:** No excuse for not using `-n` command line switch, and then score is **82=81+1**:
```
$s+=$_;
print+(map$s=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $s$/":(),/ /..$')[-5..-1]
```
And, possible integer overflow being OK, it's **81=80+1**
```
$.=$_;
print+(map$.=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $.$/":(),/ /..$')[-5..-1]
```
[Answer]
## Javascript, 247 ~~278~~ ~~288~~ ~~307~~ Characters
```
var t=[],q=1;function f(a,c){var x=a.toString().split(''),r='',p=parseInt;for(y in x){var i=p(y);if(i){r+=(p(x[i])+p(x[i-1])).toString();}}if(c!=0&&a>10){t.push(q+++':'+r+'\n');if(q>6){t.shift()}f(r,c-1);}console.log(t.join(',').replace(/,/g,''))}
```
**Formatted**
```
var t = [],
q = 1;
function f(a, c) {
var x = a.toString().split(''),
r = '',
p = parseInt;
for (y in x) {
var i = p(y);
if (i) {
r += (p(x[i]) + p(x[i - 1])).toString();
}
}
if (c != 0 && a > 10) {
t.push(q+++':' + r + '\n');
if (q > 6) {
t.shift()
}
f(r, c - 1);
}
console.log(t.join(',').replace(/,/g, ''))
}
```
**Edit 1**: Removed ternary
**Edit 2**: Flipped logic for "skipping" 0 index
**Edit 3**: Reworked recursive calling.
[Fiddle](http://jsfiddle.net/origineil/G5AY2/)
[Answer]
# Bash + coreutils, 115 bytes
```
for((a=$1;++i<=$2&a>9;)){
a=`paste -d+ <(fold -1<<<${a%?}) <(fold -1<<<${a#?})|bc|tr -d '
'`
echo $i: $a
}|tail -n5
```
Output:
```
$ ./appended-number.sh 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8
$ ./appended-number.sh 3541 5
1: 895
2: 1714
3: 885
4: 1613
5: 774
$
```
[Answer]
# JavaScript (ECMAScript 6 Draft) - 134 Characters
```
f=(x,y,i=0,j=[])=>([m=''].map.call(m+x,(z,p,n)=>m+=p?+z+1*n[p-1]:m),j[i++]=i+': '+m,m.length>1&&i<y?f(m,y,i,j):j.slice(-5).join('\n'))
```
**Examples:**
```
f(372,5)
"1: 109
2: 19
3: 10
4: 1"
f(3541,50)
"6: 1411
7: 552
8: 107
9: 17
10: 8"
f(3541,5)
"1: 895
2: 1714
3: 885
4: 1613
5: 774"
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 32 bytes
```
↑_5Ṡz+(mo`+": "sŀ)mṁs↑htU¡oṁdẊ+d
```
[Try it online!](https://tio.run/##yygtzv7//1HbxHjThzsXVGlr5OYnaCtZKSgVH23QzH24s7EYKJdREnpoYT6Qk/JwV5d2yv///41NTQz/mxoAAA "Husk – Try It Online")
Output format was cumbersome, but I had to answer this in Husk.
## Explanation
```
↑_5Ṡz+(mo`+": "sŀ)mṁs↑htU¡oṁdẊ+d
d convert first input to digits
¡ and iterate:
Ẋ+ sum overlapping pairs
ṁd convert to digits and flatten
U truncate till fixed point
ht remove first and last element
↑ take second input number of values from that
mṁs convert all the arrays to strings
Ṡz+( ) zip and concat that with:
ŀ range 1..length(seq)
mo`+": "s convert each to string, append a colon
↑_5 take the last 5 elements
```
[Answer]
# Javascript, 182 bytes
```
function f(I,T){s=[],x=1;for(;;){d=(""+I).split("");l=d.length;if(l==1||x>T)break;for(I="",i=1;i<l;)I+=+d[i-1]+ +d[i++];s.push(x+++": "+I)}s=s.slice(-5);for(i in s)console.log(s[i])}
```
[Answer]
# Perl, ~~166~~ ~~147~~ ~~138~~ 129 bytes
```
<>=~/ /;for$i(1..$'){@n=split'',$s||$`;$s=join'',map{$n[$_]+$n[$_+1]}0..@n-2;@o=(@o,"$i: $s");$s<10&&last}print join$/,@o[-5..-1]
```
Ungolfed:
```
<> =~ / /;
for $i (1..$') {
@n = split'', $s||$`;
$s = join'',map {$n[$_]+$n[$_+1]} 0..@n-2;
@o = (@o, "$i: $s");
$s<10 && last
}
print join$/,@o[-5..-1]
```
I hope it's alright that it prints some extra empty lines if the whole thing takes less than 5 steps.
[Answer]
# Java 524 405 365 chars [414 bytes]
Golfed version: `class A{static int n=0;List<String> s=new ArrayList<>();void c(int b,int r){String d=b+"";if(r==0||b <= 9){int m=s.size();for(int i= m>=5?m-5:0;i<m;i++)System.out.println(s.get(i));return;}String l="";for(int i=0;i<d.length()-1;i++)l+=d.charAt(i)+d.charAt(i+1)-96;s.add(++n+":"+l);c(Integer.valueOf(l),--r);}public static void main(String[] a){new A().c(3541,50);}}`
Readable version:
```
class AddDigits {
static int n = 0;
List<String> steps = new ArrayList<>();
void count(int num, int count) {
String digits = num + "";
if (count == 0 || num <= 9) {
int stepsSize = steps.size();
for (int i = stepsSize >= 5 ? stepsSize - 5 : 0; i < stepsSize; i++) {
System.out.println(steps.get(i));
}
return;
}
String line = "";
for (int i = 0; i < digits.length() - 1; i++) {
line += digits.charAt(i) + digits.charAt(i + 1) - 96;
}
steps.add(++n + ":" + line);
count(Integer.valueOf(line), --count);
}
public static void main(String[] args) {
new AddDigits().count(3541, 50);
}
}
```
[Answer]
## JavaScript 133 bytes
```
function f(n,g){for(c=r=[];g--;(n=s)&&(r[c++]=c+': '+s))for(i=s='',n+=s;n[++i];s+=n[i]-+-n[i-1]);console.log(r.slice(-5).join('\n'))}
```
**Ungolfed:**
```
function sums(num, guard) {
for(count = res = [];guard--;(num = sum) && (res[count++] = count + ': ' + sum))
for(i = sum = '',num += sum;num[++i];sum += num[i] -+- num[i-1]);
console.log(res.slice(-5).join('\n'))
}
```
[Answer]
# Java, 341 chars ~~371 chars~~
```
class a{public static void main(String[] a){p(3541,50);}static void p(int n,int k){Queue<String>q=new LinkedList();int c=0;while(n>9&&c<k){c++;String r="";String p=""+n;for(int i=0;i<p.length()-1;i++)r+=((p.charAt(i)+p.charAt(i+1)-96));n=Integer.parseInt(r);q.add(c+": "+n);if(q.size()>5)q.remove();}for(String s:q){System.out.println(s);}}}
```
Formatted:
```
class a {
public static void main(String[] a) {
p(3541, 50);
}
static void p(int n, int k) {
Queue<String> q = new LinkedList();
int c = 0;
while (n > 9 && c < k) {
c++;
String r = "";
String p = "" + n;
for (int i = 0; i < p.length() - 1; i++)
r += ((p.charAt(i) + p.charAt(i + 1) - 96));
n = Integer.parseInt(r);
q.add(c + ": " + n);
if (q.size() > 5)
q.remove();
}
for (String s : q) {
System.out.println(s);
}
}}
```
Thanks to user902383 i was able to reduce the code by 30 chars, by not splitting the String into an Array an using -96 instead of "Integer.valueOf()
[Answer]
# Dart, ~~602~~ 588 bytes
Dart is probably one of the worst languages to do this in... I'll need to find a better way to do this.
Anyway, Here's my entry:
Input through console
```
var steps={};void main(a){c(a[0],int.parse(a[1]));}void c(inp,m){int i=0;int n=int.parse(inp);while(++i<=m){n=addUp(n.toString());steps[i]=n;if(n<10)break;}printSteps();}int addUp(n){var ns=[];for(int i=0;i<n.length;i++){try{ns.add(n[i]+n[i+1]);}catch(e){}}return addNumbers(ns);}int addNumbers(ns){var it=ns.iterator;var s="";while(it.moveNext()){int i=0;for(var t in it.current.split('')){i+=int.parse(t);}s=s+i.toString();}return int.parse(s);}void printSteps(){int l=steps.length;for(int i=getStart(l);i<=l;i++){print("${i}:\t${steps[i]}");}}int getStart(l){int m=l-4;return m>0?m:1;}
```
And the ungolfed, slightly unminified version:
```
var steps = {};
void main(a)
{
c(a[0], int.parse(a[1]));
}
void c(String input, int max)
{
int i = 0;
int n = int.parse(input);
while(++i <= max)
{
n = addUp(n.toString());
steps[i] = n;
if(n < 10)
break;
}
printSteps();
}
int addUp(String n)
{
List numbers = [];
for(int i = 0; i < n.length; i++)
{
try
{
numbers.add(n[i] + n[i + 1]);
}
catch(e){}
}
return addNumbers(numbers);
}
int addNumbers(List numbers)
{
Iterator it = numbers.iterator;
String s = "";
while(it.moveNext())
{
int i = 0;
for(String s in it.current.split(''))
{
i += int.parse(s);
}
s = s + i.toString();
}
return int.parse(s);
}
void printSteps()
{
int l = steps.length;
for(int i = getStart(l); i <= l; i++)
{
print("${i}:\t${steps[i]}");
}
}
int getStart(int l)
{
int m = l - 4;
return m > 0 ? m : 1;
}
```
[Answer]
**PERL 135 129/125 125/121 bytes**
It has the same bug as Tal's answer
```
sub c{($e,$l)=@_;print join"\n",(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2};++$c.": ".($e=$s)}1..$l)[-5..-1]}
```
Edit 129 bytes as a function:
```
sub c{($e,$l)=@_;print join$/,(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s)}1..$l)[-5..-1]}
```
125 bytes as a function:
```
sub c{($e,$l)=@_;print+(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s).$/}1..$l)[-5..-1]}
```
125 bytes as a console script (without the hashbang):
```
($e,$l)=@ARGV;print join$/,(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s)}1..$l)[-5..-1]
```
121 bytes as a console script (without the hashbang):
```
($e,$l)=@ARGV;print+(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s).$/}1..$l)[-5..-1]
```
Expanded:
```
sub c
{
($e, $l) = @_;
print +(grep /\d$/, map {
$s="";
{
$e =~ /(.)(.)/;
redo if "" ne ($e = $2.$') and $s .= $1 + $2
}
"$_: ".($e = $s).$/
} 1 .. $l)[-5 .. -1]
}
```
Test with `c(372,4);`:
```
[blank line]
1: 109
2: 19
3: 10
4: 1
```
Test with `c(3541,50);`:
```
6: 1411
7: 552
8: 107
9: 17
10: 8
```
[Answer]
## C# - 269
```
void F(int x,int y){var o=new List<string>();var i=x+"";for(int n=1;n<y&&i.Length>1;n++){var s="";for(int z=0;z<i.Length;z++){int a=i[z]-'0';var t=a+(z+1!=i.Length?i[z+1]-'0':-a);if(t!=0)s+=t;}i=s;o.Add(n+": "+i);}foreach(var p in o.Skip(o.Count-5))Debug.WriteLine(p);}
```
Readable:
```
void F(int x,int y){
var o=new List<string>();
var i=x+"";
for(int n=1;n<y&&i.Length>1;n++)
{
var s="";
for(int z=0;z<i.Length;z++){
int a=i[z]-'0';
var t=a+(z+1!=i.Length?i[z+1]-'0':-a);
if(t!=0)
s+=t;
}
i=s;
o.Add(n+": "+i);
}
//Output
foreach(var p in o.Skip(o.Count-5))
Debug.WriteLine(p);
}
```
Usage:
```
F(3541, 50)
```
Output:
```
6: 1411
7: 552
8: 107
9: 17
10: 8
```
[Answer]
# Cobra - 363
A rather depressing result... but hey, I still beat Java.
It *should* be immune to integer overflows for practical test cases.
```
class P
cue init(a,b)
base.init
l=[]
c=.p(a.toString)
for x in b
l.add("")
y=l.count
for i in c.count-1,l[y-1]+=(c[i]+c[i+1]).toString
if l.last.length<2,break
c=.p(l.last)
z=if(y>5,y-5,0)
for x in l[z:y],print"[z+=1]:",x
def p(n) as List<of int>
c=List<of int>()
for i in n,c.add(int.parse(i.toString))
return c
```
[Answer]
## Python 2.7, ~~174~~ ~~173~~ 158 characters
Using a lot of strings to do the task.
```
x,n=raw_input().split()
o,i=[],0
while int(n)>i<o>9<x:x="".join(`sum(map(int,x[j:j+2]))`for j in range(len(x)-1));i+=1;o+=[`i`+": "+x]
print"\n".join(o[-5:])
```
## Python 2.7, 155 characters
Version defining a function
```
def a(x,n):
o,i,x=[],0,`x`
while n>i<o>9<int(x):x="".join(`sum(map(int,x[j:j+2]))`for j in range(len(x)-1));i+=1;o+=[`i`+": "+x]
print"\n".join(o[-5:])
```
**Slightly ungolfed version:**
```
x,n=map(int,raw_input().split())
o,i=[],1
while i<=n and x>9:
x=int("".join(`sum(map(int,`x`[j:j+2]))` for j in range(len(`x`)-1)))
o.append("%d: %d"%(i,x))
i+=1
print "\n".join(o[-5:])
```
[Answer]
# Haskell, 154
```
s=show
z=zipWith
m#n=concat.z(\a b->s a++": "++b++"\n")[1..].(\x->drop(length x-n)x).takeWhile(/="").iterate((\x->z(+)x(tail x)>>=s).map(\x->read[x]))$s m
```
example usage:
```
λ> 3541#5
"1: 1411\n2: 552\n3: 107\n4: 17\n5: 8\n"
```
To make it more readable, use `putStr`:
```
λ> putStr $ 3541#5
1: 1411
2: 552
3: 107
4: 17
5: 8
```
[Answer]
## Groovy - 191 182 chars
Based on [Thomas Rüping's solution](https://codegolf.stackexchange.com/a/28269/21004), ported to Groovy 2.2.1:
```
f={it as int};n=args[0];s=f args[1];q=[];x=0;while(f(n)>9&&x<s){x++;d=n.split("");n="";for(i in 1..d.length-2)n+=f(d[i])+f(d[i+1]);q << "$x: $n"};q[-1..5].reverse().each{println it}
```
Execution and output:
```
bash$ groovy Numbers.groovy 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8
```
Ungolfed:
```
f = {it as int}
n = args[0]
s = f args[1]
queue = []
stepCounter = 0
while (f(n) > 9 && stepCounter < s) {
stepCounter++
digits=n.split("")
n=""
for(i in 1..digits.length-2) {
n += f(digits[i]) + f(digits[i+1])
}
queue << "$stepCounter: $n"
}
queue[-1..5].reverse().each{ println it }
```
[Answer]
\*\*C ~~186~~ ~~179~~174 \*\*
```
f(int a,int z){for(int c,d,i,j=0,m[5];m[j++%5]=a,j<=z&&a/10;a=c)for(c=0,i=1;a/10;d=a%10+(a/=10)%10,c+=d*i,i*=d<10?10:100);for(i=j<5?0:j-5;i<j;printf("%d: %d\n",i,m[i++%5]));}
```
Slightly less golfed (mini-golfed?)
```
f(int a, int z)
{
for(int c,d,i,j=0,m[5];m[j++%5]=a,j<=z&&a/10;a=c)
for(c=0,i=1;a/10;d=a%10+(a/=10)%10,c+=d*i,i*=d<10?10:100);
for(i=j<5?0:j-5;i<j;printf("%d: %d\n",i,m[i++%5]));
}
```
Just allocate enough memory to store five results cyclically. The outer loop keeps going until we hit the limit or reach a single digit. The inner loop adds the last digit of the number to last digit of 1/10 of the number and adds this, multiplied by the relevant power of 10 to the result. Divide the number you first though of by 10 and repeat to get the total. Then print out up to the last five results.
Next challenge is to see if I can shave off enough to beat some scripting languages at golf.
Edit: Now compiles with warning but five characters shaved off by removing "void " declaration
[Answer]
# C# - 309 330 320 306 Bytes
## Golfed Version:
```
private static void F(int aN,int aM){var s=new List<string>();var n=aN.ToString();for(int i=1;i<=aM;i++){int z=n.Length;if(z==1){break;}var a=n;n="";for(int j=0;j<z-1;j++){int r=a[j]-'0'+a[j + 1]-'0';n=n+r;}s.Add(i+": "+n);}int l=s.Count;int p=5;if(l<5){p=l;}for(int k=l-p;k<l;k++){Debug.WriteLine(s[k]);}}
```
Usage: F(3541,50);
## Ungolfed version for readability:
```
private static void AppendNumbers(int aNum, int aMaxSteps)
{
var results = new List<string>();
var numString = aNum.ToString();
for (int i = 1; i <= aMaxSteps; i++)
{
int stringLength = numString.Length;
if (stringLength == 1)
{
break;
}
var a = numString;
numString = "";
for (int j = 0; j < stringLength-1; j++)
{
int additionResult = a[j]-'0' + (a[j + 1]-'0');
numString = numString + additionResult;
}
results.Add(i+": "+ numString);
}
int numberOfResults = results.Count;
int p = 5;
if (numberOfResults < 5)
{
p = numberOfResults;
}
for (int k = numberOfResults - p; k < numberOfResults; k++)
{
Debug.WriteLine(results[k]);
}
}
```
Suggestions for improvement are always welcome! ;)
**Edit:** Removed String.Empty and replaced it with "" to save 10 Bytes.
**Edit 2:** Thanks to malik for the tipp with the strings!
] |
[Question]
[
* Take a line of input (function arguments or stdin, [etc.](https://codegolf.meta.stackexchange.com/q/2447/90614)).
* Remove comments in it, where a comment starts and ends with `"`.
* Do not remove comments in string literals, which start and end with `'`. String literals do not contain escapes, because smalltalk has nice, easily lexable syntax ;).
* [Output](https://codegolf.meta.stackexchange.com/q/2447/90614) this string.
* The number of `"`s not inside strings and the number of `'`s not in comments in the input are both guaranteed to be even.
* Because removing comments makes programs more golfy, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest code per language wins.
## Examples
`input => output`
```
123 => 123
1"2"3 => 13
1""23 => 123
'12' => '12'
'1"2'3"" => '1"2'3
'1"2"3' => '1"2"3'
a"1'2'3"a => aa
"a"b"c" => b
'a'b'c' => 'a'b'c'
a'"'b'"'c => a'"'b'"'c
a"'"b"'"c => abc
```
Regex is boring as usual. Try [something](https://tryapl.org) [new](https://www.jsoftware.com/), or answer in smalltalk!
[Answer]
# [Smalltalk](https://www.tutorialspoint.com/execute_smalltalk_online.php), 325 bytes
```
[:k|k inject:OrderedCollection new into:[:a :b|(a isEmpty not and:[a last=0])ifTrue:[(b=$')ifTrue:[a removeLast. a add:b. a]ifFalse:[a removeLast. a add:b. a add:0. a]]ifFalse:[(a isEmpty not and:[a last=$"])ifTrue:[(b=$")ifTrue:[a removeLast. a]ifFalse:[a]]ifFalse:[(b=$')ifTrue:[a add:b. a add:0. a]ifFalse:[a add:b. a]]]]]
```
Some hot garbage smalltalk code.
It essentially uses a stack, pushing a `0` for a placeholder for when it sees `'`. When it sees `"`, it keeps in on the top of the stack until it sees another `"`.
I couldn't get an Eval function (smalltalk docs are *terrible*), nor could I get regex to work (smalltalk docs are *terrible*).
You can use GNU Smalltalk to run this, in theory, although I only tested it on the online compiler (linked above).
Here's a (more) readable version that takes from stdin and writes to stdout. As you can tell smalltalk is a beautiful language...
```
Transcript show:(stdin nextLine inject:
OrderedCollection new into:
[:a :b|
Transcript show: a printString; cr.
(a isEmpty not and:[a last = 0])ifTrue: [
(b = $') ifTrue: [
a removeLast.
a add: b.
a
] ifFalse:[
a removeLast.
a add: b.
a add: 0.
a
]
] ifFalse: [
(a isEmpty not and:[a last = $"]) ifTrue: [
(b = $") ifTrue: [
a removeLast.
a
] ifFalse: [a]
] ifFalse: [
(b = $') ifTrue: [
a add: b.
a add: 0.
a
] ifFalse: [
a add: b.
a
]
]
]
]).
```
Note: the regex solution almost works, using the same approach as Jakque, but it fails since smalltalk gives `nil` instead of an empty string:
```
Transcript show:(stdin nextLine replacingAllRegex: '".*?"|(''.*?''|.)' with: '%1')
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~30~~ 26 bytes ([SBCS](https://github.com/abrudz/SBCS))
Anonymous prefix lambda.
```
{⍵/⍨≠\⍛⍱⍨<⌿≠\@1⊢'''"'∘.=⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR71b9R70rHnUuiHnUO/tR70Ygx@ZRz36QgIPho65F6urqSuqPOmbo2QKV1v5Pe9Q24VFv36Ou5ke9ax71bjm03vhR28RHfVODg5yBZIiHZ/D/NHVDI2N1LiClZKQEZShBRNSBUkACwlICMo2VlOA8oFqwVKKSobo6WC4RxFVKVEpSSoYqS1RXT1JXT4YqBLkNxFcCCYF1AtlJICJZHQA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` [dfn](https://en.wikipedia.org/wiki/Direct_function); argument is `⍵`:
``a"1'2'3"a'1"2"3'a"'"b"'"c``
`'''"'∘.=⍵` equality table for `'` and `"` versus the argument
`[[0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0],`
`[0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,1,0,1,0]]`
`≠\@1⊢` running parity (lit. XOR scan) **at** the 1st row (lit XOR scan) indicating characters inside strings
`[[0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,0,0,0],`
`[0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,1,0,1,0]]`
`<⌿` second row, i.e. comment delimiters, and not first row, i.e. inside string, i.e. active comment delimiters (lit. vertical less-than reduce)
`[0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0]`
`≠\⍛⍱⍨` neither that (active comment delimiters) NOR its running parity (inside comments)
`[1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1]`
`⍵/⍨` use that to filter the characters of the argument
``aa'1"2"3'ac``
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 48 bytes
```
iⱮ⁾'"o1:0¤>/
ṣ”"2œPj€”"µẹ”'2ị‘œṖµÇ?;ß}¥/$¹f⁾'"$?
```
[Try it online!](https://tio.run/##y0rNyan8/z/z0cZ1jxr3qSvlG1oZHFpip8/1cOfiRw1zlYyOTg7IetS0BsQ@tPXhrp1AhrrRw93djxpmHJ38cOe0Q1sPt9tbH55fe2ipvsqhnWlgU1Ts////n6iupJ4ExMlK6kopQJwKAA "Jelly – Try It Online")
This is definitely not the best approach, even considering Jelly is typically not great with strings.
```
iⱮ⁾'"o1:0¤>/ Helper Link
iⱮ⁾'" Find the first ' and "; 0 if not found
o Logical OR with
1:0¤ 1 / 0 (infinity) - that way, "not found" is at the end, not the start
>/ Is the first greater than the second?
ṣ”"2œPj€”"µẹ”'2ị‘œṖµÇ?;ß}¥/$¹f⁾'"$? Main Link
? If
f⁾'"$ There are any ' or "
? $ - If
Ç - " was found first
ṣ”" - Split on "
2œP - Split over and discard the second item
j€”" - Join each of those with " (basically, this slices out
the part between and including the first and second ",
and leaves the part before and after as two sublists)
- Otherwise
ẹ”' - Find all indices of '
2ị - Get the second of these
‘ - And increment it
œṖ - And partition the list at that point (basically, this
divides the list at the second ' without removing anything)
¥/ - Then, reduce (apply to first and second as left and right) by
;ß} - Concatenating the left side with this function applied to the right link
¹ Otherwise, if ' and " aren't found, just return the string itself
```
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
⁾'"iⱮnaoɗ\ŻṖoƊỊx@
```
[Try it online!](https://tio.run/##RYyxCsIwEIb3PEW45SaHpGOx@BqCyyU4KMWuulUXoQ@giy7OIigOlYJLseBjJC8Sk4bidN//3X@3nOf5xjm7fSMs7P22ouJ7nH0a8zoUXWWaaj1xqS1PfJRxW57Tds9M8zT1w9SXdt9VdnedOidkwscZ94MJkBBDYPgvUEgMHKYPIDEBiCJwryDBwXhkBAJDjYIkYkCgQPdHiiGhQh37ERkheADUfX8I/g36O4Solf4B "Jelly – Try It Online")
A link taking a Jelly string argument and returning a Jelly string without the comments.
## Explanation
```
⁾'"iⱮ | Positions of each character in '" (so single quote -> 1, double quote -> 2, anything else -> 0)
ɗ\ | Cumulative reduce (x,y)
nao | - (x != y) and (x or y)
Ɗ | Following as a monad:
Ż | - Prepend zero
Ṗ | - Remove last item from list
o | - Or
Ị | Less than or equal to 1
x@ | Original input with 0 or 1 copies of each character as appropriate
```
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS) `g`, ~~18~~ 12 bytes
‒6 thanks to Neil.
```
'.*'
".*"
&
```
[Try it online!](https://tio.run/##HYoxCsAwDMR2P0NDDzIEkrzISaFzC32/63QR4nT36@cToVpk1IIdFtH6sEZnk3S1rgRdA35hyJymvbjhTFYW19TKIlLQyo8yiRXXBw "QuadR – Try It Online")
This is equivalent to the Dyalog APL function `'''.*''' '".*"'⎕R'&' ''⍠'Greedy'0`
The `g` flag turns off greedy patterns, essentially making `*` mean `*?`. Then the two patterns simply replace `'.*'` strings and `".*"` comments with `&` themselves and nothing, respectively.
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), ~~118~~ ~~113~~ 112 bytes
```
LINE INPUT s$
FOR i=1TO LEN(s$)
a=ASC(MID$(s$,i))
k=c
c=c XOR(a=34)<q
q=q XOR(a=39)<c
IF c+k=0THEN?CHR$(a);
NEXT
```
### Explanation
Looping over the ASCII code `a` of each character in a line of input `s$`, we track three boolean values:
* `c` is true inside a comment, false otherwise
* `q` is true inside quotes, false otherwise
* `k` is the previous iteration's value of `c` (we need to track this so we can suppress both double quotes instead of just the first one)
The values are updated as follows:
* If the current character is a double quote (`a=34`) and `q` is false, toggle `c`
* If the current character is a single quote (`a=39`) and `c` is false, toggle `q`
If both `c` and `k` are false, we're not in a comment, so output the character.
(There's a fun trick in the update statements: In QBasic, truthy is -1, so instead of `a=39AND c=0`, we can get the same result from `(a=39)<c`. The inequality will be true only when `a=39` is `-1` and `c` is `0`.)
[Answer]
# C, ~~92~~ 91 bytes
```
c;s;main(){while((c=getchar())+1)s=s?s-2?putchar(c):0,s*(c!=44-5*s):c-34?putchar(c)==39:2;}
```
All my submissions so far have been in esolangs, so even though C might not be anything groundbreaking, it's at least new to me. :)
[Try It Online!](https://tio.run/##TYpBCsIwFET3vYWz@Uk1YJK6sCH0LL@f0hZqEaO4EM8eU924eTzmjRhZeB1zlpDChedV6ddzmpdBKYnjcJeJb0rrvdUppi4Z110fv1F0ezykWskuNo051Um3Ynzz12P059aFd87W@crCYSOKk3VUAEce@Ao8VQxL28IVGD2kFKaepBRCEZCUD5VEkA8)
### Explanation
```
c;s; // for current char and state
main() {
while ((c=getchar())+1) // while input is not EOF:
s=s? // if state is not 0 (0=default, 1=string literal, 2=comment)
s-2?putchar(c):0, // output the current char if state is not 2
s*(c!=44-5*s) // set s to 0 if the relevant character is found
// (39 ['] if state = 1, 34 ["] if state = 2)
: // else (state = 0)
c-34? // if the current char is not ["]
putchar(c)==39 // output current char, and if it is ['], set s to 1
: // else (current char is ["])
2 // set s to 2
;} // end expression, statement, and main function
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), no regex, ~~75~~ 65 bytes
```
a=b=1
for i in input():c=b*i;a^="'"==c;b^='"'==a*i;print(end=c*b)
```
[Try it online!](https://tio.run/##LY7RCoMwDEXf@xUlL7G@tb6MSn5FaGOHhVGLdky/3sUxSEK453KTerZlLcOjbhevcyIAuAJFsuq5bjrrXKTqu3XGM8U@j2EiQCDiMU6EgERB1Lrl0rpUZuI@mktSVNtOr/Rnya@krU9H4u6@YP5eo9LBqTZfw75f1g3KgoN7guxoHcoAh4NE4Q@hCmDxVoKCABFYSMCILEQ@idIsHhSEwF8 "Python 3.8 (pre-release) – Try It Online")
Much cleaner solution than my previous one
### how it works :
`a` and `b` store the state of the string:
* `a` is equal to `0` if the char is inside a literal and `1` otherwise
* `b` is equal to `0` if the char is inside a comment and `1` otherwise
* `c` store the char multiplied by `b`. If the char is inside a comment (`b` is equal to `0`), `c` is equal to the empty string
* `a^=` use of the bitwise operator xor to swich the state of `a` if the current char is `'` and the char is not inside a comment
* same goes for `b` but with `"`
* `print(end=c*b)` print the char if `b` is not set to `0`. `end=` is for avoiding the trailing new line
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), regex, 52 bytes
```
lambda s:re.sub("\".*?\"|('.*?')","\\1",s)
import re
```
[Try it online!](https://tio.run/##HYpBCsMgFET3nkJm87UEqWZTCqUXcWMSQ4XEiNpFoXe3ppuZx7xJn/o64nhLua0P2za3T4vj5Z69Ku9JwEJdnhZfQb1JYoC1GkORLOzpyJVn39Yj88BD5EfyUVylyt4tQqqStlC3EH0R8s54yiFWsYogZdNmZBoGZ6IzaUM9YGgE/oCRmIOmc3EMDhPmbhxNNHdD6ACa@4e6Isw/ "Python 3.8 (pre-release) – Try It Online")
Pretty basic: I replace comments by nothing and literals by themselves. Regex substitution are not overriding. Lazy operators do the rest
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
```
s=>s.replace(/('|").*?\1/g,_=>_<'%'?'':_)
```
[Try it online!](https://tio.run/##RYzdToNAFITveQpyEjO7LYLAjTFC73wBL9VuDtulwSBUtjUx8d1xf2y8OjPfmZl3/mKrl@F0vp3mg1n7ZrVNa/PFnEbWRhQCPyTzze61LI6Zalr1iBvsgAcl18V8XobFCPQW0lX48DSM5vl70uIuw@Xc3wf8t7R/2adv2@IjzOh5svNo8nE@CpWlwLYXSkq5llWdNm3qTlJSRdF4Tf8PlBW89tcZqlATReB1QFTjSpxMmEr4GHvInBBTRzqUugSMDjrmo0wY5ARBh/zVuBm4HijiTv8C "JavaScript (Node.js) – Try It Online")
Trivial, thank EliteDaMyth for -3 bytes
# [JavaScript (Node.js)](https://nodejs.org), ~~88~~ 86 bytes, No RegEx
```
f=([c,...s],y=c=='"')=>c?[[c+s.splice(0,s.indexOf(c=="'"|y?c:s)+1).join``][+y]]+f(s):s
```
[Try it online!](https://tio.run/##RZAxb4MwEIV3fgW65WxBnQJLFMnJ1rVDR0SIOUzkiALFSVWk/nd6gKIO1r33@d2z5Jv5Np5GN9xfur6289xokVOslPJFPGnSGgGlPtIpzynyyg@tIyteY69cV9uf90ZwBhB@pxMdvIwSqW696y6XIo@mooga4eXBz6P9erjRCmw8SjVaU7@51n5MHXEXPu7NfsVDa7h9d87PYRHtPq9xyU/3ne9bq9r@Kso4ROTOUko5J2kW6mPII0gghc0sGv4vMElx0ctkAylmABtY9IogwydhGRhIcImZBRoTgIEKaF2qAjRYIW35TQaGf6jiQ2v@abgGeQ9hwxX9AQ "JavaScript (Node.js) – Try It Online")
If `s.indexOf(s)` happens to be non-negative, then `s==c` and `f([c,c])==c+c`
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes
```
('.*?')|".*?"
$1
```
[Try it online!](https://tio.run/##HYqxDYBADAP7jGEhGSiQkh@AWfIRBQ0FomT3kKexTz7fx3NenjlzW3cuL6ogk2aqNVEYRqKYaqyAsQE/oFEcyrG4wNERZZydUYYoAKM@LEXEBw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Regex, obviously. Since by default matches can't overlap, the regex can match both strings and comments and won't get confused. It then remains to delete the comments without changing the strings.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔ωζFS«F¬⁼∨ζι"ι¿№"'ι≔⁻∨ζι∧ζιζ
```
[Try it online!](https://tio.run/##TY27DsIwDEVn@hWRFztS@QKmCjEw8JBYWUpL20BI2jxaKOLbQ6AMbL6@xz5Fk5tC5zKEzFpRKxpSNvJFUmnDaK1a7w7OCFUT5@yZzL7rrXa06nwuLe0MjSkTPGVwBOAR2kfakYgvZqJitNQ@xlgifDjOfpqNUP7/PFPlNPLJ/wohhxMWUOIZKqyhQQEXvILEGyjU0GIHBi049NDjAHd8hHkv3w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ωζ
```
Keep track of the current quote character, initially , but can be `"` or `'`.
```
FS«
```
Loop over the input.
```
F¬⁼∨ζι"ι
```
If the current quote, or the current character if there is no current quote, is not `"`, then print the current character.
```
¿№"'ι
```
If the current character is a quote, then...
```
≔⁻∨ζι∧ζιζ
```
... turn the current quote on or off as appropriate.
* If the current quote is empty, then we subtract nothing from the current character, so the current quote becomes the current character.
* Otherwise, we subtract the current character from the current quote. This ends the current quote only once we find the matching character.
[Answer]
# [Haskell](https://www.haskell.org/), 105 bytes
```
f('"':s)=g s
f(a@'\'':s)=a:h s
f(a:s)=a:f s
f[]=[]
g('"':s)=f s
g(a:s)=g s
h(a@'\'':s)=a:f s
h(a:s)=a:h s
```
[Try it online!](https://tio.run/##ZZFPa4QwEMXvfoohFCaCW9C9LaQUepZ@AONhYv1H3bgYL/30Nsl03ZVeEt/vzXsBZyD33U7TNl5v87LCx2zXZZ5ey9nSF8huXsoUTif4tNMPeAUDLbZ1buskCry4VPXgkk7SO2qMmi4DExZdEFWtqjrp75HAeh4I6eGQ7pjsVVtDrnWgEoAKpMiLs8ggXqlHWUBaFFowPlDP/w1jXmBg8X5AP4rnkGAvyqPtX8DdjOJukxY5xjiFAaLd0cEzWjTcax6NhAYb7vv73NtQC0/80cS2J/n0IMZef/KQYbNOkiuNFlRYVQn8515AS8rA@D2@wW0Z7er3CgRKgckgOtsv "Haskell – Try It Online")
] |
[Question]
[
**In anticipation of [MathJax being temporarily disabled](http://chat.stackexchange.com/transcript/message/21046348#21046348), the rendered MathJax in this question has been replaced with images. You are still welcome to post answers but you'll have to view the rendered MathJax on [another site](https://math.stackexchange.com/).**
[PPCG](https://codegolf.stackexchange.com/) [just got](http://meta.codegolf.stackexchange.com/a/5024/26997) [MathJax](https://www.mathjax.org/)! This means we can now easily include well formatted mathematical formulas into posts. ([Handy MathJax tutorial.](http://meta.math.stackexchange.com/q/5020/162582))
For example, here is the [golden ratio](http://en.wikipedia.org/wiki/Golden_ratio) expressed as an infinite [continued fraction](http://en.wikipedia.org/wiki/Continued_fraction):

The MathJax code for this equation is
```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
```
You can find this by right clicking the formula and following *Show Math As* → *TeX Commands*.
The `$$` means it is displayed on its own in the center of the page instead of inline. Use a single `$` for inline.
# Challenge
Write a program that takes in a non-negative integer, n, and outputs the MathJax code for that many "steps" of the continued fraction for the golden ratio.
**To keep things standard across answers, you must use this *exact* MathJax syntax:**
* For n = 0, the output must be `$$\varphi=1+\dots$$`.
Which is rendered as:

* For n = 1, the output must be `$$\varphi=1+\cfrac1{1+\ddots}$$`.
Which is rendered as:

* For n = 2, the output must be `$$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$`.
Which is rendered as:

* For n = 3, the output must be `$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$`.
Which is rendered as:

This pattern continues on for larger n. You could say that n represents the number of division lines in the equation.
### Notes
* `\cfrac` is used instead of the more common `\frac`.
* `\dots` is used instead of `\ddots` for n = 0.
* Take input from stdin or the command line.
* Output to stdout (with an optional trailing newline).
* Alternatively, you may write a function that takes in n as an integer and returns the MathJax code as a string (or still prints it).
# Scoring
The smallest submission in bytes wins. Tiebreaker goes to the earlier submission.
[Answer]
# Python, ~~70~~ ~~68~~ 67 bytes
```
lambda n:"$$\\varphi=1+\%sdots%s$$"%("cfrac1{1+\\"*n+"d"[:n],"}"*n)
```
This defines an anonymous function which just uses simple string multiplication and string formatting.
*(Thanks to @xnor for pointing out that `\\c` can just be written as `\c`, since `c` can't be escaped. Unfortunately this doesn't hold true for `\\v`, since `\v` is ASCII 11.)*
**Previous attempts:**
```
lambda n:"$$\\varphi="+"1+\\cfrac1{"*n+"1+\\"+"ddots"[n<1:]+"}"*n+"$$"
lambda n:r"$$\varphi=%s1+\%s$$"%("1+\cfrac1{"*n,"ddots"[n<1:]+"}"*n)
```
[Answer]
# CJam, ~~51~~ 50 bytes
```
$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_
```
Code explanation:
```
"$$\varphi=1+" "This is a static string";
"\cfrac1{1+"ri:R*'\ "Repeat this string input number times. Put a \ at the end";
"ddots"R!> "If input is 0, remove 1st characters, else not";
'}R* "Put the closing bracket R times";
'$_ "The final $$";
```
Few examples:
N = 0
```
$$\varphi=1+\dots$$
```
---
N = 4
```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
```
---
N = 15
```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}}}}}}}}}}}$$
```
*UPDATE* - 1 byte saved thanks to Sp3000!
[Try it online here](http://cjam.aditsu.net/#code=%22%24%24%5Cvarphi%3D1%2B%22%22%5Ccfrac1%7B1%2B%22ri%3AR*'%5C%22ddots%22R!%3E'%7DR*'%24_&input=4)
[Answer]
# [><>](http://esolangs.org/wiki/Fish), ~~89~~ 86 + 3 = 89 bytes
```
:&"$$"{\l?!;o70.
}-1v!?:<{"}"
&:&\~"stod"&:&?:
{1->:?!v}"\+1{1carfc"
rav\$$"\~"\+1=ihp
```
Run with the `-v` flag, e.g.
```
py -3 fish.py program.fish -v 3
```
Surprisingly ><> doesn't do too badly here, since we can mimic string multiplication by having a counter which we decrement every iteration.
```
:&"$$"{\ Put n into the register and push "$$"
}-1v!?:<{"}" Push n "}"s
&:&\~"stod"&:&?: Push "stod", and copy the final "d" if n != 0
{1->:?!v}"\+1{1carfc" Push n "\+1{1carfc"s
rav\$$"\~"\+1=ihp Push "\+1=ihprav\$$"
\l?!;o70. Keep printing chars until the stack is empty
```
*(-3 bytes thanks to @randomra)*
[Answer]
# [Retina](https://github.com/mbuettner/retina), 160 + 7 = 167 bytes
```
;`.+
$$$$\varphi=1+\dots#$0$$$$
```
;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)
$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#
;`#
```
;+`\\d?dots\d(\d*)
\cfrac1{1+\ddots$1}
```
Each line goes into a separate source file, so I've added [1 byte for each file after the first](https://codegolf.meta.stackexchange.com/a/4934/8478). However, for convenience, Retina now also supports the `-s` command-line flag, which allows you to put all of this into a single file (in which case the newlines are treated as file separators).
The largest part of the code (98 bytes) is used to convert the input from decimal to unary (files 3 to 6). The basic idea of the code is to surround the input in `$$\varphi=1+\dots...$$`, then convert the input to unary, and then expand `\dotsN` or `\ddotsN` to the next level of the continued fraction (while reducing `N` to `N-1`).
[Answer]
# Julia, ~~76~~ 73 bytes
```
n->("\$\$\\varphi=1+"*"\\cfrac1{1+"^n*"\\"*"d"^(n>0)*"dots"*"}"^n*"\$\$")
```
This creates a lambda function that takes a single integer as input and returns the MathJax as a string. To call it, give it a name, e.g. `f=n->...`.
Unfortunately both backslashes and dollar signs have to be escaped in Julia strings because they both have special meaning. String concatenation is performed using `*` and string repetition with `^`.
Examples:
```
julia> f(0)
"$$\varphi=1+\dots$$"
julia> f(4)
"$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$"
```
Suggestions are welcome as always!
---
**Edit:** Saved 3 bytes thanks to plannapus!
[Answer]
# Element, 63 Chars
```
_+2:'\$\$\\varphi\=1\+`[\\cfrac1\{1\+`]?\\[d.]`"dots`[\}`]\$\$`
```
This is the most straight-forward solution. Unfortunately, the large amount of symbols in the output causes a significant increase in program length (putting the strings in the program directly causes the symbols to perform operations). I'm sure there is room for golfing, but I don't have more time right now.
Since this language is still relatively unknown, here is a link to the [interpreter](https://github.com/PhiNotPi/Element), written in Perl.
```
_+2: take input, add 0 to it to make it a number, and duplicate
' put one copy onto the control stack
\$\$\\varphi\=1\+ a "bare" string
` output the string
[ start a for loop, based on the input from earlier
\\cfrac1\{1\+ a bare string
` output it
] end the for loop
? test the second copy of the input for non-zero-ness
\\ a bare \
[d.] a "for" loop used as an if block, appends a "d"
` output it
dots` output dots
" get rid of the if condition result so the old result is on top
[ another for loop, still using the input from earlier
\}` output a }
] end for loop
\$\$` output $$
```
[Answer]
# T-SQL, ~~229~~ ~~227~~ 138
Been a while since I did an SQL answer and as always it's very verbose.
**Edit** Of course I over complicated it and didn't need a recursive query at all.
```
CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN SELECT'$$\varphi=1+\'+REPLICATE('cfrac1{1+\',@)+IIF(@>0,'d','')+'dots'+REPLICATE('}',@)+'$$'S
```
Original
```
CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT CAST('$$\varphi=1+\dots'AS VARCHAR(MAX))S,0N UNION ALL SELECT REPLACE(STUFF(S,14,0,'cfrac1{1+\'),'\do','\ddo')+'}',N+1FROM R WHERE N<=@)SELECT S+'$$'S FROM R WHERE N=@
```
This creates an inline table function that uses a recursive query to stuff in the additional `cfrac1{1+\` per iteration. Changing the dots to ddots was expensive, but saved a couple getting rid of the replace :). Also having to cast the original string as 'VARCHAR(MAX)' cost a bit.
It's used as follows [SQLFiddle](http://sqlfiddle.com/#!6/71da6/1/0):
```
SELECT *
FROM (SELECT N FROM(VALUES(0),(1),(2),(3),(4),(5))A(N)) N
CROSS APPLY A(N.N)
N S
--- ---------------------------------------------------------------------------
0 $$\varphi=1+\dots$$
1 $$\varphi=1+\cfrac1{1+\ddots}$$
2 $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$
3 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
4 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
5 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}$$
```
[Answer]
# Ruby, ~~76~~ ~~75~~ ~~71~~ 70 bytes
This feels suspiciously straightforward, so please let me know if I messed up somewhere.
Incidentally, this is the first thing I've ever written in Ruby - I was looking for a language that supported string repetition by multiplying, and Ruby seemed to do the trick.
```
f=proc{|n|'$$\varphi=1+'+'\cfrac1{1+'*n+'\dd'[0,n+2]+'ots'+'}'*n+'$$'}
```
To be applied like so:
```
f.call(0)
$$\varphi=1+\dots$$
f.call(3)
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
```
[Answer]
# J, 60 bytes
```
(<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*
```
Usage:
```
((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 0
$$\varphi=1+\dots$$
((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 3
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
```
Method:
The string `'$$\varphi=1+\ cfrac1{1+\ d dots } $$ '` is cut up at spaces and the parts are repeated `1 n signum(n) 1 n 1` times and then these parts are concatenated.
[Try it online here.](http://tryj.tk/)
[Answer]
# R, ~~93~~ 90
Much the same as the other answers. Thanks to @plannapus for the scan tip.
```
cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='')
```
`cat` used rather than paste0 as the result would end up with `\\` rather than `\`.
In use
```
> > cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='')
1: 3
2:
Read 1 item
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
```
[Answer]
# JavaScript, ~~114~~ ~~109~~ ~~106~~ 85 bytes thanks to George Reith
```
f=n=>'$$\\varphi=1+\\'+((x='cfrac1{1+\\'.repeat(n))&&x+'d')+'dots'+'}'.repeat(n)+'$$'
```
This is my first entry in a codegolf contest! Please tell me how to improve.
Previous entry (106 bytes):
```
w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{".repeat(n)+"1+\\ddots"+"}".repeat(n)+"$$"}
```
Previous entry (109 bytes):
```
x="repeat",w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}
```
Previous entry (114 bytes):
```
x="repeat";y=n=>{return a=!n?"$$\\varphi=1+\\dots$$":"$$\\varphi="+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}
```
Paste into browser console and call as `f(n)` where `n` is the number of 'steps'.
**Simplified code**:
```
function y(n) {
if(n === 0) {
return "$$\\varphi=1+\\dots$$";
} else {
return "$$\\varphi=" + "1+\\cfrac1{".repeat(n) + "1+\\ddots"+"}".repeat(n)+"$$";
}
```
[Answer]
# Pyth - 52 bytes
The simple approach in Pyth, pretty much stolen from @Sp3000's Python solution. Uses string formatting operator `%`.
```
%"$$\\varphi=1+\%sdots%s$$"(+*"cfrac1{1+\\"Q<\dQ*\}Q
```
[Try it online here](https://pyth.herokuapp.com/?code=%25%22%24%24%5C%5Cvarphi%3D1%2B%5C%25sdots%25s%24%24%22(%2B*%22cfrac1%7B1%2B%5C%5C%22Q%3C%5CdQ*%5C%7DQ&input=5).
```
% String formatting
"$$ . . . $$" String to be formatted
( Tuple (no need to close it)
+ String concatenation
*"..."Q String repetition input times
<\dQ If Q>0 then d
* String repetition
\} The character "}"
Q Q times
```
[Answer]
# Pyth, 50 bytes
```
s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$
```
[Answer]
# JavaScript (ES6), 76 ~~80~~
Partly recursive. The single/double d is most annoying part.
```
F=n=>"$$\\varphi=1+\\"+(R=d=>n--?"cfrac1{1+\\"+R("d")+"}":d+"dots")("")+"$$"
```
**Test** In Firefox /FireBug console
```
> for(i=0;i<5;i++)console.log(F(i))
$$\varphi=1+\dots$$
$$\varphi=1+\cfrac1{1+\ddots}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
```
[Answer]
# Python, ~~90~~ 116
since the most efficient solution has already been posted multiple times, i go with string replacement instead
```
f=lambda n:'$$\\varphi=1+\ddots$$'if n==0 else f(n-1).replace('\ddots','\cfrac{1+\ddots}')
# or, with exactly the same length
x='\ddots';f=lambda n:'$$\\varphi=1+'x+'$$'if n==0 else f(n-1).replace(x,'\cfrac{1+'x+'}')
```
Edit: damn, overlooked the `dots` instead of `ddots` for `n=0`, now the recursive solution with an extra clause tacked on is too ugly to compete.
```
x='$$\\varphi=1+\d%sots$$';f=lambda n:x%''if n==0 else x%'d'if n==1 else f(n-1).replace('\ddots','\cfrac{1+\ddots}')
```
[Answer]
# Haskell, 86
```
n%x=[1..n]>>x
f n="$$\\varphi=1+"++n%"\\cfrac1{1+"++'\\':drop(0^n)"ddots"++n%"}"++"$$"
```
Essentially the same approach as all solutions here. `drop(0^n)"ddots"` is cute, though!
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/3268/edit)
The [reference implementation of CRC32](http://www.faqs.org/rfcs/rfc1952.html) computes a lookup table at runtime:
```
/* Table of CRCs of all 8-bit messages. */
unsigned long crc_table[256];
/* Flag: has the table been computed? Initially false. */
int crc_table_computed = 0;
/* Make the table for a fast CRC. */
void make_crc_table(void)
{
unsigned long c;
int n, k;
for (n = 0; n < 256; n++) {
c = (unsigned long) n;
for (k = 0; k < 8; k++) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
crc_table[n] = c;
}
crc_table_computed = 1;
}
```
Can you compute the table at compile-time, thus getting rid of the function and the status flag?
[Answer]
Here's a plain C solution:
**crc32table.c**
```
#if __COUNTER__ == 0
/* Initial setup */
#define STEP(c) ((c)>>1 ^ ((c)&1 ? 0xedb88320L : 0))
#define CRC(n) STEP(STEP(STEP(STEP(STEP(STEP(STEP(STEP((unsigned long)(n)))))))))
#define CRC4(n) CRC(n), CRC(n+1), CRC(n+2), CRC(n+3)
/* Open up crc_table; subsequent iterations will fill its members. */
const unsigned long crc_table[256] = {
/* Include recursively for next iteration. */
#include "crc32table.c"
#elif __COUNTER__ < 256 * 3 / 4
/* Fill the next four CRC entries. */
CRC4((__COUNTER__ - 3) / 3 * 4),
/* Include recursively for next iteration. */
#include "crc32table.c"
#else
/* Close crc_table. */
};
#endif
```
It relies on the nonstandard [`__COUNTER__`](https://stackoverflow.com/questions/1132751/how-can-i-generate-unique-values-in-the-c-preprocessor) macro, as well as an evaluation semantics where `__COUNTER__` is evaluated before it is passed as an argument to a macro.
Note that, since `STEP` evaluates its argument twice, and `CRC` uses eight nested invocations of it, there is a small combinatorial explosion in the code size:
```
$ cpp crc32table.c | wc -c
4563276
```
I tested this in GCC 4.6.0 and Clang 2.8 on 32-bit Linux, and both produce the correct table.
[Answer]
The core loop
```
for (k = 0; k < 8; k++) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
```
can be converted into a meta-function:
```
template <unsigned c, int k = 8>
struct f : f<((c & 1) ? 0xedb88320 : 0) ^ (c >> 1), k - 1> {};
template <unsigned c>
struct f<c, 0>
{
enum { value = c };
};
```
Then, 256 calls to this meta-function (for the array initializer) are generated by the preprocessor:
```
#define A(x) B(x) B(x + 128)
#define B(x) C(x) C(x + 64)
#define C(x) D(x) D(x + 32)
#define D(x) E(x) E(x + 16)
#define E(x) F(x) F(x + 8)
#define F(x) G(x) G(x + 4)
#define G(x) H(x) H(x + 2)
#define H(x) I(x) I(x + 1)
#define I(x) f<x>::value ,
unsigned crc_table[] = { A(0) };
```
If you have Boost installed, generating the array initializer is a bit simpler:
```
#include <boost/preprocessor/repetition/enum.hpp>
#define F(Z, N, _) f<N>::value
unsigned crc_table[] = { BOOST_PP_ENUM(256, F, _) };
```
Finally, the following test driver simply prints all array elements to the console:
```
#include <cstdio>
int main()
{
for (int i = 0; i < 256; ++i)
{
printf("%08x ", crc_table[i]);
}
}
```
[Answer]
A C++0x solution
```
template<unsigned long C, int K = 0>
struct computek {
static unsigned long const value =
computek<(C & 1) ? (0xedb88320L ^ (C >> 1)) : (C >> 1), K+1>::value;
};
template<unsigned long C>
struct computek<C, 8> {
static unsigned long const value = C;
};
template<int N = 0, unsigned long ...D>
struct compute : compute<N+1, D..., computek<N>::value>
{ };
template<unsigned long ...D>
struct compute<256, D...> {
static unsigned long const crc_table[sizeof...(D)];
};
template<unsigned long...D>
unsigned long const compute<256, D...>::crc_table[sizeof...(D)] = {
D...
};
/* print it */
#include <iostream>
int main() {
for(int i = 0; i < 256; i++)
std::cout << compute<>::crc_table[i] << std::endl;
}
```
Works on GCC (4.6.1) and Clang (trunk 134121).
[Answer]
C++0x with `constexpr`. Works on GCC4.6.1
```
constexpr unsigned long computek(unsigned long c, int k = 0) {
return k < 8 ? computek((c & 1) ? (0xedb88320L ^ (c >> 1)) : (c >> 1), k+1) : c;
}
struct table {
unsigned long data[256];
};
template<bool> struct sfinae { typedef table type; };
template<> struct sfinae<false> { };
template<typename ...T>
constexpr typename sfinae<sizeof...(T) == 256>::type compute(int n, T... t) {
return table {{ t... }};
}
template<typename ...T>
constexpr typename sfinae<sizeof...(T) <= 255>::type compute(int n, T... t) {
return compute(n+1, t..., computek(n));
}
constexpr table crc_table = compute(0);
#include <iostream>
int main() {
for(int i = 0; i < 256; i++)
std::cout << crc_table.data[i] << std::endl;
}
```
You can then use `crc_table.data[X]` at compile time because `crc_table` is `constexpr`.
[Answer]
This is my [first metaprogram](http://www.ideone.com/8uMXq):
```
#include <cassert>
#include <cstddef>
template <std::size_t N, template <unsigned long> class T, unsigned long In>
struct times : public T<times<N-1,T,In>::value> {};
template <unsigned long In, template <unsigned long> class T>
struct times<1,T,In> : public T<In> {};
template <unsigned long C>
struct iter {
enum { value = C & 1 ? 0xedb88320L ^ (C >> 1) : (C >> 1) };
};
template <std::size_t N>
struct compute : public times<8,iter,N> {};
unsigned long crc_table[] = {
compute<0>::value,
compute<1>::value,
compute<2>::value,
// .
// .
// .
compute<254>::value,
compute<255>::value,
};
/* Reference Table of CRCs of all 8-bit messages. */
unsigned long reference_table[256];
/* Flag: has the table been computed? Initially false. */
int reference_table_computed = 0;
/* Make the table for a fast CRC. */
void make_reference_table(void)
{
unsigned long c;
int n, k;
for (n = 0; n < 256; n++) {
c = (unsigned long) n;
for (k = 0; k < 8; k++) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
reference_table[n] = c;
}
reference_table_computed = 1;
}
int main() {
make_reference_table();
for(int i = 0; i < 256; ++i) {
assert(crc_table[i] == reference_table[i]);
}
}
```
I "hardcoded" the calls to the template that does the computation :)
[Answer]
# D
```
import std.stdio, std.conv;
string makeCRC32Table(string name){
string result = "immutable uint[256]"~name~" = [ ";
for(uint n; n < 256; n++){
uint c = n;
for(int k; k < 8; k++)
c = (c & 1) ? 0xedb88320L ^ (c >> 1) : c >>1;
result ~= to!string(c) ~ ", ";
}
return result ~ "];";
}
void main(){
/* fill table during compilation */
mixin(makeCRC32Table("crc_table"));
/* print the table */
foreach(c; crc_table)
writeln(c);
}
```
It really puts C++ to shame, doesn't it?
[Answer]
# C/C++, 306 295 bytes
```
#define C(c)((c)>>1^((c)&1?0xEDB88320L:0))
#define K(c)(C(C(C(C(C(C(C(C(c))))))))),
#define F(h,l)K((h)|(l+0))K((h)|(l+1))K((h)|(l+2))K((h)|(l+3))
#define R(h)F(h<<4,0)F(h<<4,4)F(h<<4,8)F(h<<4,12)
unsigned long crc_table[]={R(0)R(1)R(2)R(3)R(4)R(5)R(6)R(7)R(8)R(9)R(10)R(11)R(12)R(13)R(14)R(15)};
```
Working in reverse, we wind up with an unsigned long array named crc\_table. We can omit the size of the array as the macros will ensure there are exactly 256 elements in the array. We initialize the array with 16 'rows' of data by using 16 invocations of the macro R.
Each invocation of R expands into four fragments (macro F) of four constants (macro K) for a total of 16 'columns' of data.
The macro K is the unrolled loop indexed by k in the code from the original question. It updates the value c eight times by invoking the macro C.
This preprocessor based solution uses quite a bit of memory during macro expansion. I tried to make it a little shorter by having an extra level of macro expansion and my compiler puked. The code above compiles (slowly) with both Visual C++ 2012 and g++ 4.5.3 under Cygwin (Windows 7 64 bit 8GB RAM).
Edit:
The fragment above is 295 bytes including white space. After expanding all of the macros except for C it grows to 9,918 bytes. As each level of C macro is expanded the size grows quickly:
1. 25,182
2. 54,174
3. 109,086
4. 212,766
5. 407,838
6. 773,406
7. 1,455,390
8. 2,721,054
So by the time all the macros have been expanded, that little 295 byte file expands into over 2.7 megabytes of code that must be compiled to generate the original 1024 byte array (assuming 32 bit unsigned long values)!
Another edit:
I modified the C macro based on a macro from another answer to squeeze an extra 11 bytes out, and greatly reduced the full expanded macro size. While 2.7 MB isn't as bad as 54 MB (the previous final size of all macro expansion), it is still significant.
[Answer]
I would modify the previous answer by replacing the last three lines with:
```
#define crc4( x) crcByte(x), crcByte(x+1), crcByte(x+2), crcByte(x+3)
#define crc16( x) crc4(x), crc4(x+4), crc4(x+8), crc4(x+12)
#define crc64( x) crc16(x), crc16(x+16), crc16(x+32), crc16(x+48)
#define crc256( x) crc64(x), crc64(x+64), crc64(x+128), crc64(x+192)
```
Where crcByte is his K macro without the trailing comma. Then build the table itself with:
```
static const unsigned long crc32Table[256] = { crc256( 0)};
```
And never leave out the size of the array as the compiler will then verify that you have the correct amount of elements.
] |
[Question]
[
### Background
In 1960, the [11th General Conference on Weights and Measures](https://physics.nist.gov/cuu/Units/international.html#:%7E:text=The%20International%20System%20of%20Units,G%C3%A9n%C3%A9rale%20des%20Poids%20et%20Mesures) defined the Système International d'Unités (SI) Units which scientists still use today.
The metre and the kilogram became standard units in that conference. These were based on powers of 10 (10, 100, 1000, etc.).
For example:
* there are *100* centimetres in one meter
* there are *1000* meters in one kilometer
* there are *1000* grams in one kilogram
### Time units
That conference also established the second as the standard unit for time. Now, this is interesting, because this is not based on powers of 10.
* There are *60* seconds in one minute
* There are *60* minutes in one hour
* There are *24* hours in one day
So let's make our own!
In our system, we will have:
* *100* seconds in one minute
* *100* minutes in one hour
* *10* hours in one day
### Your task
Given an input of a time (in 24-hour time), convert it to our system (10-hour).
**Example:**
Input: `12:34:56`
First, convert this to a number of seconds:
`(12 * 60 * 60) + (34 * 60) + 56 = 45296`
We have 100,000 seconds in our system, and in the normal system there are 86,400. We need to adjust for that:
`45296 / 86400 * 100000 = 52425.9259259259`
We round this to 52426. Note: this must be rounded.
Now, convert back to hours, minutes and seconds. This is easy because our 10-100-100 system lets us just place the colons in: `5:24:26`. This is our final answer.
**Note: you do not need to insert the colons.**
### Test cases
You can input and output in any format you want, including just an integer as the output format.
Here are some test cases:
```
Input Output
12:34:56 5:24:26
00:00:00 0:00:00*
23:59:59 9:99:99
11:11:11 4:66:10
15:25:35 6:42:77
01:02:03 0:43:09*
```
\* In these ones, you do not have to fill the minutes and seconds up to two places: i.e., you may output `0:0:0` and `0:43:9`.
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
[Answer]
# JavaScript (ES6), 33 bytes
Expects `(h,m,s)` and returns an integer.
```
(h,m,s)=>(h*60+m+s/60)*625/9+.5|0
```
[Try it online!](https://tio.run/##XY/LCoMwFET3/Yq7NJqadyQX7L@I1T5QU5rSVf89jYQuGpizOwwz9@E9hPF5e7yOmz9Pce5jdaUrDaQ/Vdfa8mZtArOc1FYa5prWfHgc/Rb8MrWLv1RzJSQFpSkYSwgwBgalRmkP/xZwCplsceR7Ckuq1ON2suXQ7SksIShksqXRWhRllzAUZEKZbFnUEruu3JV6ID0A9dulFXIXvw "JavaScript (Node.js) – Try It Online")
### How?
By converting to minutes instead of seconds, the final ratio is:
$$\frac{60\times 100000}{86400}=\frac{625}{9}$$
This is one byte shorter than:
```
(h,m,s)=>(h*3600+m*60+s)/.864+.5|0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
No 05AB1E yet? Let's fix that!
This is a direct port of hakr14's [canvas answer](https://codegolf.stackexchange.com/a/252955/111498).
```
60βƵOƵ7/*ò
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fzODcpmNb/Y9tNdfXOrzp//9oQ1MdI1MdY9NYAA "05AB1E – Try It Online")
```
60βƵOƵ7/*ò
60β Convert input from base 60
ƵOƵ7/ Push 125/108
* Multiply input and 125/108
ò Round
```
Thanks to @TheThonnu for this answer:
```
60β.864/ò
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fzODcJj0LMxP9w5v@/482NNUxMtUxNo0FAA "05AB1E – Try It Online")
```
60β.864/ò
60β Convert input from base 60
.864 Push .864 (108/125)
/ Divide input by 108/125
ò Round
```
[Answer]
# [Python](https://www.python.org), 39 bytes
Port of `@Arnauld`'s answer, expects an input of `h, m, s` and returns an integer.
```
lambda h,m,s:round((h*60+m+s/60)*625/9)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY31XMSc5NSEhUydHJ1iq2K8kvzUjQ0MrTMDLRztYv1zQw0tcyMTPUtNaHKU9LyiyBqFTLzFKKjDY10jE10TM1idRSiDQx0wAjENjLWMbUEIhDb0FAHjMBsUx0jUx1jUzBbB6g5NtaKS6GgKDOvRCNNA2ywJtSuBQsgNAA)
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
[ 60 * rot 60 / + + 625/9 * round ]
```
[Try it online!](https://tio.run/##PY/BDoIwEETvfMV41URKa0nQDzBevBhPhgOpJRKkxXZ7MIRvx2LQ3clmd/L2MHWlyLrpejmdj3u02hn9RFfR4zu2dTCKGms8eqeJ3r1rDMHrV9BGaY9DkgwJYg2QOcQOGccYz1VklDV3j64xgSL5sMH5BWVs0fj7LWZx8TeybNHPEBJcIpN/gwkwDjYTYzLdkDOs4SzNS4pN7JzLtPiawdxRRqZunCeBcg7TW69jxh6eKtVupw8 "Factor – Try It Online")
Expects `seconds minutes hours` as integers. Port of Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/252949/97916).
```
! 56 34 12
60 ! 56 34 12 60
* ! 56 34 720
rot ! 34 720 56
60 ! 34 720 56 60
/ ! 34 720 14/15
+ ! 34 720+14/15
+ ! 754+14/15
625/9 ! 754+14/15 69+4/9
* ! 52425+25/27
round ! 52426
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḅ60÷.864+.Ḟ
```
A monadic Link that accepts a list of non-negative integers, `[h, m, s]`, and yields a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjlYzg8Pb9SzMTLT1Hu6Y9////2hDIx1jEx1Ts1gA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjlYzg8Pb9SzMTLT1Hu6Y9//opIc7Z@gcbs961DBHwdZO4VHDXM3I//@jow2NdIxNdEzNYrl0og10gBDEMDLWMbUEIhDb0FAHjMBsUx0jUx1jUzBbB6gTpssQwjCEaDeEmBMLAA "Jelly – Try It Online").
### How?
```
ḅ60÷.864+.Ḟ - Link: list of non-negative integers, T = [h, m, s]:
ḅ60 - convert T from base sixty -> 3600*h+60*m+s = seconds
.864 - 0.864 (seconds per "second")
÷ - (seconds) divide (0.864) -> "deconds"
. - a half
+ - (deconds) add (a half)
Ḟ - floor to nearest integer
```
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes
```
h,m,s=map(int,input().split())
print(round((h*3600+m*60+s)/.864))
```
Takes input as `HH mm ss` and outputs as `Hmmss`
-3 thanks to Jonathan Allan
[Try it online!](https://tio.run/##Dcg5DoAgEADA3ldQ7gJBFCQ2PsbEAhKBDUfh65FqkqGv@ZzMGF5GWa94E4TUZEjUG6Cq9IYpLlRmQ8k9PQCeG6e1iNxpUXFVp7OIY2w7M5Yd7gc "Python 3 – Try It Online")
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~73~~ 68 bytes
*-5 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
f(char*x){return((atoi(x)*3600+atoi(x+3)*60+atoi(x+6))*125+54)/108;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6Fjdd0jSSMxKLtCo0q4tSS0qL8jQ0EkvyMzUqNLWMzQwMtCEcbWNNLTM4x0xTU8vQyFTb1ERT39DAwroWapZ6bmJmnoZmNRdnQVFmXkmahpJqipIOkDI0sjI2sTI1U9LUtOaq5YIohzkBAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I⌊⊘⊕∕↨⁶⁰A·⁴³²
```
[Try it online!](https://tio.run/##HcaxCoMwEADQX8l4gVhStS5uWqTZ3MXhiAcGYiIx5vevpW96dsdkI3rmObmQYcQrw@RjTPBBX2gDE2yig0L@/e2K2wgGvAg6rYQJ551BSiX0o21q@dczL8uzVqJplXh168pV8V8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list. Explanation:
```
A Input array
↨ Converted from base
⁶⁰ Literal integer `60`
∕ Divided by
·⁴³² Literal number `0.432`
⊕ Incremented
⊘ Halved
⌊ Floor
I Cast to string
Implicitly print
```
26 bytes for string I/O:
```
✂⪫⪪﹪%06.0f∕↨⁶⁰I⪪S:·⁸⁶⁴¦²:¹
```
[Try it online!](https://tio.run/##LYxRC8IgFEb/igjBFWy4tSTsbeulIAj8BeKsLoiO7W5/3xbs6TscDp//uslnF0t5TZgIbEQf4JExgR0jEjzzsMQM/KB0pd5cshuuOATo3BxAK8l6N9Pe3tO4kKXt6ANCMm64ENuq6qLbPzS7lKwW4lpK3ZhTa866HNf4Aw "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
‾-┴‾n‾]÷×1½+u
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDNFLSV1MjUzNCV1MjAzRW4ldTIwM0UlNUQlRjclRDcldUZGMTElQkQldUZGMEIldUZGNTU_,i=JTVCMTIlMkMzNCUyQzU2JTVE,v=8)
##### Explanation:
```
‾-┴‾n‾]÷×1½+u | Full code (converted to half-width)
--------------+------------------------------------
‾-┴ | Convert input from base 60
‾n‾]÷ | Push 125/108
× | Multiply
1½+ | Add .5
u | Floor
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
0.864<.@%~0.5+60#.]
```
[Try it online!](https://tio.run/##PYvBCkBAFEX3vuJGkvB6M@NNiFLKysreSiQbf@DXh5Kpcxenzj1dSMmOrkGCHIzmXUEY5ml0TJUtW@rjm0kyyxEtLg0QbOtxYYfSMCXE/s788bs2kPrF9@rDu0ALjPi/AmuwcQ8 "J – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ì60 /.864 r
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7DYwIC8uODY0IHI&footer=7Ew&input=WzEyIDM0IDU2XQ)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
/hyiQ60y.864
```
[Try it online!](https://tio.run/##K6gsyfj/Xz@jMjPQzKBSz8LM5P//aEMjHWMTHVOzWAA "Pyth – Try It Online") Input takes a list `[hours, minutes, seconds]`, and outputs an integer.
**Explanation:**
```
/hyiQ60y.864 # whole program
Q # take the input
i 60 # and convert it from base 60 to decimal
y # double it
h # increment it
/ # then integer divide it by
y.864 # 0.864 doubled (which is 1.728)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes
```
\d+
$*
+`1:
:60$*
1
125$*
::
54$*
1{108}
```
[Try it online!](https://tio.run/##HccxCoRAEETRvM6xgmjS1WOL1gW8hIGCBiYbLJuJZx9H4cGv@u3/47vmqp6WPG8tPg3ahYJ6K5OgR6mE6J5/0oYrZ7pSp@hhphc8KcYCpF5gyEMpYJS5LN0 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of my golf to @matteo\_c's answer.
```
\d+
$*
```
Convert the hours, minutes and seconds to unary.
```
+`1:
:60$*
```
Convert from base 60, by multiplying each `1` by 60 as it passes a `:` on its way to being a number of seconds.
```
1
125$*
```
Multiply by 125.
```
::
54$*
```
Add 54.
```
1{108}
```
Integer divide by 108 and convert to decimal.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 15 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╚*j╟*++╔/☼*∞)i½
```
Inputs as three loose floats, output as a single integer.
[Try it online.](https://tio.run/##y00syUjPz0n7///R1FlaWY@mztfS1n40dYr@oxl7tB51zNPMPLT3/39DIz0DBWMTIGFqpmfAZWAAZMEJLiNjkIQllOAyNASy4ASXoSmQZQQijE1BekESBiDzDIDaAA)
**Explanation:**
Even though MathGolf has single-byte constants for `60`, `3600`, `86400`, and `100000`, it's still pretty long because it's missing base-conversion and round builtins, so those have to be done by manually.
```
╚* # Multiply the first (implicit) input by 3600
j # Get the second input-float
╟* # Multiply it by 60
+ # Add the two together
+ # Also add the third (implicit) input-float
╔/ # Divide this by 86400
☼* # Multiply it by 100000
∞)i½ # Round it:
∞ # Double this float
) # Increase it by 1
i # Truncate it to an integer
½ # Integer-divide it by 2
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96) \approx \$ 9.05 bytes
```
aKAd.864/Zv
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharE70dU_QszEz0o8ogIlCJBauiDU11jEx1jE1jISIA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wVbPascKR6XqiloFBYWYEl07BaUon4qlpSVpuhZrE70dUxIjDA0s9LWiyiBii6K8IYyl0UopSrE33aMNjXQUjE10FEzNYrmiDXQUQAjIMjIGClmCMJBjaKijAMEgjqmOghEQG5uCOEA2kBkLMRQA)
#### Explanation
```
aKAd.864/Zv # Implicit input
aKAd # Convert from a list of digits in base-60
.864/ # Divide by .864
Zv # Round to the nearest integer
# Implicit output
```
] |
[Question]
[
Given an integer \$N\$, print or return integers \$a\$, \$b\$, and \$c\$ that satisfy all of the following conditions, if such integers exist:
* \$a \times b + c = N\$
* \$a\$, \$b\$, and \$c\$ are all prime
* \$a > b > c\$
If no valid combination of integers exist, you should return nothing, 0, None, an empty list, or raise an error.
If multiple valid combinations of integers exists, you can print or return any of them or all of them in a data type of your choosing.
A list of multiple solutions does not need to be sorted, and since we know that \$a > b > c\$, you can return them in any order.
```
Examples:
Input: 17
Output: 5 3 2
Input: 20
Output: None
Input: 37
Output: 7 5 2
Input: 48
Output: None
Input: 208
Output: [(41, 5, 3), (29, 7, 5)]
```
This is code golf, so the code with the lowest byte count wins.
Inspired by [this Redditor's neat dream](https://www.reddit.com/r/theydidthemath/comments/sgjgp5/request_i_just_took_a_nap_and_had_a_dream_where/).
[Answer]
# [Wolfram Mathematica](https://www.wolfram.com/mathematica/), 29 bytes
```
Solve[a*b+c==#>a>b>c,Primes]&
```
Test cases:
```
Solve[a*b+c==#>a>b>c,Primes]&@17
Solve[a*b+c==#>a>b>c,Primes]&@20
Solve[a*b+c==#>a>b>c,Primes]&@37
Solve[a*b+c==#>a>b>c,Primes]&@48
Solve[a*b+c==#>a>b>c,Primes]&@208
```
>
> {{a -> 5, b -> 3, c -> 2}}
>
>
> {}
>
>
> {{a -> 7, b -> 5, c -> 2}}
>
>
> {}
>
>
> {{a -> 29, b -> 7, c -> 5}, {a -> 41, b -> 5, c -> 3}}
>
>
>
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 210 bytes
```
(load library
(d p prime?
(d f(q((n k)(i(e n k)0(i(g n k 2)(g n k 2)(f n(+ k 1
(d g(q((n k j)(i(l(/ n k)j)0(i(*(l(- n(* k j))j)(l j k)(p(- n(* k j)))(p k)(p j))(list k(- n(* k j))j)(g n k(+ j 1
(d F(q((n)(f n 2
```
[Try it online!](https://tio.run/##XY7NDoIwEITvPsUctxgjoAnevPEeGH7SUrFULjx93V1INJ7m22lnZxc7rd6@Q0rkX00Lbx@xieuBWgSEaJ/dXbinmWjCaMhSB4GcaRBCab7QY6IjYyGhYQ/BSczTWYNOoxnPJ/6c6TOb5OFkf/i1eVRPmPjMBeNfSpu50m2VtVbqHSgT1bhUBixlvstN9bpJUZn0AQ "tinylisp – Try It Online")
Gotta love golfing in tinylisp...
Thanks to DLosc for saving some bytes... 32 to be exact.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.primes`, 64 bytes
```
[ dup nprimes swap 3 [ first3 * + = ] with filter-combinations ]
```
[Try it online!](https://tio.run/##NY29CsIwFIX3PsWZFYNaoUVxFhcXcSodYry1F9skJilFxWevUel2OH9fJVUwbjgd94fdGjdymhq0MtTCOm7Jw9O9I62i@rr/SJn2zFrGISsP6yiER6zrgCtpcrLhpwxstMcmSV5YZFjOkWZY5VHkeA8FLp2FHhG9tEhRoGLnQ4oJptiiRM8RWHETyM1G5O@1jAdCiFiJtjWeQFLVwwc "Factor – Try It Online")
## Explanation
Get all the combinations of three primes that satisfy `a * b + c = N`. `a > b > c` is inherent by virtue of the fact we're filtering combinations without repetition.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 37 bytes
```
FGQIP_GFHGIP_HFNHIP_NIq+*GHNQ
G
H
N.q
```
hacky, but works
[Try it online!](https://tio.run/##K6gsyfj/38090DMg3t3Nwx1Iebj5eQApP89CbS13D79ALncuDy4/vcL//w3NAQ)
explanation:
```
Q = eval(input())
F for
G G
Q in range(Q):
I if
P_ prime(
G G
):
F for
H H
G in range(G):
I if
P_ prime(
H H
):
F for
N H
H in range(H):
I if
P_ prime(
N N
):
I if
G G
* *
H H
+ +
N N
q ==
Q Q:
(newline) print(
G G
)
(newline) print(
H H
)
(newline) print(
N N
)
.q exit()
```
[Answer]
# Excel, 164 bytes
```
=TEXTJOIN(",",,LET(q,SEQUENCE(A4),a,FILTER(q,MMULT((MOD(q,TRANSPOSE(q))=0)*1,q^0)=2),b,TRANSPOSE(a),c,(a>b)*(A4-a*b),IF(XLOOKUP(c,a,a^0,0)*(b>c),a&" "&b&" "&c,"")))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJngxX4cBPILZYwXoD?e=T4EoAE)
## Explantion
```
=TEXTJOIN(",",, ~ ) # Separates multiple answers with a comma
LET(q,SEQUENCE(A4), # q = (1..A4) listed vertically
a,FILTER(q, ~ ), # a = primes in q
MMULT( ~,q^0)=2 # a number is prime if the sum of the row is 2
MOD(q,TRANSPOSE(q))=0)*1 # creates a qxq array where if row# mod column = 0 then 1 else 0
b,TRANSPOSE(a), # b primes listed horizontally
c,(a>b)*(A4-a*b), # 2-dim array where if a>b then c = A4 - a*b
IF(XLOOKUP(c,a,a^0,0)*(b>c),~,"") # if c is prime and b>c then return value else ""
a&" "&b&" "&c # a b c
```
## Insider Beta Version using LAMBDA, 157 bytes
```
=TEXTJOIN(",",,MAKEARRAY(A1,A1,LAMBDA(a,b,LET(c,MAX(A1-a*b,1),p,LAMBDA(x,SUM((MOD(x,SEQUENCE(x))=0)*1)=2),IF((a>b)*(b>c)*p(a)*p(b)*p(c),a&" "&b&" "&c,"")))))
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com) + dfns, ~~63~~43 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵⌿⍨(∧/1pco¨⍵)∧⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵}∘(3cmat⊢)⍨
```
Hats off to @ovs for a 2+18 bytes shave!
Tacit function with an anonymous function baked in.
Returns a 3-col matrix, with as many rows as possible results.
`dfns` is like a library of useful functions:
* the `pco` function I'm using, which checks for primality, can be found there; and
* the `cmat` function generates the combinations of possible `a`, `b`, and `c` values.
[Try it on online!](https://tio.run/##SyzI0U2pTMzJT/@vXpCcr66gnpybWKKu8KhvqnOkgnpKWl6xOheQ4@mv8KhtgoLB/zQgVf2od@ujnv2PeldoPOpYrm8I1HhoBVBME8h71LvLVsPgUceMRz3btQ0h9OHpRhCG5qPeTqC6WiBPwxhk0aOuRUCxFf//px1aYWiuYGSgYGyuYGIBZFgAAA)
The TIO link has 2 more bytes because of `f←`, which I'm using to make it easier to test the function. It also takes a long time because I'm being wasteful with my primality checks; here is the output on my machine:
```
f¨ 17 20 37 48 208
┌─────┬┬─────┬┬──────┐
│5 3 2││7 5 2││29 7 5│
│ ││ ││41 5 3│
└─────┴┴─────┴┴──────┘
```
Explanation:
`(3cmat⊢)` builds a 3-column matrix with all possible values of `a`, `b`, and `c`, already satisfying the restriction that `a > b > c`:
```
(3cmat⊢) 4
0 1 2
0 1 3
0 2 3
1 2 3
```
Then, `{⍵⌿⍨(∧/1pco¨⍵)∧⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵}` takes the original number on the left and that 3-col matrix on the right, and takes all rows that satisfy two criteria simultaneously:
* the rows only have prime numbers (checked with `(∧/1pco¨⍵)`); and
* `a×b+c` equals the original input (checked with `⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵`).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~28~~ ~~25~~ ~~24~~ 23 bytes
```
Zq"@tG-YfhXHd0>AHn3=*?H
```
[Try it online!](https://tio.run/##y00syfn/P6pQyaHEXTcyLSPCI8XAztEjz9hWy97j/38jAwsA "MATL – Try It Online")
```
Zq" % for each prime less than (or equal to) the input
@t % duplicate it on the stack
G- % subtract it from the input
Yf % get the prime factors of the result
h % concatenate that with the current iterating prime
XH % save that in the H clipboard
d0>A % check that it's strictly increasing
Hn3= % and has 3 elements
*? % if both conditions are true
H % push that result list back on the stack
```
Prints all valid results.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
~æ3ḋ'÷*+?=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ+w6Yz4biLJ8O3Kis/PSIsIiIsIjM3Il0=)
```
~ # Filter (implicit) range 1...n by...
æ # Is prime?
3ḋ # Combinations of length 3
' # Filtered by...
÷*+ # a*b+c
?= # Equals input?
```
Outputs a list of all valid lists.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
f=(n,b)=>p(b)&p(a=n/b|0)&p(c=n%b)&a>b?[a,b,c]:b!=n&&f(n,-~b);p=(n,i=n)=>n%--i?p(n,i):i==1
```
[Try it online!](https://tio.run/##ZYtLDoIwFEW3ggNIX9IqfhIMprADNkAYvFarNeS1AUJiFLde6djJzf2dJ8446sH6SZC73kIwkhFXICvPFGSeoaSd@uTRaknp2mGl6ha54ror1UZSlpkVEV8FFx9hK2nFKRXC1j5mKK2U@2DcwGbsE2eStuCHnB8Lfjp3MA2vt3Y0uv627d09friJCrBonPTjb22wgSX8AA "JavaScript (Node.js) – Try It Online")
If stackoverflow allowed as an error, then
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
f=(n,b)=>p(b)&p(a=n/b|0)&p(c=n%b)&a>b?[a,b,c]:f(n,-~b);p=(n,i=n)=>n%--i?p(n,i):i==1
```
[Try it online!](https://tio.run/##ZYtLCoMwFEW34sSSB0lrP2CxPN2BGxAHL6mpKZIEFaG0duupGXdyuZ9zn7TQpEbjZ2HdvQtBI7NcApaeSdh5RmgP8pNFq9CmW0elrBrikqu20BssvhJuPt4M2u1oUyFM5WOGwiAeg3YjW2hInE6anJ8yfs755drCPL7eytnJDd1@cI/IcB0VYFU0q/5vramGNfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 137 bytes
```
lambda n:[(a,b,c)for a in R(n)for b in R(n)for c in R(n)if all([a>b>c,a*b+c==n,all(all(n%m for m in R(2,n))for n in (a,b,c)),c])]
R=range
```
[Try it online!](https://tio.run/##TY2xDsIwDER3vsILkg1egAEJKf2IrqWDHQhEStwq6sLXB6WAxHDDO73Tza/lOdmpBnetSbLeBOwyoLCypzAVEIgGPdoK@g/@BzGApISDdNp5lp3uvXPGrWuxbYbm549/ZKN1b42/T8R@pHHTuyL2uNe5RFsw4OFMVN8 "Python 3 – Try It Online")
Thanks to @attiP for `R=range` -8 bytes
# [Python 3](https://docs.python.org/3/), 139 bytes
```
eval("lambda n:[(a,b,c)for aRfor bRfor cRif all([a>b>c,a*b+c==n,all(all(n%m for mR[2:])for n in (a,b,c)),c])]".replace("R"," in range(n)"))
```
[Try it online!](https://tio.run/##LYxNCsIwEIWvMgwIGR1c6K7QHiLbkMVkTLWQTksQwdNHUly8b/H@9u/7tdm9tfyR4rDImh4CNgQnnFhp3iqI70wH1S8zSCkuyJQmZTmni46jcfe67LRCL64@3IZ47A0Wg/8fsUaKeK15L6LZoUfGnlexZ3ZGSNTaDw "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 112 bytes
```
P=k=1
p=r=[]
n=input()
while k<n:
if P%k:r=r+[(k,b,n-k*b)for b in p if b>n-k*b in p];p+=k,
P*=k*k;k+=1
print r
```
[Try it online!](https://tio.run/##HY0xCsMwDAB3vUJLIbHdoe1QSKq@wXvIYmiIUFGEcCl9vUsy3nFw9qvrptfWMgldwMhpmkGJ1T616@G78vuF8tABkBfMJxmcPE6dpJL0LKH0y@ZYkBVtL8rzsAfPo0WSBJgDSZBR4r5w1ore2u3@Bw "Python 2 – Try It Online")
---
A port of [l4m2's Javascript answer](https://codegolf.stackexchange.com/a/242070/64121) with a bit of their help comes in at ~~101~~ 99 bytes:
```
f=lambda n,b=1:all(p%k for p in(n/b,b,n%b)for k in range((n%b>1)+(n/b>b),p))*(n/b,b,n%b)or f(n,b+1)
```
[Try it online!](https://tio.run/##TYzBDoIwDIbvPkUvhFWaKGiiIYGbD7IpKAHK0uwwnn52N05/8vX76vfw27hJaewWu7qPBSbX1a1dFuOLGcZNwMPEhi@OHHHhMKNZEYjl72CMsr7GKhu9Q/KI54Ot8mj0Z1VjymXM5YOguRLcdO/P9gQQZM8D4GXiAJE0iqhkiO/Bh@OtfIlsUqY/ "Python 2 – Try It Online")
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 10 bytes
```
ÆRUŒƈ×+ƭ/Ƙ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1Do0cnJxoenax9bq297aOmx9v@H249Oerhzhmbk//@G5joKRgY6CsZA2sQCxLYAAA "Jelly – Try It Online") (the Jelly equivalent)
Outputs all possible solutions, or `[]` if there are none. And, the equivalent vanilla Jelly answer:
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ÆRUœc3×+ƭ/=¥Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1Do0cnJxoenax9bq297aOmx9v@H249Oerhzhmbk//@G5joKRgY6CsZA2sQCxLYAAA "Jelly – Try It Online")
## How they work
```
ÆRUŒƈ×+ƭ/Ƙ - Main link. Takes an integer N on the left
ÆR - Primes from 2 to N
U - Reverse
Œƈ - Combinations of 3, no replacement
Ƙ - Keep those that equal N under:
/ - Reduce [a, b, c] by:
ƭ - Tie two dyads f, g:
× - Product
+ - Addition
This maps [a, b, c] -> [a×b, c] -> a×b+c
```
The normal Jelly one is identical, except that `œc3` is special-cased as `Œƈ` and `=¥Ƈ` is equivalent to `Ƙ`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~83~~ 78 bytes
```
->n{(2..n).select{|x|/^(!!+)\1+$/!~?!*x}.combination(3).find{|c,b,a|a*b+c==n}}
```
[Try it online!](https://tio.run/##BcHhCoMgEADgV5kw4i7bldtv14uMgVqCsK5YBQ11r27f993tr3hdbk@OcCdipHX8jG6L6UjtG4SQ@FLy2op/L@ojk5snG9hsYWZ4IPnAQ0yusY1JprbSac05l@UCikh1HdJkFqg8lhM "Ruby – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
ḟo=⁰§+←oΠtṖ3İp
```
[Try it online!](https://tio.run/##ASQA2/9odXNr///huJ9vPeKBsMKnK@KGkG/OoHThuZYzxLBw////Mzc "Husk – Try It Online")
Outputs c<b<a if a solution exists, otherwise quits after 1 minute with a 'the request exceeded the 60 second time limit and was terminated' warning from the '[try it online](https://tio.run/##ASQA2/9odXNr///huJ9vPeKBsMKnK@KGkG/OoHThuZYzxLBw////Mzc "Husk – Try It Online")' interpreter.
Arguably this isn't a real 'error' (and [Husk](https://github.com/barbuz/Husk) itself would happily run forever looking for a solution among higher and higher entries in the infinite list of primes), so for 1 more byte we can have:
`ḟo=¹§+←oΠtṖ3fṗḣ` (which only searches among primes less than the input).
```
ḟo # return the first...
Ṗ3 # ...list of 3 items selected from
İp # ...the infinite list of primes
# that satisfies:
§+ # the sum of...
← # ...the first item
oΠ # ...and the product of
t # ...the tail (all except first item)
=⁰ # is equal to the input
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 176 bytes
```
param($n)for($c=1;++$c-lt$n){for($b=$c;++$b-lt$n){for($a=$b;++$a-lt$n){if($a*$b+$c-eq$n-and(&($p={param($t)!($t-2)-!(2..($t-1)|?{!($t%$_)})})$a)*(&$p $b)*(&$p $c)){$a,$b,$c}}}}
```
[Try it online!](https://tio.run/##XZBRa8IwFIXf@yuucieJpmKrsg0pE2R73Zh7G0OSmOJGtV0T2aD2t3dJq1V3C5f0u@ecG5KlPyrXG5UkvkxzVWEcFVXGc74luKNxmhOUUTAbDFD6ibGoqJmIUDooLiGPUDjIj/AztqyPwnnVN@58vluTHsEsKo4bDO3Y5ofU75BwOHTngB4eCkdvcEVL@yGnfdLDDFCcDpLSAjlDwVCWtqrS8@bEA1sM5iS4dX3KYMwgpLTl4cj1CzCuhbZNr4WTu3/CcFSTSVBLXew9A@ezGgoHeErzRy43/rP4UtJAURvRKG0WXCsGqH4zO1BriABXs2acK71PjCU9jM/ievb@slzstUm3TeDHvEl0tdxLqbQG6@u2sV2wD2z/m8jurFW/HVPd3tOG8/S1uUGTdeUtvbL6Aw "PowerShell Core – Try It Online")
I tried using ranges, but it gets really slow, probably because it is allocating too many of them, so `for` for now :)
[Slow draft with ranges, 175 bytes](https://tio.run/##XVBba8IwFH7vr4hylMSlxVZlG1ImyPa6Mfc2RklrnAy1XRLZoOa3dyepl20pHL58txxalV9S6bXcbMKiVLKBVVo3lVBiS2HHKKg0jiJEh14NIoUsAOVgfoR3yIbvBvJQ7JY4EWYeigHkV4jlJ@wcQfsUqrQ@NhvWwREmLOzQJIocjpkr82Gn9SBjFj8QbED7UBHITwAFvw2HnENmrW1sEMxoQPBwMqPxtZsTTkacJIyd@WTo5i9i5I04Jn@N45t/xmTomXHsra72lhOXQw8jB/JQqntRrMPH/EMWhtQ@CEZqMxdacgLyu0JBLkmK609bWUm93xhk@rC6mL32@rSY77Upt23h26xtdGexLwqpNcFc91zbJfif8d5Wdqdn98ux1b17euGiPrcbtF1/sjawzQ8 "PowerShell Core – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~139 130 122 118~~ 115 bytes
```
a,b,c,z,y;p(x){for(y=z=1;++z<x;)y&=x%z>0;y=!y;}f(n){for(a=n;a&&p(c=(c<3?b<3?b=--a-1:--b:c)-1)|p(b)|p(a)|a*b+c-n;);}
```
[Try it online!](https://tio.run/##jY7BDoIwEETvfoWSQHalTUBMNCzVH/HS1tRwsDbEAy3w7VXwAzCZ2cu8zI7mD61jlEwxzQLz5KDHwbw68CKIkvI8ND2hz0SfhktBXuw8TQbsD5LCkswyB1qAbqqrmi04l7ysOVe1Rl7i6EDNR@Io9yrX3BLSFJ@ytYDDxkB5Qtq4rrVvA0l63y662YQts76ZgUOxilTrLcfzH4/WmCl@AA "C (gcc) – Try It Online")
Slightly golfed less.
```
a,b,c,z,y;
p(x){
y=z=1;
for(;++z<x;)
y&=x%z>0;
y=!y;
}
f(n){
a=n;
while(a&&p(c=(c<3?b<3?b=--a-1:--b:c)-1)|p(b)|p(a)|a*b+c-n);
}
```
[Answer]
# 80386 Machine Code, ~~110~~ ~~107~~ 99 bytes
[Try it online!](https://tio.run/##fVNdb5swFH22f4XFNMmstCUfUqN22y/I014ThMy1SdyCYWCirNP@@rJrm5BU3SYh@5x7r8/9sIHbHcDpgzZQDVKxz72Vurnbf6U0z4W1nS4Gq/KccyNelIxjdmi0ZHnJY/aTEozp6zxnnBLyLeInUjcHpqROmIIjJcemY6o4Jm6hwSdGtk4fKXnGqFemuo4SqNvgnKN5x/LZaCouppQSqSAoey2vjCx3Wt71Lk0@O7vEdKpNAgNRVaxFbQNsnV57i/964V/e/ty3rodqpE5KSDkyn9a15ZnUTkBNAhslj1lyadBxdsOW2dUAR9sqG9U6ZSkOELvcV5a2uLdDvw@@gGBC8jwC8NNp6XqaDpwLg3HeWL@Rb4aJ3YL8jvH6EOKt6q0TTYLys3lla7y2u@KHVSw9ihVFCUzQW8AKmjaEeQBnMLZwIiSOKImf6C9KeyushvDQSq6NZZ9E1yXMIfPm2R2aCkMr5d9fFJos2q3Z2sgZ/CXl5cR9xqJ1@JFFNxBxEwcsI44pRoJFRQluRdh67Tep/1pg22FZ/FKaQ2KzyJ4oKblI0IrIB5U8@iiZ/7YGJcUmzdw68@s8C9rufC20Cf9XUJ89TCJ8cYXn6erKsVg6cn8f6HIV2GCgqWuFqrZh0Il@7wc@dIalLuHpN5SV2PWn23oxxwUH@wXPq@oP)
When there is no valid answer, the program crashes, and I hope this belongs to "raise an error" category.
---
Thanks for the wonderful [tip](https://codegolf.stackexchange.com/a/235553/108859) for skipping instructions. I'm still trying to get rid of the `call`s which take 5 bytes each, but it's not clear for now.
`ecx` is the input number, and `edx` is the pointer to the output array
```
00000000 <f>:
0: 89 cf mov edi,ecx
2: 31 db xor ebx,ebx
4: 89 d8 mov eax,ebx
00000006 <L0>:
6: e3 40 jecxz 48 <err>
8: 83 f8 02 cmp eax,0x2
b: 7f 0b jg 18 <_1>
d: 83 fb 02 cmp ebx,0x2
10: 7f 03 jg 15 <_0>
12: 49 dec ecx
13: 89 cb mov ebx,ecx
00000015 <_0>:
15: 4b dec ebx
16: 89 d8 mov eax,ebx
00000018 <_1>:
18: 48 dec eax
19: 89 c5 mov ebp,eax
1b: e8 29 00 00 00 call 49 <p>
20: 73 e4 jae 6 <L0>
22: 89 dd mov ebp,ebx
24: e8 20 00 00 00 call 49 <p>
29: 73 db jae 6 <L0>
2b: 89 cd mov ebp,ecx
2d: e8 17 00 00 00 call 49 <p>
32: 73 d2 jae 6 <L0>
34: 89 ce mov esi,ecx
36: 0f af f3 imul esi,ebx
39: 01 c6 add esi,eax
3b: 39 fe cmp esi,edi
3d: 75 c7 jne 6 <L0>
3f: 89 0a mov DWORD PTR [edx],ecx
41: 89 5a 04 mov DWORD PTR [edx+0x4],ebx
44: 89 42 08 mov DWORD PTR [edx+0x8],eax
47: c3 ret
00000048 <err>:
48: f4 hlt
00000049 <p>:
49: 50 push eax
4a: 51 push ecx
4b: 52 push edx
4c: 89 e9 mov ecx,ebp
0000004e <L1>:
4e: 49 dec ecx
4f: 83 f9 02 cmp ecx,0x2
52: 7c 0a jl 5e <end>
54: 89 e8 mov eax,ebp
56: 99 cdq
57: f7 f1 div ecx
59: 85 d2 test edx,edx
5b: 75 f1 jne 4e <L1>
5d: a8 .byte 0xa8
0000005e <end>:
5e: f9 stc
5f: 5a pop edx
60: 59 pop ecx
61: 58 pop eax
62: c3 ret
```
**output**
```
5 3 2
7 5 2
41 5 3
47 7 5
```
[the original assembly code](https://godbolt.org/z/Mj6fdaz8T)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 120 bytes
```
.+
$*
^(11(1)+)(?<!^\3+(11+))((?<9-2>\1))+(?!1?$|(11+)\5+$)((?<-4>1)+)$(?<=(?!(11+)\7+$)((?>1(?<-9>1)+)))|.+
$.1 $.8 $.6
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK07D0FDDUFNbU8PeRjEuxlgbyNfW1NQAci11jexiDDU1tTXsFQ3tVWrAMjGm2ipgWV0TO5A2FSDTFqgAImkOkbQzBCmwBCvQ1KwB2aRnqKCiZwHEZv//GxlwGZtzmVgAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
^(11(1)+)(?<!^\3+(11+))
```
Search for a prime number `a` (`$.1` or `2+$#2`)...
```
((?<9-2>\1))+
```
... that when repeated `b` (`1+$#4` or `1+$#9`) times (`$#4`/`$#9` is less than or equal to `$#2` so `b` is less than `a`)...
```
(?!1?$|(11+)\5+$)((?<-4>1)+)$
```
... leaves a remainder `c` (`$.6`) that is prime (`$.6` is less than or equal to `$#4` so `c` is less than `b`)...
```
(?<=(?!(11+)\7+$)((?>1(?<-9>1)+)))
```
... and `b` (`$.8`) is prime.
```
|.+
```
But if a match couldn't be found, replace the input anyway.
```
$.1 $.8 $.6
```
Replace the input with the desired values.
[Answer]
# [Python 3](https://docs.python.org/3/), 174 bytes
```
from itertools import*
f=lambda n:[i for i in [(a,b,c)for a,b,c in combinations([*range(n-1,-1,-1)],3)if a*b+c==n]if all(map(lambda n:all(n%i for i in range(2,n))==(n>1),i))]
```
[Try it online!](https://tio.run/##TY5BasQwDEX3cwptClbqgWZS6DDgOUIvELJwUrsV2FJQvJnTu3EKZUCgx0Po//VRfoSHWqNKBipBi0jagPIqWrpTdMnn@csD30aCKAoExDAab2e7YBMHNblInol9IeHNjJ16/g6Gz709Bic7IEXw3fy6OMdT45RM9qv5z2iCX56C/p5cLCM6Z/jeoyXEqbYDPpr0HxYubxaGfb9fG1@n2wlAwUE0jDvuSdoUwKrExWiTIW3hWX4KB6z1Fw "Python 3 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 138 bytes
```
lambda i,F=lambda n:all(n%a for a in range(2,n)):[[j,k,l]for j in range(3,i)for k in range(3,i//j+1)if F(j)+F(k)+F(l:=i-j*k)>2<=l<k<j][:1]
```
[Try it online!](https://tio.run/##VY3NCsIwEIRfZS9C1kb6d5GQeOxL1B4iGt0k3ZbQi08fDQjqZRi@j2HW5/ZYuD@uKTtzztHOl6sFkoP5VFY2RsE7C25J8FYMyfL9JjrJiGocvQwyTkX6r@wlYUHhD9W1r1okB4PwWA0ilIjK0MHvA546baIO2k@jaqdc5vR7B13ToII1EW/CCULMLw "Python 3.8 (pre-release) – Try It Online")
Semi-brute-force method. Thanks AnttiP for spotting an obvious superfluous 5-byte segment.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅP3.Æʒ`*+Q
```
Outputs the triplets in the order \$[c,b,a]\$.
[Try it online](https://tio.run/##yy9OTMpM/f//cGuAsd7htlOTErS0A///NzQHAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8PtwYY6x1uOzUpQUv70LrA/7U6/6MNzXWMDHSMzXVMLIAMi1gA).
**Explanation:**
```
ÅP # Push a list of prime numbers ≤ the (implicit) input-integer
3.Æ # Get all unique 3-element combinations of this list
ʒ # Filter these [c,b,a]-triplets by:
` # Pop and push c,b,a separated to the stack
* # Multiply the top two: b*a
+ # Add it to the third: c+b*a
Q # Check if it's equal to the (implicit) input-integer
# (after which the filtered list of triplets is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
NθIΦE…²θ⟦ι÷θι﹪θι⟧∧⬤⊞OΦιμ¹‹λ§ιμ⬤ι⬤…²λ﹪λν
```
[Try it online!](https://tio.run/##RY1NC8IwDIbv/ooeU6igOwk7DUUYOB1exUNdixayduvH8N/XyPwIhPC@yZO3e0jfOYk513ZI8Zj6m/Yw8nLRemMjbGWIsDcYyW3kAGdp7xoKwUYu2MUIVtu4M5NRGkbBDJmNUwndrK6kK6ugQoQ2hcdp0F5G578fie/pZE190CEA0nmsrdLPecXfPLFmHr9w/OcQYvmnypyL1SYvJ3wB "Charcoal – Try It Online") Link is to verbose version of code. Outputs all solutions. Explanation: Test all values `a` from `2` up to `n` and checks that the list `[a, n/a, n%a, 1]` is descending and that the first three elements are prime. Conveniently this optimised version turns out to be golfier than a naïve brute force algorithm.
```
Nθ Input as an integer
… Range from
² Literal integer `2`
θ To input integer
E Map over values
ι Current value
θ Input integer
÷ Integer divided by
ι Current value
θ Input integer
﹪ Modulo
ι Current value
⟦ ⟧ Make into a list
Φ Filtered where
ι Current list
Φ Filtered where
μ Inner index
⊞O Concatenated with
¹ Literal integer `1`
⬤ All values satisfy
λ Current value
‹ Is less than
ι Current list
§ Indexed by
μ Inner index
∧ Logical And
ι Current list
⬤ All elements satisfy
… Range from
² Literal integer `2`
λ To current element
⬤ All values satisfy
λ Current element
﹪ Is not divisible by
ν Innermost value
I Cast to string
Implicitly print
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 37 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Main idea taken from [l4m2's answer](https://codegolf.stackexchange.com/a/242070/64121).
```
(∨⊸≡∧´(1=·+´0=↕⊸|)¨)¨⊸/⊢(⌊÷∾⊢∾|˜)¨1↓↕
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKIqOKKuOKJoeKIp8K0KDE9wrcrwrQwPeKGleKKuHwpwqgpwqjiirgv4oqiKOKMisO34oi+4oqi4oi+fMucKcKoMeKGk+KGlQoKPuKLiOKfnEbCqCA34oC/MTfigL8yMOKAvzM34oC/NDjigL8yMDg=)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) + [dfns](https://dfns.dyalog.com/n_contents.htm), 29 [bytes](https://github.com/abrudz/SBCS)
I spent a bit too much time trying to golf [RGS's answer](https://codegolf.stackexchange.com/a/242213/64121), so I decided to post this on its own now.
```
{m⌿⍨⍵=2(⌷+0⌷×⌿)⍉m←pco⌽3cmat⍵}
```
[Try it online!](https://tio.run/##lU/BSsNAEL3vV8wtDSKkjdBePEgvFgTB5OLBwzbZxECSDckijaEnoVjJFj2IXrwXLz2JIIgQ/2R@JE5aBK/CMrz39s2bGZ7F@37JYxm2RuZJAwwv4coAXD2Oz8Hwg7QwGJHJKS7urbZKsP5CvUb9djjoYf2@Z1H5fiLVRL1MyEQpWH/aXQy55m1AGurVLuPuptnYuHgg5pyNqbrHE6dF/QLqUkAqZopALgTEUSoKECmfxmL3F3kCpnImfPCjIot5yUxPZiUUPFasmu@sztGJyy5oIjlBpoy5hCvUr3j73EP9Qa9Zm9sDlp1KC8J2uigUyEzkXMmchV3Tvy5tNv2O/cbJTEVJdE27Xom8iLpFAnChP4SBBfaQhX8IHIwIjH4A "APL (Dyalog Unicode) – Try It Online")
There are two significant differences compared to the original answer:
* When `pco` is applied to a single argument, it returns the ⍵-th prime number. This can be used to construct triples of primes directly, avoiding a more complicated primality test.
* The implementation for \$a\times b+c\$ is a bit shorter using dyadic `/` to get the product.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
... So *very* out of practice. Returns all possible solutions, each in reverse order.
```
o ðj à f@¶XÎ+XÅ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=byDwaiDgIGZAtljOK1jF1w&input=Mzc)
[Answer]
# [Julia 0.4](http://julialang.org/), 62 bytes
```
N->for a=P=primes(N),b=P,c=P a>b>c&&a*b+c==N&&return a,b,c end
```
[Try it online!](https://tio.run/##bY4xD4IwEIX3/oo3kVbPRAqmaFJ2F2Q3DgVLUoOVVPj9WI3BxZve3Zfv8m5T78zc6bnalN0jwOhaD8Hd7ZNXghpdU6trmLIp2yQxq2bdal0lSbDjFDwMNdTC@uvM3rKD8ziniuSWMkV5EUNxYYgTf/qx9zzYIfCOOyEEe3tHP0zjAalip2n8xB0ySICxL5LbBVUPb5d79lNUlOQC8uK/ELtgIWeep4QdIRMELvcEFVdxeQE "Julia 0.4 – Try It Online")
Julia 0.4 for the `primes` function (later moved in the `Primes` package). Returns `nothing` is there is no solution
[Answer]
# [Haskell](https://www.haskell.org/), 91 bytes
```
f n=[[a,b,c]|a<-q$n+1,b<-q a,c<-q b,a*b+c==n,and[0<mod y x|y<-[a,b,c],x<-q y]];q z=[2..z-1]
```
[Try it online!](https://tio.run/##LYtBDoIwEAC/sgdPsm3EeDCxywv8QdPDtoVIhEWQAyX8vUjiaeYw8@Lvu@66nBsQspbRY3AbGzWepCjR/wQYwwGPfPZFIBJkifZi@iFCgmVLRv1HXI4wOfcYYSV71XpVpcs9t0JTzfEpVUWfqZVZN/l23wE "Haskell – Try It Online")
] |
[Question]
[
In one of our projects at work, we recently discovered a particularly large method for generating a 6 character string from a 15 character alphabet. A few of us claimed "I bet we can get that in one line" which started a little internal game of code golf.
Your task is to beat us, which I have no doubt won't take long!
The original algorithm used the alphabet 0-9A-E, but we've experimented with other alphabets. There are therefore three subtasks.
1. Generate a `6` character string randomly selecting from an arbitrary hardcoded `15` character alphabet like `ABC123!@TPOI098`. (This is just an example, and should be customizable without affecting the byte count.)
2. Generate a `6` character string randomly selecting from a `15` character alphabet `0123456789ABCDE`.
3. Generate a `6` character string randomly selecting from a `15` character alphabet of your choice (printable characters only please).
Each character should have **equal chance** of selection and **repetition** should be possible.
The best we have been able to manage for each of the subtasks is:
* "ABC123!@TPOI098" - `24 bytes`
* "0123456789ABCDE" - `21 bytes`
* Custom alphabet - `13 bytes`
Your score is the sum of the bytes in each subtask's solution. i.e. our score is currently 58.
We've attempted using among others, CJam and Ruby. The original was in C#. Use any language you like, but we'll be interested to see solutions in these languages particularly
[Answer]
## CJam (23 + 14 + 10 = 47 bytes)
Arbitrary alphabet: 23 bytes ([online demo](http://cjam.aditsu.net/#code=%7B%22ABC123!%40TPOI098%22mR%7D6*))
```
{"ABC123!@TPOI098"mR}6*
```
Hexadecimal alphabet: 14 bytes ([online demo](http://cjam.aditsu.net/#code=%7BFmrAbHb'0%2B%7D6*))
```
{FmrAbHb'0+}6*
```
Custom alphabet: `ABCDEFGHIJKLMNO`, 10 bytes ([online demo](http://cjam.aditsu.net/#code=%7BFmr'A%2B%7D6*))
```
{Fmr'A+}6*
```
### Dissection
The hexadecimal one is the interesting one:
```
{ e# Loop...
Fmr e# Select a random number from 0 to 14
AbHb e# Convert to base 10 and then to base 17
e# (i.e. add 7 if the number is greater than 9)
'0+ e# Add character '0' (i.e. add 48 and convert from integer to character)
e# Note that 'A' - '0' = 17
}6* e# ...six times
```
The six characters are left on the stack and printed automatically.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
TryItOnline links **A**, **B**, and **C**.
**[A](http://jelly.tryitonline.net/#code=4oCcQUJDMTIzIUDCo1BPSTA5OOKAnVfhuos2WOKCrA&input=)**: `ABC123!@£POI098`, 22 bytes
```
“ABC123!@£POI098”Wẋ6X€
```
(thinking about a compression to lessen this one)
**[B](http://jelly.tryitonline.net/#code=w5hI4bmWV-G6izZY4oKs&input=)**: `0123456789ABCDE`, 8 bytes:
```
ØHṖWẋ6X€
```
**[C](http://jelly.tryitonline.net/#code=w5hI4biKV-G6izZY4oKs&input=)**:`123456789ABCDEF` (choice), 8 bytes:
```
ØHḊWẋ6X€
```
### How?
```
...Wẋ6X€ - common theme
W - wrap (string) in a list
ẋ6 - repeat six times
X€ - random choice from €ach
ØH...... - hexadecimal digit yield: "0123456789ABCDEF"
..Ṗ..... - pop: z[:-1] (B)
..Ḋ..... - dequeue: z[1:] (C)
```
[Answer]
## Perl, 46 + 26 + 26 = 98 bytes
*A lot of the credit goes to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) for saving 13 bytes!*
The 3 programs are pretty much identical, except for the alphabet that changes.
* Hardcoded alphabet (`ABC123!@)POI098` in this example) -> 46 bytes:
`say map{substr"ABC123!@)POI098",15*rand,1}1..6`
* Fixed alphabet `0123456789ABCDE` -> 26 bytes:
`printf"%X",rand 15for 1..6`
* Custom alphabet `0123456789ABCDE` in that case -> 26 bytes:
`printf"%X",rand 15for 1..6`
You can put them all in a file to run them :
```
$ cat 6chr_strings.pl
say map{substr"ABC123!@)POI098",15*rand,1}1..6;
say "";
printf"%X",rand 15for 1..6;
say "";
printf"%X",rand 15for 1..6;
say "";
$ perl -M5.010 6chr_string.pl
CB8!8!
24D582
9ED58C
```
(the `say "";` are just here to improve the output format)
[Answer]
# R, 33+43+59 = 135 bytes
Arbitrary hard-coded alphabet (change the string to change the alphabet):
```
cat(sample(strsplit("ABC123!@TPOI098","")[[1]],6,1),sep="")
```
Alphabet of `[0-9A-E]`:
```
cat(sample(c(0:9,LETTERS[1:6]),6,1),sep="")
```
User-defined alphabet from stdin:
```
cat(sample(scan(,''),6,1),sep="")
```
All cases print the output word to stdout.
[Answer]
## JavaScript (ES6), ~~167~~ ~~166~~ ~~164~~ 163 bytes
*Saved 1 byte thanks to Neil*
*Saved 2 bytes thanks to ETHproductions*
*Saved 1 byte thanks to premek.v*
**Hardcoded:** `"ABC123!@TPOI098"` (58 bytes)
```
f=(n=6)=>n?"ABC123!@TPOI098"[Math.random()*15|0]+f(n-1):''
```
**Fixed:** `"0123456789ABCDE"` (~~58~~ 57 bytes)
```
f=(n=6)=>n?f(n-1)+("ABCDE"[n=Math.random()*15|0]||n-5):''
```
**Custom:** `"()+.1=>?M[afhnt"` (~~51~~ ~~49~~ 48 bytes)
```
f=(n=6)=>n?(f+1)[Math.random()*15|0+5]+f(n-1):''
```
[Answer]
## JavaScript (ES6), 184 bytes
Custom alphabet: 66 bytes
```
_=>"......".replace(/./g,c=>"ABC123!@TPOI098"[Math.random()*15|0])
```
0-9A-E: 63 bytes
```
_=>"......".replace(/./g,c=>"ABCDE"[n=Math.random()*15|0]||n-5)
```
0-9a-e: 55 bytes
```
_=>(Math.random()*11390625+1e8|0).toString(15).slice(1)
```
(Subtract 6 bytes if date-based randomness is permissible.)
[Answer]
# q, 42 bytes
**A**
19 bytes
```
6?"ABC123!@TPOI098"
```
**B**
14 bytes
```
6?15#.Q.n,.Q.A
```
**C**
9 bytes
```
6?15#.Q.a
```
(uses the first fifteen letters of the alphabet)
[Answer]
# Julia (36+26+21 = 83)
```
join(rand(["ABC123!@TPOI098"...],6))
base(15,rand(15^6:15^7-1))
join(rand('a':'o',6))
```
[Answer]
## CJam, 48 bytes
Arbitrary alphabet, 23 bytes:
```
{"ABC123!@TPOI098"mR}6*
```
[Try it online!](http://cjam.tryitonline.net/#code=eyJBQkMxMjMhQFRQT0kwOTgibVJ9Nio&input=)
Hex digits, 15 bytes:
```
{A,'F,65>+mR}6*
```
[Try it online!](http://cjam.tryitonline.net/#code=e0EsJ0YsNjU-K21SfTYq&input=)
Alphabet `ABCDEFGHIJKLMNO`, 10 bytes:
```
{Fmr'A+}6*
```
[Try it online!](http://cjam.tryitonline.net/#code=e0ZtcidBK302Kg&input=)
[Answer]
**Ruby 47 + 37 + 31 = 115**
Hardcoded: "ABC123!@TPOI098" (47)
```
(1..6).map{"5CABC123!@TPOI098".chars.sample}*''
```
Fixed: "0123456789ABCDE" (37)
```
(1..6).map{[*0..9,*?A..?E].sample}*''
```
Custom: "ABCDEFGHIJKLMNO" (31)
```
(1..6).map{[*?A..?O].sample}*''
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 43 bytes
Arbitratry alphabet (`ABC123!@TPOI098`), 23 bytes [Try it online](http://05ab1e.tryitonline.net/#code=IkFCQzEyMyFAVFBPSTA5OCI2Ri5ywqw_&input=)
```
"ABC123!@TPOI098"6F.r¬?
```
Almost hexadecimal alphabet (`0123456789ABCDE`), 10 bytes [Try it online](http://05ab1e.tryitonline.net/#code=MTTDnWg2Ri5ywqw_&input=)
```
14Ýh6F.r¬?
```
Custom alphabet (`abcdefghijklmno`), 10 bytes [Try it online](http://05ab1e.tryitonline.net/#code=QTE1wqM2Ri5ywqw_&input=)
```
A15£6F.r¬?
```
[Answer]
# Python 2, 70 + 70 + 64 = 204 bytes
```
from random import*
s=""
exec"s+=choice('ABC123!@TPOI098');"*6
print s
from random import*
s=""
exec"s+=choice('0123456789ABCDE');"*6
print s
from random import*
s=""
exec"s+=chr(randint(65,80));"*6
print s
```
Unfortunately, the second example is easier with the first method than something like `choice([randint(48,57)),choice(65,69)])`
[Answer]
# Vitsy, 27 + ~~24~~ 22 + ~~13~~ 10 = ~~64~~ ~~62~~ 59 bytes
#1:
```
"ABC123!@TPOI098"6\[eR2+@O]
```
[Try it online!](http://vitsy.tryitonline.net/#code=IkFCQzEyMyFAVFBPSTA5OCI2XFtlUjIrQE9d&input=)
#2:
```
aH7+D4+H6\[eR2+@68*+O]
```
[Try it online!](http://vitsy.tryitonline.net/#code=YUg3K0Q0K0g2XFtlUjIrQDY4KitPXQ&input=)
#3:
```
6\[eR5F-O]
```
Where the available characters are:
```
ヨユヤモメムミマホヘフヒハノネ
```
[Try it online!](http://vitsy.tryitonline.net/#code=NlxbZVI1Ri1PXQ&input=)
[Answer]
# J, 24 + 24 + ~~18~~ 10 = 58 bytes
*8 bytes saved thanks to miles!*
```
'ABC123!@TPOI098'{~?6#15
'0123456789ABCDE'{~?6#15
u:65+?6#15
```
Yeah, the second string isn't easily compressible in J:
```
u:47+23#.inv 12670682677028904639x
u:47+;(+i.@])/"1&.>1 10;18 5
('ABCDE',~1":i.10)
(toupper,hfd?6#15)
'0123456789ABCDE'
```
If a lowercase hex alphabet is fine, then there's `,hfd?6#15` for 9 bytes, as @miles noted.
Anyhow, `?6#15` is 6 random numbers between 0 and 15; `{~` is take-from. `u:` converts numbers to chars. The last example encodes `ABCDEFGHIJKLMNOP`.
## Bonus: general case
```
{~6?@##
```
`{~6?@##` is roughly:
```
{~6?@## input: y
# length of y
6 # six copies of the length
?@ random numbers between 0 and the length
{~ taken from y
```
[Answer]
# PHP, 46+36+35=117 bytes
### Hardcoded (46 bytes)
```
for(;$i++<6;)echo"ABC123!@TPOI098"[rand()%15];
```
~~(47 bytes)~~
```
for(;$i++<6;)echo"ABC123!@TPOI098"[rand(0,14)];
```
### Hexadecimal (lowercase) (36 bytes)
```
for(;$j++<6;)echo dechex(rand()%15);
```
For uppercase, 46 bytes with Hardcoded version.
### Custom (A-O) (35 bytes)
```
for(;$k++<6;)echo chr(rand(65,79));
```
[Answer]
# Scala, 154 bytes
Hardcoded alphabet (54 bytes):
```
Seq.fill(6)("ABC123!@TPOI098"((math.random*14).toInt))
```
Hex alphabet (54 bytes):
```
Seq.fill(6)("0123456789ABCDE"((math.random*14).toInt))
```
Custom alphabet `ABCDEFGHIJKLMNO` (47 bytes):
```
Seq.fill(6)(('A'to'O')((math.random*14).toInt))
```
Explanation:
```
Seq.fill(6)( //build a sequence of 6 elements, where each element is...
"ABC123!@TPOI098"( //from the string
(math.random*14).toInt //take a random char
)
)
```
`'A'to'O'` creates a sequence of 15 chars, A to O
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 42 bytes
Hardcoded alphabet, 22 bytes:
```
L6ORC"ABC123!@TPOI098"
```
Hex digits, 11 bytes:
```
L6ORR15TB16
```
First 15 lowercase letters, 9 bytes:
```
L6Oz@RR15
```
### Explanation
All three programs start with `L6O`: loop 6 times and output the given expression.
* `RC"..."`: Random Choice of a character from the hard-coded string
* `RR15TB16`: RandRange(15), converted To Base 16
* `z@RR15`: lowercase alphabet `z`, indexed with RandRange(15)
[Try it online!](http://pip.tryitonline.net/#code=TDZPUkMiQUJDMTIzIUBUUE9JMDk4IiAgaGFyZGNvZGVkIGFscGhhYmV0ClB4ICAgICAgICAgICAgICAgICAgICAgIHByaW50IGEgbmV3bGluZQpMNk9SUjE1VEIxNiAgICAgICAgICAgICBoZXggZGlnaXRzClB4ICAgICAgICAgICAgICAgICAgICAgIHByaW50IGEgbmV3bGluZQpMNk96QFJSMTUgICAgICAgICAgICAgICBsb3dlcmNhc2UgbGV0dGVycw&input=)
[Answer]
# [Skript](http://skunity.com)/[skQuery](http://skunity.com/SkQuery), 108 bytes
Hardcoded (43 bytes):
```
random 6 char string from `A@cD%F3h9JK{mN!`
```
0123456789ABCDE (34 bytes):
```
random 6 char string from `0-9A-E`
```
Choice (31 bytes):
```
random 6 char string from `A-M`
```
[Answer]
# Jolf, 26 + 14 + 13 = 51 bytes
```
Μ*S6d rG"ABC123!@TPOI098"E
```
Custom alphabet, 24 bytes. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpwqUzZkIHJHIkFCQzEyMyFAVFBPSTA5OCJF)
```
Μ*S6d r lp^0wά
```
0-9A-E alphabet, 14 bytes. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpwqUzZkIHIgbHBeMHfOrA) `lp^0wά` is `lp` (0-Z) sliced (`l`) from `0` to `15` (`wά`).
```
Μ*S6d r lp^1ά
```
1-9A-F alphabet, 13 bytes. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpwqUzZkIHIgbHBeMc6s) `lp^1ά` is the same as above, except from `1` to `16`.
---
General method:
```
Μ*S6d r
M*S6d map six newlines over this function:
r select random element from array.
```
Other attempts (using string compression):
```
Μ*S6d rGμpwΞ $AE
```
[Answer]
## PowerShell v2+, 45 + 44 + 37 = 126 bytes
Fixed alphabet, 45 bytes
```
-join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
```
Nearly-hexadecimal alphabet, 44 bytes
```
-join[char[]](0..5|%{Random(48..57+65..69)})
```
Custom alphabet (A to O), 37 bytes
```
-join[char[]](0..5|%{Random(65..79)})
```
All of these follow the same pattern -- loop from `0` to `5`, each iteration selecting a `Random` character or ASCII value, casting that as a `char`-array if necessary, and `-join`ing it together into a string. That string is left on the pipeline, and output is implicit.
---
### Examples
```
PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
32ATB3
PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
III@B2
PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
@302O@
PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
74E117
PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
09D7DD
PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
COJDFI
PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
EAKCNJ
```
[Answer]
## Pyke, 35 bytes
### Arbitary alphabet, 20 bytes
```
6V"ABC123!@TPOI098"H
```
[Try it here!](http://pyke.catbus.co.uk/?code=6V%22ABC123%21%40TPOI098%22H)
### Hex alphabet, 8 bytes
```
6V~J15<H
```
[Try it here!](http://pyke.catbus.co.uk/?code=6V~J15%3CH)
```
~J15< - "0123456789abcdefghijklmno..."[:15]
```
### Custom alphabet, 7 bytes
```
6VG15<H
```
[Try it here!](http://pyke.catbus.co.uk/?code=6VG15%3CH)
```
G15< - alphabet[:15]
```
Alphabet chosen: `abcdefghijklmno`
```
6V - repeat 6 times:
... - get alphabet
H - choose_random(^)
```
] |
[Question]
[
Gears transfer different amount of speeds, depending on the size of the meshed gear.
[](https://i.stack.imgur.com/RSumE.gif)
Jack has a machine, that rotates a Gear Train. but you don't know the speed of the last gear.
Luckily, You are a great code golfer, so you can help him!
# So, What should I do?
Each gear is represented by 2 numbers, the radius of the inner gear and the radius of the outer gears.
If gear `A` is `[a,b]` and gear `B` is `[c,d]`, then the ratio between the speed of `A` and the speed of `B` would be `c:b`.
Given a list of gears (list of 2-tuples), output the speed of the last gear.
You can assume the speed of the first gear is `1`.
# Worked out example
Let's say our input is `[[6,12],[3,10],[5,8]]`.
The first gear, `[6,12]`, would have a speed of `1`.
Then, the second gear, `[3,10]`, would have a speed of `1*12/3 = 4`.
Then, the last gear, `[5,8]`, would have a speed of `4*10/5 = 8`.
# Testcases
```
input output
[[1,1],[2,2]] 0.5 (1/2)
[[1,2],[1,2],[1,2]] 4 (2/1*2/1)
[[6,12],[3,10],[5,8]] 8 (12/3*10/5)
```
# Rules
Basic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
## Haskell, 19 bytes
```
foldr1(/).tail.init
```
Given a flat list like `[a,b,c,d,e,f]`, `tail.init` removes the first and last elements, and then `foldr1(/)` creates a cascade of divisions `b/(c/(d/e))))` that works out to alternating `*` and `/`: `b/c*d/e`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḊṖU÷@/
```
[Test suite.](http://jelly.tryitonline.net/#code=4biK4bmWVcO3QC8Kw4figqxH&input=&args=WzEsMSwyLDJdLFsxLDIsMSwyLDEsMl0sWzYsMTIsMywxMCw1LDhd)
```
ḊṖU÷@/ Main monadic chain. temp <- third argument (first input)
Ḋ temp <- temp with first element removed
Ṗ temp <- temp with last element removed
U temp <- temp reversed
÷@/ temp <- temp reduced by reversed floating-point division.
implicitly output temp.
```
[Answer]
# C, ~~115~~ ~~123~~ ~~121~~ ~~83~~ ~~80~~ ~~76~~ ~~71~~ 70 bytes
*4 bytes saved thanks to @LeakyNun!*
My first golf, probably not the best.
```
c;float r=1;float g(a,s)int*a;{for(;c<s-2;)r*=a[++c]/a[++c];return r;}
```
Takes an array and size.
Ungolfed:
```
int counter;
float ret=1;
float gear(int *arr, int size) {
for(; counter < size-2; )
ret = ret * arr[++counter] / arr[++counter];
return ret;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
U÷Ḣµ2\P
```
[Try it online!](http://jelly.tryitonline.net/#code=VcO34biiwrUyXFA&input=&args=W1sxLDFdLFsyLDJdXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=VcO34biiwrUyXFAKw4figqxH&input=&args=W1sxLDFdLFsyLDJdXSwgW1sxLDJdLFsxLDJdLFsxLDJdXSwgW1s2LDEyXSxbMywxMF0sWzUsOF1d).
[Answer]
## JavaScript (ES6), 44 bytes
```
a=>(t=1,a.reduce((x,y)=>(t*=x[1]/y[0],y)),t)
```
37 bytes for a flattened array:
```
a=>1/a.slice(1,-1).reduce((x,y)=>y/x)
```
Unlike (e.g.) Haskell, `reduceRight` is such a long name that it's cheaper to `reduce` the wrong way and take the reciprocal at the end.
[Answer]
# Pyth, 8 bytes
```
.UcZb_Pt
```
[Test suite.](http://pyth.herokuapp.com/?code=.UcZb_Pt&test_suite=1&test_suite_input=%5B1%2C1%2C2%2C2%5D%0A%5B1%2C2%2C1%2C2%2C1%2C2%5D%0A%5B6%2C12%2C3%2C10%2C5%2C8%5D&debug=0)
[Answer]
# J, 8 bytes
```
%/@}:@}.
```
[Try it online!](http://tryj.tk/)
## Usage
```
>> f =: %/@}:@}.
>> f 1 1 2 2
<< 0.5
>> f 1 2 1 2 1 2
<< 4
>> f 6 12 3 10 5 8
<< 8
```
where `>>` is STDIN and `<<` is STDOUT.
## Explanation
"Reduce" in `J` defaults from right to left, which took off a few bytes :p
```
divide =: %
reduce =: /
atop =: @
remove_first =: }.
remove_last =: }:
f =: (divide reduce) atop (remove_last) atop (remove_first)
```
[Answer]
## Mathematica, 26 bytes
```
#2/#&~Fold~#[[-2;;2;;-1]]&
```
An unnamed function that takes a flat even-length list of values and returns the exact result (as a fraction if necessary).
This uses the same approach as some other answers of folding division over the reversed list (after removing the first and last element).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
6L)9L&)/p
```
Input format is any of these:
```
[[6,12],[3,10],[5,8]]
[6,12,3,10,5,8]
[6 12 3 10 5 8]
```
*EDIT (July 30, 2016): the linked code replaces `9L` by `1L` to adapt to recent changes in the language.*
[**Try it online!**](http://matl.tryitonline.net/#code=NkwpMUwmKS9w&input=WzYsMTIsMywxMCw1LDhd)
### Explanation
```
6L % Predefined literal: index from second to second-last element
) % Apply index to implicit input. Removes first and last elements
9L % Predefined literal: index for elements at odd positions
&) % Two-output indexing. Gives an array with the odd-position elements
% and the complementary array, with the even-position elements of the
% original array
/ % Divide those two arrays element-wise
p % Product of all entries. Implicitly display
```
[Answer]
# JavaScript, 54 bytes
```
(a,s=1)=>a.map((v,i)=>s*=(x=a[i+1])?v[1]/x[0]:1).pop()
```
## Usage
```
f=(a,s=1)=>a.map((v,i)=>s*=(x=a[i+1])?v[1]/x[0]:1).pop()
document.write([
f([[1,1],[2,2]]),
f([[1,2],[1,2],[1,2]]),
f([[6,12],[3,10],[5,8]])
].join('<br>'))
```
## Ungolfed
```
function ( array ) {
var s = 1; // Set initial speed
for ( var i = 0; i < array.length ; i++ ) { // Loop through array
if ( array[i + 1] === undefined ) { // If last element
return s; // Return speed
} else { // Else
s = s * ( array[i][0] / array[i+1][0]) // Calculate speed
}
}
}
```
Of course, the golfed variant is a bit different. With `.map()`, it replaces the first value of the array with the speed after the second wheel, the second value with the speed of the third wheel, and the last value and the second last value with the speed of the last wheel. So, we just take the last element with `.pop()`.
[Answer]
# PHP, ~~80~~ ~~79~~ 69 bytes
```
<?for($r=1;++$i<count($a=$_GET[a]);)$r*=$a[$i-1][1]/$a[$i][0];echo$r;
```
takes input from GET parameter `a`; prints result
initializes `$r` with 1, then loops from second to last tuple to multiply with first element of previous and divide through second element of current tuple.
---
Thanks to Jörg for reminding me of `$_GET`; that saved 7 bytes.
---
more elegant version, 88 bytes:
```
<?=array_reduce($a=$_GET[a],function($r,$x){return$r*$x[1]/$x[0];},$a[0][0]/end($a)[1]);
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¦¨.«/
```
Port of [*@xnor*'s Haskell answer](https://codegolf.stackexchange.com/a/86383/52210), so also takes the input as a flattened list.
[Try it online](https://tio.run/##yy9OTMpM/f//0LJDK/QOrdb//z/aTMfQSMdYx9BAx1THIhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Q8sOrdA7tFr/v87/6GhDHUMdIx2jWJ1oEA3FQJ6ZjqGRjrGOoYGOqY5FbCwA).
**Longer, but more interesting answer (9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):**
```
ü2εÅ/`/}P
```
Takes the input as pairs, like the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f//8B6jc1sPt@on6NcG/P8fHW2mY2gUqxNtrGNoAKRMdSxiYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3uMzm093KqfoF8b8F/nf3R0tKGOYaxOtJGOUSyQAvKMgBSCBImZ6RiCuMY6hgZAylTHIjY2FgA).
**Explanation:**
```
¦¨ # Remove the first and last items of the (implicit) input-list
.« # Then left-reduce it by:
/ # Dividing
# (after which the result is output implicitly)
ü2 # Create overlapping pairs of the (implicit) input-list of pairs
ε # Map over each overlapping 2x2 block:
Å/ # Pop and push its main anti-diagonal: [[a,b],[c,d]] → [b,c]
` # Pop and push both values separated to the stack
/ # Divide the first by the second: b/c
}P # After the map: pop and push the product of the list
# (which is output implicitly as result)
```
[Answer]
# JavaScript, ~~59~~ ~~58~~ 56 bytes
```
a=>a.reduce((p,c)=>p*c[1]/c[0],a[0][0]/a[a.length-1][1])
```
# Explanation
Reduce the array and multiply by every second value and divide by every first value. So for `[[6,12],[3,10],[5,8]]` it does `12/6*10/3*8/5`. Of course, the actual computation we wanted was `12/3*10/5` so we just want to ignore that first `/6` and last `*8` by multiplying `*6` back in and dividing `/8` back out. That cancelling out is done by setting `6/8` as the initial value for the reduce.
[Answer]
# Python 2, 52 bytes
```
lambda x:reduce(lambda x,y:y/float(x),x[1:-1][::-1])
```
An anonymous function that takes input of a flattened list via argument and returns the output.
This makes use of the division cascade idea, as in [xnor's answer](https://codegolf.stackexchange.com/a/86383/55526).
[Try it on Ideone](https://ideone.com/i7YT6B)
[Answer]
# Python 3, 59 bytes
```
lambda x:eval('/'.join('{}*{}'.format(*i)for i in x)[2:-2])
```
An anonymous function that takes input of a non-flattened list via argument and returns the output.
**How it works**
For every pair of integers in the input, a string of the form `'int1*int2'` is created. Joining all these pairs on `/` gives a string of the form `'int1*int2/int3*int4/...'`, which is the desired calculation, but includes the undesired first and last integers. These are removed by slicing out the first two and last two characters in the sting, leaving the desired calculation. This is then evaluated and returned.
[Try it on Ideone](https://ideone.com/uZICXZ)
[Answer]
## Actually, 14 bytes
```
pXdX2@╪k`i/`Mπ
```
[Try it online!](http://actually.tryitonline.net/#code=cFhkWDJA4pWqa2BpL2BNz4A&input=WzYsMTIsMywxMCw1LDhd) (currently not working because TIO is a few versions behind)
This program takes a flattened list as input.
Explanation:
```
pXdX2@╪k`i/`Mπ
pXdX remove the first and last elements
2@╪k push a list where each element is a list containing every two elements of the original list (chunk into length-2 lists)
`i/`M map division over each sublist
π product
```
[Answer]
# R, 64 bytes
Turns out the vectorized approach and the `for` loop are equivalent in this case:
```
x=scan();prod(sapply(1:(sum(1|x)/2-1)*2,function(i)x[i]/x[i+1]))
```
or the `for` loop:
```
x=scan();for(i in 1:(sum(1|x)/2-1)*2)T=c(T,x[i]/x[i+1]);prod(T)}
```
`
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 94 bytes
A recursive (had to do it..) function that takes a static 2D array and its length (no. of rows) as an input. Using some pointer math on the array.
```
function r(a:pdouble;n:integer):double;begin r:=a[1]/a[2];if n=2then exit;r:=r*r(a+2,n-1);end;
```
[Try it online!](https://tio.run/##jZDBasMwEETv@Yo9Sq3iZtc0FAlD/8P4oDjrVGDWRlGa9Otd2S3Uhbb0sgOrmTdoR39ufb/txnaauou0KQwCUXk7HofLoWcnNkjiE0dtPzcHPoXssZWvsXnwNTUudCAVpRcW4FtILj/Gu0y5JyNb1I7l6KZXHzcAic/Jx@jf0MKiUO@KAg3Ms4Ghg48aqEApNKgNKDKktVuHaR2m38I0h1fynVH@g7E3uKRLg7tZH83TTNksN8iwawyJe1FRPX99zABpi5aWup8cuaz821GuHPl4xfQO "Pascal (FPC) – Try It Online")
Ungolfed:
```
function ratio(a: pdouble; n: integer): double;
begin
ratio := a[1] / a[2];
if n=2 then
Exit;
ratio := ratio * ratio(a+2, n-1);
end;
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ḢṪ‡$/ḭ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bii4bmq4oChJC/huK0iLCIiLCJbMSwxLDIsMl1cblsxLDIsMSwyLDEsMl1cbls2LDEyLDMsMTAsNSw4XSJd)
] |
[Question]
[
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.
Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.
**Examples:**
Input:`2`
Output:
```
/--\
()
()
/__\
```
Input:`3`
Output:
```
/--\
()
()
()
/__\
```
Input:`5`
Output:
```
/--\
()
()
()
()
()
/__\
```
**Rules:**
* 0 & negative numbers don't matter
* To give the lamps (an this challenge) more of a variety, you **must** change the lamp shade.
+ They must be **4** characters wide and **1** character high.
+ They can be in any shape, including non-lamp-shade shapes.
+ They must not contain whitespace.
+ The base must stay the same.
* You must show an example input & output with your lamp shade.
* Shortest code wins!
[Answer]
# [Snowman 0.2.0](https://github.com/KeyboardFire/snowman-lang/releases/tag/v0.2.0-alpha), 42 chars
```
)vg10sB]"[--]
"sP:" ()
"sP;bR"/__"sP92wRsP
```
Sample run:
```
llama@llama:...Code/snowman/ppcg53483lamp$ snowman lamp.snowman
5
[--]
()
()
()
()
()
/__\
```
So I only noticed that I forgot to implement the ability to escape backslashes within strings when I solved this challenge. That's definitely going to be a thing in the next version, but for now, here's what I did to print the final line:
```
"/__"sP92wRsP
```
`92` is the ASCII code for a backslash, `wR` wraps it in an array, and I can now print it with `sP` because "strings" in Snowman are actually just arrays of numbers.
[Answer]
# Pyth - 16 bytes
Uses quotes for the shade since N is preinitialized to that.
```
*N4VQ+d`();"/__\
```
[Try it online here](http://pyth.herokuapp.com/?code=*N4VQ%2Bd%60()%3B%22%2F__%5C&input=5&debug=0).
```
* 4 String repetition 4x, implicit print
N Preinitialized to Quote
VQ For N in range(Q)
+ String concat
d Space
`() Repr of empty tuple
; Close for loop
"/__\ Implicitly print string, implicit close quote
```
Sample for 5:
```
""""
()
()
()
()
()
/__\
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), ~~43~~ ~~41~~ 38 bytes
```
"\__/"aiv
"&-1v!?:<&a" ()
~"!_\
?!;o>l
```
Input via a code point, e.g. space is 32. This uses part of the program's own code as the lampshade, resulting in something that looks like a satellite dish:
```
~\_!
()
()
()
()
()
/__\
```
*(Suggestion thanks to @randomra)*
For three more bytes, we can change the third line to add a bit more customisation:
```
"\__/"aiv
"&-1v!?:<&a" ()
__\"\~"/
?!;o>l
```
This produces one of those lamps which shoot light upwards, for lack of a better way of putting it:
```
\__/
()
()
()
()
()
/__\
```
[Answer]
# R, ~~54~~ ~~52~~ 46 bytes
```
cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
```
In this version, **input** and **output** are almost mixed together :
**{in/out}PUT :**
```
> cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
1: 4
2:
Read 1 item
RRRR
()
()
()
()
/__\
```
*EDIT 1* : **-2** bytes thanks to @manatwork comment.
*EDIT 2* : **-6** bytes. Full credit goes to @manatwork again
[Answer]
## [Straw](https://github.com/tuxcrafting/straw), 26 bytes (non-competing)
```
<#~('--'
)>( ()
)-*>(/__\)>
```
Use `'--'` as lamp shade, ~~take input in unary~~ now in decimal
[Answer]
# CJam, 18 bytes
```
"/__\
"" ()
"ri*1$
```
Sample run for input 5:
```
/__\
()
()
()
()
()
/__\
```
[Try it online here](http://cjam.aditsu.net/#code=%22%2F__%5C%0A%22%22%20()%0A%22ri*1%24&input=5)
[Answer]
# JavaScript ES6, 34 bytes
```
i=>`|==|
${` ()
`.repeat(i)}/__\\`
```
The newlines are significant
Example with input of 5:
```
|==|
()
()
()
()
()
/__\
```
[Answer]
# sed, 28 bytes
```
s#.# ()\n#g
s#^\|$#/__\\\n#g
```
Takes input in unary. The shade is the obvious selection (same as the base).
### Test run
```
$ echo -n 111 | sed -f lamp.sed
/__\
()
()
()
/__\
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~15~~ ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„ (и„/_.ø)˜∞
```
-2 bytes (17 ‚Üí 15) thanks to *@EriktheOutgolfer*.
-2 byte (13 ‚Üí 11) after being inspired by [*@dzaima*'s Canvas answer](https://codegolf.stackexchange.com/a/169643/52210).
Cap is the same as the base (`/__\`).
**Explanation:**
```
„ ( # Literal string " ("
–∏ # Repeat " (" the input amount of times
# i.e. " (" and 3 ‚Üí [' (',' (',' (']
„/_ # Literal string "/_"
.√∏ # Surround the list of " (" with "/_" on both ends
# i.e. [' (',' (',' ('] ‚Üí ['/_',[' (',' (',' (',' ('],'/_']
Àú # Flatten this list
# i.e. ['/_',[' (',' (',' ('],'/_'] ‚Üí ['/_',' (',' (',' (','/_']
‚àû # Mirror each item
# i.e. ['/_',' (',' (',' (','/_'] ‚Üí ['/__\',' () ',' () ',' () ','/__\']
# And output the list new-line delimited (implicitly due to the mirror)
```
---
**Old 13 bytes answer:**
```
„/_D„ (Iиs)˜∞
```
[Try it online.](https://tio.run/##MzBNTDJM/f//UcM8/XgXIKmg4XlhR7Hm6TmPOub9/28CAA)
[Answer]
# [1+](https://esolangs.org/wiki/1+), 114 bytes
```
11+""*+"*";";";;1.1##(A|11+""""**+;)"""*"**;""*""*+*";1+;"\"1+/<1+#(A)11+"*(|1+"1+")1+*+;1()"*"1+*++";;1()*"1+*+;
```
You all! Stop complaining about the length, this is the best I could do! Go blame Parcly Taxel for designing such a bowly language!
Shade is `$$$$`.
[Answer]
# Gema: 30 characters
```
*=gema\n@repeat{*;\ ()\n}/__\\
```
Sample run:
```
bash-4.3$ gema '*=gema\n@repeat{*;\ ()\n}/__\\' <<< 3
gema
()
()
()
/__\
```
[Answer]
# jq: 30 characters
(29 characters code + 1 character command line option.)
```
8888,(range(.)|" ()"),"/__\\"
```
Sample run:
```
bash-4.3$ jq -r '8888,(range(.)|" ()"),"/__\\"' <<< 3
8888
()
()
()
/__\
```
[On-line test](https://jqplay.org/jq?q=8888,%28range%28.%29|%22%20%28%29%22%29,%22/__%5C%22&j=3) (Passing `-r` through URL is not supported – check Raw Output yourself.)
[Answer]
# C, 54 bytes
Call `f()` with the desired height of the lamp.
```
f(n){for(puts("||||");n--;puts(" ()"));puts("/__\\");}
```
[Try it on ideone.](http://ideone.com/2IYsrm)
Example output for 5:
```
||||
()
()
()
()
()
/__\
```
[Answer]
## Pyke, 15 bytes
```
" ()"~mQAD"/__\
```
[Try it here!](http://pyke.catbus.co.uk:3434/?code=%22+%28%29%22%7EmQAD%22%2F__%5C&input=11)
```
~m - 1000
" ()" - " ()"
QAD - duplicate(^) input times
"/__\ - "/__\"
```
Outputs:
```
1000
()
()
/__\
```
[Answer]
# [Kotlin](https://kotlinlang.org), 36 bytes
```
{"|MM|\n${" ()\n".repeat(it)}/__\\"}
```
[Try it online!](https://tio.run/##NY1BC4JAEEbv/Yph6TBzyIhukkrHIE9dF2ShTZbWUdYpKPW3b1r0nd/33r0V7zjeHgyNcYwm1H0KxxDM63CR4LjOCYYVzHsaD940XQp4YiHY5PAjIIuDGsty1LweFCBpVkmwnTWCTmjaVpXWaop/Se/eFjII1lzPji1SkUg7K5GgSGH3jXWzWDzjEsTlQLSa4v4D "Kotlin – Try It Online")
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 169 bytes
```
[S S S N
_Push_0][T N
T T _Read_STDIN_as_integer][S S S T S T T T S S N
_Push_92_\][S S S T S T T T T T N
_Push_95__][S N
S _Duplicate_95__][S S S T S T T T T N
_Push_47_/][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][T T T _Retrieve_at_address_0][S S S T N
_Push_1][T S S T _Subtract][S N
S _Duplicate][S S S N
_Push_0][S N
T _Swap_top_two][T T S _Store_at_address_0][N
T T S N
_If_neg_Jump_to_Label_PRINT][S S S T S T S N
_Push_10_newline][S S S T S T S S T N
_Push_41_)][S S S T S T S S S N
_Push_40_(][S S S T S S S S S N
_Push_32_space][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S S S T S T S N
_Push_10_newline][S S S T S S S S T N
_Push_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][N
S S T N
_Create_Label_LOOP_2][T N
S S _Print_as_character][N
S N
T N
_Jump_to_Label_LOOP_2]
```
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/##RY1LCoAwDETX806RQ3ghkULdCQoeP7ZJWyEwk/kkbz2fcl/7UdzNDCE1lKkjk0rEMjZID2UadScCpNjPjPbClptsaFFoDViSfit/xhBPkgr37QM) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
Pushes all characters in reversed order to the stack, and then prints them in a loop.
```
Integer i = STDIN as input
Push "\__/" to the stack
Start LOOP:
i = i - 1
if(i is negative):
Go to function PRINT
Push "\n)( " to the stack
Go to next iteration of LOOP
function PRINT:
Push "\n!!!!" to the stack
Start LOOP_2:
Print top as character to STDOUT
Go to next iteration of LOOP_2
```
NOTE: `i` in the pseudo-code above is stored back in the heap in every iteration of `LOOP`, because we don't want to leave it on the stack to be printed at the end.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
(×_¶/e⟳║
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTI4JUQ3XyVCNi8ldUZGNDUldTI3RjMldTI1NTE_,i=NQ__,v=5,run)
Explanation:
```
(√ó repeat "(" input times
_¶/e encase it on both sides in "_\n/"
the 1st line is surrounded in "_" and the second ends and starts with "/"
‚ü≥ rotate the string clockwise without changing characters
‚ïë palindromize horizontally with 0 overlap
```
[Answer]
# Excel, 31 bytes
An anonymous worksheet function that takes input as a numeric from range `[A1]` and outputs to the calling cell.
This lamp is musical - and will help to liven and lighten up your day.
```
="/\
"&REPT(" ()
",A1)&"/__\"
```
### Output
[](https://i.stack.imgur.com/8Tl4m.png)
[Answer]
# PowerShell 5.1, ~~28~~ 26 Bytes
Thanks Mazzy for 2 bytes
```
8008;," ()"*"$args";"/__\"
```
Since the shade can be any 4 characters, using a number saves a pair of quotes. The hardest part was finding a nice looking shade.
Output:
```
PS C:\Users\ItsMe\Desktop> .\scratch.ps1 4
8008
()
()
()
()
/__\
```
[Answer]
# Python 2, 36 bytes
```
print"-"*4+"\n ()"*input()+"\n/__\\"
```
For input 4:
```
----
()
()
()
()
/__\
```
Note that for Python that any lamp shade using pipes is a byte less.
-1 bytes thanks to @Alex!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
```
Æ` ()`Ãi¥² p"/__\
```
[Try it online!](https://tio.run/##y0osKPn//3BbgoKGZsLh5sxDSw9tUihQ0o@Pj/n/35SLSzcIAA "Japt – Try It Online")
Output for `5` is:
```
====
()
()
()
()
()
/__\
```
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), ~~65~~ 61 bytes
```
@95W2M!;2A!!;;2W2M;[25W;84W;85W!;1M;1A]25W;95W2M!;2W1M!!;;3A;
```
I'm sure it can be golfed by a few more bytes when displaying characters.
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=%4095W2M!%3B2A!!%3B%3B2W2M%3B%5B25W%3B84W%3B85W!%3B1M%3B1A%5D25W%3B95W2M!%3B2W1M!!%3B%3B3A%3B&input=9)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 15 bytes
```
×d?(‛ ()‛/_WvøṀ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C3%97d%3F%28%E2%80%9B%20%28%29%E2%80%9B%2F_Wv%C3%B8%E1%B9%80&inputs=4&header=&footer=)
Example output:
```
****
()
()
()
()
/__\
```
I kinda golfed the shade.
```
√ód # two asterisks
?( ) # Input times...
‚Äõ ( # Push the two-char ` (`
‚Äõ/_ # Push the two-char `/_`
W # Push the entire stack
vøṀ # Ascii-art mirror each item.
```
[Answer]
## Pascal, 118 characters
Strings consist of `char` values.
The available `char` values beyond the bare minimum (i.‚ÄØe. necessary to write Pascal language elements) are implementation-defined.
Provided that all `char` values present are available in your implementation, you can write:
```
program p(input,output);var l:integer;begin
read(l);writeLn('üꨂĕüí¶„Äú');for l:=1 to l do
writeLn(' ()');write('/__\')end.
```
Input:
```
4
```
Output (pun intended):
```
üꨂĕüí¶„Äú
()
()
()
()
/__\
```
This lamp grants you a wish if you rub it. üòÇ
[Answer]
# SWI-Prolog, ~~73~~ 60 bytes
```
a(X):-write(golf),writef("%r",["\n ()",X]),write("\n/__\\").
```
`a(5).` outputs
```
golf
()
()
()
()
()
/__\
```
[Answer]
# Julia, 36 bytes
```
n->print("|~~|\n"*" ()\n"^n*"/__\\")
```
This creates an unnamed function that takes an integer as input and prints to stdout.
Example:
```
julia> f(4)
|~~|
()
()
()
()
/__\
```
[Answer]
## Bash + coreutils, 37 bytes
```
yes ' ()'|sed '1i####
'$1'{a/__\\
q}'
```
The newlines are necessary and counted in the bytes total. GNU sed is required.
**Run:**
```
./squiggly_lamp.sh 2
```
**Output:**
```
####
()
()
/__\
```
[Answer]
## Ruby, 42 bytes
```
i=gets.to_i
puts "|--|\n#{" ()\n"*i}/__\\"
```
[Answer]
## [Neoscript](https://github.com/tuxcrafting/neoscript), 28 bytes
```
{n|"[~~]
"+" ()
"*n+"/--\\"}
```
[Answer]
# PyMin, 24 bytes / 17 characters
```
»ƒ+ѿ+" ø\n"*¬+ɓ+ѿ
```
Output for 5:
```
Fizz
()
()
()
()
()
Buzz
```
Shorter version with `v0.5`:
### 21 bytes / 13 characters
```
»ƒƜ+" ø¶"¯+ɓƜ
```
] |
[Question]
[
**This question already has answers here**:
[Generate a pronounceable word](/questions/11877/generate-a-pronounceable-word)
(35 answers)
Closed 2 years ago.
In the English language, a surefire way to make a pronounceable nonsense letter combination is to make it entirely out of consonant-vowel pairs, e.g., *Wu* *ko* *pa* *ha*, or, *Me* *fa* *ro*, *consonant* first, followed by *vowel*.
### Challenge:
Write a program or function that will, given a user-specified number of letters, create a random name using this principle. It's that simple.
### Input:
An integer greater than or equal to 2 which designates the required number of letters in the output. Input can be taken from STDIN, command line arguments, or function arguments.
### Output:
A string of the given length containing randomly selected consonant-vowel pairs. It can be printed to STDOUT or closest alternative or returned in the case of a function.
### Rules:
1. Each consonant of the English alphabet should have equal probability of being selected for the first character of each pair, and each vowel of the English alphabet should have equal probability of being selected for the second character of each pair.
2. Letter pairs may be repeated.
3. Since this is a name, the first letter must be capitalized.
4. If the input is odd, a randomly selected letter pair in the name should have **y** or **h** appended to the end. The choice of y or h should be random as well.
5. Standard loopholes are not permitted.
6. Smallest code in bytes wins.
### Letter definitions:
Consonants:
```
bcdfghjklmnpqrstvwxyz
```
Vowels:
```
aeiou
```
### Example I/O:
```
Input: 6
Output: Mefaro
Input: 9
Output: Wukohpaha
```
Enjoy!
[Answer]
# Pyth, 33 bytes
```
rsXOtQmO*-GJ"aeiou"J/Q2*%Q2O"hy"4
```
[Demonstration.](https://pyth.herokuapp.com/?code=rsXOtQmO*-GJ%22aeiou%22J%2FQ2*%25Q2O%22hy%224&input=9&debug=0)
[Answer]
# JavaScript ES6, ~~187~~ ~~180~~ 168 bytes
```
f=l=>{r=m=>Math.random()*m|0
d=l%2&&r(--l/2)*2+1
for(s='';l--;s+=s?a:a.toUpperCase())a=l%2?'bcdfghjklmnpqrstvwxyz'[r(21)]:'aeiou'[r(5)]+(l==d-1?'hy'[r(2)]:'')
return s}
```
Edit: I switched from using regex replace to a simple for loop, which improved the length considerably. Ungolfed code and test UI below. Input a negative number at your own risk because it makes an infinite loop. (Thanks to unclemeat for pointing that out.)
```
f=function(l){
// Function to return a random integer between 0 and m-1 inclusive
r=function(m){
return Math.random()*m|0
}
// d is the position the h or y will be added
// l is decremented only if l is odd so an extra consonant won't be added to the end
d=l%2&&r(--l/2)*2+1
for(s='';l--;){
a=l%2?'bcdfghjklmnpqrstvwxyz'[r(21)]:'aeiou'[r(5)]+(l==d-1?'hy'[r(2)]:'')
// If `s` is empty (i.e. this is the first leter), make it uppercase
s+=s?a:a.toUpperCase()
}
return s
}
run=function(){ip=parseInt(document.getElementById('input').value);if(ip<2)return alert('Input must be greater than one.');document.getElementById('output').innerHTML=f(ip)};document.getElementById('run').onclick=run;run()
```
```
<input type="number" id="input" value="7" min="2" /><button id="run">Run</button><br />
<pre id="output"></pre>
```
[Answer]
# SWI-Prolog, ~~286~~ 285 bytes
```
a(I):-a(I,[]).
a(I,R):-(I=1,r(1,K),nth0(K,`hy`,V),length(R,L),random(1,L,W),nth0(W,[O:P|Q],V:0xFEFF,R);I=0,[O:P|Q]=R),N is O-32,p([N:P|Q]);r(5,A),nth0(A,`aeiou`,X),r(21,B),nth0(B,`bcdfghjklmnpqrstvwxyz`,Y),J is I-2,a(J,[Y:X|R]).
p([A:B|R]):-put(A),put(B),p(R);!.
r(I,R):-random(0,I,R).
```
Example: `a(13).` outputs `Leqihsekeqira`.
Note: You might need to replace the ``` with `"` if you have an old version of SWI-Prolog.
[Answer]
# Pyth, ~~52~~ 42 bytes
```
V/Q2=k++kO-GJ"aeiou"OJ;rs.SXZck2*%Q2O"hy"4
```
[You can try it in the online compiler here.](https://pyth.herokuapp.com/?code=V%2FQ2%3Dk%2B%2BkO-GJ%22aeiou%22OJ%3Brs.SXZck2*%25Q2O%22hy%224&input=5&debug=0)
Thanks to Jakube for golfing it down further, NinjaBearMonkey for clarifying the challenge, and issacg for creating Pyth and inadvertently teaching me about `X`.
This program randomly selects a consonant and a vowel to fill the string, adds 'h' or 'y' to one pair if the input is odd, then capitalizes the first character. Here is the breakdown:
```
V/Q2 For N in range(1, input/2):
=k Set k to:
k k (defaults to ""),
+ O G plus a random letter from the alphabet...
- J"aeiou" without the vowels,
+ OJ plus a random vowel
; End the loop
ck2 Chop k into strings of length 2
XZ Append to the first string:
O"hy" 'h' or 'y' picked at random,
*%Q2 repeated input mod 2 times
.S Shuffle the strings
s Convert them back to a single string
r 4 Capitalize and print the string
```
It seems inefficient to append 'h' or 'y' to the first consonant-vowel pair and then scramble the list. I tried appending to a random pair but the code was always longer than this.
[Answer]
# Perl, ~~253~~ 238 bytes
```
@c=split"","bcdfghjklmnpqrstvwxyz";@v=split"","aeiou";@t=();chomp($n=<>);for(1..$n/2){$l=$c[$$=rand(21)];if($_<2){$l=uc$l};push@t,$l.$v[$$=rand(5)]};$x=0;$y=int(rand(@t));for(@t){print;if($x==$y&&$n%2>0){print qw(h y)[int(rand(1))]};$x++}
```
I can probably golf it further, but this should do for now.
Changes:
* Saved 10 bytes by myself, and 5 thanks to Alex A.
[Answer]
# Julia, 141 bytes
```
n->(R=rand;r=isodd(n)?R(1:n÷2):0;ucfirst(join([string("bcdfghjklmnpqrstvwxyz"[R(1:21)],"aeiou"[R(1:5)],i==r?"yh"[R(1:2)]:"")for i=1:n÷2])))
```
This creates an unnamed lambda function that accepts an integer as input and returns a string. it takes advantage of the fact that strings in Julia can be indexed and referenced like character arrays. To call it, give it a name, e.g. `f=n->...`.
Ungolfed + explanation:
```
function f(n)
# There will be n÷2 consonant-vowel pairs
p = n ÷ 2
# Determine which pair will get a y or h, if any
r = isodd(n) ? rand(1:p) : 0
# Consonants and vowels
c = "bcdfghjklmnpqrstvwxyz"
v = "aeiou"
# Randomly select letters for pairs, appending y or h as needed
s = [string(c[rand(1:21)], v[rand(1:5)], i == r ? "yh"[rand(1:2)] : "") for i in 1:p]
# Join s into a string and convert the first letter to uppercase
ucfirst(join(s))
end
```
Examples:
```
julia> f(9)
"Luyvunize"
julia> f(2)
"Fe"
julia> f(16)
"Pahonapipesafuze"
```
[Answer]
# Marbelous, 203 bytes
```
}0}0@1
>>^0&1
--=0@1FF
??&0}0&0
&1
qqqqqq\\\\
//\\pppppp
:p
0000
?K\\?4..}2
<G++<4+5=0\/}0
<B++<3+5?111>1!!
<6++<2+3Mult-2
<3++<1+3+7}2{<
++//mm//mm--
mm..{1..{2{>
{0
:q
}2{2}0
pppppp{0{1
-W
:m
}061
{0{0
```
[Test it out here (online interpreter).](https://codegolf.stackexchange.com/a/40808/29611) Input via arguments. Libraries and cylindrical boards must be enabled.
Commented/readable version:
```
}0 }0 @1 .. .. # 1st column: generate a number from 0 to length/2-1, wait on &1
>> ^0 &1 .. .. # 2nd column: check bottom bit; if zero activate &1, otherwise &0
-- =0 @1 FF .. # FF (wait on &0): if no h/y, set counter to 255 (0xFF)
?? &0 }0 &0 .. # Send copy of full length to :q
&1 .. .. .. ..
qq qq qq \\ \\ # Call :q with counter and length
// \\ pp pp pp # Output of :q falls into :p, which is called repeatedly until done
:p # prints a consonant/vowel pair, and h/y if needed
00 00 .. .. .. .. .. .. # two zeros, to be passed into ?K and ?4
?K \\ ?4 .. }2 .. .. .. # pass through ?K (0-20 = consonants) and ?4 (0-4 = vowels)
<G ++ <4 +5 =0 \/ }0 .. # 1st/2nd column: add 1-4 to skip vowels
<B ++ <3 +5 ?1 11 >1 !! # 3rd/4th column: add 3/6/11/16 to create nth vowel
<6 ++ <2 +3 Mu lt -2 .. # 5th/6th column: if counter is 0, generate either h or y
<3 ++ <1 +3 +7 }2 {< .. # 7th/8th column: if length left to print is 0-1, terminate
++ // mm // mm -- .. .. # mm: add 'a'. 1st/2nd start at 'b' (++)
# 5th/6th start at 'h' (+7)
mm .. {1 .. {2 {> .. .. # output consonant, vowel, h/y to {0, {1, {2
{0 .. .. .. .. .. .. .. # left input (length left): -2 + output to left
# right input (counter until print h/y): -1 + output to right
:q # calls :p, but with the first letter capitalized
}2 {2 }0 .. .. # {2 is an unused output which prevents exit when all outputs are filled
pp pp pp {0 {1 # call :p, and forward return outputs to MB to start loop
-W .. .. .. .. # subtract W (0x20) from the first letter = capitalize it
:m # add 0x61 ('a')
}0 61
{0 {0 # input + 0x61 is returned
```
This is roughly equivalent to the following pseudocode (`random(a,b)` generates numbers between `a` and `b` inclusive):
```
main(length)
if length & 0x01 == 0 then
counter, length_left = q(0xFF, , length)
else
counter, length_left = q(random(0, (length >> 1) - 1), , length)
end
while true do
length_left, counter, consonant, vowel, hy = p(length_left, , counter)
print consonant, vowel, hy
end
p(length_left, , counter)
if length_left <= 1 then terminate_program end
consonant = random(0, 20)
switch consonant
case >16: ++consonant
case >11: ++consonant
case >6: ++consonant
case >3: ++consonant
++consonant
consonant = m(consonant)
vowel = random(0, 4)
switch vowel
case >4: vowel += 5
case >3: vowel += 5
case >2: vowel += 3
case >1: vowel += 3
vowel = m(vowel)
if counter == 0 then
hy = random(0, 1) * 0x11
hy += 7
hy = m(hy)
return length_left - 2, counter - 1, consonant, vowel, hy
q(counter, , length_left)
length_left, counter, consonant, vowel, hy = p(length_left, , counter)
print consonant - 0x20, vowel, hy
return counter, length_left
m(number)
return number + 'a'
```
[Answer]
# Python 2, ~~148~~ ~~169~~ 156
```
from random import*
I=input()
R=choice
i=I/2
S=[R('hybcdfgjklmnpqrstvwxz')+R('aeiou')for _ in[0]*i]
if I%2:S[R(range(i))]+=R('hy')
print ''.join(S).title()
```
Edit: Realized it didn't capitalize the first letter. Ill see if I can golf it back down tomorrow.
Edit 2: Remembered `.title` but I think that will be it.
[Answer]
## SmileBASIC 2 (Petit Computer), ~~197~~ 177 bytes
**CONTEMPORARY EDIT MAY 2018**: This was my first submission ever, nearly 3 years ago! My skills have improved a lot since then; -20 just from minor adjustments.
It starts with a prompt (it's left blank to save bytes, so it's just a ?) where you put in the length (stored in variable `L`).
```
C$="bcdfgjklmnpqrstvwxzhyaeiou"INPUT L
J=0 OR L/2K=-1IF L%2THEN K=RND(J)
FOR I=0TO J-1?CHR$(ASC(MID$(C$,RND(21),1))-32*!I)+MID$(C$,RND(5)+21,1)+MID$(C$,RND(2)+19,1)*(K==I);
NEXT
```
I'm sure participating with an obscure BASIC language is gonna get me nothing but weird looks, but I managed to make it pretty small for BASIC. It takes advantage of SB's weird quirks (like conditionals evaluating to 1 or 0 since there's no boolean type) to eliminate as many bytes as I possibly could have when I wrote this at 3AM.
[Answer]
# Ruby, 119 bytes
13 bytes for capitalizing...
```
->n{z=(0...n/2).map{([*(?a..?z)]-v=%w[a e i o u]).sample+v.sample}
n.odd?&&z[rand n/2]+='yh'[rand 2]
(z*'').capitalize}
```
Usage:
```
f=
->n{z=(0...n/2).map{([*(?a..?z)]-v=%w[a e i o u]).sample+v.sample}
n.odd?&&z[rand n/2]+='yh'[rand 2]
(z*'').capitalize}
2.upto(20) do |i|
puts f[i]
end
```
Output:
```
Qo
Gah
Gilu
Baygu
Tevaba
Rohyori
Jigupadi
Diguvareh
Bidifenaji
Xohsuyileze
Depixoyizili
Boqizurejupiy
Buhuboketedasa
Vuwuhojetayduno
Forigikedawojawe
Qacetihxiheciyaju
Zoqigafukedugusoku
Bavuhlarofetucebapi
Zusiraxoxureqimavugo
```
[Answer]
# C, 219 characters
Seems to work, I'm still new to this.
```
char o[]="aeiouqwrtypsdfghjklzxcvbnm";n,i=0;main(int h,char**v){n=atol(v[1]);srand(time(0));h=n%2;for(;i<n-n%2;i+=2)printf("%c%c%c",o[rand()%21+5]-(i?0:32),o[rand()%5],(rand()%(n-1)<(i+2)&h)?h=0,'h'+(rand()%2?17:0):0);}
```
[Answer]
# R, 166 bytes
Takes input from STDIN and outputs to STDOUT.
```
l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')
```
Explanation
```
# Alias letters and sample
l=letters;
s=sample;
# Get input
n=scan();
# Vowel positions
v=c(1,5,9,15,21);
# Create a matrix with a row of
# consonants and a row of vowels
o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));
# If odd paste either h or y to a vowel
if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));
# Upper case first letter
o[1]=toupper(o[1]);
# Output
cat(o,sep='')
```
Some tests
```
> l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')
1: 13
2:
Read 1 item
Vetigiysurale
> l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')
1: 12
2:
Read 1 item
Mucowepideko
```
[Answer]
# K5, 131 bytes
```
{r:(`c$-32+c@1?#c),{*d@1?#d:(v;(c::(`c$97+!26)^v::"aeiou"))@2!x}'1+1_!x;$[x=p:2*_x%2;r;,/(*w),("yh"@1?2),*|w:(0,2+2**1?_(#r)%2)_r]}
```
This will NOT work on Kona or kdb+; you need to use a K5 interpreter like [oK](http://johnearnest.github.io/ok/index.html).
[Live demo.](http://johnearnest.github.io/ok/index.html?run=%7Br%3A(%60c%24-32%2Bc%401%3F%23c)%2C%7B*d%401%3F%23d%3A(v%3B(c%3A%3A(%60c%2497%2B!26)%5Ev%3A%3A%22aeiou%22))%402!x%7D%271%2B1_!x%3B%24%5Bx%3Dp%3A2*_x%252%3Br%3B%2C%2F(*w)%2C(%22yh%22%401%3F2)%2C*%7Cw%3A(0%2C2%2B2**1%3F_(%23r)%252)_r%5D%7D5) (Try setting the `5` at the end to a different number to try different inputs.)
[Answer]
# Ruby, ~~316 238~~ 216 chars
```
v=%w{a e i o u};c=[];(?a..?z).map{|i|v.include?(i)||c.push i};combos=[];c.map{|i| v.map{|j| combos.push i+j}};i=gets.to_i;o="";(i/2).times{o+=combos.sample};if i%2==1;(rand(4)==1?o+=?y:o+=?h); end; puts o.capitalize;
```
Odd number combos end in `h` or `y`.
Thanks to @blutorange for a complete dictionary of ruby golfing tips.
Whoa, I shortened my code by 100 chars.
[Answer]
## [Perl 5](https://www.perl.org/), 112 bytes
```
@;=map{(grep aeiou!~$_,a..z)[rand 21].(a,e,i,o,u)[rand 5]}1..$_/2;$_%2?$;[rand@;].=time%2?h:'y':0;$_=$"^join"",@
```
[Try it online!](https://tio.run/##LcnRCoIwGAbQ@@8pShYZrOU/tTSRfI8wGTRqoW5YXVTUo7ciuj3H6aFNva@KslPuER4G7UZKG3sdv1jDlRD32XZQ/X4kqRah4pobbvn1j2n9JCFYs5AFayZyw4qfV0Utyovp9JeO6@ltuo6@X7Jgd7KmDwJeeS8RI0GKJVbIkIMiEIEkKAYloBS0BK1AGSiHjN7WXYztz37u2g8 "Perl 5 – Try It Online")
] |
[Question]
[
If you like, write a program which sorts cities according to the rules of city name game.
* Each name of the city should start from the last letter in the previous city name. E.g. `Lviv -> v -> Viden -> n -> Neapolis -> s -> Sidney -> y -> Yokogama -> a -> Amsterdam -> m -> Madrid -> d -> Denwer`
* In the sorted list first letter of the first city and last letter of the last shouldn't match anything doesn't have to be the same letter.
* You can assume city names have only letters.
* Program output should have same capitalization as input
Example:
```
% ./script Neapolis Yokogama Sidney Amsterdam Madrid Lviv Viden Denwer
["Lviv", "Viden", "Neapolis", "Sidney", "Yokogama", "Amsterdam", "Madrid", "Denwer"]
```
[Answer]
### Ruby, 58 55 44 characters
```
p$*.permutation.find{|i|i*?,!~/(.),(?!\1)/i}
```
Yet another ruby implementation. Uses also case insensitive regex (as [Ventero](https://codegolf.stackexchange.com/users/84/ventero)'s old [solution](https://codegolf.stackexchange.com/a/6657)) but the test is done differently.
Previous version:
```
p$*.permutation.find{|i|(i*?,).gsub(/(.),\1/i,"")!~/,/}
```
[Answer]
## Python (~~162~~ ~~141~~ 124)
Brute force for the win.
```
from itertools import*
print[j for j in permutations(raw_input().split())if all(x[-1]==y[0].lower()for x,y in zip(j,j[1:]))]
```
[Answer]
# Python, 113
Very similar to @beary605's answer, and even more brute-forced.
```
from random import*
l=raw_input().split()
while any(x[-1]!=y[0].lower()for x,y in zip(l,l[1:])):
shuffle(l)
print l
```
[Answer]
## Ruby 1.9, ~~63~~ 54 characters
New solution is based on [Howard](https://codegolf.stackexchange.com/users/1490/howard)'s [solution](https://codegolf.stackexchange.com/a/6658/84):
```
p$*.permutation.max_by{|i|(i*?,).scan(/(.),\1/i).size}
```
This uses the fact that there'll always be a valid solution.
Old solution, based on [w0lf](https://codegolf.stackexchange.com/users/3527/w0lf)'s [solution](https://codegolf.stackexchange.com/a/6645/84):
```
p$*.permutation.find{|i|i.inject{|a,e|a&&e[0]=~/#{a[-1]}/i&&e}}
```
[Answer]
## Ruby ~~74 72 104 103 71~~ 70
```
p$*.permutation.find{|i|i.inject{|a,e|a[-1].casecmp(e[0])==0?e:?,}>?,}
```
**Demo:** <http://ideone.com/MDK5c> (in the demo I've used `gets().split()` instead of `$*`; I don't know if Ideone can simulate command-line args).
[Answer]
# [Haskell](https://www.haskell.org/), ~~94~~ 74 bytes
```
g[a]=[[a]]
g c=[b:r|b<-c,r<-g[x|x<-c,x/=b],last b==[r!!0!!0..]!!32]
head.g
```
Recursively finds all solutions. -7 bytes if it's ok to output all solutions instead of the first. Thanks to @Lynn for getting rid of the pesky import, shaving 18 bytes off the score!
[Try it online!](https://tio.run/##FYyxCsIwFAD3fsVrcbRVdBMzCI7qIggSM7w2r2lompYktBX67UaF47jpGvQtGRNr9ooNoSxUojgKxn8SiYKK8fLglvKYV2t3zBWfl/nf84aVYm3QBygZ4y5Ntz@KQqTpfidiIB/Y1DvpIbsRDr3RHp592yvsEO5aWnrDqfOBnMQOriidlnAZ9QgPLcnCmexELkuSDrVlg9M2wApq@I/jp6oNKh/zahi@ "Haskell – Try It Online")
[Answer]
### GolfScript, 78 characters
```
" ":s/.{1${1$=!},{:h.,{1$-1={1$0=^31&!{[1$1$]s*[\](\h\-c}*;}+/}{;.p}if}:c~;}/;
```
A first version in GolfScript. It also does a brute force approach. You can see the script running on the example input [online](http://golfscript.apphb.com/?c=OyJOZWFwb2xpcyBZb2tvZ2FtYSBTaWRuZXkgQW1zdGVyZGFtIE1hZHJpZCBMdml2IFZpZGVuIERlbndlciIKCiIgIjpzLy57MSR7MSQ9IX0sezpoLix7MSQtMT17MSQwPV4zMSYhe1sxJDEkXXMqW1xdKFxoXC1jfSo7fSsvfXs7LnB9aWZ9OmN%2BO30vOwo%3D).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
←fΛ~=o_←→P
```
[Try it online!](https://tio.run/##yygtzv7//1HbhLRzs@ts8@OBrEdtkwL@//8freSXmliQn5NZrKSj5FOWWQakXFLzylOLgIzgzJS81EogIywzJTUPSEfmZ@enJ@YmApm@iSlFmSlAhmNucUlqUUpirlIsAA "Husk – Try It Online")
### Explanation
```
←fΛ~=(_←)→P -- example input: ["Xbc","Abc","Cba"]
P -- all permutations: [["Xbc","Abc","Cba"],…,[Xbc","Cba","Abc"]]
f -- filter by the following (example with ["Xbc","Cba","Abc"])
Λ -- | all adjacent pairs ([("Xbc","Cba"),("Cba","Abc")])
~= -- | | are they equal when..
(_←) -- | | .. taking the first character lower-cased
→ -- | | .. taking the last character
-- | : ['c'=='c','a'=='a'] -> 4
-- : [["Xbc","Cba","Abc"]]
← -- take the first element: ["Xbc","Cba","Abc"]
```
### Alternatively, 10 bytes
We could also count the number of adjacent pairs which satisfy the predicate (`#`), sort on (`Ö`) that and take the last element (`→`) for the same number of bytes:
```
→Ö#~=o_←→P
```
[Try it online!](https://tio.run/##yygtzv7//1HbpMPTlOts8@MftU0AcgL@//8freSXmliQn5NZrKSj5FOWWQakXFLzylOLgIzgzJS81EogIywzJTUPSEfmZ@enJ@YmApm@iSlFmSlAhmNucUlqUUpirlIsAA "Husk – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 18 bytes (Improvements welcome!)
```
UżḢŒuE
ḲŒ!çƝẠ$ÐfḢK
```
[Try it online!](https://tio.run/##AVkApv9qZWxsef//VcW84biixZJ1RQrhuLLFkiHDp8ad4bqgJMOQZuG4okv///9OZWFwb2xpcyBZb2tvZ2FtYSBTaWRuZXkgQW1zdGVyZGFtIE1hZHJpZCBWaWRlbg "Jelly – Try It Online")
```
UżḢŒuE dyadic (2-arg) "check two adjacent city names" function:
Uż pair (żip) the letters of the reversed left argument with the right argument,
Ḣ get the Ḣead of that pairing to yield just the last letter of left and the first letter of right,
Œu capitalize both letters,
E and check that they're equal!
ḲŒ!çƝẠ$ÐfḢK i/o and check / fold function:
ḲŒ! split the input on spaces and get all permutations of it,
çƝẠ$ run the above function on every adjacent pair (çƝ), and return true if Ȧll pairs are true
Ðf filter the permutations to only get the correct ones,
ḢK take the first of those, and join by spaces!
```
Thanks to @Lynn for most of these improvements!
**25-byte solution:**
```
Uḣ1Œu=⁹ḣ1
çƝȦ
ḲŒ!©Ç€i1ị®K
```
[Try it online!](https://tio.run/##y0rNyan8/z/04Y7Fhkcnldo@atwJYnIdXn5s7ollXA93bDo6SfHQysPtj5rWZBo@3N19aJ33/////VITC/JzMosVIvOz89MTcxMVgjNT8lIrFRxzi0tSi1IScxV8E1OKMlMUfMoyyxTCMlNS8xRcUvPKU4sA "Jelly – Try It Online")
```
Uḣ1Œu=⁹ḣ1 dyadic (2-arg) "check two adjacent city names" function:
Uḣ1Œu reverse the left arg, get the ḣead, and capitalize it (AKA capitalize the last letter),
=⁹ḣ1 and check if it's equal to the head (first letter) of the right argument.
çƝȦ run the above function on every adjacent pair (çƝ), and return true if Ȧll pairs are true
ḲŒ!©Ç€i1ị®K main i/o function:
ḲŒ!© split the input on spaces and get all its permutations, ©opy that to the register
Ç€ run the above link on €ach permutation,
i1 find the index of the first "successful" permutation,
ị®K and ®ecall the permutation list to get the actual ordering at that ịndex, separating output by spaces
```
[Answer]
# Mathematica 236 chars
Define the list of cities:
```
d = {"Neapolis", "Yokogama", "Sidney", "Amsterdam", "Madrid", "Lviv", "Viden", "Denver"}
```
Find the path that includes all cities:
```
c = Characters; f = Flatten;
w = Outer[List, d, d]~f~1;
p = Graph[Cases[w, {x_, y_} /;x != y \[And] (ToUpperCase@c[x][[-1]]== c[y][[1]]) :> (x->y)]];
v = f[Cases[{#[[1]], #[[2]], GraphDistance[p, #[[1]], #[[2]]]} & /@ w, {_, _, Length[d] - 1}]];
FindShortestPath[p, v[[1]], v[[2]]]
```
Output:
```
{"Lviv", "Viden", "Neapolis", "Sidney", "Yokogama", "Amsterdam","Madrid", "Denver"}
```
The above approach assumes that the cities can be arranged as a path graph.
---
The graph p is shown below:

[Answer]
# C, 225
```
#define S t=v[c];v[c]=v[i];v[i]=t
#define L(x)for(i=x;i<n;i++)
char*t;f;n=0;main(int c,char**v){int i;if(!n)n=c,c=1;if(c==n-1){f=1;L(2){for(t=v[i-1];t[1];t++);if(v[i][0]+32-*t)f=n;}L(f)puts(v[i]);}else L(c){S;main(c+1,v);S;}}
```
Run with country names as the command line arguments
Note:
* brute force generation of permutations
* for checking it assumes that country names start with an upper case and end in lower case.
* assumes there is only one answer
* In C, assumes that the \*\*v array of main() is writable
[Answer]
## J, 69 65 60 59 54 characters
Somewhat off the pace.
```
{.l\:+/2=/\|:tolower;"2({.,{:)@>l=.(i.@!@#A.]);:1!:1[1
```
Example:
```
{.l\:+/2=/\|:tolower;"2({.,{:)@>l=.(i.@!@#A.]);:1!:1[1
Neapolis Yokogama Sydney Amsterdam Madrid Lviv Viden Denwer
+----+-----+--------+------+--------+---------+------+------+
|Lviv|Viden|Neapolis|Sydney|Yokogama|Amsterdam|Madrid|Denwer|
+----+-----+--------+------+--------+---------+------+------+
```
[Answer]
**C#, 398**
And here is C# with Linq 5 cents
```
IEnumerable<string>CityNameGame(string[]input){var cities=new List<string>(input);string lastCity=null;while(cities.Any()){var city=lastCity??cities.First();lastCity=cities.First(name=>string.Equals(city.Substring(city.Length-1),name.Substring(0,1),StringComparison.CurrentCultureIgnoreCase));cities.RemoveAll(name=>name==city||name==lastCity);yield return string.Format("{0}→{1}",city,lastCity);}}
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~374 bytes~~ 302 bytes
```
using System;using System.Linq;class Program{static void Main(string[] s){Func<char, char>u=(c)=>char.ToUpperInvariant(c);var S="";int I=0,C=s.Count();for(;I<C;I++)S=Array.Find(s,x=>u(s[I][0])==u(x[^1]))==null?s[I]:S;for(I=0;I<C;I++){Console.Write(S+" ");S=C>I?Array.Find(s,x=>u(S[^1])==u(x[0])):"";}}}
```
[Try it online!](https://tio.run/##ZZBtS8MwFIX/yqWfGjbLXt1Llo5RGRSmCPEFKRVCGmewTWaS1o2x316zCSL45XIuh/vcw@H2imsj2ra2Um2BHqwTFf67RBupPjEvmbVwb/TWsOpoHXOSQ6NlAbdMqtA64y@yHCw6rmvFF/ydmS6cZ1yTkCMSn3X0oB93O2FS1TAjmXLewV4CJUGApXKQkl43ITZKdO1dhN@0CXG6SHDa6SBKVsawQ7SWqghtd0/iOrRZmme9HBFSh/vstZ8jL1VdlsuzM6cXgqf@Qo6JVlaXIno20omQdgIIEKYkidPlfzy9IH/g/gua@5yn06lt2zvBdrqUFl70h96yigGVhRIHWFW@NlOwyldTGN/QppENPMlCKLgR6kuYdjKF4QgGQ5jOoD@A0RiuJzDrwfj6Gw "C# (.NET Core) – Try It Online")
```
using System;
using System.Linq;
class Program
{
static void Main(string[] s)
{
Func<char, char> u = (c) => char.ToUpperInvariant(c);
var S = "";
int I = 0, C = s.Count();
for (; I < C; I++)
S = Array.Find(s, x => u(s[I][0]) == u(x[^1])) == null ? s[I] : S;
for (I = 0; I < C; I++)
{
Console.Write(S + " ");
S = C > I ? Array.Find(s, x => u(S[^1]) == u(x[0])) : "";
}
}
}
```
---
[Try it online!](https://tio.run/##bVHLbtswEDxXX7HQJSTsKM77oTJBoMKAAKcoyrRBEOTASqxCVCJdknZtGPp2lbQqR2qyF@1iRzvDmczsZ0rzZmGELICujeVVHPSnaCbk7zjISmYMfNGq0KwKNgG4MpZZkcFSiRzumJDIWO1@fHoGpguDt5gW6eun42HZyz@Qh4CQPeQQ7WuK3Dai81JYtAd7GMeDdaKkUSWPHrSw3KnkqAeod93BwU4WBQIbCD9zNlelMOEYwkf1SxWsYr6nIpd87bvbyj1d56zywx3Ltch9N1uKpf9@FzmXvvnE5R@uQ6jjHt0UUdyfO51fOcs7iXXwxsHpq32dd82SaaAkDGMhLaRkMk6IiRK1kNYdcoaiOP2YxOlohCm51Zqto6mQOTLjFbk2T@lzRBc/2qtoMj7E0b36Np9zjTAhq95uFc24LOzLfh/iMHJRljf@zhXdsjkFO8LNwH5ERyGEOKYkuU5v/pdCe1z0Pa6hnKFUfOXeXzcf6qBumi466HKDNjTYJQZtXOCzgm1Q0KbUnF/A8QkcHcPFJRwewckpnJ3D5QROz/4C "C# (.NET Core) – Try It Online")
```
using System;
using System.Linq;
var S = "";
int I = 0, C = s.Count();
for (; I < C; I++)
S = Array.Find(
s, x =>
s[I].Substring(0, 1).ToUpper() == x.Substring(x.Length - 1).ToUpper()
) == null ?
s[I] :
S;
for (I = 0; I < C; I++) {
Console.Write(S + " ");
S = C > I ? Array.Find(s, x => S.Substring(S.Length - 1).ToUpper() == x.Substring(0, 1).ToUpper()) : "";
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á kÈäÈÌkYÎÃd
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=4SBryOTIzGtZzsNk&input=WyJOZWFwb2xpcyIsIllva29nYW1hIiwiU2lkbmV5IiwiQW1zdGVyZGFtIiwiTWFkcmlkIiwiTHZpdiIsIlZpZGVuIiwiRGVud2VyIl0)
[Answer]
# K, 96
```
{m@&{&/(~).'+(,_1_1#'x),,-1_-1#'x}@'$m:{$[x=1;y;,/.z.s[x-1;y]{x,/:{x@&~x in y}[y;x]}\:y]}[#x;x]}
```
.
```
k){m@&{&/(~).'+(,_1_1#'x),,-1_-1#'x}@'$m:{$[x=1;y;,/.z.s[x-1;y]{x,/:{x@&~x in y}[y;x]}\:y]}[#x;x]}`Neapolis`Yokogama`Sidney`Amsterdam`Madrid`Lviv`Viden`Denver
Lviv Viden Neapolis Sidney Yokogama Amsterdam Madrid Denver
```
] |
[Question]
[
.Net Technology is an incredible framework with marvellous functionalities, and among all of them, the most important one obviously stands out:
[](https://i.stack.imgur.com/YANCl.png)
Yep, your simple task is create a program that when it takes at input:
```
dotnet ef
```
It prints the following ascii art by output:
```
/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
```
And you have to do it in the lowest number of bytes of course.
**Rules**
* If the program doesn't receive `dotnet ef` by input it doesn't output anything
* The program with the fewest bytes wins so this is a code golf challenge
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 100 bytes
```
1/s/^dotnet ef$/oooo..oo.aJo..z..o8o..3.3.svo!.3.3.q.3.5.4.43oo)q!+./;s/./ord$&/ge;y;0-9;
_\\/|.=)-
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDMxMmYgNzMyZiA1ZTY0IDZmNzQgNmU2NSA3NDIwIDY1NjYgMjQyZiAgMS9zL15kb3RuZXQgZWYkL1xuMDAwMDAwMTA6IDZmNmYgNmY2ZiA4ZmRjIDZmNmYgYzc2MSA0YTZmIDg1MDAgN2FkMyAgb29vby4ub28uYUpvLi56LlxuMDAwMDAwMjA6IGRlNmYgMzg2ZiA4NzFlIDMzZTEgMzNlMSA3Mzc2IDZmMjEgMWUzMyAgLm84by4uMy4zLnN2byEuM1xuMDAwMDAwMzA6IGZiMzMgZmI3MSBmMTMzIDkwMzUgMWUzNCBlMTM0IDMzNmYgNmYyOSAgLjMucS4zLjUuNC40M29vKVxuMDAwMDAwNDA6IDcxMjEgMmIwMyAyZjNiIDczMmYgMmUyZiA2ZjcyIDY0MjQgMjYyZiAgcSErLi87cy8uL29yZCQmL1xuMDAwMDAwNTA6IDY3NjUgM2I3OSAzYjMwIDJkMzkgM2IwYSAyMDVmIDVjNWMgMmY3YyAgZ2U7eTswLTk7LiBfXFxcXC98XG4wMDAwMDA2MDogMmUzZCAyOTJkICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAuPSktIiwiYXJncyI6Ii1wIiwiaW5wdXQiOiJkb3RuZXQgZWYifQ==)
## Explanation
`1/s/^dotnet ef$/...` will exit with a division by zero unless the input is `dotnet ef`, then the data is packed into the 52-byte binary string. Since there were 10 distinct chars, it's possible to convert those original chars to digits 0-9, which were then packed (so `111111111111143` becomes `chr(111) + chr(111) + chr(111) + chr(111) + chr(143)`), This packed string is replaced into `$_` (where the implicit input is stored) via `s///`ubstitution, then each char is `s///`ubstituted with its `ord`inal value and then transliterated (`y///`) back to the original chars.
---
# [Perl 5](https://www.perl.org/) + `-pF/^(dotnet\x20ef)$/`, 94 bytes
Same as above, except abusing flags for the early exit.
```
1/$#F;$_='oooo..oo.aJo..z..o8o..3.3.svo!.3.3.q.3.5.4.43oo)q!+.';s/./ord$&/ge;y;0-9;
_\\/|.=)-
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDMxMmYgMjQyMyA0NjNiIDI0NWYgM2QyNyA2ZjZmIDZmNmYgOGZkYyAgMS8kI0Y7JF89J29vb28uLlxuMDAwMDAwMTA6IDZmNmYgYzc2MSA0YTZmIDg1MDAgN2FkMyBkZTZmIDM4NmYgODcxZSAgb28uYUpvLi56Li5vOG8uLlxuMDAwMDAwMjA6IDMzZTEgMzNlMSA3Mzc2IDZmMjEgMWUzMyBmYjMzIGZiNzEgZjEzMyAgMy4zLnN2byEuMy4zLnEuM1xuMDAwMDAwMzA6IDkwMzUgMWUzNCBlMTM0IDMzNmYgNmYyOSA3MTIxIDJiMDMgMjczYiAgLjUuNC40M29vKXEhKy4nO1xuMDAwMDAwNDA6IDczMmYgMmUyZiA2ZjcyIDY0MjQgMjYyZiA2NzY1IDNiNzkgM2IzMCAgcy8uL29yZCQmL2dlO3k7MFxuMDAwMDAwNTA6IDJkMzkgM2IwYSAyMDVmIDVjNWMgMmY3YyAyZTNkIDI5MmQgICAgICAgLTk7LiBfXFxcXC98Lj0pLSIsImFyZ3MiOiItcEYvXihkb3RuZXRcXHgyMGVmKSQvIiwiaW5wdXQiOiJkb3RuZXQgZWYifQ==)
[Answer]
# [Python 3](https://docs.python.org/3/), 129 bytes
```
lambda s:(s=='dotnet ef')*b'V`"D1PffayWPqfwgqUqqgc3uPvfwgU5P'.hex().translate('-/=\_|).\n '*9)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSqPY1lY9Jb8kL7VEITVNXVMrSV0QDITDEoCkkJKLoaBogFiaYFqiYKWgYHhAYVq5WLpgoYSgaCi7WGFhuqBosrigcWlAWVp5OkgbUNw0QF0vI7VCQ1OvpCgxrzgnsSRVQ11X3zYmvkZTLyZPQV3LUvN/QVFmXolGmgay5Zpc6KJpqUDR/wA "Python 3 – Try It Online")
### Explanation
We use [**`bytes.hex()`**](https://docs.python.org/3/library/stdtypes.html#bytes.hex) to convert the byte-string to a string of hexadecimal digits, which looks like this:
```
11111111111113566011111112224431111550166611666111791111575071667716671171181115550716717167111563171133755076667767111111131115553550
```
From here, we perform a [**`str.translate()`**](https://docs.python.org/3/library/stdtypes.html#str.translate), to map the digits `'0123456789'` to `'-/=\_|).\n '`. These are the ten characters that make up the entire unicorn drawing.
Special care should be taken to ensure that the compressed string won't contain any values exceeding the ASCII range. The program below finds such strings:
```
from itertools import *
ART = ' /\\__\n ---==/ \\\\\n ___ ___ |. \\|\\\n| __|| __| | ) \\\\\\\n| _| | _| \\_/ | //|\\\\\n|___||_| / \\\\\\/\\\\\n'
L = '\n )-./=\_|'
for p in permutations(range(10)):
compressed = b''.fromhex(''.join('0123456789'[p[L.find(c)]] for c in ART))
if max(compressed) < 128:
trans = [None] * 10
for i in range(10):
trans[(p[i] + 48) % 10] = L[i]
print('translation:', repr(''.join(trans)))
print('compressed:', compressed.decode())
break
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 152 bytes
Contains unprintable `RS` characters.
```
s=>Buffer(s=="dotnet ef"?'
#:u
"J`P
9&v
vn
1
39(v)&o
(!
4e&((o
s
U*90v)o
#
4R2':0).map(n=>o+=(c=` |\\)-/=
_.`)[n/10-3|0]+c[n%10],o='')&&o
```
[Try it online!](https://tio.run/##XY6xbsIwFEV3PuLVBOE8lyY4wBKkBxJjpwqJCRAJwUYg6ofi4Il/T9NOqHc4wz260r2WofRVfbk3ieOTaS21nharh7WmRk8UnbhxphHGRssY/jKYPzpGn8UXiFwGCA4ygGmOQUkG7IOYGYnIIPwbbN5zHRT/zrp@PYnnWqXf5R0dLXhEWFEhnrudSsbUO6SF2rpxppPpU@9H1dYNM73/YIpjJSW3FTvPN5Pe@IwWX54p1fvnLLM4lnVn2h8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES8), 152 bytes
```
s=>s=='dotnet ef'?`94/0__
7---==/400
1___2___3|.40|0
|1__||1__|2|2)3000
|1_|1|1_|30_/1|2//|00
|___||_|7/3000/00`.replace(/\d/g,n=>''.padEnd(n)||'\\'):''
```
[Try it online!](https://tio.run/##XY69CoMwFIX3PIW4xEDNvf6AtBA79S2EmJooLZKISqf77lYdOnQ4Z/i@M5y3@Zilm1/Tmvpg3darbVH1ohS3YfVujVzP7@21BNSaVWmaKgUlIsu01vmegmSJhIx2QGfllIsC8USUHVWghoxyADqoPoaaKjhGgNjK2U2j6VwCjYXh4lXNuZyMfXibeEHEm4aLG@dbF/wSRifHMCR9Ev8OxkKwP9eHED3NvJvtCw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes
```
¿⁼Sdotnet ef”{¶⊟u↗9≧fXj⪪⊙O|↔d<⭆)⟧ΦÞ‴ζLP≧≦⁸1?_U~l7(I℅gºqu⪫ÀF◨Y∧π⦄◧μ×⎚⁶↓sαbGAaF
```
[Try it online!](https://tio.run/##TY5BC8IwDIXv/orQUwvW/ADZ0YM3wWshlLnpYHQ6O0/577Vp5/AdHsn7eCTtw8/t5MeUhh706bX48a3P4bnEa5yHcNdmD@o2xdBF6HplDFxyHLWCf6FzRC6sm7W2aVAmJwpARFAN@FBzFsA55GIZAJhfoyKGYpIRCkfkFZL0CivXtx6KKXNMaXt5l@xn/AI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Just Charcoal's default string compression, conditional on the input line (which needs a trailing newline to prevent Charcoal's autosplit on spaces).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 82 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁼“¤fÞ#³ıḄ×»“¡mƁµɼʋ"§ĿỵSėṭƊḲṂ§ÇḋỵL}Ṅnʠṫ2#ap{}fƓ*ƑṇḢ§ƓṾ®[~]sṘÐ/wỊḊ.÷⁹ß’ḣṃ“ \_¶-=|.)/
```
A full program accepting a string that prints the art when that string is "dotnet ef".
**[Try it online!](https://tio.run/##Aa0AUv9qZWxsef//4oG84oCcwqRmw54jwrPEseG4hMOXwrvigJzCoW3GgcK1ybzKiyLCp8S/4bu1U8SX4bmtxorhuLLhuYLCp8OH4biL4bu1TH3huYRuyqDhuasyI2Fwe31mxpMqxpHhuYfhuKLCp8aT4bm@wq5bfl1z4bmYw5Avd@G7iuG4ii7Dt@KBucOf4oCZ4bij4bmD4oCcIFxfwrYtPXwuKS////9kb3RuZXQgZQ "Jelly – Try It Online")**
### How?
```
⁼“...»“...’ḣṃ“... - Main Link: string, S
“...» - dictionary compression of "dotnet ef"
⁼ - S equals that? (1 if so; 0 otherwise)
“...’ - base 250 integer (say, n) = 1111111111111023341111111555660111122413331133311178111127247133771337117119111222471371713711123017110072247333773711111110111222022
ḣ - head that (implicitly wrapped in a list) by (1 or 0)
-> [n] or []
“... - the art's characters (¶ is a newline & no closing quote needed)
ṃ - decompress the integers (in either [n] or []) using the
characters as the digits [1,...,9,0] (as there are ten of them)
- implicit, smashing print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 85 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
’¥¥‡Ò ef’Qi•{Ã∍ûç=®¤[ˆ ôÆ-˜´≠pw:‡©[§∊è$#±8¡žR=α»ιœëā7¬ÄÒU₁ýmOÜÉt×›ʒ•"_ |\/
-=)."ÅвJëõ
```
[Try it online.](https://tio.run/##AaMAXP9vc2FiaWX//@KAmcKlwqXigKHDkiBlZuKAmVFp4oCie8OD4oiNw7vDpz3CrsKkW8uGIMO0w4Yty5zCtOKJoHB3OuKAocKpW8Kn4oiKw6gkI8KxOMKhxb5SPc6xwrvOucWTw6vEgTfCrMOEw5JV4oKBw71tT8Ocw4l0w5figLrKkuKAoiJfIHxcLwotPSkuIsOF0LJKw6vDtf//ZG90bmV0IGVm)
A compressed string `.•1piN∍Ç•` instead of dictionary string `’¥¥‡Ò ef’` would be the same byte-count.
**Explanation:**
```
’¥¥‡Ò ef’ # Push the dictionary string "dotnet ef"
Qi # If the (implicit) input is equal to this:
•{Ã∍...×›ʒ• # Push compressed integer 1111111111111430051111111666774111133510001100011129111132352100221002112118111333521021210211130412114423352000220211111114111333433
"_ |\/\n-=)." # Push this string
Åв # Convert the large integer to base-"_ |\/\n-=)."
# which means base-length, and then indexing it into the string
J # Join this list of characters together
ë # Else:
õ # Push an empty string instead
# (after which the top is output implicitly as result)
```
The compressed ASCII-art is generated using [the generator program in this 05AB1E tip](https://codegolf.stackexchange.com/a/120966/52210).
[See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress strings not part of the dictionary?*, and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’¥¥‡Ò ef’` is `"dotnet ef"`; `.•1piN∍Ç•` is `"dotnet ef"` as well; and `•{Ã∍ûç=®¤[ˆ ôÆ-˜´≠pw:‡©[§∊è$#±8¡žR=α»ιœëā7¬ÄÒU₁ýmOÜÉt×›ʒ•` is `1111111111111430051111111666774111133510001100011129111132352100221002112118111333521021210211130412114423352000220211111114111333433`.
[Answer]
# [Python 3](https://docs.python.org/3/), 156 bytes
```
if"dotnet ef"==input():print(r""" /\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\""".expandtabs(6))
```
[Try it online!](https://tio.run/##PY4xCsMwDEVn5RTCkz04GgodCr6JQKQkoVkck7rQgu7uyBkqpD88HpLKr772fGttW92817xUXFaX0pbLp/rwKMeWqz@ccwBILDIAxhhTIrRiHlBEoI@OwMqDGtArEK0DmHRRxR7AQp0TacfSZaO2iy6TmO3WuHzLlOc6Pd/@HkJr/9dO "Python 3 – Try It Online")
Credits to @AnttiP
[Answer]
# [C (gcc)], ̶2̶1̶7̶ 212 202 bytes
```
#define S"\\\\\r"
main(c,v)int**v;{strcmp(v[1],"dotnet ef")||printf("%14c\\__\r%8c--==/%7s ___ ___ |. \\|\\\r| __|| __| | ) \\"S"| _| | _| \\_/ | //|"S"|___||_|%8c \\\\\\/"S,47,45,S,47);}
```
[Try it online!](https://tio.run/##PY5NCoMwEIX3PcWQIqjEBsFiQTyFy6YEiYkINRUVu@j06k0zFvoWb@B986ezXmvvj52xgzPQMEma2WFsBxdrviWDW9N0q17LOutxirdrfuOse6zOrGAsSxCnOfTYmEV5oaVUSs7RRWdZXYuoXEApBT8DPAUDKZFOYAhxtwAAkp2whoUIYTcKlCAoBBJRNKEwbN8ZSbCGFyUvzpxqUr299//nPtre237x2fML "C (gcc) – Try It Online")
Previous versions :
```
char*S="\\\\\r";main(c,v)char**v;{if(!strcmp(v[1],"dotnet ef"))printf("%14s\\__\r%8s--==/%7s ___ ___ |. \\|\\\r| __|| __| | ) \\%s| _| | _| \\_/ | //|%s|___||_|%8s \\\\\\/%s","/","-",S,S,S,"/",S);}
```
**Contributions** :
*Makonede* :
* remove the brace for the if statement
* change the define by a global variable
*celingcat* :
* replace the if by the OR test
* put the define S inside the string of the printf
* change some characters by theirs ascii values.
[Answer]
# [Julia](https://julialang.org/), ~~177~~ 163 bytes
```
f(i)=i=="dotnet ef"&&print(" "^13,"/\\__
"," "^7,raw"---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\
|___||_| / \\/\\
")
```
[Try it online!](https://tio.run/##TY6xCsMwDER3f4XQEGKwK0KHTv4TUxFoAi4lLcGlGfTvrqwuveHgng509/ejzNPR2joWn0pKeHvWbamwrDgMr71sdUTA63QOSDkzOww9X8I@fzDGmBKBKmcHzAw/AzkZlAxOFImZYgBv5dyxgJlmpn4iEuXc64a7yOr62aHXjX/rfPsC)
Thanks to MarcMush we can bring it down to 163 bytes by using `raw` which allows us to use `\` without escaping!
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 75 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
dotnet ef≡?“cL⤢43¶h\^»)√@h┘S┼N(fV/3XVk#6K}⁰⤢KE @@sMo↷.(RqgaF╶u┬∑z7F│┘@&k]⁰‟
```
[Try it here!](https://dzaima.github.io/Canvas/?u=ZG90bmV0JTIwZWYldTIyNjEldUZGMUYldTIwMUMldUZGNDNMJXUyOTIyNDMlQjZoJTVDJXVGRjNFJUJCJXVGRjA5JXUyMjFBJXVGRjIwJXVGRjQ4JXUyNTE4UyV1MjUzQ04ldUZGMDhmJXVGRjM2JXVGRjBGMyV1RkYzOCV1RkYzNiV1RkY0QiV1RkYwMyV1RkYxNiV1RkYyQiU3RCV1MjA3MCV1MjkyMiV1RkYyQiV1RkYyNSUyMEAldUZGMjBzTSV1RkY0RiV1MjFCNy4lMjgldUZGMzIldUZGNTEldUZGNDcldUZGNDEldUZGMjYldTI1NzZ1JXUyNTJDJXUyMjExJXVGRjVBJXVGRjE3RiV1MjUwMiV1MjUxOEAlMjZrJXVGRjNEJXUyMDcwJXUyMDFG,i=ZG90bmV0JTIwZWY_,v=8)
just canvas's string compression.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `O`, 82 bytes
```
«ƛ4-ʀWṪ«=[»|ȮW¼∩r¶‛v←^ǔṠlȯ¦U4;o→₄v₂V⊍cbε×√ẋÞrAĖRṫ⇧ż÷₇Ṗ⌈¨YΠ1ʁ⋎Ẋ8…ṡ@»`_ |\/\n-=).`τ₴
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJPIiwiIiwiwqvGmzQtyoBX4bmqwqs9W8K7fMiuV8K84oipcsK24oCbduKGkF7HlOG5oGzIr8KmVTQ7b+KGkuKChHbigoJW4oqNY2LOtcOX4oia4bqLw55yQcSWUuG5q+KHp8W8w7figofhuZbijIjCqFnOoDHKgeKLjuG6ijjigKbhuaFAwrtgXyB8XFwvXFxuLT0pLmDPhOKCtCIsIiIsImRvdG5ldCBlZiJd)
## Explanation
A port of [Kevin Cruijssen's O5AB1E answer](https://codegolf.stackexchange.com/a/241682/45220)
```
<O flag> (disable implicit output, so anything other than 'dotnet ef' doesnt print anything)
«ƛ4-ʀWṪ«=[ - If the input equals 'dotnet ef':
»|ȮW¼...8…ṡ@» - Push a big compressed integer
`_ |\/\n-=).`τ₴ - Replace the digits with symbols, and print.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~175~~ 169 bytes
-6 bytes by reusing the input variable
```
i;f(char*p){if(!strcmp(p,"dotnet ef"))for(p="76QI:i7[bQ4Ji1;2;3Aq4IAIiA1:B1:A2A2y3KiA19A1A19A3I9Q1A2RAJiA;B9A7Q3KQJ";i=*p++;)while(i--&7)putchar(" _|\\/-=\n.)"[i/8-6]);}
```
[Try it online!](https://tio.run/##PY@xbsIwGITn8hTGQ2UHXOQEkSZWBrMlTO6aVFVw4/BLENzgFlWUV68bL11O30l30p1mvdbegzBEH9oxsvQGhswvbtQnS@wSv5/d0DnUGUypOY/EFjjdqDKHtN6rdQVcxCKRH@tSliB5vuW5jGX8newml0keJCkzxWX8IiuQYpvJVCU7VWEBRWQXC0GvBzh2BBh7TKn9dGEHwejtp2lWrGiGJ4prWD2zzSsVdw@DQ6cWBhKgHXu9RKGAomgyXxTdZg@GBKz5lJ/dvf9/8KvNse0vnl3/AA "C (gcc) – Try It Online")
I used RLE compression, where the lower 3 bits are the length and the high bits encode the character index. By shifting the index by 6 we get an encoding that doesn't require escaping in a string literal. I used this function for encoding:
```
void encode() {
char chars[] = " _|\\/-=\n.)";
int cur, prev = ' ', count = 0;
while ((cur = getchar()) != EOF) {
if (cur == prev && count < 7) {
count++;
} else {
putchar((strchr(chars, prev) - chars + 6) * 8 + count);
count = 1;
}
prev = cur;
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~83~~ 82 bytes
```
’¥¥‡Ò ef’Q•{Ã∍ûçαÖв₂þ₂ÕµŒHθǝ¤kªγVíαвÒf¾ΘMãwà5ÚX¿Q₆Sì=ЧòqxheΘ+ãkÛž•"/ \_
-=|.)"Åв×
```
[Try it online!](https://tio.run/##AZ8AYP9vc2FiaWX//@KAmcKlwqXigKHDkiBlZuKAmVHigKJ7w4PiiI3Du8OnzrHDltCy4oKCw77igoLDlcK1xZJIzrjHncKka8KqzrNWw63OsdCyw5Jmwr7OmE3Do3fDoDXDmljCv1HigoZTw6w9w5DCp8OycXhoZc6YK8Oja8Obxb7igKIiLyBcXwotPXwuKSLDhdCyw5f/Sv9kb3RuZXQgZWY "05AB1E – Try It Online") Outputs as a list of characters. Link includes a footer to format the output.
[Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), why so bad?
[Answer]
# Python3, 177 bytes
```
if"dotnet ef"==input():print(" /\__\n ---==/ \\\\\n ___ ___ |. \|\ \n| __|| __| | ) \\\\\ \n| _| | _| \_/ | //|\\\n|___||_| / \\\/\\")
```
[Try it online!](https://tio.run/##TY4xDsMwCEWvgjzFg8vQrZJvgsTSRPFCrIoMlbi7a@O0KsMXvK8P1Lfuh9xbKxsUqacuMefwPFRWhXULj/oqokuA/0JiJrmGlFLOODoaJcDMMAXs5twISKwzc@kcIH4D0zJw6Yxx2Ig2lhmPkBt@eIaQKMTWfl9@AA)
] |
[Question]
[
We all know how binary conversion works: the sequence of bits
$$ b\_1, b\_2, ..., b\_{n-1}, b\_n $$
encodes the number
$$ b\_1 \times 2^{n-1} + b\_2 \times 2^{n-2} + ... + b\_{n-1} \times 2^1 + b\_n \times 2^0 $$
This gives an unambiguous representation when we limit all bits \$ b\_i \$ to be only `0` or `1`.
...but what if we allow digits outside that range? How about also allowing the "bits" `2` and `3`?
The normal representation of 18 in binary would be `10010`, but since `10` is \$ 1 \times 2^1 + 0 \times 2^0 = 1 \times 2 + 0 = 2 \$,
we could also write it as `02` (\$ 0 \times 2^1 + 2 \times 2^0 = 2 \$), we could also write \$ 18 \$, in an "overflowed" binary, as `10002`.
But we can also see that `10000` (\$ 16 \$) could be `02000`, so \$ 18 \$ could be `02002`. We can repeat this process
and get a whole list of possible "overflowed binary" encodings for our number \$ 18 \$ (which includes \$ 18 \$'s normal binary encoding):
```
10010
10002
02010
02002
01210
01202
01130
01122
00330
00322
```
## Task
Given a number \$ n \$ and a maximum digit value \$ c \$, output all possible lists of digits between \$ 0 \$ and \$ c \$ (inclusive)
which encode \$ n \$ in overflowed binary.
## Rules
* You may assume \$ n \$ and \$ c \$ will both be integers with \$ n \ge 0 \$ and \$ c \ge 1 \$
* You may output lists with any (finite) number of leading zeroes, but you not output duplicate lists that differ only by leading zeroes;
for example, you may not output both `[0, 1, 3]` and `[1, 3]`
* You must output in a way that clearly separates digits, even when they are greater than \$ 9 \$.
For example, `[13, 2]` must be distinguishable from `[1, 3, 2]`
* You may use [any reasonable I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
These test outputs are padded with leading zeroes such that all output lists are the same length.
```
n c output
--------------
0 1 [[0]]
0 5 [[0]]
1 1 [[1]]
4 7 [[0,0,4],[0,1,2],[0,2,0],[1,0,0]]
18 3 [[0,0,3,2,2],[0,0,3,3,0],[0,1,1,2,2],[0,1,1,3,0],[0,1,2,0,2],[0,1,2,1,0],[0,2,0,0,2],[0,2,0,1,0],[1,0,0,0,2],[1,0,0,1,0]]
12 12 [[0,0,0,12],[0,0,1,10],[0,0,2,8],[0,0,3,6],[0,0,4,4],[0,0,5,2],[0,0,6,0],[0,1,0,8],[0,1,1,6],[0,1,2,4],[0,1,3,2],[0,1,4,0],[0,2,0,4],[0,2,1,2],[0,2,2,0],[0,3,0,0],[1,0,0,4],[1,0,1,2],[1,0,2,0],[1,1,0,0]]
14 10 [[0,0,2,10],[0,0,3,8],[0,0,4,6],[0,0,5,4],[0,0,6,2],[0,0,7,0],[0,1,0,10],[0,1,1,8],[0,1,2,6],[0,1,3,4],[0,1,4,2],[0,1,5,0],[0,2,0,6],[0,2,1,4],[0,2,2,2],[0,2,3,0],[0,3,0,2],[0,3,1,0],[1,0,0,6],[1,0,1,4],[1,0,2,2],[1,0,3,0],[1,1,0,2],[1,1,1,0]]
429 3 [[0,1,2,3,2,3,3,3,3],[0,1,2,3,3,1,3,3,3],[0,1,2,3,3,2,1,3,3],[0,1,2,3,3,2,2,1,3],[0,1,2,3,3,2,2,2,1],[0,1,2,3,3,2,3,0,1],[0,1,2,3,3,3,0,1,3],[0,1,2,3,3,3,0,2,1],[0,1,2,3,3,3,1,0,1],[0,1,3,1,2,3,3,3,3],[0,1,3,1,3,1,3,3,3],[0,1,3,1,3,2,1,3,3],[0,1,3,1,3,2,2,1,3],[0,1,3,1,3,2,2,2,1],[0,1,3,1,3,2,3,0,1],[0,1,3,1,3,3,0,1,3],[0,1,3,1,3,3,0,2,1],[0,1,3,1,3,3,1,0,1],[0,1,3,2,0,3,3,3,3],[0,1,3,2,1,1,3,3,3],[0,1,3,2,1,2,1,3,3],[0,1,3,2,1,2,2,1,3],[0,1,3,2,1,2,2,2,1],[0,1,3,2,1,2,3,0,1],[0,1,3,2,1,3,0,1,3],[0,1,3,2,1,3,0,2,1],[0,1,3,2,1,3,1,0,1],[0,1,3,2,2,0,1,3,3],[0,1,3,2,2,0,2,1,3],[0,1,3,2,2,0,2,2,1],[0,1,3,2,2,0,3,0,1],[0,1,3,2,2,1,0,1,3],[0,1,3,2,2,1,0,2,1],[0,1,3,2,2,1,1,0,1],[0,1,3,3,0,0,1,3,3],[0,1,3,3,0,0,2,1,3],[0,1,3,3,0,0,2,2,1],[0,1,3,3,0,0,3,0,1],[0,1,3,3,0,1,0,1,3],[0,1,3,3,0,1,0,2,1],[0,1,3,3,0,1,1,0,1],[0,2,0,3,2,3,3,3,3],[0,2,0,3,3,1,3,3,3],[0,2,0,3,3,2,1,3,3],[0,2,0,3,3,2,2,1,3],[0,2,0,3,3,2,2,2,1],[0,2,0,3,3,2,3,0,1],[0,2,0,3,3,3,0,1,3],[0,2,0,3,3,3,0,2,1],[0,2,0,3,3,3,1,0,1],[0,2,1,1,2,3,3,3,3],[0,2,1,1,3,1,3,3,3],[0,2,1,1,3,2,1,3,3],[0,2,1,1,3,2,2,1,3],[0,2,1,1,3,2,2,2,1],[0,2,1,1,3,2,3,0,1],[0,2,1,1,3,3,0,1,3],[0,2,1,1,3,3,0,2,1],[0,2,1,1,3,3,1,0,1],[0,2,1,2,0,3,3,3,3],[0,2,1,2,1,1,3,3,3],[0,2,1,2,1,2,1,3,3],[0,2,1,2,1,2,2,1,3],[0,2,1,2,1,2,2,2,1],[0,2,1,2,1,2,3,0,1],[0,2,1,2,1,3,0,1,3],[0,2,1,2,1,3,0,2,1],[0,2,1,2,1,3,1,0,1],[0,2,1,2,2,0,1,3,3],[0,2,1,2,2,0,2,1,3],[0,2,1,2,2,0,2,2,1],[0,2,1,2,2,0,3,0,1],[0,2,1,2,2,1,0,1,3],[0,2,1,2,2,1,0,2,1],[0,2,1,2,2,1,1,0,1],[0,2,1,3,0,0,1,3,3],[0,2,1,3,0,0,2,1,3],[0,2,1,3,0,0,2,2,1],[0,2,1,3,0,0,3,0,1],[0,2,1,3,0,1,0,1,3],[0,2,1,3,0,1,0,2,1],[0,2,1,3,0,1,1,0,1],[0,2,2,0,0,3,3,3,3],[0,2,2,0,1,1,3,3,3],[0,2,2,0,1,2,1,3,3],[0,2,2,0,1,2,2,1,3],[0,2,2,0,1,2,2,2,1],[0,2,2,0,1,2,3,0,1],[0,2,2,0,1,3,0,1,3],[0,2,2,0,1,3,0,2,1],[0,2,2,0,1,3,1,0,1],[0,2,2,0,2,0,1,3,3],[0,2,2,0,2,0,2,1,3],[0,2,2,0,2,0,2,2,1],[0,2,2,0,2,0,3,0,1],[0,2,2,0,2,1,0,1,3],[0,2,2,0,2,1,0,2,1],[0,2,2,0,2,1,1,0,1],[0,2,2,1,0,0,1,3,3],[0,2,2,1,0,0,2,1,3],[0,2,2,1,0,0,2,2,1],[0,2,2,1,0,0,3,0,1],[0,2,2,1,0,1,0,1,3],[0,2,2,1,0,1,0,2,1],[0,2,2,1,0,1,1,0,1],[0,3,0,0,0,3,3,3,3],[0,3,0,0,1,1,3,3,3],[0,3,0,0,1,2,1,3,3],[0,3,0,0,1,2,2,1,3],[0,3,0,0,1,2,2,2,1],[0,3,0,0,1,2,3,0,1],[0,3,0,0,1,3,0,1,3],[0,3,0,0,1,3,0,2,1],[0,3,0,0,1,3,1,0,1],[0,3,0,0,2,0,1,3,3],[0,3,0,0,2,0,2,1,3],[0,3,0,0,2,0,2,2,1],[0,3,0,0,2,0,3,0,1],[0,3,0,0,2,1,0,1,3],[0,3,0,0,2,1,0,2,1],[0,3,0,0,2,1,1,0,1],[0,3,0,1,0,0,1,3,3],[0,3,0,1,0,0,2,1,3],[0,3,0,1,0,0,2,2,1],[0,3,0,1,0,0,3,0,1],[0,3,0,1,0,1,0,1,3],[0,3,0,1,0,1,0,2,1],[0,3,0,1,0,1,1,0,1],[1,0,0,3,2,3,3,3,3],[1,0,0,3,3,1,3,3,3],[1,0,0,3,3,2,1,3,3],[1,0,0,3,3,2,2,1,3],[1,0,0,3,3,2,2,2,1],[1,0,0,3,3,2,3,0,1],[1,0,0,3,3,3,0,1,3],[1,0,0,3,3,3,0,2,1],[1,0,0,3,3,3,1,0,1],[1,0,1,1,2,3,3,3,3],[1,0,1,1,3,1,3,3,3],[1,0,1,1,3,2,1,3,3],[1,0,1,1,3,2,2,1,3],[1,0,1,1,3,2,2,2,1],[1,0,1,1,3,2,3,0,1],[1,0,1,1,3,3,0,1,3],[1,0,1,1,3,3,0,2,1],[1,0,1,1,3,3,1,0,1],[1,0,1,2,0,3,3,3,3],[1,0,1,2,1,1,3,3,3],[1,0,1,2,1,2,1,3,3],[1,0,1,2,1,2,2,1,3],[1,0,1,2,1,2,2,2,1],[1,0,1,2,1,2,3,0,1],[1,0,1,2,1,3,0,1,3],[1,0,1,2,1,3,0,2,1],[1,0,1,2,1,3,1,0,1],[1,0,1,2,2,0,1,3,3],[1,0,1,2,2,0,2,1,3],[1,0,1,2,2,0,2,2,1],[1,0,1,2,2,0,3,0,1],[1,0,1,2,2,1,0,1,3],[1,0,1,2,2,1,0,2,1],[1,0,1,2,2,1,1,0,1],[1,0,1,3,0,0,1,3,3],[1,0,1,3,0,0,2,1,3],[1,0,1,3,0,0,2,2,1],[1,0,1,3,0,0,3,0,1],[1,0,1,3,0,1,0,1,3],[1,0,1,3,0,1,0,2,1],[1,0,1,3,0,1,1,0,1],[1,0,2,0,0,3,3,3,3],[1,0,2,0,1,1,3,3,3],[1,0,2,0,1,2,1,3,3],[1,0,2,0,1,2,2,1,3],[1,0,2,0,1,2,2,2,1],[1,0,2,0,1,2,3,0,1],[1,0,2,0,1,3,0,1,3],[1,0,2,0,1,3,0,2,1],[1,0,2,0,1,3,1,0,1],[1,0,2,0,2,0,1,3,3],[1,0,2,0,2,0,2,1,3],[1,0,2,0,2,0,2,2,1],[1,0,2,0,2,0,3,0,1],[1,0,2,0,2,1,0,1,3],[1,0,2,0,2,1,0,2,1],[1,0,2,0,2,1,1,0,1],[1,0,2,1,0,0,1,3,3],[1,0,2,1,0,0,2,1,3],[1,0,2,1,0,0,2,2,1],[1,0,2,1,0,0,3,0,1],[1,0,2,1,0,1,0,1,3],[1,0,2,1,0,1,0,2,1],[1,0,2,1,0,1,1,0,1],[1,1,0,0,0,3,3,3,3],[1,1,0,0,1,1,3,3,3],[1,1,0,0,1,2,1,3,3],[1,1,0,0,1,2,2,1,3],[1,1,0,0,1,2,2,2,1],[1,1,0,0,1,2,3,0,1],[1,1,0,0,1,3,0,1,3],[1,1,0,0,1,3,0,2,1],[1,1,0,0,1,3,1,0,1],[1,1,0,0,2,0,1,3,3],[1,1,0,0,2,0,2,1,3],[1,1,0,0,2,0,2,2,1],[1,1,0,0,2,0,3,0,1],[1,1,0,0,2,1,0,1,3],[1,1,0,0,2,1,0,2,1],[1,1,0,0,2,1,1,0,1],[1,1,0,1,0,0,1,3,3],[1,1,0,1,0,0,2,1,3],[1,1,0,1,0,0,2,2,1],[1,1,0,1,0,0,3,0,1],[1,1,0,1,0,1,0,1,3],[1,1,0,1,0,1,0,2,1],[1,1,0,1,0,1,1,0,1]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
Żṗ‘}Ḅ=¥Ƈ
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//xbvhuZfigJh94biEPcKlxof/w6cixZLhuZjigqxZ//8xLDUsMSw3/zAsMCwxLDQ "Jelly – Try It Online")
Takes `c` on the left, `n` on the right
Brute-force approach. Generates all lists of length \$n+1\$ containing the numbers \$0\$ to \$c\$, meaning that it times out for \$n > 7\$ on TIO. For a *much* faster version, see the [revision history](https://codegolf.stackexchange.com/revisions/238103/1).
-2 bytes thanks partially to [a suggestion](https://chat.stackexchange.com/transcript/message/59797443#59797443) by [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)
## How it works
```
Żṗ‘}Ḅ=¥Ƈ - Main link. Takes c on the left, n on the right
Ż - Generate the range [0, ..., c]
} - To n:
‘ - Yield n+1, to account for n = 0
ṗ - Cartesian power. Yield all lists of length n+1 of the elements of [0, ..., c]
¥Ƈ - Keep those for which the following is true:
Ḅ - When converting from binary,
= - they equal n
```
[Answer]
# [R](https://www.r-project.org/), ~~97~~ ~~81~~ ~~78~~ ~~73~~ 68 bytes
Or **[R](https://www.r-project.org/)>=4.1, 61 bytes** by replacing the word `function` with `\`.
*-11 bytes and another -3 thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
*-5 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(n,c,g=t(expand.grid(rep(list(0:c),n+1))))g[,2^(n:0)%*%g==n]
```
[Try it online!](https://tio.run/##JYpRCsIwEET/ew0pbHQjSaxaCzmJKEjahEBZSxrB28dsnZ83j5lUvC3@Qy7HNwGhw2AzTN/lReMxpDhCmhaY45pBDU4gHbSoCXc0T6BBiXbfBmvpUTwo1KJhnBn6bx1eGRc8iWYnpeSlZ6k0qM1WOtRqO5tbncoP "R – Try It Online")
Brute-force solution.
Multiple vectors are output column-wise. Outputs additional leading zeros.
~~Deals with the `0` case in a rather ugly manner.~~ No `if` thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).
### Explanation
```
function(n,c, # a function taking n and c as arguments
g= # we use another argument to compute g
# - all combinations of digits 0..c of length n+1
t( # transpose (converts from data frame to matrix)
expand.grid( # all combinations of
rep( # repeat...
list(0:c), # ...a list of digits 0..c
# (list to repeat whole object not just append to vector) ...
n+1 # n+1 times (to handle 0 edge case)
))))
g[, # get all rows of g
# and columns where ...
2^(n:0) # ...powers of 2: 2^n to 2^0...
%*%g # ...matrix-multplied by g
# (the vector of powers is promoted to a column matrix)
# - this resuts in a row matrix of corresponding overflowed binary numbers - ...
==n] # ... equal input n
```
---
Longer but faster and without additional leading zeros:
### [R](https://www.r-project.org/), 93 bytes
Or **[R](https://www.r-project.org/)>=4.1, 86 bytes** by replacing the word `function` with `\`.
```
function(n,c,g=t(expand.grid(rep(list(0:c),b<-log2(n)%/%1+1))))"if"(n,g[,2^(b:1-1)%*%g==n],0)
```
[Try it online!](https://tio.run/##JYtRCsIwEET/PUYhsNGtZmNFLeYkomDTJgTKttQI3j6mcX7eDDOzJGeS@7CNYWJgtOhNhOE7v7jf@yX0sAwzjOEdQbVWYnerx8lrYCkOgnYks6rgqnz1d9RP6FqqSYqt8MbwA5VMDhSS3Kw4raB/avBc0gWPhRpJF9MgqTLQ11ylHw "R – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 26 24 bytes
```
]((=#.)#])((##:i.@^~)>:)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/YzU0bJX1NJVjNTU0lJWtMvUc4uo07aw0/2typSZn5CsYKqQpGICZ6uoQEVMMEZAaQxQRc6CIyX8A "J – Try It Online")
Brute force. In this case, the idea is simple -- just try all possible combos and filter the ones which match `n` -- but the J mechanics are kind of fun: The whole thing is fork, made up of nested forks and dyadic hooks:
[](https://i.stack.imgur.com/iHOpo.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Cases[FrobeniusSolve[2^Range[#,0,-1],#],s_/;s#2]&
```
[Try it online!](https://tio.run/##LYlBCsIwEAC/srDQ0xabqCiIEhA8ix5DlCipBmwKTfQS8gd/47N8QmyLp5lhGh3uptHBXnWuYZ232hsvd117Mc4@/bF9vIzkp4N2NyORKiqZIlTkz5OV/74/yFWR9511QUbEBOUGaomoFBQghIAYKwKWCAbOB7J/zwgWYy8JpqPw/vDR@seqlPIP "Wolfram Language (Mathematica) – Try It Online")
-3 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
IΦE↨↨⊕θ²⊕η↨ι⊕η⁼Iθ↨ι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SMM3sUDDKbE4FUJ45iUXpeam5pWkpmgUauooGAExsliGJlAArDITQwIo41pYmphTDDG/EEmlkSYIWP//b6Jg/l@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Output removes all leading zeros even for an output of zero (which is simply empty). Uses brute force but easily manages the last test case on TIO. Explanation:
```
θ First input `n`
⊕ Incremented
↨ Converted to base
² Literal `2`
↨ Interpreted as base
η Second input `c`
⊕ Incremented
E Map over implicit range
ι Current value
↨ Converted to base
η Second input `c`
⊕ Incremented
Φ Filtered where
ι Current base `c+1` value
↨ Interpreted as base
² Literal `2`
⁼ Equals
θ First input `n`
I Cast to integer
I Cast to string
Implicitly print
```
Technically it would be more efficient to convert `n` into base `2` and from base `c+1` first before incrementing but this is code golf.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 92 bytes
```
f=lambda n,a,*i:n and f(n//2,a,n%2,*i)+(()<i<(a-1,)and f(n-1,a,i[0]+2,*i[1:])or[])or[[0,*i]]
```
[Try it online!](https://tio.run/##jZjbbts4EIbv/RSCgQWklttyhoqbDeq36F3WCFzERgU4ktcRdrF@@SwlkcM56GJRpKE/8/CNf9FT9Prv@Gvow@P19vFx3l@Obz9fj1Xvju5T99RXx/61Otf9168YSf8bRtp8ruvme/e9Pv4OrkkT4vDoumd/@DxNeYanQzPcnue/nn0kh8PHj/12u/VVVUH8ifRw2EyvHugV0HsQX7Vx9G15z3nXHlz8DQ7n3@h8/A2Rz@seqyrQzBDfXWZN4zDPnFYC8WlceNyLOMYfn08gPo2hnJj4MobFAKM5ZoNIs0A8yqchukey2qVRm@ry7oGcd2Tm04rJd0eG@ZMIZN0y5zaNyieF6d0wf1rZu00joFryZ0qfagwAfK4JSyGBCmmpkAcqZEeFfGOFQEnhkSrZUSUtVZJremA17aimlmrK1QVWHaYRz2pHdbZUZ644sIoxjZY8W/yDniiYT8H5WYp/yD7MJ1mGC1VspoZFqthUh2QzUWvDkohiwNYGxgNj2nl5LZ0z486FoThDO@f9vVkrnTOTzpjuLHfBdF81084Lk86ZoTgDjPOylzdrtTMmc7l2@X6QLrisXGFo1gazHxiXhaGZJ11C@k7iLguTLpmhWRvMftolMzTzigum72GeZc4WVhjPsrDizBmKM@TzV54fb9byLAvjzmDuTH72YIVJZzB3hjMUZ2hnMHeGMzTzpLO@M/luwArTzvrOcIbiDDDO@s5whmaedpZ3pjDtIu9MYcHsB8ZF3pnCpIu@M4VJF31nCgtmP@2i70xh3AWdN1mi8ybLhcksM@POhaE4Q2eZs/BmrcwyM@2ss8xMu@gsMwtmPzAuOsvMpAuYLDOTLmCyzCyY/bQLmCwzKy4h/TuRZ5mfM1hhPMvCijNnKM6QWZZn2Zu1PMvCtLPMsjDtIrMsLJj9wLjILAuTLjrLwqSLzrKwYPbTLjrLwrJL3on3BaBsYYWVLDnLzpKhOIP3BWDPjzdrS5accWfdy4CePVhh0ln3MslQnKGddS@TDM086Sx7GdDdgBWmnWUvkwzFGWCcZS@TDM087czvDGfahd8ZzoLZD4wLvzOcSRfZyziTLrKXcRbMftpF9jLOuIvuZUDfLbDCZJa6l0mG4gydpe5lkqGZp511lrqXSYZmbTD7gXHRWepeBjRHu4DJUvcyzoLZT7uAyRLN9x@YXgbkBiuMZwmml0mG4gyZJZheJhmaedpZZgmml0mGZm0w@4FxkVmC6WVAn7F20VmC6WWcBbOfdtFZguplh@12@@X9eunGevtnv202m/NteKu68XQbh@HyXnVv1@E2Vq@34frPr@5y2pyH2/wfgUPV9VU9psXNhMcJ/WieNsuE/dvxWp/@Pl5cPb9umk1135@nF9Povn@PO59e62napXsf3TSgg9zl1Nf35lPtqy8vL6e/Xl5c4@7NtMkw/I@lg1o6zEuvt64fF51hv7/fm4//AA "Python 3.8 (pre-release) – Try It Online")
Straight-forward recursion.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `RM`, 7 bytes
```
›ÞẊ'B¹=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSTSIsIiIsIuKAusOe4bqKJ0LCuT0iLCIiLCI0XG4zIl0=)
The `R` flag automatically converts ranges to digits. The `M` flag changes the default range from 1...n to 0...n.
```
›ÞẊ # Cartesian power - 0...c combinations to length n
' # Filtered by...
B # Binary
= # Equal to
¹ # n?
```
Luckily, Vyxal has the same ~~bug~~ feature as Jelly of automatically converting overflowed binary.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 80 bytes
```
c=>g=(n,t,i=c-(c+n&1))=>n?n*i<0?[]:g(n-i>>1,t?i+[,t]:[i])+g(n,t,i-2):print(t||0)
```
[Try it online!](https://tio.run/##jY/RboQgEEXf@xU8NVDRZdCmXbfqhxAeNlYN7RaNkiZN9t/tgFv3SdMQMsPNuTOXj/P3eapHM7h4Gsx7M3719rP5mdtirouyK6jljpuijmkd2UdgrChtZZ/Mm6iUzjtqY1OWwF1lIsWdzpXRLOoWVyxZPozGOuquV8HmlgJhVBDCTqTu7dRfmuTSdxSfhwNRSmj90NLnfzB@DmwyEJgXZLLtOVzwTHOswGWokgusgPqyI/U7Xvf8KXoWr@/T4PfzYNV9f9dxw6pLvOJv76r7Hu45bvrSwy0XSMwl93Ihi7YkSQIuEM/2cIwiVtz/OpPHTdwnT8MNZ/HNvw "JavaScript (SpiderMonkey) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
```
c=>g=(n,t=[],i=c-(c+n&1))=>n?n*i<0?[]:[...g(n-i>>1,[i,...t]),...g(n,t,i-2)]:[t]
```
[Try it online!](https://tio.run/##hZDNboMwEITveQqfIrtZwGuo@mvyIJYPkZMgV5GJgtXXp2toCYhIFbJ2GX0zHvg6fB86d/PXmIX2eOrPune6bjQPELWx4LXLuNuFLQqh67APT/5T7o19N3meNzxkvq4RjAd6jVbAqEIEnylBVLS9a0PXXk75pW34mSMTXDImxAcrCmaMtHazJJ7/JVIGzghcES9EVPMMkFBZoImghqlA0kTS1/llyn9duktyjM60l4M7peGkp/2uU/6kKzry79ZJTzveW/zq444PWqGiVmrZikgy0U9fwZLgaglTDfkQTt9bqbcZnDqXwxme0dX/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
Ýsãʒ2βQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Nziw4tPTTI6tynw/39jLnMA "05AB1E – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 84 bytes
Expects `(c)(n)` and prints all solutions as space-separated strings.
```
c=>g=(n,j,o,h=i=>~i&&g(n-(i<<j),-~j,i+' '+[o])|h(i-1))=>(n>>j)>0?h(c):n||print(o||0)
```
[Try it online!](https://tio.run/##Vc/BbsIwDAbge5/Chwls4U4NYxoMkp32FFEkqkilycFFBXEh5dW7aNXW7WDp/@T/YMf6Vl98H87X8rYdGz16bU4ahSN33OqgzSMsFieUEsPhEInLR@SwWsJyZTtHqcVQKiJtUIyJZKqPFj29S0rnPsgVu5QqGve2ALAAUDGAAsd/@DpT/d9uMt9@qbaZLzPXnGdmLqvqh5v1bioXrnhuuv6z9i2iFQbvCLSBO0znHS0IaHi6y5B338kP4I60hyb/gZLD1MxhoPEL "JavaScript (V8) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ 79 bytes
```
f=lambda a,b:[[]][a:]or[d+[i]for i in range(a,-1,-2)for d in(i<=b)*f(a-i>>1,b)]
```
[Try it online!](https://tio.run/##bZbbbptAEIavzVOs1IvglFQ7s8RNrTp9EMQFlnGL6tgWcVK1L58uh92dA6oiw8cevvHPenr9e/t1ObuPj@Pu1LzsD41piv22quq6arb1pa8On6uuPl5605nubPrm/LPNm@IBigdcD/jgcd593@3X98e8eeien6HYr@uPT6ZvXy7vrTm1zaE7/zT/2v7SvmaH9mj6F5uf1tts1ZmdsdlqWKcdlj95tuqOpn22233fNr@H2887yFZ9e3vr/YCq29ZZ9udXd2oN@NH3XXHxi7w017x9b05Fd76@3fL1l9frqfOf62w1PK6GHQ/R11zqbHXtu/Mtv3u@K8x9N4x7u/mRx3y8mR/u/EPPE/jhweulv7WHfOC7XbhZxzHrD2uMAf9XVbaus@HuMd5BfAb@rvRXX6dnhS3KuvCfUOD4iYX1n@D5OO/JGBdHOv90GjVcu3HkMBMiH64T92tFjv7Phh0iH64h7Tjz6RomA/TmGAw8DQJ@KztfYvEUrTbzVTnXZYvH6LyJZnaeMfhuomH4Jly0LolzOV@lbwrnp278toJ3OV9BrCV8p/Fb9QGADTVhKsTFQspYyGMsZBML@UoKgZTCU6xkEyspYyWhpkdS0ybWVMaaQnWOVIfzFc1qE@ssY52hYkcqxvlqyrPEb/GNgnEXHN8l/y/au3EnzXCigo1UMU8FG@rgbCRirpsSEQzIXEe4I0w6T/fcOTDqnBiyPaRzWN@qudw5MO6M85mlLjifV8mk88S4c2DI9gDlPK1l1VzpjLM5nzv9PnAXnGYuMFRznVoPlMvEUI3jLm7@TaIuE@MugaGa69R60iUwVOOSC86/wzTLkC0sMJplYsmZMmR78PcvvT9WzaVZJkadQZ2Z8O7BAuPOoM4MZcj2kM6gzgxlqMZxZ3lmwtmABSad5ZmhDNkeoJzlmaEM1TjpzM9MYtKFn5nEnFoPlAs/M4lxF3lmEuMu8swk5tR60kWemcSoCxZWZYmFVVlOjGcZGHVODNkeMsuQhVVzeZaBSWeZZWDSRWYZmFPrgXKRWQbGXUBlGRh3AZVlYE6tJ11AZRlYcnHz/xNpluE9gwVGs0wsOVOGbA@eZXqXrZpLs0xMOvMsE5MuPMvEnFoPlAvPMjHuIrNMjLvILBNzaj3pIrNMLLiElWhfgJgtLLCUJWXBmTNke9C@AOT9sWpuypIy6ix7GcR3DxYYd5a9jDNke0hn2cs4QzWOO/NeBvFswAKTzryXcYZsD1DOvJdxhmqcdKZnhjLpQs8MZU6tB8qFnhnKuAvvZZRxF97LKHNqPenCexll1EX2Moi/LbDAeJayl3GGbA@ZpexlnKEaJ51llrKXcYZqrlPrgXKRWcpeBnGMdAGVpexllDm1nnQBlSWq3z9QvQyiGywwmiWoXsYZsj14lqB6GWeoxklnniWoXsYZqrlOrQfKhWcJqpdB/I6li8wSVC@jzKn1pIvMEkQvq7P/ "Python 3 – Try It Online")
Outputs without leading zeroes.
] |
[Question]
[
## Background
[Slowsort](https://en.wikipedia.org/wiki/Slowsort) is an in-place, stable sorting algorithm that has worse-than-polynomial time complexity. The pseudocode for Slowsort looks like this:
```
procedure slowsort(A[], i, j) // Sort array range A[i ... j] in-place.
if i ≥ j then
return
m := floor( (i+j)/2 )
slowsort(A, i, m) // (1.1)
slowsort(A, m+1, j) // (1.2)
if A[j] < A[m] then
swap A[j] , A[m] // (1.3)
slowsort(A, i, j-1) // (2)
```
* (1.1) Sort the first half, recursively.
* (1.2) Sort the second half, recursively.
* (1.3) Find the maximum of the whole array by comparing the results of 1.1 and 1.2, and place it at the end of the list.
* (2) Sort the entire list (except for the maximum now at the end), recursively.
The recurrence relation of the worst-case time complexity (the number of swaps when the condition for (1.3) is always true1) is:
$$
\begin{alignat}{5}
T(1) &= 0 \\
T(n) &= T\left(\left\lfloor\frac{n}{2}\right\rfloor\right) + T\left(\left\lceil\frac{n}{2}\right\rceil\right) + 1 + T(n-1)
\end{alignat}
$$
The first 50 terms of the sequence are:
```
0, 1, 3, 6, 11, 18, 28, 41, 59, 82,
112, 149, 196, 253, 323, 406, 507, 626, 768, 933,
1128, 1353, 1615, 1914, 2260, 2653, 3103, 3610, 4187, 4834,
5564, 6377, 7291, 8306, 9440, 10693, 12088, 13625, 15327, 17194,
19256, 21513, 23995, 26702, 29671, 32902, 36432, 40261, 44436, 48957
```
This sequence seems to coincide with [A178855](https://oeis.org/A178855).
A proof by @loopy wait (which gives rise to multiple alternative formulas):
>
> Proof: start with [A033485](https://oeis.org/A033485) (`a(n) = a(n-1) + a(floor(n/2)), a(1) = 1`) and verify that `a(2n+1)-a(2n-1)=2a(n)` (because `a(2n+1) = a(2n) + a(n) = a(2n-1) + 2a(n)`). Also verify that if `n` is even `2a(n)=a(n-1)+a(n+1)`. If we substitute `b(n)=a(2n-1)` we get `b(n)-b(n-1)=b(floor(n/2))+b(ceil(n/2))` which is already similar to T. If we now set `2T+1=b` we get back the recurrence defining `T`. As the initial terms also match this shows that `T(n)=((A033485(2n-1)-1)/2` which (shifted by one) is also given as a formula for A178855.
>
>
>
## Challenge
Evaluate the sequence \$T(n)\$. [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") default I/O applies; you can choose one of the following:
* Without input, output the entire sequence \$T(1), T(2), T(3), \cdots\$ infinitely
* Given \$n > 0\$, output \$T(n)\$ (corresponding to \$n\$th value under 1-indexing)
* Given \$n \ge 0\$, output \$T(n+1)\$ (corresponding to \$n\$th value under 0-indexing)
* Given \$n > 0\$, output the first \$n\$ terms, i.e. \$T(1), T(2), \cdots, T(n)\$
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
---
1 Don't ask me how, I don't know if it can actually happen.
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
-6 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).
```
a=s 0b
b=s 1$b<*" "
s=scanl(+)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P9G2WMEgiSsJSBmqJNloKSkoKHEV2xYnJ@blaGhr/s9NzMxTsFUoKMrMK1FQUShJzE5VMDJQSPwPAA "Haskell – Try It Online")
[A178855](https://oeis.org/A178855) is the cumsum of [A033485](https://oeis.org/A033485), while A033485 is the cumsum of `1, a(1), a(1), a(2), a(2), a(3), a(3), ...`, where `a` is A033485 itself.
[Answer]
# JavaScript (ES6), 31 bytes
Returns the \$n\$-th term, 0-indexed.
```
f=n=>n&&f(n>>1)+f(--n>>1)-~f(n)
```
[Try it online!](https://tio.run/##HYpBDkAwEADvfcWepM1mBVfavwgqRHYFcRG@vtRpJpOZ27Pdu21aD2LpB9Xo2QfOsmg5hNJhtES/0fMlp1E2y@ChqIGhgSoR0cFlADrhXZYhX2S0mG5Xm1tf "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
∫Θ¡§+→ȯ→←½;1
```
[Try it online!](https://tio.run/##yygtzv7//1HH6nMzDi08tFz7UdukE@uBxKO2CYf2Whv@/w8A "Husk – Try It Online")
Uses the idea of the Haskell answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 34 bytes
```
f(n){n=n?f(n/2)+f(--n/2)-~f(n):0;}
```
[Try it online!](https://tio.run/##VVHbTuswEHznK1aVkBKaCHt9SUzo4eGIr6B9qFIHKiBFTSSqU5VPP2E2tAUieTU7mdmLXeePdT0MTdKm@3bW3gFcczptkjwXkH/InxtVHYZ129Prct0mKe0vCJ8QcfcW6z6uHhY0o73KSGdkMvIAQLrMiHEssAsZlSy8BItMB8jYQW4YwSqkThVwM1DhYQzGjA5AbUSpvXbi1BZW9mjIfqyglUSvlXQrUcSWBhrnPKI3BZiCA@YojfQJ1sqwygcpyqocO3iW4s4w1LrQwUordjKmdhpKNiE46VkobMHBF7IvB8mMt4ZlDfYgrbXGyxTBFYdqvK9603Y91U/L7RVirJ/j9uvaJvPdPc934S@Om2T0MzeTo7vZbCmRK1@3q7iDTVVHeEvd@l/cNMnpMdLrI3F1ZiqaTkf16fFOD9ij0vij@kV3oJukT3@zEez5xUfX4lvwtoWkSSaXK8r/EOJlN2@xTZ9Rl50X7mazuDiWPVwchv9187J87Ib8/RM "C (gcc) – Try It Online")
Returns the \$0\$-indexed \$n^\text{th}\$ term.
Uses given formula.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
λN<2÷₅+}.¥
```
-4 bytes porting [*@alephalpha*'s Haskell answer](https://codegolf.stackexchange.com/a/237804/52210) and combining it with [*@ovs*' 05AB1E approach](https://codegolf.stackexchange.com/a/237810/52210) of using `n-1`, so make sure to upvote both of them as well!
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//3G4/G6PD2x81tWrX6h1a@v8/AA)
**Explanation:**
```
λ # Start a recursive environment,
# to output the infinite sequence
# Starting at a(0)=1 implicitly
# Where every following a(n) is calculated by:
N< # Push n-1
2÷ # Integer-divide it by 2
₅ # Pop and push a((n-1)//2)
+ # Add it to the implicit previous item: a(n-1)+a((n-1)//2)
} # After the recursive environment
.¥ # Prepend 0 and get the cumulative sum of this list
# (after which the infinite sequence is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 15 bytes
```
HḞ,ĊƊ;’߀S‘µ0’?
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJI4bieLMSKxoo74oCZw5/igqxT4oCYwrUw4oCZPyIsIiIsIiIsWyIxMCJdXQ==)
I don't think this is close to optimal.
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal), ~~19~~ ~~18~~ 17 bytes
```
λċ[½₌⌈⌊x$xn‹xṠ›|0
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%C4%8B%5B%C2%BD%E2%82%8C%E2%8C%88%E2%8C%8Ax%24xn%E2%80%B9x%E1%B9%A0%E2%80%BA%7C0&inputs=4&header=&footer=)
Of course just as I decided to make `Ṡ` no longer sum the stack, an edge case where it's needed pops up.
## Explained
```
λċ[½₌⌈⌊x$xn‹xṠ›|0
λ # Start a monadic lambda taking argument n that:
ċ[ # if n != 1:
½₌⌈⌊ # push the ceiling and floor of (n / 2)
x$x # and call this lambda on both
n‹x # then call this lambda on n - 1
Ṡ› # finally, push the sum of the stack + 1
| # else:
0 # return 0
# The lambda is automatically called on end of execution
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
Implements the recurrence relation
```
0λND<‚;ï₅O+>
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f4NxuPxebRw2zrA@vf9TU6q9t9/8/AA "05AB1E – Try It Online")
[Answer]
# Python 3, 42 bytes:
```
f=lambda n:n and-~f(n//2)+f(~-n//2)+f(n-1)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
.+
$*
+`1(1*)(1*\1)
$1$2¶$1¶$2
¶¶
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLO8FQw1BLE4hjDDW5VAxVjA5tUzEEYiOuQ9sObfv/38QSAA "Retina 0.8.2 – Try It Online") Outputs the 0-indexed `n`th value. Explanation: Uses the recurrence relation given in the question.
```
.+
$*
```
Convert to unary.
```
+`1(1*)(1*\1)
```
Find the floor and ceiling of half of `n`.
```
$1$2¶$1¶$2
```
Replace `n` with `n-1` and the above two values. This introduces two extra lines for each recurrence.
```
¶¶
```
Count half of the number of extra lines, which represents the number of `1`s summed as part of the recurrence.
[Answer]
# [Rust](https://www.rust-lang.org/), 56 bytes
```
fn f(n:i32)->i32{if n>0{f(n/2)-!f(!-n/2)+f(n-1)}else{0}}
```
[Try it online!](https://tio.run/##RU/LbtswELzrK9a5hEJpl1w@JCpoDv2E9gMCJaYKITKtkBRaQNC3u0vXcQ8kh7OzM7txSfmyJA8pH7tuPHfd92X44fvjU3UZAgwsdKPCev9M9zoOEJ7FSuRXonYD2@0L@kLEXtabn5JfxbaVxlM/BlbDWgEM5whs5P7P7N@yP9Ywhv9pBIrwMJ3f3ulJ8zRm9vrIH@uDD8vJxz77mw/A5DN82nRAE8E3@JnjGH513RDPp5clDy37VByW8Dv2M6vrOzqQ@ETP3MdEtnf@6W4ffVqmTL4DG6FPJeRWnSknT2HHHtbtgd@Et1qfko/5xX/s2D@e3@e8KrZqqy6Cg@SgOFgChGTLAelowsZxaJFXUiIVNP2kIxkakiukSwv6GtFQNxJqLDU6pa4dBKUqSmmlKZ1SUytaCkR7dZCi3FaKktaSiW6V5pUxlpRWNcQ06GiOVpUcp3UZVlhXTFG01wSLxdwoJLVspCMD6dCUMaWRpETlnCmZjaAt0Nmm7Iuu/JTVCssaaInUWitbpnCm@Qs "Rust – Try It Online")
Returns the \$n\$-th term, 0-indexed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
FN⊞υ∨¬υ⁺⌈υ§υ⊘⊖LυI↨¹υ
```
[Try it online!](https://tio.run/##JYw7DsIwEER7TuFyLZkCiQal4lMQCYKvYJyFRPIHrXej3N4kMNXozdP4wZHPLtT6yqSgTR/hTuITCbRWVsoAYtSDoMsMoo2yQQrc3TxGiT9w5Db1OK/a1YUJe7igJ4yYeOk3TG9ePvQ/zcbSmBjOrjCcXEHYGbWOTa37Q91O4Qs "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 0-indexed `n`th value. Explanation:
```
FN
```
Input `n` and loop that many times.
```
⊞υ∨¬υ⁺⌈υ§υ⊘⊖Lυ
```
Generate the next term of `A033485`, or `1` if there are no terms yet. (Annoyingly the formula for this sequence assumes 1-indexing.)
```
I↨¹υ
```
Sum the terms (using base `1` in case there are none).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~38 ...~~ 35 bytes
```
f=->n{n<2?n:f[n/2]-~f[n-=1]+f[n/2]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/GyD7PKi06T98oVrcOSOvaGsZqQ/i1/wsUNAz09AwNNPVyEws01NI0/wMA "Ruby – Try It Online")
Recursive version, as a function, returns nth value.
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
*r=a=b=c=0;loop{p c;a,b,*r=r+=[c+=a-~b]*4}
```
[Try it online!](https://tio.run/##KypNqvz/X6vINtE2yTbZ1sA6Jz@/oLpAIdk6USdJByhepG0bnaxtm6hblxSrZVL7/z8A "Ruby – Try It Online")
Non-recursive version, faster, prints whole list.
] |
[Question]
[
### Input:
Two integers: one negative, one positive.
### Output:
On the first line output lowest to highest. On the second line we've removed the highest and lowest numbers and [sign-changed](https://en.wikipedia.org/wiki/Additive_inverse) all individual numbers. On the third line we've removed the highest and lowest numbers again and sign-changed all individual numbers again. etc. (The example below should make the challenge clearer.)
**Important:** In addition, we add spaces so the numbers in a column are all aligned (to the right).
The minimal alignment is the *main* part of this challenge, this means that you can't just make every single number the same width. The width of a column is based on the largest number-width of that specific column (and the sequence with sign-change is to give the numbers some variety in width per column).
---
**For example:**
```
Input: -3,6
Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6 // sequence from lowest to highest
2, 1, 0,-1,-2,-3,-4,-5 // -3 and 6 removed; then all signs changed
-1, 0, 1, 2, 3, 4 // 2 and -5 removed; then all signs changed again
0,-1,-2,-3 // -1 and 4 removed; then all signs changed again
1, 2 // 0 and -3 removed; then all signs changed again
// only two numbers left, so we're done
```
As you can see above, spaces are added at the positive numbers, when they share a column with negative numbers to compensate for the `-` (the same would apply to 2-digit numbers).
### Challenge rules:
* Input must be two integers
+ You can assume these integers are in the `-99`-`99` (inclusive) range.
+ The first integer will be negative, and the other will be positive.
* Output can be in any reasonable format, as long as it's clear there are rows and rightly aligned columns: I.e. STDOUT; returning as String with newlines; returning as list of Strings; etc. Your call.
* The output must also contain a delimiter of your own choice (except for spaces, tabs, new-lines, digits or `-`): I.e. `,`; and `;` and `|`; and `X`; etc. are all acceptable delimiters.
* The output lines may not contain a leading or trailing delimiter.
* The output may contain ONE trailing new-line, and any line may contain any number of trailing spaces.
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
### Test cases:
```
Input: -3,6
Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6
2, 1, 0,-1,-2,-3,-4,-5
-1, 0, 1, 2, 3, 4
0,-1,-2,-3
1, 2
Input: -1,1
Output:
-1,0,1
0
Input: -2,8
Output:
-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
1, 0,-1,-2,-3,-4,-5,-6,-7
0, 1, 2, 3, 4, 5, 6
-1,-2,-3,-4,-5
2, 3, 4
-3
Input: -15,8
Output:
-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
-13,-12,-11,-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5
-11,-10, -9, -8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3
-9, -8, -7, -6, -5, -4,-3,-2,-1, 0, 1, 2
8, 7, 6, 5, 4, 3, 2, 1, 0,-1
-7, -6, -5, -4, -3, -2,-1, 0
6, 5, 4, 3, 2, 1
-5, -4, -3, -2
4, 3
Input: -3,15
Output:
-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14,15
2, 1, 0,-1,-2,-3,-4,-5, -6,-7, -8, -9,-10,-11,-12,-13,-14
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
0,-1,-2,-3,-4,-5,-6,-7, -8,-9,-10,-11,-12
1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11
-2,-3,-4,-5,-6,-7,-8,-9,-10
3, 4, 5, 6, 7, 8, 9
-4,-5,-6,-7,-8
5, 6, 7
-6
Input: -12,12
Output:
-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12
11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11
-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10
9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9
-8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8
7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
-6, -5, -4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5
-4, -3, -2,-1, 0, 1, 2, 3, 4
3, 2, 1, 0,-1,-2,-3
-2, -1, 0, 1, 2
1, 0, -1
0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ ~~24~~ 20 bytes
```
rµḊṖNµÐĿZbȷG€Ỵ€Zj€”,
```
This is a dyadic link that returns an array of rows.
[Try it online!](https://tio.run/nexus/jelly#@190aOvDHV0Pd07zO7T18IQj@6OSTmx3f9S05uHuLUAyKgtIPGqYq/P/8PJIhYc7tj9qmKPgnJiTo1CSkaqQmJRflqqQk5mXrZCYl6JQnFqQWJRYkgqWK8ovL1bILFEoSi0pLcorVkiqBClMTUtNTSnW@/9f19D0vwUA "Jelly – TIO Nexus")
### How it works
```
rµḊṖNµÐĿZbȷG€Ỵ€Zj€”, Dyadic link. Arguments: a, b
r Range; yield [a, ..., b].
µ µÐĿ Apply the enclosed chain until the results are no longer
unique. Return the array of results.
Ḋ Dequeue; remove the first item.
Ṗ Pop; remove the last item.
N Negate; multiply all remaining integers by -1.
Z Zip; transpose rows and columns.
bȷ Base 1000; map each n to [n].
G€ Grid each; in each row, pad all integers to the same length,
separating the (singleton) rows by linefeeds.
Ỵ€ Split each result at linefeeds.
Z Zip to restore the original layout.
j€”, Join each row, separating by commata.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 59 bytes
Once again I'm screwed over by the same bug I wrote a fix for months ago but never pushed...
Golfing should still be possible though.
```
Ÿ[Ðg1‹#ˆ¦(¨]\\¯vy€g}})J.Bvyð0:S})øvyZs\})U¯vyvyXNèyg-ú}',ý,
```
[Try it online!](https://tio.run/nexus/05ab1e#@390R/ThCemGjxp2Kp9uO7RM49CK2JiYQ@vLKh81rUmvrdX00nMqqzy8wcAquFbz8I6yyqjimFrNUJCCssoIv8MrKtN1D@@qVdc5vFfn/39dYy5DUwA "05AB1E – TIO Nexus")
[Answer]
# Java 8, ~~483~~ ~~480~~ ~~486~~† 467 bytes
```
(a,b)->{int f=0,l=b-a+3,z[][]=new int[l][l],y[]=new int[l],i,j,k=0;for(;b-a>=0;k++,a++,b--,f^=1)for(j=0,i=a;i<=b;i++)z[k][j++]=f<1?i:-i;String r="",s;for(i=0;i<l;y[i++]=k)for(j=0,k=1;j<l;k=f>k?f:k)f=(r+z[j++][i]).length();for(i=0;i<l;i++){k=z[i][0];if(i>0&&k==z[i][1]&k==z[i-1][2])break;for(j=0;j<l;){k=z[i][j];s="";for(f=(s+k).length();f++<y[j];s+=" ");f=z[i][++j];if(k==f){r+=(i>0&&z[i-1][1]==z[i][1]?s+0:"")+"\n";j=l;}else r+=s+k+(f==z[i][j+1]?"":",");}}return r;}
```
**†** *Bytes raised due to bug-fix..*
Ok, this took *A LOT* more time (and bytes) than I thought (in Java that is..). This can definitely be golfed some more, probably by using a completely different approach instead of creating an NxN grid-array to fill and then 'strip out' the zeros (with an annoying edge case for the test-case of `-1,1`, as well as `-12,12`).
[Try it online.](https://tio.run/##jZLBbuMgEIbvfYoRh8oIHJlUXa1CSJ6gveyRZSXs2l2MSypwWiWRnz07dqxoe1hlJRth/n/@b2SmtR82b1/8uepsSvBkXTjdAbjQ17GxVQ3P4yfAjz668ApVhgpYPq4llSgNd7ik3vaugmcIoOCcWV7SfHMaTY0qeKfK3LIHftRGGxXqzzFedwYffvhywh1vuVeFbHYxk1i1wb1njFt8yzznzS8l6Ci2mOuUlW6tSukYo0ftjW4ZM6pZi61b5U7OPUdFCE9TpMM4t@7kQbvR6a9RXgnZouBVs/HbZoWKyiI7TonaGbro6vDa/87ol5wRfPLqiA5dGOmazG2K@3uvLkfCzNtcGL00tIy19XJmTrxrdWtkwj4nEdGJ@b@RjK0Pk4UpAgQPLkWMtRMUIQ09RaYu@BkozLWNbWLFihDKyM9AZKs6OdRdqgFLkMSQOHfB0EvIinCEDEOs@30MEOVwluM1v@/LDq95vu2PnXuBNxyY7PKjtQFL52k5pL5@W@z2/eIdpb4LWVhUWf7A4RudxubfHsFB3PIsOXy/mfP4HyZsSDzeTEKcWNJ53IfzHw)
**Explanation:**
```
(a,b)->{ // Method with two integer parameters and String return-type
int f=0, // Flag-integer, starting at 0
l=b-a+3, // Size of the NxN matrix,
// plus two additional zeros (so we won't go OutOfBounds)
z[][]=new int[l][l],
// Integer-matrix (default filled with zeros)
y[] = new int[l],
// Temp integer-array to store the largest length per column
i,j,k=0; // Index-integers
for(;b-a>=0 // Loop as long as `b-a` is not negative yet
; // After every iteration:
k++, // Increase `k` by 1
a++, // Increase `a` by 1
b--, // Decrease `b` by 1
f^=1) // Toggle the flag-integer `f` (0→1 or 1→0)
for(j=0,i=a;i<=b;i++)
// Inner loop `i` in the range [`a`, `b`]
z[k][j++]=// Set all the values in the matrix to:
f<1? // If the flag is 0:
i // Simply use `i`
: // Else (flag is 1):
-i; // Use the negative form of `i` instead
String r="", // The return-String
s; // Temp-String used for the spaces
for(i=0;i<l; // Loop `i` over the rows of the matrix
;y[i++]=k)// After every iteration: Set the max column-width
for(j=0,k=1;j<l;
// Inner loop `j` over the cells of each row
k=f>k?f:k)
// After every iteration: Set `k` to the highest of `k` and `f`
f=(r+z[j++][i]).length();
// Determine current number's width
// (NOTE: `f` is no longer the flag, so we re-use it as temp value)
for(i=0;i<l;i++){
// Loop `i` over the rows of the matrix again
k=z[i][0]; // Set `k` to the first number of this row
if(i>0 // If this isn't the first row
&&k==z[i][1]&k==z[i-1][2])
// and the first number of this row, second number of this row,
// AND third number of the previous row all equal (all three are 0)
break; // Stop loop `i`
for(j=0;j<l;){
// Inner loop `j` over the cells of each row
k=z[i][j];// Set `k` to the number of the current cell
s=""; // Make String `s` empty again
for(f=(s+k).length();f++<y[j];s+=" ");
// Append the correct amount of spaces to `s`,
// based on the maximum width of this column, and the current number
f=z[i][++j];
// Go to the next cell, and set `f` to it's value
if(k==f){ // If the current number `k` equals the next number `f` (both are 0)
r+= // Append result-String `r` with:
(i>0 // If this isn't the first row
&&z[i-1][1]==z[i][1]?
// and the second number of this and the previous rows
// are the same (both are 0):
s+0 // Append the appropriate amount of spaces and a '0'
: // Else:
"") // Leave `r` the same
+"\n";// And append a new-line
j=l;} // And then stop the inner loop `j`
else // Else:
r+=s // Append result-String `r` with the appropriate amount of spaces
+k // and the number
+(f==z[i][j+1]?"":",");}}
// and a comma if it's not the last number of the row
return r;} // Return the result `r`
```
[Answer]
# Javascript (ES6), 269 bytes
```
(a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`
```
### Explained:
```
( // begin arrow function
a,b, // input
d=~a+b+2, // distance from a to b
o=Array(~~(d/2)+1) // create an outer array of
// (distance divided by 2
// floored + 1) length
.fill( // fill each outer element
// with the following:
[...Array(d)] // create inner array of the
// distance length and
// fill with undefined
.map(_=>a++) // map each inner element
// iterating from a to b
)
.map( // map outer array
(e,i)=>e.slice(i,-i||a.a) // remove n elements from each end
// of the inner array corresponding
// to the outer index with a special
// case of changing 0 to undefined
)
.map( // map outer array
(e,i)=>i%2==0?e:e.map(e=>e*-1) // sign change the inner elements
// in every other outer element
)
)=> // arrow function return
o // outer array
.map( // map outer array
e=>e.map( // map each inner array
(e,i)=>' '.repeat( // repeat space character the
// following amount:
Math.max(... // spread the following array to
// max arguments:
[... // spread the following to an
// array:
o // outer array
.map(e=>e[i]) // map returning each element of
// the same inner index from the
// outer array
.filter(e=>e!=a.a) // remove undefined elements
]
.map(e=>[...e+''].length) // map each element to the
// length of the string
) // returns the max string
// length of each column
-`${e}`.length // subtract the current
// element's string length
// from the max string length
) // returns the appropriate amount
// of padding
+e // add the element to the padding
)
).join`
` // join each element of outer
// array as string with newline
```
```
const f = (a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`
console.log('Test Case: -1,1')
console.log(f(-1,1))
console.log('Test Case: -3,6')
console.log(f(-3,6))
console.log('Test Case: -2,8')
console.log(f(-2,8))
console.log('Test Case: -15,8')
console.log(f(-15,8))
console.log('Test Case: -3,15')
console.log(f(-3,15))
console.log('Test Case: -12,12')
console.log(f(-12,12))
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 46 bytes
```
::[0,-1*a+b,2|[a,b|?d*q';`]q=q*-1┘a=a+1┘b=b-1?
```
How it works:
```
:: Read the negative and positive ints as a and b
[0,-1*a+b,2| FOR(c = 0; c < range(a, b); c+=2) {} This creates the proper amount of lines.
[a,b| For each line, loop from lower to upper
?d*q Print the current point in the range, accounting for the sign-switch
';` And suppress newlines. The ' and ` stops interpreting special QBIC commands.
] NEXT line
q=q*-1┘ Between the lines, flip the sign-flipper
a=a+1┘ Increase the lower bound
b=b-1? Decrease the upper bound, print a newline
The outermost FOR loop is auto-closed at EOF.
```
Fortunately, when printing a number, QBasic auto-adds the necessary padding.
[Answer]
# [Perl 6](https://perl6.org), 146 bytes
```
{$_:=(($^a..$^b).List,{-«.[1..*-2]}...3>*).List;$/:=[map {"%{.max}s"},roundrobin($_)».chars];map {join ',',map {$^a.fmt: $^b},flat($_ Z $/)},$_}
```
[Try it](https://tio.run/nexus/perl6#LZBLbsMgFEXnXsVTRGucwrOcqFFkN@mog0iVOm9@cj5WqGJIDK5aIVbUJXSWjaXgdIJ491w4iFbv4XOE2yKqv@F@q3Z7mFwtWecTSsmqRCSrTYKvQhtm@eUH5xlinw@WDhGH0/4NFSTNJ/O6PIHt3Vmsyy@ne441qpW7Rm2EpGSdXH5xeygbvSy64ocSEmIWs24Kqqo2OXidY9WxNP4IvANJE8fI2l0r1cBRyL2m3UWq3tA05vHzYveQhmQmDfAp0IU2ZWPYohJS6EMCNgI4NcLT8zk36unlbTYtfDaTp9brbFd3zN76LvLorTWB@Z0vhwD9COEB4XvoTQD/giIUAo/jInJX4EMYRcAzyPw6gHHEs0cY/wE "Perl 6 – TIO Nexus")
Produces a sequence of strings
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$a」 and 「$b」
# generate the data
$_ := ( # bind to $_ so it isn't itemized
# produce a sequence
( $^a .. $^b ).List, # seed the sequence, and declare parameters
{ -«\ .[ 1 .. *-2 ] } # get all the values except the ends and negate
... # keep producing until
3 > * # the length of the produced list is less than 3
).List; # turn the Seq into a List
# generate the fmt arguments
$/ := [ # bind an array to 「$/」 so it isn't a Seq
map
{ "%{ .max }s" }, # turn into a 「.fmt」 argument ("%2s")
roundrobin($_)\ # turn the "matrix" 90 degrees
».chars # get the string length of each number
];
# combine them together
map
{
join ',',
map
{ $^a.fmt: $^b }, # pad each value out
flat(
$_ Z $/ # zip the individual number and it's associated fmt
)
},
$_ # map over the data generated earlier
}
```
[Answer]
# PHP 7.1, 277 Bytes
```
for([,$a,$b]=$argv,$c=count($r=range($a,$b))/2;$c-->0;$r=range(-$r[1],-$r[count($r)-2]))$y[]=array_map(strlen,$x[]=$r);for($i=0;$i<count($y[0]);$i++)$z[$i]=max(array_column($y,$i));foreach($x as $g){$o=[];foreach($g as$k=>$v)$o[]=sprintf("%$z[$k]d",$v);echo join(",",$o)."\n";}
```
[Online Interpreter](http://sandbox.onlinephpfunctions.com/code/088c517f1024576059d553083d908a9a56fe72f0)
[Answer]
**C# console application 196 Bytes**
```
static void p(int a,int b){string S="",d ="";int c=-1;for(int i=b;i >=a;i--){c=c==1?c=-1:c=1;for(int j = a;j<=i;j++){S=j!=a?",":S="";d=d+S+(j*c);}d+= "\r\n";a++;}Console.Write(d);Console.Read();}
```
[Answer]
## Javascript - ~~196~~ ~~185~~ 176 bytes
```
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
```
I'm not really up to speed with some of the newer JS techniques so this could probably be golfed much more.
Simply creates a good old-fashioned HTML table with no width defined for the cells so the first row defaults to the width of each entry hense optimal spacing. It also (ab)uses HTML's "feature" of not requiring closing tags if a new opening tag comes along first.
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-1,1))
</script>
```
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-3,6))
</script>
```
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-2,8))
</script>
```
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-15,8))
</script>
```
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-3,15))
</script>
```
```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-12,12))
</script>
```
[Answer]
## Python 2 - 208 bytes
[Try it online](https://tio.run/nexus/python2#TY49DsIgHMX3noKFACkYQRex9QY9AemAARXzL22aEpm8ekVd@qZf8vI@VsdTG@KUFsoqaE1Gt3FGGYWIZhvvnha/lqyvunawEwU7XJ1FWb9PTW6UFEkkrGx0SJXYgQOrOiNkL1r5BfWD1yOAR@AjBXbZ62kOcSGc7J5jiHTTGjQlmNQEO4I7E/qaOMIwFOL/L/@KojNs33gtPAcjdRlm6yrkkSv1AQ)
```
d,u=input()
l=[x for x in range(d,u+1)]
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
M[-1]-=1
M[-2]-=1
while len(l)>0:print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))));l=map(lambda e:-e,l[1:-1])
```
Creates array of padding values and then use it to construct needed formated strings
Explanation:
```
d,u=input()
# create list of all values
l=[x for x in range(d,u+1)]
# create array of padding values
# by default, padding 2 used for numbers in [-9;9] and 3 for all other (limited with -99 and 99)
# but contracting list moves numbers larger that 9 under ones, that are <=9
# so upper limit of padding 2 is limited with 21-u-u%2
# (~9 == -10)
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
# last two elements should have lower padding as there won't be any other numbers it their columns
M[-1]-=1
M[-2]-=1
while len(l)>0:
# create formatted string for every element in l
# join all strings with comma
print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))))
# get slice without first and last element and change sigh
l=map(lambda e:-e,l[1:-1])
```
] |
[Question]
[
Given `n` (the number of players), `t` (the threshold value), and `s` (the secret), output the `n` secrets generated by [Shamir's Secret Sharing algorithm](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing).
## The Algorithm
For the purposes of this challenge, the computations will be done in **GF(251)** (the finite field of size `251`, otherwise known as the integers *mod 251*). Ordinarily, the field would be chosen such that its size is a prime much greater than `n`. To simplify the challenge, the field size will be constant. `251` has been chosen because it is the largest prime representable by an 8-bit unsigned integer.
1. Generate `t-1` random integers in the (inclusive) range `[0, 250]`. Label these *a1* through *at-1*.
2. Construct a `t-1`th degree polynomial using `s` as the constant value and the random integers from step 1 as the coefficients of the powers of `x`: *f(x) = s + x\*a1 + x2\*a2 + ... + xt-1\*at-1*.
3. Output `(f(z) mod 251)` for each `z` in the (inclusive) range `[1, n]`.
## Reference Implementation
```
#!/usr/bin/env python
from __future__ import print_function
import random
import sys
# Shamir's Secret Sharing algorithm
# Input is taken on the command line, in the format "python shamir.py n t s"
n, t, s = [int(x) for x in sys.argv[1:4]]
if t > n:
print("Error: t must be less than or equal to n")
exit()
if n not in range(2, 251):
print("Error: n must be a positive integer less than 251")
exit()
if t not in range(2, 251):
print("Error: t must be a positive integer less than 251")
exit()
if s not in range(251):
print("Error: s must be a non-negative integer less than 251")
exit()
p = 251
a = [random.randrange(0, 251) for x in range(t-1)]
def f(x):
return s + sum(c*x**(i+1) for i,c in enumerate(a))
# Outputting the polynomial is for explanatory purposes only, and should not be included
# in the output for the challenge
print("f(x) = {0} + {1}".format(s, ' + '.join('{0}*x^{1}'.format(c, i+1) for i,c in enumerate(a))))
for z in range(1, n+1):
print(f(z) % p)
```
## Verification
The following Stack Snippet can be used to verify outputs:
```
var validate = function() {
$('#nts-error').attr('hidden', parseInt($('#n').val()) >= parseInt($('#t').val()));
$('#check').prop('disabled', parseInt($('#n').val()) < parseInt($('#t').val()));
};
// the following function is taken from https://rosettacode.org/wiki/Combinations#JavaScript
var combinations = function(arr, k) {
var i,
subI,
ret = [],
sub,
next;
for (i = 0; i < arr.length; i++) {
if (k === 1) {
ret.push([arr[i]]);
} else {
sub = combinations(arr.slice(i + 1, arr.length), k - 1);
for (subI = 0; subI < sub.length; subI++) {
next = sub[subI];
next.unshift(arr[i]);
ret.push(next);
}
}
}
return ret;
};
// The following code is taken from https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing#Javascript_example with the modification that the prime is 251, not 257
var prime = 251;
/* Gives the decomposition of the gcd of a and b. Returns [x,y,z] such that x = gcd(a,b) and y*a + z*b = x */
function gcdD(a, b) {
if (b == 0) return [a, 1, 0];
else {
var n = Math.floor(a / b),
c = a % b,
r = gcdD(b, c);
return [r[0], r[2], r[1] - r[2] * n];
}
}
/* Gives the multiplicative inverse of k mod prime. In other words (k * modInverse(k)) % prime = 1 for all prime > k >= 1 */
function modInverse(k) {
k = k % prime;
var r = (k < 0) ? -gcdD(prime, -k)[2] : gcdD(prime, k)[2];
return (prime + r) % prime;
}
/* Join the shares into a number */
function join(shares) {
var accum, count, formula, startposition, nextposition, value, numerator, denominator;
for (formula = accum = 0; formula < shares.length; formula++) {
/* Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation
* Result is x0(2), x1(4), x2(5) -> -4*-5 and (2-4=-2)(2-5=-3), etc for l0, l1, l2...
*/
for (count = 0, numerator = denominator = 1; count < shares.length; count++) {
if (formula == count) continue; // If not the same value
startposition = shares[formula][0];
nextposition = shares[count][0];
numerator = (numerator * -nextposition) % prime;
denominator = (denominator * (startposition - nextposition)) % prime;
}
value = shares[formula][1];
accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
}
return accum;
}
$('#check').click(
function() {
var good = true;
var problem = [];
var n = parseInt($('#n').val());
var t = parseInt($('#t').val());
var s = parseInt($('#s').val());
combinations([...Array(n + 1).keys()].slice(1), t).forEach(
function(xArr) {
var xfArr = xArr.map(
function(x) {
return [x, parseInt($('#f' + x).val())];
}
);
var L = join(xfArr);
if (L !== s) {
good = false;
problem.push(xArr);
}
}
);
$('#valid').html(good ? "True" : ("False (problematic secret sets: {" + problem.map(
function(elem) {
return "[" + elem.join(', ') + "]";
}) + "})"));
}
);
$('#n').change(
function() {
var inputHTML = "";
for (var i = 1; i <= parseInt($('#n').val()); i++) {
inputHTML += 'f(' + i + '): <input type="number" min="0" max="250" value="0" id="f' + i + '"><br>\r\n';
}
$('#inputs').html(inputHTML);
validate();
}
);
$('#t').change(
function() {
validate();
}
);
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
n:
<input type="number" min="2" max="250" value="6" id="n">t:
<input type="number" min="2" max="250" value="3" id="t">s:
<input type="number" min="0" max="250" value="230" id="s">
<br>
<div id="nts-error" hidden="true">t must be less than or equal to n!</div>
<br>
<br>
<div id="inputs">
f(1):
<input type="number" min="0" max="250" value="35" id="f1">
<br>f(2):
<input type="number" min="0" max="250" value="95" id="f2">
<br>f(3):
<input type="number" min="0" max="250" value="159" id="f3">
<br>f(4):
<input type="number" min="0" max="250" value="227" id="f4">
<br>f(5):
<input type="number" min="0" max="250" value="48" id="f5">
<br>f(6):
<input type="number" min="0" max="250" value="124" id="f6">
</div>
<br>
<input type="submit" id="check" value="Verify">
<br>
<br>Valid:
<div id="valid"></div>
```
## Rules
* `s` will be a non-negative integer less than `251`, and `n` and `t` will be positive integers less than `251` and greater than `1`. Furthermore, you are guaranteed that the inputs are valid (meaning `t <= n`).
* Input and output can be in any reasonable, unambiguous, and consistent format.
* Random numbers are to be sampled from a uniform distribution - each possible value should have equal probability of being chosen.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
251©xX€⁵0¦ḅЀ%®
```
Expects **t**, **n**, and **s** as command-line arguments. [Try it online!](http://jelly.tryitonline.net/#code=MjUxwql4WOKCrOKBtTDCpuG4hcOQ4oKsJcKu&input=&args=Mw+Ng+MjMw)
### How it works
```
251©xX€⁵0¦ḅЀ%® Main link. Left argument: t. Right argument: n Third argument: s
251© Yield 251 and copy it to the register.
x Repeat [251] t times.
X€ Random choice each; pseudo-randomly choose t integers from
[1, ..., 251]. Since 251 = 0 (mod 251), this is equivalent to
choosing them from [0, ..., 250].
⁵0¦ Replace the last generated integer (index 0) with s (⁵).
ḅЀ Interpret the resulting array as a base-k number, for each k in
[1, ..., n], and convert to integer.
® Yield 251 from the register.
% Take the generated integers modulo 251.
```
[Answer]
# Mathematica, ~~59~~ 56 bytes
```
Mod[Power~Array~{#2,#-1}.RandomInteger[250,#-1]+#3,251]&
```
Takes three arguments in the order *t*, *n*, and *s*. Constructs a 2d-array with *n* rows and *t*-1 columns. Each row vector *j*, numbered from 1 thru *n*, contains the powers of *j* thru *j**t*-1. Then a vector of random integer coefficients in the range 0 thru 250 is created with *t*-1 values. That is matrix-multiplied with the 2d-array, and then *s* is added element-wise and taken module 251 to get the value of the polynomial at each of the *n* points.
[Answer]
## CJam, ~~27~~ 25 bytes
```
{,:)@({;251mr}%@+fb251f%}
```
[Test it here.](http://cjam.aditsu.net/#code=3%20230%206%0A%7B%2C%3A)%40(%7B%3B251mr%7D%25%40%2Bfb251f%25%7D%0A~p&input=3%20230%206)
[Answer]
# Pyth, 24 bytes
```
J+EmOK251tEm%s.e*b^dkJKS
```
[Try it online!](http://pyth.herokuapp.com/?code=J%2BEmOK251tEm%25s.e%2ab%5EdkJKS&input=5%0A7%0A3&debug=0)
Input order: `n` `s` `t` separated by linefeed.
[Answer]
# JavaScript, 181 bytes
```
(n,t,s)=>{r=Array(t-1).fill(0).map($=>{return Math.random()*251});f=(x=>{p = 0;r.map((k,c)=>p+=k*Math.pow(x, c));return s+p});_=Array(t-1).fill(0);_.map((l,i)=>_[i]=f(i));return _;}
```
Ungolfed:
```
(n, t, s) => {
r = Array(t - 1).fill(0).map($ =>{return Math.random() * 251});
f = (x => {
p = 0;
r.map((k, c) => p += k * Math.pow(x, c));
return s + p
});
_ = Array(t - 1).fill(0);
_.map((l, i) => _[i] = f(i));
return _;
}
```
I don't know how to properly check it, but I do know that it was a pain to get JS to map across a new array since apparently `.map` skips undefined values. If anyone sees any ways to improve, or flaws, don't hesitate to let me know.
[Answer]
# C#, ~~138~~ 134 bytes
```
(n,t,s)=>new int[n+1].Select((_,x)=>(s+new int[t-1].Select(k=>new Random(e).Next(251)).Select((c,i)=>c*Math.Pow(x+1,i+1)).Sum())%251);
```
C# lambda where inputs are `int` and output is an `IEnumerable<double>`. You can try my code on [.NetFiddle](https://dotnetfiddle.net/1jRVwd).
I am not 100% sure about the validity of my algorithm, please comment if I misunderstood something.
4 bytes saved with @raggy's [trick](https://codegolf.stackexchange.com/a/70934/15214).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ 19 bytes
```
251tliq3$Yrihi:ZQw\
```
Input order is `t`, `s`, `n`.
[**Try it online!**](http://matl.tryitonline.net/#code=MjUxdGxpcTMkWXJpaGk6WlF3XA&input=MwoyMzAKNg)
### Explanation
```
251t % Push 251 twice
l % Push 1
iq % Take input t. Subtract 1
3$Yr % Generate t-1 random integers in [1 2 ... 251]
ih % Take input s. Concatenate with the random integers
i: % Take input n. Generate range [1 2 ... n]
ZQ % Evvaluate polynomial at those values
w % Swap to move copy og 251 to the top of the stack
\ % Modulo. Implicitly display
```
[Answer]
# Julia, 48 bytes
```
f(n,t,s)=(1:n).^(0:t-1)'*[s;rand(0:250,t-1)]%251
```
[Try it online!](http://julia.tryitonline.net/#code=ZihuLHQscyk9KDE6bikuXigwOnQtMSknKltzO3JhbmQoMDoyNTAsdC0xKV0lMjUxCgpmKDYsMywyMzApIHw-IHByaW50bG4&input=)
[Answer]
# [J](http://jsoftware.com), ~~32~~ 30 bytes
```
251|(1+i.@{.)p.~{:0}251?@#~1&{
```
Takes a list with the values *n*, *t*, and *s*.
Saved 2 bytes by using the *replace at index 0* idea from @Dennis's [solution](https://codegolf.stackexchange.com/a/84788/6710).
## Explanation
```
251|(1+i.@{.)p.~{:0}251?@#~1&{ Input: [n t s]
1&{ Select at index 1 (t)
251 #~ Create that many copies of 251
?@ Generate that many random integers in [0, 251)
{: Get the tail of the input (s)
0} Replace the value at index 0 of the random integer list
with s to make a coefficient list of the polynomial
{. Get the head of the input (n)
i.@ Make the range [0, n-1]
1+ Add 1 to each to get [1, n]
p.~ Evaluate the polynomial at each value [1, n]
251| Take each value mod 251 and return
```
[Answer]
## JavaScript (ES6), 116 bytes
```
(n,t,s)=>[...Array(n)].map((_,i)=>++i&&t.reduce((r,a)=>r*i+a)%251,t=[...Array(t)].map(_=>--t?Math.random()*251|0:s))
```
I'd like to think this is one of the rare cases where `reduce` beats `map`.
[Answer]
# Python 3 with [NumPy](http://www.numpy.org/), 103 bytes
```
from numpy import*
lambda n,t,s:[poly1d(append(random.randint(0,251,t-1),s))(i+1)%251for i in range(n)]
```
I can honestly say that I never expected to use NumPy for code golf...
An anonymous function that takes input via argument and returns a list.
**How it works**
```
from numpy import* Import everything in the NumPy library
lambda n,t,s... Function with input number of players n, threshold value t and
secret s
random.randint(0,251,t-1) Generate a NumPy array R of t-1 random integers in [0,250]
append(...,s) Append s to R
poly1d(...) Generate a polynomial p of order t-1 with coefficients R and
constant term s
...for i in range(n) For all integers i in [0,n-1]...
...(i+1) ...evaluate p(i+1), so for all integers in [1,n]...
...%251 ...and take modulo 251
...:[...] return as list
```
[Try it on Ideone](https://ideone.com/q1RVw6)
[Answer]
# Java 8, 224 bytes:
```
(n,t,s)->{int[]W=new int[t-1];for(int i=0;i<t-1;i++){W[i]=new java.util.Random().nextInt(251);};long[]O=new long[n];for(int i=1;i<=n;i++){long T=0;for(int h=1;h<t;h++){T+=W[h-1]*Math.pow(i,h);}O[i-1]=((T+s)%251);}return O;};
```
A Java 8 lambda expression. Outputs a comma separated integer array, and works perfectly until values in the output array reach beyond the range of the Java's `long`, or 64-bit signed integer, data type, upon which `-200` is output into the array.
[Try It Online! (Ideone)](http://ideone.com/kKsNCP)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 205 bytes
\$ \text{205 bytes, It can be golfed much more.} \$
---
Golfed version. [Try it online!](https://ato.pxeger.com/run?1=hZFLbtswEIb3PMVAQAAykYVItvKwqwBZFQ2MBKhdeGF4wSZ0xFQaGhQd1zC87x266abd9Cw9gO_RA2Ro0UFWLSBq8f8z37y-_2ruZSW7v6dRB81KWoxmu2-6XhjrYG8lS6er5KPEB1MzZj4_qXsH17BhAG69UPAeCuAf0MVw-AkoruDaWrmeDg0-zhiFPqg51FIjl_ax6Qd35KwmX_ThE2pHHA8FeJYV3PQ9-OfSzTsXuz8cYxc3orjaeG9SoFoFBJWbcddJxWBuLNfvOqewRGoYvLaZcC2KtvUE1VdH0TzLU7EdeM7dG86-UY6vmBScARRUz8K4OB3u9dLrAS9gMy7GJ3zCS6p0XEtXJguz4jouhUic8cDt4I5rcgs-PmnEEVUmZRuG-vs6K60ZUVma3_fzJJ_Dzketzkfrxqk60Sj2KatSVwp4yEpK2dzSaEONSoQFtlgk4CHoMLx447v_-M0__AUdzlXIb-gyQFdvRFJ_ac_Jo2kUQ_hmkWhTtsy_MPuP3XF6CRmkGTuDLqQ5y6EH5ywjLSOxR2J-xi4hh26vTXkB)
```
(n,t,s)=>{val W=new Array[Int](t-1);for(i<-0 until t-1){W(i)=Random.nextInt(251)};val O=new Array[Long](n);for(i<-1 to n){var T=0L;for(h<-1 until t) {T=T+(W(h-1)*math.pow(i,h)).toLong};O(i-1)=(T+s)%251};O}
```
Ungolfed version. [Try it online!](https://ato.pxeger.com/run?1=hVLRSuNAFAUf5ysOBWFG22DSxl2LLvi0rJQt2C59kD7M6tSMJpOSTFvL0i_xpS_6T_rir3ibmYbqwi6EkNxz7rn33Hsfn8trmcr2ev00s5PW19e9N51N88Kiigczq9PgUpqbPGMs_32nri3O8YcBdjlV-I4z8B_GNrF9CZx9w3lRyOVVLze3Y0bUGzVBJrXhsrgtux4d2EITLrr4ZbQlnY0oMJcpLrpO2DRBomUl6VCHjwg0auGFqOiYW7QQCs-Z5AW4xmkLR5gZcgAH1yLAiGuShXMWGPVgSYZHca2x2qnX_1CvssXN38VC2Bxmt8pcFhhS8lGvDlX0xNF9b7sZqPjDQ_ARsaqmD2h2Ngmm-YLrJhIhAptveqhzVvVXnxqpcmh4QxxuRrcPMvXJU5-5v3rgtGtjVOFt3sm5X_zAxflgWVqVBdqbXiQ6VeA-K0hk-ZMG2NNGiQ97MiS4JW1HLHZw-x-8_Ac-peuxqeEX9ZUE2b27Kd64ajThn3FDCLY1v2Ir5u7cn_v65SA8QYQwYsdoI4xZjA6-sIhiEQU7FIyP2QlitDsu5R0)
```
import scala.util.Random
object A {
type G = (Int, Int, Int) => Array[Long]
def main(args: Array[String]): Unit = {
val J: G = (n, t, s) => {
val W = new Array[Int](t - 1)
for (i <- 0 until t - 1) {
W(i) = Random.nextInt(251)
}
val O = new Array[Long](n)
for (i <- 1 to n) {
var T = 0L
for (h <- 1 until t) {
T = T+ (W(h - 1) * math.pow(i, h)).toLong
}
O(i - 1) = (T + s) % 251
}
O
}
val scanner = new java.util.Scanner(System.in)
while (scanner.hasNextLine) {
val n = scanner.nextInt()
val t = scanner.nextInt()
val s = scanner.nextInt()
println(J(n, t, s).mkString("[", ", ", "]"))
}
}
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 133 bytes
-10 bytes thanks to @ceilingcat!
-1 byte thanks to @ceilingcat!
```
v[999];i,j,k,l;f(n,t,s){for(i=t;--i;)v[i]=rand()%251;for(*v=s;n/++i;printf("%d ",s%251))for(s=j=0;j<t;s+=k)for(k=v[l=j++];l--;)k*=i;}
```
[Try it online!](https://tio.run/##HcpBCoMwEEDRdT2FCEJiJtQqLch0TiIuREmZaNNiQjbi2VPs9v836dc0pRT7rusGZLCwwIpGOAjg5W4@m2AKqDWjjD0PtI1uFrJs7jc8ZxXJo7sqxfjd2AUjinLOC/CnkPIknizVaJ8BvaLlnxaK/UpWqQFXrVEuFTEe6T2yEzLbs4sRD8hbyJu2lpgd6Qc "C (gcc) – Try It Online")
] |
[Question]
[
## Explanation
The **edit distance** between two strings is a function of the minimum possible number of insertions, deletions, or substitutions to convert one word into another word.
Insertions and deletions cost 1, and substitutions cost 2.
For example, the distance between `AB` and `A` is 1, because deletions cost 1 and the only edit needed is the deletion of the `B` character.
The distance between `CAR` and `FAR` is 2, because substitutions cost 2. Another way to look at this is one deletion and one insertion.
## Rules
Given two input strings (supplied however is convenient in your language), your program must find the minimum edit distance between the two strings.
You may assume that the strings only contain the characters `A-Z` and have fewer than 100 characters and more than 0 characters.
This is **code golf**, so the shortest solution wins.
## Sample Test Cases
```
ISLANDER, SLANDER
> 1
MART, KARMA
> 5
KITTEN, SITTING
> 5
INTENTION, EXECUTION
> 8
```
[Answer]
## brainfuck, 2680
```
+>>>>>>>>>>>>>>>>>>>>>>++++++>,<[->-----<]>--[+++++++++++++++++++++
+++++++++++>>[->>+<<]>>+<<,--------------------------------]>>[-<<<
+>>>]<<<<[>[-<<+>>]<<<]>[-<<<<<+>>>>>]>[>>],----------[++++++++++>>
[->>+<<]>>+<<,----------]>>[-<<<+>>>]<<<<[>[-<<+>>]<<<]>[-<<+>>]<<[
-<+>>+<]<<<[->+<]>[-<+>>>>+<<<]>>>[-<+>]<[->+>+<<]<[-<+>]<[->+>+<<]
<[-<+>>+<]<[->+<]>>>>>>[-[->>+<<]<<[->>+<<]<<[->>+<<]>>>>>>]<<[->>+
>+<<<]>>>[-<<<+>>>]<[->>+[->+>+<<]<<[->>+<<]>>]>>[-]<[<<]<<<+[->>>+
<<<]>>>[-<+<<+>>>]<<<<<[->>[->>>>[->>+<<]<<[->>+<<]<<[->>+<<]<<[->>
+<<]>>>>]>>[->>>>+<<<<]>>>>[-<<<<+<<+>>>>>>]<<+[->>+<<]>>[-<<+<+>>>
]<<<<<<<<]>>[-]>>[-]>>[-]-[+<<-]+>>>>>>>>>>>>>>>>>[-<+>]<[->+<<<<+>
>>]<<<[->>>>>>[-<+>]<[->+<<<<+>>>]<<<<<<<[-]<<+>>>>>>[-<<<<+>>>>>>>
>>>[-<+>]<[->+>+<<]<<<<<<<<<[->+<]>[->>>>>>>>+<<<<<<<<<+>]<<<[->+<]
>[->>>>>>>>+<<<<<<<<<+>]>>>>>>>>>[-<<<<<+>>>>>]<<<<<[->>+>>>+<<<<<]
>>>>>>>>[-[->>+<<]<<[->>+<<]<<[->>+<<]<<[->>+<<]>>>>>>>>]<<<<<<+>>-
[-<<[-<<<<+>>>>]<<<<[->>+>>+<<<<]>>[->>>>>>[->>+<<]<<[->>+<<]<<[->>
+<<]<<[->>+<<]>>]>>>>]>>[->>+<<]>>[-<<+>>>>+<<]->>-[-[->>+<<]>>]>[-
>+<]>[-<+>>>+<<]<<<[->+<]>[-<+>>>+<<]+[->>[-<<+>>]>>[-<<+>>]<<<<<<+
]<<<<<<[->>>>>>+<<<<<<]>>>>>>>>[-<<<<<<<<+>>>>>>>>]<<<<[->>>>+<<<<]
-<<[-]>>>>>>>>[-<<<<<<<<+>>>>>>>>]<<<<[->>[->>+<<]<<[->>+<<]>>]>>-[
-[->>+<<]>>]<[->+<]>[-<+>>>+<<]+[->>[-<<+>>]<<<<+]>>[-<<+>>]<<<<<<<
<-[+>>[-<<+>>]>>[-<<+>>]>>[-<<+>>]<<<<<<<<-]+>>>[-]<[->+<]>>>[-]<[-
>+<]>>>[-]<[->+<]>>>[->+<]>[-<+>>>>>>>>>>>>>+<<<<<<<<<<<<]>>>>>>>>>
>>>-[-[->>+<<]>>]>[->+<]>[-<+<+>>]<<<<-[+>>[-<<+>>]<<<<-]+>>[-<+>]>
>>>>>>>>[->+<]>[-<+>>>>>>>>>>>+<<<<<<<<<<]>>>>>[->+<]>[-<+>>>>>+<<<
<]>>>>-[-[->>+<<]>>]>[->+<]>[-<+<+>>]<<<<-[+>>[-<<+>>]<<<<-]+>[->-<
]>[-<[-]+>]<[->>>+<<<]>>>[-<<+<+>>>]<<-[+>[->+<]<]<[->>+<-[[-]>[->+
<]>[-<+>>>+<<]+>>[-<<[-]>>]<[->+<]>[-<+>>>+<<]+>>[-<<[-]>>]<[->+<]>
[-<+>>>+<<]+>>[-<<[-]>>]<<[-<<[-]+>>]<<[-<<[-]+>>]<<[-<<[-]+>>]<<<+
>->->>->>-<<<<<]<[->+<]]>[-<+>]>>[-<<<+>>>]<<<[->>>>>>>>>>>>>+<<<<<
<<<<<<<<]>>>>>>>>[->+<]>[-<+>>>>>>>>>+<<<<<<<<]>[->+<]>[-<+>>>>>>>>
>+<<<<<<<<]>>>>>>>>>[->>>+<<<]>>>[-<<+<+>>>]<<<<<[->>>>>+<<<<<]>>>>
>[-<<<<<+<<<+>>>>>>>>]<<<<<<<<+>>>>>>[-[->>+<<]<<[->>+<<]<<[->>+<<]
<<[->>+<<]<<[->>+<<]>>>>>>>>>>]<<<<[-<<[-<<<<<<+>>>>>>]<<<<<<[->>+>
>>>+<<<<<<]>>[->>>>>>>>[->>+<<]<<[->>+<<]<<[->>+<<]<<[->>+<<]<<[->>
+<<]>>]>>>>>>]<<[-]<<[->>>>+<<<<]>>>>>>[-[->>+<<]<<[->>+<<]>>>>]<<[
->>>>>+<<<<<]-[+<<-]+>>>>>>>>>>>>>>>]<<]>>>>>>>>[->+<]<<[->+<]<<[->
+<]>>>>>[-[->>+<<]<<[->>+<<]<<[->>+<<]>>>>>>]<<<<[->>[->>>>+<<<<]>>
>>[-<<+<<+>>>>]<<+[-[->>+<<]<<[->>+<<]<<[->>+<<]>>>>>>]<<<<]>>[-[->
>+<<]>>]>>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>[->-[>+>>]>
[+[-<+>]>+>>]<<<<<]>[-]<++++++[->++++++++[->+>+<<<<+>>]<]>>>.<.<<<.
```
Using dynamic programming, of course.
Input strings should be separated by a space, and followed by a new line. For example:
```
INTENTION EXECUTION
008
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 14 bytes
```
⟨⊇⊆⟩jg;?clᵐ-ˡṅ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FY@62h91tT2avzIr3do@Oefh1gm6pxc@3Nn6/3@0UmZeSWpeSWZ@npKOglJqRWpyKZgT@z8KAA "Brachylog – Try It Online")
This question has a surprising lack of golfing language solutions (there's an APL solution, which is a quasi-golfing language, but it doesn't beat the builtin-based solutions). So here's an attempt to get the ball rolling on that.
I'm not really happy with the golfiness of this; there's a lot of plumbing, as is so often the case when a Brachylog answer takes multiple inputs. In order to comprehensively beat the builtin-based solutions, ideally someone would come up with an answer that's shorter than the word "Levenshtein". Anyone feel like giving that a go?
## Explanation
```
⟨⊇⊆⟩jg;?clᵐ-ˡṅ
⟨ ⟩ Find a value that is related to the first and second inputs:
⊇ {the first input} is a non-continguous superstring of it
⊆ it is a non-contiguous substring of {the second input}
j Concatenate that value to itself
g Form a singleton list containing that value
;?c Append the inputs to that list
lᵐ Take the length of each of the three elements
-ˡ Left fold by subtraction
ṅ Multiply the result by -1
```
The real work is done by the `⟨⊇⊆⟩` at the start, which finds the longest common subsequence of the two inputs (as specified, it just asks for any subsequence, but Brachlog's default tiebreaks will always pick the longest). Let's call the length of this *q*, and the lengths of the inputs *a* and *b*. The edit distance is then equal to *a*-*q*+*b*-*q*; to edit one into the other, we need to delete from one until we reach the common subsequence, then insert until we reach the other (when editing with insertions and deletions, the order doesn't matter).
After our `⟨⊇⊆⟩`, the current implicit variable is a string of length *q*. Doubling this with `j` gives us a string of length 2*q*. After bringing the inputs back into our working value, we have three strings, of lengths [2*q*, *a*, *b*], and can replace these with their lengths. Reducing by subtraction then gives 2*q*-*a*-*b* = -(*a*-*q*+*b*-*q*), so we simply need to negate the answer to get the edit distance.
[Answer]
# Python, 138 148 152 characters
Ok, I knew the principle but had never implemented edit distance before, so here goes:
```
x,y=raw_input().split()
d=range(99)
for a in x:
c=d;d=[d[0]+1]
for b,p,q in zip(y,c[1:],c):d+=[min(d[-1]+1,p+1,q+2*(a!=b))]
print d[-1]
```
[Answer]
## R 51
This reads in two lines from the user (which are the input) and then just uses the `adist` function to calculate the distance. Since substitutions cost 2 for this problem we need to add a named vector for the costs parameter for adist. Since there is also a counts parameter for adist we can only shorten costs to cos so we still have a unique match for the parameter names.
```
x=readLines(n=2);adist(x[1],x[2],cos=c(i=1,d=1,s=2))
```
Example use
```
> x=readLines(n=2);adist(x[1],x[2],cos=c(i=1,d=1,s=2))
MART
KARMA
[,1]
[1,] 5
```
[Answer]
## PHP, 40
Follows the rules as stated, but not the spirit of the rules:
```
<?=levenshtein($argv[1],$argv[2],1,2,1);
```
Takes it's two parameters as arguments. Example calling: `php edit_dist.php word1 word2`.
Normally `levenshtein()` considers a substitution as one operation, but it has an overloaded form where the insert/sub/delete weights can be specified. In this case, its 1/2/1.
[Answer]
# APL (90 characters)
```
⊃⌽({h←1+c←⊃⍵⋄d←h,1↓⍵⋄h,(⊂⍵){y←⍵+1⋄d[y]←⍺{h⌷b=⍵⌷a:⍵⌷⍺⋄1+d[⍵]⌊y⌷⍺}⍵}¨⍳x}⍣(⊃⍴b←,⍞))0,⍳x←⍴a←,⍞
```
I'm using Dyalog APL as my interpreter, with `⎕IO` set to 1 and `⎕ML` set to 0. The direct function (`{ ... }`) computes, given a row as input, the next row in the distance matrix. (It is started with the initial row: `0,⍳x`.) The power operator (`⍣`) is used to nest the function once for each character in the second string (`⊃⍴b`). After all of that, the final row is reversed (`⌽`), and its first element is taken (`⊃`).
Example:
```
⊃⌽({h←1+c←⊃⍵⋄d←h,1↓⍵⋄h,(⊂⍵){y←⍵+1⋄d[y]←⍺{h⌷b=⍵⌷a:⍵⌷⍺⋄1+d[⍵]⌊y⌷⍺}⍵}¨⍳x}⍣(⊃⍴b←,⍞))0,⍳x←⍴a←,⍞
LOCKSMITH
BLACKSMITH
3
⊃⌽({h←1+c←⊃⍵⋄d←h,1↓⍵⋄h,(⊂⍵){y←⍵+1⋄d[y]←⍺{h⌷b=⍵⌷a:⍵⌷⍺⋄1+d[⍵]⌊y⌷⍺}⍵}¨⍳x}⍣(⊃⍴b←,⍞))0,⍳x←⍴a←,⍞
GATTTGTGACGCACCCTCAGAACTGCAGTAATGGTCCAGCTGCTTCACAGGCAACTGGTAACCACCTCATTTGGGGATGTTTCTGCCTTGCTAGCAGTGCCAGAGAGAACTTCATCATTGTCACCTCATCAAAGACTACTTTTTCAGACATCTCCTGTAG
AAGTACTGAACTCCTAATATCACCAATTCTTCTAAGTTCCTGGACATTGATCCGGAGGAGGATTCGCAGTTCAACATCAAGGTAAGGAAGGATACAGCATTGTTATCGTTGTTGAGATATTAGTAAGAAATACGCCTTTCCCCATGTTGTAAACGGGCTA
118
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
```
Lṁ-→FnmṖ¹
```
[Try it online!](https://tio.run/##yygtzv6fG6xRnqqpUfyoqbFc89C2/z4PdzbqPmqb5JaX@3DntEM7////n1mck5iXklqkAKW5chOLShSyE4tyE7myM0tKUvMUioFUZl46V2YekFeSmZ@nkFqRmlwKYgEA "Husk – Try It Online")
Inspired by [ais523's Brachylog solution](https://codegolf.stackexchange.com/a/214259/62393), finds the longest common (not necessarily contiguous) subsequence and subtracts it from each string.
~~I don't like having to repeat `Ṗ` twice and having to explicitly refer to the two arguments `¹` and `³`, but I couldn't find any shorter alternative.~~ *Now* I'm happy :)
### Explanation
```
Lṁ-→FnmṖ¹ Input: a list containing the two strings
Ṗ Get all possible subsequences
m ¹ for each string
Fn Keep only the common ones
→ Get the last one (which will be the longest)
- and subtract it
ṁ from each of the inputs, then concatenate the remaining characters
L Find the length of this
```
Subtracting the longest common substring for each input results in the lists of characters that need to be deleted/inserted. We concatenate these two lists and get the length to calculate the edit distance.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒP€f/ṪLạẈS
```
[Try it online!](https://tio.run/##y0rNyan8///opIBHTWvS9B/uXOXzcNfCh7s6gv///x@tlJlXkppXkpmfp6SjlFqRmlwKZscCAA "Jelly – Try It Online")
A port to Jelly of [my Brachylog answer](https://codegolf.stackexchange.com/a/214259), saving a few bytes through more convenient plumbing and some convenient builtins (and beating the builtin-based practical language answers by being shorter than the word "Levenshtein"). This is a function submission (although it also works as a full program), taking a list of the two strings.
The algorithm is the same: find the longest common subsequence of the two strings, then add together the differences in lengths between the common subsequence and each of the two original strings.
An odd side effect of this algorithm is that it seems to give an internally consistent definition of the edit difference between three or more strings, as well. I'm not sure if that would be useful for anything, but it's nice to know it exists.
## Explanation
```
ŒP€f/ṪLạẈS
€ On each of the original strings
ŒP produce all possible subsequences of the string;
f take the list of common elements
/ between the first and second sets of subsequences;
L take the length of
Ṫ the last of these common elements;
ạ take the absolute differences between that and
Ẉ the length of each {of the original strings}
S and sum them.
```
Shoutouts to `Ẉ` here for having an implied "each" in it, thus ensuring that Jelly implicitly finds the correct thing to take the length of (if you write `L`, "length", rather than `Ẉ`, "length of each", you get the *number* of strings you started with which is not helpful).
Jelly sorts the subsequences in order from shortest to longest, and `f` returns its output in the same order as in its left argument, so the `Ṫ` is guaranteed to find the longest subsequence. We can save any need to subtract from 0 (like the Brachylog submission does), because we have access to an absolute-difference builtin.
[Answer]
# Smalltalk (Smalltalk/X), 34
I am lucky - the standard "String" class already contains levenshtein:
input a, b:
```
a levenshteinTo:b s:2 k:2 c:1 i:1 d:1
```
(the additional parameters allow for different weights on substitution, deletion, etc.)
Test run:
```
#( 'ISLANDER' 'SLANDER'
'MART' 'KARMA'
'KITTEN' 'SITTING'
'INTENTION' 'EXECUTION'
) pairWiseDo:[:a :b|
a print. ' ' print. b print. ' ' print.
(a levenshteinTo:b
s:2 k:2 c:1 i:1 d:1) printCR.
].
```
->
```
ISLANDER SLANDER 1
MART KARMA 5
KITTEN SITTING 5
INTENTION EXECUTION 8
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~23~~ ~~22~~ 21 bytes
```
`-L+¹³*2▲mλΣz=←¹→)¤*Q
```
[Try it online!](https://tio.run/##yygtzv7/P0HXR/vQzkObtYweTduUe273ucVVto/aJhza@ahtkuahJVqB////T0xKTklN/58GpNLT0wA "Husk – Try It Online")
```
`-+L¹L³*2▲mλΣz=←¹→)¤*Q
`- # reversed minus: a-b
+L¹L³ # a = length of arg1 + length of arg2
*2 # b = 2x
▲ # maximum value of
m # map function to all elements of list
λ # function:
Σ # sum of
z= # elements that are equal between
←¹ # sublist 1 and
→) # sublist 2
* # list: cartesian product of
¤ Q # all sublists of arg1 and arg2
```
[Answer]
**Ruby 1.9, 124**
```
l=->a,b{a[0]?b[0]?[(a[0]==b[0]?-1:1)+l[a[1..-1],b[1..-1]],l[a[1..-1],b],l[a,b[1..-1]]].min+1: a.size: b.size}
puts l[*ARGV]
```
Golfed version of the slow, recursive Ruby method [here](http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Ruby), modified to double the weight for substitutions. The fact that it takes 7 characters to remove the first character of a string really hurts, and it'd be cool to replace `(a[0]==b[0]?-1:1)` with something like `-1**a[0]<=>b[0]` but the order of operations is not my friend.
] |
[Question]
[
# Introduction
I have an **even** number of bottles, all of different sizes. Unfortunately, I only know the size of the smallest bottle: **300ml**.
I also know the following:
* Half of the bottles are twice the size of the other half, meaning that the smallest small bottle and the smallest large bottle are in a ratio of 2:1.
* The smaller bottles, from smallest to largest, increase in size by n%, where n is the number of bottles multiplied by 3.
Could you help find what sizes my bottles are?
# Challenge
Your input is to be an **even** number of bottles.
The output should be the size of all of the small bottles (from smallest to largest), then all of the large bottles (from smallest to largest).
# Example I/O
In: `2`
Out: `300, 600`
In: `4`
Out: `300, 336, 600, 672`
In: `10`
Out: `300, 390, 507, 659.1, 856.83, 600, 780, 1014, 1318.2, 1713.66`
(Note: commas are unnecessary; this answer can be formatted in any way you want as long as all of the "small" bottles come before the "large" bottles.)
# Rules
Standard [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1789#1789) apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
# Winners
**Esoteric Languages**
15 bytes
[05AB1E by Kevin Cruijssen](https://codegolf.stackexchange.com/a/195748/89826)
**Standard Languages**
36 bytes
[Mathematica by attinat](https://codegolf.stackexchange.com/a/195781/89826)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~61~~ ~~60~~ 59 bytes
```
lambda n:[a*(1+.03*n)**i*75for a in 4,8for i in range(n/2)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpRS8NQW8/AWCtPU0srU8vcNC2/SCFRITNPwUTHAsTOBLGLEvPSUzXy9I00Y/8XFGXmlSikaRhpcsGYJgimoYHmfwA "Python 2 – Try It Online")
-1 byte, thanks to Joseph Sible
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
{#,2#}&[300(1+.03#)^Range[0,#/2-1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v1pZx0i5Vi3a2MBAw1Bbz8BYWTMuKDEvPTXaQEdZ30jXMDZW7X9AUWZeSbSyrl2ag3Ksmr5DNZeRDpeJDpehAVftfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₆v;F.03*>NmyтP,
```
Port of [*@TFeld*'s Python 2 answer](https://codegolf.stackexchange.com/a/195739/52210), so make sure to upvote him.
[Try it online](https://tio.run/##yy9OTMpM/f//UVNbmbWbnoGxlp1fbuXFpgCd//8NDQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3lopQ6Xkn9pCYSv8/9RU1vZoXXWbofW6RkYa9n55VZebArQ@V9be2ib/f9oIx0THUODWAA).
**Explanation:**
```
₆ # Push builtin integer 36
v # Loop `y` over both digits:
; # Halve the (implicit) input-integer
F # Inner loop `N` in the range [0, input/2):
.03* # Multiply the (implicit) input by 0.03
# (alternative 4-byter: `т/3*` # divide by 100, multiply by 3)
> # Increase this by 1
Nm # Take it to the power `N`
yт # Push both `y` and 100
P # And take the product of the entire stack
, # Then pop and print this number with trailing newline
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
×.03‘*HḶ$×300;Ḥ$
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//w5cuMDPigJgqSOG4tiTDlzMwMDvhuKQk////MTA "Jelly – Try It Online")
-2 bytes thanks to Nick Kennedy
# Explanation
```
×.03‘*HḶ$×300;Ḥ$ Main Link
×.03 Multiply the number of bottles by 3%
‘ Increment (add 100%)
* (Vectorized) exponent to the power of:
HḶ$ [0, 1, ..., n-1]
×300 Multiply each factor by 300
;Ḥ$ Double the list and append it
```
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
f n=[75*a*(1+0.03*n)**i|a<-[4,8],i<-[0..n/2-1]]
```
[Try it online!](https://tio.run/##HYixDoIwAAV3vuKFOEAptSBGY8TJOLk5YmNqgNBYWgI1Lv57BZd7966T06vR2qt@sKPDWTrJLlbX8qkbRK0dH3EQ9FIZlFgeqpwWNOMCK9wN0hNqGwDD293ceDVznTr7gUGSIDwgXPZfohYm9jPKarclkkRZwhnfEBMTor7ymFYF3QuqZuGMmXWeZkJ4/wM "Haskell – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 42 38 bytes
```
f(n,z=[75*(1+.03n).^(0:n÷2-1)])=4z,8z
```
-4 bytes using ideas from John and Joseph Sible.
[Try it online!](https://tio.run/##yyrNyUw0rPj/P00jT6fKNtrcVEvDUFvPwDhPUy9Ow8Aq7/B2I11DzVhNW5MqHYuq/w7FGfnlCmkaRppcMKYJgmlooPkfAA "Julia 1.0 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
n=input()/2
for c in 4,8:exec"print c*75;c*=1+.06*n;"*n
```
[Try it online!](https://tio.run/##LYvLCsMgEEX3@Yoh3SRGrKPxkQb/pDuJNJuJBAvt11tLuzmHy@Hmd3kcpGoK90php/wsw3hVXTpOiLATzNzfttcW@3zuVCAyZ9bIAk5CWkZrz6j@Shr@77G7aCk56KXBSMfBmkUgB2@s8LrNb3W@ASXOjRq9UM0OtbC2ovwA "Python 2 – Try It Online")
The `*75` trick is taken from other answers.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 63 bytes
```
f=(n,b=300,r=1+n*9/b,h=n/2)=>n?[b,...f(n-1,--h?b*r:600,r,h)]:[]
```
[Try it online!](https://tio.run/##ZcpBCoMwEADAe1@S1U1MbClUWH2IeDBqmhbZSBS/H/EoXof593u/DvG3bJLDOKXkSDBaemqNkUzO2aew6ImLEqjmprWolHKCpUEpfWOzWL3Pix66qu3SEHgN86Tm8BVOlACPq7xuYjRAOgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~70~~ 62 bytes
```
for($s=300;$i++<$n=$argn;$s=$n/2-$i?$s+$s*$n*.03:600)echo$s,_;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFSKbY0NDKxVMrW1bVTybFUSi9LzrIGCKnn6RroqmfYqxdoqxVoqeVp6BsZWZgYGmqnJGfkqxTrx1v9BLAWlmDwla67SvOLUEg2VTE04M0vT@r8RlwmXocG//IKSzPy84v@6bgA "PHP – Try It Online")
Output numbers are seperated by `_`.
Alternative for `$s+$s*$n*.03` can be `$s*=1+$n*.03` too, but both are same length.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ 54 bytes
-12 bytes thanks to mazzy
```
param($n)300,600|%{$y=$_;1..($n/2)|%{$y;$y*=1+$n*.03}}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT9PYwEDHzMCgRrVapdJWJd7aUE8PKKxvpAkWsVap1LI11FbJ09IzMK6t/c9Vy8WlppKmYMSlrg5mmMAYZjCGocF/AA "PowerShell – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~60~~ 58 bytes
```
procedure f(n)
write(!36*(1+.03*n)^(0to n/2-1)*100)&\z
end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNI0@Tq7wosyRVQ9HYTEvDUFvPwFgrTzNOw6AkXyFP30jXUFPL0MBAUy2miis1LwVJa25iZp6GJpcCEKSWpRZVKuRZ2RrVmNQYGiik5CtUg422VoCYralQC9YNAA "Icon – Try It Online")
Saved 2 bytes by replacing `(3|6)`(alternate 3 with 6) with `!36`. `!`generates the components of a data object. When applied to a number it generates its digits. In [`Unicon`](http://unicon.org/) - the descendent of `Icon` - `!n` generates the numbers in the range 1..n.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~57~~ 53 bytes
```
->n{n.times.map{|a|300*(1+a*2/n)*(1+0.03*n)**a%=n/2}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tVgvN7GguiaxxtjAQEvDUDtRy0g/TxPEMtAzMNYCMrUSVW3z9I1qa/8XKKRFG8VygSgTCGVoEPsfAA "Ruby – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 32 bytes
```
{s,2*s:(-1+x%2)((1+.03*x)*)\300}
```
[Try it online!](https://tio.run/##y9bNz/7/P82quljHSKvYSkPXULtC1UhTQ8NQW8/AWKtCU0szxtjAoPZ/moKhwX8A "K (oK) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
NθF²E⊘θI×׳⁰⁰⊕ιX⊕×θ·⁰³κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IQcNIUyGgKDOvRMM3sUDDIzGnLDUFKKmj4JxYXKIRkpmbWgwljQ0MdBQ885KLUnNT80qAqjI1gcoC8suBpiELQ1QX6ijoGRiDVGRrAoH1//@GBv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Outputs each list element on a separate line. Explanation:
```
Nθ
```
Input `n`
```
F²
```
Loop `i` twice, once for the small sizes, once for the large sizes.
```
E⊘θ
```
Loop `k` over half of the number of bottles, and implicitly output each calculation on its own line.
```
I×׳⁰⁰⊕ιX⊕×θ·⁰³κ
```
Calculate `300(i+1)(.03n+1)ᵏ` and cast the result to string.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 84 bytes
```
: x dup 2/ 0 do fdup f. fover f* loop ; : f dup s>f .03e f* 1e f+ 3e2 x 6e2 fnip x ;
```
[Try it online!](https://tio.run/##JYxBCoQwFEP3niJrRa06zELBy9hGBfGXzijevv7qJi8hIZTwX8qZCTH2uGAPj7aGgRUwBVagnC6AOTYRjwE9@Ox@I1GZzqWqUS3QuVY/vqrcV692iGoxhezzojEP4w0 "Forth (gforth) – Try It Online")
### Code Explanation
```
\ helper function to extract out common logic from the small and large numbers
: x \ start a new word definition
dup 2/ \ duplicate the input and divide by 2
0 do \ loop from 0 to n/2
fdup f. \ print the top of the floating point stack
fover f* \ multiple the top float stack value by the 2nd float stack value
loop \ end the loop
;
: f \ start a new word definition
dup s>f \ duplicate n and place a copy on the float stack
0.03e f* \ multiple by 0.03 (multiply by 3 and divide by 100)
1e f+ \ add 1 to get our increase multiplier
3e2 x \ print the smaller numbers by starting with 300
6e2 fnip x \ drop the remaining small number and print the large numbers from 600
; \ end word definition
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 23 bytes
```
Fk2Fb/Q2*300*hk^h*.03Qb
```
[Try it online!](https://tio.run/##K6gsyfj/3y3byC1JP9BIy9jAQCsjOy5DS8/AODDp/38zAA "Pyth – Try It Online")
Port of [@TFeld](https://codegolf.stackexchange.com/a/195739/90146)'s answer, which I was able to make decently concise. Cant help but feel like there's a more clever answer with Pyth but I wasnt able to find it.
## How it Works
```
Fk2Fb/Q2*300*hk^h*.03Qb
Fk2 - For k in range(2)
Fb/Q2 - For b in range(input/2)
*300*hk - 300 times k+1 times...
h*.03Q - 1 + 0.03 times input
^ b - The above to the exponent b
Implicitly prints the result
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
Two independent 40-byte answers: the first is an unnamed function, the second is a named function `g`, both taking one argument.
```
Table[300i(1+.03#)^j,{i,2},{j,0,#/2-1}]&
g@n_:=300#(1+.03n)^(#2-1)&~Array~{2,n/2}
```
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
x=scan();b=300*(1+0.03*x)^(0:(x/2-1));c(b,b*2)
```
[Try it online](https://tio.run/##K/r/v8K2ODkxT0PTOsnW2MBAS8NQ20DPwFirQjNOw8BKo0LfSNdQU9M6WSNJJ0nLSPO/ocF/AA)
[Answer]
# Java 8, 89 bytes
```
n->{for(int k=0,i;++k<3;)for(i=0;i<n/2;)System.out.println(Math.pow(.03*n+1,i++)*k*300);}
```
Port of [*@TFeld*'s Python 2 answer](https://codegolf.stackexchange.com/a/195739/52210), so make sure to upvote him.
[Try it online.](https://tio.run/##jY@xDoIwEIZ3n@LGlkKt4lbxDWBhNA61ghbwIFA1hvDsWJDRwaXJ/ffl/q@FeqqguJSjrlTXQawM9isAgzZrc6UzSKYR4FmbC2jickAqXTSs3NNZZY2GBBAiGDE49HndzlAZCd9Ixsp9KOkcRkKaPa63kqbvzmZ3Xj8sb1oHV0hiZW@8qV@Ei9BDtvENY9QrvVAIKodxKmwe58p1LZWzz93ZktS6G9fjCRT9qiLXZDs7AvyoWjYTtfuL2ojlw8P4AQ)
**Explanation:**
```
n->{ // Method with integer parameter and no return-type
for(int k=0,i;++k<3;) // Loop `k` in the range (0,3) (basically [1,2]):
for(i=0;i<n/2;) // Inner loop `i` in the range [0, i/2):
System.out.println( // Print with trailing newline:
Math.pow(.03*n // `n` multiplied by 0.03
+1 // incremented by 1
,i++) // to the power `i`
*k*300);} // multiplied by `k` and 300
```
[Answer]
# [Wren](https://github.com/munificent/wren), 79 bytes
```
Fn.new{|n|
for(a in[300,600])for(i in 1..n/2){
System.print(a)
a=a+a*n*0.03
}
}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xgq/DfLU8vL7W8uiavhistv0gjUSEzL9rYwEDHzMAgVhMkkgkUUTDU08vTN9Ks5gquLC5JzdUrKMrMK9FI1ORKtE3UTtTK0zLQMzDmquWq/Q8yVy85MSdHw0TzPwA "Wren – Try It Online")
# [Wren](https://github.com/munificent/wren), 81 bytes
TField answer turns out to be longer.
```
Fn.new{|n|
for(i in 0...n/2)for(a in[3,6])System.print(a*(1+0.03*n).pow(i)*100)
}
```
[Try it online!](https://tio.run/##FcyxDoIwEAbgnae48a6a8xDj5soLOBqHhpSkCf6QijZEfPYq6zd8OQWUt0/Uv9DRhUoLRcifFWvVj4kjRZCpKg5H2cD/4dbsz3e5Ls85PHRKETN7x/XO1BoH0WnMHMXVZlJ9yzZr54eBT1J@ "Wren – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~27~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_+3/L*Z*U}h[300]Uz
cUmÑ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=XyszL0wqWipVfWhbMzAwXVV6CmNVbdE&input=WzIsNCwxMF0KLW0KLVE)
```
_+3/L*Z*U} // function returning next element
h[300]Uz // runs the above func. U/2 times, starting from 300
cU®Ñ // concat the array obtained with the array multiplied * 2
```
Saved 4 thanks to @Shaggy
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~79~~ 74 ~~77~~ bytes
78 if the dash in compile arg is ignored.
Port of TField answer.
Increase in bytes is to comply with rules.
-5 bytes thanks to ceilingcat and bznein
```
b;c;f(a){for(b=0;++b<3;c=0)while(c<a/2)printf("%f ",pow(.03*a+1,c++)*b*300);}
```
[Try it online!](https://tio.run/##JcpLCoMwEADQtZ6iCIWZRJtouhs9TDJ0bCB@sAUX4tWbFrp6m8fNyJxzICYBj4csG4TBktahd8SDxf0Z0wO496bDdYvzW6C6yqWq12WHm3XK67ZmrVEF5axFOvPk4wx4lIUxAh1SWQjc/7S/UJ75w5L8@MpNmr4 "C (gcc) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
S+mDmo*300`^→*.03¹ŀ½
```
[Try it online!](https://tio.run/##yygtzv7/P1g71yU3X8vYwCAh7lHbJC09A@NDO482HNr7//9/QwMA "Husk – Try It Online") A port of the [standard answer](https://codegolf.stackexchange.com/a/195739).
] |
[Question]
[
### Challenge
Given an IPv4 `address` in dotted-quad notation, and an IPv4 `subnet` in [CIDR notation](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#IPv4_CIDR_blocks), determine if the `address` is in the `subnet`. Output a distinct and consistent value if it is in the `subnet`, and a separate distinct and consistent value if it is not in the `subnet`. The output values do not necessarily need to be truthy/falsey in your language.
### CIDR subnet notation brief primer
IPv4 network addresses are 32 bits in length, split into four groups of 8 bits for ease of reading. CIDR subnet notation is a ***mask*** of the specified number of bits, starting leftmost. For example, for a `/24` subnet, this means the right-most 8 bits of the address are available in that subnet. Thus two addresses that are separated by at most `255`, and have the same subnet mask, are in the same subnet. Note that valid CIDR have all the host-bits (the right hand side) unset (zeros).
```
xxxxxxxx xxxxxxxx xxxxxxxx 00000000
^--- subnet mask ---^ ^-hosts-^
```
For another example, a `/32` subnet specifies that *all* of the bits are the subnet mask, essentially meaning that only one host is allowed per `/32`.
```
xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
^--- subnet mask ---^
```
### Examples:
Using `True` for "in the subnet" and `False` for "not in the subnet" as output:
```
127.0.0.1
127.0.0.0/24
True
127.0.0.55
127.0.0.0/23
True
127.0.1.55
127.0.0.0/23
True
10.4.1.33
10.4.0.0/16
True
255.255.255.255
0.0.0.0/0
True
127.1.2.3
127.0.0.0/24
False
127.1.2.3
127.1.2.1/32
False
10.10.83.255
10.10.84.0/22
False
```
### Rules and Clarifications
* Since input parsing isn't the interesting point of this challenge, you're guaranteed to get valid IPv4 addresses and subnet masks.
* Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print the result to STDOUT or return it as a function result. Please state in your submission what values the output can take.
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# Python 3 (62 bytes)
Very straightforward:
```
from ipaddress import*
lambda i,m:ip_address(i)in ip_network(m)
```
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 250+31=281 bytes
```
(a,b)=>{Func<string,string>h=g=>string.Join("",g.Split('.').Select(x=>{var e=Convert.ToString(int.Parse(x),2);while(e.Length<8)e='0'+e;return e;}));a=h(a);var c=b.Split('/');b=h(c[0]);var d=int.Parse(c[1]);return a.Substring(0,d)==b.Substring(0,d);};
```
*Bytecount includes `using System;using System.Linq;`*
[Try it online!](https://tio.run/##nVTfa9swEH6u/4rDL7Gop9pJs5U5CozuB2wdFDK2h9IH2VESDU/qJDlNCf7bs5PtLA5bwxjGSL6777vzpzsV9kVhi11lpVrC7Mk68SPrf9AbqX5mQVCU3Fp4sw2s404W8L5SxcQ6g5Ex7Ndc63IKi0oB20U8zgmbbvuB7TJdsSWbtnv6UUsVhWG8pLOHUrpoQAeEzkQpChdtEL7mBgS71motjKNf9KyBRVI5esuNFdGGxEOSPa5kKSJBb4RautXkigg2SAbnIjPCVUaByGpCMs5WESeZ5yxYvs94MSBZjp7iLrlvnXN24C/uUrR2NJzOqrytPEriOWGe5ciS1dmuk6gT8FqX/m@kVpZ@EEoYWdC3sjFw89RJc3e/V88J6ywwUOLx/xgiAtvgbOvxe882TIevaIJPGsa/98nF8DKsY2cqUcfPIsbjY8joBCShlzSlo5FH@L0HpC@fBwzHY9p7EZZ0aZLThaV0SEd//sqCl/ZfIH6fXoyGpyCoVUKvRl1d3eelz3SABTVOxoORa@4EdKfeUoC55fNI59/x3EDHgP0EsjmYzo8LHrI@dDTJgrO2i9HV9TFMPMiHnjMIIcSQrhHRlgU1Jq/yskna5F5rOYfPHCfKp1poI3ixguhEG30ST195WYlbLs1fWxErb1uyKR7n0OpS0G9GOoE3Q1PsYYwhjKEvI2wbGTzeZ8L5itMxieHYmqL1Cq0hm3qC8N3mAcsU89dhP7IpMwYPD7maw1I79ONdc0QPPVbSE9dPP@pV17tf "C# (Visual C# Compiler) – Try It Online")
I wrote this in JS as soon as the challenge was posted, but Arnauld beat me to the punch with a much better answer, so here it is in C# instead.
Definitely a lot of room for golfing.
## Explanation:
The function consists of a sub-function called `h`:
```
h=g=>string.Join("",
g.Split('.').Select(x => {
var e = Convert.ToString(int.Parse(x), 2);
while (e.Length < 8) e = '0' + e;
return e;
}
);
```
This sub-function splits the IP Address on `.`, converts each number to a binary string, left-pads each string with `0` to be 8 bits long, then concatenates the strings into one 32-bit binary string.
This is immediately done in-place with `a=h(a);` on the given IP Address.
We then split the Subnet mask into an IP Address and a mask number with `c=b.Split('/');`
The IP Address component is also passed through our sub-function: `b=h(c[0]);` and the mask number is parsed to an integer: `var d=int.Parse(c[1]);`
Finally we take the first `d` bits of both binary strings (where `d` is the mask number) and compare them: `return a.Substring(0,d)==b.Substring(0,d);`
[Answer]
# Linux POSIX shell (with net-tools/iputils) (34 bytes non-terminating, 47 bytes terminating)
What is best suited to parse network masks and addresses than the network utilities themselves? :)
```
route add -net $2 reject;! ping $1
```
**Warning:** the script is potentially damaging to your Internet connectivity, please run with care.
**Input:** the script takes the tested IP address as first argument, and the tested subnet. as second argument.
**Output:** the script returns a truthy value (0) if the first argument of the script belongs to the subnet indicated in the second argument. Otherwise, it will never terminate.
**Assumptions:** the script must be run as a root user, in a *clean* environment (*i.e.*, no other blackhole route has been set by the administrator, and if a previous instance of the script has been run, the blackhole route it created has been removed). The script also assumes a "working Internet connection" (*i.e.*, a valid default route is present).
---
## Explanation:
We create a *blackhole* route to the specified subnet. We then test connectivity to the provided IP address by using *ping*. If the address doesn't belong to the subnet (and since we assume a properly set Internet connection), *ping* will try to send packets to that address. Note that whether this address actually responds does not matter, as *ping* will keep trying forever. Conversely, if the address does belong to the subnet, *ping* will fail with **ENETUNREACH** and return 2, and since we negated the command, the script will succeed.
---
## Example
Test whether 5.5.5.5 belongs to 8.8.8.0/24
```
$ sudo ./a.sh 5.5.5.5 8.8.8.0/24
PING 5.5.5.5 (5.5.5.5) 56(84) bytes of data.
[...runs forever...]
```
(Clean with `sudo ip route del 8.8.8.0/24` after running the command).
Test whether 5.5.5.5 belongs to 5.5.5.0/24:
```
$ sudo ./a.sh 5.5.5.5 5.5.5.0/24
connect: Network is unreachable
$ echo $?
0
```
(Clean with `sudo ip route del 5.5.5.0/24` after running the command).
Test whether 8.8.8.8 belongs to 5.5.5.0/24:
```
$ sudo ./a.sh 8.8.8.8 5.5.5.0/24
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=122 time=2.27 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=122 time=1.95 ms
[...runs forever...]
```
(Clean with `sudo ip route del 5.5.5.0/24` after running the command).
---
# 47-byte version if we disallow non-terminating scripts
```
route add -net $2 reject;ping -c1 $1;[ $? = 2 ]
```
As per @Grimy's comment, here's the version which always terminates, and returns 0 (truthy) if the address is in the subnet, and 1 (falsy) otherwise. We make *ping* terminate with the `-c1` flag which limits the number of sent packets to 1. If the address responded, *ping* will return 0, and if not, ping will return 1. Only if the address belongs to the blackholed subnet will *ping* return 2, which is thus what we test against in the last command.
[Answer]
# JavaScript (ES6), 82 bytes
Takes input as `(address)(subnet)`. Returns a Boolean value.
```
a=>s=>!([s,v]=s.split`/`,+v&&(g=s=>s.split`.`.map(k=v=>k=k<<8|v)|k>>32-v)(a)^g(s))
```
[Try it online!](https://tio.run/##hdDdboIwFAfw@z2F40LaTE@/YPPC9tIn8A5daBwyBwNiWZMlvjtSQjO3hNmmF//T/HJyzoe22hzOp6ZdVvVb1h1lp6UyUj2ixCzsXhowTXlqU5Iunux8jnLZf/oipPCpG1RIK1Uhi/V6dbH4Uigl@NJipPFrjgzG3aGuTF1mUNY5CpPt@at9/96H@OG2fkQB4y9A@8sC/BMo4VGA8cwdQmY9zqZcHP@BYoRTjkIEDIQYmAtOsWffbsrxOIab5zQdW9LBevcLhrsq2ejSTE3OgIP4Z3Jns7vQBUYEvwv7NVNYCT/AmCPXdcAedlc "JavaScript (Node.js) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~101~~ ~~92~~ 88 bytes
*-13 bytes from @gwaugh*
```
function($i,$r){[$r,$n]=explode('/',$r);return(ip2long($i)&~(1<<32-$n)+1)==ip2long($r);}
```
[Try it online!](https://tio.run/##lZDbisIwEIbv@xRFg0nYmubQ7i601TufwDtdRDS1hW4asq0Ioq9eG9EiskJlmIt/Zr456Uw38VRn2gVp0qS12lR5qRDIPWDwcQGMB9RPIg@6KLcSQR/aeGRkVRuFcs2LUu3aajw6IxbHgo@Bwh8MJ0mXa8tPTeQ4@7VZbetfjUCKIONfhLbGoOd2gvo8gBhHznBuaunITVa6g6UavILD8IkWvWhKAsKIEFfYCsuyzz4sD0Py4LYDvQ2nfTdnhBPx/9mzdfH3Dm0F8wXvR7ffpuRb3Be/6cDOf9VhOmku "PHP – Try It Online")
[Answer]
# PowerPC/PPC64 C, ~~116~~ 114 bytes
```
#include<stdio.h>
main(){unsigned u[4];char*p=u;for(;p<u+3;)scanf("%hhu%c",p++,u+3);return!((*u^u[1])>>32-p[-4]);}
```
(Tested on x86\_64 Ubuntu 18.04 using powerpc64-linux-gnu-gcc -static and qemu-user.)
The program takes the two lines on standard input, and as its exit code it returns 1 if the address matches and 0 if it does not. (So this does depend on the specification not requiring a truthy value for a match and a falsey value for a mismatch.) Note that if you're running interactively, you will need to signal EOF (`^D`) three times after entering the second line.
This relies on PowerPC being big-endian, and also on that platform returning 0 for right-shifting a 32-bit unsigned value by 32. It reads the octets into unsigned values one-by-one, along with the netmask length in another byte; then it takes the xor of the two unsigned 32-bit addresses and shifts out the irrelevant bits. Finally, it applies `!` to satisfy the requirement of returning only two distinct values.
Note: It *might* be possible to shave off two bytes by replacing `u+3` with `p` and requiring compilation with `-O0`. That's living more dangerously than I care to, though.
Thanks to Peter Cordes for the inspiration for this solution.
---
# More portable C, ~~186~~ ~~171~~ 167 bytes
Here I'll preserve a more portable version which runs 167 bytes.
```
#include<stdio.h>
main(){unsigned a,b,c,d,e,f,g,h,n;scanf("%u.%u.%u.%u %u.%u.%u.%u/%u",&a,&b,&c,&d,&e,&f,&g,&h,&n);return!(n&&((((a^e)<<8|b^f)<<8|c^g)<<8|d^h)>>32-n);}
```
This program takes the two lines on standard input, and returns exit code 1 if the address is in the subnet, and 0 if it isn't. (So this does rely on the specification not requiring a truthy value for matches and a falsey value for non matches.)
A breakdown of the core expression:
* `a^e`, `b^f`, `c^g`, `d^h` calculates the xor of the address and the mask byte-by-byte.
* `(((a^e)<<8|b^f)<<8|c^g)<<8|d^h` then combines them into a single unsigned 32-bit value by a Horner-like method.
* `...>>32-n` then shifts off the bits of the xor difference that are not relevant to the subnet mask (keeping in mind that `-` has higher precedence in C than `<<`)
* There is one gotcha, though: if n=0 then `~0U<<32` will give undefined behavior assuming `unsigned` is 32 bits (which it is on virtually all current platforms). On the other hand, if n=0 then any address will match, so `n&&...` will give the correct result (taking advantage of the short-circuiting behavior of `&&`).
* Finally, to meet the requirement that the output can only be one of two values, we apply `!` to output 0 or 1.
-15 bytes due to comments by ceilingcat and AdmBorkBork
-4 bytes due to comment by Peter Cordes
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é.○▄╗jF⌐§╥§I╓☻lw«ç┴║╫┼
```
[Run and debug it](https://staxlang.xyz/#p=822e09dcbb6a46a915d21549d6026c77ae87c1bad7c5&i=127.0.0.1+127.0.0.0%2F24%0A127.0.0.55+127.0.0.0%2F23%0A10.4.1.33+10.4.0.0%2F16%0A255.255.255.255+0.0.0.0%2F0%0A127.1.2.3+127.0.0.0%2F24%0A127.1.2.3+127.1.2.1%2F32%0A10.10.83.255+10.10.84.0%2F22&a=1&m=2)
It takes the input parameters space-separated on standard input.
Unpacked, ungolfed, and commented, it looks like this.
```
'/:/~ split on slash and push the last group back to the input stack
j{ split on space; for each group, run this code block
'./ split on period
{emVB|E evaluate integers and decode integer as base-256
;e|< peek from input stack and shift left
Vu/ integer divide by 2^32
F end of for-each
= two values left on stack are equal?
```
[Run this one](https://staxlang.xyz/#c=%27%2F%3A%2F%7E++++%09split+on+slash+and+push+the+last+group+back+to+the+input+stack%0Aj%7B+++++++%09split+on+space%3B+for+each+group,+run+this+code+block%0A++%27.%2F++++%09split+on+period%0A++%7BemVB%7CE%09evaluate+integers+and+decode+integer+as+base-256%0A++%3Be%7C%3C+++%09peek+from+input+stack+and+shift+left%0A++Vu%2F++++%09integer+divide+by+2%5E32%0AF++++++++%09end+of+for-each%0A%3D++++++++%09two+values+left+on+stack+are+equal%3F&i=127.0.0.1+127.0.0.0%2F24%0A127.0.0.55+127.0.0.0%2F23%0A10.4.1.33+10.4.0.0%2F16%0A255.255.255.255+0.0.0.0%2F0%0A127.1.2.3+127.0.0.0%2F24%0A127.1.2.3+127.1.2.1%2F32%0A10.10.83.255+10.10.84.0%2F22&m=2)
[Answer]
# x86-64 machine code function, ~~53~~ 48 bytes
changelog:
* -2 `jz` over the shift instead of using a 64-bit shift to handle the `>>(32-0)` special case.
* -3 return in ZF instead of AL, saving 3 bytes for a `setnz al`.
(See also [Daniel Schepler's 32-bit machine code answer](https://codegolf.stackexchange.com/questions/185005/im-in-your-subnets-golfing-your-code/185139#185139) based on this, which then evolved to use some other ideas we had. I'm including my latest version of that at the bottom of this answer.)
---
Returns ZF=0 for host *not* in subnet, ZF=1 for in subnet, so you can branch on the result with `je host_matches_subnet`
Callable with the x86-64 System V calling convention as
`bool not_in_subnet(int dummy_rdi, const char *input_rsi);` if you add in `setnz al`.
The input string contains both the host and network, separated by exactly 1 non-digit character. The memory following the end of the CIDR width must contain at least 3 non-digit bytes before the end of a page. (Shouldn't be a problem in most cases, like for a cmdline arg.) Daniel's 32-bit version doesn't have this limitation.
We run the same dotted-quad parse loop 3 times, getting the two IPv4 addresses, and getting the `/mask` as an integer in the high byte of a dword. (This is why there has to be readable memory after the `/mask`, but it doesn't matter if there are ASCII digits.)
**We do `(host ^ subnet) >> (32-mask)` to shift out the host bits** (the ones allowed to mismatch), leaving only the difference between the subnet and the host. To solve the `/0` special case where we need to shift by 32, we jump over the shift on count=0. (`neg cl` sets ZF, which we can branch on *and* leave as the return value if we don't shift.) Note that `32-mask mod 32 = -mask`, and x86 scalar shifts mask their count by `& 31` or `& 63`.
```
line addr machine NASM source. (from nasm -felf64 -l/dev/stdout)
num code bytes
1 %use smartalign
2
3 ;10.4.1.33 10.4.0.0/23 true
4 ;10.4.1.33 10.4.0.0/24 false
5
6 ;; https://codegolf.stackexchange.com/questions/185005/im-in-your-subnets-golfing-your-code
7 %ifidn __OUTPUT_FORMAT__, elf64
8 in_subnet:
9
10 00000000 6A03 push 3
11 00000002 5F pop rdi ; edi = 3 dotted-quads to parse, sort of.
12 .parseloop:
13
14 ;xor ebx,ebx ; doesn't need to be zeroed first; we end up shifting out the original contents
15 ;lea ecx, [rbx+4]
16 00000003 6A04 push 4
17 00000005 59 pop rcx ; rcx = 4 integers in a dotted-quad
18 .quadloop:
19
20 00000006 31D2 xor edx,edx ; standard edx=atoi(rdi) loop terminated by a non-digit char
21 00000008 EB05 jmp .digit_entry
22 .digitloop:
23 0000000A 6BD20A imul edx, 10
24 0000000D 00C2 add dl, al
25 .digit_entry:
26 0000000F AC lodsb
27 00000010 2C30 sub al, '0'
28 00000012 3C09 cmp al, 9
29 00000014 76F4 jbe .digitloop
30 ; al=non-digit character - '0'
31 ; RDI pointing to the next character.
32 ; EDX = integer
33
34 00000016 C1E308 shl ebx, 8
35 00000019 88D3 mov bl, dl ; build a quad 1 byte at a time, ending with the lowest byte
36 0000001B E2E9 loop .quadloop
37
38 0000001D 53 push rbx ; push result to be collected after parsing 3 times
39 0000001E FFCF dec edi
40 00000020 75E1 jnz .parseloop
41
42 00000022 59 pop rcx ; /mask (at the top of a dword)
43 00000023 5A pop rdx ; subnet
44 00000024 58 pop rax ; host
45 00000025 0FC9 bswap ecx ; cl=network bits (reusing the quad parse loop left it in the high byte)
49 00000027 F6D9 neg cl
50 00000029 7404 jz .all_net ; skip the count=32 special case
51
52 0000002B 31D0 xor eax, edx ; host ^ subnet
53 0000002D D3E8 shr eax, cl ; shift out the host bits, keeping only the diff of subnet bits
54
55 .all_net:
56 ; setnz al ; return ZF=1 match, ZF=0 not in subnet
57 0000002F C3 ret
58 00000030 30 .size: db $ - in_subnet
0x30 = 48 bytes
```
(not updated with latest version)
[Try it online!](https://tio.run/##dVVNb@M2EL3rV8yhW9uNJX9ukMYwetktkFux3UPRxTagxLHEmiIVkkrk/Hl3SMq2vEkNJJKH88H35s2YWYt1Lg@pYrY@Hj@0FsHWzDgmRamSBOizWcyzdbbIVisIb/NsPluu4PRxpsX/91uf/XZMWkySzQYq5xp7P5sVmmOp5S6zjhV77IqKqRKzQtezpxatE1rZ2eLu43z@cSbqVKj0oFuT2jZX6GzqQ4Uqo9HnSoR6jIf38eZNaytYxVfdABgu4J3PBpAOtrACrp1Dnj61jFtwGhpmLE7BauNA77IkCwapddNX2HTaAGDeTenvh6Rco1UjBwqR@2Q5wisaTV92wli3gRcEVBzaBmwldo6wgG4duApBG1EKxSQUWjlUzsZqEhlVK7opfDN5d7P@foEJsL4AJahF9x5Qb97CGgRlLdFYegE2hJ1k/v8AYQBIBBFC3r3JR51TnBnuHbbMaTEmjifg48GhqQkDZYb8QFWUViknWA6o0SYk/7emy2bB@EgozSHpv8ULeBdRt7K/AMkqmBjn/sHlFJhMruJjjNTc5uGN5BAiyHU0HwVTUTcn06/xEtQYGNSNVJPD9vrGrCBEkJ4TbeDLpwfim7j0raMO@84p7AbuWe/5@dNfxHvPeiTWVh5X0A7cBUutn/0jp5tx@ZZqrxEqISzR6dAnixVF87zuYRPr5/4lQ22YoTo30Rq0DAZtK12vz0JLiYXvmKS@xR5xLMI9uYhsqVfP1nkQkreq28CsZnYPMGZRzY5O9c4L7UUbPrmK4DEizu3VCYsnlbbRntsX1gT5B3tB/UFHCfeQC2epmsHWhk5QSc9CjzDQIpHIo0aS3v1xJcoq0DihjXSROSWdQrpaRpYePNtq7wMMjiytgZqwGFHsQYo9xl7sKHC1TBX45yJVU8hphmt2IDq1kgcQOxr0kUHwnPRC@Xm1@A3ga4WK9FL6UKUdeCzZULb@NqtlsHi3YBlOJSAj8SC/EAX/DJm0lemZnFJkBFXoVrktQbQNFsJvGEYcibCpTiaPicHtOiVio@56yaLz3WdyIKXTpiYhPbWC1ATYkfQJ@BK4oCNVOHhmktymAaVfBKamHHOYhZ3gl2JIb@jamRWveB@T8xx@onk7b/XkWEqdU@QjrR3jkviII/@BI/0YIPzx9cufD39/pomKkxdmyljhN6ZtbtZwc3L5ZfE9rH7rVz8z5fO3aPDgu571H6Lv3kSb62iy/E7hBstWMkpzd5vermHsYVPKKPyCSTnAdKlDEzb1HR1YfOOWq0Uk/2BD6Pu/YHT6iB2twdLothlfCoz7y01gkhyP7/5E/wc "Assembly (nasm, x64, Linux) – Try It Online")
including a `_start` that calls it on `argv[1]` and returns an exit status.
```
## on my desktop
$ ./ipv4-subnet "10.4.1.33 10.4.0.0/24" && echo "$? : in subnet" || echo "$? : not in subnet"
not in subnet
$ ./ipv4-subnet "10.4.1.33 10.4.0.0/23" && echo "$? : in subnet" || echo "$? : not in subnet"
in subnet
```
It works fine if you pass a command line arg containing a newline instead of a space. But it has to be *instead*, not as well.
---
# x86 32-bit machine code function, 38 bytes
Do 9 integer -> uint8\_t parses and "push" them on the stack, where we pop them off as dwords or use the last one still in CL. Avoids reading past the end of the string at all.
Also, `dec` is only 1 byte in 32-bit mode.
```
72 in_subnet:
73 00000000 89E7 mov edi, esp
74 00000002 51 push ecx
75 00000003 51 push ecx ; sub esp,8
76 .byteloop:
77
78 00000004 31C9 xor ecx,ecx ; standard ecx=atoi(rdi) loop terminated by a non-digit char
79 ; runs 9 times: 8 in two dotted-quads, 1 mask length
80 00000006 EB05 jmp .digit_entry
81 .digitloop:
82 00000008 6BC90A imul ecx, 10
83 0000000B 00C1 add cl, al
84 .digit_entry:
85 0000000D AC lodsb
86 0000000E 2C30 sub al, '0'
87 00000010 3C09 cmp al, 9
88 00000012 76F4 jbe .digitloop
89 ; RDI pointing to the next character.
90 ; EDX = integer
91
92 00000014 4F dec edi
93 00000015 880F mov [edi], cl ; /mask store goes below ESP but we don't reload it
94 00000017 39E7 cmp edi, esp
95 00000019 73E9 jae .byteloop
96
97 ;; CL = /mask still there from the last conversion
98 ;; ESP pointing at subnet and host on the stack, EDI = ESP-1
99
100 0000001B 5A pop edx ; subnet
101 0000001C 58 pop eax ; host
102
103 0000001D 31D0 xor eax, edx ; host ^ subnet
104 0000001F F6D9 neg cl ; -mask = (32-mask) mod 32; x86 shifts mask their count
105 00000021 7402 jz .end ; 32-n = 32 special case
106 00000023 D3E8 shr eax, cl
107 .end:
108 ; setz al ; just return in ZF
109 00000025 C3 ret
110 00000026 26 .size: db $ - in_subnet
0x26 = 38 bytes
```
Test caller
```
113 global _start
114 _start:
115 00000027 8B742408 mov esi, [esp+8] ; argv[1]
116 0000002B E8D0FFFFFF call in_subnet
117 00000030 0F95C3 setnz bl
118 00000033 B801000000 mov eax, 1 ; _exit syscall
119 00000038 CD80 int 0x80
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
ṣ”/ṣ€”.Vḅ⁹s2+Ø%BḊ€ḣ€ʋ/E
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGubqg6imNUCWXtjDHa2PGncWG2kfnqHq9HBHF1D84Q6Q7Klufdf/Oo8a5ijo2ikAleocbj866eHOGSpcD3dvOdwOVBH5/7@hkbmegZ6hnqmxPoQJhPpGxlwwjqkpmriBnglQuTFQOYgFEjU04zIyNdVDwvoGUA0GYHMM9Yz0UIw3QRMGsQz1jY1ApgORhTHYECjHBKTDCAA "Jelly – Try It Online")
Monadic link that takes a the address and subnet separated by a slash and returns 1 for true and 0 for false.
Thanks to @gwaugh for pointing out a flaw in the original - it failed to ensure the binary list was 32 long.
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint -MSocket=:all -p`, 72 bytes
```
sub c{unpack N,inet_aton pop}<>=~/(.*)\/(.*)/;$_=c($_)-&c($1)<2**(32-$2)
```
[Try it online!](https://tio.run/##JcZNC8IgAIDhe7/CwwiV/Jhr0MfsH9SlayBOJGSi0twp6qdnUpf3eZN9@L6UeRmBeS4haTOBy8YFm5XOMYAU02s4yTeDFKPbr@zYKGlgoxBZV1o0CIxhJ0gjUCmcctrR/ervjontJ6bsYpgLOfeUt7w6ursLuc41mslmedDeF5K@ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'/¡`U‚ε'.¡b8jð0:JX£}Ë
```
Takes the subnet before the address.
[Try it online](https://tio.run/##yy9OTMpM/f9fXf/QwoTQRw2zzm1V1zu0MMki6/AGAyuviEOLaw93//9vaGSuZwCC@kYmXDCOIQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/h5ulir6SQmJeioGQPZj5qmwRkFv9X1z@0MCH0UcOsc1vV9Q4tTLLIOrzBwMor4tDi2sPd/3X@GxqZ6xmAoL6RCReMY8iFJGwM55iaYhM3BIsb6JmAhQ3NIGxDPWNjLgOoWgMuI1NTPSTMhWGtoZ6RnjGcZahvbIQsDLTFQM/CBKTcCMYzBhkEAA).
**Explanation:**
```
'/¡ '# Split the first subnet-input by "/"
` # Push both values separated to the stack
U # Pop and store the trailing number in variable `X`
‚ # Pair the subnet-IP with the second address-input
ε # Map both to:
'.¡ '# Split on "."
b # Convert each integer to binary
8j # Add leading spaces to make them size 8
ð0: # And replace those spaces with "0"
J # Join the four parts together to a single string
X£ # And only leave the first `X` binary digits as substring
}Ë # After the map: check if both mapped values are the same
# (which is output implicitly as result)
```
[Answer]
# R 120 bytes
a function - I pasted ".32" to first term
`w=function(a,b){f=function(x)as.double(el(strsplit(x,"[./]")));t=f(paste0(a,".32"))-f(b);sum(t[-5]*c(256^(3:0)))<2^t[5]}`
and just for fun:
`require("iptools");w=function(a,b)ips_in_cidrs(a,b)[[2]]`
which is 56 bytes
[Answer]
# [PHP](https://php.net/), ~~75~~ ~~73~~, 71 bytes
```
<?=strtok($argv[2],'/')==long2ip(ip2long($argv[1])&1+~1<<32-strtok(_));
```
A fork of [@Luis felipe De jesus Munoz](https://codegolf.stackexchange.com/questions/185005/im-in-your-subnets-golfing-your-code#185011)'s answer, as a standalone taking input from command line args. Outputs `'1'` for Truthy, `''` (empty string) for Fasley.
```
$ php ipsn.php 127.0.0.1 127.0.0.0/24
1
$ php ipsn.php 127.1.2.3 127.0.0.0/24
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKSoJD9bQyWxKL0s2ihWR11fXdPWNic/L90os0Ajs8AIxIRKG8Zqqhlq1xna2Bgb6UI1xmtqWv///9/QyFzPAAgN4SwDfSMTAA "PHP – Try It Online")
-2 bytes borrowing [@Christoph](https://codegolf.stackexchange.com/questions/185005/im-in-your-subnets-golfing-your-code#185011)'s little trick for `strtok()`. His answer is still shorter though!
[Answer]
# x86 assembly function, ~~49~~ 43 bytes
This is mostly posted to satisfy Peter Cordes's request for the revised version I created. It can probably go away once/if he incorporates it into his answer.
This function expects `esi` to point to an input string, with the address and subnet parts separated either by a space or a newline character, and the return value is in the ZF flag (which by definition has only two possible values).
```
1 %use smartalign
2
3 ;10.4.1.33 10.4.0.0/23 true
4 ;10.4.1.33 10.4.0.0/24 false
5
6 ;; https://codegolf.stackexchange.com/questions/185005/im-in-your-subnets-golfing-your-code
7 in_subnet:
8
9 ;xor ebx,ebx ; doesn't need to be zeroed first; we end up shifting out the original contents
10 ;lea ecx, [rbx+4]
11 00000000 6A09 push 9
12 00000002 59 pop ecx ; ecx = 9 integers (8 in two dotted-quads,
13 ; 1 mask length)
14
15 00000003 89E7 mov edi, esp
16 00000005 83EC0C sub esp, 12
17 .quadloop:
18
19 00000008 31D2 xor edx,edx ; standard edx=atoi(rdi) loop terminated by a non-digit char
20 0000000A EB05 jmp .digit_entry
21 .digitloop:
22 0000000C 6BD20A imul edx, 10
23 0000000F 00C2 add dl, al
24 .digit_entry:
25 00000011 AC lodsb
26 00000012 2C30 sub al, '0'
27 00000014 3C09 cmp al, 9
28 00000016 76F4 jbe .digitloop
29 ; al=non-digit character - '0'
30 ; RDI pointing to the next character.
31 ; EDX = integer
32
33 00000018 4F dec edi
34 00000019 8817 mov [edi], dl
35 0000001B E2EB loop .quadloop
36
37 0000001D 59 pop ecx ; /mask (at the top of a dword)
38 0000001E 5A pop edx ; subnet
39 0000001F 58 pop eax ; host
40 00000020 0FC9 bswap ecx ; cl=network bits (reusing the quad parse loop left it in the high byte)
41
42 ; xor cl, -32 ; I think there's some trick like this for 32-n or 31-n, but maybe only if we're masking to &31? Then neg or not work.
43
44 00000022 31D0 xor eax, edx ; host ^ subnet
45 ; xor edx, edx ; edx = 0
46 00000024 F6D9 neg cl
47 00000026 7402 jz .end
48 00000028 D3E8 shr eax, cl ; count=32 special case isn't special for a 64-bit shift
49 .end:
50 0000002A C3 ret
51 0000002B 2B .size: db $ - in_subnet
```
And the x86 Linux wrapper part:
```
53 global _start
54 _start:
55 0000002C 8B742408 mov esi, [esp+8] ; argv[1]
56 00000030 E8CBFFFFFF call in_subnet
57 00000035 0F95C0 setnz al
58 00000038 0FB6D8 movzx ebx, al
59 0000003B B801000000 mov eax, 1 ; _exit syscall
60 00000040 CD80 int 0x80
```
-6 bytes due to suggestion from Peter Cordes to return the value in ZF.
[Answer]
# Java ~~215 211 207 202 200 199 198 190~~ 180 bytes
```
Long k,c;boolean a(String i,String s){return(b(i)^b(s))>>32-k.decode(s.split("/")[1])==0;}long b(String i){for(c=k=0l;c<4;k+=k.decode(i.split("[./]")[3+(int)-c])<<8*c++);return k;}
```
Outputs `true` for truthy and `false` for falsy.
Note: This uses `long` instead of `int` for the potential right shift of 32.
[Try it online!](https://tio.run/##rdBNT8MgGAfw@z4F6QnsRumbLum6oyc96W2ZCaWorAyaQmdM089eqdZFL@oWQwgPhPx4/uzogS50zdWurAYmqTHglgrVDTdaPYFqzrJCa8mpAhTe2Ua4QzGfCoO6htu2UbCAAj0U0CC0XsfRosIlZ7rk0GBTS2GhF3hoE25RnpOsl6NcHDXUPeoGsrzKiczYKskqPz8C4hPY4GDrjNiHQlm0YFu0Wi0vmO@j7KMHUGX9ULeFFAwYS61bDlqUYO/STG9ttgUC3WzMByjIgeIv72EhymZ3r8byPdatxbW7a6WCFFPohdEVJm6E3vxYkyBKPAR84AHzrFtZgoKD@6bl3h@gNP0uxWdK4X9IBCcOiuMRGuvRCS9PdqI0xV@m08jUFDkrXYgjHP/24ddUmpOksQ6DODpDct9N8DKewk3bZOzrB62f9cMb "Java (OpenJDK 8) – Try It Online")
Saved 1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
Saved 10 bytes thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
≔⪪S/θ≔I⊟θζ⊞θSUMθ÷↨I⪪ι.²⁵⁶X²⁻³²ζ⁼⊟θ⊟θ
```
[Try it online!](https://tio.run/##VY7NCoMwEITvPoV42oCNf60XT63toQdB8AmCigY0Jiax0JdPE/XSy7LszH4z7UjWdiGTMXcp6cCg4RNV8GZcq0atlA2AQj@IAjsFKrzTVRKpoF44CGSFrxVqLUcQof/3ae8V4eUyz4R1h6qedKNdDw8i@wNzJFKbggNHS2@5nfXy6VdIQ7@iTEvIUheDHLG2bAUvockkzw7OvndBhTFJjK84xnGU5N6@JzjLzGWbfg "Charcoal – Try It Online") Link is to verbose version of code. Takes the subnet as the first parameter and and outputs `-` only if the address lies within the subnet. Explanation:
```
≔⪪S/θ
```
Split the subnet on `/`.
```
≔I⊟θζ
```
Remove the mask and cast it to integer.
```
⊞θS
```
Push the address to the array.
```
UMθ÷↨I⪪ι.²⁵⁶X²⁻³²ζ
```
Split both addresses on `.`, convert them to integers, interpret as base 256, and discard the masked bits.
```
⁼⊟θ⊟θ
```
Compare the two values.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 26 bytes
```
Ëq'/
ËÎq. ˰¤ù8ì¯Ug1,1Ãr¶
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVJt&code=y3EnLwrLznEuIMuwpPk4w6yvVWcxLDHDcrY&input=WwpbIjEyNy4wLjAuMSIsIjEyNy4wLjAuMC8yNCJdLApbIjEyNy4wLjAuNTUiLCIxMjcuMC4wLjAvMjMiXSwKWyIxMjcuMC4xLjU1IiwiMTI3LjAuMC4wLzIzIl0sClsiMTAuNC4xLjMzIiwiMTAuNC4wLjAvMTYiXSwKWyIyNTUuMjU1LjI1NS4yNTUiLCIwLjAuMC4wLzAiXSwKWyIxMjcuMS4yLjMiLCIxMjcuMC4wLjAvMjQiXSwKWyIxMjcuMS4yLjMiLCIxMjcuMS4yLjEvMzIiXSwKWyIxMC4xMC44My4yNTUiLCIxMC4xMC44NC4wLzIyIl0KXQ)
-3 bytes thanks to @Shaggy!
Input is an array with 2 elements `[address, subnet]`. Transpiled JS below:
```
// U: implicit input array
// split elements in U on the / and
// save back to U using a map function
U = U.m(function(D, E, F) {
return D.q("/")
});
// map the result of the previous operation
// through another function
U.m(function(D, E, F) {
return D
// get the address portion of the / split
// value and split again on .
.g().q(".")
// map each octet through another function
.m(function(D, E, F) {
// convert the octet to a base 2 string
// left padded to a length of 8
return (D++).s(2).ù(8)
})
// join the base 2 octets
.q()
// take the left bits of the joined octets
// determined by subnet size
.s(0, U.g(1, 1))
})
// at this point, the intermediate result
// contains 2 masked values, reduce
// using === to check for equality
.r("===")
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 187 bytes
```
a=>{var b=a.Select(x=>x.Split(".").SelectMany(g=>Convert.ToString(int.Parse(g.Split("/")[0]),2).PadLeft(8)).Take(int.Parse(a[1].Split("/")[1])));return b.First().SequenceEqual(b.Last());}
```
I can definitely golf this down more.
[Try it online!](https://tio.run/##ZY9Ba4MwHMXv@RSdpwRimsS6FZxexgqDDspa2EE8RJd2oRLXGNsO8bN36uwmlCTw3i95/0ey0s1KdVlUOnssrVF6Fyc4LYo82oYXEUb1UZhJGgqylrnMLDyH0Zmsv3JloUMcNOBXob/hLoyeCn2UxpJNse5nQaUtWQlTSri7pqYOimmCMEftzcdSbi2cI0Q2Yi9Hz0XMknGCJQihwEhbGT1JyUKZ0sKu/lBJncnnQyVymJKl6DAKmksATp8ql/BFk5WUe4juQpchUIPfX05E@CbbeqUlRDgdmQC8G2Vlb5yaYpfTpmbYZX5T88bBAqd4C7U8xUnd6qZtA82F8QdC28XAVdEpn/0Z3x9zbzDsllMya7E3qI6ye8B9n4wOoEOA9mFGOPFua/9xp9jU493Mds@9fshgZl2C/wA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 134 bytes
```
a=>a.Select(x=>x.Split('.','/').Take(4).Aggregate(0L,(y,z)=>y<<8|int.Parse(z))>>32-int.Parse(a[1].Split('/')[1])).Distinct().Count()<2
```
[Try it online!](https://tio.run/##ZY5fS8MwFMXf8yl0L00gvUvSVgdrC6IIwh7ECT6MPWQ1q2ElkzZjf2o/e01n5wYjCff8Dpxzk1V@Vun2eWOyuLKlNvlsThfrdZEuk1YmqYSpKlRm8S5JdzD9LrTFHnjUG3oE3uVK4ZDAQ56XKpdWYTaheE8PJEn3cTz60cbCqywrhQ@EpGkg/LMjZ3x@KnRljgiBJ11Zbdw6Ao/rjXEzFu0Ybb90ofCLgVelVpjcJj4nqEZ/H76RyZuSnxNtFCZ0cQFj9FFqq44wqBn1BWtqTn0eNbVoBlTSBV1io7azee10Q1yiabm4B@YORyfFhiL8hyi69IMe@LXPIHR20KvO5XdIRBFcPMT6ADuGOQgIrtee7U7xYSC6TndHwbGkh7BLiF8 "C# (Visual C# Interactive Compiler) – Try It Online")
LINQ statement that takes a 2-element string array as input in `[address, subnet]` format.
Each dotted quad is converted into 32 bits of a long using bit manipulation. The bits are right shifted by the subnet size and elements are compared for equality.
There were a couple of C# answers at the time that this answer was posted, but none that used pure bit manipulation.
```
// a: input array containing address and subnet
a=>a
// iterate over input elements
.Select(x=>x
// split element on . and /
.Split('.','/')
// the subnet will have 5 elements,
// we only want the parts before the /
.Take(4)
// use an aggregate function to convert dotted quad to 32 bits
.Aggregate(0L,(y,z)=>y<<8|int.Parse(z))
// shift bits of aggregate to the right
>>
// shift amount determined by subnet size
32-int.Parse(a[1].Split('/')[1])
)
// test for equality by checking if number
// of unique values is equal to 1
.Distinct()
.Count()<2
```
[Answer]
# **Ruby (48 bytes)**
```
require 'ipaddr'
lambda{|a,m|IPAddr.new(m)===a}
```
] |
[Question]
[
Write a program or function that takes in positive integers `a`, `b` and `c`, and prints or returns `a/b` to `c` decimal places, using the operations +-\*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no `round`).
This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-\*/% on
[unsigned] integers.
### Examples
* `print(1,2,1)` would print `0.5`
* `print(1,2,2)` would print `0.50`
* `print(13,7,27)` would print `1.857142857142857142857142857`
* `print(2,3,1)` would print `0.6`
* `print(4,5,7)` would print `0.8000000`
* `print(4,5,1)` would print `0.8`
* `print(9999,23,1)` would print `434.7`
* `print(12345613,2321,89)` would print if your Language has 32 bit unsigned `5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466`
The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~17 13 11 19~~ 14 bytes
Input in the form `b, a, c`.
Saved 5 bytes thanks to *Grimy*.
```
‰`¹+I°*¹÷¦'.sJ
```
[Try it online!](https://tio.run/##AS8A0P9vc2FiaWX//@KAsGDCuStJwrAqwrnDt8KmJy5zSv//MjMyMQoxMjM0NTYxMwo4OQ "05AB1E – Try It Online")
[Answer]
## Haskell, 87 bytes
```
(a#b)c|s<-show$div(a*10^c)b,l<-length s-c,(h,t)<-splitAt l s=['0'|l<1]++h++['.'|c>0]++t
```
Usage example: `(13#7)27` -> `"1.857142857142857142857142857"`.
23 bytes to handle the `c==0` case and using a leading zero instead of things like `.5`.
How it works: multiply `a` with `10^c`, divide by `b`, turn into a string, split where the `.` must be inserted, join both parts with a `.` in-between and fix the edge cases.
[Answer]
# [Perl 6](https://perl6.org), ~~58 57 55~~ 48 bytes
```
{(($^a.FatRat/$^b*10**$^c).Int.FatRat/10**$c).base(10,$c)}
```
```
{(Int($^a.FatRat/$^b*10**$^c).FatRat/10**$c).base(10,$c)}
```
```
{base Int($^a.FatRat/$^b*10**$^c).FatRat/10**$c: 10,$c}
```
```
{base ($^a*10**$^c div$^b).FatRat/10**$c: 10,$c}
```
What is fairly annoying is that it could be shortened to just `{($^a.FatRat/$^b).base(10,$^c)}` if it was allowed to round to the nearest value.
## Explanation:
```
# bare block lambda with 3 placeholder parameters 「$^a」, 「$^b」 and 「$^c」
{
(
(
# create an Int containing all of the digits we care about
$^a * 10 ** $^c div $^b
).FatRat / 10**$c # turn it into a Rational
).base( 10, $c ) # force it to display 「$c」 digits after the decimal point
}
```
[Answer]
# Perl, 55 bytes
Includes +3 for `-p`
Give a and b on one line on STDIN, c on the next
```
division.pl
1 26
38
^D
```
`division.pl`:
```
#!/usr/bin/perl -p
eval'$\.=($_/$&|0)."."x!$\;$_=$_%$&.0;'x(/ .*/+<>)}{
```
the `$_/$&` is a bit arguable. I Actually ***want*** an integer division there but perl doesn't have that without loading special modules. So it's temporarily a non-integer which I then immediately truncate (using `|0`) so I end up with the integer an integer division would give. It could be rewritten as `($_-$_%$&)/$&` in order to not even temporarily have a non-integer value (it would internally still be a float though)
[Answer]
# JavaScript (ES6), ~~55~~ 50 bytes
```
f=(a,b,c,d=".")=>~c?(a/b|0)+d+f(a%b*10,b,c-1,""):d
```
`(a/b|0)` performs float division but immediately casts to an integer. Please let me know if this is not allowed.
[Answer]
# PHP, 187 Bytes
works with strings for the numerator which can be int values greater then `PHP_INT_MAX`
```
list(,$n,$d,$c)=$argv;$a=str_split($n);while($a){$n.=array_shift($a);if($n>=$d||$r)$n-=$d*$r[]=$n/$d^0;}if(!$r)$r[]=0;if($c)$r[]=".";while($c--){$n*=10;$n-=$d*$r[]=$n/$d^0;}echo join($r);
```
I have no other chance then 13/7 is shorten to 1.8571428571429 and I reach so not the test case with 27 decimal places
This way 36 Bytes is not allowed
```
<?=bcdiv(($z=$argv)[1],$z[2],$z[3]);
```
[Answer]
# Pyth - ~~21~~ ~~19~~ ~~18~~ ~~16~~ 14 bytes
Will be looking over the input format, that can prolly save a bunch.
```
j\.c`/*E^TQE]_
```
[Test Suite](http://pyth.herokuapp.com/?code=j%5C.c%60%2F%2aE%5ETQE%5D_&test_suite=1&test_suite_input=1%0A1%0A2%0A2%0A1%0A2%0A10%0A13%0A7&debug=0&input_size=3). (P.S. the 27 one doesn't finish online, so I did 10 instead).
[Answer]
## JavaScript (ES6), ~~64~~ ~~62~~ 59 bytes
*Saved 2 bytes thanks to ETHproductions.*
The included division always results in an integer.
```
f=(a,b,n,s)=>~n?f((q=(a-a%b)/b,a%b*10),b,n-1,s?s+q:q+'.'):s
console.log(f(13,7,27))
```
[Answer]
# Java 7, 105 bytes
```
import java.math.*;String c(int...a){return new BigDecimal(a[0]).divide(new BigDecimal(a[1]),a[2],3)+"";}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/AFu999)
```
import java.math.*;
class M{
static String c(int... a){
return new BigDecimal(a[0]).divide(new BigDecimal(a[1]), a[2], 3)+"";
}
public static void main(String[] a){
System.out.println(c(1, 2, 1));
System.out.println(c(1, 2, 2));
System.out.println(c(13, 7, 27));
System.out.println(c(2, 3, 1));
System.out.println(c(4, 5, 7));
System.out.println(c(4, 5, 0));
System.out.println(c(9999, 23, 0));
System.out.println(c(12345613, 2321, 89));
}
}
```
**Output:**
```
0.5
0.50
1.857142857142857142857142857
0.6
0.8000000
0
434
5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
```
[Answer]
# Ruby, 67 bytes
```
->(a,b,c){('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/,'\1.\2')}
```
if I make it a function to execute the test cases above
```
def print(a,b,c); ('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/, '\1.\2'); end
=> :print
print(1,2,1) # would print 0.5
=> "0.5"
print(1,2,2) # would print 0.50
=> "0.50"
print(13,7,27) # would print 1.857142857142857142857142857
=> "1.857142857142857142857142857"
print(2,3,1) # would print 0.6
=> "0.6"
print(4,5,7) # would print 0.8000000
=> "0.8000000"
print(4,5,1) # would print 0.8
=> "0.8"
print(9999,23,1) # would print 434.7
=> "434.7"
print(12345613,2321,89) # would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
=> "5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466"
"('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/, '\1.\2')".length
=> 52
```
[Answer]
## Racket 203 bytes
```
(let*((s(~r(/ a b)#:precision c))(sl(string-split s "."))(s2(list-ref sl 1))(n(string-length s2)))
(if(< n c)(begin(for((i(- c n)))(set! s2(string-append s2 "0")))(string-append(list-ref sl 0)"."s2))s))
```
Ungolfed:
```
(define (f a b c)
(let* ((s (~r(/ a b)#:precision c))
(sl (string-split s "."))
(s2 (list-ref sl 1))
(n (string-length s2)))
(if (< n c)
(begin
(for ((i (- c n)))
(set! s2 (string-append s2 "0")))
(string-append (list-ref sl 0) "." s2))
s )))
```
Usage:
```
(f 7 5 3)
(f 1 2 1)
(f 1 2 2)
(f 13 7 27)
```
Output:
```
"1.400"
"0.5"
"0.50"
"1.857142857142857142857142857"
```
Other method (not valid answer here):
```
(real->decimal-string(/ a b)c)
```
[Answer]
# q, 196 bytes
```
w:{((x 0)div 10;1+x 1)}/[{0<x 0};(a;0)]1;{s:x 0;m:x 2;r:(10*x 1)+$[m<0;{x*10}/[-1*m;a];{x div 10}/[m;a]]mod 10;d:1#.Q.s r div b;($[m=-1;s,".",d;$[s~,:'["0"];d;s,d]];r mod b;m-1)}/[c+w;("";0;w-1)]0
```
To run: set a, b, c first.
[Answer]
# Rust, 114 bytes
```
fn print(mut a:u32,b:u32,c:u32){let mut p=||{print!("{}",a/b);a=a%b*10};p();if c>0{print!(".")}for _ in 0..c{p()}}
```
**test code:**
```
fn main() {
print(1, 2, 1); println!(""); // should print 0.5
print(1, 2, 2); println!(""); // should print 0.50
print(13, 7, 27); println!(""); // should print 1.857142857142857142857142857
print(2, 3, 1); println!(""); // should print 0.6
print(4, 5, 7); println!(""); // should print 0.8000000
print(4, 5, 0); println!(""); // should print 0
print(9999, 23, 0);println!(""); // should print 434
print(12345613,2321,89); println!("\n"); // 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
}
```
[Answer]
# PHP, 89 bytes
```
list(,$a,$b,$c)=$argv;for($o=intdiv($a,$b).'.';$c--;)$o.=intdiv($a=10*($a%$b),$b);echo$o;
```
intdiv() is introduced in php 7 so it requires that. php 7.1 would allow me to change the list() to [] and so would save 4 bytes.
use like:
```
php -r "list(,$a,$b,$c)=$argv;for($o=intdiv($a,$b).'.';$c--;)$o.=intdiv($a=10*($a%$b),$b);echo$o;" 1 2 1
```
[Answer]
# C#, 126 bytes
```
(a,b,c)=>{var v=a*BigInteger.Parse("1"+new string('0',c))/b+"";return v.PadLeft(c+1,'0').Insert(Math.Max(1,v.Length-c),".");};
```
Full program with test cases:
```
using System;
using System.Numerics;
namespace DivisionOfNotSoLittleNumbers
{
class Program
{
static void Main(string[] args)
{
Func<BigInteger,BigInteger,int,string>f= (a,b,c)=>{var v=a*BigInteger.Parse("1"+new string('0',c))/b+"";return v.PadLeft(c+1,'0').Insert(Math.Max(1,v.Length-c),".");};
//test cases:
Console.WriteLine(f(1,2,1)); //0.5
Console.WriteLine(f(1,2,2)); //0.50
Console.WriteLine(f(13,7,27)); //1.857142857142857142857142857
Console.WriteLine(f(2,3,1)); //0.6
Console.WriteLine(f(4,5,7)); //0.8000000
Console.WriteLine(f(4,5,1)); //0.8
Console.WriteLine(f(9999,23,1)); //434.7
Console.WriteLine(f(12345613,2321,89)); //5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
Console.WriteLine(f(2,3,1)); //0.6
Console.WriteLine(f(4,5,2)); //0.80
}
}
}
```
Integer division is implemented. Numbers of any size can be used, due to the `BigInteger` data type (the import `System.Numerics` is required). The digit-count parameter `c` is restricted to 2^31-1, however it should provide more than enough digits.
[Answer]
# Groovy (~~78~~ ~~77~~ 42 Bytes)
```
{a,b,n->Eval.me(a+'.0g').divide(b, n, 1)}
```
## Explanation
`Eval.me(a+'.0g');` - Convert from integer input to BigDecimal input. In groovy BigDecimal notation is double notation with an appended G or g. I could've also used the constructor `new BigDecimal(it)` but this saved a byte.
`.divide(b, n, 1)` - Divide by b with n precision, rounding mode half-up.
Try it here: <https://groovyconsole.appspot.com/script/5177545091710976>
[Answer]
## Batch, 122 bytes
```
@set/as=%1/%2,r=%1%%%2
@set s=%s%.
@for /l %%a in (1,1,%3)do @set/ad=r*10/%2,r=r*10%%%2&call set s=%%s%%%%d%%
@echo %s%
```
[Answer]
# Mathematica, 50 bytes
```
StringInsert[ToString@Floor[10^# #2/#3],".",-#-1]&
```
Unnamed function of three arguments (which are ordered `c`, `a`, `b` to save a byte somewhere), which returns a string. It multiplies `a/b` by `10^c`, takes the greatest integer function, then converts to a string and inserts a decimal point at the appropriate spot. Too bad the function names aren't shorter.
[Answer]
**Python 3, 62 Bytes**
```
a,b,c=map(int,input().split());print("{:.{1}f}".format(a/b,c))
```
[Try It Here](https://repl.it/Ip20)
**\*Note**: *repl.it* uses an older ver of *Python 3*, which requires all field indices to be specified, meaning `"{:.{1}f}"` will be `"{0:.{1}f}"` instead, making it *63 bytes* in *repl.it*
**How to use**
Enter all three values with spaces in-between. i.e. An input of `1 2 1` would give a result of `0.5`
**Explanation**
`input().split()`: Gets user input and splits it into a list with a separator of (space)
`a,b,c = map(int,XX)`: Maps the variables into the values specified by the user with an int type
`"{:.{1}f}".format(a/b,c)`: Formats a string to display the division result and substitutes `{1}` with `c` to set the decimal place of the displayed string
`print(XX)`: prints the string supplied
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
lambda a,b,c:(lambda s:s[:-c]+"."+s[-c:])(str(a*10**c//b))
```
[Try it online!](https://tio.run/##LcnBDkAgGADgVzGnvxQqjDZPgkNlxkZadfH0cXD89rkn7rcVaRvndKpLrypTRBMj4VeQYZLULEVe5kWYqJELghA9KMxqjE1VaYSS84eNsAHjomk7JggXnJF@@OoF "Python 3 – Try It Online")
This is precise to the specified number of decimals as long as `a * 10 ** c` isn't too large.
I tried Python 2 to shorten the `str(...)` to ``...`` but Python 2 inserts an `L` at the end if it's too large so checking for that would take way more bytes than it's worth.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ä·oαì█↕▬AS¥é▼
```
[Run and debug it](https://staxlang.xyz/#p=84fa6fe08ddb121641539d821f&i=1,1,2%0A2,1,2%0A27,13,7%0A1,2,3%0A7,4,5%0A1,4,5%0A1,9999,23%0A89,12345613,2321%0A3,1,20&a=1&m=2)
Arguments are accepted in `c a b` order.
[Answer]
# C, 67 bytes
```
h(a,b,i){int j=!i;for(;printf(j++?"%u":"%u.",a/b),i--;a=10*(a%b));}
```
[Try it online!](https://tio.run/##lZLdcsIgEIXv8xRrZtKBuraEaG1Kaa/7DG0vSEwUrdEhSW80z24Rm9jfGWWAOTB8y@6BdDBN091uRhQmqOlGFxXMZU@LfGWIWBu7zsm833/0g9q/s9OVj@o6oagHA6FkyC6JChJKRbNbKl0Q6rkQsEBQkmFihxYefAbyn4oyMxVwWK9KXen3DOx@Ns0MFPUyyUz5AD4Vef5WlzPCqFjIMlWFBYMJBBMf4ULZkdA2M/@lsOc90DlJpGTb7aInOd0cr1vXFWTGqGrlTpqsqk0BTDQe7CvUkgl9HzLR72sKHtjWwTkJanSdymdbtTNItE51Gby6wM2xxj84zlhLOvmd/RcNkWMIsEedpALgDJQfUX4OGuEY@dihrTwR5RgdspyRTp6IDnGE4wPayTNQfkTPqTW2DXmE7nm@LE61ikfD0Y11iUc8xNvYefZr72ew7hN6zS6MAUIe8zgOPwA "C (gcc) – Try It Online")
Some previous version I think had a bug in read memory out of assigned to the program...Thanks to ceilingcat and for all...
] |
[Question]
[
# Challenge
Determine how many integer lattice points there are in an [ellipse](https://en.wikipedia.org/wiki/Ellipse)
$$\frac{x^2}{a^2} + \frac{y^2}{b^2} \leq 1$$
centered at the origin with width \$2a\$ and height \$2b\$ where integers \$a, b > 0\$
.
**Input**
The Semi-major \$a\$ and Semi-minor \$b\$ axes.
**Output**
Number of *interior* and *boundary* points.
# Example
Ellipse plot showing \$a=5\$ and \$b=3\$ with \$41\$ blue interior and \$4\$ red boundary points.
[](https://i.stack.imgur.com/aLrCv.png)
**Input**
\$5\$,\$3\$
**Output**
\$41\$,\$4\$
# Test Cases
| a | b | Interior | Boundary |
| --- | --- | --- | --- |
| 5 | 3 | 41 | 4 |
| 5 | 15 | 221 | 12 |
| 8 | 5 | 119 | 4 |
| 8 | 1 | 15 | 4 |
| 9 | 15 | 417 | 4 |
| 15 | 15 | 697 | 12 |
| 20 | 20 | 1245 | 12 |
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
function(a,b,z=c(a,b)^-2%*%t(expand.grid(-a:a,-b:b)^2))c(sum(z<1),sum(z==1))
```
[Try it online!](https://tio.run/##HclNCoAgEEDhfadoE8zEGGkEIXmVQC2jRRb9QHR5S1ffg3cEl/csD@729lo2D5oMvcpGcWCiKIsLpmfXfqzmYxmBaamJGflfgWjhvFd4e46UQimOGBy01GAW4W20o4SoSdQYPg "R – Try It Online")
May have issues due to numerical precision. Naive algorithm: loop over all lattice points in the \$2a \times 2b\$ grid centered around the origin, and count the points with the requisite relationship.
# [R](https://www.r-project.org/), 85 bytes
```
function(a,b,p=a^2*b^2,z=c(b,a)^2%*%t(expand.grid(-a:a,-b:b)^2))c(sum(z<p),sum(z==p))
```
[Try it online!](https://tio.run/##HclNCoMwEEDhfU/hRpiRidgpQhFzlcBMbIoLY/AHipdP1dX34C05FL0pctij38Y5gpBSsuK4Usd0WA9Kgo7Lqtzg80sSh/q7jAMY6YSMdnpORA/rPsHRJ6Q7rE2IOUBLL3xcPNvLN91wQ9xg/gM "R – Try It Online")
More precise.
[Answer]
# [R](https://www.r-project.org), ~~68~~ 66 bytes
```
\(a,b,y=b/a*(a^2-(-a:a)^2)^.5)c(B<-sum(!y%%1)-1,sum(y%/%1+.5)-B)*2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAVbhaWlJWm6FjedYjQSdZJ0Km2T9BO1NBLjjHQ1dBOtEjXjjDTj9Ew1kzWcbHSLS3M1FCtVVQ01dQ11QJxKVX1VQ22gtK6TppYR1CTLNA1THWNNBS4QbWgKZljowGhDTSBlCRIH0oamUIaRgY6RgSbEgAULIDQA)
Total points of boundary plus interior is (up to precision error) $$\sum\_{-a\le x \le a} \# \left\{ y \in \mathbb Z : |y| \le (b/a) \sqrt{a^2-x^2} \right\}$$
$$ = \sum\_{-a \le x \le a} \left( 2 \left\lfloor (b/a) \sqrt{a^2-x^2} \right\rfloor + 1 \right)$$
\$B\$ counts boundary points, subtracting over-counted cases \$|y| = a\$.
`y=b*(1-(-a:a/a)^2)^.5` actually fails the test cases due to precision errors.
[Floating point tricks in R](https://codegolf.stackexchange.com/a/269339/17360)
-2 bytes by rearranging some terms, credit Giuseppe.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
rNŒp²÷²§’ṠĠẈṖ
```
[Try it online!](https://tio.run/##y0rNyan8/7/I7@ikgkObDm8/tOnQ8kcNMx/uXHBkwcNdHQ93Tvv/cOdiy4e7ew4tebhjsVHYo6Y1h7Y@3LnP@lHDHAVdO4VHDXOtD7cDBVS4Hu7ecrgdKB/5/78ppzGniSGnCZcpp6Epp5GRIaehEZcFJ5BnaAkUteA0BImbcFmCKUNzINMQrNTM0hyk1MiAE4gMjUyAgkYA "Jelly – Try It Online")
A monadic link that takes a pair of integers and returns a pair of integers. Works perfectly for all of the examples, but there is a theoretical risk of floating point inaccuracy.
## Explanation
```
rN | Range from a to -a and b to -b
Œp | Cartesian product
² | Squared
÷² | Divide by a ** 2, b ** 2
§ | Sum inner lists
’ | Subtract 1
Ṡ | Signs
Ġ | Indices of like items in groups
Ẉ | Lengths
Ṗ | Remove last (those outside the border)
```
## Alternative [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
rNŒp²Uḋ²_²P$ṠĠẈṖ
```
[Try it online!](https://tio.run/##y0rNyan8/7/I7@ikgkObQh/u6D60Kf7QpgCVhzsXHFnwcFfHw53T/j/cudjy4e6eQ0se7lhsFPaoac2hrQ937rN@1DBHQddO4VHDXOvD7UABFa6Hu7ccbgfKR/7/b8ppzGliyGnCZcppaMppZGTIaWjEZcEJ5BlaAkUtOA1B4iZclmDK0BzINAQrNbM0Byk1MuAEIkMjE6CgEQA "Jelly – Try It Online")
This version only uses integer arithmetic so should always be accurate even for large inputs (though like the other answer has \$O(m \times n)\$ complexity).
[Answer]
# Google Sheets, 84 bytes
Assuming \$a\$ is in A1 and \$b\$ is in B1.
```
=SORT(COUNTIF(SEQUENCE(2*A1+1,1,-A1)^2/A1^2+SEQUENCE(1,2*B1+1,-B1)^2/B1^2,{"<1",1}))
```
~~92 bytes
=SORT(COUNTIF(MAKEARRAY(2*A1+1,2*B1+1,LAMBDA(x,y,SUMSQ((x-A1-1)/A1,(y-B1-1)/B1))),{"<1",1}))~~
~~93 bytes
=LET(a,A1,b,B1,SORT(COUNTIF(SEQUENCE(2*a+1,1,-a)^2/a^2+SEQUENCE(1,2*b+1,-b)^2/b^2,{"<1",1})))~~
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 64 bytes
```
f(a,b)=[1+vecsum(v=2*Vec(qfrep([a,0;0,b]^2,a^2*b^2)))-t=v[#v],t]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY_BCoJAFEV_5WGbGXuCMyEUYfQVbR5jjKIhWEw2DvYtbdxE39Tf5Giu7uXcy3vc18fotj5fzDC8O1tF2--xYhpznpJYu7J4dFfmUhmeyoLdq7Y0jDTG-xhzlUnUmQzzTHLOI5s6WjmFVv3vNNqY5sl6iA5g2vpmWU9CQYAQQE9ydD4JoJo4ToxzBKIEYTMCryLxZouwqG_SbgnEXFF8_rls-AE)
Yes, PARI/GP has a built-in for this.
>
> `qfrep(q,B,{flag=0})`: vector of (half) the number of vectors of norms from `1` to `B` for the integral and definite quadratic form `q`. If flag is `1`, count vectors of even norm from `1` to `2B`.
>
>
>
[Answer]
# Google Sheets, 88 bytes
```
=frequency(sort(sequence(2*A1+1,1,-A1)^2/A1^2+sequence(1,2*B1+1,-B1)^2/B1^2),{1-9^-9,1})
```
Put \$a\$ in cell `A1`, \$b\$ in cell `B1` and the formula in cell `C1`. The output is in cells `C1:C2` with residue in `C3`.
Generates integer \$x\$ and \$y\$ sequences for lattice points in a rectangle that bounds the ellipse and calculates the distance from origin at each point. Uses [frequency()](https://support.google.com/docs/answer/3094286) to find points within and on the ellipse. The residue shows points within the bounding rectangle but outside the ellipse. Uses [sort()](https://support.google.com/docs/answer/3093150) but as an array enabler only.
Earlier proof-of-concept version to confirm that this is easily solvable in a spreadsheet (**160 bytes** golfed, 279 ungolfed):
```
=let(a, A1, b, B1, r,
map(sequence(2 * a + 1, 1, -a), lambda(x,
map(sequence(1, 2 * b + 1, -b), lambda(y, let(
d, x^2 / a^2 + y^2 / b^2,
ifs(
d = 1, 2,
d < 1, 1,
1, 0
)
)))
)),
{ countif(r, 1), countif(r, 2) }
)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ýí€ûnR**`âOIPns-.±{Åγ¦
```
Outputs the pair in reversed order, so \$[boundaryCount, interiorCount]\$.
[Try it online](https://tio.run/##AS8A0P9vc2FiaWX//8Odw63igqzDu25SKipgw6JPSVBucy0uwrF7w4XOs8Km//9bNSwzXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf8Pzz289lHTmsO784K0tBIOL/KvDMgr1tU7tLH6cOu5zYeW/df5Hx1tqmMcqwMkDU2BlIUOhDQEkpYQIUOolJGBjpFBbCwA).
**Explanation:**
```
Ý # Convert both values in the (implicit) input-pair to [0,value]-ranged
# lists
í # Reverse each inner list
€û # Palindromize each inner list
n # Square each inner value
R # Reverse the list
** # Multiply each to the (implicit) input-pair twice
` # Pop and push both lists separately to the stack
â # Create all possible pairs using the cartesian product
O # Sum each inner pair together
IP # Push the product of the input-pair
n # Square that
s- # Subtract the sums of the list from that value
.± # Get the sign (-1 if negative; 0 if 0; 1 if positive) of each
{ # Sort these -1s, 0s, and 1s
Åγ # Then run-length encode it, pushing list [-1,0,1] (which we won't use)
# and the list of lengths
¦ # Remove the first value (for the amount of -1s)
# (after which the resulting pair is output implicitly)
```
[Try it online with step-by-step debug lines.](https://tio.run/##bZK/bhNBEMZ7nmLkhiS6Q44QDRFKQYFSRIlCGUVi7RvfjbQ3e9k/tgIdEo9BQ0EFBUKiobN7HoIXMTO758SRKG/v@37ffDvrgpkRbreTMx5SfAmT6tX61@mTyWvHS/QRZi52EB0YuJ5WS2MT3tTecIsNWArZsPlcLFcojoCAZt4BMaN/kHwvkktjiRvvenr/X93fj982v4v07W0y/pEop6uKH@fFDmEw5MEtMiio5qpozpONNNi7wskEbaMW0sJ1NsYVzTP56Ghs79FEBGMtDC4EmtkSETRDzJJ6n/Ru82WcOPX746pe/1@M1VPocm7IxRoYvGvSPI7EvXHUdHbJO@gseiOyvQILuUDxUI4PdRG@wVjw1DIc1MdAC2BsTaQlnsBUP6cnkI@lEunxoWY/cJX2bP1jzHU@8/oKDDfgE9cWuZXHgDx3jcwbKxikE3Erj0NvQ2kZFOBg1ZFgVwiN46cRUpAw5ex0hZULfNh8@vNzt9HeLctCF3LZcdfX@Xxmepc42@vj@wySnSQvejYWPAZZ@KFi119Pt9vrF9Xzm38)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
NθNηFX×η…·±θθ²FX×θ…·±ηη²⊞υ⁻X×θη²⁺ικI⟦ΣEυ›ι⁰№υ⁰
```
[Try it online!](https://tio.run/##dY4xC8IwEEb3/oqMF4igQifHDtKhpaibOMQSm2Cbtkmu/vx4EQRRXA4efO9xrZauHWUfY2knDDUOV@Vg5rvskzXxbXQMmvFBeDKD8qAFK23bozeLOkjbKahVJ4MiW7CZ09lyzn60@Z@mydBvrUGvAQWrjEX/7evXSLCGKmAEu3NODzbO2ACF9AHORxygklMq7J2iuku7NU/5YkTaYcILeTHm2SaPq6V/Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Similar approach to @vengy's C answer.
```
NθNη
```
Input `a` and `b`.
```
FX×η…·±θθ²
```
Loop `x` from `-a` to `a` inclusive.
```
FX×θ…·±ηη²
```
Loop `y` from `-b` to `b` inclusive.
```
⊞υ⁻X×θη²⁺ικ
```
Calculate the squared distance in from the perimeter, multiplied by `a²b²`.
```
I⟦ΣEυ›ι⁰№υ⁰
```
Output the number of points for where this is positive and the number for where this is zero.
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~135~~ 106 bytes
Saved 29 bytes thanks to @vengy
---
Here `a` and `b` both are positive integers.
Golfed version. [Try it online!](https://tio.run/##hY7NT4NAEMXv/BVztGUaPkwTP7oX9EKipjcP69IMdJFN2l1TBi0h/O2INT0Zy2nmzXu/vNkTV3pPbAoahlLSBvONuhPPbtvstOxSEWIiwh4fnXw1XMmOxTGLA8pivx1nnsU9pqXkVYSp759WISJMfF8phd0RF4TUY9fiIse8V/ddikmvhgfXWH4iHov12hnLtSi9q/mL@8LWNVCQhabWwJWpoWxswcZZYAfFDzeeNex@Yfg40VC6A5Bt4c17N5/aAo1qC/l85v2tkkuEawVBsD6M8p9AtFQXAjcIU350yb@dKogmX4hDhDg8J4Zv)
```
f[a_,b_]:=Module[{I=0,B=0},Do[With[{t=x^2/a^2+y^2/b^2},If[t<1,I++,If[t==1,B++]]],{x,-a,a},{y,-b,b}];{I,B}]
```
Ungolfed version. [Try it online!](https://tio.run/##hVJNb4JAEL3zK97JtLINQmNiPzj1ZNI2Nj3StVlgURLZbWBpIYbfTkdRG02VZJOZN/PezOzsZsIsZSZMGom2fdKlMs/CEJIznSpTBOJzqoxcyJwh3Lsc9z5edFyuZGABayLKPNV5J4GPEZGpVCzy@i/WMOLSeS@zjQqYJsGu4FtQcQwGOMCaM2w5W1Y19xwx92CjJi8k7xEuw3Fb2z5Izoh8f6M6Hsy2@U7UWc62Zl0x3AgG0TCsa/JDEjaU4g/dJU7ufFq2sXh7NXzVP6zWJSKhUBYSZpkWSEoVmVQrGI1os28KS6y6peOrW1eicwhV48NapN9SQRCKEQ6vrX@eaMxwy@E4s5zgGYI75hcIE4a@vHspf9fXwO0dwaM/4432jPYX)
```
CountLatticePoints[a_Integer, b_Integer] := Module[
{interiorPoints = 0, boundaryPoints = 0},
Sum[
If[IntegerQ[x] && IntegerQ[y],
If[x^2/a^2 + y^2/b^2 < 1, interiorPoints++,
If[x^2/a^2 + y^2/b^2 == 1, boundaryPoints++]
]
],
{x, -a, a}, {y, -b, b}
];
{interiorPoints, boundaryPoints}
]
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 110 bytes
```
lambda a,b,q=2:[sum(0>(t:=x*x*b*b+y*y*a*a-a*a*b*b)or(q:=q+(t<1))*0for x in range(-a,a)for y in range(-b,b)),q]
```
[Try it online!](https://tio.run/##XctBDsIgEAXQvadgydBpAm2a1Ea8iLoYotUmlhbEpJwerRvRxSze//PnGG6TrdvZp16zY7rTaM7ECA06XXWHx3Pkcs9DpxexCCNMEUUUJKh832qYPHeddgUPOwUgZD95trDBMk/2euElIcGaxSwzaADQndLsBxt4zxusATZfqSZji79Smba/r@pvWkmsZN5/xukF "Python 3.8 (pre-release) – Try It Online")
Consider four quarter
[Answer]
# [Ruby](https://www.ruby-lang.org/), 87 bytes
```
->a,b{*r=0,0,w=a*b;(k=*-w..w).product(k).map{|x,y|r[w*w<=>x*x+y*y]+=1[x%a+y%b]};r[0,2]}
```
[Try it online!](https://tio.run/##LcqxCoMwEADQvV/RRdDLGaJFKNjzR8INSYuLlIagJEH99ijY7Q3PLzblkXI9GLQreFKoMJAB25cTQR2kDJV0/vdZ3nM5VfJr3LpFTJvXAcKLhghRJEgsqNGxMCIVlvfea4Ut79ndR93hg28Xmu7SE/9oz6Y4Hw "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 96 bytes
```
lambda a,b:divmod(sum((4j,4,0)[cmp(a*b,abs(x/a*a+x%a*b*1j))]for x in range(a*b+1))-2*a-2*b+1,1j)
```
[Try it online!](https://tio.run/##XY3LDoIwEEX3fEU3Jp0yKkVIFMOXqIupgEJ4NAUNfj226gJZTHLP5Mxc/RruXRtORXqeampURoxQJVn5bLqM94@G86jCCAM4XRvNSSgk1fNxS4L8cWVZyArgUnSGjaxsmaH2ljvPlwDrUJAdm9FaU5YXTGtTtgPXkNieVB8/yNyKNianGtBl9c2e99MLHuMOYI4ynvMeFyjneFjYcnkeBhgGf4Z7ML0B "Python 2 – Try It Online")
Returns boundary,interior. Test bed borrowed from @l4m2 and modified. Testing code prettifies integer valued complex numbers into actual integers.
## How?
Uses complex numbers for two purposes:
1. abs with complex argument for Euclidean norm
2. as a means of 2d vector summation without importing any libraries.
Special Python 2 semantics of div and mod for complex operands is used to recover real and imaginary parts after summing.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
hMlBPx1Sm.acVdQ*Fm}_
```
[Try it online!](https://tio.run/##K6gsyfj/P8M3xymgwjA4Vy8xOSwlUMsttzb@//9oUx3jWAA "Pyth – Try It Online")
Takes input in the form `[a, b]` and outputs as `[interior, boundary]`.
### Explanation
```
# implicitly assign Q = eval(input())
hMlBPx1Sm.acVdQ*Fm}_ddQ # implicitly add ddQ
m Q # map lambda d over Q
}_dd # inclusive_range(-d, d)
*F # cartesian product of the two ranges
m # map over lambda d
cVdQ # vectorized divide d by Q
.a # vector size
S # sort
x1 # get list of indices where 1 appears
P # remove the last element
lB # bifurcate over length
hM # map to head, this will get the first element for the list and add one for the integer
```
[Answer]
# C (gcc), ~~133~~ 121 bytes
*-12 thanks to @Neil*
```
i,x,y,l,B;e(a,b){i=B=0;for(x=-a;x<=a;x++)for(y=-b;y<=b;y++)l=a*a*b*b-x*x*b*b-y*y*a*a,l?i+=l>0:B++;printf("%d %d\n",i,B);}
```
[Try it online!](https://tio.run/##PYrLCsIwFET3foUIhTxuIK0U1DQK@Q43SV8EYpUqmFD668ZYqJs5w5mpWV/XMVrwEMCBEi3SYPBkpZJcdPcRecm08JVMQSn@mSCZEaGSKZJxUhNNDDHME78wkJCMBnexVLozPylKxWO0w6tDu6zZZs112IEFhcUcb9oOCE@bFpWwx2JhXi7lACvzhcd1yP@XgkPBU5vjp@6c7p@Rvb8)
[Answer]
# APL+WIN, 65 bytes
Prompts for a followed by b and outputs boundary the interior:
```
((1+2×a)++/2×⌊n)-⎕←2ׯ1++/0=1|n←⎕×(1-(((⌽⍳a),0,⍳a)*2)÷(a←⎕)*2)*.5
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4aGobbR4emJmtra@kD6UU9XnqYuUA1QBZB7aL0hUNzA1rAmDygAFD48XcNQV0ND41HP3ke9mxM1dQx0wLSWkebh7RqJEEUgnpae6X@gBVz/07hMuYy5QKShKZCy4IKQhkDSEiJkCJUyMgAiAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Uiua, ~~43~~ 41 bytes
Returns the number of interior points on the top of the stack, and the number of boundary points on the bottom.
```
∩/+<1:=1./+ⁿ2÷:-⍉☇1⇡+1×2..⊂
```
[Try It](https://uiua.org/pad?src=0_8_0__4oipLys8MTo9MS4vK-KBvzLDtzot4o2J4piHMeKHoSsxw5cyLi7iioI1IDMK)
```
∩/+<1:=1./+ⁿ2÷:-⍉☇1⇡+1×2..⊂
-⍉☇1⇡+1×2..⊂ # generates a point array spanning the [-a,a]×[-b,b] rectangle,
# we also leave a copy of a and b to divide the coordinates later
÷: # divide each x coordinate by a and each y by b
ⁿ2 # square each coordinate
/+ # sum each coordinate pair
. # create a copy of the sums so we can check two conditions (interior and boundary)
=1 # boundary check
<1: # the interior point check
∩/+ # since the checks return boolean masks, sum them to get a point count.
```
[Answer]
# [Perl 5](https://www.perl.org/), 94 bytes
```
sub{($a,$b,@r)=@_;map{//;$r[1+($b*$b*$'*$'+$a*$a*$_*$_<=>$a*$a*$b*$b)]++for-$b..$b}-$a..$a;@r}
```
[Try it online!](https://tio.run/##bZLRasIwFIbv@xSHLWytrbp0OmezjrK7XexusAuRkmAdhZlIWhkiPnuXxCQdajjQLzn/@ZvkZFvJn2m3ayr4rJo2yz6ErEiA1nnX7NghRDRBLClklBcl2dDtYTwmSC5wHCI20HGvIkZ0oKNU8ZK/2pnOR8s4Xgs5RGw0Quw4RFR9KSnksSPBZg9Fq34KOYQBqHELFOxgDt55W8laSM1vYsdXVO6NeAHTxGoeHUywI8UAy@RciR2laS/Faa98dqt9CZ4n1zy9El@YnynnF4IJnl319AIPT/PZ1X2mD@4gDnA66ffslREJ1P2H5p6jg1na7G1X0S/lbVlzC0yoJqOSeJHO6MU7tD5VRKdc3Zgc@Hq4@VIEtW1V5jNazNXUkLG4@efBhPPQdPJgtsWZz@jHINTUkPc4BivBq1Ifq@bfpPsD "Perl 5 – Try It Online")
Spaceship operator `<=>` comes in handy.
[Answer]
# APL(NARS), 40 chars
```
+/¨0(>,=)⊂{+/¯1,2*⍨⍵÷k}¨,(⊂k+1)-⍳1+2×k←⎕
```
How to use and test:
```
+/¨0(>,=)⊂{+/¯1,2*⍨⍵÷k}¨,(⊂k+1)-⍳1+2×k←⎕
⎕:
5 3
41 4
{+/¨0(>,=)⊂{+/¯1,2*⍨⍵÷k}¨,(⊂k+1)-⍳1+2×k←⍵}¨(5 3)(5 15)(8 5)(8 1)(9 15)(15 15)(20 20)
41 4 221 12 119 4 15 4 417 4 697 12 1245 12
```
[Answer]
# Excel VBA, 93 Bytes
An immediate window function that takes input \$a\$ from `[A1]` and \$b\$ from `[B1]` of the activesheet object and outputs to the immediate window console.
Assumes a clean console environment. Maybe re-run after executing `u=0:v=0`.
*Note: This solution has been restricted to 32-Bit versions of Excel VBA as [`^` is the `LongLong` type literal](https://codegolf.stackexchange.com/a/143645/61846) in 64-Bit versions*
```
For x=[-A1]To[A1]:For y=[-B1]To[B1]:t=x^2/[A1^2]+y^2/[B1^2]:u=u-(t<1):v=v-(t=1):Next y,x:?u,v
```
### Commented Version
```
For x=[-A1]To[A1] '' iter over x axis
For y=[-B1]To[B1] '' iter over y axis
t=x^2/[A1^2]+y^2/[B1^2] '' calc lattice point sumsq
u=u-(t<1) '' incr. internal point count if needed
v=v-(t=1) '' incr. boundary point count if needed
Next y,x '' loop
?u,v '' print point counts
```
] |
[Question]
[
I define mousetails's sequence as follows:
* If the nth element of the sequence is q, then n+1 must appear q times in the sequence
* The sequence is weakly monotonically increasing (eg. no lower number may follow a higher number)
* f(1)=1
I'll show an example of how this works:
* the first element is 1
* after the 1, come 1 2s
* then 2 3s, since f(2)=2
* then three 4s and three 5s, since f(3)=f(4)=3
* then four 6s, four 7s, four 8s, five 9s, five 10s, and five 11s
* six 12s, six 13s six 14s, six 15s, seven 16s etc.
Thus, it comes out to be
```
1,2,3,3,4,4,4,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,9,10,10,10,10,10,11,11,11,11,11,12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,14,14,...
```
Sequence rules apply, you may either:
* Given n, output the nth element of the sequence
* Given n, output the first N terms
* Output the sequence infinity
Either 0 or 1 based indexing is acceptable.
[Answer]
# JavaScript (ES6), 29 bytes
This is based on the recurrence formula given for [A001462](https://oeis.org/A001462), which is a very similar sequence found by [bsoelch](https://codegolf.stackexchange.com/users/118682/bsoelch).
Returns the \$n\$-th term, 1-indexed.
```
f=n=>n<3?n:1+f(n-f(f(n-1)-1))
```
[Try it online!](https://tio.run/##FctNCoAgEEDhq7hrpBqIaBNZdI5oIaXR30xoBJ3eDB5v92360X5y63XnxLMJwSpSLTVlR3WRWqDcwv9CxmSYmDwfBg9eYEDE3jn9QlVJ3M3rQY546gtIqFZEJVIREW68EiRZEv0H "JavaScript (Node.js) – Try It Online")
### Formula
$$\begin{cases}a(1)=1\\
a(2)=2\\
a(n)=1+a(n-a(a(n-1)-1)),\:n\ge 3\end{cases}$$
---
# JavaScript (ES6), 36 bytes
This is my original answer. Longer but faster.
Returns the \$n\$-th term, 0-indexed.
```
f=(n,i=0,k)=>i<n?f(n,i+f(k),-~k):-~k
```
[Try it online!](https://tio.run/##FctBDoIwEEbhq7Bj/lgmbtgYi/EcxkUDrSnFGdIaEzZevcLmJd/ize7rypjj@ulEJ19rsCQm2rNJsEO8yi0cPgVKMN0v4bKnjipFF8@LvujBzPec3UZ9D05@K4Qnv91K0tih2XeAZ41CrWmB@gc "JavaScript (Node.js) – Try It Online")
### Method
We don't need to store the sequence explicitly. We just have to keep track of the current position \$i\$ and current value \$k\$, and use recursion to get the previous values.
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
i = 0, // i = current index
k // k = current value, minus 1
) => //
i < n ? // if i is less than n:
f( // do a recursive call:
n, // pass n unchanged
i + f(k), // add f(k) to i
-~k // increment k
) // end of recursive call
: // else:
-~k // return k + 1
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
{(x#&0 1,)/x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqFBWM1Aw1NHUr6jl4kpTMDQwMAAARaYFWg==)
A function returning the first `x` values of the sequence.
`(...)/x` Iterate until convergence, starting with `x` (could be any non-negative integer):
`0 1,` Prepend 0 and 1 to the current list.
`&` Where. For boolean vectors this gives the indices of 1s, for positive integers each index is repeated by the value.
`x#` Take the first `x` values from the resulting list.
[Answer]
# [Python](https://www.python.org), ~~40~~ 38 bytes
-1 thanks to @Mukundan314, additional -1 thanks to @JonathanAllan
```
f=lambda x:x*(x<3)or-~f(x-f(f(x-1)-1))
```
A port of [@Arnauld's Javascript solution](https://codegolf.stackexchange.com/a/269235/92727).
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31dJscxJzk1ISFSqsKrQ0KmyMNfOLdOvSNCp00zRApKEmEGlCVeuk5RcpZCpk5ikUJealp2oY6igYG2hacSkUFGXmlQDVZ2rqKKTmpdiqK6hD9cBsAgA)
# [Python](https://www.python.org), 62 bytes
```
def f():
yield 1
for i,x in enumerate(f()):yield from[i+2]*x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY37VJS0xTSNDStuBQqM1NzUhQMuRTS8osUMnUqFDLzFFLzSnNTixJLUjWAajStIErSivJzozO1jWK1KqCmgLWANUCMKijKzCvRqNAB6k-xVVdQ14Sog9kKAA)
[Answer]
# [Python](https://www.python.org), 42 bytes
```
a=[i:=1]
for x in a:print(x);a+=[i:=i+1]*x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tRJtozOtbA1judLyixQqFDLzFBKtCooy80o0KjStE7XBspnahrFaFRAdUI0wAwA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1Jx$Ż‘Ɗ¡ḣ
```
A monadic Link that accepts an integer, \$n\$, and yields a list of the first \$n\$ terms.
**[Try it online!](https://tio.run/##ARsA5P9qZWxsef//MUp4JMW74oCYxorCoeG4o////zc "Jelly – Try It Online")** Very inefficient! Remove `ḣ` to see the terms found before heading to \$n\$.
### How?
```
1Jx$Ż‘Ɗ¡ḣ - Link: non-negative integer, Terms (n)
1 - set the left argument, Current, to one
¬° - repeat {Terms} times:
Ɗ - last three links as a monad - f(Current):
$ - last two links as a monad - f(Current):
J - range of length
x - times {Current} (repeat indices by Current values respectively)
Ż - prefix a zero
‘ - increment
·∏£ - head to index {Terms}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ 30 bytes
*Thanks to ovs*
```
w=1:do n<-[0..];n+2<$[1..w!!n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v9zW0ColXyHPRjfaQE8v1jpP28hGJdpQT69cUTEv9n9uYmaebUFRZl6JSklidqqCoYGBQvl/AA "Haskell – Try It Online")
Constructs the list as a fixed point.
[Answer]
# [Uiua 0.8.0](https://www.uiua.org/), 22 bytes [SBCS](http://tinyurl.com/Uiua-SBCS-Jan-14 "SBCS for Uiua 0.8.0")
```
⊡:⍥(⊂:↯⊃⊡(+1)⊢⇌..),0_1
```
[Try on Uiua Pad!](https://uiua.org/pad?src=0_8_0__RiDihpAg4oqhOuKNpSjiioI64oav4oqD4oqhKCsxKeKKouKHjC4uKSwwXzEKCuKItUYgKzHih6ExMDAK)
Takes an integer \$n\$ and returns the \$n\$th term.
## Explanation
```
0_1 # array [0,1]
, # duplicate input to top of stack
‚ç•( # repeat n times
.. # dup list twice
⊢⇌ # last element
⊃⊡(+1) # fork: get both the element at that index of the list and last element + 1
‚ÜØ # reshape: repeat last + 1 that many times
⊂: # join the array to the end
)
‚ä°: # pick the nth element
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Ýλè<₅₆>
```
Outputs the 1-based \$n^{th}\$ value.
[Try it online](https://tio.run/##yy9OTMpM/f/f6PDcc7sPr7B51NT6qKnN7v9/QwMA) or [verify the infinite sequence](https://tio.run/##yy9OTMpM/f/f6PDcc7ttHjW1Pmpqs6s9tOz/fwA).
**Explanation:**
Uses the following recursive 0-based sequence to output the 1-based \$n^{th}\$ term:
$$a(0)=0, a(1)=1, a(2)=2\\
a(n)=a(n-a(a(n-1)-1))+1$$
```
λ # Start a recursive environment
è # to output the 0-based (implicit) input'th term
# (which is output implicitly at the end)
2√ù # Starting with a(0)=0, a(1)=1, and a(2)=2
# And where every following a(n) is calculated as:
# (implicitly push a(n-1)): a(n-1)
< # Decrease it by 1: a(n-1)-1
‚ÇÖ # Pop and take that term: a(a(n-1)-1)
‚ÇÜ # Pop and take the (n-value)'th term: a(n-a(a(n-1)-1))
> # And increase that by 1: a(n-a(a(n-1)-1))+1
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 96 bytes
A port of [@Command Master's Python code](https://codegolf.stackexchange.com/a/269248/110802) in Scala.
---
Golfed version. [Attmept This Online!](https://ato.pxeger.com/run?1=NY0xbsJAEEV7TjGyKGbkYEFokCUjUbqgQhGF5WIwu7Bg1tZ6UJYgTpKGFEnDibgNBkL19KX__v_-awoueXjJgp6tPtnZIL9uqsVGFQJTNhaOHYCl0rBrA7JbNTFMnONDNhNn7CqnGD6sEUgeTQCNFAlvFQ76fYp05RQXa_SQjKFuBcEm6HoIiNr2qfO7F90bXfP7Q2vGqSjHUrkstZInr4QDCsP78Jep50bWqV0qH-mSZcr1seBGoX8zlIxfQqRNWaInNOE7nZ4nP_88n5-8AQ)
```
def f():Iterator[Int]=Iterator(1)++f().zipWithIndex.flatMap{case(x,i)=>Iterator.fill(x)(i+2)}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=dVFPS8MwFMdrP8WP4SGhmm2tghQmeOxhJxEPY4esTdZol5Y01erwk3jZxX0oP40xW2VQzA8C773fnwfvc99kvOTxbvfVWnl58322r1ZPIrOYc6WxDYBcSGxcQbhZNwnujOFvi3trlF4vaYIHrSxmnglIQpnlz4JMJxPKZGUEzwrSYXaL2gksaUbnHUaUOvZHcDR3ogSpFYbbyixSbZfOr6_JlCIMvfG7qh-VLVKdi47Jkts5r7FFxhsB0l1AUZfj1-jFTKqyJB0lCiGiQ6iLDcZjTP2HCIPn-ryuhc7dWLeblTDMvlY9PXb4hx790QsjxKngyuPa40QQ9wJZtQbDrnr5dWGMDZfE4VzHq_XX-wE)
```
object Main {
def main(args: Array[String]): Unit = {
f().take(100).foreach(x => print(s"$x "))
}
def f(): Iterator[Int] = Iterator(1) ++ f().zipWithIndex.flatMap { case (x, i) =>
Iterator.fill(x)(i + 2)
}
}
// 1
// 1 2 // append 1 number.two
// 1 2 3 3 // append 2 number.three
// 1 2 3 3 4 4 4 5 5 5 // append 3 number.four append 3 number.five
//...
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 19 bytes
```
FN⊞υ∨¬υ⊕§υ±§υ⁻⌈υ²Iυ
```
[Try it online!](https://tio.run/##TYwxDsIwDEV3TpHRkYoErJ0QU4amvUJIDY3UOMixUW8fVFj449N7Py6BYwlra4/CBhy9VLzmOzJYayatC2hnRgZfBNR2xlFkzEiCM1zF0Yzbbnh8BsF/MiTSCkPYUtb8TS/2t/4wcSKBW6j7p@1bO5/a8b1@AA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` values. Explanation: Adapted my efficient answer to use @Arnauld's recurrence relation.
```
FN
```
Repeat `n` times.
```
⊞υ∨¬υ⊕§υ±§υ⁻⌈υ²
```
Push `1` as the first value, otherwise use the recurrence relation. Charcoal's cyclic indexing allows this to work for `n=2` as a degenerate case since there is only one value in the array at this point.
```
Iυ
```
Output the `n` results.
[Answer]
# Google Sheets, 62 bytes
```
=let(f,lambda(f,n,if(n<3,n,1+f(f,n-f(f,f(f,n-1)-1)))),f(f,A1))
```
Put \$n\$ in cell `A1` and the formula in cell `B1`. The output is the \$n\$th term.
Using the recursive function in [Arnauld](https://codegolf.stackexchange.com/a/269235/119296)'s JavaScript answer. Google Sheets supports recursion to a depth of 10,000 but the calculation limit is met much earlier here because the function branches several times. The formula will start erroring out at \$n\$ = 34.
This iterative implementation will handle much bigger values of \$n\$ (**75 bytes**):
```
=reduce(,sequence(A1),lambda(a,n,iferror({a;sequence(index(a,n),1,n,)},1)))
```
Put \$n\$ in cell `A1` and the formula in cell `B1`. Output appears in cells `B2:B` and contains elements up to and including the element whose value is \$n\$. To make the number of elements in the output *limited* to \$n\$ instead (**99 bytes**):
```
=array_constrain(reduce(...),A1+1,1)
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 12 bytes
```
↙:⍥(⊚⊂⇡2),[]
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oaZOuKNpSjiipriioLih6EyKSxbXQoKZiAwCmYgMQpmIDUKZiA2CmYgNwpmIDgKCuKNpSjiipriioLih6EyKTpbXSA3Cg==)
Very inefficient. An adaptation of ovs' [K answer](https://codegolf.stackexchange.com/a/269238/97916). Returns the first n elements of the sequence.
```
↙:⍥(⊚⊂⇡2),[]
[] # push empty list
, # copy input to top of stack
‚ç•( ) # repeat [input] times
‚á°2 # push [0 1]
⊂ # prepend
‚äö # repeat each index [value] times
‚Üô: # take the first [input] values
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 14 bytes
```
1Ọw{mvᵇiᵂ…YᵛỌJ
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCIx4buMd3ttduG1h2nhtYLigKZZ4bWb4buMSiIsIiIsIiIsIjMuNC4xIl0=)
```
1Ọw{mvᵇiᵂ…YᵛỌJ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌­
1Ọw # ‎⁡Output 1 without popping, wrap in list
{ # ‎⁢While true
mv # ‎⁣ Decrement the current iteration n
ᵇi # ‎⁤ Index into list without popping
ᵂ… # ‎⁢⁡ Stash indexed item, add 2 to n-1 -> n+1, unstash item
Y # ‎⁢⁢ Repeat n+1 item at index n-1 times
ᵛỌ # ‎⁢⁣ Print each element without popping
J # ‎⁢⁤ Join repeated list with original list
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
67 bytes, it can be golfed much more.
---
Golfed version. [Try it online!](https://tio.run/##DcpBDsIgEADAr2zqRWOyKV4pRx@CukRiCwQhBRfejj3PxPyoYxh1d3mjqJOP6GjnVltdFiFJGXzlIK26ydX7wHRwSZjsRl8@iu3SXpXofRhc9a9i0h86i3m@IOnnGxhaaRCidQmmE5cOE/TxBw)
```
f=Enumerator.new{|y|y<<1;e=f.dup;i=2;loop{e.next.times{y<<i};i+=1}}
```
Ungolfed version. [Try it online!](https://tio.run/##TU3LDoIwELzzFRO8aEwa8AxHP6TaJTYCJbXEIuXb61LReNjNPHZm7XiZYlTUoMmAcz92ZKUzVvT0hDIIk6ZWkQ3sAhtBVaFMAnEAdcoCmtEpodaYgdMJA5719ZA7vftqwumOHpj/OzWWzdY41r8XKvvsdbJGtPI1CSfvtC@L4iBIXm9cE3zAYHXvkO9mvyDHEuMb)
```
def f
Enumerator.new do |yielder|
yielder << 1
enum = f
i = 2
loop do
x = enum.next
x.times { yielder << i }
i += 1
end
end
end
f.lazy.take(100).each { |x| print "#{x} " }
```
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s type system, 113 bytes
```
//@ts-ignore
type G<N,I=[],O=[[1]],Z=[...I,1],S=O[I["length"]]>=I extends N?S:G<N,Z,[...O,...{[_ in keyof S]:Z}]>
```
[Try it at the TypeScript playground!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAcQB4A5AGgEkBeAbQF1KB5B+gRkeYC0GA6QdUpdKAZVot61egCIANukTxwAC1ncAfLWqF0AD3BKAJpELkA-GIBcZKj0r1B-FpWcBvegH1CsRIQBrdBxkADNCMUZrHgBfRk1MbHwiakQAYwwAWyVwUl0DI0RTQgBDRBwmTUJaQk5KQg9anz9A4LDCaijCDkI4pIJCADFYVEhwVIBVRBLUHAo9QxMzRABXTIAjdFR6-MWisw4mJmra+JPdwuL3QkVlNWtzXsILDsIH4dHxxCmZuapa5zCEh5dJZHJ5TSaeL9IgfMbzApLQirDZbeoAGQWlwOR0YJzhXx+swokJO13oAGlfP4giFwuiuujKYw5LcVOo8TFErgBgAlfEjeEAVgADAkQIRJQA9CyYIA) I/O is with unary numbers represented as tuples of 1s.
Or, **~~125~~ 122 bytes** with I/O as decimal numbers:
```
//@ts-ignore
type G<N,I=[],O=[[1]],L="length",Z=[...I,1],S=O[I[L]]>=I[L]extends N?S[L]:G<N,Z,[...O,...{[_ in keyof S]:Z}]>
```
[Try it at the TypeScript playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAcQB4A5AGgEkBeAbQF1KB5B+gRkeYBlaAiADbpE8cAAt+lAFoMAdAuqUulAMq0W9avR7cAfLW270AD3AiAJpELkA-Kp2MAXGSrTK9BXJaUvAb3oAfUJYREIAa3QcZAAzQlVnaQBfRj1MdNwCQgAxWFRIcApKQmpCU3NEK0JEAFcAWwAjdFQmQlpCJj02krKzS2s-QmFRCScbQiTCWx6x3PzCqg6vJRJST0VirnohETFJVNSM-CIAJW65gtIAVgAGNJBCR4A9W0wgA)
This keeps track of the sequence O, the requested entry N, and the current iteration number I. It continuously appends I + 1 repeated `O[I]` times to O, until I is equal to N, at which point `O[N]` (the Nth entry) is returned.
## [TypeScript](https://www.typescriptlang.org/)'s type system, 113 bytes
```
//@ts-ignore
type F<A,B="">=B extends`${A}${infer Z}`?Z:A extends"1"|"11"|"111"?A:`1${F<F<F<F<1,F<F<1,A>>>>,A>>}`
```
I/O is unary numbers represented as string types of the character 1.
This is a port of Arnauld's JavaScript solution. It ends up pretty long in TypeScript because we don't have numeric comparison or subtraction built-in.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 58 bytes
```
for(o=[0,j=i=1];;console.log(j=o[++i]))for(;j--;)o.push(i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN63S8os08m2jDXSybDNtDWOtrZPz84rzc1L1cvLTNbJs86O1tTNjNTVByqyzdHWtNfP1CkqLMzQyNSEmQA2CGQgA)
I tried another approach, this one generates the sequence infinitely.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
<3?U:ÒßU´-ßÓß
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PDM/VTrS31W0Ld/T3w&input=NTAgLW0)
-1 byte thanks to Shaggy
This uses the same method as Arnauld’s JavaScript solution, but it is rearranged slightly.
A direct port is 16 bytes:
```
<3?U:ßU-ßßUÉ É)Ä
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PDM/VTrfVS3f31XJIMkpxA&input=NTA)
This isn’t efficiently packed, though; there’s a space and a close parenthesis, which are generally good to try to avoid in Japt.
This is the obvious method, using the commonly used postfix decrement `É` (`-1`) and increment `Ä` (`+1`). Japt actually does have prefix equivalents for both of these, however: `Ò` (`-~`) for increment, and `Ó` (`~-`) for decrement. In this case, both of the parentheses can be omitted by using prefix operators.
The 16-byte version is the same as Arnauld’s:
```
f=n=>n<3?n:f(n-f(f(n-1)-1))+1
```
This version is closer to:
```
f=n=>n<3?n:-~f(n-f(~-f(n-1)))
```
where the trailing parentheses can be omitted in Japt.
Shaggy's suggestion changes that final `-1` to an in-place decrement:
```
f=n=>n<3?n:-~f((n--)-f(~-f(n)))
```
The difference is that now, that argument to the final recursion can also be omitted, saving a byte.
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 17 bytes
```
w=jn$zW rl(1:w)nN
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN5czcgvyiEoWAotSc0pRUBQ1NLpgIV7mVVbRnXkns0tKSNF2LjeW2WXkqVeEKRTkahlblmnl-EPGduYmZeQq2Cin5XAoKBUUKKgol2QqGBgYK5RD5BQsgNAA)
## Explanation
Like the my [other Haskell answer](https://codegolf.stackexchange.com/a/269239/56656) this calculates the sequence as the fixed point of a function, however it implements that function pretty differently.
If the list is `w` then we zip `1:w` with the natural numbers using `rl`, a function which repeats the input n times. Then we concat together the result.
## Alternate solutions
```
w=jn$ixo 1frl$1:w
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN5czcgvyiEoWAotSc0pRUBQ1NLpgIV7mVVbRnXkns0tKSNF2LjeW2WXkqmRX5CoZpRTkqhlblEPGduYmZeQq2Cin5XAoKBUUKKgol2QqGBgYKUPkFCyA0AA)
```
yy$jn<ixo 1frl<K1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN5czcgvyiEoWAotSc0pRUBQ1NLpgIV7mVVbRnXkns0tKSNF2LzeW2lZUqWXk2mRX5CoZpRTk23oYQmZ25iZl5CrYKKflcCgoFRQoqCiXZCoYGBgrlEPkFCyA0AA)
## Reflection
* [A couple days ago](https://codegolf.stackexchange.com/a/269116/56656) I mentioned wanting a function which zips and then concats. That would obviously be very useful here, but I still haven't implemented it.
* There should be an infix version of `zW`.
* `ixo` should have a version precomposed with small values. Maybe an infix function as well.
[Answer]
# [R](https://www.r-project.org), 33 bytes
```
`?`=\(n)`if`(n<3,n,1+?n-?-1+?n-1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3FRPsE2xjNPI0EzLTEjTybIx18nQMte3zdO11wZShJkTh5jQNc02u4sSCgpxKDUMrYyOdNKjMggUQGgA)
Port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/269235/55372).
# [R](https://www.r-project.org), 43 bytes
```
\(n)rep(seq(x<-c(1,1,rep(1:n,1:n-1))),x)[n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3tWM08jSLUgs0ilMLNSpsdJM1DHUMdUAChlZ5OkCsa6ipqalToRmdFwvRsjlNw1yTqzixoCCnEqjI2EgnTRMis2ABhAYA)
Straightforward generation of the sequence.
] |
[Question]
[
**Problem**
Consider a square 3 by 3 grid of non-negative integers. For each row `i` the sum of the integers is set to be `r_i`. Similarly for each column `j` the sum of integers in that column is set to be `c_j`.
The task is to write code to enumerate all possible different assignments of integers to the grid given the row and column sum constraints. Your code should output one assignment at a time.
**Input**
Your code should take 3 non-negative integers specifying the row constraints and 3 non-negative integers specifying the column constraints. You can assume that these are valid, i.e. that the sum or row constraints equals the sum of column constraints. Your code can do this in any way that is convenient.
**Output**
Your code should output the different 2d grids it computes in any human readable format of your choice. The prettier the better of course. The output must not contain duplicate grids.
**Example**
If all the row and column constraints are exactly `1` then there are only `6` different possibilities. For the first row you can put a `1` in any of the first three columns, for the second row there are now `2` alternatives and the last row is now completely determined by the previous two. Everything else in the grid should be set to `0`.
Say the input is `2 1 0` for the rows and `1 1 1` for the columns. Using APL's lovely output format, the possible integers grids are:
```
┌─────┬─────┬─────┐
│0 1 1│1 0 1│1 1 0│
│1 0 0│0 1 0│0 0 1│
│0 0 0│0 0 0│0 0 0│
└─────┴─────┴─────┘
```
Now say the input is `1 2 3` for the rows and `3 2 1` for the columns. The possible integer grids are:
```
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 42 bytes
```
{o/⍨(⍵≡+/,+⌿)¨o←3 3∘⍴¨(,o∘.,⊢)⍣8⊢o←⍳1+⌈/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnqPevvUgTznSHX14sScEnX1R90tQH6wq16os6@LunpSfoVCfp6CblpesS2ILilKzAQyS4pSU4Fquxan5iUm5aQGO/qEqHMB9Xn6P2qbYPA/DUhW5@s/6l2h8ah366POhdr6OtqPevZrHlqRD5QyVjB@1DHjUe@WQys0dPKBTD2dR12LNB/1LrYA0iAVj3o3GwI1dACN2Fr7/3@agiEYGgChMZe6ra2tOhdMDAzhYkZAFUYQEgA)
Uses `⎕IO←0` which is default on many systems. The other stuff in the header is just pretty printing for the matrices (boxed display).
Input is list of six values, rows sums first, then column sums.
**How?**
`o←⍳1+⌈/⍵` - `o` gets the range `0` to the maximum (`⌈/`) of input
`,o∘.,⊢` - cartesian product with `o` and flatten (`,`)
`⍣8` - repeated for eight times
`3 3∘⍴¨` - shape every 9-items list into a 3×3 matrix
`¨o←` - save these matrices to `o`, and for each
`+/,+⌿` - check if the rows sums (`+/`) concatenated to the column sums (`+⌿`)
`⍵≡` - correspond with the input
`o/⍨` - filter `o` (the matrices array) by truthy values
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ 17 bytes
```
fȯ=⁰mΣS+Tπ3π3Θḣ▲⁰
```
-3 bytes thanks to @H.PWiz
Takes input as a list `xs` encoding the constraints `[r_1,r_2,r_3,c_1,c_2,c_3]`, [try it online!](https://tio.run/##yygtzv7/P@3EettHjRtyzy0O1g4532AMROdmPNyx@NG0TUDh////RxvqwGEsAA "Husk – Try It Online")
### Explanation
Brute force approach :P Generate all 3x3 grids with entries `[0..max xs]`:
```
f(=⁰mΣS+T)π3π3Θḣ▲⁰ -- input ⁰, for example: [1,1,1,1,1,1]
▲⁰ -- max of all constraints: 1
ḣ -- range [1..max]: [1]
Θ -- prepend 0: [0,1]
π3 -- 3d cartesian power: [[0,0,0],...,[1,1,1]]
π3 -- 3d cartesian power: list of all 3x3 matrices with entries [0..max] (too many)
f( ) -- filter by the following predicate (eg. on [[0,0,1],[1,0,0],[0,1,0]]):
S+ -- append to itself, itself..: [[0,0,1],[1,0,0],[0,1,0],..
T -- .. transposed: ..[0,1,0],[0,0,1],[1,0,0]]
mΣ -- map sum: [1,1,1,1,1,1]
=⁰ -- is it equal to the input: 1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
{~⟨ṁ₃{ℕᵐ+}ᵐ²\⟩≜}ᶠ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7ru0fwVD3c2Pmpqrn7UMvXh1gnatUDi0KaYR/NXPuqcU/tw24L//6OjDXWMdIxjdaKNgbRhbOz/KAA "Brachylog – Try It Online")
**WARNING: UGLY OUTPUT!** Don't frick out, it's still human-readable, I'm not required to account for how much. ;)
For some reason it has to be much longer than what I'd expect to make sense (13 bytes):
```
⟨ṁ₃{ℕᵐ+}ᵐ²\⟩ᶠ
```
This latter version, if it worked, would have taken input from the output (i.e. command-line argument) instead.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~149~~ ~~145~~ ~~142~~ ~~141~~ ~~138~~ 136 bytes
```
lambda s:[i for i in product(range(max(sum(s,[]))+1),repeat=9)if[map(sum,(i[j:j+3],i[j/3::3]))for j in 0,3,6]==s]
from itertools import*
```
[Try it online!](https://tio.run/##TY7BagMhEIbvPsUctRGaXaFQwZfI1XqwXd3OEldRA8nTb1UKyeWf4ftn/pn0qL9xnw@vvo6rDd@LhSI1go8ZEHCHlONy@6k02311NNg7LbdAC9eGsdPEeHbJ2ao@GXodbOoup6g3uZ2E4a15F1KKNtwTt5545oJ/GKWKIT7HAFhdrjFeC2BIMde3Y3EeVlqYJHBRvjXk@c/YbsYguZOLTBn3ClmjxH60mYOQ/0JWqvXEJ8Nf1LCB5xd8fuKJt5xmzk3FwMcf "Python 2 – Try It Online")
Takes input as a list of lists: `[[r1, c1], [r2, c2], [r3, c3]]`
[Answer]
## Haskell, ~~94~~ ~~88~~ ~~84~~ 79 bytes
```
q=mapM id.(<$"abc")
f r=[k|k<-q$q$[0..sum r],(sum<$>k)++foldr1(zipWith(+))k==r]
```
Takes the sums of the rows and columns as a single flat 6-element list `[r1,r2,r3,c1,c2,c3]`.
[Try it online!](https://tio.run/##DcUxDsIgFADQvaf4aRggICk7eIPODoQBRVICtEDrYrw7kje8zZ7xnVLvVWVbVgiOY4lm@3zNZPLQlI6/KG8VVaQXzs9PhmYYHkt0j4RSfyTXBP6G8gjXhikhUalmerZhBwXumACgtLBfgMCDFkywZRib/gc "Haskell – Try It Online")
```
q=mapM id.(<$"abc") -- helper function
f r = --
[k | k <- , ] -- keep all k
q$q$[0..sum r] -- from the list of all possible matrices with
-- elements from 0 to the sum of r
-- where
(sum<$>k) ++ -- the list of sums of the rows followed by
foldr1(zipWith(+))k -- the list of sums of the columns
== r -- equals the input r
```
As the elements of the matrices to test go up to the sum of `r`, the code does not finish in reasonable time for large row/column sums. Here's a version that goes up to the maximum of `r` which is faster, but 4 bytes longer: [Try it online!](https://tio.run/##Xcq7DoIwAEbhnaf403RoQyUUVuoT6OTgQDpUkdiUciklMcZ3r8TR6RvOeZrVPYYhpUV5M59hu4I1lJjbnfCsR1Ct@7jmsNCFtmVRePOyfvMIWrB18w09Op7n/TR0QbK3na82PlnOuVMq6OSNHaHQTRmAOdgxgqJHWwkpSgG5I/WvbfESw2kEIX@rFJWoBeodqdMX "Haskell – Try It Online")
[Answer]
# Mathematica, 81 bytes
```
Select[0~Range~Max[s=#,t=#2]~g~3~(g=Tuples)~3,(T=Total)@#==s&&T@Transpose@#==t&]&
```
finds all 3x3 matrices with elements 0..Max and selects the right ones
this means that `(Max+1)^9` matrices have to be checked
[Try it online!](https://tio.run/##fYwxC8IwFIR3f0YLoYUI2swPsjkVxGYLHR41jYU2Lc0TBDF/PUbpKN4NdxzHNyHdzIQ0dBh7iI0ZTUf6EC7orAk1PrSHnBPkVRtsEKGwoO7LaHwZBC8UqJlwLGUO4BlTUq3o/DJ781mItSye18GRVHNDqVh5Woer7PXzyJNffMt2973pbP9P2Xb7Rau4SDSRMtHiGw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~115~~ 110 bytes
```
function(S)for(m in unique(combn(rep(0:max(S),9),9,matrix,F,3,3)))if(all(c(rowSums(m),colSums(m))==S))print(m)
```
[Try it online!](https://tio.run/##PYpBCgIxDEWv0mUCEZRZKc7WC/QEtUwg0KRjbHFuX7sQeX/xPjwfHO6nwd1yk2oQkauDBrHQTV59g1z1aeDbDuebpmMWdJ0jTc3loActtCCiMKRSIIPXT@z6BkXKtfwU1zUi7i7W5hs8uwv9QRxf "R – Try It Online")
Takes input as `c(r1,r2,r3,c1,c2,c3)`, a single `vector`, and prints the matrices to stdout.
It's quite similar to [Uriel's APL answer](https://codegolf.stackexchange.com/a/150020/67312), but it generates the 3x3 grids somewhat differently.
Letting `M=max(S)`, it generates the vector `0:M`, then `rep`eats it 9 times, i.e., `[0..M, 0...M, ..., 0...M]` nine times. Then it selects all combinations of that new vector taken 9 at a time, using `matrix, 3, 3` to convert each 9-combination into a `3x3` matrix, and forcing `simplify=F` to return a list rather than an array. It then uniquifies this list and saves it as `m`.
Then it filters `m` for those where row/column sums are identical to the input, printing those that are and doing nothing for those that aren't.
Since it computes `choose(9*(M+1),9)` different possible grids (more than the `(M+1)^9` possibilities), it'll run out of memory/time faster than the more efficient (but less golfy) answer below:
# [R](https://www.r-project.org/), 159 bytes
```
function(S,K=t(t(expand.grid(rep(list(0:max(S)),9)))))(m=lapply(1:nrow(K),function(x)matrix(K[x,],3,3)))[sapply(m,function(x)all(c(rowSums(x),colSums(x))==S))]
```
[Try it online!](https://tio.run/##TY3LCsIwEEV/xeUdGMXSlcV8QZZdli5CHxLIizTF@PUxohTnbubCOTOxrKf7uay7m5L2Dj1LkZCw5KDcfHlEPSMuAUZvCdfOqoyeiG/0GVhhVAjmhaZz0T8hiY9LmaxKUWfIIfPILbfVGLYvb/85ZQwmVL/f7VY7T978VhKivhvLWoGGjxCVNw "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~35~~ 22 bytes
*-13 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
```
X>Q:q9Z^!"@3et!hsG=?4M
```
[Try it online!](https://tio.run/##y00syfn/P8Iu0KrQMipOUcnBOLVEMaPY3dbexNcg@f//aEMFOIwFAA "MATL – Try It Online")
Link is to a version of the code that prints a little more nicely; this version will just print all the matrices with a single newline between them.
Takes input as `[c1 c2 c3 r1 r2 r3]`.
Obviously, this computes the cartesian power `X^` of `0...max(input)` with exponent `9`, and transposing `!`. It then loops `"` over the columns, reshaping each `@` as a 3x3 matrix `3e`, duplicating `t`, transposing `!`, and horizontally concatenating them `h`. Then it computes the column sums `s`, which will result in the vector `[c1 c2 c3 r1 r2 r3]`. We do elementwise equality to the input `G=`, and if `?` all are nonzero, we recover the correct matrix by selecting the input to the function `!` by using `4M`.
[Answer]
## Batch, 367 bytes
```
@echo off
for /l %%i in (0,1,%1)do for /l %%j in (%%i,1,%1)do for /l %%k in (%%i,1,%4)do call:c %* %%i %%j %%k
exit/b
:c
set/a"a=%1-%8,c=%4-%9,f=%8-%7,g=%9-%7,l=%5-f,m=%2-g,l^=m-l>>31&(m^l),m=%5+c-%3-f,m&=~m>>31
for /l %%l in (%m%,1,%l%)do set/a"b=%2-g-%%l,d=%5-f-%%l,e=%6-a-b"&call:l %7 %%l
exit/b
:l
echo %1 %f% %a%
echo %g% %2 %b%
echo %c% %d% %e%
echo(
```
The top left 2×2 square forces the result, so the best approach is to generate all values for the top left integer, all valid values for the sum of the top left and top middle integer, all valid values for the sum of the top left and middle left integer, and calculate the range of valid values for the middle integer, then, having looped through all the appropriate ranges, calculate the remaining values from the constraints.
[Answer]
# [Python 2](https://docs.python.org/2/), 118 bytes
```
def f(v,l=[],i=0):n=len(l);V=v*1;V[~n/3]-=i;V[n%3]-=i;return[l][any(V):]if n>8else V*-~min(V)and f(V,l+[i])+f(v,l,i+1)
```
[Try it online!](https://tio.run/##LU27CsIwFJ3tV2QRkjZF2y4SiX/g0iHLJWDBRC/Ea4mt0KW/XlOVM5wXnNNPw/1J9bJcnWeev2XQYCXqvVCkgyMexNHod14dDcy0a2ypMUna/lR0wxgJgoWOJm6EsugZnQ4uvBwzeTk/kFLc0TWNGxkKQCuK74/EohJLqz1H6seBC5H5Z2RnhsRalW1Wg6uJHd0cb0TKNn1EGtjlDJg3yoJq7AUqlSj7VQvUsvqjth8 "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 123 bytes
```
V=input()
n=max(V)+1
for k in range(n**9):
m=[];exec"m+=[k%n,k/n%n,k/n/n%n],;k/=n**3;"*3
if map(sum,m+zip(*m))==V:print m
```
[Try it online!](https://tio.run/##LYpBCoMwEADvecUiFJIYEOOpyn7DS/AgJbYh7Bo0gu3n05aWgZnLpGd@rGxLGTFwOrJUgpHmU46qbsWybhAhMGwz371kra@qF0DopsGf/lZRjS5e2MSGf/52MkNs8DN3Q6U7AWEBmpPcDzJUv0KSmpRCHPu0Bc5ApThr2j92egM "Python 2 – Try It Online")
] |
[Question]
[
The graph of the modulo operation (\$y = x \mod k\$) looks like this:
[](https://i.stack.imgur.com/FSjQG.png)
This is a very useful function, as it allows us to create "wrapping" behavior. However, it is very cumbersome when I want to use it to create an appearance of "bouncing" between two walls. The graph of the "bounce" function (\$y = \text{bounce} (x, k)\$) looks like this:
[](https://i.stack.imgur.com/VHAf7.png)
The [period](https://en.wikipedia.org/wiki/Periodic_function) of the graph of \$y = x \mod k\$ is \$k\$. The period of the graph of \$y = \text{bounce} (x, k)\$ is \$2k\$, because it moves upwards for \$k\$ units, and then moves downwards for another \$k\$ units, before returning to where it started. For both functions, the minimum value for \$y\$ is 0, and the maximum is \$k\$ (Actually, for the modulus function with integral inputs, it's \$k-1\$). In addition, for both functions, the value where \$x=0\$ is 0.
## The challenge
Given an integer \$x\$ and a positive integer \$k\$, return an integer or floating-point approximation of \$y = \text{bounce} (x, k)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (counted in bytes) wins.
## Test Cases
```
x, k -> bounce(x, k)
0, 14 -> 0
3, 7 -> 3
14, 14 -> 14
15, 14 -> 13
-13, 14 -> 13 (12.999997 etc would be an acceptable answer)
-14, 14 -> 14
191, 8 -> 1
192, 8 -> 0
```
Bonus points for a [Fourier](https://en.wikipedia.org/wiki/Square_wave)-based approach in [Fourier](http://esolangs.org/wiki/Fourier).
[Answer]
# x86-64 Machine Code, 18 bytes
```
97
99
31 D0
29 D0
99
F7 FE
29 D6
A8 01
0F 45 D6
92
C3
```
This code defines a function in x86-64 machine language that computes `bounce(x, k`). Following the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) used on Gnu/Unix systems, the `x` parameter is passed in the `EDI` register, while the `k` parameter is passed in the `ESI` register. As with all x86 calling conventions, the result is returned in the `EAX` register.
To call this from C, you would prototype it as follows:
```
int Bounce(int x, int k);
```
**[Try it online!](https://tio.run/##hY7RaoMwFIavl6cIloGROBK11mA3GN18iWUXIVobaOOI6QiMvfqyOL2dvQjh/N/5@Y5Meym9l4MeLZQnYaCrysPQdm/v8BFG3LFdeIy7nHL3QrjL2PxPWRNY87pkJXfPFXck7JGGu2I7Zyzj7pBHNRitsEpCpS2MkyBpnEZxmPAUoSBbxDUAYKO0PF/bDu5H26rh4fQEwFS8CKWnDhSml/jv3iSZhk/0Be4@TEDHOLpXXEcYzo6YYFogVP@Hc7xbobRYb9PtOk9pfmvhloFRXK3ybOGms1ejIanBt/c/8ngW/ejTS1n8Ag "C (gcc) – Try It Online")**
Ungolfed assembly mnemonics:
```
; Take absolute value of input 'x' (passed in EDI register).
; (Compensates for the fact that IDIV on x86 returns a remainder with the dividend's sign,
; whereas we want 'modulo' behavior---the result should be positive.)
xchg eax, edi ; swap EDI and EAX (put 'x' in EAX)
cdq ; sign-extend EAX to EDX:EAX, effectively putting sign bit in EDX
xor eax, edx ; EAX ^= EDX
sub eax, edx ; EAX -= EDX
; Divide EDX:EAX by 'k' (passed in ESI register).
; The quotient will be in EAX, and the remainder will be in EDX.
; (We know that EAX is positive here, so we'd normally just zero EDX before division,
; but XOR is 2 bytes whereas CDQ is 1 byte, so it wins out.)
cdq
idiv esi
; Pre-emptively subtract the remainder (EDX) from 'k' (ESI),
; leaving result in ESI. We'll either use this below, or ignore it.
sub esi, edx
; Test the LSB of the quotient to see if it is an even number (i.e., divisible by 2).
; If not (quotient is odd), then we want to use ESI, so put it in EDX.
; Otherwise (quotient is even), leave EDX alone.
test al, 1
cmovnz edx, esi
; Finally, swap EDX and EAX to get the return value in EAX.
xchg eax, edx
ret
```
Note that the first section (that takes the absolute value) could have equivalently been written:
```
; Alternative implementation of absolute value
xchg eax, edi
neg eax
cmovl eax, edi
```
which is the exact same number of bytes (6). The performance should be similar, perhaps slightly faster (except on [certain Intel chips, where conditional moves are slow](https://stackoverflow.com/questions/44754267/how-to-force-the-use-of-cmov-in-gcc-and-vs/44759962#44759962)).
`XCHG` is, of course, relatively slow and would not be preferred over `MOV` except in code golfing (since the `XCHG` is 1-byte when one of the operands is the accumulator, whereas a register-register `MOV` is always 2 bytes).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
æ%A
```
[Try it online!](https://tio.run/##y0rNyan8///wMlXH/4eX6z9qWvP/f3S0gY6hSaxOtLGOOZA0NIHwDE0htK6hMYwBk7E01LEA00ZAOhYA "Jelly – Try It Online")
Built-ins ftw.
### Explanation
`æ%` is a useful built-in here. I don't know how to describe it, so I'll just provide the output for some inputs:
As `x` goes from `0` to infinity, `xæ%4` goes `0,1,2,3,4,(-3,-2,-1,0,1,2,3,4,)` where the part in parentheses is repeated to infinity both ways.
[Answer]
# [Python 2](https://docs.python.org/2/), 29 27 bytes
```
lambda x,k:abs(x%k-x/k%2*k)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCJ9sqMalYo0I1W7dCP1vVSCtb839BUWZeiUaahoGOgqGJpiYXjG@so2COxDU0QZM3NEUT0DU0xhDB0GRpqKNggSJgBBb4DwA "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 27 bytes
```
lambda x,k:k-abs(k-x%(k*2))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ9sqWzcxqVgjW7dCVSNby0hT839BUWZeiUaahoGOgqGJpiYXjG@so2COxDU0QZM3NEUT0DU0xhDB0GRpqKNggSJgBBb4DwA "Python 3 – Try It Online")
[Answer]
## Ruby, 40 bytes 32 bytes
```
b=->(x,k){(x/k+1)%2>0?x%k:k-x%k}
```
[Try it online!](https://tio.run/##KypNqvz/P8lW106jQidbs1qjQj9b21BT1cjOwL5CNdsqWxdI1v6vULBVSE8tKdZLzsjPLdAryY/P5MrGIlZQWlKskKSXnJiTAzRPIVvzvwGXoQkA)
### Explanation
Hi, this is my first answer on this site! This code is based on the observation that the bounce function behaves exactly like modulo when (*n*-1)*k* <= *x* < *nk* and n is odd, and behaves like a reversed modulo operation when *n* is even. `(x/k+1)` is the smallest integer greater than *x*/*k* (which is *x*/*k*+1 rounded down to an integer). Therefore, `(x/k+1)` finds the *n* mentioned above. `%2>0` checks to see if *n* is odd or even. If *n* mod 2 > 0, then *n* is odd. If *n* mod 2 = 0, then *n* is even. If *n* is odd, then the bounce function should equal *x* mod *k*. If *n* is even, the bounce function should be the reverse, equal to *k* - *x* mod *k*. The whole expression `(x/k+1)%2>0?x%k:k-x%k` finds *n*, then executes the *x* mod *k* if it is odd, and executes *k* - *x* mod *k* otherwise.
The answer was improved based on a suggestion from [Cyoce](https://codegolf.stackexchange.com/users/41042/cyoce).
[Answer]
## JavaScript (ES6), ~~36~~ 32 bytes
```
k=>f=x=>x<0?f(-x):x>k?k-f(k-x):x
```
Recursively bounces `x` against `0` and `k`, so very much in the spirit of the challenge.
[Answer]
# Mathematica, 19 bytes
```
Abs@Mod[#,2#2,-#2]&
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
aa%Ey
```
[Verify all testcases.](http://pyth.herokuapp.com/?code=aa%25Ey&test_suite=1&test_suite_input=14%0A0%0A%0A7%0A3%0A%0A14%0A14%0A%0A14%0A15%0A%0A14%0A-13%0A%0A14%0A-14%0A%0A8%0A191%0A%0A8%0A192%0A&debug=0&input_size=3)
Fork of [my Python answer](https://codegolf.stackexchange.com/a/132665/48934).
[Answer]
# J, 25 bytes
Hint:
>
> This is just regular modulo on the ladder numbers. For example, in the case of 5: `0 1 2 3 4 5 4 3 2 1`
>
>
>
Here is a (not yet well-golfed) solution in J. Will try to improve tomorrow:
```
[ ((|~ #) { ]) (i.@>:,}:@i.@-) @ ]
```
compressed: `[((|~#){])(i.@>:,}:@i.@-)@]`
compressed2: `[((|~#){])(<:|.|@}.@i:)@]`
[Try it online!](https://tio.run/##y/oPBEkKtnoK0QoaGjV1CsqaCtUKsZoKGpl6DnZWOrVWDkCGrqaCg0Isl7lCkoIxl6GlIZC24Io3NAbShiYA "J – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~25~~ ~~30~~ 27 bytes
```
g=abs(:%:)~a'\`b%2|?b-g\?g
```
Did a bit of restructuring...
## Explanation
```
g=abs( ) let g be the absolute value of
% the (regular) modulo between
: : input a read from cmd line, and input b read from cmd line
~a \ b%2 IF the int division of A and B mod 2 (ie parity test) yields ODD
' ` (int divisions need to be passed to QBasic as code literals, or ELSE...)
|?b-g THEN print bouncy mod
\?g ELSE print regular mod
```
[Answer]
# C89, 40 bytes
```
t;f(x,k){t=abs(x%k);return x/k%2?k-t:t;}
```
A C port of [my x86 machine code answer](https://codegolf.stackexchange.com/a/132670/58518), this defines a function, `f`, that calculates the bounce-modulo for the parameters `x` and `k`.
It uses C89's implicit-int rule, so that both parameters, the global variable `t`, and the function's return value are all implicitly of type `int`. The global variable `t` is just used to hold a temporary value, which ends up saving bytes, compared to repeating the computation on either side of the conditional operator.
The `abs` function (absolute value) is provided in the `<stdlib.h>` header, but we don't have to include it here, again thanks to C89's implicit-int rule (where the function is implicitly declared and assumed to return `int`).
**[Try it online!](https://tio.run/##fdDRCoIwGAXg63yKYQibzFIz0Jb1It2s6XToVkwNQXz1loKX6d1/@ODA@ZlXMGaMJBz2uEKDTOmzgb1TIaLzttMK9MfKCe@VJy@SjGYvFKu7LAfXps3E61DeLEuoFkgqFJwPqguGASupdt05fNBg7d56Ig5tRzyUjQGHPg4ihMgfCaJ1Oq@SF5w2bKMyCXC8RuFCyyN8Yo3my3hNi8Z40/yUxckP "C (gcc) – Try It Online")**
**Ungolfed version:**
```
#include <stdlib.h>
int Bounce(int x, int k)
{
int mod = abs(x % k);
return (x/k % 2) ? k-mod : mod;
}
```
Looking at this in light of [my hand-tuned machine code](https://codegolf.stackexchange.com/a/132670/58518), compilers actually [generate pretty good output](https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:%27%23include+%3Cstdlib.h%3E%0A%0Aint+Bounce(int+x,+int+k)%0A%7B%0A++++int+mod+%3D+abs(x+%25+k)%3B%0A++++return+(x/k+%25+2)+%3F+k-mod+:+mod%3B%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),header:(),k:44.94773519163764,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:g63,filters:(b:%270%27,commentOnly:%270%27,directives:%270%27,intel:%270%27),options:%27-xc+-m64+-Os%27,source:1),l:%275%27,n:%270%27,o:%27x86-64+gcc+6.3+(Editor+%231,+Compiler+%231)%27,t:%270%27)),header:(),k:55.05226480836237,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4) for this. I mean, they should; it's a pretty simple function to optimize! I did [uncover a minor bug in GCC's x86-64 optimizer](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81456), though, where it curiously produces *larger* code when you tell it to optimize for size and *smaller* code when you tell it to optimize for *speed*.
[Answer]
# Haskell, 37 Bytes
[**Try it online!**](https://tio.run/##NYyxCoMwGIT3PsUfdEgGCyntkpqhQ4fOfQED@dEQk0gMYsF3T1X0loP77q5To8W@z8YNISb4/saE7vr2k4nBO/SJtphesR1ZpoRJF/RzLuwStC7nRpupsdJWM7ELr29y9eyU8RJ0uMAutU6hruB4OdIhGp9KGlFpKKHbbC8KAR@fsMXIipPSjRDCmRAny5k/Mr//AQ)
```
(!)=mod;x#k|odd$x`div`k=k-x!k|1<2=x!k
```
**How to use:**
Call as `15#14` for non-negative left arguments and as `(-13)#14` for negative left arguments, because Haskell would interpret `-13#14` as `-(13#14)` if you are using something like `ghci`. The TIO-link simply takes two command-line arguments.
**Explanation:**
First redefines the binary infix operator `!` to be the same as `mod`. Haskell's `mod` always outputs a non-negative value, so we don't need the `abs` that other solutions here do. It then checks whether `x/k` (integer division) is odd and if so, returns `k-x mod k` (ie the back-bounce) or else it returns `x mod k`.
[Answer]
# PHP, ~~40~~ 50 bytes
damn dollars. damn import overhead. :)
integer version:
```
[,$x,$k]=$argv;$y=abs($x)%$k;echo$x/$k&1?$k-$y:$y;
```
or
```
[,$x,$k]=$argv;echo[$y=abs($x)%$k,$k-$y][$x/$k&1];
```
float version, 56 bytes:
Replace `abs($x)%$k` with `fmod(abs($x),$k)`.
---
edit: fixed results for negative `x`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
d%ε¹ε
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJkJc61wrnOtSIsIiIsIjE0XG4xNSJd)
## How?
```
d%ε¹ε
d # Double the (implicit) first input
% # Modulo the (implicit) second input by this
ε # Take the absolute difference of this and the (implicit) first input
¹ε # Take the absolute difference of this and the first input again
```
[Answer]
# Common Lisp, 41 bytes
```
(lambda(x k)(- k(abs(-(mod x(* k 2))k))))
```
[Try it online!](https://tio.run/##LY7BCsIwEER/ZSiIs2LAtBH14r@kBqGkMcX2UC/99bopXVjesId5@@q7cVjZ5zzgnb/gjJ@g@@BIXmCdsMFNaN2W7XWDsc3O/fywuBfUCkHIoHYlP2FCtbhw1oV5QrEcKqgCVKdPbfAqjNqESN@ONEw5YOYJEbVIFJ21vFT4Bw)
[Answer]
# C (gcc), ~~43~~ 53 bytes
Edit: Fixed negative issue
```
int f(int x,int y){return x/y%2?abs(y-x%y):abs(x%y);}
```
[Try it Online!](https://tio.run/##fZDdboMwDIWvl6ewWiERFAoBqv5N3YvsJoS0jcTSKoQVVPXZWbzdbB3UF5Z9PstxjoyPUg5zbWTdVgpeG1fp8@K0J3@kWpdeG7RxcAgxdwxzT29WudYa6JI@yN5E2YR93AU93WKJxe4@JBGBlAEvIN7Dr0gJ5Axg9SDnxI/@H@eF15cjek5ino/pEPJsscFYgXISrue2rqBUIAwIKdXFibLGrrkqS/2WqVc33J@5fjiTI8hGQEqihBC050No8@2WsEfJQJ6EjSJsPumNvFysR4dwFuh3M2Pe15TxgtLdCPGXTaLlJEJbptmTlf6/6ymU/aD78AU)
[Answer]
# R, 28 bytes
```
pryr::f(abs((x-k)%%(2*k)-k))
```
Which evaluates to the function:
```
function (k, x)
abs((x - k)%%(2 * k) - k)
```
Which appears to be the method that most solutions use. I didn't look at them before making this.
[Answer]
# MMIX, 20 bytes (5 instrs)
"xxd --jelly"
```
00000000: 1c02 0001 fe00 0006 24ff 0100 6600 02ff ÷£¡¢“¡¡©$”¢¡f¡£”
00000010: f801 0000 ẏ¢¡¡
```
disassembly and commentary
```
bounce DIV $2,$0,$1 // f:rR = x /% k
GET $0,rR // rv = rR
SUB $255,$1,$0 // t = k - rv
CSOD $0,$2,$255 // if(f odd) rv = t
POP 1,0 // return rv
```
Not entirely sure what this does if k is negative, but it's probably the negative of bounce(x,k).
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
x#k=abs$mod(x-k)(2*k)-k
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0I52zYxqVglNz9Fo0I3W1PDSCtbUzf7f25iZp5tbmKBb7xGQVFmXoleaV5yaVFRpYaypma0hoGOgqGJpo6ChrGOgjmINjSBiRiawli6hsYIJkLe0lBHwQLCMgKxYv8DAA "Haskell – Try It Online")
Boring port of everything else ~~just to spite the existing answer for the pointless `(!)=mod;` ;)~~.
] |
[Question]
[
Write a program or a function that takes two non-empty lists of the same length as input and does the following:
* uses elements of first list to get numerators,
* uses elements of the second list to get denominators,
* displays resulting fractions after simplification `(2/4=>1/2)`, separated by "+"s,
* displays "=" and result of addition after last fraction.
## Example:
### Input
```
[1, 2, 3, 3, 6]
[2, 9, 3, 2, 4]
```
### Output
```
1/2+2/9+1+3/2+3/2=85/18
```
## About rules
* elements of lists will be positive integers,
* elements can be separated by spaces, eg: `1/2 + 2/9 + 1 + 3/2 + 3/2 = 85/18` is ok,
* trailing newline is allowed,
* lists can be taken in other formats than above, eg.: `(1 2 3 3 6)` or `{1;2;3;3;6}`, etc.,
* `1` can be expressed as `1/1`,
* instead of printing you can return appropriate string,
* you do not need to handle wrong input,
* **shortest code wins**.
[Answer]
# Ruby 2.4, ~~54~~ 53 characters
```
->n,d{a=n.zip(d).map{|n,d|n.to_r/d};a*?++"=#{a.sum}"}
```
Thanks to:
* [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) for the Ruby 2.4 specific version (-3 characters)
* [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) for optimizing the `Rational` initialization (-1 character)
### Ruby, ~~58~~ ~~57~~ 56 characters
```
->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}
```
Sample run:
```
irb(main):001:0> puts ->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}[[1, 2, 3, 3, 6], [2, 9, 3, 2, 4]]
1/2+2/9+1/1+3/2+3/2=85/18
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXp5NSXWJrYJ2nV5VZoJGiqZebWFBdAxStKdG2LbLN0yvJjy/ST7EuqtWy19ZWslWuLqlVqv1fUFpSrJAWHW2oo2Cko2AMRmaxOgrRQJ4lmAdkmMTG/gcA "Ruby – TIO Nexus")
[Answer]
## Mathematica, 33 bytes
```
Row@{Row[#/#2,"+"],"=",Tr[#/#2]}&
```
input
>
> [{1, 2, 3, 3, 6}, {2, 9, 3, 2, 4}]
>
>
>
[Answer]
# [M](https://github.com/DennisMitchell/m), ~~12~~ 11 bytes
```
÷µFj”+;”=;S
```
This is a dyadic link. Due to a bug, it doesn't work as a full program. `F` is also required due to a bug.
[Try it online!](https://tio.run/##y/3///D2Q1vdsh41zNW2BhK21sH/DXWMdIyB0OzwciMdSyDDSMfkPwA "M – Try It Online")
### How it works
```
÷µFj”+;”=;S Dyadic link. Left argument: N. Right argument: D
÷ Perform vectorized division, yielding an array of fractions (R).
µ Begin a new, monadic chain. Argument: R
F Flatten R. R is already flat, but j is buggy and has side effects.
j”+ Join R, separating by '+'.
;”= Append '='.
;S Append the sum of R.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 104 bytes
9 bytes thanks to Felipe Nardi Batista.
```
from fractions import*
def f(*t):c=[Fraction(*t)for t in zip(*t)];print('+'.join(map(str,c)),'=',sum(c))
```
[Try it online!](https://tio.run/nexus/python3#LcnLCsIwEIXhvU8xu0zqIHhBsNKtLxG6KNGBEXIhGTe@fEyLcBb/x2lcUgAui1dJsYKEnIoOu@eLgXFQO/rJPf73ak4FFCTCV/Lq@Z6LREWzN4d3kohhyVi1kLeWzGSofgL2bozuSHAiOG@7zgSu67apx2W27Qc "Python 3 – TIO Nexus")
[Answer]
# [Perl 6](https://perl6.org), ~~77~~ 73 bytes
```
{join('+',($/=[@^a Z/ @^b]).map:{.nude.join('/')})~"="~$/.sum.nude.join('/')}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X52Vn5mnoa6trqOhom8b7RCXqBClr@AQlxSrqZebWGBVrZdXmpKqB1Glr65Zq1mnZKtUp6KvV1yaiy73v6C0RAFksAaXgkK0oY6CkY6CMRiZxeqAhIB8SzAfyDCJ5dK0/g8A "Perl 6 – TIO Nexus")
```
{($/=[@^a Z/@^b])».nude».join('/').join('+')~'='~$/.sum.nude.join('/')}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X62hom8b7RCXqBCl7xCXFKt5aLdeXmlKKpDKys/M01DXV9eEsrTVNevUbdXrVPT1iktzwaoQamr/F5SWKIAM1eBSUIg21FEw0lEwBiOzWB2QEJBvCeYDGSaxXJrW/wE "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with two placeholder params 「@a」 and 「@b」
(
$/ = [ # store as an array in 「$/」 for later use
@^a Z/ @^b # zip divide the two inputs (declares them)
]
)».nude\ # get list of NUmerators and DEnominators
».join('/') # join the numerators and denominators with 「/」
.join('+') # join that list with 「+」
~
'=' # concat with 「=」
~
$/.sum.nude.join('/') # get the result and represent as fraction
}
```
[Answer]
## Clojure, 71 bytes
```
#(let[S(map / % %2)](apply str(concat(interpose '+ S)['=(apply + S)])))
```
Yay for built-in fractions!
[Answer]
# Mathematica, 61 bytes
```
t=#~ToString~InputForm&;Riffle[t/@#,"+"]<>"="<>t@Tr@#&[#/#2]&
```
[Answer]
## JavaScript (ES6), 111 bytes
Takes the lists in currying syntax `(a)(b)`.
```
let f =
a=>b=>a.map((v,i)=>F(A=v,B=b[i],N=N*B+v*D,D*=B),N=0,D=1,F=(a,b)=>b?F(b,a%b):A/a+'/'+B/a).join`+`+'='+F(A=N,B=D)
console.log(f([1, 2, 3, 3, 6])([2, 9, 3, 2, 4]))
```
[Answer]
# Java, 225 bytes
```
int c(int a,int b){return b>0?c(b,a%b):a;}
(N,D)->{int n=0,d=1,i=0,g;String s="";for(;i<N.length;g=g(N[i],D[i]),N[i]/=g,D[i]/=g,s+=(i>0?"+":"")+N[i]+"/"+D[i],n=n*D[i]+N[i]*d,d*=D[i++],g=g(n,d),n/=g,d/=g);return s+"="+n+"/"+d;}
```
`N` and `D` are both `int[]`, contextualized.
I reused [Kevin Cruijssen's GCD function](https://codegolf.stackexchange.com/a/92494/16236).
[See it and test it online!](http://ideone.com/jb3LJs)
[Answer]
## [Julia](https://julialang.org/) v0.4+, ~~66~~ 53 bytes
*-13 bytes thanks to Dennis*
```
a^b=replace(join(a.//b,"+")"=$(sum(a.//b))","//","/")
```
[Try it Online!](https://tio.run/##yyrNyUz8/z8vLsW2KLUgJzE5VSMrPzNPI09PXz9FR0lbSVPJVkWjuDQXIqKpqaSjpK8PIpQ0/xcUZeaV5ORpRBvqGOkYA6FZrEKcQrSRjiWQbaRjEqv5HwA)
Alternately, if fractions can be displayed using `//` rather than `/`, the following works for **35 bytes**:
```
a^b=join(a.//b,'+')"=$(sum(a.//b))"
```
[Answer]
# [setlX](https://randoom.org/Software/SetlX), 103 bytes
```
f:=procedure(a,b){i:=1;l:=[];while(i<=#a){l:=l+[a[i]/b[i]];i+=1;}s:=join(l,"+");return s+"="+eval(s);};
```
Creates a function called `f` where your insert two lists.
ungolfed:
```
f := procedure (a,b) {
i:=1;
l:=[];
while(i<=#a){
l:=l+[a[i]/b[i]];
i+=1;
}
s:=join(l,"+");
return s+"="+eval(s);
};
```
with named variables and annotations:
setlX doesn't provide a comment feature so let's just pretend that we can comment with `%`
```
f := procedure(firstList,secondList) {
count := 1;
list := [];
while(count <= #firstList) {
% calculate every fraction and save it as a list
list := list + [firstList[count]/secondList[count]];
count += 1;
}
% Seperate every list entry with a plus ([2/3,1] -> "2/3+1")
str := join(list, "+");
% eval executes the string above and thus calculates our sum
return str + "=" + eval(str);
};
```
[](https://i.stack.imgur.com/9KR3c.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ 34 bytes
```
‚øvyy¿÷'/ý'+}¨'=¹.¿©¹÷²*O®‚D¿÷'/ýJ
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYdbhHWWVlYf2H96urn94r7p27aEV6raHduod2n9o5aGdh7cf2qTlf2gdUJ0LTI3X///RRjoKljoKxjoKQIZJLFe0IZhlDEZmsQA "05AB1E – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes
```
,:gj”/
ṙJ$ṖP×Sç⁸P¤,ç@"j”+$¥Ṛj”=
```
[Try it online!](https://tio.run/nexus/jelly#@69jlZ71qGGuPtfDnTO9VB7unBZweHrw4eWPGncEHFqic3i5gxJIWlvl0NKHO2eBmLb///@PNtJRsNRRMNZRADJMYv9HG4JZxmBkFgsA "Jelly – TIO Nexus")
[Answer]
# PHP>=7.1, 190 Bytes
```
<?function f($x,$y){for($t=1+$x;$y%--$t||$x%$t;);return$x/$t."/".$y/$t;}[$n,$d]=$_GET;for($p=array_product($d);$x=$n[+$k];$e+=$x*$p/$y)$r[]=f($x,$y=$d[+$k++]);echo join("+",$r)."=".f($e,$p);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/40a0804afd3f3ba2fbfe1d6805f520a3b7920b39)
+14 Bytes for replacement `return$x/$t."/".$y/$t;` with `return$y/$t>1?$x/$t."/".$y/$t:$x/$t;` to output `n` instead of `n/1`
[Answer]
# F#, ~~244~~ ~~241~~ 239 bytes
```
let rec g a=function|0->abs a|b->g b (a%b)
let h a b=g a b|>fun x->a/x,b/x
let s,n,d=List.fold2(fun(s,n,d)N D->
let(N,D),(n,d)=h N D,h(n*D+N*d)(d*D)
s@[sprintf"%i/%i"N D],n,d)([],0,1)nom div
printf"%s=%i/%i"(System.String.Join("+",s))n d
```
[Try it online!](https://tio.run/nexus/fs-mono#NY9Na4QwFEX3/oqHILw4UWdsKRSJdOGqFDezFBdm4kfAiWWSFgv@d/tiKQ/e4tzDhTv3DsxyBwHNpciLJ7qXNpiJKv3taV68EsuL53b39NHfYIRODF/m5vRitnNSdtJCt8mkHEECdpFkR8EEHUgx@r@V5MNKarZyma1HbrnhSnxo69JhmVWO5OABWQ1VUgZAFta8Yhw9FBMQ5xOauDrVsWKo4ooFYN8a@/nQxg1hpLNIh2S1Rw02LT/zC/MDaU7wb1nxJ@L1x7r@nl4dBWP6vmiD4SnkljEDat9/AQ "F# (Mono) – TIO Nexus")
[Answer]
# [setlX](https://randoom.org/Software/SetlX), 62 bytes
```
[a,b]|->join([x/y:[x,y]in a><b],"+")+"="++/[x/y:[x,y]in a><b];
```
### ungolfed:
```
[a,b]|-> define a function with parameters a and b
join(
[ x/y : using set comprehension, make a list of fractions
[x,y] in a><b from the lists zipped together
],
"+"
) join them with "+"
+ "=" concat with an equals sign
+ concat with
+/[x/y:[x,y]in a><b] the sum of the list
;
```
[](https://i.stack.imgur.com/Xbh9l.png)
[Answer]
# [Haskell](https://www.haskell.org/) (Lambdabot), ~~94~~ ~~91~~ 86 bytes
```
t=tail.((\[n,_,d]->'+':n++'/':d).words.show=<<)
a#b|f<-zipWith(%)a b=t f++'=':t[sum f]
```
[Try it online!](https://tio.run/##ZY6xasMwEIZ3P8VBKJbwWcVKCK2xuqRrli4dXBOU2saitmSkC6Gl7@6qNG2H3L8c3/8d3KDDWzeOi5lm5wl2zpJ3o9g7q9vkAh81afGkybiFFGkzCsZeaosHbJv8Ic3S0mZZepuWLRdn59sgwuDOqqp4olfHz77KP8z8bGhgN1zDURH00VdpSXU4TdA3C3WBdjp0AVQCUAOrC5S4jtk2GIHE@7hL3DQ89hh7@c1/p/7nBf5EXu42eIfFFtfyysiLqFwZTZJM2lhQMOl5fwA2e2NJnOzryft3YCvO4e/b5Qs "Haskell – Try It Online")
Thanks @Laikoni for `-8` bytes!
### Ungolfed
```
-- convert each fraction to a string (has format "n%d", replace '%' with '/' and prepend '+' ("+n/d"), keep the tail (dropping the leading '+')
t = tail.((\[n,_,d]->'+':n++'/':d).words.show=<<)
-- build a list of fractions
a # b = let f = zipWith(%) a b in
-- stringify that list, append "=" and the stringified sum of these fractions
t f ++ "=" ++ t [sum f]
```
[Answer]
# Google Sheets, ~~83~~ 81 bytes
```
=ArrayFormula(JOIN("+",TRIM(TEXT(A:A/B:B,"?/???")))&"="&TEXT(sum(A:A/B:B),"?/???"
```
Saved 2 bytes thanks to Taylor Scott
Sheets will automatically add 2 closing parentheses to the end of the formula.
The two arrays are input as the *entirety* of columns `A` and `B`. Empty rows below the inputs will throws errors.
[Answer]
# Perl 6, ~~72 bytes~~ 65 bytes
Native and automatic rationals *should* make this easy, but default stringification is still as decimal, so we have to `.nude` (*nu*merator and *de*nominator) which kills our score and makes the 1 ugly :(
```
my \n = 1,2,3,3,6; my \d = 2,9,3,2,4;
(n Z/d)».nude».join("/").join("+")~"="~([+] n Z/d).nude.join("/")
```
Update: Removed unneeded brackets, kill more space and use smarter map. Saves characters over Brad's solution at the cost of no not being a lambda sub.
[Answer]
# R, 109 bytes
```
f=MASS::fractions;a=attributes
g=function(n,d)paste(paste(a(f(n/d))$f,collapse='+'),a(f(sum(n/d)))$f,sep='=')
```
requires the `MASS` library (for its `fractions` class). the function `g` returns the required output as a string.
[Try it online!](http://www.r-fiddle.org/#/fiddle?id=9f63cHQN) (R-fiddle link)
[Answer]
# TI-BASIC, 100 bytes
```
:L₁⁄L₂ //Creates a fraction from Lists 1 & 2, 7 bytes
:toString(Ans→Str1 //Create string from list, 7 bytes
:inString(Ans,",→A //Look for commas, 9 bytes
:While A //Begin while loop, 3 bytes
:Str1 //Store Str1 to Ans, 3 bytes
:sub(Ans,1,A-1)+"+"+sub(Ans,A+1,length(Ans)-A→Str1 //Replace "," with "+", 33 bytes
:inString(Ans,",→A //Check for more commas, 9 bytes
:End //End while loop, 2 bytes
:Str1 //Store Str1 to Ans, 3 bytes
:sub(Ans,2,length(Ans)-2 //Remove opening and closing brackets, 13 bytes
:Ans+"="+toString(expr(Ans //Add "=" and answer, 11 bytes
```
Note the `⁄` at the beginning, different from `/`. This makes the fractions hold their forms. It **does** work with negative fractions.
*Sigh*. TI-BASIC is *horrible* with strings. If all we had to do was print the fractions, and then their sum, the code would be:
### TI-BASIC, 12 bytes
```
:L₁⁄L₂ //Create fractions from lists, 7 bytes
:Disp Ans //Display the above fractions, 3 bytes
:sum(Ans //Display the answer, 2 bytes
```
That means that **88 bytes** of my code is spent just formatting the answer! *Hmph*.
[Answer]
# C, 171 bytes
[**Try Online**](http://ideone.com/JPdAZC)
```
i;t;x;y;f(int s,int*a,int*b){x=*a;y=*b;while(++i<s)x=(y-b[i])?(x*b[i])+(a[i]*y):(x+a[i]),y=(y-b[i])?(b[i]*y):y;for(i=1;i<=(x<y?x:y);++i)t=(x%i==0&&y%i==00)?i:t;x/=t;y/=t;}
```
[Answer]
# Axiom, 212 bytes
```
C==>concat;S==>String;g(a)==C[numerator(a)::S,"/",denom(a)::S];h(a:List PI,b:List PI):S==(r:="";s:=0/1;#a~=#b or #a=0=>"-1";for i in 1..#a repeat(v:=a.i/b.i;s:=s+v;r:=C[r,g(v),if i=#a then C("=",g(s))else"+"]);r)
```
test
```
(5) -> h([1,3,4,4,5,6], [2,9,5,5,6,7])
(5) "1/2+1/3+4/5+4/5+5/6+6/7=433/105"
Type: String
(6) -> h([1,3,4,4], [2,9,5,5,6,7])
(6) "-1"
Type: String
```
[Answer]
# Casio Basic, 161 Bytes
```
Dim(List 1)->A
for 1->I to A step 1
3*I-2->B
List 1[I]->C
List 2[I]->D
locate 1,B,C
locate 1,B+1,"/"
locate 1,B+2,D
C/D+E->E
next
locate 1,B+3,"="
locate 1,B+4,E
```
Explanation:
* Number of input is saved in `A`
* `A` iterations
* `B` acts as a counter for correct displaying
* `I`'th item of List 1 and 2 saved in `C` and `D`
* Displaying of Variable `C` / Variable `D`
* save `C`/`D`+`E` in `E`
* After last number locate `=` and `E`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 12 bytes
```
/₌≬vS\+j∑\=$
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaoiLCIiLCIv4oKM4omsdlNcXCtq4oiRXFw9JCIsIiIsIlsyLCA5LCAzLCAyLCA0XVxuWzEsIDIsIDMsIDMsIDZdIl0=)
10 bytes of this is just getting the formatting right... /:
## Explained
```
/₌≬vS\+j∑\=$
/ # divide the lists, vectorising
₌≬vS\+j # join each fraction on "+" (there's a bug where they get converted to decimal without vS :/)
∑ # get the sum of the fractions.
\=$ # place a "=" between the two
# the Ṫ flag prints the entire stack without spaces. If it wasn't for the aforementioned joining bug, the last $ could be a j and the flag wouldn't be needed.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 32 bytes
```
/YQv'%i/%i+'wYD3L)61yUYQVwV47b&h
```
Try at [MATL online!](https://matl.io/?code=%2FYQv%27%25i%2F%25i%2B%27wYD3L%2961yUYQVwV47b%26h&inputs=%5B1%2C+2%2C+3%2C+3%2C+6%5D%0A%5B2%2C+9%2C+3%2C+2%2C+4%5D&version=19.11.0)
### Explanation
Consider `[1, 2, 3, 3, 6]`, `[2, 9, 3, 2, 4]` as input.
```
/ % Implicit inout. Divide element-wise
% STACK: [0.5 0.222 1 1.5 1.5]
YQ % Rational approximation (with default tolerance)
% STACK: [1 2 1 3 3], [2 9 1 2 2]
v % Conctenate all stack elements vertically
% STACK: [1 2; 2 9; 1 2; 3 2; 3 2]
'%i/%i+' % Push this string (sprintf format specifier)
% STACK: [1 2; 2 9; 1 2; 3 2; 3 2], '%i/%i+'
wYD % Swap, sprintf
% STACK: '1/2+2/9+1/1+3/2+3/2+'
3L) % Remove last entry
% STACK: '1/2+2/9+1/1+3/2+3/2'
61 % Push 61 (ASCII for '=')
% STACK: '1/2+2/9+1/1+3/2+3/2', 61
y % Duplicate from below
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '1/2+2/9+1/1+3/2+3/2'
U % Evaluste string into a number
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, 4.722
YQ % Rational approximation
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, 85, 18
VwV % Convert to string, swap, convert to string
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85'
47 % Push 47 (ASCII for '/')
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85', 47
b % Bubble up in stack
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '85', 47, '18'
&h % Concatenate all stack elements horizontally. Implicitly display
% STACK: '1/2+2/9+1/1+3/2+3/2=85/18'
```
] |
[Question]
[
# Introduction
A xenodrome in base *n* is an integer where all of its digits in base *n* are different. [Here](https://oeis.org/search?q=Xenodromes) are some OEIS sequences of xenodromes.
For example, in base 16, `FACE`, `42` and `FEDCBA9876543210` are some xenodromes (Which are `64206`, `66` and `18364758544493064720` in base 10), but `11` and `DEFACED` are not.
# Challenge
Given an input base, *n*, output out all xenodromes for that base *in base 10*.
The output should be in order of least to greatest. It should be clear where a term in the sequence ends and a new one begins (e.g. `[0, 1, 2]` is clear where `012` is not.)
*n* will be an integer greater than 0.
## Clarifications
This challenge does IO specifically in base 10 to avoid handling integers and their base as strings. The challenge is in abstractly handling any base. As such, I am adding this additional rule:
**Integers cannot be stored as strings in a base other than base 10.**
Your program should be able to theoretically handle reasonably high *n* if there were no time, memory, precision or other technical restrictions in the implementation of a language.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program, in bytes, wins.
# Example Input and Output
```
1 # Input
0 # Output
```
```
2
0, 1, 2
```
```
3
0, 1, 2, 3, 5, 6, 7, 11, 15, 19, 21
```
```
4
0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 18, 19, 24, 27, 28, 30, 33, 35, 36, 39, 44, 45, 49, 50, 52, 54, 56, 57, 75, 78, 99, 108, 114, 120, 135, 141, 147, 156, 177, 180, 198, 201, 210, 216, 225, 228
```
[Answer]
# [Pyth](http://github.com/isaacg1/pyth), 8 bytes
```
f{IjTQU^
```
Filters the numbers in **[0, n^n - 1]** on having no duplicate elements in base **n**. The base conversion in Pyth will work with any base, but since this looks at a very quickly increasing list of numbers, it will eventually be unable to store the values in memory.
[Try it online!](http://pyth.tryitonline.net/#code=ZntJalRRVV4&input=NA)
### Explanation:
```
f{IjTQU^QQ - Auto-fill variables
U^QQ - [0, n^n-1]
f - keep only those that ...
{I - do not change when deduplicated
jTQ - are converted into base n
```
[Answer]
# Python 2, 87 bytes
```
n=input()
for x in range(n**n):
s={n};a=x
while{a%n}|s>s:s|={a%n};a/=n
print-~-a*`x`
```
Prints extra blank lines for non-xenodromes:
```
golf % python2.7 xenodromes.py <<<3
0
1
2
3
5
6
7
11
15
19
21
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ð*ḶbQ€Qḅ
```
*Thanks to @JonathanAllan for golfing off 1 byte!*
[Try it online!](http://jelly.tryitonline.net/#code=w7Aq4bi2YlHigqxR4biF&input=&args=Mw) or [verify all test cases](http://jelly.tryitonline.net/#code=w7Aq4bi2YlHigqxR4biFCsOH4oKsRw&input=&args=MSwgMiwgMywgNA).
### How it works
```
ð*ḶbQ€Qḅ Main link. Argument: n
ð Make the chain dyadic, setting both left and right argument to n.
This prevents us from having to reference n explicitly in the chain.
* Compute nⁿ.
Ḷ Unlength; yield A := [0, ..., nⁿ - 1].
b Convert each k in A to base n.
Q€ Unique each; remove duplicate digits.
Q Unique; remove duplicate digit lists.
ḅ Convert each digit list from base n to integer.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*`ḶbµQ⁼$Ðfḅ³
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=KmDhuLZiwrVR4oG8JMOQZuG4hcKz&input=&args=Mw)**
Will work for any `n`, given enough memory, Jelly's base conversion is not restrictive.
### How?
```
*`ḶbµQ⁼$Ðfḅ³ - Main link: n
µ - monadic chain separation
* - exponentiation with
` - repeated argument, i.e. n^n
Ḷ - lowered range, i.e. [0,1,2,...,n^n-1]
b - covert to base n (vectorises)
Ðf - filter keep:
$ - last two links as a monad
Q - unique elements
⁼ - equals input (no vectorisation)
³ - first program argument (n)
ḅ - convert from base (vectorises)
```
[Answer]
## JavaScript (ES7), 86 bytes
```
n=>{a=[];for(i=n**n;i--;j||a.unshift(i))for(j=i,b=0;(b^=f=1<<j%n)&f;j=j/n|0);return a}
```
[Answer]
# [Perl 6](https://perl6.org), 47 bytes
```
{(0..$_**$_).grep: !*.polymod($_ xx*).repeated}
```
Returns a [Seq](https://docs.perl6.org/type/Seq). ( [Seq](https://docs.perl6.org/type/Seq) is a basic [Iterable](https://docs.perl6.org/type/Iterable) wrapper for [Iterator](https://docs.perl6.org/type/Iterator)s )
With an input of `16` it takes 20 seconds to calculate the 53905th element of the Seq (`87887`).
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
( 0 .. ($_ ** $_) ) # Range of values to be tested
.grep: # return only those values
!\ # Where the following isn't true
*\ # the value
.polymod( $_ xx * ) # when put into the base being tested
.repeated # has repeated values
}
}
```
[Answer]
## Batch, ~~204~~ 200 bytes
```
@set/an=%1,m=1
@for /l %%i in (1,1,%1)do @set/am*=n
@for /l %%i in (0,1,%m%)do @set/ab=0,j=i=%%i&call:l
@exit/b
:l
@set/a"f&=b^=f=1<<j%%n,j/=n"
@if %f%==0 exit/b
@if %j% gtr 0 goto l
@echo %i%
```
Won't work for n > 9 because Batch only has 32-bit arithmetic. Conveniently, Batch evaluates `f &= b ^= f = 1 << j % n` as `f = 1 << j % n, b = b ^ f, f = f & b` rather than `f = f & (b = b ^ (f = 1 << j % n))`.
[Answer]
# Mathematica, ~~59~~ 48 bytes
```
Select[Range[#^#]-1,xMax[x~DigitCount~#]==1]&
```
Contains U+F4A1 "Private Use" character
# Explanation
```
Range[#^#]-1
```
Generate `{1, 2, ..., n^n}`. Subtract 1. (yields `{0, 1, ..., n^n - 1}`)
```
xMax[x~DigitCount~#]==1
```
A Boolean function: `True` if each digit occurs at most once in base `n`.
```
Select[ ... ]
```
From the list `{0, 1, ..., n^n - 1}`, select ones that give `True` when the above Boolean function is applied.
**59 byte version**
```
Select[Range[#^#]-1,xDuplicateFreeQ[x~IntegerDigits~#]]&
```
[Answer]
# Mathematica, ~~48~~ 55 bytes
```
Union[(x x~FromDigits~#)/@Permutations[Range@#-1,#]]&
```
(The triple space between the `x`s needs to be replaced by the 3-byte character \uF4A1 to make the code work.)
Unnamed function of a single argument. Rather than testing integers for xenodromicity, it simply generates all possible permutations of subsets of the allowed digits (which automatically avoids repetition) and converts the corresponding integers to base 10. Each xenodrome is generated twice, both with and without a leading 0; `Union` removes the duplicates and sorts the list to boot.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
eʁ'?τÞu
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJlyoEnP8+Ew551IiwiIiwiMyJd)
```
ʁ # Range(0,
e # n**n
' # Filtered by...
?τ # Convert to base n
Þu # All unique?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ 13 bytes
```
ʁṖƛÞSƛṖ⁰vβ]fU
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgeG5lsabw55TxpvhuZbigbB2zrJdZlUiLCIiLCIzIl0=)
```
ʁṖƛÞSƛṖ⁰vβ]fU
ʁ # Range [0, n)
Ṗƛ ] # For each permutation:
ÞSƛ # For each sublist in the permutation:
Ṗ # Generate the permutations of that
v # For each permutation:
β # Treating it as a list of digits, convert to base 10 from base
⁰ # <the input>
f # Flatten the resulting list
U # Remove duplicates
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~100~~ 80 bytes
*-20 bytes thanks to [@Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)*
```
f k=[n|n<-[0..k*k^k],let x#0=1>0;x#n|m<-mod n k=notElem m x&&(m:x)#div n k,[]#n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h2zY6rybPRjfaQE8vWys7LjtWJye1RKFC2cDW0M7AukI5rybXRjc3P0UhD6g2L7/ENSc1VyFXoUJNTSPXqkJTOSWzDCSlEx2rnBf7PzcxM0/BVqGgtCS4pEhBRaE4I78cSKUpmPwHAA "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 73 bytes
```
->n,*a{i=-1
n>1?(0..n**n).filter_map{i+=1
d=i.digits(n)
i if d==d&d}:[0]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3PXXt8nS0EqszbXUNufLsDO01DPT08rS08jT10jJzSlKL4nMTC6oztW0NuVJsM_VSMtMzS4o18jS5MhUy0xRSbG1T1FJqraINYmshBu4uUHCLNozlAlFGEMoYQpnEQlQsWAChAQ)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
o à cá mìU â ñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byDgIGPhIG3sVSDiIPE&input=NC1R)
Explanation:
```
o à cá mìU â ñ
o # Get the range [0...input]
à # Find all arrays containing unique items from that range
cá # Find all orderings for each of those arrays
m # For each one:
U # Treat it as an array of base-input digits
ì # Convert it to a base-10 number
â # Remove duplicates
ñ # Sort by ascending value
```
[This alternative](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cFUgbyBmX3NVIKVac1Ug4g&input=NA) and [this other alternative](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cFUgbyBmX3NVIPEg5C0gZQ&input=NA) are longer, but seems like that strategy could become shorter if someone finds a better way to check for "contains no duplicate elements".
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
mÝʒIвDÙQ
```
[Try it online](https://tio.run/##yy9OTMpM/f8/9/DcU5M8L2xyOTwz8P9/EwA) or [verify all test cases](https://tio.run/##ASwA0/9vc2FiaWX/NUVOPyIg4oaSICI/TkTCqf9tw53KksKu0LJEw5lR/30swrY//w).*†*
**Explanation:**
```
m # Push the (implicit) input to the power of the (implicit) input: nⁿ
Ý # Pop and push a list in the range [0,nⁿ]
ʒ # Filter this list by:
Iв # Convert the integer to base-input as list
DÙQ # Check if all items in this list are unique:
D # Duplicate the list
Ù # Uniquify the items in the copy
Q # Check if the two lists are still the same
# (after which the result is output implicitly)
```
† Note: input \$n=1\$ will output as `[0,1]` instead of `[0]`. This could be fixed in +1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) by adding a `¨` after the `Ý`, to make the range \$[0,n^n)\$ instead. However, I'd argue for \$n=1\$ it should be allowed to output either `[0]` or `[0,1]`. If base-1 follows the same rules as the other bases, only `0` can be represented, making it practically useless. Because of that, bijective base-1 (aka [unary](https://en.wikipedia.org/wiki/Unary_numeral_system)) is usually used instead when someone talks about base-1, in which case:
1. \$n=0\$ as bijective base-1 will have an empty result (technically all unique)
2. \$n=1\$ as bijective base-1 results in a single tally mark (thus all unique)
3. \$n\geq2\$ as bijective base-1 results in \$n\$ amount of tally mark (thus not all unique)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
pU ÇìU'âÃâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cFUgx%2bxVJ%2bLD4g&input=NA)
```
pU ÇìU'âÃâ :Implicit input of integer U
pU :Raised to the power of itself
Ç :Map the range [0,U**U)
ìU : Convert to base U digit array
'â : Deduplicate and convert back to integer
à :End map
â :Deduplicate
```
] |
[Question]
[
A guitar fretboard diagram looks like this:
```
0 1 2 3 4 5 6 7 8 9 10 11 12 <- Fret number (0 means it's open)
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E
|-B--C--C#-D--D#-E--F--F#-G--G#-A--A#-B
|-G--G#-A--A#-B--C--C#-D--D#-E--F--F#-G
|-D--D#-E--F--F#-G--G#-A--A#-B--C--C#-D
|-A--A#-B--C--C#-D--D#-E--F--F#-G--G#-A
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E
```
As you can see, the first string (from the top) open is an `E`. The first fret on the first string is an `F`. The fourth fret on the third string is a `B`. Note that the first note is the zeroth fret, not the first.
This can be written with numbers on the format `string, fret`. The strings are numbered from 1 to 6 from top to bottom.
The frets are numbered from 0 to 12 from left to right. The first `E` is therefore `1, 0`. Some other examples:
```
1, 0 --> E
1, 1 --> F
3, 5 --> C
5, 1 --> A#
6, 6 --> A#
```
**Challenge:**
Take `N` pairs of numbers (`s` and `f`), and output a delimited note succession.
* The input may be on any suitable format. tuples, 2D-matrix, two separate lists, an interweaved list (string,fret,string,fret...) etc.
* The output tone should be separated, but the delimiter is optional (comma, space, dash...). The output can be in either upper or lower case.
* `s` (for string) will be in the range `[1, 6]` (you may choose to have i 0-indexed)
* `f` (for fret) will be in the range `[0, 12]`
**Test cases and examples:**
```
1 4 5 2 1 3 <- String
4 2 6 3 5 1 <- Fret
G# E D# D A G#
6 2 3 1 4 2 3 2 2 2 6 5 2
0 1 2 3 4 5 6 7 8 9 10 11 12
E C A G F# E C# F# G G# D G# B
3 3 3 3 3 3 3 3 3 3 3 3 3 <- String
0 3 5 0 3 6 5 0 3 5 3 0 0 <- Fret
G A# C G A# C# C G A# C A# G G
// The same test case, but different input and output format:
(3,0)(3,3)(3,5)(3,3)(3,6)(3,5)(3,0)(3,3)(3,5)(3,3)(3,0)(3,0)
G,A#,C,G,A#,C#,C,G,A#,C,A#,G,G
```
Good luck, and happy golfing!
[Answer]
## JavaScript (ES6), ~~79~~ 70 bytes
```
a=>a.map(([s,f])=>"AA#BCC#DD#EFF#GG#".match(/.#?/g)[(s*7+(s>2)+f)%12])
```
Requires 1-based strings. Edit: Saved 9 bytes by directly calculating the string to fret conversion, based on @nimi's old answer.
[Answer]
# Mathematica, 62 bytes (non-competing)
```
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&
```
The `{24,19,15,10,5,0}` and the `E2` represent the open-string tones of the six guitar strings (for example, the top string is 24 semitones above the note E2). Non-competing because it doesn't print the names of the notes—it *plays* the sequence of notes! (only if you have Mathematica, unfortunately) For example,
```
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&@
{{4,0},{3,2},{2,3},{1,2},{5,0},{4,2},{3,2},{2,2},
{5,2},{4,4},{2,0},{2,3},{6,2},{4,4},{3,2},{2,2},
{6,3},{4,0},{3,0},{2,0},{4,0},{4,4},{3,2},{2,3},
{6,3},{3,0},{2,0},{2,3},{5,0},{4,2},{3,2},{2,2},{4,0}}
```
plays the opening 4 bars or so from Pachelbel's Canon. (which is about as much of Pachelbel's Canon as I can stand)
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~48~~ ~~47~~ 45 bytes
*Thanks to @Emigna for a correction regarding input format.*
Guitar and code golf... I had to answer this one!
```
'$)-27<'i)-'F F# G G# A A# B C C# D D#
```
Input format is: an array of (1-based) string, then an array of (0-based) frets.
[Try it online!](http://matl.tryitonline.net/#code=JyQpLTI3PCdpKS0nRiBGIyBHIEcjIEEgQSMgQiBDIEMjIEQgRCMgRSdZYncp&input=WzEgMSAzIDUgNl0KWzAgMSA1IDEgNl0K)
### Explanation
Some language features used in this answer:
* A string is *automatically converted* to a numerical array of ASCII code
points when some arithmetic operation is applied to it.
* Arithmetical operations work *element-wise*, i.e. vectorized. So the subtraction of a string and a numerical array of the same size gives an array with the subtraction of corresponding entries.
* Indexing is 1-based and *modular*.
* A *cell array* is like a list in other languages. It can contain arbitrary elements, possibly arrays of different types or sizes. Here a cell array will be used to store strings of different lengths (the notes' names).
Commented code:
```
'$)-27<' % Push this string
i % Take first input (array of guitar strings)
) % Index into the string. For example, input [1 3] gives
% the string '$-' (indexing is 1-based)
- % Implicitly take second input (array of guitar frets).
% Subtract element-wise. This automatically converts the
% previous string into an array of ASCII codes. For
% example, second input [1 5] gives a result [-35 -40],
% which is [1 5] minus [36 45], where 36 and 45 are the
% ASCII codes of '$-'
'F F# G G# A A# B C C# D D# E' % Push this string
Yb % Split at spaces. Gives a cell array of 12 (sub)strings:
% {'F', 'F#', 'G', ..., 'E'}
w) % Swap and index into the cell array of strings.
% Indexing is 1-based and modular. In the example, since
% the cell array has 12 elements, the indexing array
% [-35 -40] is the same [1 8], and thus it gives a
% (sub-)array formed by the first and eighth cells:
% {'F', 'C'}. This is displayed as the cells' contents,
% one per line
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~48~~ ~~47~~ ~~43~~ 40 bytes
Uses [CP-1252](http://www.cp1252.com/) encoding.
Both strings and frets are 0-based.
```
v7YT5¾7)y`Šè+•™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£è,
```
**Explanation**
```
v # for each pair in input
7YT5¾7) # the list [7,2,10,5,0,7]
y` # flatten the pair [string, fret] and places on stack
Šè # index into the list above using the string
+ # add the fret
•™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£ # list of accords
è # index into the string using the number calculated above
, # print
```
[Try it online!](http://05ab1e.tryitonline.net/#code=djdZVDXCvjcpeWDFoMOoK-KAouKEosOOw5osw5xsdeKAosW-aCcjQcKr4oCh4oCiN1Yz4oCiM0JTwqPDqCw&input=W1swLDRdLFszLDJdLFs0LDZdLFsxLDNdLFswLDVdLFsyLDFdXQ)
Saved 7 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
[Answer]
# Java, 174
```
String f(int[]s,int[]f){String o="";for(int i=0;i<s.length;++i){int n =(7*s[i]-7+f[i]+(s[i]>2?1:0))%12*2;o+="E F F#G G#A A#B C C#D D#".substring(n,n+2).trim()+" ";}return o;}
```
Ungolfed:
```
String f(int[] s, int[] f) {
String o = "";
for (int i = 0; i < s.length; ++i) {
int n = (7 * s[i] - 7 + f[i] + (s[i] > 2 ? 1 : 0)) % 12 * 2;
o += "E F F#G G#A A#B C C#D D#".substring(n, n + 2).trim() + " ";
}
return o;
}
```
[Answer]
# C, 104 103 bytes
```
main(s,f){for(;~scanf("%d%d",&s,&f);printf("%.2s\n",
"E F F#G G#A A#B C C#D D#"+(f+7*~-s+(s>2))%12*2));}
```
Takes numbers as `string fret` pairs on stdin, and outputs the note after every pair. E.g.:
```
1 4
G#
4 2
E
5 6
D#
2 3
D
```
[Answer]
# Ruby, 63 bytes
takes an array of 2-element arrays, in the order `[string,fret]`.
```
->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}
```
**Explanation**
In standard tuning the guitar is one of the few stringed instruments (bowed or fretted) that has inconsistent intervals between its strings. Most have either a consistent 5-semitone interval between all pairs of adjacent strings (a "fourth") or a consistent 7-semitone interval between all pairs of adjacent strings (a "fifth.") These correspond to frequency ratios of 3:4 and 2:3 respectively, and are second in importance only to the "octave" with frequency ratio 1:2.
The guitar has mostly 5-semitone intervals. If it had 5 of these it would have a difference of 25 semitones between the 1st and 6th string. Instead, the interval between the 2nd and 3rd string is reduced to 4 semitones, giving a difference of 24 semitones (2 octaves) which is better for playing chords.
This is inconvenient for the program, so we start by changing the 1-indexed guitar intonation into a 0 indexed 5-string-bass intonation, which has all intervals of 5 semitones:
```
formula (i[0]-3)%5
Before After
String 6 5 4 3 2 1 String 4 3 2 1 0
Note E A D G B E Note B E A D G
```
Next we add 2, and give the tuning of a fictitious 12 string bass, with intonation of the open strings as follows, and all intervals being 5 semitones (12 string "basses" do exist but I am not sure there are many with precisely this tuning.)
```
String 11 10 9 8 7 6 5 4 3 2 1 0
Note A# D# G# C# F# B E A D G C F
```
As can be seen, all the sharps are grouped together. This pattern can be repeated ad infinitum. It is known as the "circle of fifths" and is fundamental to the Western musical scale (with a bit of tuning adjustment the circle can be closed due to the fact that `(3/2)**12` and `2**7` are very similar numbers.
Now we deal with the fret parameter. Unlike many other answers here, which translate the string parameter into a number of frets, I translate the fret parameter into a number of strings. In the table above it can be seen that adding 7 to the string number puts us on a string whose note name is one semitone higher. (It's in a completely different octave but that does not matter.) So we add `i[1]*7` to the string number, and take it modulo 12:
```
n=(i[0]-3)%5+2+i[1]*7)%12
```
We subtract this from 6 to get a number in the range 6 to -5 and look up the letter in `BEADGCF` (Ruby allows negative indices to wrap around back to the end of the array.) If `n>=7` we need to add a `#` symbol to complete the output.
**Test program**
```
f=->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}
z=[[6, 2, 3, 1, 4, 2, 3, 2, 2, 2, 6,5,2],[0, 1, 2, 3, 4 ,5 ,6 ,7, 8, 9, 10, 11, 12]].transpose
puts f[z]
```
**Output**
```
E
C
A
G
F#
E
C#
F#
G
G#
D
G#
B
```
[Answer]
# C#, 131 bytes
```
string n(int[]s,int[]f){return string.Join(" ",s.Zip(f,(x,y)=>"E,F,F#,G,G#,A,A#,B,C,C#,D,D#".Split(',')[(7*x-7+y+(x<3?0:1))%12]));}
```
Input two separate lists, strings are 1 based.
[Answer]
# [Clora](https://github.com/opsxcq/cloralang), 55 bytes
`@T[0,7,2,10,5,0,7]+N%12@T[,A,A#,B,C#,D,D#,E,F,F#,G,G#]!`
Explanation
`@` numeric mode (read input as numbers)
`T[0,7,2,10,5,0,7]` Transform input using the array, ex array[Input]
`+N` Add N (Next input value) to current Input
`%12` Modulo 12 the current input value
`@` Flag numeric mode off
`T[,A,A#,B,C#,D,D#,E,F,F#,G,G#]` Translate the input into an array
`!` Use input as output value
[Answer]
# Java 7 ~~197~~,163 bytes
```
void f(int[]s,int[]f){String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};int[]d={0,7,2,10,5,0,7};int j=0;for(int i:s)out.print(l[(d[i]+f[j++])%12]);}
```
# Ungolfed
```
void f(int[]s,int[]f){
String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};
int[]d={0,7,2,10,5,0,7};
int j=0;
for(int i:s)
out.print(l[(d[i]+f[j++])%12]);
}
```
[Answer]
# Python 2, ~~94, 91~~, 88 bytes
```
for s,f in input():print"A A# B C C# D D# E F F# G G#".split()[([7,2,10,5,0,7][s]+f)%12]
```
There are probably some obvious improvements to be made. Input is a list of pairs, and the strings are 0-indexed, e.g:
```
[0, 4], [3, 2], [4, 6]...
```
[Answer]
## Haskell, ~~83~~ 82 bytes
```
zipWith$(!!).(`drop`cycle(words"A# B C C# D D# E F F# G G# A")).([6,1,9,4,11,6]!!)
```
Takes a list of strings and a list of frets, both 0-indexed. Usage example:
```
Prelude > ( zipWith$(!!).(`drop`cycle$words"A# B C C# D D# E F F# G G# A").([6,1,9,4,11,6]!!) ) [0,1,2,3,4,5] [0,0,0,0,0,0]
["E","B","G","D","A","E"]
```
From the infinite list of notes starting with `A#`, drop the number of notes given by the list `[6,1,9,4,11,6]` at index of the string and pick the note at index of the fret from the remaining list.
[Answer]
# JavaScript (ES6), ~~82~~ 81 bytes
```
a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))
```
I wanted to try an all-math answer, but it turned out a little long. Maybe there's a way to golf it...
### Test snippet
```
f=a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))
console.log(f([[4,1],[2,4],[6,5],[3,2],[5,1],[1,3]]))
```
[Answer]
# PHP, 102 Bytes
```
<?foreach($_GET[i]as$t)echo[E,F,"F#",G,"G#",A,"A#",B,C,"C#",D,"D#"][[0,7,3,10,5][$t[0]%5]+$t[1]%12]._;
```
Input as multiple array both 0 based for example '[[2,0],[5,3],[2,12],[3,8],[0,3]]'
Nice alternative 106 Bytes to set the # based on [mod 7 congruent](https://oeis.org/A047292)
```
<?foreach($_GET[i]as$t)echo EFFGGAABCCDD[$d=[0,7,3,10,5][$t[0]%5]+$t[1]%12].["","#"][$d%7?$d%7%2?0:1:0]._;
```
] |
[Question]
[
**The formula**
Take for instance the number 300
* The prime factors of 300 are `[2, 3, 5]` (unique numbers that are
factors of 300 and prime)
* Squaring each of those numbers will give
you `[4, 9, 25]`
* Summing that list will give you `4 + 9 + 25 = 38`
* Finally subtract that sum (38) from your original number `300-38 = 262` (this is the result)
---
**Input**
Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.
---
**Output**
Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)
---
**Test Cases**
```
Input: 3 Output: 2, -2
Input: 10 Output: 8, 4
Input: 50 Output: 48, 35
Input: 1000 Output: 1000, 971
Input: 9999 Output: 9984, 9802
```
---
**Worked Through Example**
Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)
```
Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2 [2] [4] 4 -2
3 [3] [9] 9 -6
4 [2] [4] 4 0
5 [5] [25] 25 -20
6 [2, 3] [4, 9] 13 -7
7 [7] [49] 49 -42
8 [2] [4] 4 4
9 [3] [9] 9 0
10 [2, 5] [4, 25] 29 -19
```
As you can see the greatest result is `4`, which was a result of inputting the value `8` into the formula. That means the output for an input of `10` should be `8, 4`
---
**Scoring & Rules**
The default rules for inputs and outputs apply: [Default for Code Golf: Input/Output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
The standard loopholes are forbidden: [Loopholes that are forbidden by default](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?page=1&tab=active#tab-top)
Submissions can be functions or full programs
Shortest code in bytes wins
[Answer]
# Pyth, ~~17~~ 15 bytes
```
_eSttm,-ds^R2{P
```
[Test suite.](http://pyth.herokuapp.com/?code=_eSttm%2C-ds%5ER2%7BP&test_suite=1&test_suite_input=3%0A10%0A50%0A1000%0A9999&debug=0)
[Answer]
## Java 8 lambda, ~~247~~ ~~239~~ ~~233~~ ~~225~~ ~~224~~ ~~219~~ ~~198~~ 161 characters
I thought that must be possible in under 300 chars because... you know... Java!
And it is indeed possible even in under 200 chars!
```
m->{int n=1,u,f,F[],g,G=g=1<<31;for(;++n<=m;){u=n;F=new int[m+1];for(f=1;++f<=u;)u/=u%f<1?(F[f]=f--):1;f=0;for(int p:F)f+=p*p;g=n-f>g?(G=n)-f:g;}return G+","+g;}
```
~~I don't know whether this use of imports is legit but I assume, that it should be okay.~~ Here is the lambda ungolfed into a class:
```
public class Q80507 {
static String greatestAfterReduction(int maxNumber) {
int number = 1, upper, factor, primeFactors[], greatestResult, greatestNumber = greatestResult = 1 << 31; // <-- Integer.MIN_VALUE;
for (;++number <= maxNumber;) {
// get unique primefactors
upper = number;
primeFactors = new int[maxNumber + 1];
for (factor = 1; ++factor <= upper;)
upper /= upper % factor < 1 ? (primeFactors[factor] = factor--) : 1;
factor = 0;
for (int prime : primeFactors)
factor += prime * prime;
greatestResult = number - factor > greatestResult ? (greatestNumber = number) - factor : greatestResult;
}
return greatestNumber + "," + greatestResult;
}
}
```
The primefactor-finding is based on [this answer](https://stackoverflow.com/a/4447077/3764634). The code uses the functionality of sets as they only save each value once, thus I don't have to care about added duplicates later on. The rest of the code is pretty straight forward, just following the question.
### Updates
Removed the newline from the output.
Thanks to @ogregoire for golfing the Integer.MIN\_VALUE to 1<<31!
After looking on the code again I found some more places where things could been golfed.
Thanks to @Blue for the ==0 to <1 trick!
Removed some leftover whitespace. Also for separation only one char is needed so no need to waste one char.
Thanks again to @ogregoire for pointing out that I can return the value instead of printing it and putting together the declarations! This saved a lot!
Found out I can use a ternary instead of the second if to save one more char.
Thanks to @AstronDan for the **awesome** usage of an array which saves the import. That also gave me the possibility to shorten the first if into a ternary.
[Answer]
## Actually, 21 bytes
```
u2x;`;y;*@-`M;M;)@í@E
```
[Try it online!](http://actually.tryitonline.net/#code=dTJ4O2A7eTsqQC1gTTtNOylAw61ARQ&input=MTA)
Explanation:
```
u2x;`;y;*@-`M;M;)@í@E
u2x; push two copies of range(2, n+1) ([2, n])
` `M map:
; duplicate
y; push two copies of prime divisors
* dot product of prime divisors lists (equivalent to sum of squares)
@- subtract from n
;M;) duplicate, two copies of max, move one copy to bottom of stack
@í get index of max element
@E get corresponding element from range
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
:"@tYfu2^s-]v2#X>w
```
[**Try it online!**](http://matl.tryitonline.net/#code=OiJAdFlmdTJecy1ddjIjWD53&input=NTA)
The last case takes too long for the online compiler, but it produces the correct result (it takes about 11 seconds in my computer, running on Matlab):
[](https://i.stack.imgur.com/yk4ei.png)
### Explanation
Straightforward application of the described procedure.
```
: % Implicit input n. Range [1 2 ... n]
" % For each
@ % Push that number
tYfu % Duplicate. Prime factors. Unique values
2^s- % Square. Sum of array values. Subtract
] % End for each
v % Concatenate stack contents into vertical vector
2#X> % Max and arg max
w % Swap. Implicit display
```
[Answer]
## 05AB1E, ~~19~~ ~~17~~ 16 bytes
**Code:**
```
L©f€n€O®-®)ø¦{¤R
```
**Explanation:**
```
L # make a list of 1..input [1,2,3,4,5,6]
© # save the list for reuse
f # get primefactors of numbers in list [[],[2],[3],[2],[5],[2,3]]
€n # square each factor [[],[4],[9],[4],[25],[4,9]]
€O # sum the factors [0,4,9,4,25,13]
®- # subtract from saved list [1,-2,-6,0,-20,-7]
®)ø # zip with saved list [[1,1],[-2,2],[-6,3],[0,4],[-20,5],[-7,6]]
¦ # drop the first item (n=1) [[-2,2],[-6,3],[0,4],[-20,5],[-7,6]]
{ # sort [[-20,5],[-7,6],[-6,3],[-2,2],[0,4]]
¤ # get last item [0,4]
R # reverse [4,0]
```
[Try it online](http://05ab1e.tryitonline.net/#code=TMKpZuKCrG7igqxPwq4twq4pw7jCpnvCpFI&input=MTA)
[Answer]
## C#, 194 bytes
My first Code Golf :). I used my favorite language despite its verbosity. I started this as a C# function port of @Frozn's Java but found several ways to shrink the code further with optimizations.
```
string R(int a){int u,f,g,N=g=1<<31;for(int n=1;++n<=a;){u=n;int[]P=new int[a+1];for(f=1;++f<=u;){if(u%f<1){u/=f;P[f]=f--;}}f=0;foreach(var p in P){f+=p*p;}if(n-f>g){g=(N=n)-f;}}return N+","+g;}
```
This uses an array to store the prime factors. Because it is indexed by the factor it will replace repeated factors with copies of the factor. This allows the function to have no imports. This does not even require System.
[Answer]
# Bash + GNU utilities, 74
```
seq 2 $1|factor|sed -r 's/:?( \w+)\1*/-\1*\1/g'|bc|nl -v2|sort -nrk2|sed q
```
* `seq` generates all integers 2 to n
* `factor` gives the number followed by a colon, then a space separated list of all prime factors, including duplicates. e.g. the result for 12 is `12: 2 2 3`
* `sed` removes the colon and duplicate factors, then generates the required arithmetic expression. e.g. for 12: `12- 2* 2- 3* 3`
* `bc` evaluates this
* `nl` prefixes n back in (starting at 2)
* `sort` by the second column, numerically, in descending order
* `seq` prints the first line and quits.
[Ideone.](https://ideone.com/C0vHbi)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 48 bytes
```
:2:{eI$pd:{:2^.}a+:I--:I.}fF$\hor:0m:Ir.r~m[F:J]
```
### Explanation
```
Main predicate:
:2:{}fF Unify F with the list of all binding for which predicate 1 is
true, given [Input, 2] as input.
$\hor:0m Retrieve the max of F by diagonalizing it, taking the
first row, sorting that row and reversing the sorted row.
:Ir. Unify the Output with [I, Max],
r~m[F:J] [I, Max] is in F at index J (the index is unimportant)
Predicate 1:
eI I is an integer in the range given in Input
$pd Get the list of prime factors of I, with no duplicates
:{:2^.}a Apply squaring to each element of that list
+ Sum the list
:I- Subtract I from the sum
- Multiply by -1 (let's call it Result)
:I. Unify the Output with [Result, I]
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆfQ²S_@,µ€ḊṀṚ
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZmUcKyU19ALMK14oKs4biK4bmA4bma&input=&args=MTAwMA) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZmUcKyU19ALMK14oKs4biK4bmA4bmaCsOH4oKsRw&input=&args=MywgMTAsIDUwLCAxMDAwLCA5OTk5).
### How it works
```
ÆfQ²S_@,µ€ḊṀṚ Main link. Argument: n
µ Combine the chain to the left into a link.
€ Apply it to each k in [1, ..., n].
Æf Yield k's prime factors as a list.
Q Unique; deduplicate the prime factors.
² Square each unique prime factor.
S Compute their sum.
_@ Subtract the result from k.
, Pair with k, yielding [result(k), k].
Ḋ Dequeue; discard the first pair which corresponds to k = 1.
Ṁ Get the maximum (lexicographical order).
Ṛ Reverse the pair.
```
[Answer]
# Julia, 56 bytes
```
!n=maximum(k->(k-sumabs2(k|>factor|>keys),k),2:n)[[2,1]]
```
[Try it online!](http://julia.tryitonline.net/#code=IW49bWF4aW11bShrLT4oay1zdW1hYnMyKGt8PmZhY3Rvcnw-a2V5cyksayksMjpuKVtbMiwxXV0KCmZvciBuIGluICgzLCAxMCwgNTAsIDEwMDAsIDk5OTkpCiAgICBwcmludGxuKCFuKQplbmQ&input=)
### How it works
Given an input **n**, for each integer **k** such that **2 ≤ k ≤ n**, we generate the tuple **(f(k), k)**, where **f(k)** is the difference between **k** and the sum of the squares of its prime factors.
**f(k)** itself is calculated with `k-sumabs2(k|>factor|>keys)`, which factors **k** into a Dict of prime keys and exponent values, extracts all the keys (prime factors), takes the sum of their squares and subtracts the resulting integer from **k**.
Finally, we take the lexicographical maximum of the generated tuples and reverse it by accesing it at indices **2** and **1**.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
*Ties [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/80546/94066) for #1.*
```
L¦DfnO-Z©kÌ®)
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f59Ayl7Q8f92oQyuzD/ccWqf5/78lEAAA "05AB1E – Try It Online")
```
L¦DfnO-Z©kÌ®) # full program
k # push 0-based index of...
Z # maximum of...
# (implicit) list of...
O # sums of...
# (implicit) each element of list of...
f # unique prime factors of...
# (implicit) each element of...
L D # [1, 2, 3, ...,
# ..., implicit input...
L D # ]...
¦ # excluding the first element...
# (implicit) with each element...
n # squared...
# (implicit) with each element...
- # subtracted from...
# (implicit) corresponding element in...
L # [1, 2, 3, ...,
# ..., implicit input...
L # ]...
¦ # excluding the first element...
k # in...
# (implicit) list of...
O # sums of...
# (implicit) each element of list of...
f # unique prime factors of...
# (implicit) each element of...
L D # [1, 2, 3, ...,
# ..., implicit input...
L D # ]...
¦ # excluding the first element...
# (implicit) with each element...
n # squared...
# (implicit) with each element...
- # subtracted from...
# (implicit) corresponding element in...
L # [1, 2, 3, ...,
# ..., implicit input...
L # ]...
¦ # excluding the first element...
Ì # plus 2
Z© ® # push maximum of...
# (implicit) list of...
O # sums of...
# (implicit) each element of list of...
f # unique prime factors of...
# (implicit) each element of...
L D # [1, 2, 3, ...,
# ..., implicit input...
L D # ]...
¦ # excluding the first element...
# (implicit) with each element...
n # squared...
# (implicit) with each element...
- # subtracted from...
# (implicit) corresponding element in...
L # [1, 2, 3, ...,
# ..., implicit input...
L # ]...
¦ # excluding the first element
) # push stack
# implicit output
```
**Note:** If only the calculated number needed to be output, then 5 bytes could be saved by removing `©kÌ®)`.
[Answer]
## Clojure, 215 bytes
```
(fn j[x](apply max-key second(map(fn[w][w(- w(let[y(reduce +(map #(* % %)(set(flatten((fn f[q](let[c(filter(fn[r](=(mod q r)0))(range 2 q))](if(empty? c)q(map f c))))w)))))](if(= y 0)(* w w)y)))])(range 2(inc x)))))
```
Just follows the rules. Calculates prime factors of each number, put them to square and sum them. After that generate a list of vectors of 2 elements: initial number and its result and find the element with maximum value of second element.
You can see it online here: <https://ideone.com/1J9i0y>
[Answer]
## R 109 bytes
```
y=sapply(x<-2:scan(),FUN=function(x)x-sum(unique(as.numeric(gmp::factorize(x))^2)));c(x[which.max(y)],max(y))
```
I cheated and used a package, `gmp`.
[Answer]
# CJam, 32 bytes
```
ri({))_mf_|2f#:+-}/]_:e>_@#))\]p
```
[Try it online!](http://cjam.aditsu.net/#code=ri(%7B))_mf_%7C2f%23%3A%2B-%7D%2F%5D_%3Ae%3E_%40%23))%5C%5Dp&input=1000)
[Answer]
## Pyke, 17 bytes
```
FODP}mXs-)DSei@Oi
```
[Try it here!](http://pyke.catbus.co.uk/?code=FODP%7DmXs-%29DSei%40Oi&input=10)
[Answer]
## PowerShell v2+, ~~124~~ ~~120~~ 117 bytes
```
2..$args[0]|%{$y=$z=$_;2..$_|%{$y-=$_*$_*!($z%$_)*('1'*$_-match'^(?!(..+)\1+$)..')};if($y-gt$o){$o=$y;$p=$_}}
"$p $o"
```
The first line calculates the values, the second is just output.
We start with creating a range from `2` up to our command-line argument `$args[0]` and loop that `|%{...}`. Each loop we set helper variables equal to our current value with `$y=$z=$_`. We then loop through every number from `2` up to our current number. Each inner loop we check whether that number is a divisor `!($z%$_)` and whether it's [prime](https://codegolf.stackexchange.com/a/57636/42963) `('1'*$_-match'^(?!(..+)\1+$)..')`, and if it's both we subtract the square from `$y` (the checks are done using Boolean multiplication).
Once we've gone through all prime divisors and subtracted the squares, if the number remaining is the largest we've seen so far `$y-gt$o`, we set our output variables `$o=$y;$p=$_`. After we've looped through the whole range, we simply output with a space between.
[Answer]
## Haskell, 91 bytes
```
f m=reverse$maximum[[n-sum[p^2|p<-[2..n],mod n p<1,mod(product[1..p-1]^2)p>0],n]|n<-[2..m]]
```
Usage example: `f 50`-> `[48,35]`.
Prime factor functions are available only via `import Data.Numbers.Primes` which costs too many bytes, so I'm using [@Lynn's prime checker](https://codegolf.stackexchange.com/a/57704/34531). The rest is straight forward: for input `m` loop `n` through `[2..m]` and in an inner loop `p` through `[2..n]`. Keep all `p` that are prime and divide `n`, square and sum.
[Answer]
# Python 2, ~~108~~ ~~105~~ 100 bytes
```
f=lambda n,m=2,p=1:m>n or-~f(n,m+1,p*m*m)-(n%m<p%m)*m*m
r=max(range(2,input()+1),key=f)
print r,f(r)
```
Test it on [Ideone](http://ideone.com/Lus9E5).
[Answer]
## JavaScript (ES6), ~~111~~ 105 bytes
```
f=n=>{r=n<2?[]:f(n-1);for(s=[],j=n,i=2;j>1;k%i?i++:j/s[i]=i);s.map(i=>j-=i*i,j=n);return j<r[1]?r:[n,j]}
```
No idea why I didn't think to do this recursively before.
[Answer]
# J, 44 bytes
```
[:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.
```
Straight-forward approach. Also returns all values of `n` that result in a maximum value.
## Usage
```
f =: [:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.
f 3
2 _2
f 10
8 4
f 50
48 35
f 1000
1000 971
f 9999
9984 9802
f 950
900 862
945 862
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ḢλǏ²∑-;Z↑Ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuKLOu8ePwrLiiJEtO1rihpHhuYQiLCIiLCIxMDAwIl0=)
Maximum by tail is useless they said. No one ever uses it they said. Well look who's laughing now.
## Explained
```
ḢλǏ²∑-;Z↑Ṅ
Ḣ Z # Create a list of [x, f(x)] from range(2, input + 1) where f(x) =
λ ; # lambda x:
Ǐ # prime factors
² # squared
∑ # summed
- # subtracted from x
↑ # maximum by tail
Ṅ # joined on spaces
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Tried a few different approaches but can't seem to do better than 17 :\
```
ô í ¤mÇ-k â x²ÃñÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=9CDtIKRtxy1rIOIgeLLD8cw&input=OTk5OQ)
```
õ@[XX-k â x²]ÃÅñÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=9UBbWFgtayDiIHiyXcPF8cw&input=OTk5OQ)
] |
[Question]
[
**Your goal**: to write a piece of code that will result in the classic result of "Hello, world!" being printed to STDOUT or equivalent.
**Rules**: Code must be entirely in printing ASCII. All code must be functional - removal of any single counting character must change the result or cause the code to not function. All variables must be used after assignment. Character and String literals must be necessary to the output - that is, replacement of any character literal or any character within a string literal with another character must be capable of changing the result (and not via the effect of escape sequence - replacing character with backslash or equivalent)
(NOTE: Final rule was edited in)
**Scoring**: This is where it gets interesting. Highest score wins as determined by number of characters, as per typical code-bowling rules. But repeated use of characters will result in point deductions. Specifically...
1. Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not result in a deduction).
2. Repeated use of basic punctuation ([!?.-,":';]) - including the brackets - will result in a deduction of 2 points per repeat.
3. Repeated use of other ASCII characters {`~@#$%^&\*\_+=|\/><} - including the curly brackets - will result in a deduction of 4 points per repeat.
4. Repeated use of spaces, tabs, and newlines will result in a deduction of 1 point per repeat. That is, only the first use of a space, tab, or newline will count towards your total.
Note: comments do not count towards total, although the characters marking the start/end of a comment do. For instance, in C/C++, If you have `/* This is a comment */`, then it will count two slashes and two asterisks, but nothing between them.
Some **examples** (note: using Julia as sample language)...
```
print("Hello, world!");
```
Total visible characters: 22
Contains Space: +1
Repeated alphanumerics: -12 for llor
Repeated punctuation: -2 for "
Final score: 22+1-12-2 = 9
```
print("Hel",char(108),"o, wor",0x108,"d!"); # 0x108 makes a Uint8 that prints as ASCII
```
Total characters: 43 (does not count any characters after #, which is the comment character)
Contains Space: +1
Repeated alphanumerics: -18 for rr1008
Repeated punctuation: -24 for ()""""",,,,,
Final score: 43+1-24-18 = 2
```
xy=STDOUT
m="Hello, world!"
print(xy,m);
```
Total visible characters: 37
Contains Newline: +1
Contains Space: +1
Repeated alphanumerics: -18 for xyllor
Repeated punctuation: -4 for ",
Repeated other ASCII: -4 for =
Final score: 37+1+1-18-4-4 = 13
A couple of invalid pieces of code...
```
x=2;print("Hello,world!")
```
Problem: `x` is assigned, but not used.
```
print("Hello,"*" world!")
```
Problem: `*` is unnecessary, result will be the same without it.
```
k=1
if k>0
print("Hello, world!")
else
print("abcghjmquvxyzABCDEFGIJKLMNOPQRSTUVWXYZ_+*-&|")
end
```
Problem: The second `print` command will not run. Also, removing characters in quote in second `print` command will not change output.
```
x="Hello, world!";
print(x)
```
Problem: removal of newline will not change result or cause error (in Julia, semicolon is only necessary if multiple commands are on the same line, otherwise just suppresses return value).
```
print("Hellos\b, world!")
```
Problem: `s` character does not affect result, as it gets erased by `\b`. This is acceptable if done through code (`"Hello",char(100),"\b, world!"`), but cannot be done via string literals or character literals.
**Convenient score-calculator** - <http://jsfiddle.net/4t7qG/2/> - thanks to Doorknob
[Answer]
# Perl - 96
(Pretty good, given the theoretical max 97 score)
```
s{}[Hel0o, w3$=d!];y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(
6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)+print
```
(Note that second line starts with an actual `\t` tab character)
The code is 98 characters long and contains every ascii char exactly once, plus an extra `-`.
98 - 2 = 96
There are no *string* literals here, but removal of **any** single character breaks the program.
### Deobfuscation
There are 3 statements in this program (well, actually 2 but I abused `+` as some kind of statement separator)
1. `s{}[Hel0o, w3$=d!]`
This is a very stretched case of the sed operator. It is more commonly written as `s/a/b/`, or `s:a:b:`, but perl allows much more fantasy here: `s(a)(b)` `s(a)^b^` `s(a)[b]`, and even `s qaqbq`.
It replaces an empty string (inside `{}`) with `Hel0o w360d!` (inside `[]`) (`$=` interpolates to `60` by default). Because of the lack of an `~=` operator, it operates on `$_`.
2. `y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)`
This is also a very stretched case, but of a `tr` operator, which is also called `y` (`y< >( )`).
Let's look at the replacement table:
`" # %&'*.124578:?@BCDEFGIJKLMNOQ /-9`
`\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cA k-u`
I have moved some characters around so that existing string is not broken. The only actually working part here is `/-9` -> `k-u`. It replaces `0` with `l`, `3` with `o`, and `6` with `r`.
Again because of lack of the `~=` operator, it operates on `$_`
So now we have the complete phrase in the `$_` variable.
3. `print`
Lack of arguments makes it print just the `$_` variable.
[Answer]
**This answer was created before adding of the rule about string literals and does not participate in the contest.**
```
#include <iostream>
int main(){std::cout<<56+" !$%^&*?12347890-_QWERTYUIOPASDFGJKLZXVBNM,.qypfghjk:zvbHel\x6Co, world!";}
```
It's completely legit. :P
If you remove any character from that string, it will print `ello, world!`.
[Answer]
# CJam, 94
```
{'H"EJO, WoRLD!"el96A+c/~_-3=0$@}"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"254b87%*
```
[Try it online!](http://cjam.aditsu.net/ "CJam interpreter") Note that there should be a tabulator right before the linefeed. SE doesn't like tabulators, so you'll have to insert it manually.
* 100 characters long
* repeated alnum: -0 ()
* repeated punctuation: -6 (""")
* repeated other: -0 ()
* repeated whitespace: -0 ()
Total score: 94
I've used the following code to check that none of the characters inside the string can be removed:
```
"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"
:A,,{_A\<A@)>+254b87%}%`
```
It prints an array showing the number of times *Hello, world!* would get printed if the character corresponding to the index were removed.
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), 97 points!
```
"v!dlrow ,h
B[CDEFGIJkLMNOPH
$<QRSTUV@|5cg1fe':-%\64*ab+7_/89}{0 j2
WXYZK`.=#>]
s()impq n 3~
Atuxz&;y^ ?
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X6lMMSWnKL9cQSeDyyna2cXVzd3TK9vH188/wINLxSYwKDgkNMyhxjQ53TAtVd1KVzXGzEQrMUnbPF7fwrK22kBBIcuIKzwiMso7Qc9W2S6Wq1hDMzO3oJAzT8G4jsuxpLSiSs26Mk7B/v9/AA "Befunge-98 (FBBI) – Try It Online")
The tab is between the `q` and the `n`.
Uses a similar trick to the previous Befunge answer to pad the lines with the leftover characters, but avoids using duplicate characters in the executing section. Removing any of the non-executing characters results in the executing parts being out of place, usually ending up in infinite loops or printing the wrong output.
### How It Works
Really, the only executing part looks like:
```
"v!dlrow ,h
k H
$< @|5cg1fe':-%\64*ab+7
>]
^ ?
```
First it uses a wrapping string literal to add `, world!` to the stack. This avoids two `"`s.
```
$< @|5cg1fe':-%\64*ab+7
```
This adds `Hello` to the stack using a variety of methods to avoid duplicate characters. `$` pops the excess space caused by the wrapping string literal.
`7+` adds 7 to the `h` from the end of the string literal to create the `o`
.
`ba*46\%:` calculates 111, the ascii value of `l` and duplicates it.
`'e` adds e to the stack.
`f1g` gets the character at 1,15 which is the `H`
It then reuses the `,` in the string to print out the whole `Hello, world!`. The rest is just direction changes to navigate to the ending `@`.
[Answer]
# Ruby, ~~28~~ 41
Just to start off the answers with a solution in the spirit of the question:
```
print"He#{?l*2}o, "+'world!'if[$`&(9<=>6)^7|~8-5/3.1%0x4]
```
Scoring (I think I got this right):
* 57 characters long
* repeated alnum: -12 (`orli`)
* repeated punctuation: -4 (`"'`)
* repeated other: -0
* repeated whitespace: -0
[Answer]
# PHP, 1 (yes, one point!)
Using magic characters to generate a checksum, which in binary form matches "Hell", "o, w", "orld", and "! ".
Usually I like to find loopholes, but this time I decided to play by the spirit and intent of the contest. Every character and its position is essential to the output. The only places you can substitute are variable names which are not literal values, the whitespace between `php` and `foreach` which `PHP` treats as equivalent, and use of `'` vs `"` which `PHP` treats as similar.
```
<?php foreach(array('_MC:`~+V4@SbHR/l[J','dN#UB`5!Rv^NG@D}','9gm6L&-kuD','8OM97g.q]XQ0')as$j)print(hash("crc32",$j,1))?>
```
FYI, these are some other magic strings and hashes of interest:
```
E.D}S: Hell
9UDIRQ: Hell
N\7&*`%: orld
UWX[E^O: orld
mAHzDEb: !
uLJ7Ck&: Hell
B+bG5mYJ: Hell
:OvMzuOR: !
TgYR9g!6k: o, w
NkFN`!8mI: o, w
N#VA\j~}J[: Hell
vEl*]@0XQ5: o, w
9gm6L&-kuD: orld
*}{Xg@HN`\: !
Pj@Y44uA6YJ: Hell
|7OX0VF8gv}: !
DLRJAjgMj}\: !
!0bT*D}O4Lw: orld
YGN97^v7ZY`: Hell
++~bL/kP:|]W: o, w
8OM97g.q]XQ0: !
l^m-DqZ^g[&+: !
Ewu]Rv~*DHQ7: Hell
JIqjgF|S!\`8l: Hell
b4l!MEG7vTu6/: Hell
+B:zEq*J\k-Cm: !
_}E7wZD76^`Y9AU: orld
q:Nq-~+_S7~N9Hz: !
```
[Answer]
# Ruby, 78
More rules abuse, I feel like, not sure exactly what the patch'd be. Takes a long string and checks the sum of the result, so any deletion or change will cause the program to fail. Could probably be optimized a little to remove duplication of some letters and get whitespace in there.
```
puts('Hello, world!')if%["\#$&*+-/:;<>?@ABCDEFGIJKLMNOPQRSTUVWXYZ^_`abcghjknqvxyz{|}~123].sum==4980
```
[Answer]
# PHP, 2257
Loophole: the backslash was omitted from the specifications and the score calculator!
This code counts the number of occurrences of backslashes in each string and prints an ASCII equivalent. Replacing any backslash with another character, or deleting a backslash, either causes a parse error or changes the result.
A neat feature about backslashes and `PHP` is that they need to be escaped, so that doubles the score automatically! You can re-double, triple, etc., the score by multiplying the number of backslashes, but didn't want to be greedy, and I think it might exceed the limits of what you can enter.
```
<?php foreach(array('\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\')as$x)print(chr(substr_count($x,"\\")))?>
```
[Answer]
# Befunge - 87
```
"dlrow ,olleH"bk, v
!#$%&'()*+-./0123456789:; <=>?ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`acfghijmnpqstuvxyz{|}~@
```
The first line is worth four points due to all the repetition, but there are no duplicated characters on the second line. The only string literal in this code is `dlrow ,olleH`, which gets reversed and printed as output. Removing any one character will disconnect the `v` at the end of the first line from the `@` at the end of the second, causing the program to never terminate. If the `v` itself is removed, then the code will go in to an infinite loop printing the correct output.
[Answer]
# [Aceto](https://github.com/aceto/aceto), 3
Finally managed to get a positive score!
```
"Hello, "-J' sJ"world!"∑-JUJpn
```
[Try it online!](https://tio.run/##S0xOLcn//1/JIzUnJ19HQUnXS12h2EupPL8oJ0VR6VHHRF2vUK@CvP//AQ "Aceto – Try It Online")
[Answer]
# [Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), -138 (and yes that's negative 138)
While this may not exactly be the best score I've ever gotten in PPCG, I doubt it can get any higher than this in *Acc*!!
```
108
Write 72
Write 101
Count i while i-2 {
Write _
}
Write _+3
Write 44
Write 32
Write 119
Write 111
Write 114
Write _
Write 100
Write 33
```
[Try it online!](https://tio.run/##S0xOTkr6/9/QwIIrvCizJFXB3AjKMDQw5HLOL80rUchUKM/IzElVyNQ1Uqjm4oRIx3PVQhXGaxtDWSYmUIYx3BBDSzjLEM6CKYuHW2UA02j8/z8A "Acc!! – Try It Online")
[Answer]
# Pascal, 17
One of the few occasions on this site a verbose case-insensitive language is “useful”.
This is a `program` adhering to ISO standard 7185 “Pascal”:
```
PROGrAM{}Z(oUTput);BEgIN
WRiTe('Hello, world!':1*82-75+6)EnD.
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.